diff --git a/client/dist/cm.min.js b/client/dist/cm.min.js index 6d142df..a892f46 100644 --- a/client/dist/cm.min.js +++ b/client/dist/cm.min.js @@ -1,13212 +1 @@ -/** - Pack CodeMirror and its dependencies into a single file -*/ - -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// This is CodeMirror (https://codemirror.net), a code editor -// implemented in JavaScript on top of the browser's DOM. -// -// You can find some technical background for some of the code below -// at http://marijnhaverbeke.nl/blog/#cm-internals . - -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.CodeMirror = factory()); -}(this, (function () { 'use strict'; - - // Kludges for bugs and behavior differences that can't be feature - // detected are enabled based on userAgent etc sniffing. - var userAgent = navigator.userAgent; - var platform = navigator.platform; - - var gecko = /gecko\/\d/i.test(userAgent); - var ie_upto10 = /MSIE \d/.test(userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent); - var edge = /Edge\/(\d+)/.exec(userAgent); - var ie = ie_upto10 || ie_11up || edge; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]); - var webkit = !edge && /WebKit\//.test(userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent); - var chrome = !edge && /Chrome\//.test(userAgent); - var presto = /Opera\//.test(userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent); - var phantom = /PhantomJS/.test(userAgent); - - var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent); - var android = /Android/.test(userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent); - var mac = ios || /Mac/.test(platform); - var chromeOS = /\bCrOS\b/.test(userAgent); - var windows = /win/i.test(platform); - - var presto_version = presto && userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) { presto_version = Number(presto_version[1]); } - if (presto_version && presto_version >= 15) { presto = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || (ie && ie_version >= 9); - - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } - - var rmClass = function(node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - { e.removeChild(e.firstChild); } - return e - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e) - } - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) { e.className = className; } - if (style) { e.style.cssText = style; } - if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } - else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } - return e - } - // wrapper for elt, which removes the elt from the accessibility tree - function eltP(tag, content, className, style) { - var e = elt(tag, content, className, style); - e.setAttribute("role", "presentation"); - return e - } - - var range; - if (document.createRange) { range = function(node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r - }; } - else { range = function(node, start, end) { - var r = document.body.createTextRange(); - try { r.moveToElementText(node.parentNode); } - catch(e) { return r } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r - }; } - - function contains(parent, child) { - if (child.nodeType == 3) // Android browser always returns false when child is a textnode - { child = child.parentNode; } - if (parent.contains) - { return parent.contains(child) } - do { - if (child.nodeType == 11) { child = child.host; } - if (child == parent) { return true } - } while (child = child.parentNode) - } - - function activeElt() { - // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. - // IE < 10 will throw when accessed while the page is loading or in an iframe. - // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. - var activeElement; - try { - activeElement = document.activeElement; - } catch(e) { - activeElement = document.body || null; - } - while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) - { activeElement = activeElement.shadowRoot.activeElement; } - return activeElement - } - - function addClass(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } - } - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) - { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } - return b - } - - var selectInput = function(node) { node.select(); }; - if (ios) // Mobile Safari apparently has a bug where select() is broken. - { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } - else if (ie) // Suppress mysterious IE10 errors - { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args)} - } - - function copyObj(obj, target, overwrite) { - if (!target) { target = {}; } - for (var prop in obj) - { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) - { target[prop] = obj[prop]; } } - return target - } - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - function countColumn(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) { end = string.length; } - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) - { return n + (end - i) } - n += nextTab - i; - n += tabSize - (n % tabSize); - i = nextTab + 1; - } - } - - var Delayed = function() { - this.id = null; - this.f = null; - this.time = 0; - this.handler = bind(this.onTimeout, this); - }; - Delayed.prototype.onTimeout = function (self) { - self.id = 0; - if (self.time <= +new Date) { - self.f(); - } else { - setTimeout(self.handler, self.time - +new Date); - } - }; - Delayed.prototype.set = function (ms, f) { - this.f = f; - var time = +new Date + ms; - if (!this.id || time < this.time) { - clearTimeout(this.id); - this.id = setTimeout(this.handler, ms); - this.time = time; - } - }; - - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - { if (array[i] == elt) { return i } } - return -1 - } - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = {toString: function(){return "CodeMirror.Pass"}}; - - // Reused option objects for setSelection & friends - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) { nextTab = string.length; } - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) - { return pos + Math.min(skipped, goal - col) } - col += nextTab - pos; - col += tabSize - (col % tabSize); - pos = nextTab + 1; - if (col >= goal) { return pos } - } - } - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - { spaceStrs.push(lst(spaceStrs) + " "); } - return spaceStrs[n] - } - - function lst(arr) { return arr[arr.length-1] } - - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } - return out - } - - function insertSorted(array, value, score) { - var pos = 0, priority = score(value); - while (pos < array.length && score(array[pos]) <= priority) { pos++; } - array.splice(pos, 0, value); - } - - function nothing() {} - - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) { copyObj(props, inst); } - return inst - } - - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - function isWordCharBasic(ch) { - return /\w/.test(ch) || ch > "\x80" && - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) - } - function isWordChar(ch, helper) { - if (!helper) { return isWordCharBasic(ch) } - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } - return helper.test(ch) - } - - function isEmpty(obj) { - for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } - return true - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/fonts/browsers also treat other configurations - // of code points as a group. - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } - - // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. - function skipExtendingChars(str, pos, dir) { - while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } - return pos - } - - // Returns the value from the range [`from`; `to`] that satisfies - // `pred` and is closest to `from`. Assumes that at least `to` - // satisfies `pred`. Supports `from` being greater than `to`. - function findFirst(pred, from, to) { - // At any point we are certain `to` satisfies `pred`, don't know - // whether `from` does. - var dir = from > to ? -1 : 1; - for (;;) { - if (from == to) { return from } - var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); - if (mid == from) { return pred(mid) ? from : to } - if (pred(mid)) { to = mid; } - else { from = mid + dir; } - } - } - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) { return f(from, to, "ltr", 0) } - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); - found = true; - } - } - if (!found) { f(from, to, "ltr"); } - } - - var bidiOther = null; - function getBidiPartAt(order, ch, sticky) { - var found; - bidiOther = null; - for (var i = 0; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < ch && cur.to > ch) { return i } - if (cur.to == ch) { - if (cur.from != cur.to && sticky == "before") { found = i; } - else { bidiOther = i; } - } - if (cur.from == ch) { - if (cur.from != cur.to && sticky != "before") { found = i; } - else { bidiOther = i; } - } - } - return found != null ? found : bidiOther - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6f9 - var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; - function charType(code) { - if (code <= 0xf7) { return lowTypes.charAt(code) } - else if (0x590 <= code && code <= 0x5f4) { return "R" } - else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } - else if (0x6ee <= code && code <= 0x8ac) { return "r" } - else if (0x2000 <= code && code <= 0x200b) { return "w" } - else if (code == 0x200c) { return "b" } - else { return "L" } - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - return function(str, direction) { - var outerType = direction == "ltr" ? "L" : "R"; - - if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } - var len = str.length, types = []; - for (var i = 0; i < len; ++i) - { types.push(charType(str.charCodeAt(i))); } - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { - var type = types[i$1]; - if (type == "m") { types[i$1] = prev; } - else { prev = type; } - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { - var type$1 = types[i$2]; - if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } - else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { - var type$2 = types[i$3]; - if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } - else if (type$2 == "," && prev$1 == types[i$3+1] && - (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } - prev$1 = type$2; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i$4 = 0; i$4 < len; ++i$4) { - var type$3 = types[i$4]; - if (type$3 == ",") { types[i$4] = "N"; } - else if (type$3 == "%") { - var end = (void 0); - for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; - for (var j = i$4; j < end; ++j) { types[j] = replace; } - i$4 = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { - var type$4 = types[i$5]; - if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } - else if (isStrong.test(type$4)) { cur$1 = type$4; } - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i$6 = 0; i$6 < len; ++i$6) { - if (isNeutral.test(types[i$6])) { - var end$1 = (void 0); - for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} - var before = (i$6 ? types[i$6-1] : outerType) == "L"; - var after = (end$1 < len ? types[end$1] : outerType) == "L"; - var replace$1 = before == after ? (before ? "L" : "R") : outerType; - for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } - i$6 = end$1 - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i$7 = 0; i$7 < len;) { - if (countsAsLeft.test(types[i$7])) { - var start = i$7; - for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} - order.push(new BidiSpan(0, start, i$7)); - } else { - var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0; - for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} - for (var j$2 = pos; j$2 < i$7;) { - if (countsAsNum.test(types[j$2])) { - if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; } - var nstart = j$2; - for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} - order.splice(at, 0, new BidiSpan(2, nstart, j$2)); - at += isRTL; - pos = j$2; - } else { ++j$2; } - } - if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } - } - } - if (direction == "ltr") { - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - } - - return direction == "rtl" ? order.reverse() : order - } - })(); - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line, direction) { - var order = line.order; - if (order == null) { order = line.order = bidiOrdering(line.text, direction); } - return order - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var noHandlers = []; - - var on = function(emitter, type, f) { - if (emitter.addEventListener) { - emitter.addEventListener(type, f, false); - } else if (emitter.attachEvent) { - emitter.attachEvent("on" + type, f); - } else { - var map$$1 = emitter._handlers || (emitter._handlers = {}); - map$$1[type] = (map$$1[type] || noHandlers).concat(f); - } - }; - - function getHandlers(emitter, type) { - return emitter._handlers && emitter._handlers[type] || noHandlers - } - - function off(emitter, type, f) { - if (emitter.removeEventListener) { - emitter.removeEventListener(type, f, false); - } else if (emitter.detachEvent) { - emitter.detachEvent("on" + type, f); - } else { - var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; - if (arr) { - var index = indexOf(arr, f); - if (index > -1) - { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } - } - } - } - - function signal(emitter, type /*, values...*/) { - var handlers = getHandlers(emitter, type); - if (!handlers.length) { return } - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") - { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore - } - - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) { return } - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) - { set.push(arr[i]); } } - } - - function hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0 - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - function e_preventDefault(e) { - if (e.preventDefault) { e.preventDefault(); } - else { e.returnValue = false; } - } - function e_stopPropagation(e) { - if (e.stopPropagation) { e.stopPropagation(); } - else { e.cancelBubble = true; } - } - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false - } - function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} - - function e_target(e) {return e.target || e.srcElement} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) { b = 1; } - else if (e.button & 2) { b = 3; } - else if (e.button & 4) { b = 2; } - } - if (mac && e.ctrlKey && b == 1) { b = 3; } - return b - } - - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie && ie_version < 9) { return false } - var div = elt('div'); - return "draggable" in div || "dragDrop" in div - }(); - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } - } - var node = zwspSupported ? elt("span", "\u200b") : - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) { return badBidiRects } - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - var r1 = range(txt, 1, 2).getBoundingClientRect(); - removeChildren(measure); - if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) - return badBidiRects = (r1.right - r0.right < 3) - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) { nl = string.length; } - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result - } : function (string) { return string.split(/\r\n?|\n/); }; - - var hasSelection = window.getSelection ? function (te) { - try { return te.selectionStart != te.selectionEnd } - catch(e) { return false } - } : function (te) { - var range$$1; - try {range$$1 = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range$$1 || range$$1.parentElement() != te) { return false } - return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 - }; - - var hasCopyEvent = (function () { - var e = elt("div"); - if ("oncopy" in e) { return true } - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function" - })(); - - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) { return badZoomedRects } - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 - } - - // Known modes, by name and by MIME - var modes = {}, mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - function defineMode(name, mode) { - if (arguments.length > 2) - { mode.dependencies = Array.prototype.slice.call(arguments, 2); } - modes[name] = mode; - } - - function defineMIME(mime, spec) { - mimeModes[mime] = spec; - } - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - function resolveMode(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") { found = {name: found}; } - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return resolveMode("application/xml") - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { - return resolveMode("application/json") - } - if (typeof spec == "string") { return {name: spec} } - else { return spec || {name: "null"} } - } - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - function getMode(options, spec) { - spec = resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) { return getMode(options, "text/plain") } - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) { continue } - if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) { modeObj.helperType = spec.helperType; } - if (spec.modeProps) { for (var prop$1 in spec.modeProps) - { modeObj[prop$1] = spec.modeProps[prop$1]; } } - - return modeObj - } - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = {}; - function extendMode(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - } - - function copyState(mode, state) { - if (state === true) { return state } - if (mode.copyState) { return mode.copyState(state) } - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) { val = val.concat([]); } - nstate[n] = val; - } - return nstate - } - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - function innerMode(mode, state) { - var info; - while (mode.innerMode) { - info = mode.innerMode(state); - if (!info || info.mode == mode) { break } - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state} - } - - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true - } - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = function(string, tabSize, lineOracle) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - this.lineOracle = lineOracle; - }; - - StringStream.prototype.eol = function () {return this.pos >= this.string.length}; - StringStream.prototype.sol = function () {return this.pos == this.lineStart}; - StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; - StringStream.prototype.next = function () { - if (this.pos < this.string.length) - { return this.string.charAt(this.pos++) } - }; - StringStream.prototype.eat = function (match) { - var ch = this.string.charAt(this.pos); - var ok; - if (typeof match == "string") { ok = ch == match; } - else { ok = ch && (match.test ? match.test(ch) : match(ch)); } - if (ok) {++this.pos; return ch} - }; - StringStream.prototype.eatWhile = function (match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start - }; - StringStream.prototype.eatSpace = function () { - var this$1 = this; - - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } - return this.pos > start - }; - StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; - StringStream.prototype.skipTo = function (ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true} - }; - StringStream.prototype.backUp = function (n) {this.pos -= n;}; - StringStream.prototype.column = function () { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) - }; - StringStream.prototype.indentation = function () { - return countColumn(this.string, null, this.tabSize) - - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) - }; - StringStream.prototype.match = function (pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) { this.pos += pattern.length; } - return true - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) { return null } - if (match && consume !== false) { this.pos += match[0].length; } - return match - } - }; - StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; - StringStream.prototype.hideFirstChars = function (n, inner) { - this.lineStart += n; - try { return inner() } - finally { this.lineStart -= n; } - }; - StringStream.prototype.lookAhead = function (n) { - var oracle = this.lineOracle; - return oracle && oracle.lookAhead(n) - }; - StringStream.prototype.baseToken = function () { - var oracle = this.lineOracle; - return oracle && oracle.baseToken(this.pos) - }; - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } - var chunk = doc; - while (!chunk.lines) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break } - n -= sz; - } - } - return chunk.lines[n] - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function (line) { - var text = line.text; - if (n == end.line) { text = text.slice(0, end.ch); } - if (n == start.line) { text = text.slice(start.ch); } - out.push(text); - ++n; - }); - return out - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value - return out - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) { return null } - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) { break } - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { - var child = chunk.children[i$1], ch = child.height; - if (h < ch) { chunk = child; continue outer } - h -= ch; - n += child.chunkSize(); - } - return n - } while (!chunk.lines) - var i = 0; - for (; i < chunk.lines.length; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) { break } - h -= lh; - } - return n + i - } - - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)) - } - - // A Pos instance represents a position within the text. - function Pos(line, ch, sticky) { - if ( sticky === void 0 ) sticky = null; - - if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } - this.line = line; - this.ch = ch; - this.sticky = sticky; - } - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - function cmp(a, b) { return a.line - b.line || a.ch - b.ch } - - function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } - - function copyPos(x) {return Pos(x.line, x.ch)} - function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } - function minPos(a, b) { return cmp(a, b) < 0 ? a : b } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} - function clipPos(doc, pos) { - if (pos.line < doc.first) { return Pos(doc.first, 0) } - var last = doc.first + doc.size - 1; - if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } - return clipToLen(pos, getLine(doc, pos.line).text.length) - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } - else if (ch < 0) { return Pos(pos.line, 0) } - else { return pos } - } - function clipPosArray(doc, array) { - var out = []; - for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } - return out - } - - var SavedContext = function(state, lookAhead) { - this.state = state; - this.lookAhead = lookAhead; - }; - - var Context = function(doc, state, line, lookAhead) { - this.state = state; - this.doc = doc; - this.line = line; - this.maxLookAhead = lookAhead || 0; - this.baseTokens = null; - this.baseTokenPos = 1; - }; - - Context.prototype.lookAhead = function (n) { - var line = this.doc.getLine(this.line + n); - if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } - return line - }; - - Context.prototype.baseToken = function (n) { - var this$1 = this; - - if (!this.baseTokens) { return null } - while (this.baseTokens[this.baseTokenPos] <= n) - { this$1.baseTokenPos += 2; } - var type = this.baseTokens[this.baseTokenPos + 1]; - return {type: type && type.replace(/( |^)overlay .*/, ""), - size: this.baseTokens[this.baseTokenPos] - n} - }; - - Context.prototype.nextLine = function () { - this.line++; - if (this.maxLookAhead > 0) { this.maxLookAhead--; } - }; - - Context.fromSaved = function (doc, saved, line) { - if (saved instanceof SavedContext) - { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } - else - { return new Context(doc, copyState(doc.mode, saved), line) } - }; - - Context.prototype.save = function (copy) { - var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; - return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state - }; - - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, context, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, - lineClasses, forceToEnd); - var state = context.state; - - // Run overlays, adjust style array. - var loop = function ( o ) { - context.baseTokens = st; - var overlay = cm.state.overlays[o], i = 1, at = 0; - context.state = true; - runMode(cm, line.text, overlay.mode, context, function (end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - { st.splice(i, 1, end, st[i+1], i_end); } - i += 2; - at = Math.min(end, i_end); - } - if (!style) { return } - if (overlay.opaque) { - st.splice(start, i - start, end, "overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = (cur ? cur + " " : "") + "overlay " + style; - } - } - }, lineClasses); - context.state = state; - context.baseTokens = null; - context.baseTokenPos = 1; - }; - - for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); - - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} - } - - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var context = getContextBefore(cm, lineNo(line)); - var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); - var result = highlightLine(cm, line, context); - if (resetState) { context.state = resetState; } - line.stateAfter = context.save(!resetState); - line.styles = result.styles; - if (result.classes) { line.styleClasses = result.classes; } - else if (line.styleClasses) { line.styleClasses = null; } - if (updateFrontier === cm.doc.highlightFrontier) - { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } - } - return line.styles - } - - function getContextBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) { return new Context(doc, true, n) } - var start = findStartLine(cm, n, precise); - var saved = start > doc.first && getLine(doc, start - 1).stateAfter; - var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); - - doc.iter(start, n, function (line) { - processLine(cm, line.text, context); - var pos = context.line; - line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; - context.nextLine(); - }); - if (precise) { doc.modeFrontier = context.line; } - return context - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, context, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize, context); - stream.start = stream.pos = startAt || 0; - if (text == "") { callBlankLine(mode, context.state); } - while (!stream.eol()) { - readToken(mode, stream, context.state); - stream.start = stream.pos; - } - } - - function callBlankLine(mode, state) { - if (mode.blankLine) { return mode.blankLine(state) } - if (!mode.innerMode) { return } - var inner = innerMode(mode, state); - if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } - } - - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) { inner[0] = innerMode(mode, state).mode; } - var style = mode.token(stream, state); - if (stream.pos > stream.start) { return style } - } - throw new Error("Mode " + mode.name + " failed to advance stream.") - } - - var Token = function(stream, type, state) { - this.start = stream.start; this.end = stream.pos; - this.string = stream.current(); - this.type = type || null; - this.state = state; - }; - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - var doc = cm.doc, mode = doc.mode, style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; - if (asArray) { tokens = []; } - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, context.state); - if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } - } - return asArray ? tokens : new Token(stream, style, context.state) - } - - function extractLineClasses(type, output) { - if (type) { for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) { break } - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop] == null) - { output[prop] = lineClass[2]; } - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) - { output[prop] += " " + lineClass[2]; } - } } - return type - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize, context), style; - var inner = cm.options.addModeClass && [null]; - if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) { processLine(cm, text, context, stream.pos); } - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) { style = "m-" + (style ? mName + " " + style : mName); } - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 5000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 - // characters, and returns inaccurate measurements in nodes - // starting around 5000 chars. - var pos = Math.min(stream.pos, curStart + 5000); - f(pos, curStyle); - curStart = pos; - } - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) { return doc.first } - var line = getLine(doc, search - 1), after = line.stateAfter; - if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) - { return search } - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline - } - - function retreatFrontier(doc, n) { - doc.modeFrontier = Math.min(doc.modeFrontier, n); - if (doc.highlightFrontier < n - 10) { return } - var start = doc.first; - for (var line = n - 1; line > start; line--) { - var saved = getLine(doc, line).stateAfter; - // change is on 3 - // state on line 1 looked ahead 2 -- so saw 3 - // test 1 + 2 < 3 should cover this - if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { - start = line + 1; - break - } - } - doc.highlightFrontier = Math.min(doc.highlightFrontier, start); - } - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - function seeReadOnlySpans() { - sawReadOnlySpans = true; - } - - function seeCollapsedSpans() { - sawCollapsedSpans = true; - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) { for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) { return span } - } } - } - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - var r; - for (var i = 0; i < spans.length; ++i) - { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } - return r - } - // Add a span to a line. - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - var nw; - if (old) { for (var i = 0; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) - ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } } - return nw - } - function markedSpansAfter(old, endCh, isInsert) { - var nw; - if (old) { for (var i = 0; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) - ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, - span.to == null ? null : span.to - endCh)); - } - } } - return nw - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) { return null } - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) { return null } - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) { span.to = startCh; } - else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i$1 = 0; i$1 < last.length; ++i$1) { - var span$1 = last[i$1]; - if (span$1.to != null) { span$1.to += offset; } - if (span$1.from == null) { - var found$1 = getMarkedSpanFor(first, span$1.marker); - if (!found$1) { - span$1.from = offset; - if (sameLine) { (first || (first = [])).push(span$1); } - } - } else { - span$1.from += offset; - if (sameLine) { (first || (first = [])).push(span$1); } - } - } - } - // Make sure we didn't create any zero-length spans - if (first) { first = clearEmptySpans(first); } - if (last && last != first) { last = clearEmptySpans(last); } - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - { for (var i$2 = 0; i$2 < first.length; ++i$2) - { if (first[i$2].to == null) - { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } - for (var i$3 = 0; i$3 < gap; ++i$3) - { newMarkers.push(gapMarkers); } - newMarkers.push(last); - } - return newMarkers - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) - { spans.splice(i--, 1); } - } - if (!spans.length) { return null } - return spans - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function (line) { - if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - { (markers || (markers = [])).push(mark); } - } } - }); - if (!markers) { return null } - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) - { newParts.push({from: p.from, to: m.from}); } - if (dto > 0 || !mk.inclusiveRight && !dto) - { newParts.push({from: m.to, to: p.to}); } - parts.splice.apply(parts, newParts); - j += newParts.length - 3; - } - } - return parts - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) { return } - for (var i = 0; i < spans.length; ++i) - { spans[i].marker.detachLine(line); } - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) { return } - for (var i = 0; i < spans.length; ++i) - { spans[i].marker.attachLine(line); } - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) { return lenDiff } - var aPos = a.find(), bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) { return -fromCmp } - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) { return toCmp } - return b.id - a.id - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) - { found = sp.marker; } - } } - return found - } - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } - - function collapsedSpanAround(line, ch) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) { for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } - } } - return found - } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { - var line = getLine(doc, lineNo$$1); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) { continue } - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || - fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) - { return true } - } } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - { line = merged.find(-1, true).line; } - return line - } - - function visualLineEnd(line) { - var merged; - while (merged = collapsedSpanAtEnd(line)) - { line = merged.find(1, true).line; } - return line - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line - ;(lines || (lines = [])).push(line); - } - return lines - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), vis = visualLine(line); - if (line == vis) { return lineN } - return lineNo(vis) - } - - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) { return lineN } - var line = getLine(doc, lineN), merged; - if (!lineIsHidden(doc, line)) { return lineN } - while (merged = collapsedSpanAtEnd(line)) - { line = merged.find(1, true).line; } - return lineNo(line) + 1 - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) { continue } - if (sp.from == null) { return true } - if (sp.marker.widgetNode) { continue } - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - { return true } - } } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) - } - if (span.marker.inclusiveRight && span.to == line.text.length) - { return true } - for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && - (sp.to == null || sp.to != span.from) && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) { return true } - } - } - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) { break } - else { h += line.height; } - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i$1 = 0; i$1 < p.children.length; ++i$1) { - var cur = p.children[i$1]; - if (cur == chunk) { break } - else { h += cur.height; } - } - } - return h - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) { return 0 } - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found$1 = merged.find(0, true); - len -= cur.text.length - found$1.from.ch; - cur = found$1.to.line; - len += cur.text.length - found$1.to.ch; - } - return len - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function (line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - - Line.prototype.lineNo = function () { return lineNo(this) }; - eventMixin(Line); - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) { line.stateAfter = null; } - if (line.styles) { line.styles = null; } - if (line.order != null) { line.order = null; } - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) { updateLineHeight(line, estHeight); } - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) { return null } - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || - (cache[style] = style.replace(/\S+/g, "cm-$&")) - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, - col: 0, pos: 0, cm: cm, - trailingSpace: false, - splitSpaces: cm.getOption("lineWrapping")}; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) - { builder.addToken = buildTokenBadBidi(builder.addToken, order); } - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) - { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } - if (line.styleClasses.textClass) - { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) - { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) - ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit) { - var last = builder.content.lastChild; - if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) - { builder.content.className = "cm-tab-wrap-hack"; } - } - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } - - return builder - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { - if (!text) { return } - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; - var special = builder.cm.state.specialChars, mustWrap = false; - var content; - if (!special.test(text)) { - builder.col += text.length; - content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) { mustWrap = true; } - builder.pos += text.length; - } else { - content = document.createDocumentFragment(); - var pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } - else { content.appendChild(txt); } - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) { break } - pos += skipped + 1; - var txt$1 = (void 0); - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt$1.setAttribute("role", "presentation"); - txt$1.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else if (m[0] == "\r" || m[0] == "\n") { - txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); - txt$1.setAttribute("cm-text", m[0]); - builder.col += 1; - } else { - txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); - txt$1.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } - else { content.appendChild(txt$1); } - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt$1); - builder.pos++; - } - } - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; - if (style || startStyle || endStyle || mustWrap || css) { - var fullStyle = style || ""; - if (startStyle) { fullStyle += startStyle; } - if (endStyle) { fullStyle += endStyle; } - var token = elt("span", [content], fullStyle, css); - if (attributes) { - for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") - { token.setAttribute(attr, attributes[attr]); } } - } - return builder.content.appendChild(token) - } - builder.content.appendChild(content); - } - - // Change some spaces to NBSP to prevent the browser from collapsing - // trailing spaces at the end of a line when rendering text (issue #1362). - function splitSpaces(text, trailingBefore) { - if (text.length > 1 && !/ /.test(text)) { return text } - var spaceBefore = trailingBefore, result = ""; - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) - { ch = "\u00a0"; } - result += ch; - spaceBefore = ch == " "; - } - return result - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function (builder, text, style, startStyle, endStyle, css, attributes) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - var part = (void 0); - for (var i = 0; i < order.length; i++) { - part = order[i]; - if (part.to > start && part.from <= start) { break } - } - if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } - inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - } - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) - { widget = builder.content.appendChild(document.createElement("span")); } - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - builder.trailingSpace = false; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i$1 = 1; i$1 < styles.length; i$1+=2) - { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } - return - } - - var len = allText.length, pos = 0, i = 1, text = "", style, css; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = css = ""; - attributes = null; - collapsed = null; nextChange = Infinity; - var foundBookmarks = [], endStyles = (void 0); - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) { spanStyle += " " + m.className; } - if (m.css) { css = (css ? css + ";" : "") + m.css; } - if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } - if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } - // support for the old title property - // https://github.com/codemirror/CodeMirror/pull/5673 - if (m.title) { (attributes || (attributes = {})).title = m.title; } - if (m.attributes) { - for (var attr in m.attributes) - { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } - } - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) - { collapsed = sp; } - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) - { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } - - if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) - { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) { return } - if (collapsed.to == pos) { collapsed = false; } - } - } - if (pos >= len) { break } - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); - } - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder.cm.options); - } - } - } - - - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array - } - - var operationGroup = null; - - function pushOperation(op) { - if (operationGroup) { - operationGroup.ops.push(op); - } else { - op.ownsGroup = operationGroup = { - ops: [op], - delayedCallbacks: [] - }; - } - } - - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - var callbacks = group.delayedCallbacks, i = 0; - do { - for (; i < callbacks.length; i++) - { callbacks[i].call(null); } - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) - { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) - { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } - } - } while (i < callbacks.length) - } - - function finishOperation(op, endCb) { - var group = op.ownsGroup; - if (!group) { return } - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - endCb(group); - } - } - - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = getHandlers(emitter, type); - if (!arr.length) { return } - var args = Array.prototype.slice.call(arguments, 2), list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - var loop = function ( i ) { - list.push(function () { return arr[i].apply(null, args); }); - }; - - for (var i = 0; i < arr.length; ++i) - loop( i ); - } - - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) { delayed[i](); } - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") { updateLineText(cm, lineView); } - else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } - else if (type == "class") { updateLineClasses(cm, lineView); } - else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) - { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } - } - return lineView.node - } - - function updateLineBackground(cm, lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) { cls += " CodeMirror-linebackground"; } - if (lineView.background) { - if (cls) { lineView.background.className = cls; } - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - cm.display.input.setUneditable(lineView.background); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built - } - return buildLineContent(cm, lineView) - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) { lineView.node = built.pre; } - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(cm, lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - - function updateLineClasses(cm, lineView) { - updateLineBackground(cm, lineView); - if (lineView.line.wrapClass) - { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } - else if (lineView.node != lineView.text) - { lineView.node.className = ""; } - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - if (lineView.gutterBackground) { - lineView.node.removeChild(lineView.gutterBackground); - lineView.gutterBackground = null; - } - if (lineView.line.gutterClass) { - var wrap = ensureLineWrapped(lineView); - lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, - ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); - cm.display.input.setUneditable(lineView.gutterBackground); - wrap.insertBefore(lineView.gutterBackground, lineView.text); - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap$1 = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); - cm.display.input.setUneditable(gutterWrap); - wrap$1.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) - { gutterWrap.className += " " + lineView.line.gutterClass; } - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) - { lineView.lineNumber = gutterWrap.appendChild( - elt("div", lineNumberFor(cm.options, lineN), - "CodeMirror-linenumber CodeMirror-gutter-elt", - ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } - if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { - var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; - if (found) - { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", - ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } - } } - } - } - - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) { lineView.alignable = null; } - var isWidget = classTest("CodeMirror-linewidget"); - for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { - next = node.nextSibling; - if (isWidget.test(node.className)) { lineView.node.removeChild(node); } - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) { lineView.bgClass = built.bgClass; } - if (built.textClass) { lineView.textClass = built.textClass; } - - updateLineClasses(cm, lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node - } - - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) - { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } - } - - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) { return } - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); - if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) - { wrap.insertBefore(node, lineView.gutter || lineView.text); } - else - { wrap.appendChild(node); } - signalLater(widget, "redraw"); - } - } - - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } - } - } - - function widgetHeight(widget) { - if (widget.height != null) { return widget.height } - var cm = widget.doc.cm; - if (!cm) { return 0 } - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) - { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } - if (widget.noHScroll) - { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.parentNode.offsetHeight - } - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || - (n.parentNode == display.sizer && n != display.mover)) - { return true } - } - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} - function paddingH(display) { - if (display.cachedPaddingH) { return display.cachedPaddingH } - var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; - if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } - return data - } - - function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) - { heights.push((cur.bottom + next.top) / 2 - rect.top); } - } - } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) - { return {map: lineView.measure.map, cache: lineView.measure.cache} } - for (var i = 0; i < lineView.rest.length; i++) - { if (lineView.rest[i] == line) - { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } - for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) - { if (lineNo(lineView.rest[i$1]) > lineN) - { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) - { return cm.display.view[findViewIndex(cm, lineN)] } - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) - { return ext } - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) { - view = null; - } else if (view && view.changes) { - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - cm.curOp.forceUpdate = true; - } - if (!view) - { view = updateExternalMeasurement(cm, line); } - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false - } - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) { ch = -1; } - var key = ch + (bias || ""), found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) - { prepared.rect = prepared.view.text.getBoundingClientRect(); } - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) { prepared.cache[key] = found; } - } - return {left: found.left, right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom} - } - - var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; - - function nodeAndOffsetInLineMap(map$$1, ch, bias) { - var node, start, end, collapse, mStart, mEnd; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map$$1.length; i += 3) { - mStart = map$$1[i]; - mEnd = map$$1[i + 1]; - if (ch < mStart) { - start = 0; end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) { collapse = "right"; } - } - if (start != null) { - node = map$$1[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) - { collapse = bias; } - if (bias == "left" && start == 0) - { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { - node = map$$1[(i -= 3) + 2]; - collapse = "left"; - } } - if (bias == "right" && start == mEnd - mStart) - { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { - node = map$$1[(i += 3) + 2]; - collapse = "right"; - } } - break - } - } - return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} - } - - function getUsefulRect(rects, bias) { - var rect = nullRect; - if (bias == "left") { for (var i = 0; i < rects.length; i++) { - if ((rect = rects[i]).left != rect.right) { break } - } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { - if ((rect = rects[i$1]).left != rect.right) { break } - } } - return rect - } - - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, start = place.start, end = place.end, collapse = place.collapse; - - var rect; - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. - for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) - { rect = node.parentNode.getBoundingClientRect(); } - else - { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } - if (rect.left || rect.right || start == 0) { break } - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } - } else { // If it is a widget, simply get the box for the whole widget. - if (start > 0) { collapse = bias = "right"; } - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) - { rect = rects[bias == "right" ? rects.length - 1 : 0]; } - else - { rect = node.getBoundingClientRect(); } - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) - { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } - else - { rect = nullRect; } - } - - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - var i = 0; - for (; i < heights.length - 1; i++) - { if (mid < heights[i]) { break } } - var top = i ? heights[i - 1] : 0, bot = heights[i]; - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, bottom: bot}; - if (!rect.left && !rect.right) { result.bogus = true; } - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } - - return result - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) - { return rect } - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return {left: rect.left * scaleX, right: rect.right * scaleX, - top: rect.top * scaleY, bottom: rect.bottom * scaleY} - } - - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) - { lineView.measure.caches[i] = {}; } } - } - } - - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i = 0; i < cm.display.view.length; i++) - { clearLineMeasurementCacheFor(cm.display.view[i]); } - } - - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } - cm.display.lineNumChars = null; - } - - function pageScrollX() { - // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 - // which causes page_Offset and bounding client rects to use - // different reference viewports and invalidate our calculations. - if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } - return window.pageXOffset || (document.documentElement || document.body).scrollLeft - } - function pageScrollY() { - if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } - return window.pageYOffset || (document.documentElement || document.body).scrollTop - } - - function widgetTopHeight(lineObj) { - var height = 0; - if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) - { height += widgetHeight(lineObj.widgets[i]); } } } - return height - } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"./null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { - if (!includeWidgets) { - var height = widgetTopHeight(lineObj); - rect.top += height; rect.bottom += height; - } - if (context == "line") { return rect } - if (!context) { context = "local"; } - var yOff = heightAtLine(lineObj); - if (context == "local") { yOff += paddingTop(cm.display); } - else { yOff -= cm.display.viewOffset; } - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"./null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") { return coords } - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` - // and after `char - 1` in writing order of `char - 1` - // A cursor Pos(line, char, "after") is on the same visual line as `char` - // and before `char` in writing order of `char` - // Examples (upper-case letters are RTL, lower-case are LTR): - // Pos(0, 1, ...) - // before after - // ab a|b a|b - // aB a|B aB| - // Ab |Ab A|b - // AB B|A B|A - // Every position after the last character on a line is considered to stick - // to the last character on the line. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) { m.left = m.right; } else { m.right = m.left; } - return intoCoordSystem(cm, lineObj, m, context) - } - var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; - if (ch >= lineObj.text.length) { - ch = lineObj.text.length; - sticky = "before"; - } else if (ch <= 0) { - ch = 0; - sticky = "after"; - } - if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } - - function getBidi(ch, partPos, invert) { - var part = order[partPos], right = part.level == 1; - return get(invert ? ch - 1 : ch, right != invert) - } - var partPos = getBidiPartAt(order, ch, sticky); - var other = bidiOther; - var val = getBidi(ch, partPos, sticky == "before"); - if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } - return val - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0; - pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return {left: left, right: left, top: top, bottom: top + lineObj.height} - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, sticky, outside, xRel) { - var pos = Pos(line, ch, sticky); - pos.xRel = xRel; - if (outside) { pos.outside = outside; } - return pos - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineN > last) - { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } - if (x < 0) { x = 0; } - - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); - if (!collapsed) { return found } - var rangeEnd = collapsed.find(1); - if (rangeEnd.line == lineN) { return rangeEnd } - lineObj = getLine(doc, lineN = rangeEnd.line); - } - } - - function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { - y -= widgetTopHeight(lineObj); - var end = lineObj.text.length; - var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); - end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); - return {begin: begin, end: end} - } - - function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { - if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } - var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; - return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) - } - - // Returns true if the given side of a box is after the given - // coordinates, in top-to-bottom, left-to-right order. - function boxIsAfter(box, x, y, left) { - return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x - } - - function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { - // Move y into line-local coordinate space - y -= heightAtLine(lineObj); - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - // When directly calling `measureCharPrepared`, we have to adjust - // for the widgets at this line. - var widgetHeight$$1 = widgetTopHeight(lineObj); - var begin = 0, end = lineObj.text.length, ltr = true; - - var order = getOrder(lineObj, cm.doc.direction); - // If the line isn't plain left-to-right text, first figure out - // which bidi section the coordinates fall into. - if (order) { - var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) - (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y); - ltr = part.level != 1; - // The awkward -1 offsets are needed because findFirst (called - // on these below) will treat its first bound as inclusive, - // second as exclusive, but we want to actually address the - // characters in the part's range - begin = ltr ? part.from : part.to - 1; - end = ltr ? part.to : part.from - 1; - } - - // A binary search to find the first character whose bounding box - // starts after the coordinates. If we run across any whose box wrap - // the coordinates, store that. - var chAround = null, boxAround = null; - var ch = findFirst(function (ch) { - var box = measureCharPrepared(cm, preparedMeasure, ch); - box.top += widgetHeight$$1; box.bottom += widgetHeight$$1; - if (!boxIsAfter(box, x, y, false)) { return false } - if (box.top <= y && box.left <= x) { - chAround = ch; - boxAround = box; - } - return true - }, begin, end); - - var baseX, sticky, outside = false; - // If a box around the coordinates was found, use that - if (boxAround) { - // Distinguish coordinates nearer to the left or right side of the box - var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; - ch = chAround + (atStart ? 0 : 1); - sticky = atStart ? "after" : "before"; - baseX = atLeft ? boxAround.left : boxAround.right; - } else { - // (Adjust for extended bound, if necessary.) - if (!ltr && (ch == end || ch == begin)) { ch++; } - // To determine which side to associate with, get the box to the - // left of the character and compare it's vertical position to the - // coordinates - sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : - (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ? - "after" : "before"; - // Now get accurate coordinates for this place, in order to get a - // base X position - var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure); - baseX = coords.left; - outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; - } - - ch = skipExtendingChars(lineObj.text, ch, 1); - return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX) - } - - function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) { - // Bidi parts are sorted left-to-right, and in a non-line-wrapping - // situation, we can take this ordering to correspond to the visual - // ordering. This finds the first part whose end is after the given - // coordinates. - var index = findFirst(function (i) { - var part = order[i], ltr = part.level != 1; - return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"), - "line", lineObj, preparedMeasure), x, y, true) - }, 0, order.length - 1); - var part = order[index]; - // If this isn't the first part, the part's start is also after - // the coordinates, and the coordinates aren't on the same line as - // that start, move one part back. - if (index > 0) { - var ltr = part.level != 1; - var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"), - "line", lineObj, preparedMeasure); - if (boxIsAfter(start, x, y, true) && start.top > y) - { part = order[index - 1]; } - } - return part - } - - function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { - // In a wrapped line, rtl text on wrapping boundaries can do things - // that don't correspond to the ordering in our `order` array at - // all, so a binary search doesn't work, and we want to return a - // part that only spans one line so that the binary search in - // coordsCharInner is safe. As such, we first find the extent of the - // wrapped line, and then do a flat search in which we discard any - // spans that aren't on the line. - var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); - var begin = ref.begin; - var end = ref.end; - if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } - var part = null, closestDist = null; - for (var i = 0; i < order.length; i++) { - var p = order[i]; - if (p.from >= end || p.to <= begin) { continue } - var ltr = p.level != 1; - var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; - // Weigh against spans ending before this, so that they are only - // picked if nothing ends after - var dist = endX < x ? x - endX + 1e9 : endX - x; - if (!part || closestDist > dist) { - part = p; - closestDist = dist; - } - } - if (!part) { part = order[order.length - 1]; } - // Clip the part to the wrapped line. - if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } - if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } - return part - } - - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) { return display.cachedTextHeight } - if (measureText == null) { - measureText = elt("pre", null, "CodeMirror-line-like"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) { display.cachedTextHeight = height; } - removeChildren(display.measure); - return height || 1 - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) { return display.cachedCharWidth } - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor], "CodeMirror-line-like"); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; - if (width > 2) { display.cachedCharWidth = width; } - return width || 10 - } - - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - var id = cm.display.gutterSpecs[i].className; - left[id] = n.offsetLeft + n.clientLeft + gutterLeft; - width[id] = n.clientWidth; - } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth} - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function (line) { - if (lineIsHidden(cm.doc, line)) { return 0 } - - var widgetsHeight = 0; - if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } - } } - - if (wrapping) - { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } - else - { return widgetsHeight + th } - } - } - - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function (line) { - var estHeight = est(line); - if (estHeight != line.height) { updateLineHeight(line, estHeight); } - }); - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } - - var x, y, space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX - space.left; y = e.clientY - space.top; } - catch (e) { return null } - var coords = coordsChar(cm, x, y), line; - if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) { return null } - n -= cm.display.viewFrom; - if (n < 0) { return null } - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) { return i } - } - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) { from = cm.doc.first; } - if (to == null) { to = cm.doc.first + cm.doc.size; } - if (!lendiff) { lendiff = 0; } - - var display = cm.display; - if (lendiff && to < display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers > from)) - { display.updateLineNumbers = from; } - - cm.curOp.viewChanged = true; - - if (from >= display.viewTo) { // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) - { resetView(cm); } - } else if (to <= display.viewFrom) { // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { // Bottom overlap - var cut$1 = viewCuttingPoint(cm, from, from, -1); - if (cut$1) { - display.view = display.view.slice(0, cut$1.index); - display.viewTo = cut$1.lineN; - } else { - resetView(cm); - } - } else { // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index) - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) - .concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - { ext.lineN += lendiff; } - else if (from < ext.lineN + ext.size) - { display.externalMeasured = null; } - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) - { display.externalMeasured = null; } - - if (line < display.viewFrom || line >= display.viewTo) { return } - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) { return } - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) { arr.push(type); } - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), diff, view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) - { return {index: index, lineN: newN} } - var n = cm.display.viewFrom; - for (var i = 0; i < index; i++) - { n += view[i].size; } - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) { return null } - diff = (n + view[index].size) - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) { return null } - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return {index: index, lineN: newN} - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) - { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } - else if (display.viewFrom < from) - { display.view = display.view.slice(findViewIndex(cm, from)); } - display.viewFrom = from; - if (display.viewTo < to) - { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } - else if (display.viewTo > to) - { display.view = display.view.slice(0, findViewIndex(cm, to)); } - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } - } - return dirty - } - - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - - function prepareSelection(cm, primary) { - if ( primary === void 0 ) primary = true; - - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (!primary && i == doc.sel.primIndex) { continue } - var range$$1 = doc.sel.ranges[i]; - if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } - var collapsed = range$$1.empty(); - if (collapsed || cm.options.showCursorWhenSelecting) - { drawSelectionCursor(cm, range$$1.head, curFragment); } - if (!collapsed) - { drawSelectionRange(cm, range$$1, selFragment); } - } - return result - } - - // Draws a cursor for the given range - function drawSelectionCursor(cm, head, output) { - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); - - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } - } - - function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range$$1, output) { - var display = cm.display, doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - var docLTR = doc.direction == "ltr"; - - function add(left, top, width, bottom) { - if (top < 0) { top = 0; } - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); - } - - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias) - } - - function wrapX(pos, dir, side) { - var extent = wrappedLineExtentChar(cm, lineObj, null, pos); - var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); - return coords(ch, prop)[prop] - } - - var order = getOrder(lineObj, doc.direction); - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { - var ltr = dir == "ltr"; - var fromPos = coords(from, ltr ? "left" : "right"); - var toPos = coords(to - 1, ltr ? "right" : "left"); - - var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; - var first = i == 0, last = !order || i == order.length - 1; - if (toPos.top - fromPos.top <= 3) { // Single line - var openLeft = (docLTR ? openStart : openEnd) && first; - var openRight = (docLTR ? openEnd : openStart) && last; - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; - add(left, fromPos.top, right - left, fromPos.bottom); - } else { // Multiple lines - var topLeft, topRight, botLeft, botRight; - if (ltr) { - topLeft = docLTR && openStart && first ? leftSide : fromPos.left; - topRight = docLTR ? rightSide : wrapX(from, dir, "before"); - botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); - botRight = docLTR && openEnd && last ? rightSide : toPos.right; - } else { - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); - topRight = !docLTR && openStart && first ? rightSide : fromPos.right; - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; - botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); - } - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); - if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); - } - - if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } - if (cmpCoords(toPos, start) < 0) { start = toPos; } - if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } - if (cmpCoords(toPos, end) < 0) { end = toPos; } - }); - return {start: start, end: end} - } - - var sFrom = range$$1.from(), sTo = range$$1.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) - { add(leftSide, leftEnd.bottom, null, rightStart.top); } - } - - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) { return } - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, - cm.options.cursorBlinkRate); } - else if (cm.options.cursorBlinkRate < 0) - { display.cursorDiv.style.visibility = "hidden"; } - } - - function ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } - } - - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function () { if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } }, 100); - } - - function onFocus(cm, e) { - if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } - - if (cm.options.readOnly == "nocursor") { return } - if (!cm.state.focused) { - signal(cm, "focus", cm, e); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm, e) { - if (cm.state.delayingBlurEvent) { return } - - if (cm.state.focused) { - signal(cm, "blur", cm, e); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], wrapping = cm.options.lineWrapping; - var height = (void 0), width = 0; - if (cur.hidden) { continue } - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - // Check that lines don't extend past the right of the current - // editor width - if (!wrapping && cur.text.firstChild) - { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } - } - var diff = cur.line.height - height; - if (diff > .005 || diff < -.005) { - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) - { updateWidgetHeight(cur.rest[j]); } } - } - if (width > cm.display.sizerWidth) { - var chWidth = Math.ceil(width / charWidth(cm.display)); - if (chWidth > cm.display.maxLineLength) { - cm.display.maxLineLength = chWidth; - cm.display.maxLine = cur.line; - cm.display.maxLineChanged = true; - } - } - } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { - var w = line.widgets[i], parent = w.node.parentNode; - if (parent) { w.height = parent.offsetHeight; } - } } - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return {from: from, to: Math.max(to, from + 1)} - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, rect) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } - - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; - if (rect.top + box.top < 0) { doScroll = true; } - else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) { margin = 0; } - var rect; - if (!cm.options.lineWrapping && pos == end) { - // Set pos and end to the cursor positions around the character pos sticks to - // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch - // If pos == Pos(_, 0, "before"), pos and end are unchanged - pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; - end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; - } - for (var limit = 0; limit < 5; limit++) { - var changed = false; - var coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - rect = {left: Math.min(coords.left, endCoords.left), - top: Math.min(coords.top, endCoords.top) - margin, - right: Math.max(coords.left, endCoords.left), - bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; - var scrollPos = calculateScrollPos(cm, rect); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } - } - if (!changed) { break } - } - return rect - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, rect) { - var scrollPos = calculateScrollPos(cm, rect); - if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } - if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, rect) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (rect.top < 0) { rect.top = 0; } - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), result = {}; - if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } - var docBottom = cm.doc.height + paddingVert(display); - var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; - if (rect.top < screentop) { - result.scrollTop = atTop ? 0 : rect.top; - } else if (rect.bottom > screentop + screen) { - var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); - if (newTop != screentop) { result.scrollTop = newTop; } - } - - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; - var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); - var tooWide = rect.right - rect.left > screenw; - if (tooWide) { rect.right = rect.left + screenw; } - if (rect.left < 10) - { result.scrollLeft = 0; } - else if (rect.left < screenleft) - { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } - else if (rect.right > screenw + screenleft - 3) - { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } - return result - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollTop(cm, top) { - if (top == null) { return } - resolveScrollToPos(cm); - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(); - cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; - } - - function scrollToCoords(cm, x, y) { - if (x != null || y != null) { resolveScrollToPos(cm); } - if (x != null) { cm.curOp.scrollLeft = x; } - if (y != null) { cm.curOp.scrollTop = y; } - } - - function scrollToRange(cm, range$$1) { - resolveScrollToPos(cm); - cm.curOp.scrollToPos = range$$1; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range$$1 = cm.curOp.scrollToPos; - if (range$$1) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); - scrollToCoordsRange(cm, from, to, range$$1.margin); - } - } - - function scrollToCoordsRange(cm, from, to, margin) { - var sPos = calculateScrollPos(cm, { - left: Math.min(from.left, to.left), - top: Math.min(from.top, to.top) - margin, - right: Math.max(from.right, to.right), - bottom: Math.max(from.bottom, to.bottom) + margin - }); - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); - } - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function updateScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) { return } - if (!gecko) { updateDisplaySimple(cm, {top: val}); } - setScrollTop(cm, val, true); - if (gecko) { updateDisplaySimple(cm); } - startWorker(cm, 100); - } - - function setScrollTop(cm, val, forceScroll) { - val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); - if (cm.display.scroller.scrollTop == val && !forceScroll) { return } - cm.doc.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } - } - - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller, forceScroll) { - val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); - if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } - cm.display.scrollbars.setScrollLeft(val); - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - } - } - - var NativeScrollbars = function(place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - vert.tabIndex = horiz.tabIndex = -1; - place(vert); place(horiz); - - on(vert, "scroll", function () { - if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } - }); - on(horiz, "scroll", function () { - if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } - }); - - this.checkedZeroWidth = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } - }; - - NativeScrollbars.prototype.update = function (measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = - Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) { this.zeroWidthHack(); } - this.checkedZeroWidth = true; - } - - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} - }; - - NativeScrollbars.prototype.setScrollLeft = function (pos) { - if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } - if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } - }; - - NativeScrollbars.prototype.setScrollTop = function (pos) { - if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } - if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } - }; - - NativeScrollbars.prototype.zeroWidthHack = function () { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.height = this.vert.style.width = w; - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; - this.disableHoriz = new Delayed; - this.disableVert = new Delayed; - }; - - NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { - bar.style.pointerEvents = "auto"; - function maybeDisable() { - // To find out whether the scrollbar is still visible, we - // check whether the element under the pixel in the bottom - // right corner of the scrollbar box is the scrollbar box - // itself (when the bar is still visible) or its filler child - // (when the bar is hidden). If it is still visible, we keep - // it enabled, if it's hidden, we disable pointer events. - var box = bar.getBoundingClientRect(); - var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) - : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); - if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } - else { delay.set(1000, maybeDisable); } - } - delay.set(1000, maybeDisable); - }; - - NativeScrollbars.prototype.clear = function () { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - }; - - var NullScrollbars = function () {}; - - NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; - NullScrollbars.prototype.setScrollLeft = function () {}; - NullScrollbars.prototype.setScrollTop = function () {}; - NullScrollbars.prototype.clear = function () {}; - - function updateScrollbars(cm, measure) { - if (!measure) { measure = measureForScrollbars(cm); } - var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) - { updateHeightsInViewport(cm); } - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; - - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else { d.scrollbarFiller.style.display = ""; } - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else { d.gutterFiller.style.display = ""; } - } - - var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } - } - - cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function () { - if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } - }); - node.setAttribute("cm-not-content", "true"); - }, function (pos, axis) { - if (axis == "horizontal") { setScrollLeft(cm, pos); } - else { updateScrollTop(cm, pos); } - }, cm); - if (cm.display.scrollbars.addClass) - { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } - } - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, // Used to detect need to update scrollbar - forceUpdate: false, // Used to force a redraw - updateInput: 0, // Whether to reset the input textarea - typing: false, // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, // Accumulated changes, for firing change events - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already - selectionChanged: false, // Whether the selection needs to be redrawn - updateMaxLine: false, // Set when the widest line needs to be determined anew - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, // Used to scroll to a specific position - focus: false, - id: ++nextOpId // Unique ID - }; - pushOperation(cm.curOp); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp; - if (op) { finishOperation(op, function (group) { - for (var i = 0; i < group.ops.length; i++) - { group.ops[i].cm.curOp = null; } - endOperations(group); - }); } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) // Read DOM - { endOperation_R1(ops[i]); } - for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) - { endOperation_W1(ops[i$1]); } - for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM - { endOperation_R2(ops[i$2]); } - for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) - { endOperation_W2(ops[i$3]); } - for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM - { endOperation_finish(ops[i$4]); } - } - - function endOperation_R1(op) { - var cm = op.cm, display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) { findMaxLine(cm); } - - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || - op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || - op.scrollToPos.to.line >= display.viewTo) || - display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && - new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); - } - - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } - - function endOperation_R2(op) { - var cm = op.cm, display = cm.display; - if (op.updatedDisplay) { updateHeightsInViewport(cm); } - - op.barMeasure = measureForScrollbars(cm); - - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = - Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - - if (op.updatedDisplay || op.selectionChanged) - { op.preparedSelection = display.input.prepareSelection(); } - } - - function endOperation_W2(op) { - var cm = op.cm; - - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) - { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } - cm.display.maxLineChanged = false; - } - - var takeFocus = op.focus && op.focus == activeElt(); - if (op.preparedSelection) - { cm.display.input.showSelection(op.preparedSelection, takeFocus); } - if (op.updatedDisplay || op.startHeight != cm.doc.height) - { updateScrollbars(cm, op.barMeasure); } - if (op.updatedDisplay) - { setDocumentHeight(cm, op.barMeasure); } - - if (op.selectionChanged) { restartBlink(cm); } - - if (cm.state.focused && op.updateInput) - { cm.display.input.reset(op.typing); } - if (takeFocus) { ensureFocus(op.cm); } - } - - function endOperation_finish(op) { - var cm = op.cm, display = cm.display, doc = cm.doc; - - if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) - { display.wheelStartX = display.wheelStartY = null; } - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } - - if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - maybeScrollWindow(cm, rect); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) { for (var i = 0; i < hidden.length; ++i) - { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } - if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) - { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } - - if (display.wrapper.offsetHeight) - { doc.scrollTop = cm.display.scroller.scrollTop; } - - // Fire change events, and delayed event handlers - if (op.changeObjs) - { signal(cm, "changes", cm, op.changeObjs); } - if (op.update) - { op.update.finish(); } - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) { return f() } - startOperation(cm); - try { return f() } - finally { endOperation(cm); } - } - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm, f) { - return function() { - if (cm.curOp) { return f.apply(cm, arguments) } - startOperation(cm); - try { return f.apply(cm, arguments) } - finally { endOperation(cm); } - } - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - function methodOp(f) { - return function() { - if (this.curOp) { return f.apply(this, arguments) } - startOperation(this); - try { return f.apply(this, arguments) } - finally { endOperation(this); } - } - } - function docMethodOp(f) { - return function() { - var cm = this.cm; - if (!cm || cm.curOp) { return f.apply(this, arguments) } - startOperation(cm); - try { return f.apply(this, arguments) } - finally { endOperation(cm); } - } - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.highlightFrontier < cm.display.viewTo) - { cm.state.highlight.set(time, bind(highlightWorker, cm)); } - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.highlightFrontier >= cm.display.viewTo) { return } - var end = +new Date + cm.options.workTime; - var context = getContextBefore(cm, doc.highlightFrontier); - var changedLines = []; - - doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { - if (context.line >= cm.display.viewFrom) { // Visible - var oldStyles = line.styles; - var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; - var highlighted = highlightLine(cm, line, context, true); - if (resetState) { context.state = resetState; } - line.styles = highlighted.styles; - var oldCls = line.styleClasses, newCls = highlighted.classes; - if (newCls) { line.styleClasses = newCls; } - else if (oldCls) { line.styleClasses = null; } - var ischange = !oldStyles || oldStyles.length != line.styles.length || - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } - if (ischange) { changedLines.push(context.line); } - line.stateAfter = context.save(); - context.nextLine(); - } else { - if (line.text.length <= cm.options.maxHighlightLength) - { processLine(cm, line.text, context); } - line.stateAfter = context.line % 5 == 0 ? context.save() : null; - context.nextLine(); - } - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true - } - }); - doc.highlightFrontier = context.line; - doc.modeFrontier = Math.max(doc.modeFrontier, context.line); - if (changedLines.length) { runInOp(cm, function () { - for (var i = 0; i < changedLines.length; i++) - { regLineChange(cm, changedLines[i], "text"); } - }); } - } - - // DISPLAY DRAWING - - var DisplayUpdate = function(cm, viewport, force) { - var display = cm.display; - - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - }; - - DisplayUpdate.prototype.signal = function (emitter, type) { - if (hasHandler(emitter, type)) - { this.events.push(arguments); } - }; - DisplayUpdate.prototype.finish = function () { - var this$1 = this; - - for (var i = 0; i < this.events.length; i++) - { signal.apply(null, this$1.events[i]); } - }; - - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - - function selectionSnapshot(cm) { - if (cm.hasFocus()) { return null } - var active = activeElt(); - if (!active || !contains(cm.display.lineDiv, active)) { return null } - var result = {activeElt: active}; - if (window.getSelection) { - var sel = window.getSelection(); - if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { - result.anchorNode = sel.anchorNode; - result.anchorOffset = sel.anchorOffset; - result.focusNode = sel.focusNode; - result.focusOffset = sel.focusOffset; - } - } - return result - } - - function restoreSelection(snapshot) { - if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } - snapshot.activeElt.focus(); - if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { - var sel = window.getSelection(), range$$1 = document.createRange(); - range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); - range$$1.collapse(false); - sel.removeAllRanges(); - sel.addRange(range$$1); - sel.extend(snapshot.focusNode, snapshot.focusOffset); - } - } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, doc = cm.doc; - - if (update.editorIsHidden) { - resetView(cm); - return false - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && - display.renderedView == display.view && countDirtyView(cm) == 0) - { return false } - - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); - } - - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } - if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); - } - - var different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - { return false } - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var selSnapshot = selectionSnapshot(cm); - if (toUpdate > 4) { display.lineDiv.style.display = "none"; } - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) { display.lineDiv.style.display = ""; } - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - restoreSelection(selSnapshot); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = display.sizer.style.minHeight = 0; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - - display.updateLineNumbers = null; - - return true - } - - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) - { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) - { break } - } else if (first) { - update.visible = visibleLines(cm.display, cm.doc, viewport); - } - if (!updateDisplayIfNeeded(cm, update)) { break } - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.force = false; - } - - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; - } - } - - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.finish(); - } - } - - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) - { node.style.display = "none"; } - else - { node.parentNode.removeChild(node); } - return next - } - - var view = display.view, lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { // Already drawn - while (cur != lineView.node) { cur = rm(cur); } - var updateNumber = lineNumbers && updateNumbersFrom != null && - updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) { cur = rm(cur); } - } - - function updateGutterSpace(display) { - var width = display.gutters.offsetWidth; - display.sizer.style.marginLeft = width + "px"; - } - - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - cm.display.heightForcer.style.top = measure.docHeight + "px"; - cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; - } - - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, left = comp + "px"; - for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { - if (cm.options.fixedGutter) { - if (view[i].gutter) - { view[i].gutter.style.left = left; } - if (view[i].gutterBackground) - { view[i].gutterBackground.style.left = left; } - } - var align = view[i].alignable; - if (align) { for (var j = 0; j < align.length; j++) - { align[j].style.left = left; } } - } } - if (cm.options.fixedGutter) - { display.gutters.style.left = (comp + gutterW) + "px"; } - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) { return false } - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm.display); - return true - } - return false - } - - function getGutters(gutters, lineNumbers) { - var result = [], sawLineNumbers = false; - for (var i = 0; i < gutters.length; i++) { - var name = gutters[i], style = null; - if (typeof name != "string") { style = name.style; name = name.className; } - if (name == "CodeMirror-linenumbers") { - if (!lineNumbers) { continue } - else { sawLineNumbers = true; } - } - result.push({className: name, style: style}); - } - if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } - return result - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function renderGutters(display) { - var gutters = display.gutters, specs = display.gutterSpecs; - removeChildren(gutters); - display.lineGutter = null; - for (var i = 0; i < specs.length; ++i) { - var ref = specs[i]; - var className = ref.className; - var style = ref.style; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); - if (style) { gElt.style.cssText = style; } - if (className == "CodeMirror-linenumbers") { - display.lineGutter = gElt; - gElt.style.width = (display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = specs.length ? "" : "none"; - updateGutterSpace(display); - } - - function updateGutters(cm) { - renderGutters(cm.display); - regChange(cm); - alignHorizontally(cm); - } - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input, options) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = eltP("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], - null, "position: relative; outline: none"); - var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [lines], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } - - if (place) { - if (place.appendChild) { place.appendChild(d.wrapper); } - else { place(d.wrapper); } - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); - renderGutters(d); - - input.init(d); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) { wheelPixelsPerUnit = -.53; } - else if (gecko) { wheelPixelsPerUnit = 15; } - else if (chrome) { wheelPixelsPerUnit = -.7; } - else if (safari) { wheelPixelsPerUnit = -1/3; } - - function wheelEventDelta(e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } - else if (dy == null) { dy = e.wheelDelta; } - return {x: dx, y: dy} - } - function wheelEventPixels(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta - } - - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - var canScrollX = scroll.scrollWidth > scroll.clientWidth; - var canScrollY = scroll.scrollHeight > scroll.clientHeight; - if (!(dx && canScrollX || dy && canScrollY)) { return } - - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { - for (var i = 0; i < view.length; i++) { - if (view[i].node == cur) { - cm.display.currentWheelTarget = cur; - break outer - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { - if (dy && canScrollY) - { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } - setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); - // Only prevent default scrolling if vertical scrolling is - // actually possible. Otherwise, it causes vertical scroll - // jitter on OSX trackpads when deltaX is small and deltaY - // is large (issue #3579) - if (!dy || (dy && canScrollY)) - { e_preventDefault(e); } - display.wheelStartX = null; // Abort measurement, if in progress - return - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) { top = Math.max(0, top + pixels - 50); } - else { bot = Math.min(cm.doc.height, bot + pixels + 50); } - updateDisplaySimple(cm, {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function () { - if (display.wheelStartX == null) { return } - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) { return } - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; - } - } - } - - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - var Selection = function(ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - }; - - Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; - - Selection.prototype.equals = function (other) { - var this$1 = this; - - if (other == this) { return true } - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } - for (var i = 0; i < this.ranges.length; i++) { - var here = this$1.ranges[i], there = other.ranges[i]; - if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } - } - return true - }; - - Selection.prototype.deepCopy = function () { - var this$1 = this; - - var out = []; - for (var i = 0; i < this.ranges.length; i++) - { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } - return new Selection(out, this.primIndex) - }; - - Selection.prototype.somethingSelected = function () { - var this$1 = this; - - for (var i = 0; i < this.ranges.length; i++) - { if (!this$1.ranges[i].empty()) { return true } } - return false - }; - - Selection.prototype.contains = function (pos, end) { - var this$1 = this; - - if (!end) { end = pos; } - for (var i = 0; i < this.ranges.length; i++) { - var range = this$1.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) - { return i } - } - return -1 - }; - - var Range = function(anchor, head) { - this.anchor = anchor; this.head = head; - }; - - Range.prototype.from = function () { return minPos(this.anchor, this.head) }; - Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; - Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(cm, ranges, primIndex) { - var mayTouch = cm && cm.options.selectionsMayTouch; - var prim = ranges[primIndex]; - ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], prev = ranges[i - 1]; - var diff = cmp(prev.to(), cur.from()); - if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) { --primIndex; } - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex) - } - - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0) - } - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - function changeEnd(change) { - if (!change.text) { return change.to } - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) - } - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) { return pos } - if (cmp(pos, change.to) <= 0) { return changeEnd(change) } - - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } - return Pos(line, ch) - } - - function computeSelAfterChange(doc, change) { - var out = []; - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - out.push(new Range(adjustForChange(range.anchor, change), - adjustForChange(range.head, change))); - } - return normalizeSelection(doc.cm, out, doc.sel.primIndex) - } - - function offsetPos(pos, old, nw) { - if (pos.line == old.line) - { return Pos(nw.line, pos.ch - old.ch + nw.ch) } - else - { return Pos(nw.line + (pos.line - old.line), pos.ch) } - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex) - } - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - - function resetModeState(cm) { - cm.doc.iter(function (line) { - if (line.stateAfter) { line.stateAfter = null; } - if (line.styles) { line.styles = null; } - }); - cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) { regChange(cm); } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore) - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight$$1) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight$$1); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - var result = []; - for (var i = start; i < end; ++i) - { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } - return result - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) { doc.remove(from.line, nlines); } - if (added.length) { doc.insert(from.line, added); } - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added$1 = linesFor(1, text.length - 1); - added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added$1); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added$2 = linesFor(1, text.length - 1); - if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } - doc.insert(from.line + 1, added$2); - } - - signalLater(doc, "change", doc, change); - } - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) { continue } - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) { continue } - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) { throw new Error("This document is already in use.") } - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - setDirectionClass(cm); - if (!cm.options.lineWrapping) { findMaxLine(cm); } - cm.options.mode = doc.modeOption; - regChange(cm); - } - - function setDirectionClass(cm) { - (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); - } - - function directionChanged(cm) { - runInOp(cm, function () { - setDirectionClass(cm); - regChange(cm); - }); - } - - function History(startGen) { - // Arrays of change events and selections. Doing something adds an - // event to done and clears undo. Undoing moves events from done - // to undone, redoing moves them in the other direction. - this.done = []; this.undone = []; - this.undoDepth = Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = startGen || 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); - return histChange - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) { array.pop(); } - else { break } - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done) - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done) - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done) - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, or are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur; - var last; - - if ((hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || - change.origin.charAt(0) == "*")) && - (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) - { pushSelectionToHistory(doc.sel, hist.done); } - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation}; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) { hist.done.shift(); } - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - - if (!last) { signal(doc, "historyAdded"); } - } - - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || - ch == "+" && - prev.ranges.length == sel.ranges.length && - prev.somethingSelected() == sel.somethingSelected() && - new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || - (origin && hist.lastSelOrigin == origin && - (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) - { hist.done[hist.done.length - 1] = sel; } - else - { pushSelectionToHistory(sel, hist.done); } - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - { clearSelectionEvents(hist.undone); } - } - - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - { dest.push(sel); } - } - - // Used to store marked span information in the history. - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { - if (line.markedSpans) - { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) { return null } - var out; - for (var i = 0; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } - else if (out) { out.push(spans[i]); } - } - return !out ? spans : out.length ? out : null - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) { return null } - var nw = []; - for (var i = 0; i < change.text.length; ++i) - { nw.push(removeClearedSpans(found[i])); } - return nw - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) { return stretched } - if (!stretched) { return old } - - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - { if (oldCur[k].marker == span.marker) { continue spans } } - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - var copy = []; - for (var i = 0; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue - } - var changes = event.changes, newChanges = []; - copy.push({changes: newChanges}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m = (void 0); - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } } } - } - } - return copy - } - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(range, head, other, extend) { - if (extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != (cmp(other, anchor) < 0)) { - anchor = head; - head = other; - } else if (posBefore != (cmp(head, other) < 0)) { - head = other; - } - } - return new Range(anchor, head) - } else { - return new Range(other || head, head) - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options, extend) { - if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } - setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - var out = []; - var extend = doc.cm && (doc.cm.display.shift || doc.extend); - for (var i = 0; i < doc.sel.ranges.length; i++) - { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } - var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel, options) { - var obj = { - ranges: sel.ranges, - update: function(ranges) { - var this$1 = this; - - this.ranges = []; - for (var i = 0; i < ranges.length; i++) - { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), - clipPos(doc, ranges[i].head)); } - }, - origin: options && options.origin - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } - if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } - else { return sel } - } - - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); - } - } - - // Set a new selection. - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } - - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) - { sel = filterSelectionChange(doc, sel, options); } - - var bias = options && options.bias || - (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - - if (!(options && options.scroll === false) && doc.cm) - { ensureCursorVisible(doc.cm); } - } - - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) { return } - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = 1; - doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) { out = sel.ranges.slice(0, i); } - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel - } - - function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { - var line = getLine(doc, pos.line); - if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], m = sp.marker; - - // Determine if we should prevent the cursor being placed to the left/right of an atomic marker - // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it - // is with selectLeft/Right - var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; - var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; - - if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && - (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) { break } - else {--i; continue} - } - } - if (!m.atomic) { continue } - - if (oldPos) { - var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); - if (dir < 0 ? preventCursorRight : preventCursorLeft) - { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) - { return skipAtomicInner(doc, near, pos, dir, mayClear) } - } - - var far = m.find(dir < 0 ? -1 : 1); - if (dir < 0 ? preventCursorLeft : preventCursorRight) - { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null - } - } } - return pos - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, oldPos, bias, mayClear) { - var dir = bias || 1; - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || - (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || - skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || - (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); - if (!found) { - doc.cantEdit = true; - return Pos(doc.first, 0) - } - return found - } - - function movePos(doc, pos, dir, line) { - if (dir < 0 && pos.ch == 0) { - if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } - else { return null } - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { - if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } - else { return null } - } else { - return new Pos(pos.line, pos.ch + dir) - } - } - - function selectAll(cm) { - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); - } - - // UPDATING - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function () { return obj.canceled = true; } - }; - if (update) { obj.update = function (from, to, text, origin) { - if (from) { obj.from = clipPos(doc, from); } - if (to) { obj.to = clipPos(doc, to); } - if (text) { obj.text = text; } - if (origin !== undefined) { obj.origin = origin; } - }; } - signal(doc, "beforeChange", doc, obj); - if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } - - if (obj.canceled) { - if (doc.cm) { doc.cm.curOp.updateInput = 2; } - return null - } - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} - } - - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } - if (doc.cm.state.suppressEdits) { return } - } - - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) { return } - } - - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) - { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } - } else { - makeChangeInner(doc, change); - } - } - - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - - linkedDocs(doc, function (doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - var suppress = doc.cm && doc.cm.state.suppressEdits; - if (suppress && !allowSelectionOnly) { return } - - var hist = doc.history, event, selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - var i = 0; - for (; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) - { break } - } - if (i == source.length) { return } - hist.lastOrigin = hist.lastSelOrigin = null; - - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, {clearRedo: false}); - return - } - selAfter = event; - } else if (suppress) { - source.push(event); - return - } else { break } - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({changes: antiChanges, generation: hist.generation}); - hist.generation = event.generation || ++hist.maxGeneration; - - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - - var loop = function ( i ) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return {} - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function (doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - }; - - for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { - var returned = loop( i$1 ); - - if ( returned ) return returned.v; - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) { return } - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( - Pos(range.anchor.line + distance, range.anchor.ch), - Pos(range.head.line + distance, range.head.ch) - ); }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) - { regLineChange(doc.cm, l, "gutter"); } - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } - - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return - } - if (change.from.line > doc.lastLine()) { return } - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; - } - - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } - if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } - else { updateDoc(doc, change, spans); } - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - - if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) - { doc.cantEdit = false; } - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function (line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - { signalCursorActivity(cm); } - - updateDoc(doc, change, spans, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function (line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } - } - - retreatFrontier(doc, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) - { regChange(cm); } - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) - { regLineChange(cm, from.line, "text"); } - else - { regChange(cm, from.line, to.line + 1, lendiff); } - - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) { signalLater(cm, "change", cm, obj); } - if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } - } - cm.display.selForContextMenu = null; - } - - function replaceRange(doc, code, from, to, origin) { - var assign; - - if (!to) { to = from; } - if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } - if (typeof code == "string") { code = doc.splitLines(code); } - makeChange(doc, {from: from, to: to, text: code, origin: origin}); - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - if (sub.ranges) { - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue - } - for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { - var cur = sub.changes[j$1]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, line = handle; - if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } - else { no = lineNo(handle); } - if (no == null) { return null } - if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } - return line - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - var this$1 = this; - - this.lines = lines; - this.parent = null; - var height = 0; - for (var i = 0; i < lines.length; ++i) { - lines[i].parent = this$1; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length }, - - // Remove the n lines at offset 'at'. - removeInner: function(at, n) { - var this$1 = this; - - for (var i = at, e = at + n; i < e; ++i) { - var line = this$1.lines[i]; - this$1.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - - // Helper used to collapse a small branch into a single leaf. - collapse: function(lines) { - lines.push.apply(lines, this.lines); - }, - - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function(at, lines, height) { - var this$1 = this; - - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } - }, - - // Used to iterate over a part of the tree. - iterN: function(at, n, op) { - var this$1 = this; - - for (var e = at + n; at < e; ++at) - { if (op(this$1.lines[at])) { return true } } - } - }; - - function BranchChunk(children) { - var this$1 = this; - - this.children = children; - var size = 0, height = 0; - for (var i = 0; i < children.length; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this$1; - } - this.size = size; - this.height = height; - this.parent = null; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size }, - - removeInner: function(at, n) { - var this$1 = this; - - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this$1.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.removeInner(at, rm); - this$1.height -= oldHeight - child.height; - if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) { break } - at = 0; - } else { at -= sz; } - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - - collapse: function(lines) { - var this$1 = this; - - for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } - }, - - insertInner: function(at, lines, height) { - var this$1 = this; - - this.size += lines.length; - this.height += height; - for (var i = 0; i < this.children.length; ++i) { - var child = this$1.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. - // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. - var remaining = child.lines.length % 25 + 25; - for (var pos = remaining; pos < child.lines.length;) { - var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); - child.height -= leaf.height; - this$1.children.splice(++i, 0, leaf); - leaf.parent = this$1; - } - child.lines = child.lines.slice(0, remaining); - this$1.maybeSpill(); - } - break - } - at -= sz; - } - }, - - // When a node has grown, check whether it should be split. - maybeSpill: function() { - if (this.children.length <= 10) { return } - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10) - me.parent.maybeSpill(); - }, - - iterN: function(at, n, op) { - var this$1 = this; - - for (var i = 0; i < this.children.length; ++i) { - var child = this$1.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) { return true } - if ((n -= used) == 0) { break } - at = 0; - } else { at -= sz; } - } - } - }; - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = function(doc, node, options) { - var this$1 = this; - - if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) - { this$1[opt] = options[opt]; } } } - this.doc = doc; - this.node = node; - }; - - LineWidget.prototype.clear = function () { - var this$1 = this; - - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); - if (no == null || !ws) { return } - for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } - if (!ws.length) { line.widgets = null; } - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) { - runInOp(cm, function () { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - signalLater(cm, "lineWidgetCleared", cm, this, no); - } - }; - - LineWidget.prototype.changed = function () { - var this$1 = this; - - var oldH = this.height, cm = this.doc.cm, line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) { return } - if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } - if (cm) { - runInOp(cm, function () { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); - }); - } - }; - eventMixin(LineWidget); - - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - { addToScrollTop(cm, diff); } - } - - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } - changeLine(doc, handle, "widget", function (line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) { widgets.push(widget); } - else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) { addToScrollTop(cm, widget.height); } - cm.curOp.forceUpdate = true; - } - return true - }); - if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } - return widget - } - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - - var TextMarker = function(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - - // Clear the marker. - TextMarker.prototype.clear = function () { - var this$1 = this; - - if (this.explicitlyCleared) { return } - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) { startOperation(cm); } - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) { signalLater(this, "clear", found.from, found.to); } - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this$1.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this$1); - if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } - else if (cm) { - if (span.to != null) { max = lineNo(line); } - if (span.from != null) { min = lineNo(line); } - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) - { updateLineHeight(line, textHeight(cm.display)); } - } - if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { - var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } } - - if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) { reCheckSelection(cm.doc); } - } - if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } - if (withOp) { endOperation(cm); } - if (this.parent) { this.parent.clear(); } - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function (side, lineObj) { - var this$1 = this; - - if (side == null && this.type == "bookmark") { side = 1; } - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this$1.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this$1); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) { return from } - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) { return to } - } - } - return from && {from: from, to: to} - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function () { - var this$1 = this; - - var pos = this.find(-1, true), widget = this, cm = this.doc.cm; - if (!pos || !cm) { return } - runInOp(cm, function () { - var line = pos.line, lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) - { updateLineHeight(line, line.height + dHeight); } - } - signalLater(cm, "markerChanged", cm, this$1); - }); - }; - - TextMarker.prototype.attachLine = function (line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } - } - this.lines.push(line); - }; - - TextMarker.prototype.detachLine = function (line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp - ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - eventMixin(TextMarker); - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) { return markTextShared(doc, from, to, options, type) } - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } - - var marker = new TextMarker(doc, type), diff = cmp(from, to); - if (options) { copyObj(options, marker, false); } - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) - { return marker } - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } - if (options.insertLeft) { marker.widgetNode.insertLeft = true; } - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || - from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) - { throw new Error("Inserting collapsed marker partially overlapping an existing one") } - seeCollapsedSpans(); - } - - if (marker.addToHistory) - { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } - - var curLine = from.line, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function (line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) - { updateMaxLine = true; } - if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } - addMarkedSpan(line, new MarkedSpan(marker, - curLine == from.line ? from.ch : null, - curLine == to.line ? to.ch : null)); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { - if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } - }); } - - if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } - - if (marker.readOnly) { - seeReadOnlySpans(); - if (doc.history.done.length || doc.history.undone.length) - { doc.clearHistory(); } - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) { cm.curOp.updateMaxLine = true; } - if (marker.collapsed) - { regChange(cm, from.line, to.line + 1); } - else if (marker.className || marker.startStyle || marker.endStyle || marker.css || - marker.attributes || marker.title) - { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } - if (marker.atomic) { reCheckSelection(cm.doc); } - signalLater(cm, "markerAdded", cm, marker); - } - return marker - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = function(markers, primary) { - var this$1 = this; - - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) - { markers[i].parent = this$1; } - }; - - SharedTextMarker.prototype.clear = function () { - var this$1 = this; - - if (this.explicitlyCleared) { return } - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) - { this$1.markers[i].clear(); } - signalLater(this, "clear"); - }; - - SharedTextMarker.prototype.find = function (side, lineObj) { - return this.primary.find(side, lineObj) - }; - eventMixin(SharedTextMarker); - - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function (doc) { - if (widget) { options.widgetNode = widget.cloneNode(true); } - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) - { if (doc.linked[i].isParent) { return } } - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary) - } - - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) - } - - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], pos = marker.find(); - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - - function detachSharedMarkers(markers) { - var loop = function ( i ) { - var marker = markers[i], linked = [marker.primary.doc]; - linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - }; - - for (var i = 0; i < markers.length; i++) loop( i ); - } - - var nextDocId = 0; - var Doc = function(text, mode, firstLine, lineSep, direction) { - if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } - if (firstLine == null) { firstLine = 0; } - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.modeFrontier = this.highlightFrontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - this.lineSep = lineSep; - this.direction = (direction == "rtl") ? "rtl" : "ltr"; - this.extend = false; - - if (typeof text == "string") { text = this.splitLines(text); } - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function(from, to, op) { - if (op) { this.iterN(from - this.first, to - from, op); } - else { this.iterN(this.first, this.first + this.size, from); } - }, - - // Non-public interface for adding and removing lines. - insert: function(at, lines) { - var height = 0; - for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } - this.insertInner(at - this.first, lines, height); - }, - remove: function(at, n) { this.removeInner(at - this.first, n); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function(lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) { return lines } - return lines.join(lineSep || this.lineSeparator()) - }, - setValue: docMethodOp(function(code) { - var top = Pos(this.first, 0), last = this.first + this.size - 1; - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), - text: this.splitLines(code), origin: "setValue", full: true}, true); - if (this.cm) { scrollToCoords(this.cm, 0, 0); } - setSelection(this, simpleSelection(top), sel_dontScroll); - }), - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) { return lines } - return lines.join(lineSep || this.lineSeparator()) - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, - - getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, - getLineNumber: function(line) {return lineNo(line)}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") { line = getLine(this, line); } - return visualLine(line) - }, - - lineCount: function() {return this.size}, - firstLine: function() {return this.first}, - lastLine: function() {return this.first + this.size - 1}, - - clipPos: function(pos) {return clipPos(this, pos)}, - - getCursor: function(start) { - var range$$1 = this.sel.primary(), pos; - if (start == null || start == "head") { pos = range$$1.head; } - else if (start == "anchor") { pos = range$$1.anchor; } - else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } - else { pos = range$$1.from(); } - return pos - }, - listSelections: function() { return this.sel.ranges }, - somethingSelected: function() {return this.sel.somethingSelected()}, - - setCursor: docMethodOp(function(line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function(anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function(head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function(heads, options) { - extendSelections(this, clipPosArray(this, heads), options); - }), - extendSelectionsBy: docMethodOp(function(f, options) { - var heads = map(this.sel.ranges, f); - extendSelections(this, clipPosArray(this, heads), options); - }), - setSelections: docMethodOp(function(ranges, primary, options) { - var this$1 = this; - - if (!ranges.length) { return } - var out = []; - for (var i = 0; i < ranges.length; i++) - { out[i] = new Range(clipPos(this$1, ranges[i].anchor), - clipPos(this$1, ranges[i].head)); } - if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } - setSelection(this, normalizeSelection(this.cm, out, primary), options); - }), - addSelection: docMethodOp(function(anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); - }), - - getSelection: function(lineSep) { - var this$1 = this; - - var ranges = this.sel.ranges, lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) { return lines } - else { return lines.join(lineSep || this.lineSeparator()) } - }, - getSelections: function(lineSep) { - var this$1 = this; - - var parts = [], ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } - parts[i] = sel; - } - return parts - }, - replaceSelection: function(code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) - { dup[i] = code; } - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function(code, collapse, origin) { - var this$1 = this; - - var changes = [], sel = this.sel; - for (var i = 0; i < sel.ranges.length; i++) { - var range$$1 = sel.ranges[i]; - changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) - { makeChange(this$1, changes[i$1]); } - if (newSel) { setSelectionReplaceHistory(this, newSel); } - else if (this.cm) { ensureCursorVisible(this.cm); } - }), - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend}, - - historySize: function() { - var hist = this.history, done = 0, undone = 0; - for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } - for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } - return {undo: done, redo: undone} - }, - clearHistory: function() { - var this$1 = this; - - this.history = new History(this.history.maxGeneration); - linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true); - }, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function(forceSplit) { - if (forceSplit) - { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } - return this.history.generation - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration) - }, - - getHistory: function() { - return {done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone)} - }, - setHistory: function(histData) { - var hist = this.history = new History(this.history.maxGeneration); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - - setGutterMarker: docMethodOp(function(line, gutterID, value) { - return changeLine(this, line, "gutter", function (line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) { line.gutterMarkers = null; } - return true - }) - }), - - clearGutter: docMethodOp(function(gutterID) { - var this$1 = this; - - this.iter(function (line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - changeLine(this$1, line, "gutter", function () { - line.gutterMarkers[gutterID] = null; - if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } - return true - }); - } - }); - }), - - lineInfo: function(line) { - var n; - if (typeof line == "number") { - if (!isLine(this, line)) { return null } - n = line; - line = getLine(this, line); - if (!line) { return null } - } else { - n = lineNo(line); - if (n == null) { return null } - } - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, - widgets: line.widgets} - }, - - addLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) { line[prop] = cls; } - else if (classTest(cls).test(line[prop])) { return false } - else { line[prop] += " " + cls; } - return true - }) - }), - removeLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) { return false } - else if (cls == null) { line[prop] = null; } - else { - var found = cur.match(classTest(cls)); - if (!found) { return false } - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true - }) - }), - - addLineWidget: docMethodOp(function(handle, node, options) { - return addLineWidget(this, handle, node, options) - }), - removeLineWidget: function(widget) { widget.clear(); }, - - markText: function(from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") - }, - setBookmark: function(pos, options) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark") - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) { for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || span.to >= pos.ch)) - { markers.push(span.marker.parent || span.marker); } - } } - return markers - }, - findMarks: function(from, to, filter) { - from = clipPos(this, from); to = clipPos(this, to); - var found = [], lineNo$$1 = from.line; - this.iter(from.line, to.line + 1, function (line) { - var spans = line.markedSpans; - if (spans) { for (var i = 0; i < spans.length; i++) { - var span = spans[i]; - if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || - span.from == null && lineNo$$1 != from.line || - span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && - (!filter || filter(span.marker))) - { found.push(span.marker.parent || span.marker); } - } } - ++lineNo$$1; - }); - return found - }, - getAllMarks: function() { - var markers = []; - this.iter(function (line) { - var sps = line.markedSpans; - if (sps) { for (var i = 0; i < sps.length; ++i) - { if (sps[i].from != null) { markers.push(sps[i].marker); } } } - }); - return markers - }, - - posFromIndex: function(off) { - var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; - this.iter(function (line) { - var sz = line.text.length + sepSize; - if (sz > off) { ch = off; return true } - off -= sz; - ++lineNo$$1; - }); - return clipPos(this, Pos(lineNo$$1, ch)) - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) { return 0 } - var sepSize = this.lineSeparator().length; - this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value - index += line.text.length + sepSize; - }); - return index - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), - this.modeOption, this.first, this.lineSep, this.direction); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc - }, - - linkedDoc: function(options) { - if (!options) { options = {}; } - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) { from = options.from; } - if (options.to != null && options.to < to) { to = options.to; } - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); - if (options.sharedHist) { copy.history = this.history - ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy - }, - unlinkDoc: function(other) { - var this$1 = this; - - if (other instanceof CodeMirror) { other = other.doc; } - if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { - var link = this$1.linked[i]; - if (link.doc != other) { continue } - this$1.linked.splice(i, 1); - other.unlinkDoc(this$1); - detachSharedMarkers(findSharedMarkers(this$1)); - break - } } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function(f) {linkedDocs(this, f);}, - - getMode: function() {return this.mode}, - getEditor: function() {return this.cm}, - - splitLines: function(str) { - if (this.lineSep) { return str.split(this.lineSep) } - return splitLinesAuto(str) - }, - lineSeparator: function() { return this.lineSep || "\n" }, - - setDirection: docMethodOp(function (dir) { - if (dir != "rtl") { dir = "ltr"; } - if (dir == this.direction) { return } - this.direction = dir; - this.iter(function (line) { return line.order = null; }); - if (this.cm) { directionChanged(this.cm); } - }) - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - - function onDrop(e) { - var cm = this; - clearDragCursor(cm); - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) - { return } - e_preventDefault(e); - if (ie) { lastDrop = +new Date; } - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || cm.isReadOnly()) { return } - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var markAsReadAndPasteIfAllFilesAreRead = function () { - if (++read == n) { - operation(cm, function () { - pos = clipPos(cm.doc, pos); - var change = {from: pos, to: pos, - text: cm.doc.splitLines( - text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())), - origin: "paste"}; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); - })(); - } - }; - var readTextFromFile = function (file, i) { - if (cm.options.allowDropFileTypes && - indexOf(cm.options.allowDropFileTypes, file.type) == -1) { - markAsReadAndPasteIfAllFilesAreRead(); - return - } - var reader = new FileReader; - reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); }; - reader.onload = function () { - var content = reader.result; - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { - markAsReadAndPasteIfAllFilesAreRead(); - return - } - text[i] = content; - markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.readAsText(file); - }; - for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); } - } else { // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function () { return cm.display.input.focus(); }, 20); - return - } - try { - var text$1 = e.dataTransfer.getData("Text"); - if (text$1) { - var selected; - if (cm.state.draggingText && !cm.state.draggingText.copy) - { selected = cm.listSelections(); } - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) - { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } - cm.replaceSelection(text$1, "around", "paste"); - cm.display.input.focus(); - } - } - catch(e){} - } - } - - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } - - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove"; - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) { img.parentNode.removeChild(img); } - } - } - - function onDragOver(cm, e) { - var pos = posFromMouse(cm, e); - if (!pos) { return } - var frag = document.createDocumentFragment(); - drawSelectionCursor(cm, pos, frag); - if (!cm.display.dragCursor) { - cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); - cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); - } - removeChildrenAndAdd(cm.display.dragCursor, frag); - } - - function clearDragCursor(cm) { - if (cm.display.dragCursor) { - cm.display.lineSpace.removeChild(cm.display.dragCursor); - cm.display.dragCursor = null; - } - } - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.getElementsByClassName) { return } - var byClass = document.getElementsByClassName("CodeMirror"), editors = []; - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) { editors.push(cm); } - } - if (editors.length) { editors[0].operation(function () { - for (var i = 0; i < editors.length; i++) { f(editors[i]); } - }); } - } - - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) { return } - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function () { - if (resizeTimer == null) { resizeTimer = setTimeout(function () { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); } - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function () { return forEachCodeMirror(onBlur); }); - } - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - - var keyNames = { - 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", - 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" - }; - - // Number keys - for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } - // Alphabetic keys - for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } - // Function keys - for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } - - var keyMap = {}; - - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", - "fallthrough": "basic" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", - "Ctrl-O": "openLine" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", - "fallthrough": ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/); - name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } - else if (/^a(lt)?$/i.test(mod)) { alt = true; } - else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } - else if (/^s(hift)?$/i.test(mod)) { shift = true; } - else { throw new Error("Unrecognized modifier name: " + mod) } - } - if (alt) { name = "Alt-" + name; } - if (ctrl) { name = "Ctrl-" + name; } - if (cmd) { name = "Cmd-" + name; } - if (shift) { name = "Shift-" + name; } - return name - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - function normalizeKeyMap(keymap) { - var copy = {}; - for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } - if (value == "...") { delete keymap[keyname]; continue } - - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val = (void 0), name = (void 0); - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) { copy[name] = val; } - else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } - } - delete keymap[keyname]; - } } - for (var prop in copy) { keymap[prop] = copy[prop]; } - return keymap - } - - function lookupKey(key, map$$1, handle, context) { - map$$1 = getKeyMap(map$$1); - var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; - if (found === false) { return "nothing" } - if (found === "...") { return "multi" } - if (found != null && handle(found)) { return "handled" } - - if (map$$1.fallthrough) { - if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") - { return lookupKey(key, map$$1.fallthrough, handle, context) } - for (var i = 0; i < map$$1.fallthrough.length; i++) { - var result = lookupKey(key, map$$1.fallthrough[i], handle, context); - if (result) { return result } - } - } - } - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - function isModifierKey(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" - } - - function addModifierNames(name, event, noShift) { - var base = name; - if (event.altKey && base != "Alt") { name = "Alt-" + name; } - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } - if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } - return name - } - - // Look up the name of a key as indicated by an event object. - function keyName(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) { return false } - var name = keyNames[event.keyCode]; - if (name == null || event.altGraphKey) { return false } - // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, - // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) - if (event.keyCode == 3 && event.code) { name = event.code; } - return addModifierNames(name, event, noShift) - } - - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break - } - } - kill.push(toKill); - } - // Next, remove those actual ranges. - runInOp(cm, function () { - for (var i = kill.length - 1; i >= 0; i--) - { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } - ensureCursorVisible(cm); - }); - } - - function moveCharLogically(line, ch, dir) { - var target = skipExtendingChars(line.text, ch + dir, dir); - return target < 0 || target > line.text.length ? null : target - } - - function moveLogically(line, start, dir) { - var ch = moveCharLogically(line, start.ch, dir); - return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") - } - - function endOfLine(visually, cm, lineObj, lineNo, dir) { - if (visually) { - if (cm.doc.direction == "rtl") { dir = -dir; } - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = dir < 0 ? lst(order) : order[0]; - var moveInStorageOrder = (dir < 0) == (part.level == 1); - var sticky = moveInStorageOrder ? "after" : "before"; - var ch; - // With a wrapped rtl chunk (possibly spanning multiple bidi parts), - // it could be that the last bidi part is not on the last visual line, - // since visual lines contain content order-consecutive chunks. - // Thus, in rtl, we are looking for the first (content-order) character - // in the rtl chunk that is on the last line (that is, the same line - // as the last (content-order) character). - if (part.level > 0 || cm.doc.direction == "rtl") { - var prep = prepareMeasureForLine(cm, lineObj); - ch = dir < 0 ? lineObj.text.length - 1 : 0; - var targetTop = measureCharPrepared(cm, prep, ch).top; - ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); - if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } - } else { ch = dir < 0 ? part.to : part.from; } - return new Pos(lineNo, ch, sticky) - } - } - return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") - } - - function moveVisually(cm, line, start, dir) { - var bidi = getOrder(line, cm.doc.direction); - if (!bidi) { return moveLogically(line, start, dir) } - if (start.ch >= line.text.length) { - start.ch = line.text.length; - start.sticky = "before"; - } else if (start.ch <= 0) { - start.ch = 0; - start.sticky = "after"; - } - var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; - if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { - // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, - // nothing interesting happens. - return moveLogically(line, start, dir) - } - - var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; - var prep; - var getWrappedLineExtent = function (ch) { - if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } - prep = prep || prepareMeasureForLine(cm, line); - return wrappedLineExtentChar(cm, line, prep, ch) - }; - var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); - - if (cm.doc.direction == "rtl" || part.level == 1) { - var moveInStorageOrder = (part.level == 1) == (dir < 0); - var ch = mv(start, moveInStorageOrder ? 1 : -1); - if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { - // Case 2: We move within an rtl part or in an rtl editor on the same visual line - var sticky = moveInStorageOrder ? "before" : "after"; - return new Pos(start.line, ch, sticky) - } - } - - // Case 3: Could not move within this bidi part in this visual line, so leave - // the current bidi part - - var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { - var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder - ? new Pos(start.line, mv(ch, 1), "before") - : new Pos(start.line, ch, "after"); }; - - for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { - var part = bidi[partPos]; - var moveInStorageOrder = (dir > 0) == (part.level != 1); - var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); - if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } - ch = moveInStorageOrder ? part.from : mv(part.to, -1); - if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } - } - }; - - // Case 3a: Look for other bidi parts on the same visual line - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); - if (res) { return res } - - // Case 3b: Look for other bidi parts on the next visual line - var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); - if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { - res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); - if (res) { return res } - } - - // Case 4: Nowhere to move - return null - } - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = { - selectAll: selectAll, - singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, - killLine: function (cm) { return deleteNearSelection(cm, function (range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) - { return {from: range.head, to: Pos(range.head.line + 1, 0)} } - else - { return {from: range.head, to: Pos(range.head.line, len)} } - } else { - return {from: range.from(), to: range.to()} - } - }); }, - deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ - from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) - }); }); }, - delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ - from: Pos(range.from().line, 0), to: range.from() - }); }); }, - delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({left: 0, top: top}, "div"); - return {from: leftPos, to: range.from()} - }); }, - delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - return {from: range.from(), to: rightPos } - }); }, - undo: function (cm) { return cm.undo(); }, - redo: function (cm) { return cm.redo(); }, - undoSelection: function (cm) { return cm.undoSelection(); }, - redoSelection: function (cm) { return cm.redoSelection(); }, - goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, - goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, - goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, - {origin: "+move", bias: 1} - ); }, - goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, - {origin: "+move", bias: 1} - ); }, - goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, - {origin: "+move", bias: -1} - ); }, - goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") - }, sel_move); }, - goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - return cm.coordsChar({left: 0, top: top}, "div") - }, sel_move); }, - goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({left: 0, top: top}, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } - return pos - }, sel_move); }, - goLineUp: function (cm) { return cm.moveV(-1, "line"); }, - goLineDown: function (cm) { return cm.moveV(1, "line"); }, - goPageUp: function (cm) { return cm.moveV(-1, "page"); }, - goPageDown: function (cm) { return cm.moveV(1, "page"); }, - goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, - goCharRight: function (cm) { return cm.moveH(1, "char"); }, - goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, - goColumnRight: function (cm) { return cm.moveH(1, "column"); }, - goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, - goGroupRight: function (cm) { return cm.moveH(1, "group"); }, - goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, - goWordRight: function (cm) { return cm.moveH(1, "word"); }, - delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, - delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, - delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, - delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, - delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, - delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, - indentAuto: function (cm) { return cm.indentSelection("smart"); }, - indentMore: function (cm) { return cm.indentSelection("add"); }, - indentLess: function (cm) { return cm.indentSelection("subtract"); }, - insertTab: function (cm) { return cm.replaceSelection("\t"); }, - insertSoftTab: function (cm) { - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(spaceStr(tabSize - col % tabSize)); - } - cm.replaceSelections(spaces); - }, - defaultTab: function (cm) { - if (cm.somethingSelected()) { cm.indentSelection("add"); } - else { cm.execCommand("insertTab"); } - }, - // Swap the two chars left and right of each selection's head. - // Move cursor behind the two swapped characters afterwards. - // - // Doesn't consider line feeds a character. - // Doesn't scan more than one line above to find a character. - // Doesn't do anything on an empty line. - // Doesn't do anything with non-empty selections. - transposeChars: function (cm) { return runInOp(cm, function () { - var ranges = cm.listSelections(), newSel = []; - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) { continue } - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), - Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) { - cur = new Pos(cur.line, 1); - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + - prev.charAt(prev.length - 1), - Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); - } - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); }, - newlineAndIndent: function (cm) { return runInOp(cm, function () { - var sels = cm.listSelections(); - for (var i = sels.length - 1; i >= 0; i--) - { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } - sels = cm.listSelections(); - for (var i$1 = 0; i$1 < sels.length; i$1++) - { cm.indentLine(sels[i$1].from().line, null, true); } - ensureCursorVisible(cm); - }); }, - openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, - toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } - }; - - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) { lineN = lineNo(visual); } - return endOfLine(true, cm, visual, lineN, 1) - } - function lineEnd(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLineEnd(line); - if (visual != line) { lineN = lineNo(visual); } - return endOfLine(true, cm, line, lineN, -1) - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line, cm.doc.direction); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) - } - return start - } - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) { return false } - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, done = false; - try { - if (cm.isReadOnly()) { cm.state.suppressEdits = true; } - if (dropShift) { cm.display.shift = false; } - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done - } - - function lookupKeyForEditor(cm, name, handle) { - for (var i = 0; i < cm.state.keyMaps.length; i++) { - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); - if (result) { return result } - } - return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) - || lookupKey(name, cm.options.keyMap, handle, cm) - } - - // Note that, despite the name, this function is also used to check - // for bound mouse clicks. - - var stopSeq = new Delayed; - - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) { return "handled" } - if (/\'$/.test(name)) - { cm.state.keySeq = null; } - else - { stopSeq.set(50, function () { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); } - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } - } - return dispatchKeyInner(cm, name, e, handle) - } - - function dispatchKeyInner(cm, name, e, handle) { - var result = lookupKeyForEditor(cm, name, handle); - - if (result == "multi") - { cm.state.keySeq = name; } - if (result == "handled") - { signalLater(cm, "keyHandled", cm, name, e); } - - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - - return !!result - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) { return false } - - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) - || dispatchKey(cm, name, e, function (b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - { return doHandleBinding(cm, b) } - }) - } else { - return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) { return } - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - { cm.replaceSelection("", null, "cut"); } - } - if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) - { document.execCommand("cut"); } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) - { showCrossHair(cm); } - } - - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - - function onKeyUp(e) { - if (e.keyCode == 16) { this.doc.sel.shift = false; } - signalDOMEvent(this, e); - } - - function onKeyPress(e) { - var cm = this; - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } - var keyCode = e.keyCode, charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - // Some browsers fire keypress events for backspace - if (ch == "\x08") { return } - if (handleCharBinding(cm, e, ch)) { return } - cm.display.input.onKeyPress(e); - } - - var DOUBLECLICK_DELAY = 400; - - var PastClick = function(time, pos, button) { - this.time = time; - this.pos = pos; - this.button = button; - }; - - PastClick.prototype.compare = function (time, pos, button) { - return this.time + DOUBLECLICK_DELAY > time && - cmp(pos, this.pos) == 0 && button == this.button - }; - - var lastClick, lastDoubleClick; - function clickRepeat(pos, button) { - var now = +new Date; - if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { - lastClick = lastDoubleClick = null; - return "triple" - } else if (lastClick && lastClick.compare(now, pos, button)) { - lastDoubleClick = new PastClick(now, pos, button); - lastClick = null; - return "double" - } else { - lastClick = new PastClick(now, pos, button); - lastDoubleClick = null; - return "single" - } - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, display = cm.display; - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } - display.input.ensurePolled(); - display.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function () { return display.scroller.draggable = true; }, 100); - } - return - } - if (clickInGutter(cm, e)) { return } - var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; - window.focus(); - - // #3261: make sure, that we're not starting a second selection - if (button == 1 && cm.state.selectingText) - { cm.state.selectingText(e); } - - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } - - if (button == 1) { - if (pos) { leftButtonDown(cm, pos, repeat, e); } - else if (e_target(e) == display.scroller) { e_preventDefault(e); } - } else if (button == 2) { - if (pos) { extendSelection(cm.doc, pos); } - setTimeout(function () { return display.input.focus(); }, 20); - } else if (button == 3) { - if (captureRightClick) { cm.display.input.onContextMenu(e); } - else { delayBlurEvent(cm); } - } - } - - function handleMappedButton(cm, button, pos, repeat, event) { - var name = "Click"; - if (repeat == "double") { name = "Double" + name; } - else if (repeat == "triple") { name = "Triple" + name; } - name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; - - return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { - if (typeof bound == "string") { bound = commands[bound]; } - if (!bound) { return false } - var done = false; - try { - if (cm.isReadOnly()) { cm.state.suppressEdits = true; } - done = bound(cm, pos) != Pass; - } finally { - cm.state.suppressEdits = false; - } - return done - }) - } - - function configureMouse(cm, repeat, event) { - var option = cm.getOption("configureMouse"); - var value = option ? option(cm, repeat, event) : {}; - if (value.unit == null) { - var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; - value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; - } - if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } - if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } - if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } - return value - } - - function leftButtonDown(cm, pos, repeat, event) { - if (ie) { setTimeout(bind(ensureFocus, cm), 0); } - else { cm.curOp.focus = activeElt(); } - - var behavior = configureMouse(cm, repeat, event); - - var sel = cm.doc.sel, contained; - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && - repeat == "single" && (contained = sel.contains(pos)) > -1 && - (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && - (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) - { leftButtonStartDrag(cm, event, pos, behavior); } - else - { leftButtonSelect(cm, event, pos, behavior); } - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, event, pos, behavior) { - var display = cm.display, moved = false; - var dragEnd = operation(cm, function (e) { - if (webkit) { display.scroller.draggable = false; } - cm.state.draggingText = false; - off(display.wrapper.ownerDocument, "mouseup", dragEnd); - off(display.wrapper.ownerDocument, "mousemove", mouseMove); - off(display.scroller, "dragstart", dragStart); - off(display.scroller, "drop", dragEnd); - if (!moved) { - e_preventDefault(e); - if (!behavior.addNew) - { extendSelection(cm.doc, pos, null, null, behavior.extend); } - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit || ie && ie_version == 9) - { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); } - else - { display.input.focus(); } - } - }); - var mouseMove = function(e2) { - moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; - }; - var dragStart = function () { return moved = true; }; - // Let the drag handler handle this. - if (webkit) { display.scroller.draggable = true; } - cm.state.draggingText = dragEnd; - dragEnd.copy = !behavior.moveOnDrag; - // IE's approach to draggable - if (display.scroller.dragDrop) { display.scroller.dragDrop(); } - on(display.wrapper.ownerDocument, "mouseup", dragEnd); - on(display.wrapper.ownerDocument, "mousemove", mouseMove); - on(display.scroller, "dragstart", dragStart); - on(display.scroller, "drop", dragEnd); - - delayBlurEvent(cm); - setTimeout(function () { return display.input.focus(); }, 20); - } - - function rangeForUnit(cm, pos, unit) { - if (unit == "char") { return new Range(pos, pos) } - if (unit == "word") { return cm.findWordAt(pos) } - if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } - var result = unit(cm, pos); - return new Range(result.from, result.to) - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, event, start, behavior) { - var display = cm.display, doc = cm.doc; - e_preventDefault(event); - - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; - if (behavior.addNew && !behavior.extend) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) - { ourRange = ranges[ourIndex]; } - else - { ourRange = new Range(start, start); } - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - - if (behavior.unit == "rectangle") { - if (!behavior.addNew) { ourRange = new Range(start, start); } - start = posFromMouse(cm, event, true, true); - ourIndex = -1; - } else { - var range$$1 = rangeForUnit(cm, start, behavior.unit); - if (behavior.extend) - { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } - else - { ourRange = range$$1; } - } - - if (!behavior.addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), - {scroll: false, origin: "*mouse"}); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { - setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), - {scroll: false, origin: "*mouse"}); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) { return } - lastPos = pos; - - if (behavior.unit == "rectangle") { - var ranges = [], tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); - line <= end; line++) { - var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); - if (left == right) - { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } - else if (text.length > leftPos) - { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } - } - if (!ranges.length) { ranges.push(new Range(start, start)); } - setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), - {origin: "*mouse", scroll: false}); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var range$$1 = rangeForUnit(cm, pos, behavior.unit); - var anchor = oldRange.anchor, head; - if (cmp(range$$1.anchor, anchor) > 0) { - head = range$$1.head; - anchor = minPos(oldRange.from(), range$$1.anchor); - } else { - head = range$$1.anchor; - anchor = maxPos(oldRange.to(), range$$1.head); - } - var ranges$1 = startSel.ranges.slice(0); - ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); - setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); - } - } - - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); - if (!cur) { return } - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) { setTimeout(operation(cm, function () { - if (counter != curCount) { return } - display.scroller.scrollTop += outside; - extend(e); - }), 50); } - } - } - - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - // If e is null or undefined we interpret this as someone trying - // to explicitly cancel the selection rather than the user - // letting go of the mouse button. - if (e) { - e_preventDefault(e); - display.input.focus(); - } - off(display.wrapper.ownerDocument, "mousemove", move); - off(display.wrapper.ownerDocument, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - var move = operation(cm, function (e) { - if (e.buttons === 0 || !e_button(e)) { done(e); } - else { extend(e); } - }); - var up = operation(cm, done); - cm.state.selectingText = up; - on(display.wrapper.ownerDocument, "mousemove", move); - on(display.wrapper.ownerDocument, "mouseup", up); - } - - // Used when mouse-selecting to adjust the anchor to the proper side - // of a bidi jump depending on the visual position of the head. - function bidiSimplify(cm, range$$1) { - var anchor = range$$1.anchor; - var head = range$$1.head; - var anchorLine = getLine(cm.doc, anchor.line); - if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 } - var order = getOrder(anchorLine); - if (!order) { return range$$1 } - var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; - if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 } - var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); - if (boundary == 0 || boundary == order.length) { return range$$1 } - - // Compute the relative visual position of the head compared to the - // anchor (<0 is to the left, >0 to the right) - var leftSide; - if (head.line != anchor.line) { - leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; - } else { - var headIndex = getBidiPartAt(order, head.ch, head.sticky); - var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); - if (headIndex == boundary - 1 || headIndex == boundary) - { leftSide = dir < 0; } - else - { leftSide = dir > 0; } - } - - var usePart = order[boundary + (leftSide ? -1 : 0)]; - var from = leftSide == (usePart.level == 1); - var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; - return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head) - } - - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent) { - var mX, mY; - if (e.touches) { - mX = e.touches[0].clientX; - mY = e.touches[0].clientY; - } else { - try { mX = e.clientX; mY = e.clientY; } - catch(e) { return false } - } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } - if (prevent) { e_preventDefault(e); } - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } - mY -= lineBox.top - display.viewOffset; - - for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.display.gutterSpecs[i]; - signal(cm, type, cm, line, gutter.className, e); - return e_defaultPrevented(e) - } - } - } - - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true) - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } - if (signalDOMEvent(cm, e, "contextmenu")) { return } - if (!captureRightClick) { cm.display.input.onContextMenu(e); } - } - - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) { return false } - return gutterEvent(cm, e, "gutterContextMenu", false) - } - - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + - cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - - var Init = {toString: function(){return "CodeMirror.Init"}}; - - var defaults = {}; - var optionHandlers = {}; - - function defineOptions(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) { optionHandlers[name] = - notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } - } - - CodeMirror.defineOption = option; - - // Passed to option handlers when there is no old value. - CodeMirror.Init = Init; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function (cm, val) { return cm.setValue(val); }, true); - option("mode", null, function (cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function (cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - - option("lineSeparator", null, function (cm, val) { - cm.doc.lineSep = val; - if (!val) { return } - var newBreaks = [], lineNo = cm.doc.first; - cm.doc.iter(function (line) { - for (var pos = 0;;) { - var found = line.text.indexOf(val, pos); - if (found == -1) { break } - pos = found + val.length; - newBreaks.push(Pos(lineNo, found)); - } - lineNo++; - }); - for (var i = newBreaks.length - 1; i >= 0; i--) - { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } - }); - option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != Init) { cm.refresh(); } - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function () { - throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME - }, true); - option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); - option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); - option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function (cm) { - themeChanged(cm); - updateGutters(cm); - }, true); - option("keyMap", "default", function (cm, val, old) { - var next = getKeyMap(val); - var prev = old != Init && getKeyMap(old); - if (prev && prev.detach) { prev.detach(cm, next); } - if (next.attach) { next.attach(cm, prev || null); } - }); - option("extraKeys", null); - option("configureMouse", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function (cm, val) { - cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); - updateGutters(cm); - }, true); - option("fixedGutter", true, function (cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); - option("scrollbarStyle", "native", function (cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function (cm, val) { - cm.display.gutterSpecs = getGutters(cm.options.gutters, val); - updateGutters(cm); - }, true); - option("firstLineNumber", 1, updateGutters, true); - option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - option("pasteLinesPerSelection", true); - option("selectionsMayTouch", false); - - option("readOnly", false, function (cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - } - cm.display.input.readOnlyChanged(val); - }); - - option("screenReaderLabel", null, function (cm, val) { - val = (val === '') ? null : val; - cm.display.input.screenReaderLabelChanged(val); - }); - - option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); - option("dragDrop", true, dragDropChanged); - option("allowDropFileTypes", null); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function (cm, val) { - if (!val) { cm.display.input.resetPosition(); } - }); - - option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); - option("autofocus", null); - option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); - option("phrases", null); - } - - function dragDropChanged(cm, value, old) { - var wasOn = old && old != Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.enter); - toggle(cm.display.scroller, "dragover", funcs.over); - toggle(cm.display.scroller, "dragleave", funcs.leave); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function () { return updateScrollbars(cm); }, 100); - } - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - var this$1 = this; - - if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } - - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - - var doc = options.value; - if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } - else if (options.mode) { doc.modeOption = options.mode; } - this.doc = doc; - - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input, options); - display.wrapper.CodeMirror = this; - themeChanged(this); - if (options.lineWrapping) - { this.display.wrapper.className += " CodeMirror-wrap"; } - initScrollbars(this); - - this.state = { - keyMaps: [], // stores maps added by addKeyMap - overlays: [], // highlighting overlays, as added by addOverlay - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode - pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll - selectingText: false, - draggingText: false, - highlight: new Delayed(), // stores highlight worker timeout - keySeq: null, // Unfinished key sequence - specialChars: null - }; - - if (options.autofocus && !mobile) { display.input.focus(); } - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } - - registerEventHandlers(this); - ensureGlobalHandlers(); - - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - - if ((options.autofocus && !mobile) || this.hasFocus()) - { setTimeout(bind(onFocus, this), 20); } - else - { onBlur(this); } - - for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) - { optionHandlers[opt](this$1, options[opt], Init); } } - maybeUpdateLineNumberWidth(this); - if (options.finishInit) { options.finishInit(this); } - for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") - { display.lineDiv.style.textRendering = "auto"; } - } - - // The default configuration options. - CodeMirror.defaults = defaults; - // Functions to run when options are changed. - CodeMirror.optionHandlers = optionHandlers; - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) - { on(d.scroller, "dblclick", operation(cm, function (e) { - if (signalDOMEvent(cm, e)) { return } - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); } - else - { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); - on(d.input.getField(), "contextmenu", function (e) { - if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); } - }); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, prevTouch = {end: 0}; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date; - } - } - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) { return false } - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1 - } - function farAway(touch, other) { - if (other.left == null) { return true } - var dx = other.left - touch.left, dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20 - } - on(d.scroller, "touchstart", function (e) { - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { - d.input.ensurePolled(); - clearTimeout(touchFinished); - var now = +new Date; - d.activeTouch = {start: now, moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null}; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function () { - if (d.activeTouch) { d.activeTouch.moved = true; } - }); - on(d.scroller, "touchend", function (e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && - !touch.moved && new Date - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), range; - if (!touch.prev || farAway(touch, touch.prev)) // Single tap - { range = new Range(pos, pos); } - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap - { range = cm.findWordAt(pos); } - else // Triple tap - { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function () { - if (d.scroller.clientHeight) { - updateScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); - - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); - on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); - - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); - - d.dragFunctions = { - enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, - over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, - start: function (e) { return onDragStart(cm, e); }, - drop: operation(cm, onDrop), - leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} - }; - - var inp = d.input.getField(); - on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", function (e) { return onFocus(cm, e); }); - on(inp, "blur", function (e) { return onBlur(cm, e); }); - } - - var initHooks = []; - CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, state; - if (how == null) { how = "add"; } - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) { how = "prev"; } - else { state = getContextBefore(cm, n).state; } - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) { line.stateAfter = null; } - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) { return } - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } - else { indentation = 0; } - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var indentString = "", pos = 0; - if (cm.options.indentWithTabs) - { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } - if (pos < indentation) { indentString += spaceStr(indentation - pos); } - - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { - var range = doc.sel.ranges[i$1]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos$1 = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); - break - } - } - } - } - - // This will be set to a {lineWise: bool, text: [string]} object, so - // that, when pasting, we know what kind of selections the copied - // text was made out of. - var lastCopied = null; - - function setLastCopied(newLastCopied) { - lastCopied = newLastCopied; - } - - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) { sel = doc.sel; } - - var recent = +new Date - 200; - var paste = origin == "paste" || cm.state.pasteIncoming > recent; - var textLines = splitLinesAuto(inserted), multiPaste = null; - // When pasting N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.text.join("\n") == inserted) { - if (sel.ranges.length % lastCopied.text.length == 0) { - multiPaste = []; - for (var i = 0; i < lastCopied.text.length; i++) - { multiPaste.push(doc.splitLines(lastCopied.text[i])); } - } - } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { - multiPaste = map(textLines, function (l) { return [l]; }); - } - } - - var updateInput = cm.curOp.updateInput; - // Normal behavior is to insert the new text into every selection - for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { - var range$$1 = sel.ranges[i$1]; - var from = range$$1.from(), to = range$$1.to(); - if (range$$1.empty()) { - if (deleted && deleted > 0) // Handle deletion - { from = Pos(from.line, from.ch - deleted); } - else if (cm.state.overwrite && !paste) // Handle overwrite - { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } - else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) - { from = to = Pos(from.line, 0); } - } - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) - { triggerElectric(cm, inserted); } - - ensureCursorVisible(cm); - if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = -1; - } - - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) - { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } - return true - } - } - - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) { return } - var sel = cm.doc.sel; - - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range$$1 = sel.ranges[i]; - if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } - var mode = cm.getModeAt(range$$1.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) - { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range$$1.head.line, "smart"); - break - } } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) - { indented = indentLine(cm, range$$1.head.line, "smart"); } - } - if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } - } - } - - function copyableRanges(cm) { - var text = [], ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return {text: text, ranges: ranges} - } - - function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { - field.setAttribute("autocorrect", autocorrect ? "" : "off"); - field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); - field.setAttribute("spellcheck", !!spellcheck); - } - - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) { te.style.width = "1000px"; } - else { te.setAttribute("wrap", "off"); } - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) { te.style.border = "1px solid black"; } - disableBrowserMagic(te); - return div - } - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - function addEditorMethods(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - - var helpers = CodeMirror.helpers = {}; - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") { return } - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - { operation(this, optionHandlers[option])(this, value, old); } - signal(this, "optionChange", this, option); - }, - - getOption: function(option) {return this.options[option]}, - getDoc: function() {return this.doc}, - - addKeyMap: function(map$$1, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); - }, - removeKeyMap: function(map$$1) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - { if (maps[i] == map$$1 || maps[i].name == map$$1) { - maps.splice(i, 1); - return true - } } - }, - - addOverlay: methodOp(function(spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) { throw new Error("Overlays may not be stateful.") } - insertSorted(this.state.overlays, - {mode: mode, modeSpec: spec, opaque: options && options.opaque, - priority: (options && options.priority) || 0}, - function (overlay) { return overlay.priority; }); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function(spec) { - var this$1 = this; - - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this$1.state.modeGen++; - regChange(this$1); - return - } - } - }), - - indentLine: methodOp(function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } - else { dir = dir ? "add" : "subtract"; } - } - if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } - }), - indentSelection: methodOp(function(how) { - var this$1 = this; - - var ranges = this.doc.sel.ranges, end = -1; - for (var i = 0; i < ranges.length; i++) { - var range$$1 = ranges[i]; - if (!range$$1.empty()) { - var from = range$$1.from(), to = range$$1.to(); - var start = Math.max(end, from.line); - end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) - { indentLine(this$1, j, how); } - var newRanges = this$1.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) - { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } - } else if (range$$1.head.line > end) { - indentLine(this$1, range$$1.head.line, how, true); - end = range$$1.head.line; - if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } - } - } - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - return takeToken(this, pos, precise) - }, - - getLineTokens: function(line, precise) { - return takeToken(this, Pos(line), precise, true) - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - var type; - if (ch == 0) { type = styles[2]; } - else { for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } - else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } - else { type = styles[mid * 2 + 2]; break } - } } - var cut = type ? type.indexOf("overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { return mode } - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0] - }, - - getHelpers: function(pos, type) { - var this$1 = this; - - var found = []; - if (!helpers.hasOwnProperty(type)) { return found } - var help = helpers[type], mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) { found.push(help[mode[type]]); } - } else if (mode[type]) { - for (var i = 0; i < mode[type].length; i++) { - var val = help[mode[type][i]]; - if (val) { found.push(val); } - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i$1 = 0; i$1 < help._global.length; i$1++) { - var cur = help._global[i$1]; - if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) - { found.push(cur.val); } - } - return found - }, - - getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getContextBefore(this, line + 1, precise).state - }, - - cursorCoords: function(start, mode) { - var pos, range$$1 = this.doc.sel.primary(); - if (start == null) { pos = range$$1.head; } - else if (typeof start == "object") { pos = clipPos(this.doc, start); } - else { pos = start ? range$$1.from() : range$$1.to(); } - return cursorCoords(this, pos, mode || "page") - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page") - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top) - }, - - lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset) - }, - heightAtLine: function(line, mode, includeWidgets) { - var end = false, lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) { line = this.doc.first; } - else if (line > last) { line = last; end = true; } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + - (end ? this.doc.height - heightAtLine(lineObj) : 0) - }, - - defaultTextHeight: function() { return textHeight(this.display) }, - defaultCharWidth: function() { return charWidth(this.display) }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, - - addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - { top = pos.top - node.offsetHeight; } - else if (pos.bottom + node.offsetHeight <= vspace) - { top = pos.bottom; } - if (left + node.offsetWidth > hspace) - { left = hspace - node.offsetWidth; } - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") { left = 0; } - else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } - node.style.left = left + "px"; - } - if (scroll) - { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - - execCommand: function(cmd) { - if (commands.hasOwnProperty(cmd)) - { return commands[cmd].call(null, this) } - }, - - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), - - findPosH: function(from, amount, unit, visually) { - var this$1 = this; - - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - var cur = clipPos(this.doc, from); - for (var i = 0; i < amount; ++i) { - cur = findPosH(this$1.doc, cur, dir, unit, visually); - if (cur.hitSide) { break } - } - return cur - }, - - moveH: methodOp(function(dir, unit) { - var this$1 = this; - - this.extendSelectionsBy(function (range$$1) { - if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) - { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } - else - { return dir < 0 ? range$$1.from() : range$$1.to() } - }, sel_move); - }), - - deleteH: methodOp(function(dir, unit) { - var sel = this.doc.sel, doc = this.doc; - if (sel.somethingSelected()) - { doc.replaceSelection("", null, "+delete"); } - else - { deleteNearSelection(this, function (range$$1) { - var other = findPosH(doc, range$$1.head, dir, unit, false); - return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} - }); } - }), - - findPosV: function(from, amount, unit, goalColumn) { - var this$1 = this; - - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - var cur = clipPos(this.doc, from); - for (var i = 0; i < amount; ++i) { - var coords = cursorCoords(this$1, cur, "div"); - if (x == null) { x = coords.left; } - else { coords.left = x; } - cur = findPosV(this$1, coords, dir, unit); - if (cur.hitSide) { break } - } - return cur - }, - - moveV: methodOp(function(dir, unit) { - var this$1 = this; - - var doc = this.doc, goals = []; - var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function (range$$1) { - if (collapse) - { return dir < 0 ? range$$1.from() : range$$1.to() } - var headPos = cursorCoords(this$1, range$$1.head, "div"); - if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } - goals.push(headPos.left); - var pos = findPosV(this$1, headPos, dir, unit); - if (unit == "page" && range$$1 == doc.sel.primary()) - { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } - return pos - }, sel_move); - if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) - { doc.sel.ranges[i].goalColumn = goals[i]; } } - }), - - // Find the word at the given position (as returned by coordsChar). - findWordAt: function(pos) { - var doc = this.doc, line = getLine(doc, pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) - ? function (ch) { return isWordChar(ch, helper); } - : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } - : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; - while (start > 0 && check(line.charAt(start - 1))) { --start; } - while (end < line.length && check(line.charAt(end))) { ++end; } - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)) - }, - - toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) { return } - if (this.state.overwrite = !this.state.overwrite) - { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } - else - { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } - - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function() { return this.display.input.getField() == activeElt() }, - isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, - - scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), - getScrollInfo: function() { - var scroller = this.display.scroller; - return {left: scroller.scrollLeft, top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), clientWidth: displayWidth(this)} - }, - - scrollIntoView: methodOp(function(range$$1, margin) { - if (range$$1 == null) { - range$$1 = {from: this.doc.sel.primary().head, to: null}; - if (margin == null) { margin = this.options.cursorScrollMargin; } - } else if (typeof range$$1 == "number") { - range$$1 = {from: Pos(range$$1, 0), to: null}; - } else if (range$$1.from == null) { - range$$1 = {from: range$$1, to: null}; - } - if (!range$$1.to) { range$$1.to = range$$1.from; } - range$$1.margin = margin || 0; - - if (range$$1.from.line != null) { - scrollToRange(this, range$$1); - } else { - scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); - } - }), - - setSize: methodOp(function(width, height) { - var this$1 = this; - - var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; - if (width != null) { this.display.wrapper.style.width = interpret(width); } - if (height != null) { this.display.wrapper.style.height = interpret(height); } - if (this.options.lineWrapping) { clearLineMeasurementCache(this); } - var lineNo$$1 = this.display.viewFrom; - this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { - if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) - { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } - ++lineNo$$1; - }); - this.curOp.forceUpdate = true; - signal(this, "refresh", this); - }), - - operation: function(f){return runInOp(this, f)}, - startOperation: function(){return startOperation(this)}, - endOperation: function(){return endOperation(this)}, - - refresh: methodOp(function() { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this.display); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) - { estimateLineHeights(this); } - signal(this, "refresh", this); - }), - - swapDoc: methodOp(function(doc) { - var old = this.doc; - old.cm = null; - // Cancel the current text selection if any (#5821) - if (this.state.selectingText) { this.state.selectingText(); } - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - scrollToCoords(this, doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old - }), - - phrase: function(phraseText) { - var phrases = this.options.phrases; - return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText - }, - - getInputField: function(){return this.display.input.getField()}, - getWrapperElement: function(){return this.display.wrapper}, - getScrollerElement: function(){return this.display.scroller}, - getGutterElement: function(){return this.display.gutters} - }; - eventMixin(CodeMirror); - - CodeMirror.registerHelper = function(type, name, value) { - if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } - helpers[type][name] = value; - }; - CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { - CodeMirror.registerHelper(type, name, value); - helpers[type]._global.push({pred: predicate, val: value}); - }; - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "char", "column" (like char, but doesn't - // cross line boundaries), "word" (across next word), or "group" (to - // the start of next group of word or non-word-non-whitespace - // chars). The visually param controls whether, in right-to-left - // text, direction 1 means to move towards the next index in the - // string, or towards the character to the right of the current - // position. The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var oldPos = pos; - var origDir = dir; - var lineObj = getLine(doc, pos.line); - var lineDir = visually && doc.direction == "rtl" ? -dir : dir; - function findNextLine() { - var l = pos.line + lineDir; - if (l < doc.first || l >= doc.first + doc.size) { return false } - pos = new Pos(l, pos.ch, pos.sticky); - return lineObj = getLine(doc, l) - } - function moveOnce(boundToLine) { - var next; - if (visually) { - next = moveVisually(doc.cm, lineObj, pos, dir); - } else { - next = moveLogically(lineObj, pos, dir); - } - if (next == null) { - if (!boundToLine && findNextLine()) - { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); } - else - { return false } - } else { - pos = next; - } - return true - } - - if (unit == "char") { - moveOnce(); - } else if (unit == "column") { - moveOnce(true); - } else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) { break } - var cur = lineObj.text.charAt(pos.ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" - : group && cur == "\n" ? "n" - : !group || /\s/.test(cur) ? null - : "p"; - if (group && !first && !type) { type = "s"; } - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} - break - } - - if (type) { sawType = type; } - if (dir > 0 && !moveOnce(!first)) { break } - } - } - var result = skipAtomic(doc, pos, oldPos, origDir, true); - if (equalCursorPos(oldPos, result)) { result.hitSide = true; } - return result - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - var target; - for (;;) { - target = coordsChar(cm, x, y); - if (!target.outside) { break } - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } - y += dir * 5; - } - return target - } - - // CONTENTEDITABLE INPUT STYLE - - var ContentEditableInput = function(cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.composing = null; - this.gracePeriod = false; - this.readDOMTimeout = null; - }; - - ContentEditableInput.prototype.init = function (display) { - var this$1 = this; - - var input = this, cm = input.cm; - var div = input.div = display.lineDiv; - disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); - - on(div, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } - // IE doesn't fire input events, so we schedule a read for the pasted content in this way - if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } - }); - - on(div, "compositionstart", function (e) { - this$1.composing = {data: e.data, done: false}; - }); - on(div, "compositionupdate", function (e) { - if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } - }); - on(div, "compositionend", function (e) { - if (this$1.composing) { - if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } - this$1.composing.done = true; - } - }); - - on(div, "touchstart", function () { return input.forceCompositionEnd(); }); - - on(div, "input", function () { - if (!this$1.composing) { this$1.readFromDOMSoon(); } - }); - - function onCopyCut(e) { - if (signalDOMEvent(cm, e)) { return } - if (cm.somethingSelected()) { - setLastCopied({lineWise: false, text: cm.getSelections()}); - if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } - } else if (!cm.options.lineWiseCopyCut) { - return - } else { - var ranges = copyableRanges(cm); - setLastCopied({lineWise: true, text: ranges.text}); - if (e.type == "cut") { - cm.operation(function () { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); - } - } - if (e.clipboardData) { - e.clipboardData.clearData(); - var content = lastCopied.text.join("\n"); - // iOS exposes the clipboard API, but seems to discard content inserted into it - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return - } - } - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.text.join("\n"); - var hadFocus = document.activeElement; - selectInput(te); - setTimeout(function () { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) { input.showPrimarySelection(); } - }, 50); - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }; - - ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { - // Label for screenreaders, accessibility - if(label) { - this.div.setAttribute('aria-label', label); - } else { - this.div.removeAttribute('aria-label'); - } - }; - - ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = document.activeElement == this.div; - return result - }; - - ContentEditableInput.prototype.showSelection = function (info, takeFocus) { - if (!info || !this.cm.display.view.length) { return } - if (info.focus || takeFocus) { this.showPrimarySelection(); } - this.showMultipleSelections(info); - }; - - ContentEditableInput.prototype.getSelection = function () { - return this.cm.display.wrapper.ownerDocument.getSelection() - }; - - ContentEditableInput.prototype.showPrimarySelection = function () { - var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); - var from = prim.from(), to = prim.to(); - - if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { - sel.removeAllRanges(); - return - } - - var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && - cmp(minPos(curAnchor, curFocus), from) == 0 && - cmp(maxPos(curAnchor, curFocus), to) == 0) - { return } - - var view = cm.display.view; - var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || - {node: view[0].measure.map[2], offset: 0}; - var end = to.line < cm.display.viewTo && posToDOM(cm, to); - if (!end) { - var measure = view[view.length - 1].measure; - var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; - } - - if (!start || !end) { - sel.removeAllRanges(); - return - } - - var old = sel.rangeCount && sel.getRangeAt(0), rng; - try { rng = range(start.node, start.offset, end.offset, end.node); } - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - if (!gecko && cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) { - sel.removeAllRanges(); - sel.addRange(rng); - } - } else { - sel.removeAllRanges(); - sel.addRange(rng); - } - if (old && sel.anchorNode == null) { sel.addRange(old); } - else if (gecko) { this.startGracePeriod(); } - } - this.rememberSelection(); - }; - - ContentEditableInput.prototype.startGracePeriod = function () { - var this$1 = this; - - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function () { - this$1.gracePeriod = false; - if (this$1.selectionChanged()) - { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } - }, 20); - }; - - ContentEditableInput.prototype.showMultipleSelections = function (info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }; - - ContentEditableInput.prototype.rememberSelection = function () { - var sel = this.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; - }; - - ContentEditableInput.prototype.selectionInEditor = function () { - var sel = this.getSelection(); - if (!sel.rangeCount) { return false } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node) - }; - - ContentEditableInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor") { - if (!this.selectionInEditor() || document.activeElement != this.div) - { this.showSelection(this.prepareSelection(), true); } - this.div.focus(); - } - }; - ContentEditableInput.prototype.blur = function () { this.div.blur(); }; - ContentEditableInput.prototype.getField = function () { return this.div }; - - ContentEditableInput.prototype.supportsTouch = function () { return true }; - - ContentEditableInput.prototype.receivedFocus = function () { - var input = this; - if (this.selectionInEditor()) - { this.pollSelection(); } - else - { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } - - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }; - - ContentEditableInput.prototype.selectionChanged = function () { - var sel = this.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset - }; - - ContentEditableInput.prototype.pollSelection = function () { - if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } - var sel = this.getSelection(), cm = this.cm; - // On Android Chrome (version 56, at least), backspacing into an - // uneditable block element will put the cursor in that element, - // and then, because it's not editable, hide the virtual keyboard. - // Because Android doesn't allow us to actually detect backspace - // presses in a sane way, this code checks for when that happens - // and simulates a backspace press in this case. - if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { - this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); - this.blur(); - this.focus(); - return - } - if (this.composing) { return } - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) { runInOp(cm, function () { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } - }); } - }; - - ContentEditableInput.prototype.pollContent = function () { - if (this.readDOMTimeout != null) { - clearTimeout(this.readDOMTimeout); - this.readDOMTimeout = null; - } - - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); - var from = sel.from(), to = sel.to(); - if (from.ch == 0 && from.line > cm.firstLine()) - { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } - if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) - { to = Pos(to.line + 1, 0); } - if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } - - var fromIndex, fromLine, fromNode; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - fromLine = lineNo(display.view[0].line); - fromNode = display.view[0].node; - } else { - fromLine = lineNo(display.view[fromIndex].line); - fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - var toLine, toNode; - if (toIndex == display.view.length - 1) { - toLine = display.viewTo - 1; - toNode = display.lineDiv.lastChild; - } else { - toLine = lineNo(display.view[toIndex + 1].line) - 1; - toNode = display.view[toIndex + 1].node.previousSibling; - } - - if (!fromNode) { return false } - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } - else { break } - } - - var cutFront = 0, cutEnd = 0; - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) - { ++cutFront; } - var newBot = lst(newText), oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) - { ++cutEnd; } - // Try to move start of change to start of selection if ambiguous - if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { - while (cutFront && cutFront > from.ch && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - cutFront--; - cutEnd++; - } - } - - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); - - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true - } - }; - - ContentEditableInput.prototype.ensurePolled = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.reset = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.forceCompositionEnd = function () { - if (!this.composing) { return } - clearTimeout(this.readDOMTimeout); - this.composing = null; - this.updateFromDOM(); - this.div.blur(); - this.div.focus(); - }; - ContentEditableInput.prototype.readFromDOMSoon = function () { - var this$1 = this; - - if (this.readDOMTimeout != null) { return } - this.readDOMTimeout = setTimeout(function () { - this$1.readDOMTimeout = null; - if (this$1.composing) { - if (this$1.composing.done) { this$1.composing = null; } - else { return } - } - this$1.updateFromDOM(); - }, 80); - }; - - ContentEditableInput.prototype.updateFromDOM = function () { - var this$1 = this; - - if (this.cm.isReadOnly() || !this.pollContent()) - { runInOp(this.cm, function () { return regChange(this$1.cm); }); } - }; - - ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; - }; - - ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { return } - e.preventDefault(); - if (!this.cm.isReadOnly()) - { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } - }; - - ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); - }; - - ContentEditableInput.prototype.onContextMenu = function () {}; - ContentEditableInput.prototype.resetPosition = function () {}; - - ContentEditableInput.prototype.needsContentAttribute = true; - - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) { return null } - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - - var order = getOrder(line, cm.doc.direction), side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result - } - - function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) - { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } - return false - } - - function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } - - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; - function recognizeMarker(id) { return function (marker) { return marker.id == id; } } - function close() { - if (closing) { - text += lineSep; - if (extraLinebreak) { text += lineSep; } - closing = extraLinebreak = false; - } - } - function addText(str) { - if (str) { - close(); - text += str; - } - } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText) { - addText(cmText); - return - } - var markerID = node.getAttribute("cm-marker"), range$$1; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range$$1 = found[0].find(0))) - { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } - return - } - if (node.getAttribute("contenteditable") == "false") { return } - var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); - if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } - - if (isBlock) { close(); } - for (var i = 0; i < node.childNodes.length; i++) - { walk(node.childNodes[i]); } - - if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } - if (isBlock) { closing = true; } - } else if (node.nodeType == 3) { - addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); - } - } - for (;;) { - walk(from); - if (from == to) { break } - from = from.nextSibling; - extraLinebreak = false; - } - return text - } - - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } - node = null; offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) { return null } - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } - } - } - for (var i = 0; i < cm.display.view.length; i++) { - var lineView = cm.display.view[i]; - if (lineView.node == lineNode) - { return locateNodeInLineView(lineView, node, offset) } - } - } - - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, bad = false; - if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad) - } - } - - var textNode = node.nodeType == 3 ? node : null, topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) { offset = textNode.nodeValue.length; } - } - while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } - var measure = lineView.measure, maps = measure.maps; - - function find(textNode, topNode, offset) { - for (var i = -1; i < (maps ? maps.length : 0); i++) { - var map$$1 = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map$$1.length; j += 3) { - var curNode = map$$1[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map$$1[j] + offset; - if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } - return Pos(line, ch) - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) { return badPos(found, bad) } - - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) - { return badPos(Pos(found.line, found.ch - dist), bad) } - else - { dist += after.textContent.length; } - } - for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) - { return badPos(Pos(found.line, found.ch + dist$1), bad) } - else - { dist$1 += before.textContent.length; } - } - } - - // TEXTAREA INPUT STYLE - - var TextareaInput = function(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; - - TextareaInput.prototype.init = function (display) { - var this$1 = this; - - var input = this, cm = this.cm; - this.createField(display); - var te = this.textarea; - - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) { te.style.width = "0px"; } - - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } - input.poll(); - }); - - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } - - cm.state.pasteIncoming = +new Date; - input.fastPoll(); - }); - - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) { return } - if (cm.somethingSelected()) { - setLastCopied({lineWise: false, text: cm.getSelections()}); - } else if (!cm.options.lineWiseCopyCut) { - return - } else { - var ranges = copyableRanges(cm); - setLastCopied({lineWise: true, text: ranges.text}); - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") { cm.state.cutIncoming = +new Date; } - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - - on(display.scroller, "paste", function (e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } - if (!te.dispatchEvent) { - cm.state.pasteIncoming = +new Date; - input.focus(); - return - } - - // Pass the `paste` event to the textarea so it's handled by its event listener. - var event = new Event("paste"); - event.clipboardData = e.clipboardData; - te.dispatchEvent(event); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function (e) { - if (!eventInWidget(display, e)) { e_preventDefault(e); } - }); - - on(te, "compositionstart", function () { - var start = cm.getCursor("from"); - if (input.composing) { input.composing.range.clear(); } - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) - }; - }); - on(te, "compositionend", function () { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }; - - TextareaInput.prototype.createField = function (_display) { - // Wraps and hides input textarea - this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - this.textarea = this.wrapper.firstChild; - }; - - TextareaInput.prototype.screenReaderLabelChanged = function (label) { - // Label for screenreaders, accessibility - if(label) { - this.textarea.setAttribute('aria-label', label); - } else { - this.textarea.removeAttribute('aria-label'); - } - }; - - TextareaInput.prototype.prepareSelection = function () { - // Redraw the selection and/or cursor - var cm = this.cm, display = cm.display, doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)); - } - - return result - }; - - TextareaInput.prototype.showSelection = function (drawn) { - var cm = this.cm, display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }; - - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - TextareaInput.prototype.reset = function (typing) { - if (this.contextMenuPending || this.composing) { return } - var cm = this.cm; - if (cm.somethingSelected()) { - this.prevInput = ""; - var content = cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) { selectInput(this.textarea); } - if (ie && ie_version >= 9) { this.hasSelection = content; } - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) { this.hasSelection = null; } - } - }; - - TextareaInput.prototype.getField = function () { return this.textarea }; - - TextareaInput.prototype.supportsTouch = function () { return false }; - - TextareaInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { this.textarea.focus(); } - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } - }; - - TextareaInput.prototype.blur = function () { this.textarea.blur(); }; - - TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; - }; - - TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - TextareaInput.prototype.slowPoll = function () { - var this$1 = this; - - if (this.pollingFast) { return } - this.polling.set(this.cm.options.pollInterval, function () { - this$1.poll(); - if (this$1.cm.state.focused) { this$1.slowPoll(); } - }); - }; - - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - TextareaInput.prototype.fastPoll = function () { - var missed = false, input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) {missed = true; input.polling.set(60, p);} - else {input.pollingFast = false; input.slowPoll();} - } - input.polling.set(20, p); - }; - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - TextareaInput.prototype.poll = function () { - var this$1 = this; - - var cm = this.cm, input = this.textarea, prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || - (hasSelection(input) && !prevInput && !this.composing) || - cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) - { return false } - - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) { return false } - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || - mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false - } - - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } - } - // Find the part of the input that is actually new - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } - - runInOp(cm, function () { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, this$1.composing ? "*compose" : null); - - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } - else { this$1.prevInput = text; } - - if (this$1.composing) { - this$1.composing.range.clear(); - this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), - {className: "CodeMirror-composing"}); - } - }); - return true - }; - - TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { this.pollingFast = false; } - }; - - TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { this.hasSelection = null; } - this.fastPoll(); - }; - - TextareaInput.prototype.onContextMenu = function (e) { - var input = this, cm = input.cm, display = cm.display, te = input.textarea; - if (input.contextMenuPending) { input.contextMenuPending(); } - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || presto) { return } // Opera is difficult. - - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) - { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } - - var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; - var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); - input.wrapper.style.cssText = "position: static"; - te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - var oldScrollY; - if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) { window.scrollTo(null, oldScrollY); } - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } - input.contextMenuPending = rehide; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - if (input.contextMenuPending != rehide) { return } - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } - var i = 0, poll = function () { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && - te.selectionEnd > 0 && input.prevInput == "\u200b") { - operation(cm, selectAll)(cm); - } else if (i++ < 10) { - display.detectingSelectAll = setTimeout(poll, 500); - } else { - display.selForContextMenu = null; - display.input.reset(); - } - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - - if (ie && ie_version >= 9) { prepareSelectAllHack(); } - if (captureRightClick) { - e_stop(e); - var mouseup = function () { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }; - - TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { this.reset(); } - this.textarea.disabled = val == "nocursor"; - }; - - TextareaInput.prototype.setUneditable = function () {}; - - TextareaInput.prototype.needsContentAttribute = false; - - function fromTextArea(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) - { options.tabindex = textarea.tabIndex; } - if (!options.placeholder && textarea.placeholder) - { options.placeholder = textarea.placeholder; } - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - - function save() {textarea.value = cm.getValue();} - - var realSubmit; - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form; - realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function () { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch(e) {} - } - } - - options.finishInit = function (cm) { - cm.save = save; - cm.getTextArea = function () { return textarea; }; - cm.toTextArea = function () { - cm.toTextArea = isNaN; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") - { textarea.form.submit = realSubmit; } - } - }; - }; - - textarea.style.display = "none"; - var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, - options); - return cm - } - - function addLegacyProps(CodeMirror) { - CodeMirror.off = off; - CodeMirror.on = on; - CodeMirror.wheelEventPixels = wheelEventPixels; - CodeMirror.Doc = Doc; - CodeMirror.splitLines = splitLinesAuto; - CodeMirror.countColumn = countColumn; - CodeMirror.findColumn = findColumn; - CodeMirror.isWordChar = isWordCharBasic; - CodeMirror.Pass = Pass; - CodeMirror.signal = signal; - CodeMirror.Line = Line; - CodeMirror.changeEnd = changeEnd; - CodeMirror.scrollbarModel = scrollbarModel; - CodeMirror.Pos = Pos; - CodeMirror.cmpPos = cmp; - CodeMirror.modes = modes; - CodeMirror.mimeModes = mimeModes; - CodeMirror.resolveMode = resolveMode; - CodeMirror.getMode = getMode; - CodeMirror.modeExtensions = modeExtensions; - CodeMirror.extendMode = extendMode; - CodeMirror.copyState = copyState; - CodeMirror.startState = startState; - CodeMirror.innerMode = innerMode; - CodeMirror.commands = commands; - CodeMirror.keyMap = keyMap; - CodeMirror.keyName = keyName; - CodeMirror.isModifierKey = isModifierKey; - CodeMirror.lookupKey = lookupKey; - CodeMirror.normalizeKeyMap = normalizeKeyMap; - CodeMirror.StringStream = StringStream; - CodeMirror.SharedTextMarker = SharedTextMarker; - CodeMirror.TextMarker = TextMarker; - CodeMirror.LineWidget = LineWidget; - CodeMirror.e_preventDefault = e_preventDefault; - CodeMirror.e_stopPropagation = e_stopPropagation; - CodeMirror.e_stop = e_stop; - CodeMirror.addClass = addClass; - CodeMirror.contains = contains; - CodeMirror.rmClass = rmClass; - CodeMirror.keyNames = keyNames; - } - - // EDITOR CONSTRUCTOR - - defineOptions(CodeMirror); - - addEditorMethods(CodeMirror); - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - { CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments)} - })(Doc.prototype[prop]); } } - - eventMixin(Doc); - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function(name/*, mode, …*/) { - if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } - defineMode.apply(this, arguments); - }; - - CodeMirror.defineMIME = defineMIME; - - // Minimal default mode. - CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); - CodeMirror.defineMIME("text/plain", "null"); - - // EXTENSIONS - - CodeMirror.defineExtension = function (name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; - }; - - CodeMirror.fromTextArea = fromTextArea; - - addLegacyProps(CodeMirror); - - CodeMirror.version = "5.52.2"; - - return CodeMirror; - -}))); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")) - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod) - else // Plain browser env - mod(CodeMirror) -})(function(CodeMirror) { - "use strict" - var Pos = CodeMirror.Pos - - function regexpFlags(regexp) { - var flags = regexp.flags - return flags != null ? flags : (regexp.ignoreCase ? "i" : "") - + (regexp.global ? "g" : "") - + (regexp.multiline ? "m" : "") - } - - function ensureFlags(regexp, flags) { - var current = regexpFlags(regexp), target = current - for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) - target += flags.charAt(i) - return current == target ? regexp : new RegExp(regexp.source, target) - } - - function maybeMultiline(regexp) { - return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source) - } - - function searchRegexpForward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g") - for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { - regexp.lastIndex = ch - var string = doc.getLine(line), match = regexp.exec(string) - if (match) - return {from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match: match} - } - } - - function searchRegexpForwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start) - - regexp = ensureFlags(regexp, "gm") - var string, chunk = 1 - for (var line = start.line, last = doc.lastLine(); line <= last;) { - // This grows the search buffer in exponentially-sized chunks - // between matches, so that nearby matches are fast and don't - // require concatenating the whole document (in case we're - // searching for something that has tons of matches), but at the - // same time, the amount of retries is limited. - for (var i = 0; i < chunk; i++) { - if (line > last) break - var curLine = doc.getLine(line++) - string = string == null ? curLine : string + "\n" + curLine - } - chunk = chunk * 2 - regexp.lastIndex = start.ch - var match = regexp.exec(string) - if (match) { - var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n") - var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length - return {from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, - inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match: match} - } - } - } - - function lastMatchIn(string, regexp, endMargin) { - var match, from = 0 - while (from <= string.length) { - regexp.lastIndex = from - var newMatch = regexp.exec(string) - if (!newMatch) break - var end = newMatch.index + newMatch[0].length - if (end > string.length - endMargin) break - if (!match || end > match.index + match[0].length) - match = newMatch - from = newMatch.index + 1 - } - return match - } - - function searchRegexpBackward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g") - for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { - var string = doc.getLine(line) - var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch) - if (match) - return {from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match: match} - } - } - - function searchRegexpBackwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start) - regexp = ensureFlags(regexp, "gm") - var string, chunkSize = 1, endMargin = doc.getLine(start.line).length - start.ch - for (var line = start.line, first = doc.firstLine(); line >= first;) { - for (var i = 0; i < chunkSize && line >= first; i++) { - var curLine = doc.getLine(line--) - string = string == null ? curLine : curLine + "\n" + string - } - chunkSize *= 2 - - var match = lastMatchIn(string, regexp, endMargin) - if (match) { - var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n") - var startLine = line + before.length, startCh = before[before.length - 1].length - return {from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, - inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match: match} - } - } - } - - var doFold, noFold - if (String.prototype.normalize) { - doFold = function(str) { return str.normalize("NFD").toLowerCase() } - noFold = function(str) { return str.normalize("NFD") } - } else { - doFold = function(str) { return str.toLowerCase() } - noFold = function(str) { return str } - } - - // Maps a position in a case-folded line back to a position in the original line - // (compensating for codepoints increasing in number during folding) - function adjustPos(orig, folded, pos, foldFunc) { - if (orig.length == folded.length) return pos - for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { - if (min == max) return min - var mid = (min + max) >> 1 - var len = foldFunc(orig.slice(0, mid)).length - if (len == pos) return mid - else if (len > pos) max = mid - else min = mid + 1 - } - } - - function searchStringForward(doc, query, start, caseFold) { - // Empty string would match anything and never progress, so we - // define it to match nothing instead. - if (!query.length) return null - var fold = caseFold ? doFold : noFold - var lines = fold(query).split(/\r|\n\r?/) - - search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { - var orig = doc.getLine(line).slice(ch), string = fold(orig) - if (lines.length == 1) { - var found = string.indexOf(lines[0]) - if (found == -1) continue search - var start = adjustPos(orig, string, found, fold) + ch - return {from: Pos(line, adjustPos(orig, string, found, fold) + ch), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)} - } else { - var cutFrom = string.length - lines[0].length - if (string.slice(cutFrom) != lines[0]) continue search - for (var i = 1; i < lines.length - 1; i++) - if (fold(doc.getLine(line + i)) != lines[i]) continue search - var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1] - if (endString.slice(0, lastLine.length) != lastLine) continue search - return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), - to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))} - } - } - } - - function searchStringBackward(doc, query, start, caseFold) { - if (!query.length) return null - var fold = caseFold ? doFold : noFold - var lines = fold(query).split(/\r|\n\r?/) - - search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { - var orig = doc.getLine(line) - if (ch > -1) orig = orig.slice(0, ch) - var string = fold(orig) - if (lines.length == 1) { - var found = string.lastIndexOf(lines[0]) - if (found == -1) continue search - return {from: Pos(line, adjustPos(orig, string, found, fold)), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))} - } else { - var lastLine = lines[lines.length - 1] - if (string.slice(0, lastLine.length) != lastLine) continue search - for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) - if (fold(doc.getLine(start + i)) != lines[i]) continue search - var top = doc.getLine(line + 1 - lines.length), topString = fold(top) - if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search - return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), - to: Pos(line, adjustPos(orig, string, lastLine.length, fold))} - } - } - } - - function SearchCursor(doc, query, pos, options) { - this.atOccurrence = false - this.doc = doc - pos = pos ? doc.clipPos(pos) : Pos(0, 0) - this.pos = {from: pos, to: pos} - - var caseFold - if (typeof options == "object") { - caseFold = options.caseFold - } else { // Backwards compat for when caseFold was the 4th argument - caseFold = options - options = null - } - - if (typeof query == "string") { - if (caseFold == null) caseFold = false - this.matches = function(reverse, pos) { - return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold) - } - } else { - query = ensureFlags(query, "gm") - if (!options || options.multiline !== false) - this.matches = function(reverse, pos) { - return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos) - } - else - this.matches = function(reverse, pos) { - return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos) - } - } - } - - SearchCursor.prototype = { - findNext: function() {return this.find(false)}, - findPrevious: function() {return this.find(true)}, - - find: function(reverse) { - var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to)) - - // Implements weird auto-growing behavior on null-matches for - // backwards-compatiblity with the vim code (unfortunately) - while (result && CodeMirror.cmpPos(result.from, result.to) == 0) { - if (reverse) { - if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1) - else if (result.from.line == this.doc.firstLine()) result = null - else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1))) - } else { - if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1) - else if (result.to.line == this.doc.lastLine()) result = null - else result = this.matches(reverse, Pos(result.to.line + 1, 0)) - } - } - - if (result) { - this.pos = result - this.atOccurrence = true - return this.pos.match || true - } else { - var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0) - this.pos = {from: end, to: end} - return this.atOccurrence = false - } - }, - - from: function() {if (this.atOccurrence) return this.pos.from}, - to: function() {if (this.atOccurrence) return this.pos.to}, - - replace: function(newText, origin) { - if (!this.atOccurrence) return - var lines = CodeMirror.splitLines(newText) - this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin) - this.pos.to = Pos(this.pos.from.line + lines.length - 1, - lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)) - } - } - - CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold) - }) - CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold) - }) - - CodeMirror.defineExtension("selectMatches", function(query, caseFold) { - var ranges = [] - var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold) - while (cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break - ranges.push({anchor: cur.from(), head: cur.to()}) - } - if (ranges.length) - this.setSelections(ranges, 0) - }) -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// Highlighting text that matches the selection -// -// Defines an option highlightSelectionMatches, which, when enabled, -// will style strings that match the selection throughout the -// document. -// -// The option can be set to true to simply enable it, or to a -// {minChars, style, wordsOnly, showToken, delay} object to explicitly -// configure it. minChars is the minimum amount of characters that should be -// selected for the behavior to occur, and style is the token style to -// apply to the matches. This will be prefixed by "cm-" to create an -// actual CSS class name. If wordsOnly is enabled, the matches will be -// highlighted only if the selected text is a word. showToken, when enabled, -// will cause the current token to be highlighted when nothing is selected. -// delay is used to specify how much time to wait, in milliseconds, before -// highlighting the matches. If annotateScrollbar is enabled, the occurences -// will be highlighted on the scrollbar via the matchesonscrollbar addon. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror"), require("./matchesonscrollbar")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror", "./matchesonscrollbar"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - var defaults = { - style: "matchhighlight", - minChars: 2, - delay: 100, - wordsOnly: false, - annotateScrollbar: false, - showToken: false, - trim: true - } - - function State(options) { - this.options = {} - for (var name in defaults) - this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name] - this.overlay = this.timeout = null; - this.matchesonscroll = null; - this.active = false; - } - - CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) { - removeOverlay(cm); - clearTimeout(cm.state.matchHighlighter.timeout); - cm.state.matchHighlighter = null; - cm.off("cursorActivity", cursorActivity); - cm.off("focus", onFocus) - } - if (val) { - var state = cm.state.matchHighlighter = new State(val); - if (cm.hasFocus()) { - state.active = true - highlightMatches(cm) - } else { - cm.on("focus", onFocus) - } - cm.on("cursorActivity", cursorActivity); - } - }); - - function cursorActivity(cm) { - var state = cm.state.matchHighlighter; - if (state.active || cm.hasFocus()) scheduleHighlight(cm, state) - } - - function onFocus(cm) { - var state = cm.state.matchHighlighter - if (!state.active) { - state.active = true - scheduleHighlight(cm, state) - } - } - - function scheduleHighlight(cm, state) { - clearTimeout(state.timeout); - state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay); - } - - function addOverlay(cm, query, hasBoundary, style) { - var state = cm.state.matchHighlighter; - cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style)); - if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) { - var searchFor = hasBoundary ? new RegExp("\\b" + query.replace(/[\\\[.+*?(){|^$]/g, "\\$&") + "\\b") : query; - state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false, - {className: "CodeMirror-selection-highlight-scrollbar"}); - } - } - - function removeOverlay(cm) { - var state = cm.state.matchHighlighter; - if (state.overlay) { - cm.removeOverlay(state.overlay); - state.overlay = null; - if (state.matchesonscroll) { - state.matchesonscroll.clear(); - state.matchesonscroll = null; - } - } - } - - function highlightMatches(cm) { - cm.operation(function() { - var state = cm.state.matchHighlighter; - removeOverlay(cm); - if (!cm.somethingSelected() && state.options.showToken) { - var re = state.options.showToken === true ? /[\w$]/ : state.options.showToken; - var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start; - while (start && re.test(line.charAt(start - 1))) --start; - while (end < line.length && re.test(line.charAt(end))) ++end; - if (start < end) - addOverlay(cm, line.slice(start, end), re, state.options.style); - return; - } - var from = cm.getCursor("from"), to = cm.getCursor("to"); - if (from.line != to.line) return; - if (state.options.wordsOnly && !isWord(cm, from, to)) return; - var selection = cm.getRange(from, to) - if (state.options.trim) selection = selection.replace(/^\s+|\s+$/g, "") - if (selection.length >= state.options.minChars) - addOverlay(cm, selection, false, state.options.style); - }); - } - - function isWord(cm, from, to) { - var str = cm.getRange(from, to); - if (str.match(/^\w+$/) !== null) { - if (from.ch > 0) { - var pos = {line: from.line, ch: from.ch - 1}; - var chr = cm.getRange(pos, from); - if (chr.match(/\W/) === null) return false; - } - if (to.ch < cm.getLine(from.line).length) { - var pos = {line: to.line, ch: to.ch + 1}; - var chr = cm.getRange(to, pos); - if (chr.match(/\W/) === null) return false; - } - return true; - } else return false; - } - - function boundariesAround(stream, re) { - return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) && - (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos))); - } - - function makeOverlay(query, hasBoundary, style) { - return {token: function(stream) { - if (stream.match(query) && - (!hasBoundary || boundariesAround(stream, hasBoundary))) - return style; - stream.next(); - stream.skipTo(query.charAt(0)) || stream.skipToEnd(); - }}; - } -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror"), require("./searchcursor"), require("../scroll/annotatescrollbar")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror", "./searchcursor", "../scroll/annotatescrollbar"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineExtension("showMatchesOnScrollbar", function(query, caseFold, options) { - if (typeof options == "string") options = {className: options}; - if (!options) options = {}; - return new SearchAnnotation(this, query, caseFold, options); - }); - - function SearchAnnotation(cm, query, caseFold, options) { - this.cm = cm; - this.options = options; - var annotateOptions = {listenForChanges: false}; - for (var prop in options) annotateOptions[prop] = options[prop]; - if (!annotateOptions.className) annotateOptions.className = "CodeMirror-search-match"; - this.annotation = cm.annotateScrollbar(annotateOptions); - this.query = query; - this.caseFold = caseFold; - this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1}; - this.matches = []; - this.update = null; - - this.findMatches(); - this.annotation.update(this.matches); - - var self = this; - cm.on("change", this.changeHandler = function(_cm, change) { self.onChange(change); }); - } - - var MAX_MATCHES = 1000; - - SearchAnnotation.prototype.findMatches = function() { - if (!this.gap) return; - for (var i = 0; i < this.matches.length; i++) { - var match = this.matches[i]; - if (match.from.line >= this.gap.to) break; - if (match.to.line >= this.gap.from) this.matches.splice(i--, 1); - } - var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), {caseFold: this.caseFold, multiline: this.options.multiline}); - var maxMatches = this.options && this.options.maxMatches || MAX_MATCHES; - while (cursor.findNext()) { - var match = {from: cursor.from(), to: cursor.to()}; - if (match.from.line >= this.gap.to) break; - this.matches.splice(i++, 0, match); - if (this.matches.length > maxMatches) break; - } - this.gap = null; - }; - - function offsetLine(line, changeStart, sizeChange) { - if (line <= changeStart) return line; - return Math.max(changeStart, line + sizeChange); - } - - SearchAnnotation.prototype.onChange = function(change) { - var startLine = change.from.line; - var endLine = CodeMirror.changeEnd(change).line; - var sizeChange = endLine - change.to.line; - if (this.gap) { - this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line); - this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line); - } else { - this.gap = {from: change.from.line, to: endLine + 1}; - } - - if (sizeChange) for (var i = 0; i < this.matches.length; i++) { - var match = this.matches[i]; - var newFrom = offsetLine(match.from.line, startLine, sizeChange); - if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch); - var newTo = offsetLine(match.to.line, startLine, sizeChange); - if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch); - } - clearTimeout(this.update); - var self = this; - this.update = setTimeout(function() { self.updateAfterChange(); }, 250); - }; - - SearchAnnotation.prototype.updateAfterChange = function() { - this.findMatches(); - this.annotation.update(this.matches); - }; - - SearchAnnotation.prototype.clear = function() { - this.cm.off("change", this.changeHandler); - this.annotation.clear(); - }; -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - var defaults = { - pairs: "()[]{}''\"\"", - closeBefore: ")]}'\":;>", - triples: "", - explode: "[]{}" - }; - - var Pos = CodeMirror.Pos; - - CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.removeKeyMap(keyMap); - cm.state.closeBrackets = null; - } - if (val) { - ensureBound(getOption(val, "pairs")) - cm.state.closeBrackets = val; - cm.addKeyMap(keyMap); - } - }); - - function getOption(conf, name) { - if (name == "pairs" && typeof conf == "string") return conf; - if (typeof conf == "object" && conf[name] != null) return conf[name]; - return defaults[name]; - } - - var keyMap = {Backspace: handleBackspace, Enter: handleEnter}; - function ensureBound(chars) { - for (var i = 0; i < chars.length; i++) { - var ch = chars.charAt(i), key = "'" + ch + "'" - if (!keyMap[key]) keyMap[key] = handler(ch) - } - } - ensureBound(defaults.pairs + "`") - - function handler(ch) { - return function(cm) { return handleChar(cm, ch); }; - } - - function getConfig(cm) { - var deflt = cm.state.closeBrackets; - if (!deflt || deflt.override) return deflt; - var mode = cm.getModeAt(cm.getCursor()); - return mode.closeBrackets || deflt; - } - - function handleBackspace(cm) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - - var pairs = getOption(conf, "pairs"); - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - for (var i = ranges.length - 1; i >= 0; i--) { - var cur = ranges[i].head; - cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); - } - } - - function handleEnter(cm) { - var conf = getConfig(cm); - var explode = conf && getOption(conf, "explode"); - if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; - - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - cm.operation(function() { - var linesep = cm.lineSeparator() || "\n"; - cm.replaceSelection(linesep + linesep, null); - cm.execCommand("goCharLeft"); - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var line = ranges[i].head.line; - cm.indentLine(line, null, true); - cm.indentLine(line + 1, null, true); - } - }); - } - - function contractSelection(sel) { - var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; - return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), - head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))}; - } - - function handleChar(cm, ch) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - - var pairs = getOption(conf, "pairs"); - var pos = pairs.indexOf(ch); - if (pos == -1) return CodeMirror.Pass; - - var closeBefore = getOption(conf,"closeBefore"); - - var triples = getOption(conf, "triples"); - - var identical = pairs.charAt(pos + 1) == ch; - var ranges = cm.listSelections(); - var opening = pos % 2 == 0; - - var type; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], cur = range.head, curType; - var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); - if (opening && !range.empty()) { - curType = "surround"; - } else if ((identical || !opening) && next == ch) { - if (identical && stringStartsAfter(cm, cur)) - curType = "both"; - else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) - curType = "skipThree"; - else - curType = "skip"; - } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && - cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { - if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; - curType = "addFour"; - } else if (identical) { - var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur) - if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both"; - else return CodeMirror.Pass; - } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { - curType = "both"; - } else { - return CodeMirror.Pass; - } - if (!type) type = curType; - else if (type != curType) return CodeMirror.Pass; - } - - var left = pos % 2 ? pairs.charAt(pos - 1) : ch; - var right = pos % 2 ? ch : pairs.charAt(pos + 1); - cm.operation(function() { - if (type == "skip") { - cm.execCommand("goCharRight"); - } else if (type == "skipThree") { - for (var i = 0; i < 3; i++) - cm.execCommand("goCharRight"); - } else if (type == "surround") { - var sels = cm.getSelections(); - for (var i = 0; i < sels.length; i++) - sels[i] = left + sels[i] + right; - cm.replaceSelections(sels, "around"); - sels = cm.listSelections().slice(); - for (var i = 0; i < sels.length; i++) - sels[i] = contractSelection(sels[i]); - cm.setSelections(sels); - } else if (type == "both") { - cm.replaceSelection(left + right, null); - cm.triggerElectric(left + right); - cm.execCommand("goCharLeft"); - } else if (type == "addFour") { - cm.replaceSelection(left + left + left + left, "before"); - cm.execCommand("goCharRight"); - } - }); - } - - function charsAround(cm, pos) { - var str = cm.getRange(Pos(pos.line, pos.ch - 1), - Pos(pos.line, pos.ch + 1)); - return str.length == 2 ? str : null; - } - - function stringStartsAfter(cm, pos) { - var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) - return /\bstring/.test(token.type) && token.start == pos.ch && - (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))) - } -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && - (document.documentMode == null || document.documentMode < 8); - - var Pos = CodeMirror.Pos; - - var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"}; - - function bracketRegex(config) { - return config && config.bracketRegex || /[(){}[\]]/ - } - - function findMatchingBracket(cm, where, config) { - var line = cm.getLineHandle(where.line), pos = where.ch - 1; - var afterCursor = config && config.afterCursor - if (afterCursor == null) - afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className) - var re = bracketRegex(config) - - // A cursor is defined as between two characters, but in in vim command mode - // (i.e. not insert mode), the cursor is visually represented as a - // highlighted box on top of the 2nd character. Otherwise, we allow matches - // from before or after the cursor. - var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) || - re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (config && config.strict && (dir > 0) != (pos == where.ch)) return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - - var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config); - if (found == null) return null; - return {from: Pos(where.line, pos), to: found && found.pos, - match: found && found.ch == match.charAt(0), forward: dir > 0}; - } - - // bracketRegex is used to specify which type of bracket to scan - // should be a regexp, e.g. /[[\]]/ - // - // Note: If "where" is on an open bracket, then this bracket is ignored. - // - // Returns false when no bracket was found, null when it reached - // maxScanLines and gave up - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = (config && config.maxScanLineLength) || 10000; - var maxScanLines = (config && config.maxScanLines) || 1000; - - var stack = []; - var re = bracketRegex(config) - var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) - : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) { - var match = matching[ch]; - if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch); - else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch}; - else stack.pop(); - } - } - } - return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; - } - - function matchBrackets(cm, autoclear, config) { - // Disable brace matching in long lines, since it'll cause hugely slow updates - var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; - var marks = [], ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); - if (match && cm.getLine(match.from.line).length <= maxHighlightLen) { - var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style})); - if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) - marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style})); - } - } - - if (marks.length) { - // Kludge to work around the IE bug from issue #1193, where text - // input stops going to the textare whever this fires. - if (ie_lt8 && cm.state.focused) cm.focus(); - - var clear = function() { - cm.operation(function() { - for (var i = 0; i < marks.length; i++) marks[i].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800); - else return clear; - } - } - - function doMatchBrackets(cm) { - cm.operation(function() { - if (cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); - }); - } - - CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.off("cursorActivity", doMatchBrackets); - if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - } - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - } - }); - - CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); - CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){ - // Backwards-compatibility kludge - if (oldConfig || typeof config == "boolean") { - if (!oldConfig) { - config = config ? {strict: true} : null - } else { - oldConfig.strict = config - config = oldConfig - } - } - return findMatchingBracket(this, pos, config) - }); - CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){ - return scanForBracket(this, pos, dir, style, config); - }); -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - function Bar(cls, orientation, scroll) { - this.orientation = orientation; - this.scroll = scroll; - this.screen = this.total = this.size = 1; - this.pos = 0; - - this.node = document.createElement("div"); - this.node.className = cls + "-" + orientation; - this.inner = this.node.appendChild(document.createElement("div")); - - var self = this; - CodeMirror.on(this.inner, "mousedown", function(e) { - if (e.which != 1) return; - CodeMirror.e_preventDefault(e); - var axis = self.orientation == "horizontal" ? "pageX" : "pageY"; - var start = e[axis], startpos = self.pos; - function done() { - CodeMirror.off(document, "mousemove", move); - CodeMirror.off(document, "mouseup", done); - } - function move(e) { - if (e.which != 1) return done(); - self.moveTo(startpos + (e[axis] - start) * (self.total / self.size)); - } - CodeMirror.on(document, "mousemove", move); - CodeMirror.on(document, "mouseup", done); - }); - - CodeMirror.on(this.node, "click", function(e) { - CodeMirror.e_preventDefault(e); - var innerBox = self.inner.getBoundingClientRect(), where; - if (self.orientation == "horizontal") - where = e.clientX < innerBox.left ? -1 : e.clientX > innerBox.right ? 1 : 0; - else - where = e.clientY < innerBox.top ? -1 : e.clientY > innerBox.bottom ? 1 : 0; - self.moveTo(self.pos + where * self.screen); - }); - - function onWheel(e) { - var moved = CodeMirror.wheelEventPixels(e)[self.orientation == "horizontal" ? "x" : "y"]; - var oldPos = self.pos; - self.moveTo(self.pos + moved); - if (self.pos != oldPos) CodeMirror.e_preventDefault(e); - } - CodeMirror.on(this.node, "mousewheel", onWheel); - CodeMirror.on(this.node, "DOMMouseScroll", onWheel); - } - - Bar.prototype.setPos = function(pos, force) { - if (pos < 0) pos = 0; - if (pos > this.total - this.screen) pos = this.total - this.screen; - if (!force && pos == this.pos) return false; - this.pos = pos; - this.inner.style[this.orientation == "horizontal" ? "left" : "top"] = - (pos * (this.size / this.total)) + "px"; - return true - }; - - Bar.prototype.moveTo = function(pos) { - if (this.setPos(pos)) this.scroll(pos, this.orientation); - } - - var minButtonSize = 10; - - Bar.prototype.update = function(scrollSize, clientSize, barSize) { - var sizeChanged = this.screen != clientSize || this.total != scrollSize || this.size != barSize - if (sizeChanged) { - this.screen = clientSize; - this.total = scrollSize; - this.size = barSize; - } - - var buttonSize = this.screen * (this.size / this.total); - if (buttonSize < minButtonSize) { - this.size -= minButtonSize - buttonSize; - buttonSize = minButtonSize; - } - this.inner.style[this.orientation == "horizontal" ? "width" : "height"] = - buttonSize + "px"; - this.setPos(this.pos, sizeChanged); - }; - - function SimpleScrollbars(cls, place, scroll) { - this.addClass = cls; - this.horiz = new Bar(cls, "horizontal", scroll); - place(this.horiz.node); - this.vert = new Bar(cls, "vertical", scroll); - place(this.vert.node); - this.width = null; - } - - SimpleScrollbars.prototype.update = function(measure) { - if (this.width == null) { - var style = window.getComputedStyle ? window.getComputedStyle(this.horiz.node) : this.horiz.node.currentStyle; - if (style) this.width = parseInt(style.height); - } - var width = this.width || 0; - - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - this.vert.node.style.display = needsV ? "block" : "none"; - this.horiz.node.style.display = needsH ? "block" : "none"; - - if (needsV) { - this.vert.update(measure.scrollHeight, measure.clientHeight, - measure.viewHeight - (needsH ? width : 0)); - this.vert.node.style.bottom = needsH ? width + "px" : "0"; - } - if (needsH) { - this.horiz.update(measure.scrollWidth, measure.clientWidth, - measure.viewWidth - (needsV ? width : 0) - measure.barLeft); - this.horiz.node.style.right = needsV ? width + "px" : "0"; - this.horiz.node.style.left = measure.barLeft + "px"; - } - - return {right: needsV ? width : 0, bottom: needsH ? width : 0}; - }; - - SimpleScrollbars.prototype.setScrollTop = function(pos) { - this.vert.setPos(pos); - }; - - SimpleScrollbars.prototype.setScrollLeft = function(pos) { - this.horiz.setPos(pos); - }; - - SimpleScrollbars.prototype.clear = function() { - var parent = this.horiz.node.parentNode; - parent.removeChild(this.horiz.node); - parent.removeChild(this.vert.node); - }; - - CodeMirror.scrollbarModel.simple = function(place, scroll) { - return new SimpleScrollbars("CodeMirror-simplescroll", place, scroll); - }; - CodeMirror.scrollbarModel.overlay = function(place, scroll) { - return new SimpleScrollbars("CodeMirror-overlayscroll", place, scroll); - }; -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineExtension("annotateScrollbar", function(options) { - if (typeof options == "string") options = {className: options}; - return new Annotation(this, options); - }); - - CodeMirror.defineOption("scrollButtonHeight", 0); - - function Annotation(cm, options) { - this.cm = cm; - this.options = options; - this.buttonHeight = options.scrollButtonHeight || cm.getOption("scrollButtonHeight"); - this.annotations = []; - this.doRedraw = this.doUpdate = null; - this.div = cm.getWrapperElement().appendChild(document.createElement("div")); - this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none"; - this.computeScale(); - - function scheduleRedraw(delay) { - clearTimeout(self.doRedraw); - self.doRedraw = setTimeout(function() { self.redraw(); }, delay); - } - - var self = this; - cm.on("refresh", this.resizeHandler = function() { - clearTimeout(self.doUpdate); - self.doUpdate = setTimeout(function() { - if (self.computeScale()) scheduleRedraw(20); - }, 100); - }); - cm.on("markerAdded", this.resizeHandler); - cm.on("markerCleared", this.resizeHandler); - if (options.listenForChanges !== false) - cm.on("changes", this.changeHandler = function() { - scheduleRedraw(250); - }); - } - - Annotation.prototype.computeScale = function() { - var cm = this.cm; - var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) / - cm.getScrollerElement().scrollHeight - if (hScale != this.hScale) { - this.hScale = hScale; - return true; - } - }; - - Annotation.prototype.update = function(annotations) { - this.annotations = annotations; - this.redraw(); - }; - - Annotation.prototype.redraw = function(compute) { - if (compute !== false) this.computeScale(); - var cm = this.cm, hScale = this.hScale; - - var frag = document.createDocumentFragment(), anns = this.annotations; - - var wrapping = cm.getOption("lineWrapping"); - var singleLineH = wrapping && cm.defaultTextHeight() * 1.5; - var curLine = null, curLineObj = null; - function getY(pos, top) { - if (curLine != pos.line) { - curLine = pos.line; - curLineObj = cm.getLineHandle(curLine); - } - if ((curLineObj.widgets && curLineObj.widgets.length) || - (wrapping && curLineObj.height > singleLineH)) - return cm.charCoords(pos, "local")[top ? "top" : "bottom"]; - var topY = cm.heightAtLine(curLineObj, "local"); - return topY + (top ? 0 : curLineObj.height); - } - - var lastLine = cm.lastLine() - if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) { - var ann = anns[i]; - if (ann.to.line > lastLine) continue; - var top = nextTop || getY(ann.from, true) * hScale; - var bottom = getY(ann.to, false) * hScale; - while (i < anns.length - 1) { - if (anns[i + 1].to.line > lastLine) break; - nextTop = getY(anns[i + 1].from, true) * hScale; - if (nextTop > bottom + .9) break; - ann = anns[++i]; - bottom = getY(ann.to, false) * hScale; - } - if (bottom == top) continue; - var height = Math.max(bottom - top, 3); - - var elt = frag.appendChild(document.createElement("div")); - elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: " - + (top + this.buttonHeight) + "px; height: " + height + "px"; - elt.className = this.options.className; - if (ann.id) { - elt.setAttribute("annotation-id", ann.id); - } - } - this.div.textContent = ""; - this.div.appendChild(frag); - }; - - Annotation.prototype.clear = function() { - this.cm.off("refresh", this.resizeHandler); - this.cm.off("markerAdded", this.resizeHandler); - this.cm.off("markerCleared", this.resizeHandler); - if (this.changeHandler) this.cm.off("changes", this.changeHandler); - this.div.parentNode.removeChild(this.div); - }; -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - var WRAP_CLASS = "CodeMirror-activeline"; - var BACK_CLASS = "CodeMirror-activeline-background"; - var GUTT_CLASS = "CodeMirror-activeline-gutter"; - - CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) { - var prev = old == CodeMirror.Init ? false : old; - if (val == prev) return - if (prev) { - cm.off("beforeSelectionChange", selectionChange); - clearActiveLines(cm); - delete cm.state.activeLines; - } - if (val) { - cm.state.activeLines = []; - updateActiveLines(cm, cm.listSelections()); - cm.on("beforeSelectionChange", selectionChange); - } - }); - - function clearActiveLines(cm) { - for (var i = 0; i < cm.state.activeLines.length; i++) { - cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS); - cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS); - cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS); - } - } - - function sameArray(a, b) { - if (a.length != b.length) return false; - for (var i = 0; i < a.length; i++) - if (a[i] != b[i]) return false; - return true; - } - - function updateActiveLines(cm, ranges) { - var active = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var option = cm.getOption("styleActiveLine"); - if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty()) - continue - var line = cm.getLineHandleVisualStart(range.head.line); - if (active[active.length - 1] != line) active.push(line); - } - if (sameArray(cm.state.activeLines, active)) return; - cm.operation(function() { - clearActiveLines(cm); - for (var i = 0; i < active.length; i++) { - cm.addLineClass(active[i], "wrap", WRAP_CLASS); - cm.addLineClass(active[i], "background", BACK_CLASS); - cm.addLineClass(active[i], "gutter", GUTT_CLASS); - } - cm.state.activeLines = active; - }); - } - - function selectionChange(cm, sel) { - updateActiveLines(cm, sel.ranges); - } -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineOption("fullScreen", false, function(cm, val, old) { - if (old == CodeMirror.Init) old = false; - if (!old == !val) return; - if (val) setFullscreen(cm); - else setNormal(cm); - }); - - function setFullscreen(cm) { - var wrap = cm.getWrapperElement(); - cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, - width: wrap.style.width, height: wrap.style.height}; - wrap.style.width = ""; - wrap.style.height = "auto"; - wrap.className += " CodeMirror-fullscreen"; - document.documentElement.style.overflow = "hidden"; - cm.refresh(); - } - - function setNormal(cm) { - var wrap = cm.getWrapperElement(); - wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, ""); - document.documentElement.style.overflow = ""; - var info = cm.state.fullScreenRestore; - wrap.style.width = info.width; wrap.style.height = info.height; - window.scrollTo(info.scrollLeft, info.scrollTop); - cm.refresh(); - } -}); -CodeMirror.defineMode("glsl", function(config, parserConfig) { - var indentUnit = config.indentUnit, - keywords = parserConfig.keywords || {}, - builtins = parserConfig.builtins || {}, - blockKeywords = parserConfig.blockKeywords || {}, - atoms = parserConfig.atoms || {}, - hooks = parserConfig.hooks || {}, - multiLineStrings = parserConfig.multiLineStrings; - var isOperatorChar = /[+\-*&%=<>!?|\/]/; - - var curPunc; - - function tokenBase(stream, state) { - var ch = stream.next(); - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } - if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - curPunc = ch; - return "bracket"; - } - if (/\d/.test(ch)) { - stream.eatWhile(/[\w\.]/); - return "number"; - } - if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } - if (stream.eat("/")) { - stream.skipToEnd(); - return "comment"; - } - } - if (isOperatorChar.test(ch)) { - stream.eatWhile(isOperatorChar); - return "operator"; - } - stream.eatWhile(/[\w\$_]/); - var cur = stream.current(); - if (keywords.propertyIsEnumerable(cur)) { - if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; - return "keyword"; - } - if (builtins.propertyIsEnumerable(cur)) { - return "builtin"; - } - if (atoms.propertyIsEnumerable(cur)) return "atom"; - return "word"; - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next, end = false; - while ((next = stream.next()) != null) { - if (next == quote && !escaped) {end = true; break;} - escaped = !escaped && next == "\\"; - } - if (end || !(escaped || multiLineStrings)) - state.tokenize = tokenBase; - return "string"; - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return "comment"; - } - - function Context(indented, column, type, align, prev) { - this.indented = indented; - this.column = column; - this.type = type; - this.align = align; - this.prev = prev; - } - function pushContext(state, col, type) { - return state.context = new Context(state.indented, col, type, null, state.context); - } - function popContext(state) { - var t = state.context.type; - if (t == ")" || t == "]" || t == "}") - state.indented = state.context.indented; - return state.context = state.context.prev; - } - - // Interface - - return { - startState: function(basecolumn) { - return { - tokenize: null, - context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), - indented: 0, - startOfLine: true - }; - }, - - token: function(stream, state) { - var ctx = state.context; - if (stream.sol()) { - if (ctx.align == null) ctx.align = false; - state.indented = stream.indentation(); - state.startOfLine = true; - } - if (stream.eatSpace()) return null; - curPunc = null; - var style = (state.tokenize || tokenBase)(stream, state); - if (style == "comment" || style == "meta") return style; - if (ctx.align == null) ctx.align = true; - - if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); - else if (curPunc == "{") pushContext(state, stream.column(), "}"); - else if (curPunc == "[") pushContext(state, stream.column(), "]"); - else if (curPunc == "(") pushContext(state, stream.column(), ")"); - else if (curPunc == "}") { - while (ctx.type == "statement") ctx = popContext(state); - if (ctx.type == "}") ctx = popContext(state); - while (ctx.type == "statement") ctx = popContext(state); - } - else if (curPunc == ctx.type) popContext(state); - else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) - pushContext(state, stream.column(), "statement"); - state.startOfLine = false; - return style; - }, - - indent: function(state, textAfter) { - if (state.tokenize != tokenBase && state.tokenize != null) return 0; - var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type; - if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit); - else if (ctx.align) return ctx.column + (closing ? 0 : 1); - else return ctx.indented + (closing ? 0 : indentUnit); - }, - - electricChars: "{}" - }; -}); - -(function() { - function words(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } - var glslKeywords = "attribute const uniform varying break continue " + - "do for while if else in out inout float int void bool true false " + - "lowp mediump highp precision invariant discard return mat2 mat3 " + - "mat4 vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 sampler2D " + - "samplerCube struct gl_FragCoord gl_FragColor"; - var glslBuiltins = "radians degrees sin cos tan asin acos atan pow " + - "exp log exp2 log2 sqrt inversesqrt abs sign floor ceil fract mod " + - "min max clamp mix step smoothstep length distance dot cross " + - "normalize faceforward reflect refract matrixCompMult lessThan " + - "lessThanEqual greaterThan greaterThanEqual equal notEqual any all " + - "not dFdx dFdy fwidth texture2D texture2DProj texture2DLod " + - "texture2DProjLod textureCube textureCubeLod"; - - function cppHook(stream, state) { - if (!state.startOfLine) return false; - stream.skipToEnd(); - return "meta"; - } - - // C#-style strings where "" escapes a quote. - function tokenAtString(stream, state) { - var next; - while ((next = stream.next()) != null) { - if (next == '"' && !stream.eat('"')) { - state.tokenize = null; - break; - } - } - return "string"; - } - - CodeMirror.defineMIME("text/x-glsl", { - name: "glsl", - keywords: words(glslKeywords), - builtins: words(glslBuiltins), - blockKeywords: words("case do else for if switch while struct"), - atoms: words("null"), - hooks: {"#": cppHook} - }); -}());// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode("javascript", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - - // Tokenizer - - var keywords = function(){ - function kw(type) {return {type: type, style: "keyword"};} - var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); - var operator = kw("operator"), atom = {type: "atom", style: "atom"}; - - return { - "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, - "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, - "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), - "function": kw("function"), "catch": kw("catch"), - "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), - "in": operator, "typeof": operator, "instanceof": operator, - "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, - "this": kw("this"), "class": kw("class"), "super": kw("atom"), - "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, - "await": C - }; - }(); - - var isOperatorChar = /[+\-*&%=<>!?|~^@]/; - var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - - function readRegexp(stream) { - var escaped = false, next, inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true; - else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; - } - } - - // Used as scratch variables to communicate multiple values without - // consing up tons of objects. - var type, content; - function ret(tp, style, cont) { - type = tp; content = cont; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (expressionAllowed(stream, state, 1)) { - readRegexp(stream); - stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); - return ret("regexp", "string-2"); - } else { - stream.eat("="); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#") { - stream.skipToEnd(); - return ret("error", "error"); - } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) { - stream.skipToEnd() - return ret("comment", "comment") - } else if (isOperatorChar.test(ch)) { - if (ch != ">" || !state.lexical || state.lexical.type != ">") { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("=") - } else if (/[<>*+\-]/.test(ch)) { - stream.eat(ch) - if (ch == ">") stream.eat(ch) - } - } - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current() - if (state.lastType != ".") { - if (keywords.propertyIsEnumerable(word)) { - var kw = keywords[word] - return ret(kw.type, kw.style, word) - } - if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) - return ret("async", "keyword", word) - } - return ret("variable", "variable", word) - } - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next; - if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return ret("comment", "comment"); - } - - function tokenQuasi(stream, state) { - var escaped = false, next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - - var brackets = "([{}])"; - // This is a crude lookahead trick to try and notice that we're - // parsing the argument patterns for a fat-arrow function before we - // actually hit the arrow token. It only works if the arrow is on - // the same line as the arguments and there's no strange noise - // (comments) in between. Fallback is to only notice when we hit the - // arrow, and not declare the arguments as locals for the arrow - // body. - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - - if (isTS) { // Try to skip TypeScript return type declarations after the arguments - var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) - if (m) arrow = m.index - } - - var depth = 0, sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { ++pos; break; } - if (--depth == 0) { if (ch == "(") sawSomething = true; break; } - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/`]/.test(ch)) { - for (;; --pos) { - if (pos == 0) return - var next = stream.string.charAt(pos - 1) - if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } - } - } else if (sawSomething && !depth) { - ++pos; - break; - } - } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - - // Parser - - var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; - - function JSLexical(indented, column, type, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - - function inScope(state, varname) { - for (var v = state.localVars; v; v = v.next) - if (v.name == varname) return true; - for (var cx = state.context; cx; cx = cx.prev) { - for (var v = cx.vars; v; v = v.next) - if (v.name == varname) return true; - } - } - - function parseJS(state, style, type, content, stream) { - var cc = state.cc; - // Communicate our context to the combinators. - // (Less wasteful than consing up a hundred closures on every call.) - cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; - - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = true; - - while(true) { - var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; - if (combinator(type, content)) { - while(cc.length && cc[cc.length - 1].lex) - cc.pop()(); - if (cx.marked) return cx.marked; - if (type == "variable" && inScope(state, content)) return "variable-2"; - return style; - } - } - } - - // Combinator utils - - var cx = {state: null, column: null, marked: null, cc: null}; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - function inList(name, list) { - for (var v = list; v; v = v.next) if (v.name == name) return true - return false; - } - function register(varname) { - var state = cx.state; - cx.marked = "def"; - if (state.context) { - if (state.lexical.info == "var" && state.context && state.context.block) { - // FIXME function decls are also not block scoped - var newContext = registerVarScoped(varname, state.context) - if (newContext != null) { - state.context = newContext - return - } - } else if (!inList(varname, state.localVars)) { - state.localVars = new Var(varname, state.localVars) - return - } - } - // Fall through means this is global - if (parserConfig.globalVars && !inList(varname, state.globalVars)) - state.globalVars = new Var(varname, state.globalVars) - } - function registerVarScoped(varname, context) { - if (!context) { - return null - } else if (context.block) { - var inner = registerVarScoped(varname, context.prev) - if (!inner) return null - if (inner == context.prev) return context - return new Context(inner, context.vars, true) - } else if (inList(varname, context.vars)) { - return context - } else { - return new Context(context.prev, new Var(varname, context.vars), false) - } - } - - function isModifier(name) { - return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" - } - - // Combinators - - function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } - function Var(name, next) { this.name = name; this.next = next } - - var defaultVars = new Var("this", new Var("arguments", null)) - function pushcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, false) - cx.state.localVars = defaultVars - } - function pushblockcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, true) - cx.state.localVars = null - } - function popcontext() { - cx.state.localVars = cx.state.context.vars - cx.state.context = cx.state.context.prev - } - popcontext.lex = true - function pushlex(type, info) { - var result = function() { - var state = cx.state, indent = state.indented; - if (state.lexical.type == "stat") indent = state.lexical.indented; - else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) - indent = outer.indented; - state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); - }; - result.lex = true; - return result; - } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") - state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - - function expect(wanted) { - function exp(type) { - if (type == wanted) return cont(); - else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); - else return cont(exp); - }; - return exp; - } - - function statement(type, value) { - if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); - if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); - if (type == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); - if (type == "debugger") return cont(expect(";")); - if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); - if (type == ";") return cont(); - if (type == "if") { - if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) - cx.state.cc.pop()(); - return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); - } - if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); - if (type == "class" || (isTS && value == "interface")) { - cx.marked = "keyword" - return cont(pushlex("form", type == "class" ? type : value), className, poplex) - } - if (type == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword" - return cont(statement) - } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { - cx.marked = "keyword" - if (value == "enum") return cont(enumdef); - else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); - else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) - } else if (isTS && value == "namespace") { - cx.marked = "keyword" - return cont(pushlex("form"), expression, statement, poplex) - } else if (isTS && value == "abstract") { - cx.marked = "keyword" - return cont(statement) - } else { - return cont(pushlex("stat"), maybelabel); - } - } - if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, - block, poplex, poplex, popcontext); - if (type == "case") return cont(expression, expect(":")); - if (type == "default") return cont(expect(":")); - if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); - if (type == "export") return cont(pushlex("stat"), afterExport, poplex); - if (type == "import") return cont(pushlex("stat"), afterImport, poplex); - if (type == "async") return cont(statement) - if (value == "@") return cont(expression, statement) - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function maybeCatchBinding(type) { - if (type == "(") return cont(funarg, expect(")")) - } - function expression(type, value) { - return expressionInner(type, value, false); - } - function expressionNoComma(type, value) { - return expressionInner(type, value, true); - } - function parenExpr(type) { - if (type != "(") return pass() - return cont(pushlex(")"), maybeexpression, expect(")"), poplex) - } - function expressionInner(type, value, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); - else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); - } - - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); - if (type == "function") return cont(functiondef, maybeop); - if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } - if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); - if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); - if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); - if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type == "{") return contCommasep(objprop, "}", null, maybeop); - if (type == "quasi") return pass(quasi, maybeop); - if (type == "new") return cont(maybeTarget(noComma)); - if (type == "import") return cont(expression); - return cont(); - } - function maybeexpression(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - - function maybeoperatorComma(type, value) { - if (type == ",") return cont(maybeexpression); - return maybeoperatorNoComma(type, value, false); - } - function maybeoperatorNoComma(type, value, noComma) { - var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); - if (type == "operator") { - if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); - if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) - return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); - if (value == "?") return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type == "quasi") { return pass(quasi, me); } - if (type == ";") return; - if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); - if (type == ".") return cont(property, me); - if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); - if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } - if (type == "regexp") { - cx.state.lastType = cx.marked = "operator" - cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) - return cont(expr) - } - } - function quasi(type, value) { - if (type != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(expression, continueQuasi); - } - function continueQuasi(type) { - if (type == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); - } - } - function arrowBody(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expression); - } - function arrowBodyNoComma(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expressionNoComma); - } - function maybeTarget(noComma) { - return function(type) { - if (type == ".") return cont(noComma ? targetNoComma : target); - else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) - else return pass(noComma ? expressionNoComma : expression); - }; - } - function target(_, value) { - if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } - } - function targetNoComma(_, value) { - if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } - } - function maybelabel(type) { - if (type == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type) { - if (type == "variable") {cx.marked = "property"; return cont();} - } - function objprop(type, value) { - if (type == "async") { - cx.marked = "property"; - return cont(objprop); - } else if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(getterSetter); - var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params - if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) - cx.state.fatArrowAt = cx.stream.pos + m[0].length - return cont(afterprop); - } else if (type == "number" || type == "string") { - cx.marked = jsonldMode ? "property" : (cx.style + " property"); - return cont(afterprop); - } else if (type == "jsonld-keyword") { - return cont(afterprop); - } else if (isTS && isModifier(value)) { - cx.marked = "keyword" - return cont(objprop) - } else if (type == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } else if (type == ":") { - return pass(afterprop) - } - } - function getterSetter(type) { - if (type != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type) { - if (type == ":") return cont(expressionNoComma); - if (type == "(") return pass(functiondef); - } - function commasep(what, end, sep) { - function proceed(type, value) { - if (sep ? sep.indexOf(type) > -1 : type == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(function(type, value) { - if (type == end || value == end) return pass() - return pass(what) - }, proceed); - } - if (type == end || value == end) return cont(); - if (sep && sep.indexOf(";") > -1) return pass(what) - return cont(expect(end)); - } - return function(type, value) { - if (type == end || value == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) - cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type) { - if (type == "}") return cont(); - return pass(statement, block); - } - function maybetype(type, value) { - if (isTS) { - if (type == ":") return cont(typeexpr); - if (value == "?") return cont(maybetype); - } - } - function maybetypeOrIn(type, value) { - if (isTS && (type == ":" || value == "in")) return cont(typeexpr) - } - function mayberettype(type) { - if (isTS && type == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) - else return cont(typeexpr) - } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword" - return cont() - } - } - function typeexpr(type, value) { - if (value == "keyof" || value == "typeof" || value == "infer") { - cx.marked = "keyword" - return cont(value == "typeof" ? expressionNoComma : typeexpr) - } - if (type == "variable" || value == "void") { - cx.marked = "type" - return cont(afterType) - } - if (value == "|" || value == "&") return cont(typeexpr) - if (type == "string" || type == "number" || type == "atom") return cont(afterType); - if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) - if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) - if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) - if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) - } - function maybeReturnType(type) { - if (type == "=>") return cont(typeexpr) - } - function typeprop(type, value) { - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property" - return cont(typeprop) - } else if (value == "?" || type == "number" || type == "string") { - return cont(typeprop) - } else if (type == ":") { - return cont(typeexpr) - } else if (type == "[") { - return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) - } else if (type == "(") { - return pass(functiondecl, typeprop) - } - } - function typearg(type, value) { - if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) - if (type == ":") return cont(typeexpr) - if (type == "spread") return cont(typearg) - return pass(typeexpr) - } - function afterType(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) - if (value == "|" || type == "." || value == "&") return cont(typeexpr) - if (type == "[") return cont(typeexpr, expect("]"), afterType) - if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } - if (value == "?") return cont(typeexpr, expect(":"), typeexpr) - } - function maybeTypeArgs(_, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault) - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr) - } - function vardef(_, value) { - if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type, value) { - if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } - if (type == "variable") { register(value); return cont(); } - if (type == "spread") return cont(pattern); - if (type == "[") return contCommasep(eltpattern, "]"); - if (type == "{") return contCommasep(proppattern, "}"); - } - function proppattern(type, value) { - if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type == "variable") cx.marked = "property"; - if (type == "spread") return cont(pattern); - if (type == "}") return pass(); - if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); - return cont(expect(":"), pattern, maybeAssign); - } - function eltpattern() { - return pass(pattern, maybeAssign) - } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); - } - function vardefCont(type) { - if (type == ",") return cont(vardef); - } - function maybeelse(type, value) { - if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); - } - function forspec(type, value) { - if (value == "await") return cont(forspec); - if (type == "(") return cont(pushlex(")"), forspec1, poplex); - } - function forspec1(type) { - if (type == "var") return cont(vardef, forspec2); - if (type == "variable") return cont(forspec2); - return pass(forspec2) - } - function forspec2(type, value) { - if (type == ")") return cont() - if (type == ";") return cont(forspec2) - if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } - return pass(expression, forspec2) - } - function functiondef(type, value) { - if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} - if (type == "variable") {register(value); return cont(functiondef);} - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) - } - function functiondecl(type, value) { - if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} - if (type == "variable") {register(value); return cont(functiondecl);} - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) - } - function typename(type, value) { - if (type == "keyword" || type == "variable") { - cx.marked = "type" - return cont(typename) - } else if (value == "<") { - return cont(pushlex(">"), commasep(typeparam, ">"), poplex) - } - } - function funarg(type, value) { - if (value == "@") cont(expression, funarg) - if (type == "spread") return cont(funarg); - if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } - if (isTS && type == "this") return cont(maybetype, maybeAssign) - return pass(pattern, maybetype, maybeAssign); - } - function classExpression(type, value) { - // Class expressions may have an optional name. - if (type == "variable") return className(type, value); - return classNameAfter(type, value); - } - function className(type, value) { - if (type == "variable") {register(value); return cont(classNameAfter);} - } - function classNameAfter(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) - if (value == "extends" || value == "implements" || (isTS && type == ",")) { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); - } - if (type == "{") return cont(pushlex("}"), classBody, poplex); - } - function classBody(type, value) { - if (type == "async" || - (type == "variable" && - (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && - cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { - cx.marked = "keyword"; - return cont(classBody); - } - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(isTS ? classfield : functiondef, classBody); - } - if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody); - if (type == "[") - return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody) - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (isTS && type == "(") return pass(functiondecl, classBody) - if (type == ";" || type == ",") return cont(classBody); - if (type == "}") return cont(); - if (value == "@") return cont(expression, classBody) - } - function classfield(type, value) { - if (value == "?") return cont(classfield) - if (type == ":") return cont(typeexpr, maybeAssign) - if (value == "=") return cont(expressionNoComma) - var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" - return pass(isInterface ? functiondecl : functiondef) - } - function afterExport(type, value) { - if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } - if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } - if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); - return pass(statement); - } - function exportField(type, value) { - if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } - if (type == "variable") return pass(expressionNoComma, exportField); - } - function afterImport(type) { - if (type == "string") return cont(); - if (type == "(") return pass(expression); - return pass(importSpec, maybeMoreImports, maybeFrom); - } - function importSpec(type, value) { - if (type == "{") return contCommasep(importSpec, "}"); - if (type == "variable") register(value); - if (value == "*") cx.marked = "keyword"; - return cont(maybeAs); - } - function maybeMoreImports(type) { - if (type == ",") return cont(importSpec, maybeMoreImports) - } - function maybeAs(_type, value) { - if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } - } - function maybeFrom(_type, value) { - if (value == "from") { cx.marked = "keyword"; return cont(expression); } - } - function arrayLiteral(type) { - if (type == "]") return cont(); - return pass(commasep(expressionNoComma, "]")); - } - function enumdef() { - return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) - } - function enummember() { - return pass(pattern, maybeAssign); - } - - function isContinuedStatement(state, textAfter) { - return state.lastType == "operator" || state.lastType == "," || - isOperatorChar.test(textAfter.charAt(0)) || - /[,.]/.test(textAfter.charAt(0)); - } - - function expressionAllowed(stream, state, backUp) { - return state.tokenize == tokenBase && - /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || - (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) - } - - // Interface - - return { - startState: function(basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && new Context(null, null, false), - indented: basecolumn || 0 - }; - if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") - state.globalVars = parserConfig.globalVars; - return state; - }, - - token: function(stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; - return parseJS(state, style, type, content, stream); - }, - - indent: function(state, textAfter) { - if (state.tokenize == tokenComment) return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top - // Kludge to prevent 'maybelse' from blocking lexical scope pops - if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev; - else if (c != maybeelse) break; - } - while ((lexical.type == "stat" || lexical.type == "form") && - (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && - (top == maybeoperatorComma || top == maybeoperatorNoComma) && - !/^[,\.=+\-*:?[\(]/.test(textAfter)))) - lexical = lexical.prev; - if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") - lexical = lexical.prev; - var type = lexical.type, closing = firstChar == type; - - if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); - else if (type == "form" && firstChar == "{") return lexical.indented; - else if (type == "form") return lexical.indented + indentUnit; - else if (type == "stat") - return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); - else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) - return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); - else if (lexical.align) return lexical.column + (closing ? 0 : 1); - else return lexical.indented + (closing ? 0 : indentUnit); - }, - - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - blockCommentContinue: jsonMode ? null : " * ", - lineComment: jsonMode ? null : "//", - fold: "brace", - closeBrackets: "()[]{}''\"\"``", - - helperType: jsonMode ? "json" : "javascript", - jsonldMode: jsonldMode, - jsonMode: jsonMode, - - expressionAllowed: expressionAllowed, - - skipExpression: function(state) { - var top = state.cc[state.cc.length - 1] - if (top == expression || top == expressionNoComma) state.cc.pop() - } - }; -}); - -CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - -CodeMirror.defineMIME("text/javascript", "javascript"); -CodeMirror.defineMIME("text/ecmascript", "javascript"); -CodeMirror.defineMIME("application/javascript", "javascript"); -CodeMirror.defineMIME("application/x-javascript", "javascript"); -CodeMirror.defineMIME("application/ecmascript", "javascript"); -CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); -CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); -CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); -CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); -CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); - -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -function Context(indented, column, type, info, align, prev) { - this.indented = indented; - this.column = column; - this.type = type; - this.info = info; - this.align = align; - this.prev = prev; -} -function pushContext(state, col, type, info) { - var indent = state.indented; - if (state.context && state.context.type == "statement" && type != "statement") - indent = state.context.indented; - return state.context = new Context(indent, col, type, info, null, state.context); -} -function popContext(state) { - var t = state.context.type; - if (t == ")" || t == "]" || t == "}") - state.indented = state.context.indented; - return state.context = state.context.prev; -} - -function typeBefore(stream, state, pos) { - if (state.prevToken == "variable" || state.prevToken == "type") return true; - if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; - if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; -} - -function isTopScope(context) { - for (;;) { - if (!context || context.type == "top") return true; - if (context.type == "}" && context.prev.info != "namespace") return false; - context = context.prev; - } -} - -CodeMirror.defineMode("clike", function(config, parserConfig) { - var indentUnit = config.indentUnit, - statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, - dontAlignCalls = parserConfig.dontAlignCalls, - keywords = parserConfig.keywords || {}, - types = parserConfig.types || {}, - builtin = parserConfig.builtin || {}, - blockKeywords = parserConfig.blockKeywords || {}, - defKeywords = parserConfig.defKeywords || {}, - atoms = parserConfig.atoms || {}, - hooks = parserConfig.hooks || {}, - multiLineStrings = parserConfig.multiLineStrings, - indentStatements = parserConfig.indentStatements !== false, - indentSwitch = parserConfig.indentSwitch !== false, - namespaceSeparator = parserConfig.namespaceSeparator, - isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, - numberStart = parserConfig.numberStart || /[\d\.]/, - number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, - isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, - isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/, - // An optional function that takes a {string} token and returns true if it - // should be treated as a builtin. - isReservedIdentifier = parserConfig.isReservedIdentifier || false; - - var curPunc, isDefKeyword; - - function tokenBase(stream, state) { - var ch = stream.next(); - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } - if (isPunctuationChar.test(ch)) { - curPunc = ch; - return null; - } - if (numberStart.test(ch)) { - stream.backUp(1) - if (stream.match(number)) return "number" - stream.next() - } - if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } - if (stream.eat("/")) { - stream.skipToEnd(); - return "comment"; - } - } - if (isOperatorChar.test(ch)) { - while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} - return "operator"; - } - stream.eatWhile(isIdentifierChar); - if (namespaceSeparator) while (stream.match(namespaceSeparator)) - stream.eatWhile(isIdentifierChar); - - var cur = stream.current(); - if (contains(keywords, cur)) { - if (contains(blockKeywords, cur)) curPunc = "newstatement"; - if (contains(defKeywords, cur)) isDefKeyword = true; - return "keyword"; - } - if (contains(types, cur)) return "type"; - if (contains(builtin, cur) - || (isReservedIdentifier && isReservedIdentifier(cur))) { - if (contains(blockKeywords, cur)) curPunc = "newstatement"; - return "builtin"; - } - if (contains(atoms, cur)) return "atom"; - return "variable"; - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next, end = false; - while ((next = stream.next()) != null) { - if (next == quote && !escaped) {end = true; break;} - escaped = !escaped && next == "\\"; - } - if (end || !(escaped || multiLineStrings)) - state.tokenize = null; - return "string"; - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = null; - break; - } - maybeEnd = (ch == "*"); - } - return "comment"; - } - - function maybeEOL(stream, state) { - if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) - state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) - } - - // Interface - - return { - startState: function(basecolumn) { - return { - tokenize: null, - context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), - indented: 0, - startOfLine: true, - prevToken: null - }; - }, - - token: function(stream, state) { - var ctx = state.context; - if (stream.sol()) { - if (ctx.align == null) ctx.align = false; - state.indented = stream.indentation(); - state.startOfLine = true; - } - if (stream.eatSpace()) { maybeEOL(stream, state); return null; } - curPunc = isDefKeyword = null; - var style = (state.tokenize || tokenBase)(stream, state); - if (style == "comment" || style == "meta") return style; - if (ctx.align == null) ctx.align = true; - - if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) - while (state.context.type == "statement") popContext(state); - else if (curPunc == "{") pushContext(state, stream.column(), "}"); - else if (curPunc == "[") pushContext(state, stream.column(), "]"); - else if (curPunc == "(") pushContext(state, stream.column(), ")"); - else if (curPunc == "}") { - while (ctx.type == "statement") ctx = popContext(state); - if (ctx.type == "}") ctx = popContext(state); - while (ctx.type == "statement") ctx = popContext(state); - } - else if (curPunc == ctx.type) popContext(state); - else if (indentStatements && - (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || - (ctx.type == "statement" && curPunc == "newstatement"))) { - pushContext(state, stream.column(), "statement", stream.current()); - } - - if (style == "variable" && - ((state.prevToken == "def" || - (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && - isTopScope(state.context) && stream.match(/^\s*\(/, false))))) - style = "def"; - - if (hooks.token) { - var result = hooks.token(stream, state, style); - if (result !== undefined) style = result; - } - - if (style == "def" && parserConfig.styleDefs === false) style = "variable"; - - state.startOfLine = false; - state.prevToken = isDefKeyword ? "def" : style || curPunc; - maybeEOL(stream, state); - return style; - }, - - indent: function(state, textAfter) { - if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; - var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); - var closing = firstChar == ctx.type; - if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; - if (parserConfig.dontIndentStatements) - while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) - ctx = ctx.prev - if (hooks.indent) { - var hook = hooks.indent(state, ctx, textAfter, indentUnit); - if (typeof hook == "number") return hook - } - var switchBlock = ctx.prev && ctx.prev.info == "switch"; - if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { - while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev - return ctx.indented - } - if (ctx.type == "statement") - return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); - if (ctx.align && (!dontAlignCalls || ctx.type != ")")) - return ctx.column + (closing ? 0 : 1); - if (ctx.type == ")" && !closing) - return ctx.indented + statementIndentUnit; - - return ctx.indented + (closing ? 0 : indentUnit) + - (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); - }, - - electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, - blockCommentStart: "/*", - blockCommentEnd: "*/", - blockCommentContinue: " * ", - lineComment: "//", - fold: "brace" - }; -}); - - function words(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } - function contains(words, word) { - if (typeof words === "function") { - return words(word); - } else { - return words.propertyIsEnumerable(word); - } - } - var cKeywords = "auto if break case register continue return default do sizeof " + - "static else struct switch extern typedef union for goto while enum const " + - "volatile inline restrict asm fortran"; - - // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20. - var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch " + - "class compl concept constexpr const_cast decltype delete dynamic_cast " + - "explicit export final friend import module mutable namespace new noexcept " + - "not not_eq operator or or_eq override private protected public " + - "reinterpret_cast requires static_assert static_cast template this " + - "thread_local throw try typeid typename using virtual xor xor_eq"; - - var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy " + - "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " + - "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " + - "@public @package @private @protected @required @optional @try @catch @finally @import " + - "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"; - - var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION " + - " NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER " + - "NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION " + - "NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT" - - // Do not use this. Use the cTypes function below. This is global just to avoid - // excessive calls when cTypes is being called multiple times during a parse. - var basicCTypes = words("int long char short double float unsigned signed " + - "void bool"); - - // Do not use this. Use the objCTypes function below. This is global just to avoid - // excessive calls when objCTypes is being called multiple times during a parse. - var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL"); - - // Returns true if identifier is a "C" type. - // C type is defined as those that are reserved by the compiler (basicTypes), - // and those that end in _t (Reserved by POSIX for types) - // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html - function cTypes(identifier) { - return contains(basicCTypes, identifier) || /.+_t$/.test(identifier); - } - - // Returns true if identifier is a "Objective C" type. - function objCTypes(identifier) { - return cTypes(identifier) || contains(basicObjCTypes, identifier); - } - - var cBlockKeywords = "case do else for if switch while struct enum union"; - var cDefKeywords = "struct enum union"; - - function cppHook(stream, state) { - if (!state.startOfLine) return false - for (var ch, next = null; ch = stream.peek();) { - if (ch == "\\" && stream.match(/^.$/)) { - next = cppHook - break - } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { - break - } - stream.next() - } - state.tokenize = next - return "meta" - } - - function pointerHook(_stream, state) { - if (state.prevToken == "type") return "type"; - return false; - } - - // For C and C++ (and ObjC): identifiers starting with __ - // or _ followed by a capital letter are reserved for the compiler. - function cIsReservedIdentifier(token) { - if (!token || token.length < 2) return false; - if (token[0] != '_') return false; - return (token[1] == '_') || (token[1] !== token[1].toLowerCase()); - } - - function cpp14Literal(stream) { - stream.eatWhile(/[\w\.']/); - return "number"; - } - - function cpp11StringHook(stream, state) { - stream.backUp(1); - // Raw strings. - if (stream.match(/(R|u8R|uR|UR|LR)/)) { - var match = stream.match(/"([^\s\\()]{0,16})\(/); - if (!match) { - return false; - } - state.cpp11RawStringDelim = match[1]; - state.tokenize = tokenRawString; - return tokenRawString(stream, state); - } - // Unicode strings/chars. - if (stream.match(/(u8|u|U|L)/)) { - if (stream.match(/["']/, /* eat */ false)) { - return "string"; - } - return false; - } - // Ignore this hook. - stream.next(); - return false; - } - - function cppLooksLikeConstructor(word) { - var lastTwo = /(\w+)::~?(\w+)$/.exec(word); - return lastTwo && lastTwo[1] == lastTwo[2]; - } - - // C#-style strings where "" escapes a quote. - function tokenAtString(stream, state) { - var next; - while ((next = stream.next()) != null) { - if (next == '"' && !stream.eat('"')) { - state.tokenize = null; - break; - } - } - return "string"; - } - - // C++11 raw string literal is "( anything )", where - // can be a string up to 16 characters long. - function tokenRawString(stream, state) { - // Escape characters that have special regex meanings. - var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); - var match = stream.match(new RegExp(".*?\\)" + delim + '"')); - if (match) - state.tokenize = null; - else - stream.skipToEnd(); - return "string"; - } - - function def(mimes, mode) { - if (typeof mimes == "string") mimes = [mimes]; - var words = []; - function add(obj) { - if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) - words.push(prop); - } - add(mode.keywords); - add(mode.types); - add(mode.builtin); - add(mode.atoms); - if (words.length) { - mode.helperType = mimes[0]; - CodeMirror.registerHelper("hintWords", mimes[0], words); - } - - for (var i = 0; i < mimes.length; ++i) - CodeMirror.defineMIME(mimes[i], mode); - } - - def(["text/x-csrc", "text/x-c", "text/x-chdr"], { - name: "clike", - keywords: words(cKeywords), - types: cTypes, - blockKeywords: words(cBlockKeywords), - defKeywords: words(cDefKeywords), - typeFirstDefinitions: true, - atoms: words("NULL true false"), - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - }, - modeProps: {fold: ["brace", "include"]} - }); - - def(["text/x-c++src", "text/x-c++hdr"], { - name: "clike", - keywords: words(cKeywords + " " + cppKeywords), - types: cTypes, - blockKeywords: words(cBlockKeywords + " class try catch"), - defKeywords: words(cDefKeywords + " class namespace"), - typeFirstDefinitions: true, - atoms: words("true false NULL nullptr"), - dontIndentStatements: /^template$/, - isIdentifierChar: /[\w\$_~\xa1-\uffff]/, - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - "u": cpp11StringHook, - "U": cpp11StringHook, - "L": cpp11StringHook, - "R": cpp11StringHook, - "0": cpp14Literal, - "1": cpp14Literal, - "2": cpp14Literal, - "3": cpp14Literal, - "4": cpp14Literal, - "5": cpp14Literal, - "6": cpp14Literal, - "7": cpp14Literal, - "8": cpp14Literal, - "9": cpp14Literal, - token: function(stream, state, style) { - if (style == "variable" && stream.peek() == "(" && - (state.prevToken == ";" || state.prevToken == null || - state.prevToken == "}") && - cppLooksLikeConstructor(stream.current())) - return "def"; - } - }, - namespaceSeparator: "::", - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-java", { - name: "clike", - keywords: words("abstract assert break case catch class const continue default " + - "do else enum extends final finally for goto if implements import " + - "instanceof interface native new package private protected public " + - "return static strictfp super switch synchronized this throw throws transient " + - "try volatile while @interface"), - types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + - "Integer Long Number Object Short String StringBuffer StringBuilder Void"), - blockKeywords: words("catch class do else finally for if switch try while"), - defKeywords: words("class interface enum @interface"), - typeFirstDefinitions: true, - atoms: words("true false null"), - number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, - hooks: { - "@": function(stream) { - // Don't match the @interface keyword. - if (stream.match('interface', false)) return false; - - stream.eatWhile(/[\w\$_]/); - return "meta"; - } - }, - modeProps: {fold: ["brace", "import"]} - }); - - def("text/x-csharp", { - name: "clike", - keywords: words("abstract as async await base break case catch checked class const continue" + - " default delegate do else enum event explicit extern finally fixed for" + - " foreach goto if implicit in interface internal is lock namespace new" + - " operator out override params private protected public readonly ref return sealed" + - " sizeof stackalloc static struct switch this throw try typeof unchecked" + - " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + - " global group into join let orderby partial remove select set value var yield"), - types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + - " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + - " UInt64 bool byte char decimal double short int long object" + - " sbyte float string ushort uint ulong"), - blockKeywords: words("catch class do else finally for foreach if struct switch try while"), - defKeywords: words("class interface namespace struct var"), - typeFirstDefinitions: true, - atoms: words("true false null"), - hooks: { - "@": function(stream, state) { - if (stream.eat('"')) { - state.tokenize = tokenAtString; - return tokenAtString(stream, state); - } - stream.eatWhile(/[\w\$_]/); - return "meta"; - } - } - }); - - function tokenTripleString(stream, state) { - var escaped = false; - while (!stream.eol()) { - if (!escaped && stream.match('"""')) { - state.tokenize = null; - break; - } - escaped = stream.next() == "\\" && !escaped; - } - return "string"; - } - - function tokenNestedComment(depth) { - return function (stream, state) { - var ch - while (ch = stream.next()) { - if (ch == "*" && stream.eat("/")) { - if (depth == 1) { - state.tokenize = null - break - } else { - state.tokenize = tokenNestedComment(depth - 1) - return state.tokenize(stream, state) - } - } else if (ch == "/" && stream.eat("*")) { - state.tokenize = tokenNestedComment(depth + 1) - return state.tokenize(stream, state) - } - } - return "comment" - } - } - - def("text/x-scala", { - name: "clike", - keywords: words( - /* scala */ - "abstract case catch class def do else extends final finally for forSome if " + - "implicit import lazy match new null object override package private protected return " + - "sealed super this throw trait try type val var while with yield _ " + - - /* package scala */ - "assert assume require print println printf readLine readBoolean readByte readShort " + - "readChar readInt readLong readFloat readDouble" - ), - types: words( - "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + - "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + - "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + - "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + - "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + - - /* package java.lang */ - "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + - "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + - "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + - "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" - ), - multiLineStrings: true, - blockKeywords: words("catch class enum do else finally for forSome if match switch try while"), - defKeywords: words("class enum def object package trait type val var"), - atoms: words("true false null"), - indentStatements: false, - indentSwitch: false, - isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, - hooks: { - "@": function(stream) { - stream.eatWhile(/[\w\$_]/); - return "meta"; - }, - '"': function(stream, state) { - if (!stream.match('""')) return false; - state.tokenize = tokenTripleString; - return state.tokenize(stream, state); - }, - "'": function(stream) { - stream.eatWhile(/[\w\$_\xa1-\uffff]/); - return "atom"; - }, - "=": function(stream, state) { - var cx = state.context - if (cx.type == "}" && cx.align && stream.eat(">")) { - state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) - return "operator" - } else { - return false - } - }, - - "/": function(stream, state) { - if (!stream.eat("*")) return false - state.tokenize = tokenNestedComment(1) - return state.tokenize(stream, state) - } - }, - modeProps: {closeBrackets: {pairs: '()[]{}""', triples: '"'}} - }); - - function tokenKotlinString(tripleString){ - return function (stream, state) { - var escaped = false, next, end = false; - while (!stream.eol()) { - if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} - if (tripleString && stream.match('"""')) {end = true; break;} - next = stream.next(); - if(!escaped && next == "$" && stream.match('{')) - stream.skipTo("}"); - escaped = !escaped && next == "\\" && !tripleString; - } - if (end || !tripleString) - state.tokenize = null; - return "string"; - } - } - - def("text/x-kotlin", { - name: "clike", - keywords: words( - /*keywords*/ - "package as typealias class interface this super val operator " + - "var fun for is in This throw return annotation " + - "break continue object if else while do try when !in !is as? " + - - /*soft keywords*/ - "file import where by get set abstract enum open inner override private public internal " + - "protected catch finally out final vararg reified dynamic companion constructor init " + - "sealed field property receiver param sparam lateinit data inline noinline tailrec " + - "external annotation crossinline const operator infix suspend actual expect setparam" - ), - types: words( - /* package java.lang */ - "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + - "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + - "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + - "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " + - "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " + - "LazyThreadSafetyMode LongArray Nothing ShortArray Unit" - ), - intendSwitch: false, - indentStatements: false, - multiLineStrings: true, - number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, - blockKeywords: words("catch class do else finally for if where try while enum"), - defKeywords: words("class val var object interface fun"), - atoms: words("true false null this"), - hooks: { - "@": function(stream) { - stream.eatWhile(/[\w\$_]/); - return "meta"; - }, - '*': function(_stream, state) { - return state.prevToken == '.' ? 'variable' : 'operator'; - }, - '"': function(stream, state) { - state.tokenize = tokenKotlinString(stream.match('""')); - return state.tokenize(stream, state); - }, - "/": function(stream, state) { - if (!stream.eat("*")) return false; - state.tokenize = tokenNestedComment(1); - return state.tokenize(stream, state) - }, - indent: function(state, ctx, textAfter, indentUnit) { - var firstChar = textAfter && textAfter.charAt(0); - if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "") - return state.indented; - if ((state.prevToken == "operator" && textAfter != "}" && state.context.type != "}") || - state.prevToken == "variable" && firstChar == "." || - (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".") - return indentUnit * 2 + ctx.indented; - if (ctx.align && ctx.type == "}") - return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit); - } - }, - modeProps: {closeBrackets: {triples: '"'}} - }); - - def(["x-shader/x-vertex", "x-shader/x-fragment"], { - name: "clike", - keywords: words("sampler1D sampler2D sampler3D samplerCube " + - "sampler1DShadow sampler2DShadow " + - "const attribute uniform varying " + - "break continue discard return " + - "for while do if else struct " + - "in out inout"), - types: words("float int bool void " + - "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + - "mat2 mat3 mat4"), - blockKeywords: words("for while do if else struct"), - builtin: words("radians degrees sin cos tan asin acos atan " + - "pow exp log exp2 sqrt inversesqrt " + - "abs sign floor ceil fract mod min max clamp mix step smoothstep " + - "length distance dot cross normalize ftransform faceforward " + - "reflect refract matrixCompMult " + - "lessThan lessThanEqual greaterThan greaterThanEqual " + - "equal notEqual any all not " + - "texture1D texture1DProj texture1DLod texture1DProjLod " + - "texture2D texture2DProj texture2DLod texture2DProjLod " + - "texture3D texture3DProj texture3DLod texture3DProjLod " + - "textureCube textureCubeLod " + - "shadow1D shadow2D shadow1DProj shadow2DProj " + - "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + - "dFdx dFdy fwidth " + - "noise1 noise2 noise3 noise4"), - atoms: words("true false " + - "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + - "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + - "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + - "gl_FogCoord gl_PointCoord " + - "gl_Position gl_PointSize gl_ClipVertex " + - "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + - "gl_TexCoord gl_FogFragCoord " + - "gl_FragCoord gl_FrontFacing " + - "gl_FragData gl_FragDepth " + - "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + - "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + - "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + - "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + - "gl_ProjectionMatrixInverseTranspose " + - "gl_ModelViewProjectionMatrixInverseTranspose " + - "gl_TextureMatrixInverseTranspose " + - "gl_NormalScale gl_DepthRange gl_ClipPlane " + - "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + - "gl_FrontLightModelProduct gl_BackLightModelProduct " + - "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + - "gl_FogParameters " + - "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + - "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + - "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + - "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + - "gl_MaxDrawBuffers"), - indentSwitch: false, - hooks: {"#": cppHook}, - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-nesc", { - name: "clike", - keywords: words(cKeywords + " as atomic async call command component components configuration event generic " + - "implementation includes interface module new norace nx_struct nx_union post provides " + - "signal task uses abstract extends"), - types: cTypes, - blockKeywords: words(cBlockKeywords), - atoms: words("null true false"), - hooks: {"#": cppHook}, - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-objectivec", { - name: "clike", - keywords: words(cKeywords + " " + objCKeywords), - types: objCTypes, - builtin: words(objCBuiltins), - blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"), - defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"), - dontIndentStatements: /^@.*$/, - typeFirstDefinitions: true, - atoms: words("YES NO NULL Nil nil true false nullptr"), - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - }, - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-objectivec++", { - name: "clike", - keywords: words(cKeywords + " " + objCKeywords + " " + cppKeywords), - types: objCTypes, - builtin: words(objCBuiltins), - blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"), - defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class class namespace"), - dontIndentStatements: /^@.*$|^template$/, - typeFirstDefinitions: true, - atoms: words("YES NO NULL Nil nil true false nullptr"), - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - "u": cpp11StringHook, - "U": cpp11StringHook, - "L": cpp11StringHook, - "R": cpp11StringHook, - "0": cpp14Literal, - "1": cpp14Literal, - "2": cpp14Literal, - "3": cpp14Literal, - "4": cpp14Literal, - "5": cpp14Literal, - "6": cpp14Literal, - "7": cpp14Literal, - "8": cpp14Literal, - "9": cpp14Literal, - token: function(stream, state, style) { - if (style == "variable" && stream.peek() == "(" && - (state.prevToken == ";" || state.prevToken == null || - state.prevToken == "}") && - cppLooksLikeConstructor(stream.current())) - return "def"; - } - }, - namespaceSeparator: "::", - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-squirrel", { - name: "clike", - keywords: words("base break clone continue const default delete enum extends function in class" + - " foreach local resume return this throw typeof yield constructor instanceof static"), - types: cTypes, - blockKeywords: words("case catch class else for foreach if switch try while"), - defKeywords: words("function local class"), - typeFirstDefinitions: true, - atoms: words("true false null"), - hooks: {"#": cppHook}, - modeProps: {fold: ["brace", "include"]} - }); - - // Ceylon Strings need to deal with interpolation - var stringTokenizer = null; - function tokenCeylonString(type) { - return function(stream, state) { - var escaped = false, next, end = false; - while (!stream.eol()) { - if (!escaped && stream.match('"') && - (type == "single" || stream.match('""'))) { - end = true; - break; - } - if (!escaped && stream.match('``')) { - stringTokenizer = tokenCeylonString(type); - end = true; - break; - } - next = stream.next(); - escaped = type == "single" && !escaped && next == "\\"; - } - if (end) - state.tokenize = null; - return "string"; - } - } - - def("text/x-ceylon", { - name: "clike", - keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + - " exists extends finally for function given if import in interface is let module new" + - " nonempty object of out outer package return satisfies super switch then this throw" + - " try value void while"), - types: function(word) { - // In Ceylon all identifiers that start with an uppercase are types - var first = word.charAt(0); - return (first === first.toUpperCase() && first !== first.toLowerCase()); - }, - blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), - defKeywords: words("class dynamic function interface module object package value"), - builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + - " native optional sealed see serializable shared suppressWarnings tagged throws variable"), - isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, - isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, - numberStart: /[\d#$]/, - number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, - multiLineStrings: true, - typeFirstDefinitions: true, - atoms: words("true false null larger smaller equal empty finished"), - indentSwitch: false, - styleDefs: false, - hooks: { - "@": function(stream) { - stream.eatWhile(/[\w\$_]/); - return "meta"; - }, - '"': function(stream, state) { - state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); - return state.tokenize(stream, state); - }, - '`': function(stream, state) { - if (!stringTokenizer || !stream.match('`')) return false; - state.tokenize = stringTokenizer; - stringTokenizer = null; - return state.tokenize(stream, state); - }, - "'": function(stream) { - stream.eatWhile(/[\w\$_\xa1-\uffff]/); - return "atom"; - }, - token: function(_stream, state, style) { - if ((style == "variable" || style == "type") && - state.prevToken == ".") { - return "variable-2"; - } - } - }, - modeProps: { - fold: ["brace", "import"], - closeBrackets: {triples: '"'} - } - }); - -}); - -window.onload = function() { - var new_editor_element = document.body.getElementsByClassName("fs-editor"), - new_editor; - if (new_editor_element.length > 0) { - new_editor_element = new_editor_element[0]; - } - - new_editor = new CodeMirror(new_editor_element, window.opener.gb_code_editor_settings); - new_editor.setOption("theme", window.opener.gb_code_editor_theme); - new_editor.setValue(window.opener.gb_code_editor.getValue()); - - synced_cm_document = window.opener.gb_code_editor.getDoc(); - - new_editor.swapDoc(synced_cm_document.linkedDoc({ - sharedHist: true - })); - - window.addEventListener("load", function () { - new_editor.refresh(); - }, false); - window.addEventListener("resize", function () { - new_editor.refresh(); - }, false); - - window.cm = new_editor; -}; \ No newline at end of file +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.CodeMirror=t()}(this,function(){"use strict";var e=navigator.userAgent,t=navigator.platform,n=/gecko\/\d/i.test(e),r=/MSIE \d/.test(e),i=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(e),o=/Edge\/(\d+)/.exec(e),a=r||i||o,l=a&&(r?document.documentMode||6:+(o||i)[1]),s=!o&&/WebKit\//.test(e),c=s&&/Qt\/\d+\.\d+/.test(e),u=!o&&/Chrome\//.test(e),f=/Opera\//.test(e),h=/Apple Computer/.test(navigator.vendor),d=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(e),p=/PhantomJS/.test(e),g=!o&&/AppleWebKit/.test(e)&&/Mobile\/\w+/.test(e),m=/Android/.test(e),v=g||m||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(e),y=g||/Mac/.test(t),b=/\bCrOS\b/.test(e),x=/win/i.test(t),w=f&&e.match(/Version\/(\d*\.\d*)/);w&&(w=Number(w[1])),w&&w>=15&&(f=!1,s=!0);var k=y&&(c||f&&(null==w||w<12.11)),C=n||a&&l>=9;function S(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}var L,T=function(e,t){var n=e.className,r=S(t).exec(n);if(r){var i=n.slice(r.index+r[0].length);e.className=n.slice(0,r.index)+(i?r[1]+i:"")}};function M(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function N(e,t){return M(e).appendChild(t)}function A(e,t,n,r){var i=document.createElement(e);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o=t)return a+(t-o);a+=l-o,a+=n-a%n,o=l+1}}g?z=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:a&&(z=function(e){try{e.select()}catch(e){}});var R=function(){this.id=null,this.f=null,this.time=0,this.handler=I(this.onTimeout,this)};function _(e,t){for(var n=0;n=t)return r+Math.min(a,t-i);if(i+=o-r,r=o+1,(i+=n-i%n)>=t)return r}}var q=[""];function $(e){for(;q.length<=e;)q.push(X(q)+" ");return q[e]}function X(e){return e[e.length-1]}function Y(e,t){for(var n=[],r=0;r"€"&&(e.toUpperCase()!=e.toLowerCase()||J.test(e))}function te(e,t){return t?!!(t.source.indexOf("\\w")>-1&&ee(e))||t.test(e):ee(e)}function ne(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}var re=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function ie(e){return e.charCodeAt(0)>=768&&re.test(e)}function oe(e,t,n){for(;(n<0?t>0:tn?-1:1;;){if(t==n)return t;var i=(t+n)/2,o=r<0?Math.ceil(i):Math.floor(i);if(o==t)return e(o)?t:n;e(o)?n=o:t=o+r}}var le=null;function se(e,t,n){var r;le=null;for(var i=0;it)return i;o.to==t&&(o.from!=o.to&&"before"==n?r=i:le=i),o.from==t&&(o.from!=o.to&&"before"!=n?r=i:le=i)}return null!=r?r:le}var ce=function(){var e="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",t="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";var n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,r=/[stwN]/,i=/[LRr]/,o=/[Lb1n]/,a=/[1n]/;function l(e,t,n){this.level=e,this.from=t,this.to=n}return function(s,c){var u="ltr"==c?"L":"R";if(0==s.length||"ltr"==c&&!n.test(s))return!1;for(var f,h=s.length,d=[],p=0;p-1&&(r[t]=i.slice(0,o).concat(i.slice(o+1)))}}}function ge(e,t){var n=de(e,t);if(n.length)for(var r=Array.prototype.slice.call(arguments,2),i=0;i0}function be(e){e.prototype.on=function(e,t){he(this,e,t)},e.prototype.off=function(e,t){pe(this,e,t)}}function xe(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function we(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function ke(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function Ce(e){xe(e),we(e)}function Se(e){return e.target||e.srcElement}function Le(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),y&&e.ctrlKey&&1==t&&(t=3),t}var Te,Me,Ne=function(){if(a&&l<9)return!1;var e=A("div");return"draggable"in e||"dragDrop"in e}();function Ae(e){if(null==Te){var t=A("span","​");N(e,A("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(Te=t.offsetWidth<=1&&t.offsetHeight>2&&!(a&&l<8))}var n=Te?A("span","​"):A("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return n.setAttribute("cm-text",""),n}function Oe(e){if(null!=Me)return Me;var t=N(e,document.createTextNode("AخA")),n=L(t,0,1).getBoundingClientRect(),r=L(t,1,2).getBoundingClientRect();return M(e),!(!n||n.left==n.right)&&(Me=r.right-n.right<3)}var De,Ee=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],r=e.length;t<=r;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(n.push(o.slice(0,a)),t+=a+1):(n.push(o),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},Pe=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(e){return!1}}:function(e){var t;try{t=e.ownerDocument.selection.createRange()}catch(e){}return!(!t||t.parentElement()!=e)&&0!=t.compareEndPoints("StartToEnd",t)},We="oncopy"in(De=A("div"))||(De.setAttribute("oncopy","return;"),"function"==typeof De.oncopy),ze=null;var Ie={},Fe={};function He(e){if("string"==typeof e&&Fe.hasOwnProperty(e))e=Fe[e];else if(e&&"string"==typeof e.name&&Fe.hasOwnProperty(e.name)){var t=Fe[e.name];"string"==typeof t&&(t={name:t}),(e=Q(t,e)).name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return He("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return He("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function Re(e,t){t=He(t);var n=Ie[t.name];if(!n)return Re(e,"text/plain");var r=n(e,t);if(_e.hasOwnProperty(t.name)){var i=_e[t.name];for(var o in i)i.hasOwnProperty(o)&&(r.hasOwnProperty(o)&&(r["_"+o]=r[o]),r[o]=i[o])}if(r.name=t.name,t.helperType&&(r.helperType=t.helperType),t.modeProps)for(var a in t.modeProps)r[a]=t.modeProps[a];return r}var _e={};function Be(e,t){F(t,_e.hasOwnProperty(e)?_e[e]:_e[e]={})}function je(e,t){if(!0===t)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n}function Ue(e,t){for(var n;e.innerMode&&(n=e.innerMode(t))&&n.mode!=e;)t=n.state,e=n.mode;return n||{mode:e,state:t}}function Ve(e,t,n){return!e.startState||e.startState(t,n)}var Ke=function(e,t,n){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Ge(e,t){if((t-=e.first)<0||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(t=e.first&&tn?et(n,Ge(e,n).text.length):function(e,t){var n=e.ch;return null==n||n>t?et(e.line,t):n<0?et(e.line,0):e}(t,Ge(e,t.line).text.length)}function st(e,t){for(var n=[],r=0;r=this.string.length},Ke.prototype.sol=function(){return this.pos==this.lineStart},Ke.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ke.prototype.next=function(){if(this.post},Ke.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},Ke.prototype.skipToEnd=function(){this.pos=this.string.length},Ke.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},Ke.prototype.backUp=function(e){this.pos-=e},Ke.prototype.column=function(){return this.lastColumnPos0?null:(r&&!1!==t&&(this.pos+=r[0].length),r)}var i=function(e){return n?e.toLowerCase():e};if(i(this.string.substr(this.pos,e.length))==i(e))return!1!==t&&(this.pos+=e.length),!0},Ke.prototype.current=function(){return this.string.slice(this.start,this.pos)},Ke.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}},Ke.prototype.lookAhead=function(e){var t=this.lineOracle;return t&&t.lookAhead(e)},Ke.prototype.baseToken=function(){var e=this.lineOracle;return e&&e.baseToken(this.pos)};var ct=function(e,t){this.state=e,this.lookAhead=t},ut=function(e,t,n,r){this.state=t,this.doc=e,this.line=n,this.maxLookAhead=r||0,this.baseTokens=null,this.baseTokenPos=1};function ft(e,t,n,r){var i=[e.state.modeGen],o={};xt(e,t.text,e.doc.mode,n,function(e,t){return i.push(e,t)},o,r);for(var a=n.state,l=function(r){n.baseTokens=i;var l=e.state.overlays[r],s=1,c=0;n.state=!0,xt(e,t.text,l.mode,n,function(e,t){for(var n=s;ce&&i.splice(s,1,e,i[s+1],r),s+=2,c=Math.min(e,r)}if(t)if(l.opaque)i.splice(n,s-n,e,"overlay "+t),s=n+2;else for(;ne.options.maxHighlightLength&&je(e.doc.mode,r.state),o=ft(e,t,r);i&&(r.state=i),t.stateAfter=r.save(!i),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),n===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function dt(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return new ut(r,!0,t);var o=function(e,t,n){for(var r,i,o=e.doc,a=n?-1:t-(e.doc.mode.innerMode?1e3:100),l=t;l>a;--l){if(l<=o.first)return o.first;var s=Ge(o,l-1),c=s.stateAfter;if(c&&(!n||l+(c instanceof ct?c.lookAhead:0)<=o.modeFrontier))return l;var u=H(s.text,null,e.options.tabSize);(null==i||r>u)&&(i=l-1,r=u)}return i}(e,t,n),a=o>r.first&&Ge(r,o-1).stateAfter,l=a?ut.fromSaved(r,a,o):new ut(r,Ve(r.mode),o);return r.iter(o,t,function(n){pt(e,n.text,l);var r=l.line;n.stateAfter=r==t-1||r%5==0||r>=i.viewFrom&&rt.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}ut.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},ut.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},ut.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},ut.fromSaved=function(e,t,n){return t instanceof ct?new ut(e,je(e.mode,t.state),n,t.lookAhead):new ut(e,je(e.mode,t),n)},ut.prototype.save=function(e){var t=!1!==e?je(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new ct(t,this.maxLookAhead):t};var vt=function(e,t,n){this.start=e.start,this.end=e.pos,this.string=e.current(),this.type=t||null,this.state=n};function yt(e,t,n,r){var i,o,a=e.doc,l=a.mode,s=Ge(a,(t=lt(a,t)).line),c=dt(e,t.line,n),u=new Ke(s.text,e.options.tabSize,c);for(r&&(o=[]);(r||u.pose.options.maxHighlightLength?(l=!1,a&&pt(e,t,r,f.pos),f.pos=t.length,s=null):s=bt(mt(n,f,r.state,h),o),h){var d=h[0].name;d&&(s="m-"+(s?d+" "+s:d))}if(!l||u!=s){for(;c=t:o.to>t);(r||(r=[])).push(new Ct(a,o.from,l?null:o.to))}}return r}(n,i,a),s=function(e,t,n){var r;if(e)for(var i=0;i=t:o.to>t)||o.from==t&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=t:o.from0&&l)for(var b=0;bt)&&(!n||Et(n,o.marker)<0)&&(n=o.marker)}return n}function Ft(e,t,n,r,i){var o=Ge(e,t),a=kt&&o.markedSpans;if(a)for(var l=0;l=0&&f<=0||u<=0&&f>=0)&&(u<=0&&(s.marker.inclusiveRight&&i.inclusiveLeft?tt(c.to,n)>=0:tt(c.to,n)>0)||u>=0&&(s.marker.inclusiveRight&&i.inclusiveLeft?tt(c.from,r)<=0:tt(c.from,r)<0)))return!0}}}function Ht(e){for(var t;t=Wt(e);)e=t.find(-1,!0).line;return e}function Rt(e,t){var n=Ge(e,t),r=Ht(n);return n==r?t:Ye(r)}function _t(e,t){if(t>e.lastLine())return t;var n,r=Ge(e,t);if(!Bt(e,r))return t;for(;n=zt(r);)r=n.find(1,!0).line;return Ye(r)+1}function Bt(e,t){var n=kt&&t.markedSpans;if(n)for(var r=void 0,i=0;it.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}var Gt=function(e,t,n){this.text=e,At(this,t),this.height=n?n(this):1};function qt(e){e.parent=null,Nt(e)}Gt.prototype.lineNo=function(){return Ye(this)},be(Gt);var $t={},Xt={};function Yt(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?Xt:$t;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function Zt(e,t){var n=O("span",null,null,s?"padding-right: .1px":null),r={pre:O("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:e,trailingSpace:!1,splitSpaces:e.getOption("lineWrapping")};t.measure={};for(var i=0;i<=(t.rest?t.rest.length:0);i++){var o=i?t.rest[i-1]:t.line,a=void 0;r.pos=0,r.addToken=Jt,Oe(e.display.measure)&&(a=ue(o,e.doc.direction))&&(r.addToken=en(r.addToken,a)),r.map=[],nn(o,r,ht(e,o,t!=e.display.externalMeasured&&Ye(o))),o.styleClasses&&(o.styleClasses.bgClass&&(r.bgClass=W(o.styleClasses.bgClass,r.bgClass||"")),o.styleClasses.textClass&&(r.textClass=W(o.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(Ae(e.display.measure))),0==i?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}if(s){var l=r.content.lastChild;(/\bcm-tab\b/.test(l.className)||l.querySelector&&l.querySelector(".cm-tab"))&&(r.content.className="cm-tab-wrap-hack")}return ge(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=W(r.pre.className,r.textClass||"")),r}function Qt(e){var t=A("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t.setAttribute("aria-label",t.title),t}function Jt(e,t,n,r,i,o,s){if(t){var c,u=e.splitSpaces?function(e,t){if(e.length>1&&!/ /.test(e))return e;for(var n=t,r="",i=0;ic&&f.from<=c);h++);if(f.to>=u)return e(n,r,i,o,a,l,s);e(n,r.slice(0,f.to-c),i,o,null,l,s),o=null,r=r.slice(f.to-c),c=f.to}}}function tn(e,t,n,r){var i=!r&&n.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!r&&e.cm.display.input.needsContentAttribute&&(i||(i=e.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",n.id)),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function nn(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var a,l,s,c,u,f,h,d=i.length,p=0,g=1,m="",v=0;;){if(v==p){s=c=u=l="",h=null,f=null,v=1/0;for(var y=[],b=void 0,x=0;xp||k.collapsed&&w.to==p&&w.from==p)){if(null!=w.to&&w.to!=p&&v>w.to&&(v=w.to,c=""),k.className&&(s+=" "+k.className),k.css&&(l=(l?l+";":"")+k.css),k.startStyle&&w.from==p&&(u+=" "+k.startStyle),k.endStyle&&w.to==v&&(b||(b=[])).push(k.endStyle,w.to),k.title&&((h||(h={})).title=k.title),k.attributes)for(var C in k.attributes)(h||(h={}))[C]=k.attributes[C];k.collapsed&&(!f||Et(f.marker,k)<0)&&(f=w)}else w.from>p&&v>w.from&&(v=w.from)}if(b)for(var S=0;S=d)break;for(var T=Math.min(d,v);;){if(m){var M=p+m.length;if(!f){var N=M>T?m.slice(0,T-p):m;t.addToken(t,N,a?a+s:s,u,p+N.length==v?c:"",l,h)}if(M>=T){m=m.slice(T-p),p=T;break}p=M,u=""}m=i.slice(o,o=n[g++]),a=Yt(n[g++],t.cm.options)}}else for(var A=1;An)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function On(e,t,n,r){return Pn(e,En(e,t),n,r)}function Dn(e,t){if(t>=e.display.viewFrom&&t=n.lineN&&t2&&o.push((s.bottom+c.top)/2-n.top)}}o.push(n.bottom-n.top)}}(e,t.view,t.rect),t.hasHeights=!0),(o=function(e,t,n,r){var i,o=In(t.map,n,r),s=o.node,c=o.start,u=o.end,f=o.collapse;if(3==s.nodeType){for(var h=0;h<4;h++){for(;c&&ie(t.line.text.charAt(o.coverStart+c));)--c;for(;o.coverStart+u1}(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*r,bottom:t.bottom*r}}(e.display.measure,i))}else{var d;c>0&&(f=r="right"),i=e.options.lineWrapping&&(d=s.getClientRects()).length>1?d["right"==r?d.length-1:0]:s.getBoundingClientRect()}if(a&&l<9&&!c&&(!i||!i.left&&!i.right)){var p=s.parentNode.getClientRects()[0];i=p?{left:p.left,right:p.left+nr(e.display),top:p.top,bottom:p.bottom}:zn}for(var g=i.top-t.rect.top,m=i.bottom-t.rect.top,v=(g+m)/2,y=t.view.measure.heights,b=0;bt)&&(i=(o=s-l)-1,t>=s&&(a="right")),null!=i){if(r=e[c+2],l==s&&n==(r.insertLeft?"left":"right")&&(a=n),"left"==n&&0==i)for(;c&&e[c-2]==e[c-3]&&e[c-1].insertLeft;)r=e[2+(c-=3)],a="left";if("right"==n&&i==s-l)for(;c=0&&(n=e[i]).left==n.right;i--);return n}function Hn(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t=r.text.length?(s=r.text.length,c="before"):s<=0&&(s=0,c="after"),!l)return a("before"==c?s-1:s,"before"==c);function u(e,t,n){var r=1==l[t].level;return a(n?e-1:e,r!=n)}var f=se(l,s,c),h=le,d=u(s,f,"before"==c);return null!=h&&(d.other=u(s,h,"before"!=c)),d}function $n(e,t){var n=0;t=lt(e.doc,t),e.options.lineWrapping||(n=nr(e.display)*t.ch);var r=Ge(e.doc,t.line),i=Ut(r)+Cn(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function Xn(e,t,n,r,i){var o=et(e,t,n);return o.xRel=i,r&&(o.outside=r),o}function Yn(e,t,n){var r=e.doc;if((n+=e.display.viewOffset)<0)return Xn(r.first,0,null,-1,-1);var i=Ze(r,n),o=r.first+r.size-1;if(i>o)return Xn(r.first+r.size-1,Ge(r,o).text.length,null,1,1);t<0&&(t=0);for(var a=Ge(r,i);;){var l=er(e,a,i,t,n),s=It(a,l.ch+(l.xRel>0||l.outside>0?1:0));if(!s)return l;var c=s.find(1);if(c.line==i)return c;a=Ge(r,i=c.line)}}function Zn(e,t,n,r){r-=Un(t);var i=t.text.length,o=ae(function(t){return Pn(e,n,t-1).bottom<=r},i,0);return{begin:o,end:i=ae(function(t){return Pn(e,n,t).top>r},o,i)}}function Qn(e,t,n,r){return n||(n=En(e,t)),Zn(e,t,n,Vn(e,t,Pn(e,n,r),"line").top)}function Jn(e,t,n,r){return!(e.bottom<=n)&&(e.top>n||(r?e.left:e.right)>t)}function er(e,t,n,r,i){i-=Ut(t);var o=En(e,t),a=Un(t),l=0,s=t.text.length,c=!0,u=ue(t,e.doc.direction);if(u){var f=(e.options.lineWrapping?function(e,t,n,r,i,o,a){var l=Zn(e,t,r,a),s=l.begin,c=l.end;/\s/.test(t.text.charAt(c-1))&&c--;for(var u=null,f=null,h=0;h=c||d.to<=s)){var p=1!=d.level,g=Pn(e,r,p?Math.min(c,d.to)-1:Math.max(s,d.from)).right,m=gm)&&(u=d,f=m)}}u||(u=i[i.length-1]);u.fromc&&(u={from:u.from,to:c,level:u.level});return u}:function(e,t,n,r,i,o,a){var l=ae(function(l){var s=i[l],c=1!=s.level;return Jn(qn(e,et(n,c?s.to:s.from,c?"before":"after"),"line",t,r),o,a,!0)},0,i.length-1),s=i[l];if(l>0){var c=1!=s.level,u=qn(e,et(n,c?s.from:s.to,c?"after":"before"),"line",t,r);Jn(u,o,a,!0)&&u.top>a&&(s=i[l-1])}return s})(e,t,n,o,u,r,i);l=(c=1!=f.level)?f.from:f.to-1,s=c?f.to:f.from-1}var h,d,p=null,g=null,m=ae(function(t){var n=Pn(e,o,t);return n.top+=a,n.bottom+=a,!!Jn(n,r,i,!1)&&(n.top<=i&&n.left<=r&&(p=t,g=n),!0)},l,s),v=!1;if(g){var y=r-g.left=x.bottom?1:0}return Xn(n,m=oe(t.text,m,1),d,v,r-h)}function tr(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Wn){Wn=A("pre",null,"CodeMirror-line-like");for(var t=0;t<49;++t)Wn.appendChild(document.createTextNode("x")),Wn.appendChild(A("br"));Wn.appendChild(document.createTextNode("x"))}N(e.measure,Wn);var n=Wn.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),M(e.measure),n||1}function nr(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=A("span","xxxxxxxxxx"),n=A("pre",[t],"CodeMirror-line-like");N(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(e.cachedCharWidth=i),i||10}function rr(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,a=0;o;o=o.nextSibling,++a){var l=e.display.gutterSpecs[a].className;n[l]=o.offsetLeft+o.clientLeft+i,r[l]=o.clientWidth}return{fixedPos:ir(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function ir(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function or(e){var t=tr(e.display),n=e.options.lineWrapping,r=n&&Math.max(5,e.display.scroller.clientWidth/nr(e.display)-3);return function(i){if(Bt(e.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a0&&(s=Ge(e.doc,c.line).text).length==c.ch){var u=H(s,s.length,e.options.tabSize)-s.length;c=et(c.line,Math.max(0,Math.round((o-Ln(e.display).left)/nr(e.display))-u))}return c}function sr(e,t){if(t>=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var n=e.display.view,r=0;rt)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)kt&&Rt(e.doc,t)i.viewFrom?fr(e):(i.viewFrom+=r,i.viewTo+=r);else if(t<=i.viewFrom&&n>=i.viewTo)fr(e);else if(t<=i.viewFrom){var o=hr(e,n,n+r,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=r):fr(e)}else if(n>=i.viewTo){var a=hr(e,t,t,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):fr(e)}else{var l=hr(e,t,t,-1),s=hr(e,n,n+r,1);l&&s?(i.view=i.view.slice(0,l.index).concat(on(e,l.lineN,s.lineN)).concat(i.view.slice(s.index)),i.viewTo+=r):fr(e)}var c=i.externalMeasured;c&&(n=i.lineN&&t=r.viewTo)){var o=r.view[sr(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==_(a,n)&&a.push(n)}}}function fr(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function hr(e,t,n,r){var i,o=sr(e,t),a=e.display.view;if(!kt||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var l=e.display.viewFrom,s=0;s0){if(o==a.length-1)return null;i=l+a[o].size-t,o++}else i=l-t;t+=i,n+=i}for(;Rt(e.doc,n)!=n;){if(o==(r<0?0:a.length-1))return null;n+=r*a[o-(r<0?1:0)].size,o+=r}return{index:o,lineN:n}}function dr(e){for(var t=e.display.view,n=0,r=0;r=e.display.viewTo||l.to().linet||t==n&&a.to==t)&&(r(Math.max(a.from,t),Math.min(a.to,n),1==a.level?"rtl":"ltr",o),i=!0)}i||r(t,n,"ltr")}(g,n||0,null==r?h:r,function(e,t,i,f){var m="ltr"==i,v=d(e,m?"left":"right"),y=d(t-1,m?"right":"left"),b=null==n&&0==e,x=null==r&&t==h,w=0==f,k=!g||f==g.length-1;if(y.top-v.top<=3){var C=(c?x:b)&&k,S=(c?b:x)&&w?l:(m?v:y).left,L=C?s:(m?y:v).right;u(S,v.top,L-S,v.bottom)}else{var T,M,N,A;m?(T=c&&b&&w?l:v.left,M=c?s:p(e,i,"before"),N=c?l:p(t,i,"after"),A=c&&x&&k?s:y.right):(T=c?p(e,i,"before"):l,M=!c&&b&&w?s:v.right,N=!c&&x&&k?l:y.left,A=c?p(t,i,"after"):s),u(T,v.top,M-T,v.bottom),v.bottom0?t.blinker=setInterval(function(){return t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function xr(e){e.state.focused||(e.display.input.focus(),kr(e))}function wr(e){e.state.delayingBlurEvent=!0,setTimeout(function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,Cr(e))},100)}function kr(e,t){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(ge(e,"focus",e,t),e.state.focused=!0,P(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),s&&setTimeout(function(){return e.display.input.reset(!0)},20)),e.display.input.receivedFocus()),br(e))}function Cr(e,t){e.state.delayingBlurEvent||(e.state.focused&&(ge(e,"blur",e,t),e.state.focused=!1,T(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150))}function Sr(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=0;r.005||h<-.005)&&(Xe(i.line,s),Lr(i.line),i.rest))for(var d=0;de.display.sizerWidth){var p=Math.ceil(c/nr(e.display));p>e.display.maxLineLength&&(e.display.maxLineLength=p,e.display.maxLine=i.line,e.display.maxLineChanged=!0)}}}}function Lr(e){if(e.widgets)for(var t=0;t=a&&(o=Ze(t,Ut(Ge(t,s))-e.wrapper.clientHeight),a=s)}return{from:o,to:Math.max(a,o+1)}}function Mr(e,t){var n=e.display,r=tr(e.display);t.top<0&&(t.top=0);var i=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:n.scroller.scrollTop,o=Nn(e),a={};t.bottom-t.top>o&&(t.bottom=t.top+o);var l=e.doc.height+Sn(n),s=t.topl-r;if(t.topi+o){var u=Math.min(t.top,(c?l:t.bottom)-o);u!=i&&(a.scrollTop=u)}var f=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:n.scroller.scrollLeft,h=Mn(e)-(e.options.fixedGutter?n.gutters.offsetWidth:0),d=t.right-t.left>h;return d&&(t.right=t.left+h),t.left<10?a.scrollLeft=0:t.lefth+f-3&&(a.scrollLeft=t.right+(d?0:10)-h),a}function Nr(e,t){null!=t&&(Dr(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function Ar(e){Dr(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function Or(e,t,n){null==t&&null==n||Dr(e),null!=t&&(e.curOp.scrollLeft=t),null!=n&&(e.curOp.scrollTop=n)}function Dr(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,Er(e,$n(e,t.from),$n(e,t.to),t.margin))}function Er(e,t,n,r){var i=Mr(e,{left:Math.min(t.left,n.left),top:Math.min(t.top,n.top)-r,right:Math.max(t.right,n.right),bottom:Math.max(t.bottom,n.bottom)+r});Or(e,i.scrollLeft,i.scrollTop)}function Pr(e,t){Math.abs(e.doc.scrollTop-t)<2||(n||oi(e,{top:t}),Wr(e,t,!0),n&&oi(e),ei(e,100))}function Wr(e,t,n){t=Math.max(0,Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t)),(e.display.scroller.scrollTop!=t||n)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function zr(e,t,n,r){t=Math.max(0,Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth)),(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!r||(e.doc.scrollLeft=t,si(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function Ir(e){var t=e.display,n=t.gutters.offsetWidth,r=Math.round(e.doc.height+Sn(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:r,scrollHeight:r+Tn(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}var Fr=function(e,t,n){this.cm=n;var r=this.vert=A("div",[A("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=A("div",[A("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");r.tabIndex=i.tabIndex=-1,e(r),e(i),he(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")}),he(i,"scroll",function(){i.clientWidth&&t(i.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,a&&l<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};Fr.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,n=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=t?r+"px":"0";var i=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=n?r+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(n?r:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&e.clientHeight>0&&(0==r&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?r:0,bottom:t?r:0}},Fr.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},Fr.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},Fr.prototype.zeroWidthHack=function(){var e=y&&!d?"12px":"18px";this.horiz.style.height=this.vert.style.width=e,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new R,this.disableVert=new R},Fr.prototype.enableZeroWidthBar=function(e,t,n){e.style.pointerEvents="auto",t.set(1e3,function r(){var i=e.getBoundingClientRect();("vert"==n?document.elementFromPoint(i.right-1,(i.top+i.bottom)/2):document.elementFromPoint((i.right+i.left)/2,i.bottom-1))!=e?e.style.pointerEvents="none":t.set(1e3,r)})},Fr.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};var Hr=function(){};function Rr(e,t){t||(t=Ir(e));var n=e.display.barWidth,r=e.display.barHeight;_r(e,t);for(var i=0;i<4&&n!=e.display.barWidth||r!=e.display.barHeight;i++)n!=e.display.barWidth&&e.options.lineWrapping&&Sr(e),_r(e,Ir(e)),n=e.display.barWidth,r=e.display.barHeight}function _r(e,t){var n=e.display,r=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=r.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=r.bottom)+"px",n.heightForcer.style.borderBottom=r.bottom+"px solid transparent",r.right&&r.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=r.bottom+"px",n.scrollbarFiller.style.width=r.right+"px"):n.scrollbarFiller.style.display="",r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r.bottom+"px",n.gutterFiller.style.width=t.gutterWidth+"px"):n.gutterFiller.style.display=""}Hr.prototype.update=function(){return{bottom:0,right:0}},Hr.prototype.setScrollLeft=function(){},Hr.prototype.setScrollTop=function(){},Hr.prototype.clear=function(){};var Br={native:Fr,null:Hr};function jr(e){e.display.scrollbars&&(e.display.scrollbars.clear(),e.display.scrollbars.addClass&&T(e.display.wrapper,e.display.scrollbars.addClass)),e.display.scrollbars=new Br[e.options.scrollbarStyle](function(t){e.display.wrapper.insertBefore(t,e.display.scrollbarFiller),he(t,"mousedown",function(){e.state.focused&&setTimeout(function(){return e.display.input.focus()},0)}),t.setAttribute("cm-not-content","true")},function(t,n){"horizontal"==n?zr(e,t):Pr(e,t)},e),e.display.scrollbars.addClass&&P(e.display.wrapper,e.display.scrollbars.addClass)}var Ur=0;function Vr(e){var t;e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Ur},t=e.curOp,an?an.ops.push(t):t.ownsGroup=an={ops:[t],delayedCallbacks:[]}}function Kr(e){var t=e.curOp;t&&function(e,t){var n=e.ownsGroup;if(n)try{!function(e){var t=e.delayedCallbacks,n=0;do{for(;n=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new ni(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function qr(e){var t=e.cm,n=t.display;e.updatedDisplay&&Sr(t),e.barMeasure=Ir(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=On(t,n.maxLine,n.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+Tn(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-Mn(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=n.input.prepareSelection())}function $r(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!p){var o=A("div","​",null,"position: absolute;\n top: "+(t.top-n.viewOffset-Cn(e.display))+"px;\n height: "+(t.bottom-t.top+Tn(e)+n.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(i),e.display.lineSpace.removeChild(o)}}}(t,function(e,t,n,r){var i;null==r&&(r=0),e.options.lineWrapping||t!=n||(n="before"==(t=t.ch?et(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t).sticky?et(t.line,t.ch+1,"before"):t);for(var o=0;o<5;o++){var a=!1,l=qn(e,t),s=n&&n!=t?qn(e,n):l,c=Mr(e,i={left:Math.min(l.left,s.left),top:Math.min(l.top,s.top)-r,right:Math.max(l.left,s.left),bottom:Math.max(l.bottom,s.bottom)+r}),u=e.doc.scrollTop,f=e.doc.scrollLeft;if(null!=c.scrollTop&&(Pr(e,c.scrollTop),Math.abs(e.doc.scrollTop-u)>1&&(a=!0)),null!=c.scrollLeft&&(zr(e,c.scrollLeft),Math.abs(e.doc.scrollLeft-f)>1&&(a=!0)),!a)break}return i}(t,lt(r,e.scrollToPos.from),lt(r,e.scrollToPos.to),e.scrollToPos.margin));var i=e.maybeHiddenMarkers,o=e.maybeUnhiddenMarkers;if(i)for(var a=0;a=e.display.viewTo)){var n=+new Date+e.options.workTime,r=dt(e,t.highlightFrontier),i=[];t.iter(r.line,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(r.line>=e.display.viewFrom){var a=o.styles,l=o.text.length>e.options.maxHighlightLength?je(t.mode,r.state):null,s=ft(e,o,r,!0);l&&(r.state=l),o.styles=s.styles;var c=o.styleClasses,u=s.classes;u?o.styleClasses=u:c&&(o.styleClasses=null);for(var f=!a||a.length!=o.styles.length||c!=u&&(!c||!u||c.bgClass!=u.bgClass||c.textClass!=u.textClass),h=0;!f&&hn)return ei(e,e.options.workDelay),!0}),t.highlightFrontier=r.line,t.modeFrontier=Math.max(t.modeFrontier,r.line),i.length&&Yr(e,function(){for(var t=0;t=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==dr(e))return!1;ci(e)&&(fr(e),t.dims=rr(e));var i=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),a=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFroma&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo)),kt&&(o=Rt(e.doc,o),a=_t(e.doc,a));var l=o!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;!function(e,t,n){var r=e.display;0==r.view.length||t>=r.viewTo||n<=r.viewFrom?(r.view=on(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=on(e,t,r.viewFrom).concat(r.view):r.viewFromn&&(r.view=r.view.slice(0,sr(e,n)))),r.viewTo=n}(e,o,a),n.viewOffset=Ut(Ge(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var c=dr(e);if(!l&&0==c&&!t.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=function(e){if(e.hasFocus())return null;var t=E();if(!t||!D(e.display.lineDiv,t))return null;var n={activeElt:t};if(window.getSelection){var r=window.getSelection();r.anchorNode&&r.extend&&D(e.display.lineDiv,r.anchorNode)&&(n.anchorNode=r.anchorNode,n.anchorOffset=r.anchorOffset,n.focusNode=r.focusNode,n.focusOffset=r.focusOffset)}return n}(e);return c>4&&(n.lineDiv.style.display="none"),function(e,t,n){var r=e.display,i=e.options.lineNumbers,o=r.lineDiv,a=o.firstChild;function l(t){var n=t.nextSibling;return s&&y&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var c=r.view,u=r.viewFrom,f=0;f-1&&(d=!1),un(e,h,u,n)),d&&(M(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(Je(e.options,u)))),a=h.node.nextSibling}else{var p=vn(e,h,u,n);o.insertBefore(p,a)}u+=h.size}for(;a;)a=l(a)}(e,n.updateLineNumbers,t.dims),c>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,function(e){if(e&&e.activeElt&&e.activeElt!=E()&&(e.activeElt.focus(),e.anchorNode&&D(document.body,e.anchorNode)&&D(document.body,e.focusNode))){var t=window.getSelection(),n=document.createRange();n.setEnd(e.anchorNode,e.anchorOffset),n.collapse(!1),t.removeAllRanges(),t.addRange(n),t.extend(e.focusNode,e.focusOffset)}}(u),M(n.cursorDiv),M(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,l&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,ei(e,400)),n.updateLineNumbers=null,!0}function ii(e,t){for(var n=t.viewport,r=!0;;r=!1){if(r&&e.options.lineWrapping&&t.oldDisplayWidth!=Mn(e))r&&(t.visible=Tr(e.display,e.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(e.doc.height+Sn(e.display)-Nn(e),n.top)}),t.visible=Tr(e.display,e.doc,n),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!ri(e,t))break;Sr(e);var i=Ir(e);pr(e),Rr(e,i),li(e,i),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function oi(e,t){var n=new ni(e,t);if(ri(e,n)){Sr(e),ii(e,n);var r=Ir(e);pr(e),Rr(e,r),li(e,r),n.finish()}}function ai(e){var t=e.gutters.offsetWidth;e.sizer.style.marginLeft=t+"px"}function li(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Tn(e)+"px"}function si(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=ir(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",a=0;al.clientWidth,u=l.scrollHeight>l.clientHeight;if(i&&c||o&&u){if(o&&y&&s)e:for(var h=t.target,d=a.view;h!=l;h=h.parentNode)for(var p=0;p=0&&tt(e,r.to())<=0)return n}return-1};var bi=function(e,t){this.anchor=e,this.head=t};function xi(e,t,n){var r=e&&e.options.selectionsMayTouch,i=t[n];t.sort(function(e,t){return tt(e.from(),t.from())}),n=_(t,i);for(var o=1;o0:s>=0){var c=ot(l.from(),a.from()),u=it(l.to(),a.to()),f=l.empty()?a.from()==a.head:l.from()==l.head;o<=n&&--n,t.splice(--o,2,new bi(f?u:c,f?c:u))}}return new yi(t,n)}function wi(e,t){return new yi([new bi(e,t||e)],0)}function ki(e){return e.text?et(e.from.line+e.text.length-1,X(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function Ci(e,t){if(tt(e,t.from)<0)return e;if(tt(e,t.to)<=0)return ki(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=ki(t).ch-t.to.ch),et(n,r)}function Si(e,t){for(var n=[],r=0;r1&&e.remove(l.line+1,p-1),e.insert(l.line+1,v)}sn(e,"change",e,t)}function Oi(e,t,n){!function e(r,i,o){if(r.linked)for(var a=0;al-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(o=function(e,t){return t?(zi(e.done),X(e.done)):e.done.length&&!X(e.done).ranges?X(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),X(e.done)):void 0}(i,i.lastOp==r)))a=X(o.changes),0==tt(t.from,t.to)&&0==tt(t.from,a.to)?a.to=ki(t):o.changes.push(Wi(e,t));else{var s=X(i.done);for(s&&s.ranges||Hi(e.sel,i.done),o={changes:[Wi(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=l,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,a||ge(e,"historyAdded")}function Fi(e,t,n,r){var i=e.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||function(e,t,n,r){var i=t.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}(e,o,X(i.done),t))?i.done[i.done.length-1]=t:Hi(t,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=n,r&&!1!==r.clearRedo&&zi(i.undone)}function Hi(e,t){var n=X(t);n&&n.ranges&&n.equals(e)||t.push(e)}function Ri(e,t,n,r){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=n.markedSpans),++o})}function _i(e){if(!e)return null;for(var t,n=0;n-1&&(X(l)[f]=c[f],delete c[f])}}}return r}function Ui(e,t,n,r){if(r){var i=e.anchor;if(n){var o=tt(t,i)<0;o!=tt(n,i)<0?(i=t,t=n):o!=tt(t,n)<0&&(t=n)}return new bi(i,t)}return new bi(n||t,t)}function Vi(e,t,n,r,i){null==i&&(i=e.cm&&(e.cm.display.shift||e.extend)),Xi(e,new yi([Ui(e.sel.primary(),t,n,i)],0),r)}function Ki(e,t,n){for(var r=[],i=e.cm&&(e.cm.display.shift||e.extend),o=0;o=t.ch:l.to>t.ch))){if(i&&(ge(s,"beforeCursorEnter"),s.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!s.atomic)continue;if(n){var f=s.find(r<0?1:-1),h=void 0;if((r<0?u:c)&&(f=no(e,f,-r,f&&f.line==t.line?o:null)),f&&f.line==t.line&&(h=tt(f,n))&&(r<0?h<0:h>0))return eo(e,f,t,r,i)}var d=s.find(r<0?-1:1);return(r<0?c:u)&&(d=no(e,d,r,d.line==t.line?o:null)),d?eo(e,d,t,r,i):null}}return t}function to(e,t,n,r,i){var o=r||1,a=eo(e,t,n,o,i)||!i&&eo(e,t,n,o,!0)||eo(e,t,n,-o,i)||!i&&eo(e,t,n,-o,!0);return a||(e.cantEdit=!0,et(e.first,0))}function no(e,t,n,r){return n<0&&0==t.ch?t.line>e.first?lt(e,et(t.line-1)):null:n>0&&t.ch==(r||Ge(e,t.line)).text.length?t.line0)){var u=[s,1],f=tt(c.from,l.from),h=tt(c.to,l.to);(f<0||!a.inclusiveLeft&&!f)&&u.push({from:c.from,to:l.from}),(h>0||!a.inclusiveRight&&!h)&&u.push({from:l.to,to:c.to}),i.splice.apply(i,u),s+=u.length-3}}return i}(e,t.from,t.to);if(r)for(var i=r.length-1;i>=0;--i)ao(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text,origin:t.origin});else ao(e,t)}}function ao(e,t){if(1!=t.text.length||""!=t.text[0]||0!=tt(t.from,t.to)){var n=Si(e,t);Ii(e,t,n,e.cm?e.cm.curOp.id:NaN),co(e,t,n,Tt(e,t));var r=[];Oi(e,function(e,n){n||-1!=_(r,e.history)||(po(e.history,t),r.push(e.history)),co(e,t,null,Tt(e,t))})}}function lo(e,t,n){var r=e.cm&&e.cm.state.suppressEdits;if(!r||n){for(var i,o=e.history,a=e.sel,l="undo"==t?o.done:o.undone,s="undo"==t?o.undone:o.done,c=0;c=0;--d){var p=h(d);if(p)return p.v}}}}function so(e,t){if(0!=t&&(e.first+=t,e.sel=new yi(Y(e.sel.ranges,function(e){return new bi(et(e.anchor.line+t,e.anchor.ch),et(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){cr(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;re.lastLine())){if(t.from.lineo&&(t={from:t.from,to:et(o,Ge(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=qe(e,t.from,t.to),n||(n=Si(e,t)),e.cm?function(e,t,n){var r=e.doc,i=e.display,o=t.from,a=t.to,l=!1,s=o.line;e.options.lineWrapping||(s=Ye(Ht(Ge(r,o.line))),r.iter(s,a.line+1,function(e){if(e==i.maxLine)return l=!0,!0}));r.sel.contains(t.from,t.to)>-1&&ve(e);Ai(r,t,n,or(e)),e.options.lineWrapping||(r.iter(s,o.line+t.text.length,function(e){var t=Vt(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)}),l&&(e.curOp.updateMaxLine=!0));(function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontiern;r--){var i=Ge(e,r).stateAfter;if(i&&(!(i instanceof ct)||r+i.lookAhead1||!(this.children[0]instanceof mo))){var l=[];this.collapse(l),this.children=[new mo(l)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t50){for(var a=i.lines.length%25+25,l=a;l10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=0;r0||0==a&&!1!==o.clearWhenEmpty)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=O("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true"),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Ft(e,t.line,t,n,o)||t.line!=n.line&&Ft(e,n.line,t,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");kt=!0}o.addToHistory&&Ii(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var l,s=t.line,c=e.cm;if(e.iter(s,n.line+1,function(e){c&&o.collapsed&&!c.options.lineWrapping&&Ht(e)==c.display.maxLine&&(l=!0),o.collapsed&&s!=t.line&&Xe(e,0),function(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}(e,new Ct(o,s==t.line?t.ch:null,s==n.line?n.ch:null)),++s}),o.collapsed&&e.iter(t.line,n.line+1,function(t){Bt(e,t)&&Xe(t,0)}),o.clearOnEnter&&he(o,"beforeCursorEnter",function(){return o.clear()}),o.readOnly&&(wt=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++xo,o.atomic=!0),c){if(l&&(c.curOp.updateMaxLine=!0),o.collapsed)cr(c,t.line,n.line+1);else if(o.className||o.startStyle||o.endStyle||o.css||o.attributes||o.title)for(var u=t.line;u<=n.line;u++)ur(c,u,"text");o.atomic&&Qi(c.doc),sn(c,"markerAdded",c,o)}return o}wo.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Vr(e),ye(this,"clear")){var n=this.find();n&&sn(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;oe.display.maxLineLength&&(e.display.maxLine=c,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=r&&e&&this.collapsed&&cr(e,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&Qi(e.doc)),e&&sn(e,"markerCleared",e,this,r,i),t&&Kr(e),this.parent&&this.parent.clear()}},wo.prototype.find=function(e,t){var n,r;null==e&&"bookmark"==this.type&&(e=1);for(var i=0;i=0;s--)oo(this,r[s]);l?$i(this,l):this.cm&&Ar(this.cm)}),undo:Jr(function(){lo(this,"undo")}),redo:Jr(function(){lo(this,"redo")}),undoSelection:Jr(function(){lo(this,"undo",!0)}),redoSelection:Jr(function(){lo(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=lt(this,e),t=lt(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,function(o){var a=o.markedSpans;if(a)for(var l=0;l=s.to||null==s.from&&i!=e.line||null!=s.from&&i==t.line&&s.from>=t.ch||n&&!n(s.marker)||r.push(s.marker.parent||s.marker)}++i}),r},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var r=0;re)return t=e,!0;e-=o,++n}),lt(this,et(n,t))},indexFromPos:function(e){var t=(e=lt(this,e)).ch;if(e.linet&&(t=e.from),null!=e.to&&e.to-1)return t.state.draggingText(e),void setTimeout(function(){return t.display.input.focus()},20);try{var f=e.dataTransfer.getData("Text");if(f){var h;if(t.state.draggingText&&!t.state.draggingText.copy&&(h=t.listSelections()),Yi(t.doc,wi(n,n)),h)for(var d=0;d=0;t--)uo(e.doc,"",r[t].from,r[t].to,"+delete");Ar(e)})}function $o(e,t,n){var r=oe(e.text,t+n,n);return r<0||r>e.text.length?null:r}function Xo(e,t,n){var r=$o(e,t.ch,n);return null==r?null:new et(t.line,r,n<0?"after":"before")}function Yo(e,t,n,r,i){if(e){"rtl"==t.doc.direction&&(i=-i);var o=ue(n,t.doc.direction);if(o){var a,l=i<0?X(o):o[0],s=i<0==(1==l.level)?"after":"before";if(l.level>0||"rtl"==t.doc.direction){var c=En(t,n);a=i<0?n.text.length-1:0;var u=Pn(t,c,a).top;a=ae(function(e){return Pn(t,c,e).top==u},i<0==(1==l.level)?l.from:l.to-1,a),"before"==s&&(a=$o(n,a,1))}else a=i<0?l.to:l.from;return new et(r,a,s)}}return new et(r,i<0?n.text.length:0,i<0?"before":"after")}Ro.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Ro.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Ro.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Ro.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Ro.default=y?Ro.macDefault:Ro.pcDefault;var Zo={selectAll:ro,singleSelection:function(e){return e.setSelection(e.getCursor("anchor"),e.getCursor("head"),U)},killLine:function(e){return qo(e,function(t){if(t.empty()){var n=Ge(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line0)i=new et(i.line,i.ch+1),e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),et(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var a=Ge(e.doc,i.line-1).text;a&&(i=new et(i.line,1),e.replaceRange(o.charAt(0)+e.doc.lineSeparator()+a.charAt(a.length-1),et(i.line-1,a.length-1),i,"+transpose"))}n.push(new bi(i,i))}e.setSelections(n)})},newlineAndIndent:function(e){return Yr(e,function(){for(var t=e.listSelections(),n=t.length-1;n>=0;n--)e.replaceRange(e.doc.lineSeparator(),t[n].anchor,t[n].head,"+input");t=e.listSelections();for(var r=0;r-1&&(tt((i=c.ranges[i]).from(),t)<0||t.xRel>0)&&(tt(i.to(),t)>0||t.xRel<0)?function(e,t,n,r){var i=e.display,o=!1,c=Zr(e,function(t){s&&(i.scroller.draggable=!1),e.state.draggingText=!1,pe(i.wrapper.ownerDocument,"mouseup",c),pe(i.wrapper.ownerDocument,"mousemove",u),pe(i.scroller,"dragstart",f),pe(i.scroller,"drop",c),o||(xe(t),r.addNew||Vi(e.doc,n,null,null,r.extend),s||a&&9==l?setTimeout(function(){i.wrapper.ownerDocument.body.focus(),i.input.focus()},20):i.input.focus())}),u=function(e){o=o||Math.abs(t.clientX-e.clientX)+Math.abs(t.clientY-e.clientY)>=10},f=function(){return o=!0};s&&(i.scroller.draggable=!0);e.state.draggingText=c,c.copy=!r.moveOnDrag,i.scroller.dragDrop&&i.scroller.dragDrop();he(i.wrapper.ownerDocument,"mouseup",c),he(i.wrapper.ownerDocument,"mousemove",u),he(i.scroller,"dragstart",f),he(i.scroller,"drop",c),wr(e),setTimeout(function(){return i.input.focus()},20)}(e,r,t,o):function(e,t,n,r){var i=e.display,o=e.doc;xe(t);var a,l,s=o.sel,c=s.ranges;r.addNew&&!r.extend?(l=o.sel.contains(n),a=l>-1?c[l]:new bi(n,n)):(a=o.sel.primary(),l=o.sel.primIndex);if("rectangle"==r.unit)r.addNew||(a=new bi(n,n)),n=lr(e,t,!0,!0),l=-1;else{var u=da(e,n,r.unit);a=r.extend?Ui(a,u.anchor,u.head,r.extend):u}r.addNew?-1==l?(l=c.length,Xi(o,xi(e,c.concat([a]),l),{scroll:!1,origin:"*mouse"})):c.length>1&&c[l].empty()&&"char"==r.unit&&!r.extend?(Xi(o,xi(e,c.slice(0,l).concat(c.slice(l+1)),0),{scroll:!1,origin:"*mouse"}),s=o.sel):Gi(o,l,a,V):(l=0,Xi(o,new yi([a],0),V),s=o.sel);var f=n;function h(t){if(0!=tt(f,t))if(f=t,"rectangle"==r.unit){for(var i=[],c=e.options.tabSize,u=H(Ge(o,n.line).text,n.ch,c),h=H(Ge(o,t.line).text,t.ch,c),d=Math.min(u,h),p=Math.max(u,h),g=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));g<=m;g++){var v=Ge(o,g).text,y=G(v,d,c);d==p?i.push(new bi(et(g,y),et(g,y))):v.length>y&&i.push(new bi(et(g,y),et(g,G(v,p,c))))}i.length||i.push(new bi(n,n)),Xi(o,xi(e,s.ranges.slice(0,l).concat(i),l),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var b,x=a,w=da(e,t,r.unit),k=x.anchor;tt(w.anchor,k)>0?(b=w.head,k=ot(x.from(),w.anchor)):(b=w.anchor,k=it(x.to(),w.head));var C=s.ranges.slice(0);C[l]=function(e,t){var n=t.anchor,r=t.head,i=Ge(e.doc,n.line);if(0==tt(n,r)&&n.sticky==r.sticky)return t;var o=ue(i);if(!o)return t;var a=se(o,n.ch,n.sticky),l=o[a];if(l.from!=n.ch&&l.to!=n.ch)return t;var s,c=a+(l.from==n.ch==(1!=l.level)?0:1);if(0==c||c==o.length)return t;if(r.line!=n.line)s=(r.line-n.line)*("ltr"==e.doc.direction?1:-1)>0;else{var u=se(o,r.ch,r.sticky),f=u-a||(r.ch-n.ch)*(1==l.level?-1:1);s=u==c-1||u==c?f<0:f>0}var h=o[c+(s?-1:0)],d=s==(1==h.level),p=d?h.from:h.to,g=d?"after":"before";return n.ch==p&&n.sticky==g?t:new bi(new et(n.line,p,g),r)}(e,new bi(lt(o,k),b)),Xi(o,xi(e,C,l),V)}}var d=i.wrapper.getBoundingClientRect(),p=0;function g(t){e.state.selectingText=!1,p=1/0,t&&(xe(t),i.input.focus()),pe(i.wrapper.ownerDocument,"mousemove",m),pe(i.wrapper.ownerDocument,"mouseup",v),o.history.lastSelOrigin=null}var m=Zr(e,function(t){0!==t.buttons&&Le(t)?function t(n){var a=++p;var l=lr(e,n,!0,"rectangle"==r.unit);if(!l)return;if(0!=tt(l,f)){e.curOp.focus=E(),h(l);var s=Tr(i,o);(l.line>=s.to||l.lined.bottom?20:0;c&&setTimeout(Zr(e,function(){p==a&&(i.scroller.scrollTop+=c,t(n))}),50)}}(t):g(t)}),v=Zr(e,g);e.state.selectingText=v,he(i.wrapper.ownerDocument,"mousemove",m),he(i.wrapper.ownerDocument,"mouseup",v)}(e,r,t,o)}(t,r,o,e):Se(e)==n.scroller&&xe(e):2==i?(r&&Vi(t.doc,r),setTimeout(function(){return n.input.focus()},20)):3==i&&(C?t.display.input.onContextMenu(e):wr(t)))}}function da(e,t,n){if("char"==n)return new bi(t,t);if("word"==n)return e.findWordAt(t);if("line"==n)return new bi(et(t.line,0),lt(e.doc,et(t.line+1,0)));var r=n(e,t);return new bi(r.from,r.to)}function pa(e,t,n,r){var i,o;if(t.touches)i=t.touches[0].clientX,o=t.touches[0].clientY;else try{i=t.clientX,o=t.clientY}catch(t){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&xe(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(o>l.bottom||!ye(e,n))return ke(t);o-=l.top-a.viewOffset;for(var s=0;s=i)return ge(e,n,e,Ze(e.doc,o),e.display.gutterSpecs[s].className,t),ke(t)}}function ga(e,t){return pa(e,t,"gutterClick",!0)}function ma(e,t){kn(e.display,t)||function(e,t){if(!ye(e,"gutterContextMenu"))return!1;return pa(e,t,"gutterContextMenu",!1)}(e,t)||me(e,t,"contextmenu")||C||e.display.input.onContextMenu(t)}function va(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),_n(e)}fa.prototype.compare=function(e,t,n){return this.time+400>e&&0==tt(t,this.pos)&&n==this.button};var ya={toString:function(){return"CodeMirror.Init"}},ba={},xa={};function wa(e,t,n){if(!t!=!(n&&n!=ya)){var r=e.display.dragFunctions,i=t?he:pe;i(e.display.scroller,"dragstart",r.start),i(e.display.scroller,"dragenter",r.enter),i(e.display.scroller,"dragover",r.over),i(e.display.scroller,"dragleave",r.leave),i(e.display.scroller,"drop",r.drop)}}function ka(e){e.options.lineWrapping?(P(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(T(e.display.wrapper,"CodeMirror-wrap"),Kt(e)),ar(e),cr(e),_n(e),setTimeout(function(){return Rr(e)},100)}function Ca(e,t){var r=this;if(!(this instanceof Ca))return new Ca(e,t);this.options=t=t?F(t):{},F(ba,t,!1);var i=t.value;"string"==typeof i?i=new Mo(i,t.mode,null,t.lineSeparator,t.direction):t.mode&&(i.modeOption=t.mode),this.doc=i;var o=new Ca.inputStyles[t.inputStyle](this),c=this.display=new function(e,t,r,i){var o=this;this.input=r,o.scrollbarFiller=A("div",null,"CodeMirror-scrollbar-filler"),o.scrollbarFiller.setAttribute("cm-not-content","true"),o.gutterFiller=A("div",null,"CodeMirror-gutter-filler"),o.gutterFiller.setAttribute("cm-not-content","true"),o.lineDiv=O("div",null,"CodeMirror-code"),o.selectionDiv=A("div",null,null,"position: relative; z-index: 1"),o.cursorDiv=A("div",null,"CodeMirror-cursors"),o.measure=A("div",null,"CodeMirror-measure"),o.lineMeasure=A("div",null,"CodeMirror-measure"),o.lineSpace=O("div",[o.measure,o.lineMeasure,o.selectionDiv,o.cursorDiv,o.lineDiv],null,"position: relative; outline: none");var c=O("div",[o.lineSpace],"CodeMirror-lines");o.mover=A("div",[c],null,"position: relative"),o.sizer=A("div",[o.mover],"CodeMirror-sizer"),o.sizerWidth=null,o.heightForcer=A("div",null,null,"position: absolute; height: "+B+"px; width: 1px;"),o.gutters=A("div",null,"CodeMirror-gutters"),o.lineGutter=null,o.scroller=A("div",[o.sizer,o.heightForcer,o.gutters],"CodeMirror-scroll"),o.scroller.setAttribute("tabIndex","-1"),o.wrapper=A("div",[o.scrollbarFiller,o.gutterFiller,o.scroller],"CodeMirror"),a&&l<8&&(o.gutters.style.zIndex=-1,o.scroller.style.paddingRight=0),s||n&&v||(o.scroller.draggable=!0),e&&(e.appendChild?e.appendChild(o.wrapper):e(o.wrapper)),o.viewFrom=o.viewTo=t.first,o.reportedViewFrom=o.reportedViewTo=t.first,o.view=[],o.renderedView=null,o.externalMeasured=null,o.viewOffset=0,o.lastWrapHeight=o.lastWrapWidth=0,o.updateLineNumbers=null,o.nativeBarWidth=o.barHeight=o.barWidth=0,o.scrollbarsClipped=!1,o.lineNumWidth=o.lineNumInnerWidth=o.lineNumChars=null,o.alignWidgets=!1,o.cachedCharWidth=o.cachedTextHeight=o.cachedPaddingH=null,o.maxLine=null,o.maxLineLength=0,o.maxLineChanged=!1,o.wheelDX=o.wheelDY=o.wheelStartX=o.wheelStartY=null,o.shift=!1,o.selForContextMenu=null,o.activeTouch=null,o.gutterSpecs=ui(i.gutters,i.lineNumbers),fi(o),r.init(o)}(e,i,o,t);for(var u in c.wrapper.CodeMirror=this,va(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),jr(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new R,keySeq:null,specialChars:null},t.autofocus&&!v&&c.input.focus(),a&&l<11&&setTimeout(function(){return r.display.input.reset(!0)},20),function(e){var t=e.display;he(t.scroller,"mousedown",Zr(e,ha)),he(t.scroller,"dblclick",a&&l<11?Zr(e,function(t){if(!me(e,t)){var n=lr(e,t);if(n&&!ga(e,t)&&!kn(e.display,t)){xe(t);var r=e.findWordAt(n);Vi(e.doc,r.anchor,r.head)}}}):function(t){return me(e,t)||xe(t)});he(t.scroller,"contextmenu",function(t){return ma(e,t)}),he(t.input.getField(),"contextmenu",function(n){t.scroller.contains(n.target)||ma(e,n)});var n,r={end:0};function i(){t.activeTouch&&(n=setTimeout(function(){return t.activeTouch=null},1e3),(r=t.activeTouch).end=+new Date)}function o(e,t){if(null==t.left)return!0;var n=t.left-e.left,r=t.top-e.top;return n*n+r*r>400}he(t.scroller,"touchstart",function(i){if(!me(e,i)&&!function(e){if(1!=e.touches.length)return!1;var t=e.touches[0];return t.radiusX<=1&&t.radiusY<=1}(i)&&!ga(e,i)){t.input.ensurePolled(),clearTimeout(n);var o=+new Date;t.activeTouch={start:o,moved:!1,prev:o-r.end<=300?r:null},1==i.touches.length&&(t.activeTouch.left=i.touches[0].pageX,t.activeTouch.top=i.touches[0].pageY)}}),he(t.scroller,"touchmove",function(){t.activeTouch&&(t.activeTouch.moved=!0)}),he(t.scroller,"touchend",function(n){var r=t.activeTouch;if(r&&!kn(t,n)&&null!=r.left&&!r.moved&&new Date-r.start<300){var a,l=e.coordsChar(t.activeTouch,"page");a=!r.prev||o(r,r.prev)?new bi(l,l):!r.prev.prev||o(r,r.prev.prev)?e.findWordAt(l):new bi(et(l.line,0),lt(e.doc,et(l.line+1,0))),e.setSelection(a.anchor,a.head),e.focus(),xe(n)}i()}),he(t.scroller,"touchcancel",i),he(t.scroller,"scroll",function(){t.scroller.clientHeight&&(Pr(e,t.scroller.scrollTop),zr(e,t.scroller.scrollLeft,!0),ge(e,"scroll",e))}),he(t.scroller,"mousewheel",function(t){return vi(e,t)}),he(t.scroller,"DOMMouseScroll",function(t){return vi(e,t)}),he(t.wrapper,"scroll",function(){return t.wrapper.scrollTop=t.wrapper.scrollLeft=0}),t.dragFunctions={enter:function(t){me(e,t)||Ce(t)},over:function(t){me(e,t)||(!function(e,t){var n=lr(e,t);if(n){var r=document.createDocumentFragment();mr(e,n,r),e.display.dragCursor||(e.display.dragCursor=A("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),e.display.lineSpace.insertBefore(e.display.dragCursor,e.display.cursorDiv)),N(e.display.dragCursor,r)}}(e,t),Ce(t))},start:function(t){return function(e,t){if(a&&(!e.state.draggingText||+new Date-No<100))Ce(t);else if(!me(e,t)&&!kn(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setDragImage&&!h)){var n=A("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",f&&(n.width=n.height=1,e.display.wrapper.appendChild(n),n._top=n.offsetTop),t.dataTransfer.setDragImage(n,0,0),f&&n.parentNode.removeChild(n)}}(e,t)},drop:Zr(e,Ao),leave:function(t){me(e,t)||Oo(e)}};var s=t.input.getField();he(s,"keyup",function(t){return la.call(e,t)}),he(s,"keydown",Zr(e,aa)),he(s,"keypress",Zr(e,sa)),he(s,"focus",function(t){return kr(e,t)}),he(s,"blur",function(t){return Cr(e,t)})}(this),Po(),Vr(this),this.curOp.forceUpdate=!0,Di(this,i),t.autofocus&&!v||this.hasFocus()?setTimeout(I(kr,this),20):Cr(this),xa)xa.hasOwnProperty(u)&&xa[u](r,t[u],ya);ci(this),t.finishInit&&t.finishInit(this);for(var d=0;d150)){if(!r)return;n="prev"}}else c=0,n="not";"prev"==n?c=t>o.first?H(Ge(o,t-1).text,null,a):0:"add"==n?c=s+e.options.indentUnit:"subtract"==n?c=s-e.options.indentUnit:"number"==typeof n&&(c=s+n),c=Math.max(0,c);var f="",h=0;if(e.options.indentWithTabs)for(var d=Math.floor(c/a);d;--d)h+=a,f+="\t";if(ha,s=Ee(t),c=null;if(l&&r.ranges.length>1)if(Ta&&Ta.text.join("\n")==t){if(r.ranges.length%Ta.text.length==0){c=[];for(var u=0;u=0;h--){var d=r.ranges[h],p=d.from(),g=d.to();d.empty()&&(n&&n>0?p=et(p.line,p.ch-n):e.state.overwrite&&!l?g=et(g.line,Math.min(Ge(o,g.line).text.length,g.ch+X(s).length)):l&&Ta&&Ta.lineWise&&Ta.text.join("\n")==t&&(p=g=et(p.line,0)));var m={from:p,to:g,text:c?c[h%c.length]:s,origin:i||(l?"paste":e.state.cutIncoming>a?"cut":"+input")};oo(e.doc,m),sn(e,"inputRead",e,m)}t&&!l&&Oa(e,t),Ar(e),e.curOp.updateInput<2&&(e.curOp.updateInput=f),e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=-1}function Aa(e,t){var n=e.clipboardData&&e.clipboardData.getData("Text");if(n)return e.preventDefault(),t.isReadOnly()||t.options.disableInput||Yr(t,function(){return Na(t,n,0,null,"paste")}),!0}function Oa(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var n=e.doc.sel,r=n.ranges.length-1;r>=0;r--){var i=n.ranges[r];if(!(i.head.ch>100||r&&n.ranges[r-1].head.line==i.head.line)){var o=e.getModeAt(i.head),a=!1;if(o.electricChars){for(var l=0;l-1){a=La(e,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(Ge(e.doc,i.head.line).text.slice(0,i.head.ch))&&(a=La(e,i.head.line,"smart"));a&&sn(e,"electricInput",e,i.head.line)}}}function Da(e){for(var t=[],n=[],r=0;r=t.text.length?(n.ch=t.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var o=se(i,n.ch,n.sticky),a=i[o];if("ltr"==e.doc.direction&&a.level%2==0&&(r>0?a.to>n.ch:a.from=a.from&&h>=u.begin)){var d=f?"before":"after";return new et(n.line,h,d)}}var p=function(e,t,r){for(var o=function(e,t){return t?new et(n.line,s(e,1),"before"):new et(n.line,e,"after")};e>=0&&e0==(1!=a.level),c=l?r.begin:s(r.end,-1);if(a.from<=c&&c0?u.end:s(u.begin,-1);return null==m||r>0&&m==t.text.length||!(g=p(r>0?0:i.length-1,r,c(m)))?null:g}(e.cm,l,t,n):Xo(l,t,n))){if(r||(a=t.line+s)=e.first+e.size||(t=new et(a,t.ch,t.sticky),!(l=Ge(e,a))))return!1;t=Yo(i,e.cm,l,t.line,s)}else t=o;return!0}if("char"==r)c();else if("column"==r)c(!0);else if("word"==r||"group"==r)for(var u=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),d=!0;!(n<0)||c(!d);d=!1){var p=l.text.charAt(t.ch)||"\n",g=te(p,h)?"w":f&&"\n"==p?"n":!f||/\s/.test(p)?null:"p";if(!f||d||g||(g="s"),u&&u!=g){n<0&&(n=1,c(),t.sticky="after");break}if(g&&(u=g),n>0&&!c(!d))break}var m=to(e,t,o,a,!0);return nt(o,m)&&(m.hitSide=!0),m}function za(e,t,n,r){var i,o,a=e.doc,l=t.left;if("page"==r){var s=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),c=Math.max(s-.5*tr(e.display),3);i=(n>0?t.bottom:t.top)+n*c}else"line"==r&&(i=n>0?t.bottom+3:t.top-3);for(;(o=Yn(e,l,i)).outside;){if(n<0?i<=0:i>=a.height){o.hitSide=!0;break}i+=5*n}return o}var Ia=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new R,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function Fa(e,t){var n=Dn(e,t.line);if(!n||n.hidden)return null;var r=Ge(e.doc,t.line),i=An(n,r,t.line),o=ue(r,e.doc.direction),a="left";o&&(a=se(o,t.ch)%2?"right":"left");var l=In(i.map,t.ch,a);return l.offset="right"==l.collapse?l.end:l.start,l}function Ha(e,t){return t&&(e.bad=!0),e}function Ra(e,t,n){var r;if(t==e.display.lineDiv){if(!(r=e.display.lineDiv.childNodes[n]))return Ha(e.clipPos(et(e.display.viewTo-1)),!0);t=null,n=0}else for(r=t;;r=r.parentNode){if(!r||r==e.display.lineDiv)return null;if(r.parentNode&&r.parentNode==e.display.lineDiv)break}for(var i=0;i=t.display.viewTo||o.line=t.display.viewFrom&&Fa(t,i)||{node:s[0].measure.map[2],offset:0},u=o.liner.firstLine()&&(a=et(a.line-1,Ge(r.doc,a.line-1).length)),l.ch==Ge(r.doc,l.line).text.length&&l.linei.viewTo-1)return!1;a.line==i.viewFrom||0==(e=sr(r,a.line))?(t=Ye(i.view[0].line),n=i.view[0].node):(t=Ye(i.view[e].line),n=i.view[e-1].node.nextSibling);var s,c,u=sr(r,l.line);if(u==i.view.length-1?(s=i.viewTo-1,c=i.lineDiv.lastChild):(s=Ye(i.view[u+1].line)-1,c=i.view[u+1].node.previousSibling),!n)return!1;for(var f=r.doc.splitLines(function(e,t,n,r,i){var o="",a=!1,l=e.doc.lineSeparator(),s=!1;function c(){a&&(o+=l,s&&(o+=l),a=s=!1)}function u(e){e&&(c(),o+=e)}function f(t){if(1==t.nodeType){var n=t.getAttribute("cm-text");if(n)return void u(n);var o,h=t.getAttribute("cm-marker");if(h){var d=e.findMarks(et(r,0),et(i+1,0),(m=+h,function(e){return e.id==m}));return void(d.length&&(o=d[0].find(0))&&u(qe(e.doc,o.from,o.to).join(l)))}if("false"==t.getAttribute("contenteditable"))return;var p=/^(pre|div|p|li|table|br)$/i.test(t.nodeName);if(!/^br$/i.test(t.nodeName)&&0==t.textContent.length)return;p&&c();for(var g=0;g1&&h.length>1;)if(X(f)==X(h))f.pop(),h.pop(),s--;else{if(f[0]!=h[0])break;f.shift(),h.shift(),t++}for(var d=0,p=0,g=f[0],m=h[0],v=Math.min(g.length,m.length);da.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)d--,p++;f[f.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),f[0]=f[0].slice(d).replace(/\u200b+$/,"");var w=et(t,d),k=et(s,h.length?X(h).length-p:0);return f.length>1||f[0]||tt(w,k)?(uo(r.doc,f,w,k,"+input"),!0):void 0},Ia.prototype.ensurePolled=function(){this.forceCompositionEnd()},Ia.prototype.reset=function(){this.forceCompositionEnd()},Ia.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},Ia.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()},80))},Ia.prototype.updateFromDOM=function(){var e=this;!this.cm.isReadOnly()&&this.pollContent()||Yr(this.cm,function(){return cr(e.cm)})},Ia.prototype.setUneditable=function(e){e.contentEditable="false"},Ia.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly()||Zr(this.cm,Na)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},Ia.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},Ia.prototype.onContextMenu=function(){},Ia.prototype.resetPosition=function(){},Ia.prototype.needsContentAttribute=!0;var Ba=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new R,this.hasSelection=!1,this.composing=null};Ba.prototype.init=function(e){var t=this,n=this,r=this.cm;this.createField(e);var i=this.textarea;function o(e){if(!me(r,e)){if(r.somethingSelected())Ma({lineWise:!1,text:r.getSelections()});else{if(!r.options.lineWiseCopyCut)return;var t=Da(r);Ma({lineWise:!0,text:t.text}),"cut"==e.type?r.setSelections(t.ranges,null,U):(n.prevInput="",i.value=t.text.join("\n"),z(i))}"cut"==e.type&&(r.state.cutIncoming=+new Date)}}e.wrapper.insertBefore(this.wrapper,e.wrapper.firstChild),g&&(i.style.width="0px"),he(i,"input",function(){a&&l>=9&&t.hasSelection&&(t.hasSelection=null),n.poll()}),he(i,"paste",function(e){me(r,e)||Aa(e,r)||(r.state.pasteIncoming=+new Date,n.fastPoll())}),he(i,"cut",o),he(i,"copy",o),he(e.scroller,"paste",function(t){if(!kn(e,t)&&!me(r,t)){if(!i.dispatchEvent)return r.state.pasteIncoming=+new Date,void n.focus();var o=new Event("paste");o.clipboardData=t.clipboardData,i.dispatchEvent(o)}}),he(e.lineSpace,"selectstart",function(t){kn(e,t)||xe(t)}),he(i,"compositionstart",function(){var e=r.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:e,range:r.markText(e,r.getCursor("to"),{className:"CodeMirror-composing"})}}),he(i,"compositionend",function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)})},Ba.prototype.createField=function(e){this.wrapper=Pa(),this.textarea=this.wrapper.firstChild},Ba.prototype.screenReaderLabelChanged=function(e){e?this.textarea.setAttribute("aria-label",e):this.textarea.removeAttribute("aria-label")},Ba.prototype.prepareSelection=function(){var e=this.cm,t=e.display,n=e.doc,r=gr(e);if(e.options.moveInputWithCursor){var i=qn(e,n.sel.primary().head,"div"),o=t.wrapper.getBoundingClientRect(),a=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,i.top+a.top-o.top)),r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,i.left+a.left-o.left))}return r},Ba.prototype.showSelection=function(e){var t=this.cm.display;N(t.cursorDiv,e.cursors),N(t.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},Ba.prototype.reset=function(e){if(!this.contextMenuPending&&!this.composing){var t=this.cm;if(t.somethingSelected()){this.prevInput="";var n=t.getSelection();this.textarea.value=n,t.state.focused&&z(this.textarea),a&&l>=9&&(this.hasSelection=n)}else e||(this.prevInput=this.textarea.value="",a&&l>=9&&(this.hasSelection=null))}},Ba.prototype.getField=function(){return this.textarea},Ba.prototype.supportsTouch=function(){return!1},Ba.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!v||E()!=this.textarea))try{this.textarea.focus()}catch(e){}},Ba.prototype.blur=function(){this.textarea.blur()},Ba.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},Ba.prototype.receivedFocus=function(){this.slowPoll()},Ba.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){e.poll(),e.cm.state.focused&&e.slowPoll()})},Ba.prototype.fastPoll=function(){var e=!1,t=this;t.pollingFast=!0,t.polling.set(20,function n(){t.poll()||e?(t.pollingFast=!1,t.slowPoll()):(e=!0,t.polling.set(60,n))})},Ba.prototype.poll=function(){var e=this,t=this.cm,n=this.textarea,r=this.prevInput;if(this.contextMenuPending||!t.state.focused||Pe(n)&&!r&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var i=n.value;if(i==r&&!t.somethingSelected())return!1;if(a&&l>=9&&this.hasSelection===i||y&&/[\uf700-\uf7ff]/.test(i))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||r||(r="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var s=0,c=Math.min(r.length,i.length);s1e3||i.indexOf("\n")>-1?n.value=e.prevInput="":e.prevInput=i,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},Ba.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},Ba.prototype.onKeyPress=function(){a&&l>=9&&(this.hasSelection=null),this.fastPoll()},Ba.prototype.onContextMenu=function(e){var t=this,n=t.cm,r=n.display,i=t.textarea;t.contextMenuPending&&t.contextMenuPending();var o=lr(n,e),c=r.scroller.scrollTop;if(o&&!f){n.options.resetSelectionOnContextMenu&&-1==n.doc.sel.contains(o)&&Zr(n,Xi)(n.doc,wi(o),U);var u,h=i.style.cssText,d=t.wrapper.style.cssText,p=t.wrapper.offsetParent.getBoundingClientRect();if(t.wrapper.style.cssText="position: static",i.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-p.top-5)+"px; left: "+(e.clientX-p.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",s&&(u=window.scrollY),r.input.focus(),s&&window.scrollTo(null,u),r.input.reset(),n.somethingSelected()||(i.value=t.prevInput=" "),t.contextMenuPending=v,r.selForContextMenu=n.doc.sel,clearTimeout(r.detectingSelectAll),a&&l>=9&&m(),C){Ce(e);var g=function(){pe(window,"mouseup",g),setTimeout(v,20)};he(window,"mouseup",g)}else setTimeout(v,50)}function m(){if(null!=i.selectionStart){var e=n.somethingSelected(),o="​"+(e?i.value:"");i.value="⇚",i.value=o,t.prevInput=e?"":"​",i.selectionStart=1,i.selectionEnd=o.length,r.selForContextMenu=n.doc.sel}}function v(){if(t.contextMenuPending==v&&(t.contextMenuPending=!1,t.wrapper.style.cssText=d,i.style.cssText=h,a&&l<9&&r.scrollbars.setScrollTop(r.scroller.scrollTop=c),null!=i.selectionStart)){(!a||a&&l<9)&&m();var e=0,o=function(){r.selForContextMenu==n.doc.sel&&0==i.selectionStart&&i.selectionEnd>0&&"​"==t.prevInput?Zr(n,ro)(n):e++<10?r.detectingSelectAll=setTimeout(o,500):(r.selForContextMenu=null,r.input.reset())};r.detectingSelectAll=setTimeout(o,200)}}},Ba.prototype.readOnlyChanged=function(e){e||this.reset(),this.textarea.disabled="nocursor"==e},Ba.prototype.setUneditable=function(){},Ba.prototype.needsContentAttribute=!1,function(e){var t=e.optionHandlers;function n(n,r,i,o){e.defaults[n]=r,i&&(t[n]=o?function(e,t,n){n!=ya&&i(e,t,n)}:i)}e.defineOption=n,e.Init=ya,n("value","",function(e,t){return e.setValue(t)},!0),n("mode",null,function(e,t){e.doc.modeOption=t,Ti(e)},!0),n("indentUnit",2,Ti,!0),n("indentWithTabs",!1),n("smartIndent",!0),n("tabSize",4,function(e){Mi(e),_n(e),cr(e)},!0),n("lineSeparator",null,function(e,t){if(e.doc.lineSep=t,t){var n=[],r=e.doc.first;e.doc.iter(function(e){for(var i=0;;){var o=e.text.indexOf(t,i);if(-1==o)break;i=o+t.length,n.push(et(r,o))}r++});for(var i=n.length-1;i>=0;i--)uo(e.doc,t,n[i],et(n[i].line,n[i].ch+t.length))}}),n("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(e,t,n){e.state.specialChars=new RegExp(t.source+(t.test("\t")?"":"|\t"),"g"),n!=ya&&e.refresh()}),n("specialCharPlaceholder",Qt,function(e){return e.refresh()},!0),n("electricChars",!0),n("inputStyle",v?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),n("spellcheck",!1,function(e,t){return e.getInputField().spellcheck=t},!0),n("autocorrect",!1,function(e,t){return e.getInputField().autocorrect=t},!0),n("autocapitalize",!1,function(e,t){return e.getInputField().autocapitalize=t},!0),n("rtlMoveVisually",!x),n("wholeLineUpdateBefore",!0),n("theme","default",function(e){va(e),hi(e)},!0),n("keyMap","default",function(e,t,n){var r=Go(t),i=n!=ya&&Go(n);i&&i.detach&&i.detach(e,r),r.attach&&r.attach(e,i||null)}),n("extraKeys",null),n("configureMouse",null),n("lineWrapping",!1,ka,!0),n("gutters",[],function(e,t){e.display.gutterSpecs=ui(t,e.options.lineNumbers),hi(e)},!0),n("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?ir(e.display)+"px":"0",e.refresh()},!0),n("coverGutterNextToScrollbar",!1,function(e){return Rr(e)},!0),n("scrollbarStyle","native",function(e){jr(e),Rr(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0),n("lineNumbers",!1,function(e,t){e.display.gutterSpecs=ui(e.options.gutters,t),hi(e)},!0),n("firstLineNumber",1,hi,!0),n("lineNumberFormatter",function(e){return e},hi,!0),n("showCursorWhenSelecting",!1,pr,!0),n("resetSelectionOnContextMenu",!0),n("lineWiseCopyCut",!0),n("pasteLinesPerSelection",!0),n("selectionsMayTouch",!1),n("readOnly",!1,function(e,t){"nocursor"==t&&(Cr(e),e.display.input.blur()),e.display.input.readOnlyChanged(t)}),n("screenReaderLabel",null,function(e,t){t=""===t?null:t,e.display.input.screenReaderLabelChanged(t)}),n("disableInput",!1,function(e,t){t||e.display.input.reset()},!0),n("dragDrop",!0,wa),n("allowDropFileTypes",null),n("cursorBlinkRate",530),n("cursorScrollMargin",0),n("cursorHeight",1,pr,!0),n("singleCursorHeightPerLine",!0,pr,!0),n("workTime",100),n("workDelay",100),n("flattenSpans",!0,Mi,!0),n("addModeClass",!1,Mi,!0),n("pollInterval",100),n("undoDepth",200,function(e,t){return e.doc.history.undoDepth=t}),n("historyEventDelay",1250),n("viewportMargin",10,function(e){return e.refresh()},!0),n("maxHighlightLength",1e4,Mi,!0),n("moveInputWithCursor",!0,function(e,t){t||e.display.input.resetPosition()}),n("tabindex",null,function(e,t){return e.display.input.getField().tabIndex=t||""}),n("autofocus",null),n("direction","ltr",function(e,t){return e.doc.setDirection(t)},!0),n("phrases",null)}(Ca),function(e){var t=e.optionHandlers,n=e.helpers={};e.prototype={constructor:e,focus:function(){window.focus(),this.display.input.focus()},setOption:function(e,n){var r=this.options,i=r[e];r[e]==n&&"mode"!=e||(r[e]=n,t.hasOwnProperty(e)&&Zr(this,t[e])(this,n,i),ge(this,"optionChange",this,e))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Go(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;nn&&(La(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&Ar(this));else{var o=i.from(),a=i.to(),l=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var s=l;s0&&Gi(this.doc,r,new bi(o,c[r].to()),U)}}}),getTokenAt:function(e,t){return yt(this,e,t)},getLineTokens:function(e,t){return yt(this,et(e),t,!0)},getTokenTypeAt:function(e){e=lt(this.doc,e);var t,n=ht(this,Ge(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]o&&(e=o,i=!0),r=Ge(this.doc,e)}else r=e;return Vn(this,r,{top:0,left:0},t||"page",n||i).top+(i?this.doc.height-Ut(r):0)},defaultTextHeight:function(){return tr(this.display)},defaultCharWidth:function(){return nr(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var o,a,l,s=this.display,c=(e=qn(this,lt(this.doc,e))).bottom,u=e.left;if(t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),s.sizer.appendChild(t),"over"==r)c=e.top;else if("above"==r||"near"==r){var f=Math.max(s.wrapper.clientHeight,this.doc.height),h=Math.max(s.sizer.clientWidth,s.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>f)&&e.top>t.offsetHeight?c=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=f&&(c=e.bottom),u+t.offsetWidth>h&&(u=h-t.offsetWidth)}t.style.top=c+"px",t.style.left=t.style.right="","right"==i?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?u=0:"middle"==i&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),n&&(o=this,a={left:u,top:c,right:u+t.offsetWidth,bottom:c+t.offsetHeight},null!=(l=Mr(o,a)).scrollTop&&Pr(o,l.scrollTop),null!=l.scrollLeft&&zr(o,l.scrollLeft))},triggerOnKeyDown:Qr(aa),triggerOnKeyPress:Qr(sa),triggerOnKeyUp:la,triggerOnMouseDown:Qr(ha),execCommand:function(e){if(Zo.hasOwnProperty(e))return Zo[e].call(null,this)},triggerElectric:Qr(function(e){Oa(this,e)}),findPosH:function(e,t,n,r){var i=1;t<0&&(i=-1,t=-t);for(var o=lt(this.doc,e),a=0;a0&&a(t.charAt(n-1));)--n;for(;r.5)&&ar(this),ge(this,"refresh",this)}),swapDoc:Qr(function(e){var t=this.doc;return t.cm=null,this.state.selectingText&&this.state.selectingText(),Di(this,e),_n(this),this.display.input.reset(),Or(this,e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,sn(this,"swapDoc",this,t),t}),phrase:function(e){var t=this.options.phrases;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},be(e),e.registerHelper=function(t,r,i){n.hasOwnProperty(t)||(n[t]=e[t]={_global:[]}),n[t][r]=i},e.registerGlobalHelper=function(t,r,i,o){e.registerHelper(t,r,o),n[t]._global.push({pred:i,val:o})}}(Ca);var ja="iter insert remove copy getEditor constructor".split(" ");for(var Ua in Mo.prototype)Mo.prototype.hasOwnProperty(Ua)&&_(ja,Ua)<0&&(Ca.prototype[Ua]=function(e){return function(){return e.apply(this.doc,arguments)}}(Mo.prototype[Ua]));return be(Mo),Ca.inputStyles={textarea:Ba,contenteditable:Ia},Ca.defineMode=function(e){Ca.defaults.mode||"null"==e||(Ca.defaults.mode=e),function(e,t){arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),Ie[e]=t}.apply(this,arguments)},Ca.defineMIME=function(e,t){Fe[e]=t},Ca.defineMode("null",function(){return{token:function(e){return e.skipToEnd()}}}),Ca.defineMIME("text/plain","null"),Ca.defineExtension=function(e,t){Ca.prototype[e]=t},Ca.defineDocExtension=function(e,t){Mo.prototype[e]=t},Ca.fromTextArea=function(e,t){if((t=t?F(t):{}).value=e.value,!t.tabindex&&e.tabIndex&&(t.tabindex=e.tabIndex),!t.placeholder&&e.placeholder&&(t.placeholder=e.placeholder),null==t.autofocus){var n=E();t.autofocus=n==e||null!=e.getAttribute("autofocus")&&n==document.body}function r(){e.value=l.getValue()}var i;if(e.form&&(he(e.form,"submit",r),!t.leaveSubmitMethodAlone)){var o=e.form;i=o.submit;try{var a=o.submit=function(){r(),o.submit=i,o.submit(),o.submit=a}}catch(e){}}t.finishInit=function(n){n.save=r,n.getTextArea=function(){return e},n.toTextArea=function(){n.toTextArea=isNaN,r(),e.parentNode.removeChild(n.getWrapperElement()),e.style.display="",e.form&&(pe(e.form,"submit",r),t.leaveSubmitMethodAlone||"function"!=typeof e.form.submit||(e.form.submit=i))}},e.style.display="none";var l=Ca(function(t){return e.parentNode.insertBefore(t,e.nextSibling)},t);return l},function(e){e.off=pe,e.on=he,e.wheelEventPixels=mi,e.Doc=Mo,e.splitLines=Ee,e.countColumn=H,e.findColumn=G,e.isWordChar=ee,e.Pass=j,e.signal=ge,e.Line=Gt,e.changeEnd=ki,e.scrollbarModel=Br,e.Pos=et,e.cmpPos=tt,e.modes=Ie,e.mimeModes=Fe,e.resolveMode=He,e.getMode=Re,e.modeExtensions=_e,e.extendMode=Be,e.copyState=je,e.startState=Ve,e.innerMode=Ue,e.commands=Zo,e.keyMap=Ro,e.keyName=Ko,e.isModifierKey=Uo,e.lookupKey=jo,e.normalizeKeyMap=Bo,e.StringStream=Ke,e.SharedTextMarker=Co,e.TextMarker=wo,e.LineWidget=yo,e.e_preventDefault=xe,e.e_stopPropagation=we,e.e_stop=Ce,e.addClass=P,e.contains=D,e.rmClass=T,e.keyNames=zo}(Ca),Ca.version="5.52.2",Ca}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";var t,n,r=e.Pos;function i(e,t){for(var n=function(e){var t=e.flags;return null!=t?t:(e.ignoreCase?"i":"")+(e.global?"g":"")+(e.multiline?"m":"")}(e),r=n,i=0;ie.length-n)break;(!r||a>r.index+r[0].length)&&(r=o),i=o.index+1}return r}function s(e,t,n){t=i(t,"g");for(var o=n.line,a=n.ch,s=e.firstLine();o>=s;o--,a=-1){var c=e.getLine(o),u=l(c,t,a<0?0:c.length-a);if(u)return{from:r(o,u.index),to:r(o,u.index+u[0].length),match:u}}}function c(e,t,n,r){if(e.length==t.length)return n;for(var i=0,o=n+Math.max(0,e.length-t.length);;){if(i==o)return i;var a=i+o>>1,l=r(e.slice(0,a)).length;if(l==n)return a;l>n?o=a:i=a+1}}function u(e,u,f,h){var d;this.atOccurrence=!1,this.doc=e,f=f?e.clipPos(f):r(0,0),this.pos={from:f,to:f},"object"==typeof h?d=h.caseFold:(d=h,h=null),"string"==typeof u?(null==d&&(d=!1),this.matches=function(i,o){return(i?function(e,i,o,a){if(!i.length)return null;var l=a?t:n,s=l(i).split(/\r|\n\r?/);e:for(var u=o.line,f=o.ch,h=e.firstLine()-1+s.length;u>=h;u--,f=-1){var d=e.getLine(u);f>-1&&(d=d.slice(0,f));var p=l(d);if(1==s.length){var g=p.lastIndexOf(s[0]);if(-1==g)continue e;return{from:r(u,c(d,p,g,l)),to:r(u,c(d,p,g+s[0].length,l))}}var m=s[s.length-1];if(p.slice(0,m.length)==m){var v=1;for(o=u-s.length+1;v=h;){for(var d=0;d=h;d++){var p=e.getLine(f--);a=null==a?p:p+"\n"+a}c*=2;var g=l(a,t,u);if(g){var m=a.slice(0,g.index).split("\n"),v=g[0].split("\n"),y=f+m.length,b=m[m.length-1].length;return{from:r(y,b),to:r(y+v.length-1,1==v.length?b+v[0].length:v[v.length-1].length),match:g}}}}:function(e,t,n){if(!o(t))return a(e,t,n);t=i(t,"gm");for(var l,s=1,c=n.line,u=e.lastLine();c<=u;){for(var f=0;fu);f++){var h=e.getLine(c++);l=null==l?h:l+"\n"+h}s*=2,t.lastIndex=n.ch;var d=t.exec(l);if(d){var p=l.slice(0,d.index).split("\n"),g=d[0].split("\n"),m=n.line+p.length-1,v=p[p.length-1].length;return{from:r(m,v),to:r(m+g.length-1,1==g.length?v+g[0].length:g[g.length-1].length),match:d}}}})(e,u,n)})}String.prototype.normalize?(t=function(e){return e.normalize("NFD").toLowerCase()},n=function(e){return e.normalize("NFD")}):(t=function(e){return e.toLowerCase()},n=function(e){return e}),u.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(t){for(var n=this.matches(t,this.doc.clipPos(t?this.pos.from:this.pos.to));n&&0==e.cmpPos(n.from,n.to);)t?n.from.ch?n.from=r(n.from.line,n.from.ch-1):n=n.from.line==this.doc.firstLine()?null:this.matches(t,this.doc.clipPos(r(n.from.line-1))):n.to.ch0);)r.push({anchor:i.from(),head:i.to()});r.length&&this.setSelections(r,0)})}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror"),require("./matchesonscrollbar")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./matchesonscrollbar"],e):e(CodeMirror)}(function(e){"use strict";var t={style:"matchhighlight",minChars:2,delay:100,wordsOnly:!1,annotateScrollbar:!1,showToken:!1,trim:!0};function n(e){var t=e.state.matchHighlighter;(t.active||e.hasFocus())&&i(e,t)}function r(e){var t=e.state.matchHighlighter;t.active||(t.active=!0,i(e,t))}function i(e,t){clearTimeout(t.timeout),t.timeout=setTimeout(function(){l(e)},t.options.delay)}function o(e,t,n,r){var i=e.state.matchHighlighter;if(e.addOverlay(i.overlay=function(e,t,n){return{token:function(r){if(r.match(e)&&(!t||function(e,t){return!(e.start&&t.test(e.string.charAt(e.start-1))||e.pos!=e.string.length&&t.test(e.string.charAt(e.pos)))}(r,t)))return n;r.next(),r.skipTo(e.charAt(0))||r.skipToEnd()}}}(t,n,r)),i.options.annotateScrollbar&&e.showMatchesOnScrollbar){var o=n?new RegExp("\\b"+t.replace(/[\\\[.+*?(){|^$]/g,"\\$&")+"\\b"):t;i.matchesonscroll=e.showMatchesOnScrollbar(o,!1,{className:"CodeMirror-selection-highlight-scrollbar"})}}function a(e){var t=e.state.matchHighlighter;t.overlay&&(e.removeOverlay(t.overlay),t.overlay=null,t.matchesonscroll&&(t.matchesonscroll.clear(),t.matchesonscroll=null))}function l(e){e.operation(function(){var t=e.state.matchHighlighter;if(a(e),e.somethingSelected()||!t.options.showToken){var n=e.getCursor("from"),r=e.getCursor("to");if(n.line==r.line&&(!t.options.wordsOnly||function(e,t,n){if(null!==e.getRange(t,n).match(/^\w+$/)){if(t.ch>0){var r={line:t.line,ch:t.ch-1},i=e.getRange(r,t);if(null===i.match(/\W/))return!1}if(n.ch=t.options.minChars&&o(e,i,!1,t.options.style)}}else{for(var l=!0===t.options.showToken?/[\w$]/:t.options.showToken,s=e.getCursor(),c=e.getLine(s.line),u=s.ch,f=u;u&&l.test(c.charAt(u-1));)--u;for(;f=this.gap.to)break;i.to.line>=this.gap.from&&this.matches.splice(t--,1)}for(var n=this.cm.getSearchCursor(this.query,e.Pos(this.gap.from,0),{caseFold:this.caseFold,multiline:this.options.multiline}),r=this.options&&this.options.maxMatches||1e3;n.findNext();){var i;if((i={from:n.from(),to:n.to()}).from.line>=this.gap.to)break;if(this.matches.splice(t++,0,i),this.matches.length>r)break}this.gap=null}},t.prototype.onChange=function(t){var r=t.from.line,i=e.changeEnd(t).line,o=i-t.to.line;if(this.gap?(this.gap.from=Math.min(n(this.gap.from,r,o),t.from.line),this.gap.to=Math.max(n(this.gap.to,r,o),t.from.line)):this.gap={from:t.from.line,to:i+1},o)for(var a=0;a",triples:"",explode:"[]{}"},n=e.Pos;function r(e,n){return"pairs"==n&&"string"==typeof e?e:"object"==typeof e&&null!=e[n]?e[n]:t[n]}e.defineOption("autoCloseBrackets",!1,function(t,n,a){a&&a!=e.Init&&(t.removeKeyMap(i),t.state.closeBrackets=null),n&&(o(r(n,"pairs")),t.state.closeBrackets=n,t.addKeyMap(i))});var i={Backspace:function(t){var i=l(t);if(!i||t.getOption("disableInput"))return e.Pass;for(var o=r(i,"pairs"),a=t.listSelections(),c=0;c=0;c--){var f=a[c].head;t.replaceRange("",n(f.line,f.ch-1),n(f.line,f.ch+1),"+delete")}},Enter:function(t){var n=l(t),i=n&&r(n,"explode");if(!i||t.getOption("disableInput"))return e.Pass;for(var o=t.listSelections(),a=0;a1&&h.indexOf(i)>=0&&t.getRange(n(b.line,b.ch-2),b)==i+i){if(b.ch>2&&/\bstring/.test(t.getTokenTypeAt(n(b.line,b.ch-2))))return e.Pass;v="addFour"}else if(d){var w=0==b.ch?" ":t.getRange(n(b.line,b.ch-1),b);if(e.isWordChar(x)||w==i||e.isWordChar(w))return e.Pass;v="both"}else{if(!g||!(0===x.length||/\s/.test(x)||f.indexOf(x)>-1))return e.Pass;v="both"}else v=d&&c(t,b)?"both":h.indexOf(i)>=0&&t.getRange(b,n(b.line,b.ch+3))==i+i+i?"skipThree":"skip";if(u){if(u!=v)return e.Pass}else u=v}var k=s%2?a.charAt(s-1):i,C=s%2?i:a.charAt(s+1);t.operation(function(){if("skip"==u)t.execCommand("goCharRight");else if("skipThree"==u)for(var r=0;r<3;r++)t.execCommand("goCharRight");else if("surround"==u){for(var i=t.getSelections(),r=0;r0,{anchor:new n(o.anchor.line,o.anchor.ch+(a?-1:1)),head:new n(o.head.line,o.head.ch+(a?1:-1))});t.setSelections(i)}else"both"==u?(t.replaceSelection(k+C,null),t.triggerElectric(k+C),t.execCommand("goCharLeft")):"addFour"==u&&(t.replaceSelection(k+k+k+k,"before"),t.execCommand("goCharRight"));var o,a})}(i,t)}}function l(e){var t=e.state.closeBrackets;return!t||t.override?t:e.getModeAt(e.getCursor()).closeBrackets||t}function s(e,t){var r=e.getRange(n(t.line,t.ch-1),n(t.line,t.ch+1));return 2==r.length?r:null}function c(e,t){var r=e.getTokenAt(n(t.line,t.ch+1));return/\bstring/.test(r.type)&&r.start==t.ch&&(0==t.ch||!/\bstring/.test(e.getTokenTypeAt(t)))}o(t.pairs+"`")}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){var t=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),n=e.Pos,r={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<","<":">>",">":"<<"};function i(e){return e&&e.bracketRegex||/[(){}[\]]/}function o(e,t,o){var l=e.getLineHandle(t.line),s=t.ch-1,c=o&&o.afterCursor;null==c&&(c=/(^| )cm-fat-cursor($| )/.test(e.getWrapperElement().className));var u=i(o),f=!c&&s>=0&&u.test(l.text.charAt(s))&&r[l.text.charAt(s)]||u.test(l.text.charAt(s+1))&&r[l.text.charAt(++s)];if(!f)return null;var h=">"==f.charAt(1)?1:-1;if(o&&o.strict&&h>0!=(s==t.ch))return null;var d=e.getTokenTypeAt(n(t.line,s+1)),p=a(e,n(t.line,s+(h>0?1:0)),h,d||null,o);return null==p?null:{from:n(t.line,s),to:p&&p.pos,match:p&&p.ch==f.charAt(0),forward:h>0}}function a(e,t,o,a,l){for(var s=l&&l.maxScanLineLength||1e4,c=l&&l.maxScanLines||1e3,u=[],f=i(l),h=o>0?Math.min(t.line+c,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-c),d=t.line;d!=h;d+=o){var p=e.getLine(d);if(p){var g=o>0?0:p.length-1,m=o>0?p.length:-1;if(!(p.length>s))for(d==t.line&&(g=t.ch-(o<0?1:0));g!=m;g+=o){var v=p.charAt(g);if(f.test(v)&&(void 0===a||e.getTokenTypeAt(n(d,g+1))==a)){var y=r[v];if(y&&">"==y.charAt(1)==o>0)u.push(v);else{if(!u.length)return{pos:n(d,g),ch:v};u.pop()}}}}}return d-o!=(o>0?e.lastLine():e.firstLine())&&null}function l(e,r,i){for(var a=e.state.matchBrackets.maxHighlightLineLength||1e3,l=[],s=e.listSelections(),c=0;cr.right?1:0:t.clientYr.bottom?1:0,i.moveTo(i.pos+n*i.screen)}),e.on(this.node,"mousewheel",o),e.on(this.node,"DOMMouseScroll",o)}t.prototype.setPos=function(e,t){return e<0&&(e=0),e>this.total-this.screen&&(e=this.total-this.screen),!(!t&&e==this.pos)&&(this.pos=e,this.inner.style["horizontal"==this.orientation?"left":"top"]=e*(this.size/this.total)+"px",!0)},t.prototype.moveTo=function(e){this.setPos(e)&&this.scroll(e,this.orientation)};function n(e,n,r){this.addClass=e,this.horiz=new t(e,"horizontal",r),n(this.horiz.node),this.vert=new t(e,"vertical",r),n(this.vert.node),this.width=null}t.prototype.update=function(e,t,n){var r=this.screen!=t||this.total!=e||this.size!=n;r&&(this.screen=t,this.total=e,this.size=n);var i=this.screen*(this.size/this.total);i<10&&(this.size-=10-i,i=10),this.inner.style["horizontal"==this.orientation?"width":"height"]=i+"px",this.setPos(this.pos,r)},n.prototype.update=function(e){if(null==this.width){var t=window.getComputedStyle?window.getComputedStyle(this.horiz.node):this.horiz.node.currentStyle;t&&(this.width=parseInt(t.height))}var n=this.width||0,r=e.scrollWidth>e.clientWidth+1,i=e.scrollHeight>e.clientHeight+1;return this.vert.node.style.display=i?"block":"none",this.horiz.node.style.display=r?"block":"none",i&&(this.vert.update(e.scrollHeight,e.clientHeight,e.viewHeight-(r?n:0)),this.vert.node.style.bottom=r?n+"px":"0"),r&&(this.horiz.update(e.scrollWidth,e.clientWidth,e.viewWidth-(i?n:0)-e.barLeft),this.horiz.node.style.right=i?n+"px":"0",this.horiz.node.style.left=e.barLeft+"px"),{right:i?n:0,bottom:r?n:0}},n.prototype.setScrollTop=function(e){this.vert.setPos(e)},n.prototype.setScrollLeft=function(e){this.horiz.setPos(e)},n.prototype.clear=function(){var e=this.horiz.node.parentNode;e.removeChild(this.horiz.node),e.removeChild(this.vert.node)},e.scrollbarModel.simple=function(e,t){return new n("CodeMirror-simplescroll",e,t)},e.scrollbarModel.overlay=function(e,t){return new n("CodeMirror-overlayscroll",e,t)}}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";function t(e,t){function n(e){clearTimeout(r.doRedraw),r.doRedraw=setTimeout(function(){r.redraw()},e)}this.cm=e,this.options=t,this.buttonHeight=t.scrollButtonHeight||e.getOption("scrollButtonHeight"),this.annotations=[],this.doRedraw=this.doUpdate=null,this.div=e.getWrapperElement().appendChild(document.createElement("div")),this.div.style.cssText="position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none",this.computeScale();var r=this;e.on("refresh",this.resizeHandler=function(){clearTimeout(r.doUpdate),r.doUpdate=setTimeout(function(){r.computeScale()&&n(20)},100)}),e.on("markerAdded",this.resizeHandler),e.on("markerCleared",this.resizeHandler),!1!==t.listenForChanges&&e.on("changes",this.changeHandler=function(){n(250)})}e.defineExtension("annotateScrollbar",function(e){return"string"==typeof e&&(e={className:e}),new t(this,e)}),e.defineOption("scrollButtonHeight",0),t.prototype.computeScale=function(){var e=this.cm,t=(e.getWrapperElement().clientHeight-e.display.barHeight-2*this.buttonHeight)/e.getScrollerElement().scrollHeight;if(t!=this.hScale)return this.hScale=t,!0},t.prototype.update=function(e){this.annotations=e,this.redraw()},t.prototype.redraw=function(e){!1!==e&&this.computeScale();var t=this.cm,n=this.hScale,r=document.createDocumentFragment(),i=this.annotations,o=t.getOption("lineWrapping"),a=o&&1.5*t.defaultTextHeight(),l=null,s=null;function c(e,n){return l!=e.line&&(l=e.line,s=t.getLineHandle(l)),s.widgets&&s.widgets.length||o&&s.height>a?t.charCoords(e,"local")[n?"top":"bottom"]:t.heightAtLine(s,"local")+(n?0:s.height)}var u=t.lastLine();if(t.display.barWidth)for(var f,h=0;hu)){for(var p=f||c(d.from,!0)*n,g=c(d.to,!1)*n;hu)&&!((f=c(i[h+1].from,!0)*n)>g+.9);)g=c((d=i[++h]).to,!1)*n;if(g!=p){var m=Math.max(g-p,3),v=r.appendChild(document.createElement("div"));v.style.cssText="position: absolute; right: 0px; width: "+Math.max(t.display.barWidth-1,2)+"px; top: "+(p+this.buttonHeight)+"px; height: "+m+"px",v.className=this.options.className,d.id&&v.setAttribute("annotation-id",d.id)}}}this.div.textContent="",this.div.appendChild(r)},t.prototype.clear=function(){this.cm.off("refresh",this.resizeHandler),this.cm.off("markerAdded",this.resizeHandler),this.cm.off("markerCleared",this.resizeHandler),this.changeHandler&&this.cm.off("changes",this.changeHandler),this.div.parentNode.removeChild(this.div)}}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";var t="CodeMirror-activeline",n="CodeMirror-activeline-background",r="CodeMirror-activeline-gutter";function i(e){for(var i=0;i!?|\/]/;function f(e,t){var r,d=e.next();if(s[d]){var p=s[d](e,t);if(!1!==p)return p}if('"'==d||"'"==d)return t.tokenize=(r=d,function(e,t){for(var n,i=!1,o=!1;null!=(n=e.next());){if(n==r&&!i){o=!0;break}i=!i&&"\\"==n}return(o||!i&&!c)&&(t.tokenize=f),"string"}),t.tokenize(e,t);if(/[\[\]{}\(\),;\:\.]/.test(d))return n=d,"bracket";if(/\d/.test(d))return e.eatWhile(/[\w\.]/),"number";if("/"==d){if(e.eat("*"))return t.tokenize=h,h(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(u.test(d))return e.eatWhile(u),"operator";e.eatWhile(/[\w\$_]/);var g=e.current();return i.propertyIsEnumerable(g)?(a.propertyIsEnumerable(g)&&(n="newstatement"),"keyword"):o.propertyIsEnumerable(g)?"builtin":l.propertyIsEnumerable(g)?"atom":"word"}function h(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=f;break}r="*"==n}return"comment"}function d(e,t,n,r,i){this.indented=e,this.column=t,this.type=n,this.align=r,this.prev=i}function p(e,t,n){return e.context=new d(e.indented,t,n,null,e.context)}function g(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}return{startState:function(e){return{tokenize:null,context:new d((e||0)-r,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,t){var r=t.context;if(e.sol()&&(null==r.align&&(r.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return null;n=null;var i=(t.tokenize||f)(e,t);if("comment"==i||"meta"==i)return i;if(null==r.align&&(r.align=!0),";"!=n&&":"!=n||"statement"!=r.type)if("{"==n)p(t,e.column(),"}");else if("["==n)p(t,e.column(),"]");else if("("==n)p(t,e.column(),")");else if("}"==n){for(;"statement"==r.type;)r=g(t);for("}"==r.type&&(r=g(t));"statement"==r.type;)r=g(t)}else n==r.type?g(t):("}"==r.type||"top"==r.type||"statement"==r.type&&"newstatement"==n)&&p(t,e.column(),"statement");else g(t);return t.startOfLine=!1,i},indent:function(e,t){if(e.tokenize!=f&&null!=e.tokenize)return 0;var n=t&&t.charAt(0),i=e.context,o=n==i.type;return"statement"==i.type?i.indented+("{"==n?0:r):i.align?i.column+(o?0:1):i.indented+(o?0:r)},electricChars:"{}"}}),function(){function e(e){for(var t={},n=e.split(" "),r=0;r!?|~^@]/,d=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function p(e,t,n){return r=e,i=n,t}function g(e,t){var n,r=e.next();if('"'==r||"'"==r)return t.tokenize=(n=r,function(e,t){var r,i=!1;if(l&&"@"==e.peek()&&e.match(d))return t.tokenize=g,p("jsonld-keyword","meta");for(;null!=(r=e.next())&&(r!=n||i);)i=!i&&"\\"==r;return i||(t.tokenize=g),p("string","string")}),t.tokenize(e,t);if("."==r&&e.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return p("number","number");if("."==r&&e.match(".."))return p("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return p(r);if("="==r&&e.eat(">"))return p("=>","operator");if("0"==r&&e.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return p("number","number");if(/\d/.test(r))return e.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),p("number","number");if("/"==r)return e.eat("*")?(t.tokenize=m,m(e,t)):e.eat("/")?(e.skipToEnd(),p("comment","comment")):$e(e,t,1)?(function(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}(e),e.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),p("regexp","string-2")):(e.eat("="),p("operator","operator",e.current()));if("`"==r)return t.tokenize=v,v(e,t);if("#"==r)return e.skipToEnd(),p("error","error");if("<"==r&&e.match("!--")||"-"==r&&e.match("->"))return e.skipToEnd(),p("comment","comment");if(h.test(r))return">"==r&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=r&&"="!=r||e.eat("="):/[<>*+\-]/.test(r)&&(e.eat(r),">"==r&&e.eat(r))),p("operator","operator",e.current());if(u.test(r)){e.eatWhile(u);var i=e.current();if("."!=t.lastType){if(f.propertyIsEnumerable(i)){var o=f[i];return p(o.type,o.style,i)}if("async"==i&&e.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/,!1))return p("async","keyword",i)}return p("variable","variable",i)}}function m(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=g;break}r="*"==n}return p("comment","comment")}function v(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=g;break}r=!r&&"\\"==n}return p("quasi","string-2",e.current())}var y="([{}])";function b(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(n<0)){if(c){var r=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,n));r&&(n=r.index)}for(var i=0,o=!1,a=n-1;a>=0;--a){var l=e.string.charAt(a),s=y.indexOf(l);if(s>=0&&s<3){if(!i){++a;break}if(0==--i){"("==l&&(o=!0);break}}else if(s>=3&&s<6)++i;else if(u.test(l))o=!0;else if(/["'\/`]/.test(l))for(;;--a){if(0==a)return;if(e.string.charAt(a-1)==l&&"\\"!=e.string.charAt(a-2)){a--;break}}else if(o&&!i){++a;break}}o&&!i&&(t.fatArrowAt=a)}}var x={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0};function w(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=o,null!=r&&(this.align=r)}function k(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(n=r.vars;n;n=n.next)if(n.name==t)return!0}var C={state:null,column:null,marked:null,cc:null};function S(){for(var e=arguments.length-1;e>=0;e--)C.cc.push(arguments[e])}function L(){return S.apply(null,arguments),!0}function T(e,t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}function M(e){var t=C.state;if(C.marked="def",t.context)if("var"==t.lexical.info&&t.context&&t.context.block){var r=function e(t,n){if(n){if(n.block){var r=e(t,n.prev);return r?r==n.prev?n:new A(r,n.vars,!0):null}return T(t,n.vars)?n:new A(n.prev,new O(t,n.vars),!1)}return null}(e,t.context);if(null!=r)return void(t.context=r)}else if(!T(e,t.localVars))return void(t.localVars=new O(e,t.localVars));n.globalVars&&!T(e,t.globalVars)&&(t.globalVars=new O(e,t.globalVars))}function N(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function A(e,t,n){this.prev=e,this.vars=t,this.block=n}function O(e,t){this.name=e,this.next=t}var D=new O("this",new O("arguments",null));function E(){C.state.context=new A(C.state.context,C.state.localVars,!1),C.state.localVars=D}function P(){C.state.context=new A(C.state.context,C.state.localVars,!0),C.state.localVars=null}function W(){C.state.localVars=C.state.context.vars,C.state.context=C.state.context.prev}function z(e,t){var n=function(){var n=C.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new w(r,C.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function I(){var e=C.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function F(e){return function t(n){return n==e?L():";"==e||"}"==n||")"==n||"]"==n?S():L(t)}}function H(e,t){return"var"==e?L(z("vardef",t),be,F(";"),I):"keyword a"==e?L(z("form"),j,H,I):"keyword b"==e?L(z("form"),H,I):"keyword d"==e?C.stream.match(/^\s*$/,!1)?L():L(z("stat"),V,F(";"),I):"debugger"==e?L(F(";")):"{"==e?L(z("}"),P,ae,I,W):";"==e?L():"if"==e?("else"==C.state.lexical.info&&C.state.cc[C.state.cc.length-1]==I&&C.state.cc.pop()(),L(z("form"),j,H,I,Le)):"function"==e?L(Ae):"for"==e?L(z("form"),Te,H,I):"class"==e||c&&"interface"==t?(C.marked="keyword",L(z("form","class"==e?e:t),We,I)):"variable"==e?c&&"declare"==t?(C.marked="keyword",L(H)):c&&("module"==t||"enum"==t||"type"==t)&&C.stream.match(/^\s*\w/,!1)?(C.marked="keyword","enum"==t?L(Ge):"type"==t?L(De,F("operator"),fe,F(";")):L(z("form"),xe,F("{"),z("}"),ae,I,I)):c&&"namespace"==t?(C.marked="keyword",L(z("form"),_,H,I)):c&&"abstract"==t?(C.marked="keyword",L(H)):L(z("stat"),J):"switch"==e?L(z("form"),j,F("{"),z("}","switch"),P,ae,I,I,W):"case"==e?L(_,F(":")):"default"==e?L(F(":")):"catch"==e?L(z("form"),E,R,H,I,W):"export"==e?L(z("stat"),He,I):"import"==e?L(z("stat"),_e,I):"async"==e?L(H):"@"==t?L(_,H):S(z("stat"),_,F(";"),I)}function R(e){if("("==e)return L(Ee,F(")"))}function _(e,t){return U(e,t,!1)}function B(e,t){return U(e,t,!0)}function j(e){return"("!=e?S():L(z(")"),V,F(")"),I)}function U(e,t,n){if(C.state.fatArrowAt==C.stream.start){var r=n?Y:X;if("("==e)return L(E,z(")"),ie(Ee,")"),I,F("=>"),r,W);if("variable"==e)return S(E,xe,F("=>"),r,W)}var i=n?G:K;return x.hasOwnProperty(e)?L(i):"function"==e?L(Ae,i):"class"==e||c&&"interface"==t?(C.marked="keyword",L(z("form"),Pe,I)):"keyword c"==e||"async"==e?L(n?B:_):"("==e?L(z(")"),V,F(")"),I,i):"operator"==e||"spread"==e?L(n?B:_):"["==e?L(z("]"),Ke,I,i):"{"==e?oe(te,"}",null,i):"quasi"==e?S(q,i):"new"==e?L(function(e){return function(t){return"."==t?L(e?Q:Z):"variable"==t&&c?L(me,e?G:K):S(e?B:_)}}(n)):"import"==e?L(_):L()}function V(e){return e.match(/[;\}\)\],]/)?S():S(_)}function K(e,t){return","==e?L(V):G(e,t,!1)}function G(e,t,n){var r=0==n?K:G,i=0==n?_:B;return"=>"==e?L(E,n?Y:X,W):"operator"==e?/\+\+|--/.test(t)||c&&"!"==t?L(r):c&&"<"==t&&C.stream.match(/^([^>]|<.*?>)*>\s*\(/,!1)?L(z(">"),ie(fe,">"),I,r):"?"==t?L(_,F(":"),i):L(i):"quasi"==e?S(q,r):";"!=e?"("==e?oe(B,")","call",r):"."==e?L(ee,r):"["==e?L(z("]"),V,F("]"),I,r):c&&"as"==t?(C.marked="keyword",L(fe,r)):"regexp"==e?(C.state.lastType=C.marked="operator",C.stream.backUp(C.stream.pos-C.stream.start-1),L(i)):void 0:void 0}function q(e,t){return"quasi"!=e?S():"${"!=t.slice(t.length-2)?L(q):L(_,$)}function $(e){if("}"==e)return C.marked="string-2",C.state.tokenize=v,L(q)}function X(e){return b(C.stream,C.state),S("{"==e?H:_)}function Y(e){return b(C.stream,C.state),S("{"==e?H:B)}function Z(e,t){if("target"==t)return C.marked="keyword",L(K)}function Q(e,t){if("target"==t)return C.marked="keyword",L(G)}function J(e){return":"==e?L(I,H):S(K,F(";"),I)}function ee(e){if("variable"==e)return C.marked="property",L()}function te(e,t){if("async"==e)return C.marked="property",L(te);if("variable"==e||"keyword"==C.style){return C.marked="property","get"==t||"set"==t?L(ne):(c&&C.state.fatArrowAt==C.stream.start&&(n=C.stream.match(/^\s*:\s*/,!1))&&(C.state.fatArrowAt=C.stream.pos+n[0].length),L(re));var n}else{if("number"==e||"string"==e)return C.marked=l?"property":C.style+" property",L(re);if("jsonld-keyword"==e)return L(re);if(c&&N(t))return C.marked="keyword",L(te);if("["==e)return L(_,le,F("]"),re);if("spread"==e)return L(B,re);if("*"==t)return C.marked="keyword",L(te);if(":"==e)return S(re)}}function ne(e){return"variable"!=e?S(re):(C.marked="property",L(Ae))}function re(e){return":"==e?L(B):"("==e?S(Ae):void 0}function ie(e,t,n){function r(i,o){if(n?n.indexOf(i)>-1:","==i){var a=C.state.lexical;return"call"==a.info&&(a.pos=(a.pos||0)+1),L(function(n,r){return n==t||r==t?S():S(e)},r)}return i==t||o==t?L():n&&n.indexOf(";")>-1?S(e):L(F(t))}return function(n,i){return n==t||i==t?L():S(e,r)}}function oe(e,t,n){for(var r=3;r"),fe):void 0}function he(e){if("=>"==e)return L(fe)}function de(e,t){return"variable"==e||"keyword"==C.style?(C.marked="property",L(de)):"?"==t||"number"==e||"string"==e?L(de):":"==e?L(fe):"["==e?L(F("variable"),se,F("]"),de):"("==e?S(Oe,de):void 0}function pe(e,t){return"variable"==e&&C.stream.match(/^\s*[?:]/,!1)||"?"==t?L(pe):":"==e?L(fe):"spread"==e?L(pe):S(fe)}function ge(e,t){return"<"==t?L(z(">"),ie(fe,">"),I,ge):"|"==t||"."==e||"&"==t?L(fe):"["==e?L(fe,F("]"),ge):"extends"==t||"implements"==t?(C.marked="keyword",L(fe)):"?"==t?L(fe,F(":"),fe):void 0}function me(e,t){if("<"==t)return L(z(">"),ie(fe,">"),I,ge)}function ve(){return S(fe,ye)}function ye(e,t){if("="==t)return L(fe)}function be(e,t){return"enum"==t?(C.marked="keyword",L(Ge)):S(xe,le,Ce,Se)}function xe(e,t){return c&&N(t)?(C.marked="keyword",L(xe)):"variable"==e?(M(t),L()):"spread"==e?L(xe):"["==e?oe(ke,"]"):"{"==e?oe(we,"}"):void 0}function we(e,t){return"variable"!=e||C.stream.match(/^\s*:/,!1)?("variable"==e&&(C.marked="property"),"spread"==e?L(xe):"}"==e?S():"["==e?L(_,F("]"),F(":"),we):L(F(":"),xe,Ce)):(M(t),L(Ce))}function ke(){return S(xe,Ce)}function Ce(e,t){if("="==t)return L(B)}function Se(e){if(","==e)return L(be)}function Le(e,t){if("keyword b"==e&&"else"==t)return L(z("form","else"),H,I)}function Te(e,t){return"await"==t?L(Te):"("==e?L(z(")"),Me,I):void 0}function Me(e){return"var"==e?L(be,Ne):"variable"==e?L(Ne):S(Ne)}function Ne(e,t){return")"==e?L():";"==e?L(Ne):"in"==t||"of"==t?(C.marked="keyword",L(_,Ne)):S(_,Ne)}function Ae(e,t){return"*"==t?(C.marked="keyword",L(Ae)):"variable"==e?(M(t),L(Ae)):"("==e?L(E,z(")"),ie(Ee,")"),I,ce,H,W):c&&"<"==t?L(z(">"),ie(ve,">"),I,Ae):void 0}function Oe(e,t){return"*"==t?(C.marked="keyword",L(Oe)):"variable"==e?(M(t),L(Oe)):"("==e?L(E,z(")"),ie(Ee,")"),I,ce,W):c&&"<"==t?L(z(">"),ie(ve,">"),I,Oe):void 0}function De(e,t){return"keyword"==e||"variable"==e?(C.marked="type",L(De)):"<"==t?L(z(">"),ie(ve,">"),I):void 0}function Ee(e,t){return"@"==t&&L(_,Ee),"spread"==e?L(Ee):c&&N(t)?(C.marked="keyword",L(Ee)):c&&"this"==e?L(le,Ce):S(xe,le,Ce)}function Pe(e,t){return"variable"==e?We(e,t):ze(e,t)}function We(e,t){if("variable"==e)return M(t),L(ze)}function ze(e,t){return"<"==t?L(z(">"),ie(ve,">"),I,ze):"extends"==t||"implements"==t||c&&","==e?("implements"==t&&(C.marked="keyword"),L(c?fe:_,ze)):"{"==e?L(z("}"),Ie,I):void 0}function Ie(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||c&&N(t))&&C.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(C.marked="keyword",L(Ie)):"variable"==e||"keyword"==C.style?(C.marked="property",L(c?Fe:Ae,Ie)):"number"==e||"string"==e?L(c?Fe:Ae,Ie):"["==e?L(_,le,F("]"),c?Fe:Ae,Ie):"*"==t?(C.marked="keyword",L(Ie)):c&&"("==e?S(Oe,Ie):";"==e||","==e?L(Ie):"}"==e?L():"@"==t?L(_,Ie):void 0}function Fe(e,t){if("?"==t)return L(Fe);if(":"==e)return L(fe,Ce);if("="==t)return L(B);var n=C.state.lexical.prev;return S(n&&"interface"==n.info?Oe:Ae)}function He(e,t){return"*"==t?(C.marked="keyword",L(Ve,F(";"))):"default"==t?(C.marked="keyword",L(_,F(";"))):"{"==e?L(ie(Re,"}"),Ve,F(";")):S(H)}function Re(e,t){return"as"==t?(C.marked="keyword",L(F("variable"))):"variable"==e?S(B,Re):void 0}function _e(e){return"string"==e?L():"("==e?S(_):S(Be,je,Ve)}function Be(e,t){return"{"==e?oe(Be,"}"):("variable"==e&&M(t),"*"==t&&(C.marked="keyword"),L(Ue))}function je(e){if(","==e)return L(Be,je)}function Ue(e,t){if("as"==t)return C.marked="keyword",L(Be)}function Ve(e,t){if("from"==t)return C.marked="keyword",L(_)}function Ke(e){return"]"==e?L():S(ie(B,"]"))}function Ge(){return S(z("form"),xe,F("{"),z("}"),ie(qe,"}"),I,I)}function qe(){return S(xe,Ce)}function $e(e,t,n){return t.tokenize==g&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(n||0)))}return W.lex=!0,I.lex=!0,{startState:function(e){var t={tokenize:g,lastType:"sof",cc:[],lexical:new w((e||0)-o,0,"block",!1),localVars:n.localVars,context:n.localVars&&new A(null,null,!1),indented:e||0};return n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),b(e,t)),t.tokenize!=m&&e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==r?n:(t.lastType="operator"!=r||"++"!=i&&"--"!=i?r:"incdec",function(e,t,n,r,i){var o=e.cc;for(C.state=e,C.stream=i,C.marked=null,C.cc=o,C.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():s?_:H)(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return C.marked?C.marked:"variable"==n&&k(e,r)?"variable-2":t}}(t,n,r,i,e))},indent:function(t,r){if(t.tokenize==m)return e.Pass;if(t.tokenize!=g)return 0;var i,l=r&&r.charAt(0),s=t.lexical;if(!/^\s*else\b/.test(r))for(var c=t.cc.length-1;c>=0;--c){var u=t.cc[c];if(u==I)s=s.prev;else if(u!=Le)break}for(;("stat"==s.type||"form"==s.type)&&("}"==l||(i=t.cc[t.cc.length-1])&&(i==K||i==G)&&!/^[,\.=+\-*:?[\(]/.test(r));)s=s.prev;a&&")"==s.type&&"stat"==s.prev.type&&(s=s.prev);var f=s.type,d=l==f;return"vardef"==f?s.indented+("operator"==t.lastType||","==t.lastType?s.info.length+1:0):"form"==f&&"{"==l?s.indented:"form"==f?s.indented+o:"stat"==f?s.indented+(function(e,t){return"operator"==e.lastType||","==e.lastType||h.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}(t,r)?a||o:0):"switch"!=s.info||d||0==n.doubleIndentSwitch?s.align?s.column+(d?0:1):s.indented+(d?0:o):s.indented+(/^(?:case|default)\b/.test(r)?o:2*o)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:s?null:"/*",blockCommentEnd:s?null:"*/",blockCommentContinue:s?null:" * ",lineComment:s?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:s?"json":"javascript",jsonldMode:l,jsonMode:s,expressionAllowed:$e,skipExpression:function(e){var t=e.cc[e.cc.length-1];t!=_&&t!=B||e.cc.pop()}}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";function t(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.info=r,this.align=i,this.prev=o}function n(e,n,r,i){var o=e.indented;return e.context&&"statement"==e.context.type&&"statement"!=r&&(o=e.context.indented),e.context=new t(o,n,r,i,null,e.context)}function r(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}function i(e,t,n){return"variable"==t.prevToken||"type"==t.prevToken||(!!/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(e.string.slice(0,n))||(!(!t.typeAtEndOfLine||e.column()!=e.indentation())||void 0))}function o(e){for(;;){if(!e||"top"==e.type)return!0;if("}"==e.type&&"namespace"!=e.prev.info)return!1;e=e.prev}}function a(e){for(var t={},n=e.split(" "),r=0;r!?|\/]/,A=s.isIdentifierChar||/[\w\$_\xa1-\uffff]/,O=s.isReservedIdentifier||!1;function D(e,t){var n,r=e.next();if(x[r]){var i=x[r](e,t);if(!1!==i)return i}if('"'==r||"'"==r)return t.tokenize=(n=r,function(e,t){for(var r,i=!1,o=!1;null!=(r=e.next());){if(r==n&&!i){o=!0;break}i=!i&&"\\"==r}return(o||!i&&!w)&&(t.tokenize=null),"string"}),t.tokenize(e,t);if(L.test(r))return c=r,null;if(T.test(r)){if(e.backUp(1),e.match(M))return"number";e.next()}if("/"==r){if(e.eat("*"))return t.tokenize=E,E(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(N.test(r)){for(;!e.match(/^\/[\/*]/,!1)&&e.eat(N););return"operator"}if(e.eatWhile(A),S)for(;e.match(S);)e.eatWhile(A);var o=e.current();return l(p,o)?(l(v,o)&&(c="newstatement"),l(y,o)&&(u=!0),"keyword"):l(g,o)?"type":l(m,o)||O&&O(o)?(l(v,o)&&(c="newstatement"),"builtin"):l(b,o)?"atom":"variable"}function E(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=null;break}r="*"==n}return"comment"}function P(e,t){s.typeFirstDefinitions&&e.eol()&&o(t.context)&&(t.typeAtEndOfLine=i(e,t,e.pos))}return{startState:function(e){return{tokenize:null,context:new t((e||0)-f,0,"top",null,!1),indented:0,startOfLine:!0,prevToken:null}},token:function(e,t){var a=t.context;if(e.sol()&&(null==a.align&&(a.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return P(e,t),null;c=u=null;var l=(t.tokenize||D)(e,t);if("comment"==l||"meta"==l)return l;if(null==a.align&&(a.align=!0),";"==c||":"==c||","==c&&e.match(/^\s*(?:\/\/.*)?$/,!1))for(;"statement"==t.context.type;)r(t);else if("{"==c)n(t,e.column(),"}");else if("["==c)n(t,e.column(),"]");else if("("==c)n(t,e.column(),")");else if("}"==c){for(;"statement"==a.type;)a=r(t);for("}"==a.type&&(a=r(t));"statement"==a.type;)a=r(t)}else c==a.type?r(t):k&&(("}"==a.type||"top"==a.type)&&";"!=c||"statement"==a.type&&"newstatement"==c)&&n(t,e.column(),"statement",e.current());if("variable"==l&&("def"==t.prevToken||s.typeFirstDefinitions&&i(e,t,e.start)&&o(t.context)&&e.match(/^\s*\(/,!1))&&(l="def"),x.token){var f=x.token(e,t,l);void 0!==f&&(l=f)}return"def"==l&&!1===s.styleDefs&&(l="variable"),t.startOfLine=!1,t.prevToken=u?"def":l||c,P(e,t),l},indent:function(t,n){if(t.tokenize!=D&&null!=t.tokenize||t.typeAtEndOfLine)return e.Pass;var r=t.context,i=n&&n.charAt(0),o=i==r.type;if("statement"==r.type&&"}"==i&&(r=r.prev),s.dontIndentStatements)for(;"statement"==r.type&&s.dontIndentStatements.test(r.info);)r=r.prev;if(x.indent){var a=x.indent(t,r,n,f);if("number"==typeof a)return a}var l=r.prev&&"switch"==r.prev.info;if(s.allmanIndentation&&/[{(]/.test(i)){for(;"top"!=r.type&&"}"!=r.type;)r=r.prev;return r.indented}return"statement"==r.type?r.indented+("{"==i?0:h):!r.align||d&&")"==r.type?")"!=r.type||o?r.indented+(o?0:f)+(o||!l||/^(?:case|default)\b/.test(n)?0:f):r.indented+h:r.column+(o?0:1)},electricInput:C?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:"//",fold:"brace"}});var s="auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran",c="alignas alignof and and_eq audit axiom bitand bitor catch class compl concept constexpr const_cast decltype delete dynamic_cast explicit export final friend import module mutable namespace new noexcept not not_eq operator or or_eq override private protected public reinterpret_cast requires static_assert static_cast template this thread_local throw try typeid typename using virtual xor xor_eq",u="bycopy byref in inout oneway out self super atomic nonatomic retain copy readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd @interface @implementation @end @protocol @encode @property @synthesize @dynamic @class @public @package @private @protected @required @optional @try @catch @finally @import @selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available",f="FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT",h=a("int long char short double float unsigned signed void bool"),d=a("SEL instancetype id Class Protocol BOOL");function p(e){return l(h,e)||/.+_t$/.test(e)}function g(e){return p(e)||l(d,e)}var m="case do else for if switch while struct enum union";function v(e,t){if(!t.startOfLine)return!1;for(var n,r=null;n=e.peek();){if("\\"==n&&e.match(/^.$/)){r=v;break}if("/"==n&&e.match(/^\/[\/\*]/,!1))break;e.next()}return t.tokenize=r,"meta"}function y(e,t){return"type"==t.prevToken&&"type"}function b(e){return!(!e||e.length<2)&&("_"==e[0]&&("_"==e[1]||e[1]!==e[1].toLowerCase()))}function x(e){return e.eatWhile(/[\w\.']/),"number"}function w(e,t){if(e.backUp(1),e.match(/(R|u8R|uR|UR|LR)/)){var n=e.match(/"([^\s\\()]{0,16})\(/);return!!n&&(t.cpp11RawStringDelim=n[1],t.tokenize=S,S(e,t))}return e.match(/(u8|u|U|L)/)?!!e.match(/["']/,!1)&&"string":(e.next(),!1)}function k(e){var t=/(\w+)::~?(\w+)$/.exec(e);return t&&t[1]==t[2]}function C(e,t){for(var n;null!=(n=e.next());)if('"'==n&&!e.eat('"')){t.tokenize=null;break}return"string"}function S(e,t){var n=t.cpp11RawStringDelim.replace(/[^\w\s]/g,"\\$&");return e.match(new RegExp(".*?\\)"+n+'"'))?t.tokenize=null:e.skipToEnd(),"string"}function L(t,n){"string"==typeof t&&(t=[t]);var r=[];function i(e){if(e)for(var t in e)e.hasOwnProperty(t)&&r.push(t)}i(n.keywords),i(n.types),i(n.builtin),i(n.atoms),r.length&&(n.helperType=t[0],e.registerHelper("hintWords",t[0],r));for(var o=0;o!?|\/#:@]/,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return!!e.match('""')&&(t.tokenize=T,t.tokenize(e,t))},"'":function(e){return e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},"=":function(e,n){var r=n.context;return!("}"!=r.type||!r.align||!e.eat(">"))&&(n.context=new t(r.indented,r.column,r.type,r.info,null,r.prev),"operator")},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=M(1),t.tokenize(e,t))}},modeProps:{closeBrackets:{pairs:'()[]{}""',triples:'"'}}}),L("text/x-kotlin",{name:"clike",keywords:a("package as typealias class interface this super val operator var fun for is in This throw return annotation break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix suspend actual expect setparam"),types:a("Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy LazyThreadSafetyMode LongArray Nothing ShortArray Unit"),intendSwitch:!1,indentStatements:!1,multiLineStrings:!0,number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,blockKeywords:a("catch class do else finally for if where try while enum"),defKeywords:a("class val var object interface fun"),atoms:a("true false null this"),hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},"*":function(e,t){return"."==t.prevToken?"variable":"operator"},'"':function(e,t){var n;return t.tokenize=(n=e.match('""'),function(e,t){for(var r,i=!1,o=!1;!e.eol();){if(!n&&!i&&e.match('"')){o=!0;break}if(n&&e.match('"""')){o=!0;break}r=e.next(),!i&&"$"==r&&e.match("{")&&e.skipTo("}"),i=!i&&"\\"==r&&!n}return!o&&n||(t.tokenize=null),"string"}),t.tokenize(e,t)},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=M(1),t.tokenize(e,t))},indent:function(e,t,n,r){var i=n&&n.charAt(0);return"}"!=e.prevToken&&")"!=e.prevToken||""!=n?"operator"==e.prevToken&&"}"!=n&&"}"!=e.context.type||"variable"==e.prevToken&&"."==i||("}"==e.prevToken||")"==e.prevToken)&&"."==i?2*r+t.indented:t.align&&"}"==t.type?t.indented+(e.context.type==(n||"").charAt(0)?0:r):void 0:e.indented}},modeProps:{closeBrackets:{triples:'"'}}}),L(["x-shader/x-vertex","x-shader/x-fragment"],{name:"clike",keywords:a("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:a("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:a("for while do if else struct"),builtin:a("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:a("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":v},modeProps:{fold:["brace","include"]}}),L("text/x-nesc",{name:"clike",keywords:a(s+" as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:p,blockKeywords:a(m),atoms:a("null true false"),hooks:{"#":v},modeProps:{fold:["brace","include"]}}),L("text/x-objectivec",{name:"clike",keywords:a(s+" "+u),types:g,builtin:a(f),blockKeywords:a(m+" @synthesize @try @catch @finally @autoreleasepool @synchronized"),defKeywords:a("struct enum union @interface @implementation @protocol @class"),dontIndentStatements:/^@.*$/,typeFirstDefinitions:!0,atoms:a("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:b,hooks:{"#":v,"*":y},modeProps:{fold:["brace","include"]}}),L("text/x-objectivec++",{name:"clike",keywords:a(s+" "+u+" "+c),types:g,builtin:a(f),blockKeywords:a(m+" @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"),defKeywords:a("struct enum union @interface @implementation @protocol @class class namespace"),dontIndentStatements:/^@.*$|^template$/,typeFirstDefinitions:!0,atoms:a("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:b,hooks:{"#":v,"*":y,u:w,U:w,L:w,R:w,0:x,1:x,2:x,3:x,4:x,5:x,6:x,7:x,8:x,9:x,token:function(e,t,n){if("variable"==n&&"("==e.peek()&&(";"==t.prevToken||null==t.prevToken||"}"==t.prevToken)&&k(e.current()))return"def"}},namespaceSeparator:"::",modeProps:{fold:["brace","include"]}}),L("text/x-squirrel",{name:"clike",keywords:a("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:p,blockKeywords:a("case catch class else for foreach if switch try while"),defKeywords:a("function local class"),typeFirstDefinitions:!0,atoms:a("true false null"),hooks:{"#":v},modeProps:{fold:["brace","include"]}});var N=null;L("text/x-ceylon",{name:"clike",keywords:a("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"),types:function(e){var t=e.charAt(0);return t===t.toUpperCase()&&t!==t.toLowerCase()},blockKeywords:a("case catch class dynamic else finally for function if interface module new object switch try while"),defKeywords:a("class dynamic function interface module object package value"),builtin:a("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"),isPunctuationChar:/[\[\]{}\(\),;\:\.`]/,isOperatorChar:/[+\-*&%=<>!?|^~:\/]/,numberStart:/[\d#$]/,number:/^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,multiLineStrings:!0,typeFirstDefinitions:!0,atoms:a("true false null larger smaller equal empty finished"),indentSwitch:!1,styleDefs:!1,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return t.tokenize=function e(t){return function(n,r){for(var i,o=!1,a=!1;!n.eol();){if(!o&&n.match('"')&&("single"==t||n.match('""'))){a=!0;break}if(!o&&n.match("``")){N=e(t),a=!0;break}i=n.next(),o="single"==t&&!o&&"\\"==i}return a&&(r.tokenize=null),"string"}}(e.match('""')?"triple":"single"),t.tokenize(e,t)},"`":function(e,t){return!(!N||!e.match("`"))&&(t.tokenize=N,N=null,t.tokenize(e,t))},"'":function(e){return e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},token:function(e,t,n){if(("variable"==n||"type"==n)&&"."==t.prevToken)return"variable-2"}},modeProps:{fold:["brace","import"],closeBrackets:{triples:'"'}}})}),window.onload=function(){var e,t=document.body.getElementsByClassName("fs-editor");t.length>0&&(t=t[0]),(e=new CodeMirror(t,window.opener.gb_code_editor_settings)).setOption("theme",window.opener.gb_code_editor_theme),e.setValue(window.opener.gb_code_editor.getValue()),synced_cm_document=window.opener.gb_code_editor.getDoc(),e.swapDoc(synced_cm_document.linkedDoc({sharedHist:!0})),window.addEventListener("load",function(){e.refresh()},!1),window.addEventListener("resize",function(){e.refresh()},!1),window.cm=e}; \ No newline at end of file diff --git a/client/dist/fs.js b/client/dist/fs.js index 98b2220..cac435b 100644 --- a/client/dist/fs.js +++ b/client/dist/fs.js @@ -21332,7 +21332,7 @@ _utter_fail_element.innerHTML = ""; Fields. ************************************************************/ - var _motd = '', + var _motd = '', _webmidi_support_msg = '
WebMIDI API is not enabled/supported by this browser, please use a compatible browser.
', @@ -21772,7 +21772,8 @@ _utter_fail_element.innerHTML = ""; */ var _ws_protocol = "ws", - _domain = "127.0.0.1";/* jslint browser: true */ + _domain = "127.0.0.1"; +/* jslint browser: true */ /** * IndexedDB initialization & interface @@ -26994,10 +26995,12 @@ var _initWorkspace = function () { Fields. ************************************************************/ -var _ffs_address = _domain + ":3122", +var _ffs_address = "127.0.0.1:3122", _dir_state = new Map(), _selected_files = new Map(), - _file_check_state = null; + _file_check_state = null, + + _ffs_address_input = document.getElementById("fs_ffs_address"); /*********************************************************** Functions. @@ -27647,7 +27650,20 @@ var _refreshFileManager = function (target_element_id, target) { Init. ************************************************************/ -/* jslint browser: true */ +var _ffsInit = function () { + var address = localStorage.getItem("ffs-address"); + if (address !== null) { + _ffs_address = address; + } + + _ffs_address_input.value = _ffs_address; + + _ffs_address_input.addEventListener('input', function () { + _ffs_address = this.value; + + localStorage.setItem("ffs-address", _ffs_address); + }); +};/* jslint browser: true */ /*********************************************************** Fields. @@ -37229,6 +37245,8 @@ var _oscInit = function () { _allocateFramesData(); _fasInit(); + + _ffsInit(); _uiInit(); diff --git a/client/dist/fs.min.js b/client/dist/fs.min.js index 98b2220..3265b97 100644 --- a/client/dist/fs.min.js +++ b/client/dist/fs.min.js @@ -1,37540 +1 @@ -/* jslint browser: true */ - -/* global CodeMirror, performance*/ - -// WUI - https://github.com/grz0zrg/wui -/* jslint browser: true */ -/* jshint globalstrict: false */ - -var WUI_Form = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _widget_list = {}, - - _class_name = { - form: "wui-form", - main_group: "wui-form-main-group", - sub_group: "wui-form-sub-group", - sub_group_div: "wui-form-sub-group-div", - tn: "wui-form-tn", - sm: "wui-form-sm", - md: "wui-form-md", - xl: "wui-form-xl", - align_right: "wui-form-align-right", - inline: "wui-form-inline" - }, - - _known_options = { - width: "auto", - on_change: null - }, - - _identifier_patterns = { - wui_item: "wui_form_item_", - std_item: "wui_form_std_item_" - }, - - // this is the type="" (value) mapped to a HTML element (key) - _form_type_table = { - "checkbox": "input", - "text": "input", - "color": "input", - "date": "input", - "datetime-local": "input", - "email": "input", - "file": "input", - "hidden": "input", - "image": "input", - "month": "input", - "number": "input", - "radio": "input", - "range": "input", - "reset": "input", - "search": "input", - "submit": "input", - "tel": "input", - "time": "input", - "url": "input", - "week": "input", - "password": "input" - }, - - _allowed_form_items = [ - "button", - "datalist", - "input", - "label", - "legend", - "meter", - "select", - "textarea", - - // see _form_type_table - "checkbox", - "text", - "color", - "date", - "datetime-local", - "email", - "file", - "hidden", - "image", - "month", - "number", - "radio", - "range", - "reset", - "search", - "submit", - "tel", - "time", - "url", - "week", - "password" - ], - - _allowed_wui_items = [ - "WUI_RangeSlider", "WUI_Input", "WUI_DropDown" - ]; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _log = function (content) { - if (!window.WUI_Reporting) { - return; - } - - if (typeof console !== "undefined") { - console.log(content); - } - }; - - var _copyAttributes = function (src, dst) { - var key; - - for (key in src) { - if (src.hasOwnProperty(key)) { - dst.setAttribute(key, src[key]); - } - } - }; - - var _getOnChange = function (obj, cb, cb2) { - return function (ev) { - // we keep track of the data - if (ev.target) { - if (obj["name"]) { - if (obj.type === "checkbox") { - _widget_list[obj.wid].sitems[obj.name].value = ev.target.checked; - - obj.value = ev.target.checked; - } else { - _widget_list[obj.wid].sitems[obj.name].value = ev.target.value; - - obj.value = ev.target.value; - } - } else { - if (obj.type === "checkbox") { - obj.value = ev.target.checked; - } else { - obj.value = ev.target.value; - } - } - } else { - if (obj["name"]) { - _widget_list[obj.wid].sitems[obj.name].value = ev; - } - - obj.value = ev; - } - - if (cb !== undefined) { - cb(obj.value, ev, obj); - } - - if (cb2 !== undefined) { - cb2(obj.value, ev, obj); - } - }; - } - - var _addFormItems = function (id, legend_name, attr_list, element, frame_object, index, opts) { - var i = 0, - j = 0, - - key, - - fields_count = index, - - frame_elem, - frame_item, - frame_legend, - wui_form_elem, - - div_elem, - form_elem, - label_elem, - option_elem, - option_parent, - opt_group_elem, - datalist_input_elem, - sub_group_attr, - - final_elem, - - option; - - if (legend_name === undefined) { - frame_elem = document.createElement("div"); - frame_legend = document.createElement("legend"); - } else { - frame_elem = document.createElement("fieldset"); - frame_legend = document.createElement("legend"); - frame_legend.innerHTML = legend_name; - } - - if (attr_list !== undefined) { - _copyAttributes(attr_list, frame_elem); - } - - frame_elem.appendChild(frame_legend); - - for (i = 0; i < frame_object.length; i += 1) { - frame_item = frame_object[i]; - - if (frame_item["type"]) { - if (_allowed_form_items.indexOf(frame_item.type) !== -1) { // standard HTML form items - div_elem = null; - - if (_form_type_table[frame_item.type]) { - form_elem = document.createElement(_form_type_table[frame_item.type]); - form_elem.type = frame_item.type; - - final_elem = form_elem; - } else { - form_elem = document.createElement(frame_item.type); - final_elem = form_elem; - } - - if (frame_item["wrap"]) { - div_elem = document.createElement("div"); - div_elem.appendChild(form_elem); - final_elem = div_elem; - } - - form_elem.id = _identifier_patterns.std_item + fields_count + "_" + id; - - if (frame_item["group"]) { - form_elem.name = frame_item.group; - } - - if (frame_item["name"]) { - _widget_list[id].items[frame_item.name] = { elem: form_elem }; - _widget_list[id].sitems[frame_item.name] = { value: 0 }; - } - - if (frame_item.type === "textarea" || frame_item.type === "text") { - form_elem.addEventListener("input", _getOnChange({wid: id, name: frame_item["name"], type: frame_item.type}, opts["on_change"])); - } else if (frame_item.type === "button") { - form_elem.addEventListener("click", _getOnChange({wid: id, name: frame_item["name"], type: frame_item.type}, opts["on_change"])); - } else { - form_elem.addEventListener("change", _getOnChange({wid: id, name: frame_item["name"], type: frame_item.type}, opts["on_change"])); - } - - if (frame_item["content"]) { - form_elem.innerHTML = frame_item["content"]; - } - - if (frame_item["label"]) { - label_elem = document.createElement("label"); - label_elem.setAttribute("for", form_elem.id); - - label_elem.innerHTML = frame_item.label; - - if (div_elem === null) { - frame_elem.appendChild(label_elem); - } else { - final_elem.insertBefore(label_elem, form_elem); - } - - if (frame_item.type === "input") { - label_elem.appendChild(form_elem); - final_elem = label_elem; - } - } - - if (frame_item["attr"]) { - _copyAttributes(frame_item.attr, form_elem); - } - - if (frame_item.type === "select" || frame_item.type === "datalist") { - if (frame_item.type === "datalist") { - datalist_input_elem = document.createElement("input"); - datalist_input_elem.setAttribute("list", form_elem.id); - - if (frame_item["id"]) { - datalist_input_elem.setAttribute("id", frame_item.id); - } - - if (frame_item["name"]) { - datalist_input_elem.setAttribute("name", frame_item.name); - } - - final_elem.appendChild(datalist_input_elem); - } - - if (frame_item["options"]) { - option_parent = form_elem; - - for (j = 0; j < frame_item.options.length; j += 1) { - option = frame_item.options[j]; - - if ((typeof option) === "object") { - if (option["group"]) { - option_parent = document.createElement("optgroup"); - option_parent.setAttribute("label", option.group); - if (option["group_attr"]) { - _copyAttributes(option.group_attr, option_parent); - } - form_elem.appendChild(option_parent); - } - } - - option_elem = document.createElement("option"); - - if ((typeof option) === "string") { - option_elem.innerHTML = option; - option_parent.appendChild(option_elem); - } else if ((typeof option) === "object") { - if (option["name"]) { - option_elem.innerHTML = option.name; - option_parent.appendChild(option_elem); - - if (option["label"]) { - option_elem.setAttribute("label", option.label); - } - - if ((typeof option["disabled"]) === "booleans") { - option_elem.setAttribute("disabled", option.disabled); - } - - if ((typeof option["selected"]) === "booleans") { - option_elem.setAttribute("selected", option.selected); - } - - if (option["value"]) { - option_elem.setAttribute("value", option.value); - } - - if (option["attr"]) { - _copyAttributes(option.attr, option_elem); - } - } - } - } - } - } - - if (frame_item["value"]) { - form_elem.value = frame_item.value; - - //_widget_list[id] - } - - frame_elem.appendChild(final_elem); - - fields_count += 1; - } else if (_allowed_wui_items.indexOf(frame_item.type) !== -1) { // WUI items - if (window[frame_item.type]) { - wui_form_elem = document.createElement("div"); - wui_form_elem.id = _identifier_patterns.wui_item + fields_count; - - if (frame_item["name"]) { - _widget_list[id].items[frame_item.name] = { elem: wui_form_elem }; - _widget_list[id].sitems[frame_item.name] = { value: 0 }; - } - - // wrap detected events to keep tracks of data - if (frame_item["opts"]) { - if (frame_item.opts.on_change) { - frame_item.opts.on_change = _getOnChange({wid: id, name: frame_item["name"]}, frame_item.opts.on_change, opts["on_change"]); - } - - if (frame_item.opts.on_item_selected) { - frame_item.opts.on_item_selected = _getOnChange({wid: id, name: frame_item["name"]}, frame_item.opts.on_item_selected, opts["on_change"]); - } - } - - window[frame_item.type].create(wui_form_elem, frame_item["opts"], frame_item["items"]); - - frame_elem.appendChild(wui_form_elem); - - fields_count += 1; - } - } else if (frame_item.type === "fieldset") { - if (frame_item["items"]) { - sub_group_attr = { - "style": "" - }; - - if (frame_item["class"]) { - sub_group_attr["class"] = frame_item.class; - sub_group_attr["class"] += " " + _class_name.sub_group; - } else { - sub_group_attr["class"] = _class_name.sub_group; - } - - if (frame_item["style"]) { - sub_group_attr.style += frame_item.style; - } - - if (frame_item["width"]) { - sub_group_attr.style += "width: " + frame_item["width"]; - } - - if (frame_item["height"]) { - sub_group_attr.style += "height: " + frame_item["height"]; - } - - if (frame_item["content_align"] === "right") { - sub_group_attr["class"] += " " + _class_name.align_right; - } - - if (frame_item["inline"]) { - sub_group_attr["class"] += " " + _class_name.inline; - } - - if (frame_item["items_size"]) { - if (frame_item.items_size === "tn") { - sub_group_attr["class"] += " " + _class_name.tn; - } else if (frame_item.items_size === "sm") { - sub_group_attr["class"] += " " + _class_name.sm; - } else if (frame_item.items_size === "md") { - sub_group_attr["class"] += " " + _class_name.md; - } else if (frame_item.items_size === "xl") { - sub_group_attr["class"] += " " + _class_name.xl; - } - } else { - sub_group_attr["class"] += " " + _class_name.sm; - } - - if (frame_item["name"] === undefined) { - sub_group_attr["class"] += " " + _class_name.sub_group_div; - } - - fields_count = _addFormItems(id, frame_item["name"], sub_group_attr, frame_elem, frame_item.items, fields_count, opts); - } - } - } - } - - element.appendChild(frame_elem); - - - - return fields_count; - }; - - var _createFailed = function () { - _log("WUI_Form 'create' failed, first argument not an id nor a DOM element."); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - this.create = function (id, options, items) { - var element, - - frame, - - frame_elem, - - total_items = 0, - - opts = {}, - - key, - - i = 0; - - if ((typeof id) === "string") { - element = document.getElementById(id); - } else if ((typeof id) === "object") { - if ((typeof id.innerHTML) !== "string") { - _createFailed(); - - return; - } - - element = id; - - id = element.id; - } else { - _createFailed(); - - return; - } - - if (_widget_list[id] !== undefined) { - _log("WUI_Form id '" + id + "' already created, aborting."); - - return; - } - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - } - - _widget_list[id] = { - element: element, - total_items: total_items, - items: {}, // items reference - sitems: {}, // serializable item data - opts : opts - }; - - for (key in items) { - if (items.hasOwnProperty(key)) { - frame = items[key]; - - total_items += _addFormItems(id, key, { "class": _class_name.main_group }, element, frame, total_items, opts); - } - } - - _widget_list[id].total_items = total_items; - - element.style.width = opts.width; - - element.classList.add(_class_name.form); - - return id; - }; - - this.destroy = function (id) { - var widget = _widget_list[id], - - element, - - wui_form_item, - - i, j; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_Form, destroying aborted."); - - return; - } - - element = widget.element; - - // delete WUI form items - for (i = 0; i < widget.total_items; i += 1) { - wui_form_item = document.getElementById(_identifier_patterns.wui_item + i + "_" + element.id); - if (wui_form_item) { - for (j = 0; j < _allowed_wui_items.length; j += 1) { - window[_allowed_wui_items[j]].destroy(wui_form_item); - } - } - } - - delete _widget_list[id]; - }; - - this.getParameters = function (id) { - var widget = _widget_list[id], - parameters = { }, - key; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_Form, getParameters aborted."); - - return null; - } - - for (key in widget.sitems) { - if (widget.sitems.hasOwnProperty(key)) { - parameters[key] = widget.sitems[key]; - } - } - - return parameters; - }; - - this.setParameters = function (id, parameters, trigger_on_change) { - var widget = _widget_list[id], - ev, - key; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_Form, setParameters aborted."); - - return; - } - - if (!parameters) { - return; - } - - for (key in parameters) { - if (parameters.hasOwnProperty(key)) { - if (widget.items[key]) { - widget.sitems[key] = parameters[key]; - - if (trigger_on_change) { - widget.items[key].elem.value = parameters[key].value; - widget.items[key].elem.checked = parameters[key].checked; - } - } - } - } - }; -})(); - -/* jslint browser: true */ - -var WUI_Dialog = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _self = this, - - _widget_list = {}, - - _dragged_dialog = null, - _resized_dialog = null, - - _touch_identifier = null, - - _drag_x = 0, - _drag_y = 0, - - _resize_start_x = 0, - _resize_start_y = 0, - - _resize_timeout = null, - - _detached_windows = [], - - _class_name = { - dialog: "wui-dialog", - content: "wui-dialog-content", - btn: "wui-dialog-btn", - btn_close: "wui-dialog-close", - detach: "wui-dialog-detach", - minimized: "wui-dialog-minimized", - minimize: "wui-dialog-minimize", - maximize: "wui-dialog-maximize", - header: "wui-dialog-header", - open: "wui-dialog-open", - closed: "wui-dialog-closed", - draggable: "wui-dialog-draggable", - transition: "wui-dialog-transition", - dim_transition: "wui-dialog-dim-transition", - modal: "wui-dialog-modal", - status_bar: "wui-dialog-status-bar", - title_wrapper: "wui-dialog-title-wrapper", - detached: "wui-dialog-detach-window-body" - }, - - _known_options = { - title: "", - - width: "80%", - height: "40%", - - open: true, - - closable: true, - minimizable: false, - draggable: false, - resizable: false, - detachable: false, - - min_width: "title", - min_height: 32, - - header_btn: null, - - status_bar: false, - status_bar_content: "", - - keep_align_when_resized: false, - - halign: "left", // 'left', 'center', 'right' - valign: "top", // 'top', 'center', 'bottom' - - top: 0, - left: 0, - - modal: false, - - minimized: false, - - on_open: null, - on_close: null, - on_detach: null, - on_pre_detach: null, - on_resize: null - }; - - /*********************************************************** - Private section. - - Initialization. - ************************************************************/ - - var _withinDialog = function (e) { - var node = e.parentElement; - while (node !== null) { - if (node.classList.contains(_class_name.dialog) || - node.classList.contains(_class_name.detached)) { - return true; - } - - node = node.parentElement; - } - - return false; - }; - - // this keep track of event listeners... globally - // a tricky solution but the only one i know of until a standard pop up or someone has a better solution - if (!Element.prototype['_addEventListener']) { - Element.prototype._addEventListener = Element.prototype.addEventListener; - Element.prototype.addEventListener = function (a, b, c, d) { - this._addEventListener(a, b, c, d); - - if (_withinDialog(this)) { - if (this['eventListenerList'] === undefined) { - this['eventListenerList'] = {}; - } - - if (this.eventListenerList[a] === undefined) { - this.eventListenerList[a] = []; - } - this.eventListenerList[a].push(b); - } - }; - Element.prototype._removeEventListener = Element.prototype.removeEventListener; - Element.prototype.removeEventListener = function (a, b, c) { - if (this['eventListenerList']) { - var events = this.eventListenerList[a], i; - if (events) { - for (i = 0; i < events.length; i += 1) { - if (events[i] === b) { - events.splice(i, 1); - break; - } - } - } - } - this._removeEventListener(a, b, c); - }; - } - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _log = function (content) { - if (!window.WUI_Reporting) { - return; - } - - if (typeof console !== "undefined") { - console.log(content); - } - }; - - var _removeDetachedWindow = function (widget) { - var i = 0; - - for (i = 0; i < _detached_windows.length; i += 1) { - if (_detached_windows[i] === widget.detachable_ref) { - _detached_windows.splice(i, 1); - break; - } - } - }; - - var _close = function (dialog, detach, propagate, remove_modal_element) { - var widget = _widget_list[dialog.id], modal_elems, i, j, w; - - if (!widget) { - return; - } - - if (detach) { - if(widget.detachable_ref) { - if (!widget.detachable_ref.closed) { - widget.detachable_ref.close(); - } - - _removeDetachedWindow(widget); - } - } - - if (widget.dialog.classList.contains(_class_name.closed) && !widget.detachable_ref) { - return; - } - - if (remove_modal_element) { - if (widget.modal_element) { - document.body.removeChild(widget.modal_element); - - for (i = 0; i < _detached_windows.length; i += 1) { - w = _detached_windows[i]; - - modal_elems = w.document.body.getElementsByClassName(_class_name.modal); - - for (j = 0; j < modal_elems.length; j += 1) { - w.document.body.removeChild(modal_elems[j]); - } - } - } - } - - if (!widget.dialog.classList.contains(_class_name.open) && !widget.detachable_ref) { - return; - } - - dialog.classList.add(_class_name.closed); - dialog.classList.remove(_class_name.open); - - if (propagate) { - if (widget.opts.on_close !== null) { - widget.opts.on_close(); - } - } - }; - - var _focus = function (dialog) { - var cz_index = 0, - - tmp_dialog = null, - - elem = null, - - widget = _widget_list[dialog.id]; - - if (widget.opts.modal) { - return; - } - - for (var i in _widget_list) { - if (_widget_list.hasOwnProperty(i)) { - tmp_dialog = _widget_list[i].dialog; - - if (!isNaN(tmp_dialog.style.zIndex)) { - cz_index = parseInt(tmp_dialog.style.zIndex, 10); - - if (cz_index > 100) { - tmp_dialog.style.zIndex = 100; - } - } - } - } - - // traverse backward to see if it is contained by another dialog and focus all the parents, note: could be done once for performances - elem = widget.dialog.parentElement; - - while (elem !== null) { - if (elem.classList.contains(_class_name.dialog)) { - elem.style.zIndex = 101; - } - - elem = elem.parentElement; - } - - dialog.style.zIndex = 101; - }; - - var _createModalElement = function (dialog) { - var div = document.createElement("div"); - - div.className = "wui-dialog-modal"; - - div.addEventListener("click", function (ev) { - ev.preventDefault(); - - _close(dialog, true, true, true); - }); - - div.style.zIndex = 16777270; - - return div; - }; - - var _computeThenSetPosition = function (dialog) { - var widget = _widget_list[dialog.id], - - opts = widget.opts, - - parent_width = dialog.parentElement.offsetWidth, - parent_height = dialog.parentElement.offsetHeight, - - dialog_width = dialog.offsetWidth, - dialog_height = dialog.offsetHeight; - - if (opts.halign === "center") { - dialog.style.left = Math.round((parent_width - dialog_width) / 2 + opts.left) + "px"; - } else if (opts.halign === "right") { - dialog.style.left = (parent_width - dialog_width + opts.left) + "px"; - } else { - dialog.style.left = opts.left + "px"; - } - - if (opts.valign === "center") { - dialog.style.top = Math.round((parent_height - dialog_height) / 2 + opts.top) + "px"; - } else if (opts.valign === "bottom") { - dialog.style.top = (parent_height - dialog_height + opts.top) + "px"; - } else { - dialog.style.top = opts.top + "px"; - } - }; - - var _minimize = function (minimize_btn, dialog) { - var widget = _widget_list[dialog.id], - - resize_handler = widget.resize_handler; - - if (widget.dialog !== dialog) { - _minimize(widget.header_minimaxi_btn, widget.dialog); - } - - minimize_btn.classList.toggle(_class_name.minimize); - minimize_btn.classList.toggle(_class_name.maximize); - - dialog.classList.toggle(_class_name.minimized); - - if (dialog.classList.contains(_class_name.minimized)) { - dialog.style.borderStyle = "solid"; - dialog.style.borderColor = "#808080"; - dialog.style.borderWidth = "1px"; - } else { - dialog.style.borderStyle = ""; - dialog.style.borderColor = ""; - dialog.style.borderWidth = ""; - } - - if (resize_handler) { - resize_handler.classList.toggle(_class_name.open); - } - - if (widget.status_bar) { - widget.status_bar.classList.toggle(_class_name.open); - } - }; - - var _onWindowResize = function (detached) { - if (_resize_timeout === null) { - _resize_timeout = setTimeout(function() { - _resize_timeout = null; - - var doc = document, - dialog_contents, - - widget, - - content, - dialog, - - status_bar, - - bcr, - - i; - - if (detached) { - doc = detached.document; - - dialog_contents = doc.getElementsByClassName(_class_name.content); - - for (i = 0; i < dialog_contents.length; i += 1) { - content = dialog_contents[i]; - - dialog = content.parentElement; - - widget = _widget_list[dialog.id]; - - status_bar = dialog.getElementsByClassName(_class_name.status_bar); - - if (status_bar.length > 0) { - content.style.height = (detached.innerHeight - 32) + "px"; - } else { - content.style.height = detached.innerHeight + "px"; - } - - bcr = content.getBoundingClientRect(); - - if (widget.opts.on_resize) { - widget.opts.on_resize(bcr.width, bcr.height); - } - } - - return; - } - - dialog_contents = doc.getElementsByClassName(_class_name.content); - - // resize content & set position - for (i = 0; i < dialog_contents.length; i += 1) { - content = dialog_contents[i]; - - dialog = content.parentElement; - - status_bar = dialog.getElementsByClassName(_class_name.status_bar); - - if (status_bar.length > 0) { - content.style.height = dialog.offsetHeight - 64 + "px"; - } else { - content.style.height = dialog.offsetHeight - 32 + "px"; - } - - _computeThenSetPosition(dialog); - - bcr = content.getBoundingClientRect(); - - widget = _widget_list[dialog.id]; - - if (widget.opts.on_resize) { - widget.opts.on_resize(bcr.width, bcr.height); - } - } - }, 1000 / 8); - } - }; - - var _addListenerWalk = function (elem, target) { - var key, i; - - do { - if (elem.nodeType == 1) { - if (elem['eventListenerList']) { - for (key in elem.eventListenerList) { - if (key === 'length' || !elem.eventListenerList.hasOwnProperty(key)) { - continue; - } - - for (i = 0; i < elem.eventListenerList[key].length; i += 1) { - target.addEventListener(key, elem.eventListenerList[key][i]); - } - } - } - } - if (elem.hasChildNodes()) { - _addListenerWalk(elem.firstChild, target.firstChild); - } - - elem = elem.nextSibling; - target = target.nextSibling; - } while (elem && target); - }; - - var _detach = function (dialog) { - var widget = _widget_list[dialog.id], - - //window_w, window_h, - w, h, - - screen_left, screen_top, - - dialog_title_element = dialog.firstElementChild.firstElementChild.firstElementChild, - - stripped_title = dialog_title_element.textContent || dialog_title_element.innerText || "", - - child_window = widget.detachable_ref, - - css, css_html, i, dbc = dialog.getBoundingClientRect(); - - if (widget.opts.on_pre_detach) { - widget.opts.on_pre_detach(); - } - - if (dialog.classList.contains(_class_name.minimized)) { - w = parseInt(dialog.style.width, 10); - h = parseInt(dialog.style.height, 10) - 32; - } else { - w = dbc.width; - h = dbc.height - 32; - } - - screen_left = typeof window.screenLeft !== "undefined" ? window.screenLeft : screen.left; - screen_top = typeof window.screenTop !== "undefined" ? window.screenTop : screen.top; - - /*window_w = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.availWidth; - window_h = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.availHeight;*/ - - _close(dialog, true, false, false); - - child_window = window.open("", stripped_title, [ - "toolbar=no", - "location=no", - "directories=no", - "status=no", - "menubar=no", - "scrollbars=yes", - "resizable=yes", - "width=" + w, - "height=" + h, - "top=" + (dbc.top + screen_top + 32),//((window_h-h)/2 + screen_top), - "left=" + (dbc.left + screen_left)].join(','));//((window_w-w) / 2 + screen_left)].join(',')); - - widget.detachable_ref = child_window; - - css_html = ""; - - css = document.head.getElementsByTagName("link"); - - for (i = 0; i < css.length; i += 1) { - if (css[i].type === "text/css" && css[i].rel === "stylesheet") { - css_html += css[i].outerHTML; - } - } - - css = document.head.getElementsByTagName("style"); - - for (i = 0; i < css.length; i += 1) { - css_html += css[i].outerHTML; - } - - // insert the dialog content in the newly opened window - // it insert back all CSS files of the parent as well... - child_window.document.open(); - child_window.document.write(['', - '', - '' + stripped_title + '', - css_html, - '', - '", - //dialog.children[1].outerHTML, - '', - ''].join('')); - child_window.document.close(); - - child_window.document.body.appendChild(dialog.children[1].cloneNode(true)); - - var status_bar = dialog.getElementsByClassName(_class_name.status_bar); - - if (status_bar.length > 0) { - var new_status_bar = status_bar[0].cloneNode(true); - - new_status_bar.classList.add(_class_name.open); - - child_window.document.body.appendChild(new_status_bar); - } - - child_window.addEventListener("keyup", function (ev) { if (ev.keyCode !== 27) { return; } _close(dialog, true, true, true); }, false); - - child_window.addEventListener("resize", function () { _onWindowResize(child_window); }, false); - - child_window.addEventListener("beforeunload", function () { - //_removeDetachedWindow(widget); - _close(dialog, true, true, true); - - if (widget.modal_element) { - document.body.removeChild(widget.modal_element); - } - }, false); - - _detached_windows.push(child_window); - }; - - var _onClick = function (ev) { - ev.preventDefault(); - //ev.stopPropagation(); - - var element = ev.target, - - dialog = null; - - if (element.classList.contains(_class_name.btn_close)) { - dialog = element.parentElement.parentElement; - - _close(dialog, false, true, true); - } else if (element.classList.contains(_class_name.maximize) || - element.classList.contains(_class_name.minimize)) { - dialog = element.parentElement.parentElement; - - _minimize(element, dialog); - } else if (element.classList.contains(_class_name.detach)) { - dialog = element.parentElement.parentElement; - - _detach(dialog); - } - }; - - var _onKeyUp = function (ev) { - if (ev.keyCode !== 27) { - return; - } - - var key, widget; - - for (key in _widget_list) { - if (_widget_list.hasOwnProperty(key)) { - widget = _widget_list[key]; - - if (widget.opts.closable && - (widget.dialog.style.zIndex === "101" || widget.dialog.style.zIndex === "16777271" || widget.dialog.style.zIndex === "16777270") && - widget.dialog.classList.contains(_class_name.open)) { - _self.close(key, true); - - return; - } - } - } - }; - - var _windowMouseMove = function (ev) { - if (!_dragged_dialog) { - return; - } - - ev.preventDefault(); - - var widget = _widget_list[_dragged_dialog.id], - - x = ev.clientX, - y = ev.clientY, - - touches = ev.changedTouches, - - touch = null, - - i, - - new_x, new_y; - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - x = touches[i].clientX; - y = touches[i].clientY; - - break; - } - } - } - - new_x = x - _drag_x; - new_y = y - _drag_y; - - _dragged_dialog.style.left = new_x + 'px'; - _dragged_dialog.style.top = new_y + 'px'; - - if (widget.dialog !== _dragged_dialog) { - widget.dialog.style.left = new_x + 'px'; - widget.dialog.style.top = new_y + 'px'; - } - }; - - var _windowMouseUp = function (ev) { - if (!_dragged_dialog) { - return; - } - - var touches = ev.changedTouches, - - touch = null, - - i, - - owner_doc = _dragged_dialog.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - _dragged_dialog = null; - - owner_doc.body.style.cursor = "default"; - - owner_win.removeEventListener('touchmove', _windowMouseMove, false); - owner_win.removeEventListener('touchend', _windowMouseUp, false); - - break; - } - } - } else { - _dragged_dialog = null; - - owner_doc.body.style.cursor = "default"; - - owner_win.removeEventListener('mousemove', _windowMouseMove, false); - owner_win.removeEventListener('mouseup', _windowMouseUp, false); - } - }; - - var _onMouseDown = function (ev) { - var x = ev.clientX, - y = ev.clientY, - - left = 0, - top = 0, - - touches = ev.changedTouches, - - owner_doc, - owner_win, - - dragged_dialog; - - ev.preventDefault(); - - if (_dragged_dialog === null) { - if (touches) { - _touch_identifier = touches[0].identifier; - - x = touches[0].clientX; - y = touches[0].clientY; - } else if (ev.button !== 0) { - return; - } - } - - dragged_dialog = ev.target.parentElement; - - if (dragged_dialog.classList.contains(_class_name.maximize) || - !dragged_dialog.classList.contains(_class_name.draggable)) { - return; - } - - _dragged_dialog = dragged_dialog; - - owner_doc = _dragged_dialog.ownerDocument; - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - _focus(_dragged_dialog); - - owner_doc.body.style.cursor = "move"; - - left = parseInt(_dragged_dialog.style.left, 10); - top = parseInt(_dragged_dialog.style.top, 10); - - _drag_x = x - left; - _drag_y = y - top; - - owner_win.addEventListener('mousemove', _windowMouseMove, false); - owner_win.addEventListener('touchmove', _windowMouseMove, false); - - owner_win.addEventListener('mouseup', _windowMouseUp, false); - owner_win.addEventListener('touchend', _windowMouseUp, false); - }; - - var _onStartResize = function (e) { - e.preventDefault(); - e.stopPropagation(); - - var dialog = e.target.parentElement, - - left = dialog.offsetLeft, - top = dialog.offsetTop, - - touches = e.changedTouches, - - owner_doc = dialog.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - if (touches) { - _touch_identifier = touches[0].identifier; - } - - _resize_start_x = left; - _resize_start_y = top; - - dialog.classList.remove(_class_name.dim_transition); - - owner_win.addEventListener('mousemove', _onResize, false); - owner_win.addEventListener('touchmove', _onResize, false); - - owner_win.addEventListener('mouseup', _onStopResize, false); - owner_win.addEventListener('touchend', _onStopResize, false); - - _focus(dialog); - - _resized_dialog = dialog; - }; - - var _onResize = function (e) { - e.preventDefault(); - - var x = e.clientX, y = e.clientY, - - touches = e.changedTouches, - - touch = null, - - widget = _widget_list[_resized_dialog.id], - - dialog_contents = null, - - title_div = null, - title_div_width = 0, - - i = 0, - - w, h, off_h = 0; - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - x = touches[i].clientX; - y = touches[i].clientY; - - break; - } - } - } - - w = x - _resize_start_x; - h = y - _resize_start_y; - - /*if (widget.opts.halign === "center") { - w += 2; - } - - if (widget.opts.valign === "center") { - h += 2; - }*/ - - title_div = _resized_dialog.firstElementChild.firstElementChild.firstElementChild; - - title_div_width = title_div.offsetWidth + 148; - - if (widget.opts.min_width === "title" && - w < title_div_width) { - w = title_div_width; - } else if (w < widget.opts.min_width) { - w = widget.opts.min_width; - } - - if (widget.opts.status_bar) { - off_h = 32; - } - - if (h < (widget.opts.min_height + off_h)) { - h = widget.opts.min_height + off_h; - } - - _resized_dialog.style.width = w + "px"; - - if (!_resized_dialog.classList.contains(_class_name.minimized)) { - _resized_dialog.style.height = h + "px"; - } - - dialog_contents = _resized_dialog.getElementsByClassName(_class_name.content); - - for (i = 0; i < dialog_contents.length; i += 1) { - var content = dialog_contents[i], - - widg = _widget_list[content.parentElement.id], - - bcr; - - content.style.height = (_resized_dialog.offsetHeight - 32 - off_h) + "px"; - - bcr = content.getBoundingClientRect(); - - if (widg.opts.on_resize) { - widg.opts.on_resize(bcr.width, bcr.height); - } - - if (widget.opts.keep_align_when_resized) { - _computeThenSetPosition(_resized_dialog); - } - } - }; - - var _onStopResize = function (e) { - var owner_doc = _resized_dialog.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - e.preventDefault(); - - _resized_dialog.classList.add(_class_name.dim_transition); - - owner_win.removeEventListener('mousemove', _onResize, false); - owner_win.removeEventListener('touchmove', _onResize, false); - - owner_win.removeEventListener('mouseup', _onStopResize, false); - owner_win.removeEventListener('touchend', _onStopResize, false); - - _resized_dialog = null; - }; - - var _onBeforeUnload = function () { - for (var id in _widget_list) { - if (_widget_list.hasOwnProperty(id)) { - _close(_widget_list[id].dialog, true, false, true); - } - } - }; - - var _createFailed = function () { - _log("WUI_RangeSlider 'create' failed, first argument not an id nor a DOM element."); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - this.create = function (id, options) { - var dialog, - - header = document.createElement("div"), - - resize_handler = null, - - header_detach_btn = null, - header_close_btn = null, - header_minimaxi_btn = null, - header_title = null, - header_title_wrapper = null, - - element = null, - opt = null, - - status_bar = null, - - opts = {}, - - i = 0, - - key; - - if ((typeof id) === "string") { - dialog = document.getElementById(id); - } else if ((typeof id) === "object") { - if ((typeof id.innerHTML) !== "string") { - _createFailed(); - - return; - } - - dialog = id; - - id = dialog.id; - } else { - _createFailed(); - - return; - } - - if (_widget_list[id] !== undefined) { - _log("WUI_Dialog id '" + id + "' already created, aborting."); - - return; - } - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - } - - var content = dialog.firstElementChild; - - if (content === null) { - content = document.createElement("div"); - - dialog.appendChild(content); - } - - // set dialog style - dialog.style.width = opts.width; - dialog.style.height = opts.height; - - if (opts.min_width != "title") { - dialog.style.minWidth = opts.min_width + "px"; - } - dialog.style.minHeight = opts.min_height + "px"; - - dialog.classList.add(_class_name.dialog); - - content.classList.add(_class_name.content); - - // build the dialog header (btns and the title) - header.className = _class_name.header; - - if (opts.height !== "auto" && opts.height !== "100%") { - if (opts.status_bar) { - content.style.height = dialog.offsetHeight - 64 + "px"; - } else { - content.style.height = dialog.offsetHeight - 32 + "px"; - } - } - - //if (opts.title !== "") { - header_title_wrapper = document.createElement("div"); - header_title = document.createElement("div"); - - header_title_wrapper.style.display = "inline-block"; - header_title_wrapper.className = _class_name.title_wrapper; - - header_title.className = "wui-dialog-title"; - header_title_wrapper.innerHTML = opts.title; - - header_title.appendChild(header_title_wrapper); - header.appendChild(header_title); - //} - - if (opts.draggable) { - dialog.classList.toggle(_class_name.draggable); - - header.addEventListener("mousedown", _onMouseDown, false); - header.addEventListener("touchstart", _onMouseDown, false); - } - - if (opts.closable) { - header_close_btn = document.createElement("div"); - header_close_btn.className = _class_name.btn + " " + _class_name.btn_close; - - header_close_btn.title = "Close"; - - header.appendChild(header_close_btn); - } - - if (opts.minimizable) { - header_minimaxi_btn = document.createElement("div"); - header_minimaxi_btn.className = _class_name.btn + " " + _class_name.minimize; - - if (opts.minimized) { - _minimize(header_minimaxi_btn, dialog); - } - - header.appendChild(header_minimaxi_btn); - } - - if (opts.detachable) { - header_detach_btn = document.createElement("div"); - header_detach_btn.className = _class_name.btn + " " + _class_name.detach; - - header_detach_btn.title = "Detach"; - - header.appendChild(header_detach_btn); - } - - if (opts.header_btn) { - for (i = 0; i < opts.header_btn.length; i += 1) { - opt = opts.header_btn[i]; - element = document.createElement("div"); - - if (opt['title'] !== undefined) { - element.title = opt.title; - } - - if (opt['on_click'] !== undefined) { - element.addEventListener("touchstart", opt.on_click, false); - element.addEventListener("mousedown", opt.on_click, false); - } else { - continue; - } - - if (opt['class_name'] !== undefined) { - element.className = _class_name.btn + " " + opt.class_name; - } else { - continue; - } - - header.appendChild(element); - } - } - - if (opts.status_bar) { - status_bar = document.createElement("div"); - - status_bar.classList.add(_class_name.status_bar); - status_bar.classList.add(_class_name.transition); - status_bar.classList.add(_class_name.open); - - status_bar.innerHTML = opts.status_bar_content; - - dialog.appendChild(status_bar); - } - - header.addEventListener("click", _onClick, false); - header.addEventListener("touchstart", _onClick, false); - - window.addEventListener("resize", function () { _onWindowResize(false); }, false); - window.addEventListener("beforeunload", _onBeforeUnload, false); - - dialog.classList.add(_class_name.transition); - dialog.classList.add(_class_name.dim_transition); - - // go! - dialog.insertBefore(header, content); - - if (opts.resizable) { - resize_handler = document.createElement("div"); - - resize_handler.addEventListener("mousedown", _onStartResize, false); - resize_handler.addEventListener("touchstart", _onStartResize, false); - - resize_handler.classList.add("wui-dialog-resize"); - - resize_handler.classList.add(_class_name.transition); - - resize_handler.classList.add(_class_name.open); - - dialog.appendChild(resize_handler); - } - - _widget_list[id] = { - dialog: dialog, - minimized_id: -1, - - resize_handler: resize_handler, - - header_minimaxi_btn: header_minimaxi_btn, - - header_title: header_title_wrapper, - - opts: opts, - - detachable_ref: null, - - modal_element: null, - - status_bar: status_bar - }; - - _computeThenSetPosition(dialog); - - _focus(dialog); - - if (opts.open) { - this.open(id, false); - } else { - dialog.classList.add(_class_name.closed); - } - - if (opts.min_width === "title") { - dialog.style.minWidth = header_title_wrapper.offsetWidth + 148 + "px"; - } - - return id; - }; - - this.getTitle = function (id) { - var widget = _widget_list[id]; - - if (widget === undefined) { - _log("Cannot getTitle of WUI dialog \"" + id + "\"."); - - return; - } - - if (widget.header_title) { - return widget.header_title.innerHTML; - } - }; - - this.setTitle = function (id, content) { - var widget = _widget_list[id], - - title_bar, - - detach_ref; - - if (widget === undefined) { - _log("Cannot setTitle of WUI dialog \"" + id + "\"."); - - return; - } - - if (widget.header_title) { - widget.header_title.innerHTML = content; - - detach_ref = widget.detachable_ref; - if (detach_ref) { - if (!detach_ref.closed) { - title_bar = detach_ref.document.body.getElementsByClassName(_class_name.title_wrapper); - - if (title_bar.length > 0) { - title_bar[0].innerHTML = content; - } - } - } - } - }; - - this.setStatusBarContent = function (id, content) { - var widget = _widget_list[id], - - status_bar, - - detach_ref; - - if (widget === undefined) { - _log("Cannot setStatusBarContent of WUI dialog \"" + id + "\"."); - - return; - } - - if (widget.status_bar) { - widget.status_bar.innerHTML = content; - - detach_ref = widget.detachable_ref; - if (detach_ref) { - if (!detach_ref.closed) { - status_bar = detach_ref.document.body.getElementsByClassName(_class_name.status_bar); - - if (status_bar.length > 0) { - status_bar[0].innerHTML = content; - } - } - } - } - }; - - this.open = function (id, detach) { - var widget = _widget_list[id], - - div, i, dialog; - - if (widget === undefined) { - _log("Cannot open WUI dialog \"" + id + "\"."); - - return; - } - - if (widget.detachable_ref) { - if (!widget.detachable_ref.closed) { - widget.detachable_ref.focus(); - - return; - } - } - - dialog = widget.dialog; - - if (widget.opts.modal) { - div = _createModalElement(dialog); - - widget.dialog.style.zIndex = 16777271; - - widget.modal_element = div; - - document.body.appendChild(div); - - for (i = 0; i < _detached_windows.length; i += 1) { - div = _createModalElement(dialog); - - _detached_windows[i].document.body.appendChild(div); - } - } - - if (detach) { - _detach(dialog); - - return; - } - - dialog.classList.remove(_class_name.closed); - dialog.classList.add(_class_name.open); - - _focus(dialog); - - if (widget.opts.on_open) { - widget.opts.on_open(); - } - }; - - this.focus = function (id) { - var widget = _widget_list[id]; - - if (widget === undefined) { - _log("Cannot focus WUI dialog \"" + id + "\"."); - - return; - } - - _focus(widget.dialog); - }; - - this.close = function (id, propagate) { - var widget = _widget_list[id]; - - if (widget === undefined) { - _log("Cannot close WUI dialog \"" + id + "\"."); - - return; - } - - _close(widget.dialog, true, propagate, true); - }; - - this.destroy = function (id) { - var widget = _widget_list[id], - - element; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_Dialog, destroying aborted."); - - return; - } - - _close(widget.dialog, true, false, true); - - element = widget.dialog; - - element.parentElement.removeChild(element); - - delete _widget_list[id]; - }; - - // called from a dialog detached window, this basically ensure that the window is initialized before adding back listeners on elements - this.childWindowLoaded = function (id) { - var widget = _widget_list[id], - child_window = widget.detachable_ref; - - if (!child_window) { - return; - } - - if (child_window.document.body.firstElementChild) { - _addListenerWalk(widget.dialog.children[1], child_window.document.body.firstElementChild); - - if (widget.opts.on_detach) { - widget.opts.on_detach(child_window); - } - } else { - window.setTimeout(function(){ // temporary - WUI_Dialog.childWindowLoaded(id); - }, 500); - } - }; - - // get the corresponding detached dialog for dialog dialog_id - this.getDetachedDialog = function (dialog_id) { - var widget = _widget_list[dialog_id], - - i = 0; - - if (widget === undefined) { - if (dialog_id !== undefined) { - _log("WUI_Dialog.getDetachedDialog: Element id '" + dialog_id + "' is not a WUI_Dialog."); - } - - return null; - } - - for (i = 0; i < _detached_windows.length; i += 1) { - if (_detached_windows[i] === widget.detachable_ref) { - return widget.detachable_ref; - } - } - - return null; - }; - - this.closeAll = function (propagate) { - var id, widget; - for (id in _widget_list) { - widget = _widget_list[id]; - if (widget) { - _close(widget.dialog, true, propagate, true); - } - } - }; - - this.centerAll = function () { - var id, widget; - for (id in _widget_list) { - widget = _widget_list[id]; - if (widget) { - var opts = widget.opts, - - dialog = widget.dialog, - - parent_width = dialog.parentElement.offsetWidth, - parent_height = dialog.parentElement.offsetHeight, - - dialog_width = dialog.offsetWidth, - dialog_height = dialog.offsetHeight; - - dialog.style.left = Math.round((parent_width - dialog_width) / 2 + opts.left) + "px"; - dialog.style.top = Math.round((parent_height - dialog_height) / 2 + opts.top) + "px"; - } - } - }; - - document.addEventListener("keyup", _onKeyUp, false); -})(); - -/* jslint browser: true */ -/* jshint globalstrict: false */ -/* global */ - -var WUI_DropDown = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _widget_list = {}, - - _class_name = { - dropdown: "wui-dropdown", - item: "wui-dropdown-item", - content: "wui-dropdown-content", - selected: "wui-dropdown-selected", - open: "wui-dropdown-open", - on: "wui-dropdown-on" - }, - - _known_options = { - width: "auto", - height: 24, - - ms_before_hiding: 2000, - - vertical: false, - - vspacing: 0, - - selected_id: 0, // default item selected - - on_item_selected: null - }; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _log = function (content) { - if (!window.WUI_Reporting) { - return; - } - - if (typeof console !== "undefined") { - console.log(content); - } - }; - - var _getElementOffset = function (element) { - var owner_doc = element.ownerDocument, - box = element.getBoundingClientRect(), - body = owner_doc.body, - docEl = owner_doc.documentElement, - - owner_win = owner_doc.defaultView || owner_doc.parentWindow, - - scrollTop = owner_win.pageYOffset || docEl.scrollTop || body.scrollTop, - scrollLeft = owner_win.pageXOffset || docEl.scrollLeft || body.scrollLeft, - - clientTop = docEl.clientTop || body.clientTop || 0, - clientLeft = docEl.clientLeft || body.clientLeft || 0, - - top = box.top + scrollTop - clientTop, - left = box.left + scrollLeft - clientLeft; - - return { top: Math.round(top), left: Math.round(left) }; - }; - - var _createFloatingContent = function (doc, widget) { - var floating_content = doc.createElement("div"), - div_item = null, - item = "", - i; - - for (i = 0; i < widget.content_array.length; i += 1) { - item = widget.content_array[i]; - - div_item = doc.createElement("div"); - - if (!widget.opts.vertical) { - div_item.classList.add("wui-dropdown-horizontal"); - } - - div_item.classList.add(_class_name.item); - - div_item.innerHTML = item; - - div_item.dataset.index = i; - - floating_content.appendChild(div_item); - - //widget.items.push(div_item); - - div_item.addEventListener("click", _itemClick, false); - - if (item === widget.content_array[widget.selected_id]) { - div_item.classList.add(_class_name.selected); - } - } - - floating_content.addEventListener("mouseover", _mouseOver, false); - - floating_content.classList.add(_class_name.content); - - floating_content.dataset.linkedto = widget.element.id; - - doc.body.appendChild(floating_content); - - widget.floating_content = floating_content; - }; - - var _deleteFloatingContent = function (doc, dd, widget) { - //widget.floating_content.classList.remove(_class_name.open); - dd.classList.remove(_class_name.on); - - if (widget.floating_content) { - if (widget.floating_content.parentElement === doc.body) { - doc.body.removeChild(widget.floating_content); - } - } - - widget.floating_content = null; - - widget.close_timeout = null; - }; - - var _click = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var current_element = ev.target, - - widget = null, - - floating_content = null; - - if (current_element.classList.contains(_class_name.dropdown)) { - widget = _widget_list[current_element.id]; - - floating_content = widget.floating_content; - - if (floating_content) { - if (floating_content.classList.contains(_class_name.open)) { - _deleteFloatingContent(ev.target.ownerDocument, current_element, widget); - } - } else { - _mouseOver(ev); - } - } - - return; - }; - - var _itemClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var current_element = ev.target, - - widget, - - floating_content = null, - - floating_content_childs = null, - - i; - - if (current_element.classList.contains(_class_name.item)) { - floating_content = current_element.parentElement; - - widget = _widget_list[floating_content.dataset.linkedto]; - } else { - return; - } - - floating_content_childs = floating_content.getElementsByTagName('div'); - - for (i = 0; i < floating_content_childs.length; i += 1) { - floating_content_childs[i].classList.remove(_class_name.selected); - } - - current_element.classList.add(_class_name.selected); - - widget.selected_id = parseInt(current_element.dataset.index, 10); - widget.target_element.lastElementChild.innerHTML = current_element.textContent; - - if (widget.element !== widget.target_element) { - widget.element.lastElementChild.innerHTML = current_element.textContent; - } - - if (widget.opts.on_item_selected !== undefined) { - widget.opts.on_item_selected(current_element.dataset.index); - } - - _deleteFloatingContent(current_element.ownerDocument, widget.target_element, widget); - }; - - var _mouseOver = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var current_element = ev.target, - - widget = null, - - offset = null, - - floating_content = null, - - owner_doc = current_element.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - if (current_element.classList.contains(_class_name.dropdown)) { - widget = _widget_list[current_element.id]; - - if (widget.floating_content === null) { - current_element.classList.add(_class_name.on); - - _createFloatingContent(owner_doc, widget); - - floating_content = widget.floating_content; - - offset = _getElementOffset(current_element); - - floating_content.style.top = (offset.top - floating_content.offsetHeight - widget.opts.vspacing) + "px"; - floating_content.style.left = offset.left + "px"; - - floating_content.classList.add(_class_name.open); - - widget.target_element = current_element; - } - } else if ( current_element.classList.contains(_class_name.content)) { - widget = _widget_list[current_element.dataset.linkedto]; - } else if ( current_element.classList.contains(_class_name.item)) { - widget = _widget_list[current_element.parentElement.dataset.linkedto]; - } else { - return; - } - - owner_win.clearTimeout(widget.close_timeout); - - current_element.addEventListener("mouseleave", _mouseLeave, false); - }; - - var _mouseLeave = function (ev) { - ev.preventDefault(); - - var current_element = ev.target, - - widget = null, - - owner_doc = current_element.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - if (current_element.classList.contains(_class_name.content)) { - widget = _widget_list[current_element.dataset.linkedto]; - } else if (current_element.classList.contains(_class_name.item)) { - widget = _widget_list[current_element.parentElement.dataset.linkedto]; - } else { - widget = _widget_list[current_element.id]; - } - - widget.close_timeout = owner_win.setTimeout(_deleteFloatingContent, widget.opts.ms_before_hiding, owner_doc, widget.target_element, widget); - - current_element.removeEventListener("mouseleave", _mouseLeave, false); - }; - - var _createFailed = function () { - _log("WUI_RangeSlider 'create' failed, first argument not an id nor a DOM element."); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - this.create = function (id, options, content_array) { - var dropdown, - - opts = {}, - - key; - - if ((typeof id) === "string") { - dropdown = document.getElementById(id); - } else if ((typeof id) === "object") { - if ((typeof id.innerHTML) !== "string") { - _createFailed(); - - return; - } - - dropdown = id; - - id = dropdown.id; - } else { - _createFailed(); - - return; - } - - if (_widget_list[id] !== undefined) { - _log("WUI_DropDown id '" + id + "' already created, aborting."); - - return; - } - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - } - - dropdown.classList.add(_class_name.dropdown); - - dropdown.style.width = opts.width; - dropdown.style.height = opts.height; - - var div_icon = document.createElement("div"); - div_icon.classList.add("wui-dropdown-icon"); - - dropdown.appendChild(div_icon); - - var div_button = document.createElement("div"); - div_button.classList.add("wui-dropdown-text"); - - if (content_array.length !== 0) { - div_button.innerHTML = content_array[opts.selected_id]; - } - - dropdown.appendChild(div_button); - - dropdown.addEventListener("click", _click, false); - - dropdown.addEventListener("mouseover", _mouseOver, false); - - var dd = { - element: dropdown, - - floating_content: null, - //items: [], - selected_id: opts.selected_id, - - content_array: content_array, - - opts: opts, - - button_item: div_button, - - hover_count: 0, - - target_element: null, - - close_timeout: null - }; - - _widget_list[id] = dd; - - return id; - }; - - this.destroy = function (id) { - var widget = _widget_list[id], - - element; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_DropDown, destroying aborted."); - - return; - } - - element = widget.element; - - _deleteFloatingContent(document, element, widget); - - element.parentElement.removeChild(element); - - delete _widget_list[id]; - }; -})(); - -/* jslint browser: true */ -/* jshint globalstrict: false */ -/* global */ - -var WUI_RangeSlider = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _widget_list = {}, - - _hook_value = null, - - _grabbed_widget = null, - _grabbed_hook_element = null, - - _touch_identifier = null, - - _container_suffix_id = "_wui_container", - - //_midi_learn_disabled_color = "background-color: #ff0000", - _midi_learn_enabled_color = "background-color: #00ff00", - _midi_learn_current = null, - _midi_controls = { - - }, - - _title = { - midi_learn_btn: "MIDI learn" - }, - - _class_name = { - hook: "wui-rangeslider-hook", - bar: "wui-rangeslider-bar", - filler: "wui-rangeslider-filler", - - hook_focus: "wui-rangeslider-hook-focus", - - value_input: "wui-rangeslider-input", - - midi_learn_btn: "wui-rangeslider-midi-learn-btn" - }, - - _known_options = { - width: 148, - height: 8, - - title: "", - - title_min_width: 0, - value_min_width: 0, - - min: 0, - max: 1, - - decimals: 4, - - step: 0.01, - scroll_step: 0.01, - - vertical: false, - - title_on_top: false, - - on_change: null, - - default_value: 0.0, - value: 0.0, - - bar: true, - - midi: null, - - /* - can be an object with the following fields (example) : - { - min: { min: 0, max: 0, val: 0 }, - max: { min: 0, max: 0, val: 0 }, - step: { min: 0, max: 0, val: 0 }, - scroll_step: { min: 0, max: 0, val: 0 } - } - if one of these keys are undefined, the option will be not configurable - */ - configurable: null - }, - - _known_configurable_options = { - min: 0, - max: 0, - step: 0, - scroll_step: 0 - }, - - // exportable parameters - _exportable_parameters = { - opts: {}, - endless: false, - midi: {}, - value: 0 - }; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _log = function (content) { - if (!window.WUI_Reporting) { - return; - } - - if (typeof console !== "undefined") { - console.log(content); - } - }; - - // find the same slider element from a detached WUI_Dialog - var _getDetachedElement = function (id) { - var node = document.getElementById(id), - - wui_dialog_id, - win_handle; - - while (node) { - if (node.classList) { - if (node.classList.contains('wui-dialog')) { - wui_dialog_id = node.id; - break; - } - } - - node = node.parentNode; - } - - if (WUI_Dialog) { - win_handle = WUI_Dialog.getDetachedDialog(wui_dialog_id); - - if (win_handle) { - return win_handle.document.getElementById(id); - } - } - - return null; - }; - - var _getElementOffset = function (element) { - var owner_doc = element.ownerDocument, - box = element.getBoundingClientRect(), - body = owner_doc.body, - docEl = owner_doc.documentElement, - - owner_win = owner_doc.defaultView || owner_doc.parentWindow, - - scrollTop = owner_win.pageYOffset || docEl.scrollTop || body.scrollTop, - scrollLeft = owner_win.pageXOffset || docEl.scrollLeft || body.scrollLeft, - - clientTop = docEl.clientTop || body.clientTop || 0, - clientLeft = docEl.clientLeft || body.clientLeft || 0, - - top = box.top + scrollTop - clientTop, - left = box.left + scrollLeft - clientLeft; - - return { top: Math.round(top), left: Math.round(left) }; - }; - - var _onChange = function (func, value) { - if (func !== null) { - func(value); - } - }; - - var _truncateDecimals = function (num, digits) { - var n = (+num).toFixed(digits + 1); - return +(n.slice(0, n.length - 1)); - }; - - var _truncateFloat = function (num, precision) { - var mult = 1.0, prec = precision; - - if (prec > 0) { - while (prec--) { - mult *= 10; - } - } - - return ((num * mult) >> 0) / mult; - }; - - var _getHookElementFromTarget = function (ev_target) { - if (ev_target.classList.contains(_class_name.hook)) { - return ev_target; - } else if (ev_target.classList.contains(_class_name.filler)) { - return ev_target.firstElementChild; - } else if (!ev_target.firstElementChild) { - return null; - } - - return ev_target.firstElementChild.firstElementChild; - }; - - var _update = function (rs_element, rs, value) { - var element = rs_element, - - widget = _widget_list[element.id], - - bar, - filler, - hook, - - value_input, - - width = rs.opts.width, - height = rs.opts.height, - - pos = Math.abs((value - rs.opts.min) / rs.opts.range); - - bar = element.getElementsByClassName(_class_name.bar)[0]; - filler = bar.firstElementChild; - hook = filler.firstElementChild; - - value_input = bar.nextElementSibling; - -// value = _truncateDecimals(value, widget.opts.decimals); - - if (rs.opts.vertical) { - pos = Math.round(pos * bar.offsetHeight); - - filler.style.position = "absolute"; - filler.style.bottom = "0"; - filler.style.width = "100%"; - filler.style.height = pos + "px"; - - hook.style.marginTop = -width + "px"; - hook.style.marginLeft = -width / 2 - 1 + "px"; - - hook.style.width = width * 2 + "px"; - hook.style.height = width * 2 + "px"; - - value_input.style.marginTop = "13px"; - - // all theses are to support synchronization between a detached dialog and the original dialog - // TODO: optimize/clean all this mess :P - if (widget.element !== element) { - widget.filler.style.position = "absolute"; - widget.filler.style.bottom = "0"; - widget.filler.style.width = "100%"; - widget.filler.style.height = pos + "px"; - - widget.hook.style.marginTop = -width + "px"; - widget.hook.style.marginLeft = -width / 2 - 1 + "px"; - - widget.hook.style.width = width * 2 + "px"; - widget.hook.style.height = width * 2 + "px"; - - widget.value_input.style.marginTop = "13px"; - } - } else { - pos = Math.round(pos * width); - - filler.style.width = pos + "px"; - filler.style.height = "100%"; - - hook.style.left = pos + "px"; - - hook.style.marginTop = -height / 2 + "px"; - hook.style.marginLeft = -height + "px"; - - hook.style.width = height * 2 + "px"; - hook.style.height = height * 2 + "px"; - - if (widget.element !== element) { - widget.filler.style.width = pos + "px"; - widget.filler.style.height = "100%"; - - widget.hook.style.left = pos + "px"; - - widget.hook.style.marginTop = -height / 2 + "px"; - widget.hook.style.marginLeft = -height + "px"; - - widget.hook.style.width = height * 2 + "px"; - widget.hook.style.height = height * 2 + "px"; - } - } - - widget.value_input.value = value; - value_input.value = value; - - rs.value = value; - }; - - var _mouseMove = function (ev) { - ev.preventDefault(); - - if (_grabbed_hook_element !== null) { - var filler = _grabbed_hook_element.parentElement, - bar = filler.parentElement, - - value_input = bar.nextElementSibling,//bar.parentElement.lastElementChild, - - bar_offset = _getElementOffset(bar), - max_pos = bar.offsetWidth, - - cursor_relative_pos = 0, - - x = ev.clientX, - y = ev.clientY, - - touches = ev.changedTouches, - - touch = null, - - i, v; - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - x = touches[i].clientX; - y = touches[i].clientY; - - break; - } - } - } - - if (_grabbed_widget.opts.vertical) { - max_pos = bar.offsetHeight; - - cursor_relative_pos = Math.round((bar_offset.top + bar.offsetHeight - y) / _grabbed_widget.opts.step) * _grabbed_widget.opts.step; - } else { - cursor_relative_pos = Math.round((x - bar_offset.left) / _grabbed_widget.opts.step) * _grabbed_widget.opts.step; - } - - if (cursor_relative_pos > max_pos) { - cursor_relative_pos = max_pos; - - _hook_value = _grabbed_widget.opts.max; - } else if (cursor_relative_pos < 0) { - cursor_relative_pos = 0; - - _hook_value = _grabbed_widget.opts.min; - } else { - _hook_value = (Math.round((_grabbed_widget.opts.min + (cursor_relative_pos / max_pos) * _grabbed_widget.opts.range) / _grabbed_widget.opts.step) * _grabbed_widget.opts.step); - } - - if (_grabbed_widget.value === _hook_value) { - return; - } - - _grabbed_widget.value = _hook_value; - - v = _truncateDecimals(_hook_value, _grabbed_widget.opts.decimals); - - value_input.value = v; - _grabbed_widget.value_input.value = v; - - if (_grabbed_widget.opts.vertical) { - filler.style.height = cursor_relative_pos + "px"; - _grabbed_widget.filler.style.height = cursor_relative_pos + "px"; - } else { - filler.style.width = cursor_relative_pos + "px"; - _grabbed_widget.filler.style.width = cursor_relative_pos + "px"; - - _grabbed_hook_element.style.left = cursor_relative_pos + "px"; - _grabbed_widget.hook.style.left = cursor_relative_pos + "px"; - } - - _onChange(_grabbed_widget.opts.on_change, _hook_value); - } - }; - - var _rsMouseUp = function (ev) { - if (!_grabbed_hook_element) { - return; - } - - ev.preventDefault(); - - var touches = ev.changedTouches, - - touch = null, - - stop_drag = false, - - i, - - owner_doc = _grabbed_hook_element.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - stop_drag = true; - - owner_win.removeEventListener("touchend", _rsMouseUp, false); - owner_win.removeEventListener("touchmove", _mouseMove, false); - - break; - } - } - } else { - stop_drag = true; - - owner_win.removeEventListener("mouseup", _rsMouseUp, false); - owner_win.removeEventListener("mousemove", _mouseMove, false); - } - - if (stop_drag) { - _grabbed_hook_element.classList.remove(_class_name.hook_focus); - - _grabbed_hook_element = null; - _grabbed_widget = null; - - owner_doc.body.style.cursor = "default"; - } - }; - - var _rsMouseDown = function (ev) { - //ev.preventDefault(); - ev.stopPropagation(); - - var rs_element = null, - - drag_slider = false, - - touches = ev.changedTouches, - - owner_doc, - owner_win; - - if (_grabbed_widget === null) { - if (touches) { - _touch_identifier = touches[0].identifier; - - drag_slider = true; - } - } - - if (ev.button === 0) { - drag_slider = true; - } - - if (drag_slider) { - _grabbed_hook_element = _getHookElementFromTarget(ev.target); - - _grabbed_hook_element.classList.add(_class_name.hook_focus); - - rs_element = _grabbed_hook_element.parentElement.parentElement.parentElement; - - _grabbed_widget = _widget_list[rs_element.id]; - - owner_doc = rs_element.ownerDocument; - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - owner_doc.body.style.cursor = "pointer"; - - _mouseMove(ev); - - owner_win.addEventListener("mousemove", _mouseMove, false); - owner_win.addEventListener("touchmove", _mouseMove, false); - owner_win.addEventListener("mouseup", _rsMouseUp, false); - owner_win.addEventListener("touchend", _rsMouseUp, false); - } - }; - - var _rsDblClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var hook_element = ev.target, - - rs_element = hook_element.parentElement.parentElement.parentElement, - - grabbed_widget = _widget_list[rs_element.id], - - value = grabbed_widget.opts.default_value; - - _update(rs_element, grabbed_widget, value); - - _onChange(grabbed_widget.opts.on_change, value); - }; - - var _rsMouseWheel = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var hook_element, - rs_element, - grabbed_widget, - delta = ev.wheelDelta ? ev.wheelDelta / 40 : ev.detail ? -ev.detail : 0, - value; - - if (ev.deltaY) { - delta = -ev.deltaY; - } - - hook_element = _getHookElementFromTarget(ev.target); - - if (hook_element === null) { - rs_element = ev.target.parentElement; - grabbed_widget = _widget_list[rs_element.id]; - } else { - rs_element = hook_element.parentElement.parentElement.parentElement; - grabbed_widget = _widget_list[rs_element.id]; - } - - value = parseFloat(grabbed_widget.value); - - if (delta >= 0) { - value += grabbed_widget.opts.scroll_step; - } else { - value -= grabbed_widget.opts.scroll_step; - } - - if (!grabbed_widget.endless) { - if (grabbed_widget.opts.max && value > grabbed_widget.opts.max) { - value = grabbed_widget.opts.max; - } else if (value < grabbed_widget.opts.min) { - value = grabbed_widget.opts.min; - } - } - - _update(rs_element, grabbed_widget, value); - - _onChange(grabbed_widget.opts.on_change, value); - }; - - var _inputChange = function (ev) { - if ((ev.target.validity) && (!ev.target.validity.valid)) { - return; - } - -/* - var target = ev.target.parentElement.childNodes[1]; - - if (target === undefined) { - return; - } - - var hook_element = _getHookElementFromTarget(target), -*/ - var rs_element = /*hook_element*/ev.target.parentElement/*.parentElement.parentElement*/, - - grabbed_widget = _widget_list[rs_element.id]; - - _update(rs_element, grabbed_widget, ev.target.value); - - _onChange(grabbed_widget.opts.on_change, ev.target.value); - }; - - var _fnConfInputChange = function (ev, widget, conf_key) { - return function (ev) { - var target = ev.target, - opts = widget.opts; - - if ((target.validity) && (!target.validity.valid)) { - if (conf_key === "min" || - conf_key === "max") { - widget.endless = true; - } else if (conf_key === "step") { - widget.value_input.step = "any"; - } - - return; - } - - if (conf_key === "min") { - opts.min = _truncateDecimals(target.value, opts.decimals); - - widget.value_input.min = opts.min; - - //if (opts.min < 0) { - opts.range = opts.max - opts.min; - //} - - widget.endless = false; - } else if (conf_key === "max") { - opts.max = _truncateDecimals(target.value, opts.decimals); - - widget.value_input.max = opts.max; - - //opts.range = opts.max; - - //if (opts.min < 0) { - opts.range = opts.max - opts.min; - //} - - widget.endless = false; - } else if (conf_key === "step") { - opts.step = _truncateDecimals(target.value, opts.decimals); - - widget.value_input.step = opts.step; - } else if (conf_key === "scroll_step") { - opts.scroll_step = _truncateDecimals(target.value, opts.decimals); - } - - if (opts.configurable[conf_key] !== undefined) { - opts.configurable[conf_key].val = target.value; - } - }; - }; - - var _removeMIDIControls = function (id) { - var device, - control, - - ctrl_obj, - - widget_id, - - i; - - if (id) { - for(device in _midi_controls) { - for(control in _midi_controls[device]) { - ctrl_obj = _midi_controls[device][control]; - - for (i = 0; i < ctrl_obj.widgets.length; i += 1) { - widget_id = ctrl_obj.widgets[i]; - - if (widget_id === id) { - ctrl_obj.widgets.splice(i, 1); - - return; - } - } - } - } - } - }; - - var _onMIDILearnBtnClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var target = ev.target, - rs_element = target.parentElement, - - widget = _widget_list[rs_element.id], - - detached_slider, - - key, - value_obj, - - elems; - - if (widget.learn) { - widget.learn = false; - - target.style = ""; - target.title = _title.midi_learn_btn; - - widget.learn_elem.title = _title.midi_learn_btn; - - _midi_learn_current = null; - - widget.midi.device = null; - widget.midi.controller = null; - - _removeMIDIControls(rs_element.id); - - return; - } - - for(key in _widget_list) { - if (_widget_list.hasOwnProperty(key)) { - value_obj = _widget_list[key]; - - value_obj.learn = false; - - detached_slider = _getDetachedElement(key); - - if (detached_slider) { - elems = detached_slider.getElementsByClassName(_class_name.midi_learn_btn); - if (elems.length > 0) { - elems[0].style = ""; - } - } - - if (value_obj.learn_elem) { - value_obj.learn_elem.style = ""; - } - } - } - - widget.learn = true; - - target.style = _midi_learn_enabled_color; - - _midi_learn_current = rs_element.id; - }; - - var _onConfigurableBtnClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var target = ev.target, - rs_element = target.parentElement, - - widget = _widget_list[rs_element.id], - - opts = widget.opts, - - owner_doc = target.ownerDocument, - - id = widget.element.id + _container_suffix_id, - - fn, - btn_offset, - key, key_value, - configure_container, - input_label, input_element, - close_btn, - i = 1; - - if (!document.getElementById(id)) { - widget.configure_panel_open = false; - } - - if (widget.configure_panel_open === true) { - return; - } - - configure_container = owner_doc.createElement("div"); - configure_container.className = "wui-rangeslider-configure-container"; - - close_btn = owner_doc.createElement("div"); - close_btn.className = "wui-rangeslider-configure-close"; - - fn = function (ev) { - widget.configure_panel_open = false; - - var doc_cc = document.getElementById(id), - own_cc = ev.target.ownerDocument.getElementById(id); - - if (doc_cc) { - if (doc_cc.parentElement) { - doc_cc.parentElement.removeChild(doc_cc); - } - } - - if (own_cc) { - if (own_cc.parentElement) { - own_cc.parentElement.removeChild(own_cc); - } - } - }; - - close_btn.addEventListener("click", fn, false); - close_btn.addEventListener("touchstart", fn, false); - - configure_container.id = id; - - configure_container.appendChild(close_btn); - - for (key in opts.configurable) { - if (opts.configurable.hasOwnProperty(key)) { - if (_known_configurable_options[key] !== undefined) { - key_value = opts.configurable[key]; - - input_label = owner_doc.createElement("div"); - input_label.style.display = "inline-block"; - input_label.style.marginRight = "8px"; - input_label.style.width = "80px"; - input_label.style.textAlign = "right"; - input_label.innerHTML = key.replace("_", " ") + " : "; - - input_element = owner_doc.createElement("input"); - input_element.className = _class_name.value_input; - - //input_element.style.display = "inline-block"; - - configure_container.appendChild(input_label); - configure_container.appendChild(input_element); - - if (i%2 === 0) { - configure_container.appendChild(owner_doc.createElement("div")); - } - - input_element.setAttribute("type", "number"); - input_element.setAttribute("step", "any"); - - if (key_value !== undefined) { - if (key_value.min !== undefined) { - input_element.setAttribute("min", key_value.min); - input_element.title = input_element.title + " min: " + key_value.min; - } - if (key_value.max !== undefined) { - input_element.setAttribute("max", key_value.max); - input_element.title = input_element.title + " max: " + key_value.max; - } - if (key_value.val !== undefined) { - input_element.setAttribute("value", key_value.val); - } else { - if (key === "min") { - input_element.setAttribute("value", opts.min); - } else if (key === "max") { - input_element.setAttribute("value", opts.max); - } else if (key === "step") { - input_element.setAttribute("value", opts.step); - } else if (key === "scroll_step") { - input_element.setAttribute("value", opts.scroll_step); - } - } - } - - input_element.addEventListener("input", _fnConfInputChange(ev, widget, key), false); - - i += 1; - } - } - } - - btn_offset = _getElementOffset(target); - - //configure_container.style.top = btn_offset.top + "px"; - //configure_container.style.left = btn_offset.left + "px"; - - /*owner_doc.body*/rs_element.insertBefore(configure_container, target); - - widget.configure_panel_open = true; - }; - - var _createFailed = function () { - _log("WUI_RangeSlider 'create' failed, first argument not an id nor a DOM element."); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - this.create = function (id, options) { - var range_slider, - - wheel_evt, - - opts = {}, - - key; - - if ((typeof id) === "string") { - range_slider = document.getElementById(id); - } else if ((typeof id) === "object") { - if ((typeof id.innerHTML) !== "string") { - _createFailed(); - - return; - } - - range_slider = id; - - id = range_slider.id; - } else { - _createFailed(); - - return; - } - - if (_widget_list[id] !== undefined) { - _log("WUI_RangeSlider id '" + id + "' already created, aborting."); - - return; - } - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - - if (options.max !== undefined) { - opts.range = options.max; - } - - if (options.step !== undefined) { - opts.step = options.step; - - if (options.scroll_step === undefined) { - opts.scroll_step = opts.step; - } - } - - if (options.title_on_top !== undefined) { - opts.title_on_top = options.title_on_top; - } else { - if (opts.vertical) { - opts.title_on_top = true; - } - } - - if (options.default_value !== undefined) { - opts.default_value = options.default_value; - } else { - if (options.min !== undefined && options.max !== undefined) { - opts.default_value = opts.min + opts.max / 2; - } - } - } - - if (opts.min < opts.max) { - opts.range = opts.max - opts.min; - } - - // build up the range slider widget internal data structure - _widget_list[id] = null; - - // build the range slider and its items - range_slider.classList.add("wui-rangeslider"); - - if (opts.title_on_top) { - range_slider.classList.add("wui-rangeslider-title-ontop"); - } - - var title_div = document.createElement("div"), - bar = document.createElement("div"), - filler = document.createElement("div"), - hook = document.createElement("div"), - value_div = document.createElement("div"), - value_input = document.createElement("input"), - - rs = { - element: range_slider, - - opts: opts, - - bar: null, - filler: null, - hook: null, - - endless: false, - - midi: { - device: null, - controller: null, - - ctrl_type: "abs" - }, - - learn: false, - learn_elem: null, - - value_input: value_input, - - default_value: opts.default_value, - value: opts.value - }; - - title_div.innerHTML = opts.title; - - value_input.setAttribute("value", opts.value); - value_input.setAttribute("type", "number"); - value_input.setAttribute("step", opts.step); - - value_input.classList.add(_class_name.value_input); - - value_div.classList.add("wui-rangeslider-value"); - title_div.classList.add("wui-rangeslider-title"); - bar.classList.add(_class_name.bar); - filler.classList.add(_class_name.filler); - hook.classList.add(_class_name.hook); - - if (opts.vertical) { - title_div.style.textAlign = "center"; - } - - title_div.style.minWidth = opts.title_min_width + "px"; - value_div.style.minWidth = opts.value_min_width + "px"; - value_input.style.minWidth = opts.value_min_width + "px"; - - bar.style.width = opts.width + "px"; - bar.style.height = opts.height + "px"; - - range_slider.appendChild(title_div); - - if (!opts.bar) { - bar.style.display = "none"; - - value_input.style.marginTop = "6px"; - } - - if (options.hasOwnProperty("min")) { - value_input.setAttribute("min", opts.min); - } else { - opts.min = undefined; - } - - if (options.hasOwnProperty("max")) { - value_input.setAttribute("max", opts.max); - } else { - opts.max = undefined; - - if (opts.min === undefined) { - rs.endless = true; - } - } - - bar.appendChild(filler); - filler.appendChild(hook); - range_slider.appendChild(bar); - - rs.bar = bar; - rs.filler = filler; - rs.hook = hook; - - range_slider.appendChild(value_input); - - if (opts.configurable) { - var configurable_opts = 0; - for (key in opts.configurable) { - if (opts.configurable.hasOwnProperty(key)) { - if (_known_configurable_options[key] !== undefined) { - configurable_opts += 1; - } - } - } - - // add configurable button - if (configurable_opts > 0) { - var configurable_btn_div = document.createElement("div"); - - configurable_btn_div.classList.add("wui-rangeslider-configurable-btn"); - - configurable_btn_div.addEventListener("click", _onConfigurableBtnClick, false); - configurable_btn_div.addEventListener("touchstart", _onConfigurableBtnClick, false); - - // accomodate the slider layout for the configurable button - if (opts.title_on_top && !opts.vertical) { - configurable_btn_div.style.bottom = "0"; - title_div.style.marginBottom = "4px"; - } else if (opts.title_on_top && opts.vertical) { - title_div.style.marginLeft = "16px"; - title_div.style.marginRight = "16px"; - configurable_btn_div.style.top = "0"; - } else { - title_div.style.marginLeft = "16px"; - configurable_btn_div.style.top = "0"; - } - - if (opts.vertical) { - range_slider.appendChild(configurable_btn_div); - } else { - range_slider.insertBefore(configurable_btn_div, title_div); - } - } - } - - if (opts.midi) { - if (navigator.requestMIDIAccess) { - var midi_learn_elem = document.createElement("div"); - midi_learn_elem.classList.add(_class_name.midi_learn_btn); - midi_learn_elem.title = _title.midi_learn_btn; - - midi_learn_elem.addEventListener("click", _onMIDILearnBtnClick, false); - midi_learn_elem.addEventListener("touchstart", _onMIDILearnBtnClick, false); - - rs.learn_elem = midi_learn_elem; - - if (opts.midi["type"]) { - rs.midi.ctrl_type = opts.midi.type; - } - - range_slider.appendChild(midi_learn_elem); - } else { - _log("WUI_RangeSlider id '" + id + "' : Web MIDI API is disabled. (not supported by your browser?)"); - } - } - - wheel_evt = "onwheel" in document.createElement("div") ? "wheel" : document.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll"; - - if (opts.bar) { - bar.addEventListener("mousedown", _rsMouseDown, false); - bar.addEventListener("touchstart", _rsMouseDown, false); - bar.addEventListener(wheel_evt, _rsMouseWheel, false); - - hook.addEventListener("dblclick", _rsDblClick, false); - } else { - value_input.addEventListener(wheel_evt, _rsMouseWheel, false); - } - - value_input.addEventListener("input", _inputChange, false); - - _widget_list[id] = rs; - - _update(range_slider, rs, opts.value); - - _onChange(rs.opts.on_change, rs.value); - - return id; - }; - - this.destroy = function (id) { - var widget = _widget_list[id], - - element, - - owner_doc, - - container_element; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_RangeSlider, destroying aborted."); - - return; - } - - if (_midi_learn_current === id) { - _midi_learn_current = null; - } - - _removeMIDIControls(id); - - element = widget.element; - - element.parentElement.removeChild(element); - - owner_doc = element.ownerDocument; - - container_element = owner_doc.getElementById(id + _container_suffix_id); - - if (container_element) { - owner_doc.removeChild(container_element); - } - - delete _widget_list[id]; - }; - - this.getParameters = function (id) { - var widget = _widget_list[id], - parameters = { }, - key; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_RangeSlider, getParameters aborted."); - - return null; - } - - for (key in widget) { - if (widget.hasOwnProperty(key)) { - if (_exportable_parameters[key] !== undefined) { - parameters[key] = widget[key]; - } - } - } - - return parameters; - }; - - this.setParameters = function (id, parameters, trigger_on_change) { - var widget = _widget_list[id], - key; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_RangeSlider, setParameters aborted."); - - return; - } - - if (!parameters) { - return; - } - - for (key in widget) { - if (widget.hasOwnProperty(key)) { - if (parameters[key] !== undefined) { - widget[key] = parameters[key]; - } - } - } - - if (widget.midi.device) { - if (widget.midi.controller) { - _midi_controls["d" + widget.midi.device]["c" + widget.midi.controller].widgets.push(id); - } - } - - _update(widget.element, widget, widget.value); - - if (trigger_on_change) { - _onChange(widget.opts.on_change, widget.value); - } - }; - - this.setValue = function (id, value, trigger_on_change) { - var widget = _widget_list[id]; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_RangeSlider, setParameters aborted."); - - return; - } - - _update(widget.element, widget, value); - - if (trigger_on_change) { - _onChange(widget.opts.on_change, value); - } - }; - - this.submitMIDIMessage = function (midi_event) { - var id = _midi_learn_current, - - widget, - - device = midi_event.data[0], - controller = midi_event.data[1], - value = parseInt(midi_event.data[2], 10), - - kdevice = "d" + device, - kcontroller = "c" + controller, - - ctrl_obj, - - elems, - elem, - - detached_slider, - - new_value, - - i = 0; - - if (_midi_learn_current) { - widget = _widget_list[id]; - - if (!widget) { - _midi_learn_current = null; - } else { - if (!_midi_controls[kdevice]) { - _midi_controls[kdevice] = {}; - } - - if (!_midi_controls[kdevice][kcontroller]) { - _midi_controls[kdevice][kcontroller] = { - prev_value: value, - widgets: [], - increments: 1 - }; - } - - _midi_controls[kdevice][kcontroller].widgets.push(id); - - var isAbs = (widget.midi.ctrl_type === "abs" && widget.opts.range !== undefined && widget.opts.min !== undefined); - var type = isAbs ? "abs" : "rel"; - - detached_slider = _getDetachedElement(id); - if (detached_slider) { - elems = detached_slider.getElementsByClassName(_class_name.midi_learn_btn); - if (elems.length > 0) { - elems[0].style = ""; - elems[0].title = kdevice + " " + kcontroller + " (" + type + ")"; - } - } - - widget.midi.device = device; - widget.midi.controller = controller; - - widget.learn = false; - widget.learn_elem.style = ""; - widget.learn_elem.title = kdevice + " " + kcontroller + " (" + type + ")"; - _midi_learn_current = null; - - return; - } - } - - if (_midi_controls[kdevice]) { - if (_midi_controls[kdevice][kcontroller]) { - ctrl_obj = _midi_controls[kdevice][kcontroller]; - - for (i = 0; i < ctrl_obj.widgets.length; i += 1) { - id = ctrl_obj.widgets[i]; - - widget = _widget_list[id]; - - // clean MIDI stuff / widget when it don't exist anymore (may have been deleted) - if (!widget) { - if (_midi_learn_current === id) { - _midi_learn_current = null; - } - - _removeMIDIControls(id); - - delete _widget_list[id]; - - continue; - } - - detached_slider = _getDetachedElement(id); - if (detached_slider) { - elem = detached_slider; - } else { - elem = widget.element; - } - - if (widget.midi.ctrl_type === "abs" && widget.opts.range !== undefined && widget.opts.min !== undefined) { - new_value = widget.opts.min + widget.opts.range * (value / 127.0); - new_value = _truncateFloat(new_value, widget.opts.decimals); - - _update(elem, widget, new_value); - - _onChange(widget.opts.on_change, new_value); - } else if (widget.midi.ctrl_type === "rel" || (widget.midi.ctrl_type === "abs" && (widget.opts.range === undefined || widget.opts.min === undefined))) { - var step = widget.opts.step; - if (step === "any") { - step = 0.5; - } - - if (ctrl_obj.prev_value > value) { - ctrl_obj.increments = -step; - - new_value = widget.value - step; - - if (new_value < widget.opts.min && !widget.endless && widget.opts.min !== undefined) { - continue; - } - - ctrl_obj.prev_value = value; - } else if (ctrl_obj.prev_value < value) { - ctrl_obj.increments = step; - - new_value = widget.value + step; - - if (new_value > widget.opts.max && !widget.endless && widget.opts.max !== undefined) { - continue; - } - - ctrl_obj.prev_value = value; - } else { - new_value = widget.value + ctrl_obj.increments; - - if (!widget.endless && widget.opts.min !== undefined && widget.opts.max !== undefined) { - if (new_value > widget.opts.max) { - continue; - } else if (new_value < widget.opts.min) { - continue; - } - } - } - - new_value = _truncateFloat(new_value, widget.opts.decimals); - - _update(elem, widget, new_value); - - _onChange(widget.opts.on_change, new_value); - } - } - } - } - }; -})(); - -var WUI_Input = WUI_RangeSlider; - -/* jslint browser: true */ -/* jshint globalstrict: false */ - -var WUI_Tabs = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _widget_list = {}, - - _class_name = { - enabled: "wui-tab-enabled", - disabled: "wui-tab-disabled", - display_none: "wui-tab-display-none", - tabs: "wui-tabs", - tab: "wui-tab", - tabs_content: "wui-tabs-content", - tab_content: "wui-tab-content", - underline: "wui-tabs-underline" - }, - - _known_options = { - on_tab_click: null, - - height: "calc(100% - 30px)" - }; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _log = function (content) { - if (!window.WUI_Reporting) { - return; - } - - if (typeof console !== "undefined") { - console.log(content); - } - }; - - var _onTabClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var tab_elem = ev.target, - - tabs = tab_elem.parentElement, - content = tabs.nextElementSibling.nextElementSibling, - - widget_id = tabs.parentElement.id, - - widget = _widget_list[widget_id], - - tab_index = 0, - elem = null, - - i = 0; - - for (i = 0; i < tabs.childElementCount; i += 1) { - elem = tabs.children[i]; - - elem.classList.remove(_class_name.enabled); - elem.classList.add(_class_name.disabled); - - widget.tabs[i].classList.remove(_class_name.enabled); - widget.tabs[i].classList.add(_class_name.disabled); - - if (elem === tab_elem) { - tab_index = i; - } - } - - for (i = 0; i < content.childElementCount; i += 1) { - elem = content.children[i]; - - elem.classList.remove(_class_name.display_none); - - widget.contents[i].classList.remove(_class_name.display_none); - - if (tab_index !== i) { - elem.classList.add(_class_name.display_none); - - widget.contents[i].classList.add(_class_name.display_none); - } - } - - widget.tabs[tab_index].classList.remove(_class_name.disabled); - widget.tabs[tab_index].classList.add(_class_name.enabled); - - ev.target.classList.remove(_class_name.disabled); - ev.target.classList.add(_class_name.enabled); - - if (widget.opts.on_tab_click) { - widget.opts.on_tab_click(tab_index); - } - }; - - var _createFailed = function () { - _log("WUI_RangeSlider 'create' failed, first argument not an id nor a DOM element."); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - /** - * Create a tabs widget from an element. - * @param {String} id DOM Element id - * @param {Function} tab_click_callback Called when a tab is clicked - */ - this.create = function (id, options) { - var element, - - tabs, - underline = document.createElement("div"), - content, - - first_tab, - - opts = {}, - - key, - - i = 0; - - if ((typeof id) === "string") { - element = document.getElementById(id); - } else if ((typeof id) === "object") { - if ((typeof id.innerHTML) !== "string") { - _createFailed(); - - return; - } - - element = id; - - id = element.id; - } else { - _createFailed(); - - return; - } - - tabs = element.firstElementChild; - content = tabs.nextElementSibling; - - first_tab = tabs.children[0]; - - if (_widget_list[id] !== undefined) { - _log("WUI_Tabs id '" + id + "' already created, aborting."); - - return; - } - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - } - - element.style.overflow = "hidden"; - - underline.className = "wui-tabs-underline"; - - element.insertBefore(underline, content); - - // style tabs - tabs.classList.add(_class_name.tabs); - - var tab_count = tabs.childElementCount, - tab_elems = []; - - for (i = 0; i < tab_count; i += 1) { - var tab = tabs.children[i]; - - tab.classList.add("wui-tab"); - - if (tab !== first_tab) { - tab.classList.add(_class_name.disabled); - } - - tab.addEventListener("click", _onTabClick, false); - tab.addEventListener("touchstart", _onTabClick, false); - - tab_elems.push(tab); - } - - first_tab.classList.add(_class_name.enabled); - first_tab.classList.add("wui-first-tab"); - - // style tabs content - content.classList.add("wui-tabs-content"); - - var tab_content_count = content.childElementCount, - content_elems = [content.children[0]]; - - content.style.height = opts.height; - - content.children[0].classList.add(_class_name.tab_content); - - for (i = 1; i < tab_content_count; i += 1) { - var tab_content = content.children[i]; - - tab_content.classList.add(_class_name.tab_content); - tab_content.classList.add(_class_name.display_none); - - content_elems.push(tab_content); - } - - _widget_list[id] = { element: element, tabs: tab_elems, contents: content_elems, opts : opts }; - - return id; - }; - - /** - * Get tab content element from a widget id and tab id - * @param {String} id Widget id - * @param {Number} tab_id Tab id - * @returns {Object} DOM Element of the tab content - */ - this.getContentElement = function (id, tab_id) { - var element = document.getElementById(id); - var content = element.firstElementChild.nextElementSibling.nextElementSibling; - - return content.children[tab_id]; - }; - - /** - * Get a tab name from a widget id and tab id - * @param {String} id Widget id - * @param {Number} tab_id Tab id - * @returns {String} Tab name - */ - - this.getTabName = function (id, tab_id) { - var content = this.getContentElement(id, tab_id); - - return content.getAttribute("data-group-name"); - }; - - this.destroy = function (id) { - var widget = _widget_list[id], - - element, - - tabs, tabs_underline, tabs_content, - - i; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_Tabs, destroying aborted."); - - return; - } - - element = widget.element; - - // make it compatible with WUI_Dialog, it shouldn't remove the WUI_Dialog content div... - if (!element.classList.contains("wui-dialog-content")) { - element.parentElement.removeChild(element); - } else { - tabs = element.getElementsByClassName(_class_name.tabs); - tabs_underline = element.getElementsByClassName(_class_name.underline); - tabs_content = element.getElementsByClassName(_class_name.tabs_content); - - for (i = 0; i < tabs.length; i += 1) { - element.removeChild(tabs[i]); - element.removeChild(tabs_underline[i]); - element.removeChild(tabs_content[i]); - } - } - - delete _widget_list[id]; - }; -})(); - -/* jslint browser: true */ -/* jshint globalstrict: false */ - -var WUI_ToolBar = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _widget_list = {}, - - _class_name = { - minimize_icon: "wui-toolbar-minimize-icon", - maximize_icon: "wui-toolbar-maximize-icon", - button: "wui-toolbar-button", - minimize_group: "wui-toolbar-minimize-group", - minimize_gr_v: "wui-toolbar-minimize-group-vertical", - toggle: "wui-toolbar-toggle", - toggle_on: "wui-toolbar-toggle-on", - item: "wui-toolbar-item", - group: "wui-toolbar-group", - vertical_group: "wui-toolbar-group-vertical", - group_title: "wui-toolbar-group-title", - group_title_vertical: "wui-toolbar-group-title-vertical", - group_title_vertical_s: "wui-toolbar-group-title-vertical-s", - tb: "wui-toolbar", - - // dropdown - dd_content: "wui-toolbar-dropdown-content", - dd_item: "wui-toolbar-dropdown-item", - dd_open: "wui-toolbar-dropdown-open" - }, - - _known_options = { - item_hmargin: null, - item_vmargin: null, - - item_width: 32, - item_height: 32, - - icon_width: 32, - icon_height: 32, - - show_groups_title: false, - groups_title_orientation: "s", - - allow_groups_minimize: false, - - vertical: false - }; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _log = function (content) { - if (!window.WUI_Reporting) { - return; - } - - if (typeof console !== "undefined") { - console.log(content); - } - }; - - var _getWidget = function (toolbar_id) { - var widget = _widget_list[toolbar_id]; - - if (widget === undefined) { - _log("_getWidget failed, the element id \"" + toolbar_id + "\" is not a WUI_ToolBar."); - - return null; - } - - return widget; - }; - - var _getElementOffset = function (element) { - var owner_doc = element.ownerDocument, - box = element.getBoundingClientRect(), - body = owner_doc.body, - docEl = owner_doc.documentElement, - - owner_win = owner_doc.defaultView || owner_doc.parentWindow, - - scrollTop = owner_win.pageYOffset || docEl.scrollTop || body.scrollTop, - scrollLeft = owner_win.pageXOffset || docEl.scrollLeft || body.scrollLeft, - - clientTop = docEl.clientTop || body.clientTop || 0, - clientLeft = docEl.clientLeft || body.clientLeft || 0, - - top = box.top + scrollTop - clientTop, - left = box.left + scrollLeft - clientLeft; - - return { top: Math.round(top), left: Math.round(left) }; - }; - - var _getWidgetFromElement = function (element, toolbar_id) { - if (toolbar_id !== undefined) { - return _widget_list[toolbar_id]; - } else if (element.classList.contains(_class_name.tb)) { - return _widget_list[element.id]; - } else if (element.classList.contains(_class_name.minimize_icon) || - element.classList.contains(_class_name.maximize_icon) || - element.classList.contains(_class_name.vertical_group)|| - element.classList.contains(_class_name.group)) { - return _widget_list[element.parentElement.id]; - } else { - return _widget_list[element.parentElement.parentElement.id]; - } - }; - - var _propagate = function (tool, type, state) { - if (tool.on_click !== undefined && - tool.on_click !== null) { - var o = { - id: tool.id, - type: type - }; - - if (state !== undefined) { - o.state = state; - } - - tool.on_click(o); - } - }; - - var _createDdFloatingContent = function (doc, tool, widget) { - var dropdown_floating_content = doc.createElement("div"), j; - - if (tool.items !== undefined) { - for (j = 0; j < tool.items.length; j += 1) { - var item = tool.items[j], - - div_item = doc.createElement("div"); - - if (!tool.vertical) { - div_item.classList.add("wui-toolbar-dropdown-horizontal"); - } - - div_item.classList.add(_class_name.dd_item); - - div_item.innerHTML = item.title; - - div_item.dataset.index = j; - - dropdown_floating_content.appendChild(div_item); - } - } - - dropdown_floating_content.addEventListener("click", _ddItemClick, false); - - //widget.floating_content = dropdown_floating_content; - - dropdown_floating_content.style.width = widget.dd_items_width + "px"; - - dropdown_floating_content.classList.add(_class_name.dd_content); - - dropdown_floating_content.dataset.linkedto_tb = widget.element.id; - dropdown_floating_content.dataset.linkedto_tool_index = tool.id; - - doc.body.appendChild(dropdown_floating_content); - - return dropdown_floating_content; - }; - - var _toggle = function (element, toolbar_id, propagate) { - var widget = null, - - state = false, - - toggle_group, - - tb, - - tools, - - i = 0; - - widget = _getWidgetFromElement(element, toolbar_id); - - tb = widget.element; - - if (element.parentElement) { - if (element.parentElement.parentElement) { - tb = element.parentElement.parentElement; - } - } - - var my_tool = widget.tools[parseInt(element.dataset.tool_id, 10)]; - - if (my_tool.element.dataset.on === "1") { - my_tool.element.dataset.on = 0; - element.dataset.on = 0; - - my_tool.element.title = my_tool.tooltip; - - element.title = my_tool.tooltip; - - if (my_tool.icon !== undefined) { - my_tool.element.classList.add(my_tool.icon); - my_tool.element.classList.remove(my_tool.toggled_icon); - - element.classList.add(my_tool.icon); - element.classList.remove(my_tool.toggled_icon); - } - } else { - my_tool.element.dataset.on = 1; - element.dataset.on = 1; - - if (my_tool.tooltip_toggled !== undefined) { - my_tool.element.title = my_tool.tooltip_toggled; - element.title = my_tool.tooltip_toggled; - } - - if (my_tool.toggled_icon !== undefined) { - my_tool.element.classList.add(my_tool.toggled_icon); - my_tool.element.classList.remove(my_tool.icon); - - element.classList.add(my_tool.toggled_icon); - element.classList.remove(my_tool.icon); - } - - state = true; - } - - if (my_tool.toggled_style !== "none") { - if (element.classList.contains(_class_name.toggle_on)) { - my_tool.element.classList.remove(_class_name.toggle_on); - element.classList.remove(_class_name.toggle_on); - } else { - my_tool.element.classList.add(_class_name.toggle_on); - element.classList.add(_class_name.toggle_on); - } - } - - toggle_group = element.dataset.toggle_group; - - if (toggle_group !== undefined) { - tools = tb.getElementsByClassName(_class_name.item); - - for (i = 0; i < tools.length; i += 1) { - var tool_element = tools[i], - - tool = widget.tools[parseInt(tool_element.dataset.tool_id, 10)]; - - if (toggle_group === tool_element.dataset.toggle_group && - tool_element.dataset.tool_id !== element.dataset.tool_id) { - - if (tool_element.dataset.on === "0") { - continue; - } - - tool_element.dataset.on = "0"; - tool.element.dataset.on = "0"; - - tool_element.classList.remove(_class_name.toggle_on); - tool.element.classList.remove(_class_name.toggle_on); - - if (my_tool.toggled_icon !== undefined) { - tool_element.classList.remove(tool.toggled_icon); - tool.element.classList.remove(tool.toggled_icon); - } - - if (my_tool.icon !== undefined) { - tool_element.classList.add(tool.icon); - tool.element.classList.add(tool.icon); - } - - if (propagate || propagate === undefined) { - _propagate(tool, "toggle", false); - } - } - } - } - - if (propagate === true || propagate === undefined) { - _propagate(my_tool, "toggle", state); - } - }; - - var _ddItemClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var item_element = ev.target, - - doc = item_element.ownerDocument, - - dropdown_content = item_element.parentElement, - - widget = _widget_list[dropdown_content.dataset.linkedto_tb], - - tool_index = parseInt(dropdown_content.dataset.linkedto_tool_index, 10), - - my_tool = widget.tools[tool_index], - - item_index = parseInt(item_element.dataset.index, 10), - - item = my_tool.items[item_index], - - tb_elem = doc.getElementById(dropdown_content.dataset.linkedto_tb), - - tool_elems = tb_elem.getElementsByClassName(_class_name.item), - - tool_elem = tool_elems[tool_index]; - - if (item.on_click !== undefined) { - item.on_click(); - - tool_elem.classList.remove(_class_name.toggle_on); - my_tool.element.classList.remove(_class_name.toggle_on); - - _removeDdFloatingContent(my_tool, tool_elem); - //dropdown_content.classList.remove(_class_name.dd_open); - } - }; - - var _removeDdFloatingContent = function (tool, element) { - var owner_doc = element.ownerDocument, - - floating_contents = owner_doc.body.getElementsByClassName(_class_name.dd_content), - - floating_content_element, - - i; - - for (i = 0; i < floating_contents.length; i += 1) { - floating_content_element = floating_contents[i]; - - floating_content_element.removeEventListener("click", _ddItemClick, false); - floating_content_element.parentElement.removeChild(floating_content_element); - } - - tool.element.classList.remove(_class_name.toggle_on); - element.classList.remove(_class_name.toggle_on); - }; - - var _removeDdFloatingContentHandler = function (tool, element) { - var handler = function () { - var owner_doc = element.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - _removeDdFloatingContent(tool, element); - - owner_win.removeEventListener('click', handler); - }; - - return handler; - }; - - var _onClick = function (ev) { - ev.preventDefault(); - ev.stopPropagation(); - - var element = ev.target; - - // delegation - if (element.classList.contains(_class_name.minimize_group) || - element.classList.contains(_class_name.minimize_gr_v)) { - _minimizeGroup(element); - - return; - } else if (element.classList.contains(_class_name.toggle)) { - _toggle(element); - - return; - } else if (element.classList.contains(_class_name.tb) || - element.classList.contains(_class_name.group) || - element.classList.contains(_class_name.vertical_group)) { - return; - } - - // else, regular button - - var my_tool = null, - - dropdown_floating_content = null, - - offset = null, - - widget = null, - - owner_doc = element.ownerDocument, - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - widget = _getWidgetFromElement(element); - - my_tool = widget.tools[element.dataset.tool_id]; - - if (my_tool.type === "dropdown") { - if (element.classList.contains(_class_name.toggle_on)) { - _removeDdFloatingContent(my_tool, element); - - return; - } - - dropdown_floating_content = _createDdFloatingContent(owner_doc, my_tool, widget); - - var tool_element = my_tool.element; - - element.classList.add(_class_name.toggle_on); - tool_element.classList.add(_class_name.toggle_on); - - offset = _getElementOffset(element); - - if (my_tool.dd_items_width === "tb_item") { - dropdown_floating_content.style.width = element.offsetWidth + "px"; - } - - if (my_tool.orientation === "s") { - dropdown_floating_content.style.top = (offset.top + element.offsetHeight) + "px"; - dropdown_floating_content.style.left = offset.left + "px"; - } else if (my_tool.orientation === "sw") { - dropdown_floating_content.style.top = (offset.top + element.offsetHeight) + "px"; - dropdown_floating_content.style.left = (offset.left - dropdown_floating_content.offsetWidth) + "px"; - } else if (my_tool.orientation === "nw") { - dropdown_floating_content.style.top = (offset.top - dropdown_floating_content.offsetHeight + element.offsetHeight) + "px"; - dropdown_floating_content.style.left = (offset.left - dropdown_floating_content.offsetWidth) + "px"; - } else if (my_tool.orientation === "se") { - dropdown_floating_content.style.top = (offset.top + element.offsetHeight) + "px"; - dropdown_floating_content.style.left = (offset.left + element.offsetWidth) + "px"; - } else if (my_tool.orientation === "ne") { - dropdown_floating_content.style.top = (offset.top - dropdown_floating_content.offsetHeight + element.offsetHeight) + "px"; - dropdown_floating_content.style.left = (offset.left + element.offsetWidth) + "px"; - } else { // n - dropdown_floating_content.style.top = (offset.top - dropdown_floating_content.offsetHeight) + "px"; - dropdown_floating_content.style.left = offset.left + "px"; - } - - dropdown_floating_content.classList.add(_class_name.dd_open); - - if(ev.stopPropagation) { - ev.stopPropagation(); - } - - owner_win.addEventListener("click", _removeDdFloatingContentHandler(my_tool, element), false); - } else { - _propagate(my_tool, "click"); - } - }; - - var _minimizeGroup = function (minimize_element) { - var group = minimize_element.nextSibling; - - if (minimize_element.classList.contains(_class_name.minimize_icon)) { - minimize_element.classList.add(_class_name.maximize_icon); - minimize_element.classList.remove(_class_name.minimize_icon); - - minimize_element.title = "Maximize group"; - - group.style.display = "none"; - } else { - minimize_element.classList.add(_class_name.minimize_icon); - minimize_element.classList.remove(_class_name.maximize_icon); - - minimize_element.title = "Minimize group"; - - group.style.display = ""; - } - }; - - var _createFailed = function () { - _log("WUI_RangeSlider 'create' failed, first argument not an id nor a DOM element."); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - /** - * Create a toolbar widget from an element. - * - * @param {String} id DOM Element id - * @param {Object} options [[Description]] - * @param {Array} tools [[Description]] - * @returns {String} Created widget reference, internally used to recognize the widget - */ - this.create = function (id, options, tools) { - var toolbar, - - group = null, - elem = null, - - index = null, - - previous_group = null, - - opts = {}, - - key; - - if ((typeof id) === "string") { - toolbar = document.getElementById(id); - } else if ((typeof id) === "object") { - if ((typeof id.innerHTML) !== "string") { - _createFailed(); - - return; - } - - toolbar = id; - - id = toolbar.id; - } else { - _createFailed(); - - return; - } - - if (_widget_list[id] !== undefined) { - _log("WUI_Toolbar id '" + id + "' already created, aborting."); - - return; - } - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - } - - // build up the toolbar widget internal data structure - _widget_list[id] = { - element: toolbar, - - tools: [], - opts: opts - }; - - // build the toolbar and its items - toolbar.classList.add(_class_name.tb); - - var group_class = _class_name.group, - item_class = _class_name.item, - spacer_class = "wui-toolbar-spacer", - group_minimize_class = _class_name.minimize_group; - - if (opts.vertical) { - toolbar.classList.add("wui-toolbar-vertical"); - - group_class = _class_name.vertical_group; - item_class += " wui-toolbar-item-vertical"; - spacer_class = "wui-toolbar-spacer-vertical"; - group_minimize_class = _class_name.minimize_gr_v; - - toolbar.style.maxWidth = (opts.item_width + 4) + "px"; - - if (opts.item_hmargin === null) { - opts.item_hmargin = 3; - } - - if (opts.item_vmargin === null) { - opts.item_vmargin = 8; - } - } else { - toolbar.style.maxHeight = (opts.item_height + 4) + "px"; - - if (opts.item_hmargin === null) { - opts.item_hmargin = 3; - } - - if (opts.item_vmargin === null) { - opts.item_vmargin = 0; - } - } - - group_minimize_class = _class_name.button + " " + _class_name.minimize_icon + " " + group_minimize_class; - - toolbar.addEventListener("click", _onClick, false); - - var i; - - for(index in tools) { - if (tools.hasOwnProperty(index)) { - if (previous_group !== null) { - elem = document.createElement("div"); - elem.className = spacer_class; - - toolbar.appendChild(elem); - } - - if (opts.allow_groups_minimize) { - elem = document.createElement("div"); - elem.className = group_minimize_class; - - elem.title = "Minimize group"; - - toolbar.appendChild(elem); - } - - group = tools[index]; - - var group_element = document.createElement("div"); - group_element.className = group_class; - - if (opts.vertical) { - group_element.style.maxWidth = opts.item_width + "px"; - } else { - group_element.style.maxHeight = opts.item_height + "px"; - } - - for (i = 0; i < group.length; i += 1) { - var tool = group[i], - tool_element = document.createElement("div"), - - tool_id = _widget_list[id].tools.length, - - widget = { - element: tool_element, - on_click: tool.on_click, - on_rclick: tool.on_rclick, - icon: tool.icon, - items: [], - tooltip: "", - type: tool.type, - dd_items_width: tool.dropdown_items_width, - orientation: tool.orientation, - id: tool_id - }, - - j; - - if (widget.on_rclick) { - tool_element.addEventListener("contextmenu", function (e) { - var widget = _getWidgetFromElement(e.target), - my_tool = widget.tools[e.target.dataset.tool_id]; - - e.preventDefault(); - - my_tool.on_rclick(); - }); - } - - tool_element.className = item_class; - - tool_element.style.minWidth = opts.item_width + "px"; - tool_element.style.minHeight = opts.item_height + "px"; - tool_element.style.marginLeft = opts.item_hmargin + "px"; - tool_element.style.marginRight = opts.item_hmargin + "px"; - tool_element.style.marginTop = opts.item_vmargin + "px"; - tool_element.style.marginBottom = opts.item_vmargin + "px"; - - tool_element.style.backgroundSize = (opts.icon_width - 4) + "px " + (opts.icon_height - 4) + "px"; - - group_element.appendChild(tool_element); - - _widget_list[id].tools.push(widget); - - tool_element.dataset.tool_id = tool_id; - - widget.tooltip = tool.tooltip; - - if (tool.tooltip !== undefined) { - tool_element.title = tool.tooltip; - } - - if (tool.text !== undefined) { - tool_element.innerHTML = tool.text; - - tool_element.style.lineHeight = opts.item_height + "px"; - - tool_element.classList.add("wui-toolbar-text"); - - if (tool.icon !== undefined) { - tool_element.style.paddingLeft = (opts.icon_width + 2) + "px"; - tool_element.style.backgroundPosition = "left center"; - } - } - - if (tool.icon !== undefined) { - tool_element.classList.add(tool.icon); - } - - if (tool.id !== undefined) { - tool_element.id = tool.id; - } - - // handle button type - if (tool.type === "toggle") { - tool_element.classList.add(_class_name.toggle); - - widget.toggled_icon = tool.toggled_icon; - widget.tooltip_toggled = tool.tooltip_toggled; - widget.toggled_style = tool.toggled_style; - - if (tool.toggle_group !== undefined) { - tool_element.dataset.toggle_group = tool.toggle_group; - } - - if (tool.toggle_state) { - tool_element.dataset.on = "1"; - } - } else if (tool.type === "dropdown") { - tool_element.classList.add(_class_name.button); - - if (tool.items !== undefined) { - for (j = 0; j < tool.items.length; j += 1) { - var item = tool.items[j]; - widget.items.push({ title: item.title, on_click: item.on_click }); - } - } - } else { // default to standard button - tool_element.classList.add(_class_name.button); - } - } - - if (opts.show_groups_title) { - var group_title = document.createElement("div"); - - if (opts.vertical) { - group_title.classList.add(_class_name.group_title_vertical); - } else { - group_title.classList.add(_class_name.group_title); - } - group_title.innerHTML = index; - - if (opts.groups_title_orientation === "s") { - group_element.appendChild(group_title); - group_title.classList.add(_class_name.group_title_vertical_s); - } else { - group_element.insertBefore(group_title, group_element.firstChild); - } - } - - toolbar.appendChild(group_element); - - previous_group = group; - } - } - - // now setup tools state, this could have been done before, - // but to work with the detachable dialog widget we need them added to the toolbar before calling _toggle etc. - var tools_elems = toolbar.getElementsByClassName(_class_name.item); - - for (i = 0; i < tools_elems.length; i += 1) { - var tool_elem = tools_elems[i]; - - if (tool_elem.dataset.on === "1") { - tool_elem.dataset.on = "0"; - - _toggle(tool_elem, id, true); - } - } - - return id; - }; - - this.hideGroup = function (toolbar_id, group_index) { - var widget = _getWidget(toolbar_id), - - groups, group, minimize_group; - - if (widget) { - if (widget.opts.vertical) { - groups = widget.element.getElementsByClassName(_class_name.vertical_group); - } else { - groups = widget.element.getElementsByClassName(_class_name.group); - } - - if (groups.length === 0) { - return; - } - - group = groups[group_index]; - - minimize_group = group.previousElementSibling; - - if (minimize_group.classList.contains(_class_name.minimize_group) || - minimize_group.classList.contains(_class_name.minimize_gr_v)) { - minimize_group.style.display = "none"; - } - - group.style.display = "none"; - } - }; - - this.showGroup = function (toolbar_id, group_index) { - var widget = _getWidget(toolbar_id), - - groups, group, minimize_group; - - if (widget) { - if (widget.opts.vertical) { - groups = widget.element.getElementsByClassName(_class_name.vertical_group); - } else { - groups = widget.element.getElementsByClassName(_class_name.group); - } - - if (groups.length === 0) { - return; - } - - group = groups[group_index]; - - minimize_group = group.previousElementSibling; - - if (minimize_group.classList.contains(_class_name.minimize_group) || - minimize_group.classList.contains(_class_name.minimize_gr_v)) { - minimize_group.style.display = ""; - } - - groups[group_index].style.display = ""; - } - }; - - this.toggle = function (toolbar_id, tool_index, propagate) { - var widget = _getWidget(toolbar_id); - - if (widget) { - _toggle(widget.tools[tool_index].element, toolbar_id, propagate); - } - }; - - this.getItemElement = function (toolbar_id, tool_index) { - var widget = _getWidget(toolbar_id); - - if (widget) { - return widget.tools[tool_index].element; - } - }; - - this.destroy = function (id) { - var widget = _widget_list[id], - - element, - - tools, tool, tool_items, first_item, first_item_element, - - i; - - if (widget === undefined) { - _log("Element id '" + id + "' is not a WUI_ToolBar, destroying aborted."); - - return; - } - - element = widget.toolbar; - - tools = widget.tools; - - element.parentElement.removeChild(element); - - // destroy any related content as well (like the floating element created by a dropdown tool) - for (i = 0; i < tools.length; i += 1) { - tool = tools[i]; - - if (tool.type === "dropdown") { - tool_items = tool.items; - - if (tool_items.length > 0) { - first_item = tool_items[0]; - - first_item_element = first_item.element; - - first_item_element.parentElement.removeChild(first_item_element); - } - } - } - - delete _widget_list[id]; - }; -})(); - -/* jslint browser: true */ -/* jshint globalstrict: false */ - -var WUI_CircularMenu = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _elems = [], - - _last_time = 0, - - _class_name = { - item: "wui-circularmenu-item", - show: "wui-circularmenu-show", - content: "wui-circularmenu-content" - }, - - _known_options = { - x: null, - y: null, - - rx: 64, - ry: 48, - - angle: 0, - - item_width: 32, - item_height: 32, - - window: null, - - element: null - }; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _destroy = function (doc) { - var elem, - - i; - - //try { // this is in case it is in a detached WUI dialog, it will try to remove something that does not exist if the dialog was closed while the circular menu is still shown - for (i = 0; i < _elems.length; i += 1) { - elem = _elems[i]; - - if (doc.body.contains(elem)) { - doc.body.removeChild(elem); - } - } - /*} catch (e) { - _elems = []; - }*/ - }; - - var _onClickOutHandler = function (win, doc) { - var handler = function (ev) { - ev.preventDefault(); - - var now = new Date().getTime(); - if (now - _last_time <= 500) { - return; - } - - if (ev.target.classList.contains(_class_name.item)) { - return; - } - - _destroy(doc); - - //win.removeEventListener("click", handler); - win.removeEventListener("mousedown", handler); - }; - - return handler; - }; - - var _onClickHandler = function (win, doc, cb) { - var handler = function (ev) { - ev.preventDefault(); - - cb(); - - _destroy(doc); - - win.removeEventListener("mousedown", _onClickOutHandler(win, doc)); - }; - - return handler; - }; - - var _getElementOffset = function (elem) { - var box = elem.getBoundingClientRect(), - body = elem.ownerDocument.body, - docEl = elem.ownerDocument.documentElement, - - scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop, - scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft, - - clientTop = docEl.clientTop || body.clientTop || 0, - clientLeft = docEl.clientLeft || body.clientLeft || 0, - - top = box.top + scrollTop - clientTop, - left = box.left + scrollLeft - clientLeft; - - return { top: Math.round(top), left: Math.round(left), width: box.width, height: box.height }; - }; - - var _toRadians = function (angle) { - return angle * (Math.PI / 180.0); - }; - - var _addItems = function (opts, items, win, doc, x, y) { - _destroy(doc); - - var elem, content, item, i, handler, - a = -(Math.PI / 2) + _toRadians(opts.angle), - c = items.length, - ia = (Math.PI * 2 / c); - - for (i = 0; i < c; i += 1) { - item = items[i]; - - elem = doc.createElement("div"); - - elem.classList.add(_class_name.item); - - elem.style.width = opts.item_width + "px"; - elem.style.height = opts.item_height + "px"; - - elem.style.backgroundSize = (opts.item_width - 4) + "px " + (opts.item_height - 4) + "px"; - - elem.style.left = (x + opts.rx * Math.cos(a)) + "px"; - elem.style.top = (y + opts.ry * Math.sin(a)) + "px"; - - elem.classList.add(item.icon); - - if (item.tooltip) { - elem.title = item.tooltip; - } - - if (item.content) { - content = doc.createElement("div"); - - content.style.width = opts.item_width + "px"; - content.style.height = opts.item_height + "px"; - - content.classList.add(_class_name.content); - - content.innerHTML = item.content; - - elem.appendChild(content); - } - - doc.body.appendChild(elem); - - // for the transition to work, force the layout engine - win.getComputedStyle(elem).width; - - _elems.push(elem); - - if (item.on_click) { - elem.addEventListener("click", _onClickHandler(win, doc, item.on_click)); - } - - if (item.on_right_click) { - elem.addEventListener("contextmenu", _onClickHandler(win, doc, item.on_right_click)); - } - - if (item.on_middle_click) { - elem.addEventListener("auxclick", _onClickHandler(win, doc, item.on_middle_click)); - } - - elem.classList.add(_class_name.show); - - a += ia; - } - - handler = _onClickOutHandler(win, doc); - - //win.addEventListener("click", handler); - - _last_time = new Date().getTime(); - - win.addEventListener("mousedown", handler); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - /** - * Create a circular menu. - */ - this.create = function (options, items) { - var opts = {}, - - key, - - x, y, - - elem, - elem_bcr, - - owner_doc = document, - owner_win = window; - - for (key in _known_options) { - if (_known_options.hasOwnProperty(key)) { - opts[key] = _known_options[key]; - } - } - - if (options !== undefined) { - for (key in options) { - if (options.hasOwnProperty(key)) { - if (_known_options[key] !== undefined) { - opts[key] = options[key]; - } - } - } - } - - elem = opts.element; - - if (elem !== null) { - elem_bcr = _getElementOffset(elem); - - owner_doc = elem.ownerDocument; - owner_win = owner_doc.defaultView || owner_doc.parentWindow; - - x = elem_bcr.left + (elem_bcr.width - opts.item_width) / 2; - y = elem_bcr.top + (elem_bcr.height - opts.item_height) / 2; - - _addItems(opts, items, owner_win, owner_doc, x, y); - } else if (x !== null && y !== null) { - if (opts.window !== null) { - owner_win = opts.window; - owner_doc = owner_win.document; - } - - x = opts.x - opts.item_width / 2; - y = opts.y - opts.item_height / 2; - - _addItems(opts, items, owner_win, owner_doc, x, y); - } - }; -})(); - -/* jslint browser: true */ -/* jshint globalstrict: false */ -/* global WUI_ToolBar, WUI_DropDown, WUI_RangeSlider, WUI_Tabs, WUI_Dialog */ - -var WUI = new (function() { - "use strict"; - - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - - var _class_name = { - display_none: "wui-display-none", - hide_fi_500: "wui-hide-fi-500", - hide_show_500: "wui-show-fi-500", - draggable: "wui-draggable" - }, - - - // Draggable - _draggables = [], - - _dragged_element = null, - _dragged_element_id = null, - - _touch_identifier = null, - - _drag_x = 0, - _drag_y = 0; - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - - var _hideHandler = function (element, fade_finish_cb, hide_when_fade_finish) { - var handler = function () { - if (hide_when_fade_finish) { - element.classList.add(_class_name.display_none); - } - - if (fade_finish_cb) { - fade_finish_cb(); - } - - element.removeEventListener('transitionend', handler); - }; - - return handler; - }; - - var _dragStart = function (ev) { - ev.preventDefault(); - - var x = ev.clientX, - y = ev.clientY, - - draggable, - - touches = ev.changedTouches; - - if (!ev.target.classList.contains(_class_name.draggable)) { - return; - } - - if (_dragged_element === null) { - if (touches) { - _touch_identifier = touches[0].identifier; - - x = touches[0].clientX; - y = touches[0].clientY; - } else if (ev.button !== 0) { - return; - } - } - - draggable = _draggables[parseInt(ev.target.dataset.wui_draggable_id, 10)]; - - if (draggable.target_element !== undefined) { - _dragged_element = draggable.target_element; - } else { - _dragged_element = ev.target; - } - - _dragged_element_id = parseInt(_dragged_element.dataset.wui_draggable_id, 10); - - document.body.style.cursor = "move"; - - if (draggable.virtual) { - draggable = _draggables[_dragged_element_id]; - - _drag_x = x - parseInt(draggable.x, 10); - _drag_y = y - parseInt(draggable.y, 10); - } else { - _drag_x = x - parseInt(_dragged_element.style.left, 10); - _drag_y = y - parseInt(_dragged_element.style.top, 10); - } - - window.addEventListener('mousemove', _drag, false); - window.addEventListener('touchmove', _drag, false); - - window.addEventListener('mouseup', _dragStop, false); - window.addEventListener('touchend', _dragStop, false); - }; - - var _drag = function (ev) { - ev.preventDefault(); - - var x = ev.clientX, - y = ev.clientY, - - touches = ev.changedTouches, - - touch = null, - - i, - - draggable = _draggables[_dragged_element_id], - - new_x = draggable.x, new_y = draggable.y; - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - x = touches[i].clientX; - y = touches[i].clientY; - - break; - } - } - } - - if (draggable.axisLock !== 0) { - new_x = x - _drag_x; - - if (!draggable.virtual) { - _dragged_element.style.left = new_x + 'px'; - } - - draggable.x = new_x; - } - - if (draggable.axisLock !== 1) { - new_y = y - _drag_y; - - if (!draggable.virtual) { - _dragged_element.style.top = new_y + 'px'; - } - - draggable.y = new_y; - } - - if (draggable) { - if (draggable.cb !== undefined) { - draggable.cb(_dragged_element, new_x, new_y); - } - } - }; - - var _dragStop = function (ev) { - ev.preventDefault(); - - var touches = ev.changedTouches, - - touch = null, - - i; - - if (_draggables.length === 0) { - return; - } - - if (touches) { - for (i = 0; i < touches.length; i += 1) { - touch = touches[i]; - - if (touch.identifier === _touch_identifier) { - _dragged_element = null; - - document.body.style.cursor = "default"; - - window.removeEventListener('touchmove', _drag, false); - window.removeEventListener('touchend', _dragStop, false); - - break; - } - } - } else { - _dragged_element = null; - - document.body.style.cursor = "default"; - - window.removeEventListener('mousemove', _drag, false); - window.removeEventListener('mouseup', _dragStop, false); - } - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - - /** - * Apply a fade out effect to the element. - * - * @param {Object} element DOM Element - * @param {Callback} fade_finish_cb Function called when the fade out effect finish - * @param {Boolean} hide_when_fade_finish If true, add a "display: none;" style class automatically when the fade out effect finish - */ - this.fadeOut = function (element, duration_ms, fade_finish_cb, hide_when_fade_finish) { - var transition_str; - - if (duration_ms === undefined || duration_ms === null) { - duration_ms = 500; - } - - transition_str = "visibility 0s ease-in-out " + duration_ms + "ms, opacity " + duration_ms + "ms ease-in-out"; - - if (element.style['WebkitTransition'] === undefined) { - element.style.transition = transition_str; - } else { - element.style.WebkitTransition = transition_str; - } - - element.addEventListener('transitionend', _hideHandler(element, fade_finish_cb, hide_when_fade_finish), false); - - element.classList.add(_class_name.hide_fi_500); - element.classList.remove(_class_name.hide_show_500); - }; - - /** - * Apply a fade in effect to the element. - * - * @param {Object} element DOM Element - */ - this.fadeIn = function (element, duration_ms) { - var transition_str; - - if (duration_ms === undefined || duration_ms === null) { - duration_ms = 500; - } - - transition_str = "visibility 0s ease-in-out 0s, opacity " + duration_ms + "ms ease-in-out"; - - if (element.style['WebkitTransition'] === undefined) { - element.style.transition = transition_str; - } else { - element.style.WebkitTransition = transition_str; - } - - element.classList.remove(_class_name.hide_fi_500); - element.classList.add(_class_name.hide_show_500); - - element.classList.remove(_class_name.display_none); - }; - - /** - * Make an element draggable - * - * @param {Object} element DOM Element - * @param {Callback} function called when the element is being dragged, it has two argument which is the new x/y - * @param {Boolean} virtual true to keep track of element position WITHOUT updating the element position (updating it is left to users through the callback) - * @param {Object} element DOM Element target, the drag will happen on this element, the first argument will just initiate the drag event - */ - this.draggable = function (element, on_drag_cb, virtual, target_element) { - if (element.classList.contains(_class_name.draggable)) { - return; - } - - element.classList.add(_class_name.draggable); - - element.addEventListener("mousedown", _dragStart, false); - element.addEventListener("touchstart", _dragStart, false); - - element.dataset.wui_draggable_id = _draggables.length; - - _draggables.push({ - cb: on_drag_cb, - element: element, - target_element: target_element, - axisLock: null, - virtual: virtual, - x: parseInt(element.style.left, 10), - y: parseInt(element.style.top, 10) - }); - }; - - /** - * Make an element undraggable - * - * @param {Object} element DOM Element - */ - this.undraggable = function (element) { - if (!element.classList.contains(_class_name.draggable)) { - return; - } - - element.classList.remove(_class_name.draggable); - - element.removeEventListener("mousedown", _dragStart, false); - element.removeEventListener("touchstart", _dragStart, false); - - var id = parseInt(element.dataset.wui_draggable_id, 10), - - i; - - _draggables.splice(id, 1); - - for (i = 0; i < _draggables.length; i += 1) { - var draggable = _draggables[i]; - - draggable.element.dataset.wui_draggable_id = i; - } - }; - - this.lockDraggable = function (element, axis) { - if (!element.classList.contains(_class_name.draggable)) { - return; - } - - var draggable = _draggables[parseInt(element.dataset.wui_draggable_id, 10)]; - - if (axis === 'x') { - draggable.axisLock = 0; - } else if (axis === 'y') { - draggable.axisLock = 1; - } else { - draggable.axisLock = null; - } - }; -})(); - -// Processing.js - http://processingjs.org/download/ -!function s(o,a,l){function h(t,e){if(!a[t]){if(!o[t]){var n="function"==typeof require&&require;if(!e&&n)return n(t,!0);if(u)return u(t,!0);var r=new Error("Cannot find module '"+t+"'");throw r.code="MODULE_NOT_FOUND",r}var i=a[t]={exports:{}};o[t][0].call(i.exports,function(e){return h(o[t][1][e]||e)},i,i.exports,s,o,a,l)}return a[t].exports}for(var u="function"==typeof require&&require,e=0;e"),i.print.apply(i,e),i.BufferArray.length>i.BufferMax?i.BufferArray.splice(0,1):i.javaconsole.scrollTop=i.javaconsole.scrollHeight},i.showconsole=function(){i.wrapper.classList.remove("hidden")},i.hideconsole=function(){i.wrapper.classList.add("hidden")},i.closer.onclick=function(){i.hideconsole()},i.hideconsole(),i}},{}],6:[function(e,t,n){t.exports=function(t){function e(){}e.prototype=t.PConstants;var h=new e;function s(e,t,n){if(e.hasOwnProperty(t)&&"function"==typeof e[t]){var r=e[t];if("$overloads"in r)r.$defaultOverload=n;else if("$overloads"in n||r.length!==n.length){var i,s;"$overloads"in n?((i=n.$overloads.slice(0))[r.length]=r,s=n.$defaultOverload):((i=[])[n.length]=n,s=i[r.length]=r);var o=function(){return(o.$overloads[arguments.length]||("$methodArgsIndex"in o&&arguments.length>o.$methodArgsIndex?o.$overloads[o.$methodArgsIndex]:null)||o.$defaultOverload).apply(this,arguments)};o.$overloads=i,"$methodArgsIndex"in n&&(o.$methodArgsIndex=n.$methodArgsIndex),o.$defaultOverload=s,e[o.name=t]=o}}else e[t]=n}function r(e,n){function t(t){h.defineProperty(e,t,{get:function(){return n[t]},set:function(e){n[t]=e},enumerable:!0})}var r=[];for(var i in n)"function"==typeof n[i]?s(e,i,n[i]):"$"===i.charAt(0)||i in e||r.push(i);for(;0o.$methodArgsIndex?o.$overloads[o.$methodArgsIndex]:null)||o.$defaultOverload).apply(this,arguments)},a=[];i&&(a[i.length]=i),a[s]=n,o.$overloads=a,o.$defaultOverload=i||n,r&&(o.$methodArgsIndex=s),e[o.name=t]=o}}else e[t]=n},h.createJavaArray=function(e,t){var n,r=null,i=null;if("string"==typeof e&&("boolean"===e?i=!1:"string"==typeof(n=e)&&-1!==["byte","int","char","color","float","long","double"].indexOf(n)&&(i=0)),"number"==typeof t[0]){var s=0|t[0];if(t.length<=1){(r=[]).length=s;for(var o=0;o "+t),f===c){if(0!==u.length)throw"Processing.js: Unable to load pjs sketch files: "+u.join("\n");var n=new g(a,h.join("\n"));l&&l(n)}}if("#"!==i.charAt(0)){var t,n,s;t=i,n=e,(s=new m).onreadystatechange=function(){var e;4===s.readyState&&(200!==s.status&&0!==s.status?e="Invalid XHR status "+s.status:""===s.responseText&&(e="withCredentials"in new m&&!1===(new m).withCredentials&&"file:"===p.location.protocol?"XMLHttpRequest failure, possibly due to a same-origin policy violation. You can try loading this page in another browser, or load it from http://localhost using a local webserver. See the Processing.js README for a more detailed explanation of this problem and solutions.":"File is empty."),n(s.responseText,e))},s.open("GET",t,!0),s.overrideMimeType&&s.overrideMimeType("application/json"),s.setRequestHeader("If-Modified-Since","Fri, 01 Jan 1960 00:00:00 GMT"),s.send(null)}else{var o=d.getElementById(i.substring(1));o?e(o.text||o.textContent):e("","Unable to load pjs sketch: element with id '"+i.substring(1)+"' was not found")}}for(var n=0;nr.length)throw"Index out of bounds for addAll: "+e+" greater or equal than "+r.length;for(n=new ObjectIterator(t);n.hasNext();)r.splice(e++,0,n.next())}else for(n=new ObjectIterator(e);n.hasNext();)r.push(n.next())},this.set=function(){if(2!==arguments.length)throw"Please use the proper number of parameters.";var e=arguments[0];if("number"!=typeof e)throw typeof e+" is not a number";if(!(0<=e&&e=a.length)s=!0;else{if(!(void 0===a[r]||i>=a[r].length))return;i=-1,++r}}this.hasNext=function(){return!s},this.next=function(){return n=e(a[r][i]),o(),n},this.remove=function(){void 0!==n&&(t(n),--i,o())},o()}function i(e,t,s){this.clear=function(){r.clear()},this.contains=function(e){return t(e)},this.containsAll=function(e){for(var t=e.iterator();t.hasNext();)if(!this.contains(t.next()))return!1;return!0},this.isEmpty=function(){return r.isEmpty()},this.iterator=function(){return new n(e,s)},this.remove=function(e){return!!this.contains(e)&&(s(e),!0)},this.removeAll=function(e){for(var t=e.iterator();t.hasNext();){var n=t.next();this.contains(n)&&s(n)}return!0},this.retainAll=function(e){for(var t=this.iterator(),n=[];t.hasNext();){var r=t.next();e.contains(r)||n.push(r)}for(var i=0;i"+s,v.body.appendChild(o);var a=n.width,l=n.height,h=l/2;i.fillStyle="white",i.fillRect(0,0,a,l),i.fillStyle="black",i.fillText(s,0,h);for(var u=i.getImageData(0,0,a,l).data,c=0,f=4*a,p=u.length;++c=2*e.size&&(e.leading=Math.round(d/2))}if(v.body.removeChild(o),e.caching)return i}(this),this.css=this.getCSSDefinition(),this.context2d&&(this.context2d.font=this.css)}return o.prototype.caching=!0,o.prototype.getCSSDefinition=function(e,t){return e===s&&(e=this.size+"px"),t===s&&(t=this.leading+"px"),[this.style,"normal",this.weight,e+"/"+t,this.family].join(" ")},o.prototype.measureTextWidth=function(e){return this.context2d.measureText(e).width},o.prototype.measureTextWidthFallback=function(e){var t=v.createElement("canvas").getContext("2d");return t.font=this.css,t.measureText(e).width},o.PFontCache={length:0},o.get=function(e,t){var n=o.PFontCache,r=e+"/"+(t=(10*t+.5|0)/10);if(!n[r]){if(n[r]=new o(e,t),n.length++,50===n.length){var i;for(i in o.prototype.measureTextWidth=o.prototype.measureTextWidthFallback,o.prototype.caching=!1,n)"length"!==i&&(n[i].context2d=null);return new o(e,t)}if(400===n.length)return o.PFontCache={},o.get=o.getFallback,new o(e,t)}return n[r]},o.getFallback=function(e,t){return new o(e,t)},o.list=function(){return["sans-serif","serif","monospace","fantasy","cursive"]},o.preloading={template:{},initialized:!1,initialize:function(){var e=v.createElement("style");e.setAttribute("type","text/css"),e.innerHTML='@font-face {\n font-family: "PjsEmptyFont";\n src: url(\'data:application/x-font-ttf;base64,'+"#E3KAI2wAgT1MvMg7Eo3VmNtYX7ABi3CxnbHlm7Abw3kaGVhZ7ACs3OGhoZWE7A53CRobXR47AY3AGbG9jYQ7G03Bm1heH7ABC3CBuYW1l7Ae3AgcG9zd7AI3AE#B3AQ2kgTY18PPPUACwAg3ALSRoo3#yld0xg32QAB77#E777773B#E3C#I#Q77773E#Q7777777772CMAIw7AB77732B#M#Q3wAB#g3B#E#E2BB//82BB////w#B7#gAEg3E77x2B32B#E#Q#MTcBAQ32gAe#M#QQJ#E32M#QQJ#I#g32Q77#".replace(/[#237]/g,function(e){return"AAAAAAAA".substr(~~e?7-e:6)})+"')\n format('truetype');\n}",v.head.appendChild(e);var t=v.createElement("span");t.style.cssText='position: absolute; top: -1000; left: 0; opacity: 0; font-family: "PjsEmptyFont", fantasy;',t.innerHTML="AAAAAAAA",v.body.appendChild(t),this.template=t,this.initialized=!0},getElementWidth:function(e){return v.defaultView.getComputedStyle(e,"").getPropertyValue("width")},timeAttempted:0,pending:function(e){this.initialized||this.initialize();for(var t,n,r=this.getElementWidth(this.template),i=0;iPConstants.MIN_INT){var t=this.elements[0],n=this.elements[1],r=this.elements[2],i=this.elements[3],s=this.elements[4],o=this.elements[5];return this.elements[0]=s/e,this.elements[3]=-i/e,this.elements[1]=-n/e,this.elements[4]=t/e,this.elements[2]=(n*o-s*r)/e,this.elements[5]=(i*r-t*o)/e,!0}return!1},scale:function(e,t){e&&t===n&&(t=e),e&&t&&(this.elements[0]*=e,this.elements[1]*=t,this.elements[3]*=e,this.elements[4]*=t)},invScale:function(e,t){e&&!t&&(t=e),this.scale(1/e,1/t)},apply:function(){var e;1===arguments.length&&arguments[0]instanceof s?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,this.elements[2],0,0,this.elements[5]],n=0,r=0;r<2;r++)for(var i=0;i<3;i++,n++)t[n]+=this.elements[3*r+0]*e[i+0]+this.elements[3*r+1]*e[i+3];this.elements=t.slice()},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof s?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);var t=[0,0,e[2],0,0,e[5]];t[2]=e[2]+this.elements[2]*e[0]+this.elements[5]*e[1],t[5]=e[5]+this.elements[2]*e[3]+this.elements[5]*e[4],t[0]=this.elements[0]*e[0]+this.elements[3]*e[1],t[3]=this.elements[0]*e[3]+this.elements[3]*e[4],t[1]=this.elements[1]*e[0]+this.elements[4]*e[1],t[4]=this.elements[1]*e[3]+this.elements[4]*e[4],this.elements=t.slice()},rotate:function(e){var t=Math.cos(e),n=Math.sin(e),r=this.elements[0],i=this.elements[1];this.elements[0]=t*r+n*i,this.elements[1]=-n*r+t*i,r=this.elements[3],i=this.elements[4],this.elements[3]=t*r+n*i,this.elements[4]=-n*r+t*i},rotateZ:function(e){this.rotate(e)},invRotateZ:function(e){this.rotateZ(e-Math.PI)},print:function(){var e=printMatrixHelper(this.elements),t=r.nfs(this.elements[0],e,4)+" "+r.nfs(this.elements[1],e,4)+" "+r.nfs(this.elements[2],e,4)+"\n"+r.nfs(this.elements[3],e,4)+" "+r.nfs(this.elements[4],e,4)+" "+r.nfs(this.elements[5],e,4)+"\n\n";r.println(t)}},s}},{}],15:[function(e,t,n){t.exports=function(e,r){var n=e.p,s=function(){this.reset()};return s.prototype={set:function(){16===arguments.length?this.elements=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof s?this.elements=arguments[0].array():1===arguments.length&&arguments[0]instanceof Array&&(this.elements=arguments[0].slice())},get:function(){var e=new s;return e.set(this.elements),e},reset:function(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},array:function(){return this.elements.slice()},translate:function(e,t,n){n===r&&(n=0),this.elements[3]+=e*this.elements[0]+t*this.elements[1]+n*this.elements[2],this.elements[7]+=e*this.elements[4]+t*this.elements[5]+n*this.elements[6],this.elements[11]+=e*this.elements[8]+t*this.elements[9]+n*this.elements[10],this.elements[15]+=e*this.elements[12]+t*this.elements[13]+n*this.elements[14]},transpose:function(){var e=this.elements[4];this.elements[4]=this.elements[1],this.elements[1]=e,e=this.elements[8],this.elements[8]=this.elements[2],this.elements[2]=e,e=this.elements[6],this.elements[6]=this.elements[9],this.elements[9]=e,e=this.elements[3],this.elements[3]=this.elements[12],this.elements[12]=e,e=this.elements[7],this.elements[7]=this.elements[13],this.elements[13]=e,e=this.elements[11],this.elements[11]=this.elements[14],this.elements[14]=e},mult:function(e,t){var n,r,i,s;return e instanceof PVector?(n=e.x,r=e.y,i=e.z,s=1,t||(t=new PVector)):e instanceof Array&&(n=e[0],r=e[1],i=e[2],s=e[3]||1,(!t||3!==t.length&&4!==t.length)&&(t=[0,0,0])),t instanceof Array&&(3===t.length?(t[0]=this.elements[0]*n+this.elements[1]*r+this.elements[2]*i+this.elements[3],t[1]=this.elements[4]*n+this.elements[5]*r+this.elements[6]*i+this.elements[7],t[2]=this.elements[8]*n+this.elements[9]*r+this.elements[10]*i+this.elements[11]):4===t.length&&(t[0]=this.elements[0]*n+this.elements[1]*r+this.elements[2]*i+this.elements[3]*s,t[1]=this.elements[4]*n+this.elements[5]*r+this.elements[6]*i+this.elements[7]*s,t[2]=this.elements[8]*n+this.elements[9]*r+this.elements[10]*i+this.elements[11]*s,t[3]=this.elements[12]*n+this.elements[13]*r+this.elements[14]*i+this.elements[15]*s)),t instanceof PVector&&(t.x=this.elements[0]*n+this.elements[1]*r+this.elements[2]*i+this.elements[3],t.y=this.elements[4]*n+this.elements[5]*r+this.elements[6]*i+this.elements[7],t.z=this.elements[8]*n+this.elements[9]*r+this.elements[10]*i+this.elements[11]),t},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof s?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=0;r<4;r++)for(var i=0;i<4;i++,n++)t[n]+=this.elements[i+0]*e[4*r+0]+this.elements[i+4]*e[4*r+1]+this.elements[i+8]*e[4*r+2]+this.elements[i+12]*e[4*r+3];this.elements=t.slice()},apply:function(){var e;1===arguments.length&&arguments[0]instanceof s?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=0;r<4;r++)for(var i=0;i<4;i++,n++)t[n]+=this.elements[4*r+0]*e[i+0]+this.elements[4*r+1]*e[i+4]+this.elements[4*r+2]*e[i+8]+this.elements[4*r+3]*e[i+12];this.elements=t.slice()},rotate:function(e,t,n,r){if(n){var i=Math.cos(e),s=Math.sin(e),o=1-i;this.apply(o*t*t+i,o*t*n-s*r,o*t*r+s*n,0,o*t*n+s*r,o*n*n+i,o*n*r-s*t,0,o*t*r-s*n,o*n*r+s*t,o*r*r+i,0,0,0,0,1)}else this.rotateZ(e)},invApply:function(){inverseCopy===r&&(inverseCopy=new s);var e=arguments;return inverseCopy.set(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]),!!inverseCopy.invert()&&(this.preApply(inverseCopy),!0)},rotateX:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},rotateY:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},rotateZ:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},scale:function(e,t,n){e&&t===r&&n===r?t=n=e:e&&t&&n===r&&(n=1),e&&t&&n&&(this.elements[0]*=e,this.elements[1]*=t,this.elements[2]*=n,this.elements[4]*=e,this.elements[5]*=t,this.elements[6]*=n,this.elements[8]*=e,this.elements[9]*=t,this.elements[10]*=n,this.elements[12]*=e,this.elements[13]*=t,this.elements[14]*=n)},skewX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},skewY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},shearX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},shearY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},multX:function(e,t,n,r){return n?r?this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]*r:this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]:this.elements[0]*e+this.elements[1]*t+this.elements[3]},multY:function(e,t,n,r){return n?r?this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]*r:this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]:this.elements[4]*e+this.elements[5]*t+this.elements[7]},multZ:function(e,t,n,r){return r?this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]*r:this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]},multW:function(e,t,n,r){return r?this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]*r:this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]},invert:function(){var e=this.elements[0]*this.elements[5]-this.elements[1]*this.elements[4],t=this.elements[0]*this.elements[6]-this.elements[2]*this.elements[4],n=this.elements[0]*this.elements[7]-this.elements[3]*this.elements[4],r=this.elements[1]*this.elements[6]-this.elements[2]*this.elements[5],i=this.elements[1]*this.elements[7]-this.elements[3]*this.elements[5],s=this.elements[2]*this.elements[7]-this.elements[3]*this.elements[6],o=this.elements[8]*this.elements[13]-this.elements[9]*this.elements[12],a=this.elements[8]*this.elements[14]-this.elements[10]*this.elements[12],l=this.elements[8]*this.elements[15]-this.elements[11]*this.elements[12],h=this.elements[9]*this.elements[14]-this.elements[10]*this.elements[13],u=this.elements[9]*this.elements[15]-this.elements[11]*this.elements[13],c=this.elements[10]*this.elements[15]-this.elements[11]*this.elements[14],f=e*c-t*u+n*h+r*l-i*a+s*o;if(Math.abs(f)<=1e-9)return!1;var p=[];p[0]=+this.elements[5]*c-this.elements[6]*u+this.elements[7]*h,p[4]=-this.elements[4]*c+this.elements[6]*l-this.elements[7]*a,p[8]=+this.elements[4]*u-this.elements[5]*l+this.elements[7]*o,p[12]=-this.elements[4]*h+this.elements[5]*a-this.elements[6]*o,p[1]=-this.elements[1]*c+this.elements[2]*u-this.elements[3]*h,p[5]=+this.elements[0]*c-this.elements[2]*l+this.elements[3]*a,p[9]=-this.elements[0]*u+this.elements[1]*l-this.elements[3]*o,p[13]=+this.elements[0]*h-this.elements[1]*a+this.elements[2]*o,p[2]=+this.elements[13]*s-this.elements[14]*i+this.elements[15]*r,p[6]=-this.elements[12]*s+this.elements[14]*n-this.elements[15]*t,p[10]=+this.elements[12]*i-this.elements[13]*n+this.elements[15]*e,p[14]=-this.elements[12]*r+this.elements[13]*t-this.elements[14]*e,p[3]=-this.elements[9]*s+this.elements[10]*i-this.elements[11]*r,p[7]=+this.elements[8]*s-this.elements[10]*n+this.elements[11]*t,p[11]=-this.elements[8]*i+this.elements[9]*n-this.elements[11]*e,p[15]=+this.elements[8]*r-this.elements[9]*t+this.elements[10]*e;var m=1/f;return p[0]*=m,p[1]*=m,p[2]*=m,p[3]*=m,p[4]*=m,p[5]*=m,p[6]*=m,p[7]*=m,p[8]*=m,p[9]*=m,p[10]*=m,p[11]*=m,p[12]*=m,p[13]*=m,p[14]*=m,p[15]*=m,this.elements=p.slice(),!0},toString:function(){for(var e="",t=0;t<15;t++)e+=this.elements[t]+", ";return e+=this.elements[15]},print:function(){var e=printMatrixHelper(this.elements),t=n.nfs(this.elements[0],e,4)+" "+n.nfs(this.elements[1],e,4)+" "+n.nfs(this.elements[2],e,4)+" "+n.nfs(this.elements[3],e,4)+"\n"+n.nfs(this.elements[4],e,4)+" "+n.nfs(this.elements[5],e,4)+" "+n.nfs(this.elements[6],e,4)+" "+n.nfs(this.elements[7],e,4)+"\n"+n.nfs(this.elements[8],e,4)+" "+n.nfs(this.elements[9],e,4)+" "+n.nfs(this.elements[10],e,4)+" "+n.nfs(this.elements[11],e,4)+"\n"+n.nfs(this.elements[12],e,4)+" "+n.nfs(this.elements[13],e,4)+" "+n.nfs(this.elements[14],e,4)+" "+n.nfs(this.elements[15],e,4)+"\n\n";n.println(t)},invTranslate:function(e,t,n){this.preApply(1,0,0,-e,0,1,0,-t,0,0,1,-n,0,0,0,1)},invRotateX:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},invRotateY:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},invRotateZ:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},invScale:function(e,t,n){this.preApply([1/e,0,0,0,0,1/t,0,0,0,0,1/n,0,0,0,0,1])}},s}},{}],16:[function(e,t,n){t.exports=function(e){var s=e.PConstants,t=e.PMatrix2D,n=e.PMatrix3D,r=function(e){this.family=e||s.GROUP,this.visible=!0,this.style=!0,this.children=[],this.nameTable=[],this.params=[],this.name="",this.image=null,this.matrix=null,this.kind=null,this.close=null,this.width=null,this.height=null,this.parent=null};return r.prototype={isVisible:function(){return this.visible},setVisible:function(e){this.visible=e},disableStyle:function(){this.style=!1;for(var e=0,t=this.children.length;e, it's <"+this.element.getName()+">"}else 2===arguments.length&&("string"==typeof arguments[1]?-1 tag of this file.";this.parseColors(this.element),this.parseChildren(this.element)};return(r.prototype=new o).parseMatrix=function(){function u(e){var n=[];return e.replace(/\((.*?)\)/,function(e,t){n=t.replace(/,+/g," ").split(/\s+/)}),n}return function(e){this.checkMatrix(2);var t=[];if(e.replace(/\s*(\w+)\((.*?)\)/g,function(e){t.push(S.trim(e))}),0===t.length)return null;for(var n=0,r=t.length;n"},r.prototype.parseEllipse=function(e){var t,n;if(this.kind=P.ELLIPSE,this.family=P.PRIMITIVE,this.params=[],this.params[0]=0|this.element.getFloatAttribute("cx"),this.params[1]=0|this.element.getFloatAttribute("cy"),e){if((t=n=this.element.getFloatAttribute("r"))<0)throw"svg error: negative radius found while parsing "}else if(t=this.element.getFloatAttribute("rx"),n=this.element.getFloatAttribute("ry"),t<0||n<0)throw"svg error: negative x-axis radius or y-axis radius found while parsing ";this.params[0]-=t,this.params[1]-=n,this.params[2]=2*t,this.params[3]=2*n},r.prototype.parseLine=function(){this.kind=P.LINE,this.family=P.PRIMITIVE,this.params=[],this.params[0]=this.element.getFloatAttribute("x1"),this.params[1]=this.element.getFloatAttribute("y1"),this.params[2]=this.element.getFloatAttribute("x2"),this.params[3]=this.element.getFloatAttribute("y2")},r.prototype.parseColors=function(e){if(e.hasAttribute("opacity")&&this.setOpacity(e.getAttribute("opacity")),e.hasAttribute("stroke")&&this.setStroke(e.getAttribute("stroke")),e.hasAttribute("stroke-width")&&this.setStrokeWeight(e.getAttribute("stroke-width")),e.hasAttribute("stroke-linejoin")&&this.setStrokeJoin(e.getAttribute("stroke-linejoin")),e.hasAttribute("stroke-linecap")&&this.setStrokeCap(e.getStringAttribute("stroke-linecap")),e.hasAttribute("fill")&&this.setFill(e.getStringAttribute("fill")),e.hasAttribute("style"))for(var t=e.getStringAttribute("style").toString().split(";"),n=0,r=t.length;ne&&(this.normalize(),this.mult(e))},heading:function(){return-Math.atan2(-this.y,this.x)},heading2D:function(){return this.heading()},toString:function(){return"["+this.x+", "+this.y+", "+this.z+"]"},array:function(){return[this.x,this.y,this.z]}})l.prototype.hasOwnProperty(n)&&!l.hasOwnProperty(n)&&(l[n]=t(n));return l}},{}],19:[function(e,t,n){t.exports=function(){var e=function(e,t,n,r,i){this.fullName=e||"",this.name=t||"",this.namespace=n||"",this.value=r,this.type=i};return e.prototype={getName:function(){return this.name},getFullName:function(){return this.fullName},getNamespace:function(){return this.namespace},getValue:function(){return this.value},getType:function(){return this.type},setValue:function(e){this.value=e}},e}},{}],20:[function(e,t,n){t.exports=function(e,i){var t=e.Browser,r=t.ajax,n=t.window,s=(n.XMLHttpRequest,n.DOMParser),h=e.XMLAttribute,u=function(e,t,n,r){this.attributes=[],this.children=[],this.fullName=null,this.name=null,this.namespace="",this.content=null,this.parent=null,this.lineNr="",this.systemID="",this.type="ELEMENT",e&&("string"==typeof e?t===i&&-1":">","'":"'",'"':"""};for(n in r)Object.hasOwnProperty(r,n)||(e=e.replace(new RegExp(n,"g"),r[n]));return t.cdata=e,t},hasAttribute:function(){return 1===arguments.length?null!==this.getAttribute(arguments[0]):2===arguments.length?null!==this.getAttribute(arguments[0],arguments[1]):void 0},equals:function(e){if(!(e instanceof u))return!1;var t,n,r,i,s;if(this.fullName!==e.fullName)return!1;if(this.attributes.length!==e.getAttributeCount())return!1;if(this.attributes.length!==e.attributes.length)return!1;for(t=0,n=this.attributes.length;te&&this.children.splice(e,1)},findAttribute:function(e,t){this.namespace=t||"";for(var n=0,r=this.attributes.length;n":r+=">"+this.content+"";else{for(r+=">",t=0;t"}return r}},u.parse=function(e){var t=new u;return t.parse(e),t},u}},{}],21:[function(e,t,n){t.exports={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"}},{}],22:[function(e,t,n){t.exports=function(n,r,h){return function(t,l){t.__contains=function(e,t){return"string"!=typeof e?e.contains.apply(e,l(arguments)):null!==e&&null!==t&&"string"==typeof t&&-1e.length)&&(""===t||t===e||e.indexOf(t)===n)},t.__endsWith=function(e,t){if("string"!=typeof e)return e.endsWith.apply(e,l(arguments));var n=t?t.length:0;return""===t||t===e||e.indexOf(t)===e.length-n},t.__hashCode=function(e){return e.hashCode instanceof Function?e.hashCode.apply(e,l(arguments)):n(e)},t.__printStackTrace=function(e){t.println("Exception: "+e.toString())}}}},{}],23:[function(e,t,n){t.exports=function(e,h){var i=function(){return Math.random()};function o(e,t){var n=e||362436069,r=t||521288629,i=function(){return 4294967295&((65535&(n=36969*(65535&n)+(n>>>16)&4294967295))<<16|65535&(r=18e3*(65535&r)+(r>>>16)&4294967295))};this.doubleGenerator=function(){var e=i()/4294967296;return e<0?1+e:e},this.intGenerator=i}function l(e){var t,n,r=e!==h?new o(e,(e<<16)+(e>>16)):o.createRandomized(),g=new Uint8Array(512);for(t=0;t<256;++t)g[t]=t;for(t=0;t<256;++t){var i=g[n=255&r.intGenerator()];g[n]=g[t],g[t]=i}for(t=0;t<256;++t)g[t+256]=g[t];function d(e,t,n,r){var i=15&e,s=i<8?t:n,o=i<4?n:12===i||14===i?t:r;return(0==(1&i)?s:-s)+(0==(2&i)?o:-o)}function l(e,t,n){var r=0==(1&e)?t:n;return 0==(2&e)?-r:r}function s(e,t){return 0==(1&e)?-t:t}function v(e,t,n){return t+e*(n-t)}this.noise3d=function(e,t,n){var r=255&Math.floor(e),i=255&Math.floor(t),s=255&Math.floor(n),o=(3-2*(e-=Math.floor(e)))*e*e,a=(3-2*(t-=Math.floor(t)))*t*t,l=(3-2*(n-=Math.floor(n)))*n*n,h=g[r]+i,u=g[h]+s,c=g[h+1]+s,f=g[r+1]+i,p=g[f]+s,m=g[f+1]+s;return v(l,v(a,v(o,d(g[u],e,t,n),d(g[p],e-1,t,n)),v(o,d(g[c],e,t-1,n),d(g[m],e-1,t-1,n))),v(a,v(o,d(g[u+1],e,t,n-1),d(g[p+1],e-1,t,n-1)),v(o,d(g[c+1],e,t-1,n-1),d(g[m+1],e-1,t-1,n-1))))},this.noise2d=function(e,t){var n=255&Math.floor(e),r=255&Math.floor(t),i=(3-2*(e-=Math.floor(e)))*e*e,s=(3-2*(t-=Math.floor(t)))*t*t,o=g[n]+r,a=g[n+1]+r;return v(s,v(i,l(g[o],e,t),l(g[a],e-1,t)),v(i,l(g[o+1],e,t-1),l(g[a+1],e-1,t-1)))},this.noise1d=function(e){var t=255&Math.floor(e);return v((3-2*(e-=Math.floor(e)))*e*e,s(g[t],e),s(g[t+1],e-1))}}e.abs=Math.abs,e.ceil=Math.ceil,e.exp=Math.exp,e.floor=Math.floor,e.log=Math.log,e.pow=Math.pow,e.round=Math.round,e.sqrt=Math.sqrt,e.acos=Math.acos,e.asin=Math.asin,e.atan=Math.atan,e.atan2=Math.atan2,e.cos=Math.cos,e.sin=Math.sin,e.tan=Math.tan,e.constrain=function(e,t,n){return ne[r]&&(t=e[r]);return t},e.norm=function(e,t,n){return(e-t)/(n-t)},e.sq=function(e){return e*e},e.degrees=function(e){return 180*e/Math.PI},e.random=function(e,t){if(0===arguments.length?(t=1,e=0):1===arguments.length&&(t=e,e=0),e===t)return e;for(var n=0;n<100;n++){var r=i()*(t-e)+e;if(r!==t)return r}return e},o.createRandomized=function(){var e=new Date;return new o(e/6e4&4294967295,4294967295&e)},e.randomSeed=function(e){i=new o(e,(e<<16)+(e>>16)).doubleGenerator,this.haveNextNextGaussian=!1},e.randomGaussian=function(){if(this.haveNextNextGaussian)return this.haveNextNextGaussian=!1,this.nextNextGaussian;for(var e,t,n;1<=(n=(e=2*i()-1)*e+(t=2*i()-1)*t)||0===n;);var r=Math.sqrt(-2*Math.log(n)/n);return this.nextNextGaussian=t*r,this.haveNextNextGaussian=!0,e*r};var u={generator:h,octaves:4,fallout:.5,seed:h};e.noise=function(e,t,n){u.generator===h&&(u.generator=new l(u.seed));for(var r=u.generator,i=1,s=1,o=0,a=0;a([=]?)/g,o),i;);var _,u,c,f,y,p,d,A=function(e){for(var t=[],n=e.split(/([\{\[\(\)\]\}])/),r=n[0],i=[],s=1;s\=]+)/g,function(e,t){var n=v(t);return n.untrim("__int_cast("+n.middle+")")})).replace(/\bsuper(\s*"B\d+")/g,"$$superCstr$1").replace(/\bsuper(\s*\.)/g,"$$super$1")).replace(/\b0+((\d*)(?:\.[\d*])?(?:[eE][\-\+]?\d+)?[fF]?)\b/,function(e,t,n){return t===n?e:""===n?"0"+t:t})).replace(/\b(\.?\d+\.?)[fF]\b/g,"$1")).replace(/([^\s])%([^=\s])/g,"$1 % $2")).replace(/\b(frameRate|keyPressed|mousePressed)\b(?!\s*"B)/g,"__$1")).replace(/\b(boolean|byte|char|float|int)\s*"B/g,function(e,t){return"parse"+t.substring(0,1).toUpperCase()+t.substring(1)+'"B'})).replace(/\bpixels\b\s*(("C(\d+)")|\.length)?(\s*=(?!=)([^,\]\)\}]+))?/g,function(e,t,n,r,i,s){if(n){var o=A[r];return i?"pixels.setPixel"+b("("+o.substring(1,o.length-1)+","+s+")","B"):"pixels.getPixel"+b("("+o.substring(1,o.length-1)+")","B")}return t?"pixels.getLength"+b("()","B"):i?"pixels.set"+b("("+s+")","B"):"pixels.toArray"+b("()","B")});o=!1,t=t.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*\.\s*(?:[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*\.\s*)*)(replace|replaceAll|replaceFirst|contains|equals|equalsIgnoreCase|hashCode|toCharArray|printStackTrace|split|startsWith|endsWith|codePointAt|matches)\s*"B(\d+)"/g,n),o;);function r(e,t,n){return o=!0,"__instanceof"+b("("+t+", "+n+")","B")}for(;o=!1,t=t.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*(?:\.\s*[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*)*)instanceof\s+([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)/g,r),o;);return t=t.replace(/\bthis(\s*"B\d+")/g,"$$constr$1")}(t.middle);return n=n.replace(/"[ABC](\d+)"/g,function(e,t){return G(A[t])}),t.untrim(n)}function V(e,t){this.expr=e,this.transforms=t}function z(e,t,n){this.name=e,this.value=t,this.isDefault=n}function U(e,t){var n,r,i,s=e.indexOf("=");return s<0?(n=e,r=t,i=!0):(n=e.substring(0,s),r=d(e.substring(s+1)),i=!1),new z(T(n.replace(/(\s*"C\d+")+/g,"")),r,i)}function H(e){return"int"===e||"float"===e?"0":"boolean"===e?"false":"color"===e?"0x00000000":"null"}function X(e,t){this.definitions=e,this.varType=t}function Y(e){this.expression=e}function j(e){if(P.test(e)){for(var t=M.exec(e),n=e.substring(t[0].length).split(","),r=H(t[2]),i=0;i=":"===")+" "+C+") { $constr_"+C+".apply("+n+", arguments); }")}return 0";var ir=[],sr={},or=this.Processing=function(e,t,n){if(!(this instanceof or))throw"called Processing constructor as if it were a function: missing 'new'.";var l={},r=e===zn&&t===zn;if(!("getContext"in(l=r?Kn.createElement("canvas"):"string"==typeof e?Kn.getElementById(e):e)))throw"called Processing constructor without passing canvas element reference or id.";var i=[];function s(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent("on"+t,n),i.push({elem:e,type:t,fn:n})}function o(e){var t=e.elem,n=e.type,r=e.fn;t.removeEventListener?t.removeEventListener(n,r,!1):t.detachEvent&&t.detachEvent("on"+n,r)}var V=this;V.Char=V.Character=Char,i=[],Hn.withCommonFunctions(V),Hn.withMath(V),Hn.withProxyFunctions(V,function(e){return Array.prototype.slice.call(e,1)}),Hn.withTouch(V,l,s,function(t,n){Object.keys(i).forEach(function(e){-1 cos( light.angle ) ) { spotAttenuation = pow( spotDot, light.concentration ); } else{ spotAttenuation = 0.0; } attenuation *= spotAttenuation;")+" float nDotVP = max( 0.0, dot( vertNormal, VP ) ); vec3 halfVector = normalize( VP - normalize(ecPos) ); float nDotHV = max( 0.0, dot( vertNormal, halfVector ) ); if( nDotVP != 0.0 ) { powerFactor = pow( nDotHV, uShininess ); } spec += uSpecular * powerFactor * attenuation; col += light.color * nDotVP * attenuation;}void main(void) { vec3 finalAmbient = vec3( 0.0 ); vec3 finalDiffuse = vec3( 0.0 ); vec3 finalSpecular = vec3( 0.0 ); vec4 col = uColor; if ( uColor[0] == -1.0 ){ col = aColor; } vec3 norm = normalize(vec3( uNormalTransform * vec4( aNormal, 0.0 ) )); vec4 ecPos4 = uView * uModel * vec4(aVertex, 1.0); vec3 ecPos = (vec3(ecPos4))/ecPos4.w; if( uLightCount == 0 ) { vFrontColor = col + vec4(uMaterialSpecular, 1.0); } else { for( int i = 0; i < 8; i++ ) { Light l = getLight(i); if( i >= uLightCount ){ break; } if( l.type == 0 ) { AmbientLight( finalAmbient, ecPos, l ); } else if( l.type == 1 ) { DirectionalLight( finalDiffuse, finalSpecular, norm, ecPos, l ); } else if( l.type == 2 ) { PointLight( finalDiffuse, finalSpecular, norm, ecPos, l ); } else { SpotLight( finalDiffuse, finalSpecular, norm, ecPos, l ); } } if( uUsingMat == false ) { vFrontColor = vec4( vec3( col ) * finalAmbient + vec3( col ) * finalDiffuse + vec3( col ) * finalSpecular, col[3] ); } else{ vFrontColor = vec4( uMaterialEmissive + (vec3(col) * uMaterialAmbient * finalAmbient ) + (vec3(col) * finalDiffuse) + (uMaterialSpecular * finalSpecular), col[3] ); } } vTexture.xy = aTexture.xy; gl_Position = uProjection * uView * uModel * vec4( aVertex, 1.0 );}";function Lt(e,t,n,r){var i=Fe.locations[e];i===zn&&(i=d.getUniformLocation(t,n),Fe.locations[e]=i),null!==i&&(4===r.length?d.uniform4fv(i,r):3===r.length?d.uniform3fv(i,r):2===r.length?d.uniform2fv(i,r):d.uniform1f(i,r))}function It(e,t,n,r){var i=Fe.locations[e];i===zn&&(i=d.getUniformLocation(t,n),Fe.locations[e]=i),null!==i&&(4===r.length?d.uniform4iv(i,r):3===r.length?d.uniform3iv(i,r):2===r.length?d.uniform2iv(i,r):d.uniform1i(i,r))}function Dt(e,t,n,r,i){var s=Fe.locations[e];s===zn&&(s=d.getUniformLocation(t,n),Fe.locations[e]=s),-1!==s&&(16===i.length?d.uniformMatrix4fv(s,r,i):9===i.length?d.uniformMatrix3fv(s,r,i):d.uniformMatrix2fv(s,r,i))}function Ot(e,t,n,r,i){var s=Fe.attributes[e];s===zn&&(s=d.getAttribLocation(t,n),Fe.attributes[e]=s),-1!==s&&(d.bindBuffer(d.ARRAY_BUFFER,i),d.vertexAttribPointer(s,r,d.FLOAT,!1,0,0),d.enableVertexAttribArray(s))}function Nt(e,t,n){var r=Fe.attributes[e];r===zn&&(r=d.getAttribLocation(t,n),Fe.attributes[e]=r),-1!==r&&d.disableVertexAttribArray(r)}var Ft=function(e,t,n){var r=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(r,t),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw e.getShaderInfoLog(r);var i=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(i,n),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS))throw e.getShaderInfoLog(i);var s=e.createProgram();if(e.attachShader(s,r),e.attachShader(s,i),e.linkProgram(s),!e.getProgramParameter(s,e.LINK_STATUS))throw"Error linking shaders.";return s},kt=function(e,t,n,r,i){return{x:e,y:t,w:n,h:r}},Bt=kt,$t=function(e,t,n,r,i){return{x:e,y:t,w:i?n:n-e,h:i?r:r-t}},Gt=function(e,t,n,r,i){return{x:e-n/2,y:t-r/2,w:n,h:r}},Vt=function(){},zt=function(){},Ut=function(){},Ht=function(){};zt.prototype=new Vt,zt.prototype.constructor=zt,Ut.prototype=new Vt,Ut.prototype.constructor=Ut,Ht.prototype=new Vt,Ht.prototype.constructor=Ht,Vt.prototype.a3DOnlyFunction=Wn,V.shape=function(e,t,n,r,i){1<=arguments.length&&null!==e&&e.isVisible()&&(V.pushMatrix(),Et===Zn.CENTER?5===arguments.length?(V.translate(t-r/2,n-i/2),V.scale(r/e.getWidth(),i/e.getHeight())):3===arguments.length?V.translate(t-e.getWidth()/2,-e.getHeight()/2):V.translate(-e.getWidth()/2,-e.getHeight()/2):Et===Zn.CORNER?5===arguments.length?(V.translate(t,n),V.scale(r/e.getWidth(),i/e.getHeight())):3===arguments.length&&V.translate(t,n):Et===Zn.CORNERS&&(5===arguments.length?(r-=t,i-=n,V.translate(t,n),V.scale(r/e.getWidth(),i/e.getHeight())):3===arguments.length&&V.translate(t,n)),e.draw(V),(1===arguments.length&&Et===Zn.CENTER||1Zn.MIN_INT){var t=this.elements[0],n=this.elements[1],r=this.elements[2],i=this.elements[3],s=this.elements[4],o=this.elements[5];return this.elements[0]=s/e,this.elements[3]=-i/e,this.elements[1]=-n/e,this.elements[4]=t/e,this.elements[2]=(n*o-s*r)/e,this.elements[5]=(i*r-t*o)/e,!0}return!1},scale:function(e,t){e&&!t&&(t=e),e&&t&&(this.elements[0]*=e,this.elements[1]*=t,this.elements[3]*=e,this.elements[4]*=t)},invScale:function(e,t){e&&!t&&(t=e),this.scale(1/e,1/t)},apply:function(){var e;1===arguments.length&&arguments[0]instanceof Yt?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,this.elements[2],0,0,this.elements[5]],n=0,r=0;r<2;r++)for(var i=0;i<3;i++,n++)t[n]+=this.elements[3*r+0]*e[i+0]+this.elements[3*r+1]*e[i+3];this.elements=t.slice()},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof Yt?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);var t=[0,0,e[2],0,0,e[5]];t[2]=e[2]+this.elements[2]*e[0]+this.elements[5]*e[1],t[5]=e[5]+this.elements[2]*e[3]+this.elements[5]*e[4],t[0]=this.elements[0]*e[0]+this.elements[3]*e[1],t[3]=this.elements[0]*e[3]+this.elements[3]*e[4],t[1]=this.elements[1]*e[0]+this.elements[4]*e[1],t[4]=this.elements[1]*e[3]+this.elements[4]*e[4],this.elements=t.slice()},rotate:function(e){var t=Math.cos(e),n=Math.sin(e),r=this.elements[0],i=this.elements[1];this.elements[0]=t*r+n*i,this.elements[1]=-n*r+t*i,r=this.elements[3],i=this.elements[4],this.elements[3]=t*r+n*i,this.elements[4]=-n*r+t*i},rotateZ:function(e){this.rotate(e)},invRotateZ:function(e){this.rotateZ(e-Math.PI)},print:function(){var e=Xt(this.elements),t=V.nfs(this.elements[0],e,4)+" "+V.nfs(this.elements[1],e,4)+" "+V.nfs(this.elements[2],e,4)+"\n"+V.nfs(this.elements[3],e,4)+" "+V.nfs(this.elements[4],e,4)+" "+V.nfs(this.elements[5],e,4)+"\n\n";V.println(t)}};var jt=V.PMatrix3D=function(){this.reset()};jt.prototype={set:function(){16===arguments.length?this.elements=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof jt?this.elements=arguments[0].array():1===arguments.length&&arguments[0]instanceof Array&&(this.elements=arguments[0].slice())},get:function(){var e=new jt;return e.set(this.elements),e},reset:function(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},array:function(){return this.elements.slice()},translate:function(e,t,n){n===zn&&(n=0),this.elements[3]+=e*this.elements[0]+t*this.elements[1]+n*this.elements[2],this.elements[7]+=e*this.elements[4]+t*this.elements[5]+n*this.elements[6],this.elements[11]+=e*this.elements[8]+t*this.elements[9]+n*this.elements[10],this.elements[15]+=e*this.elements[12]+t*this.elements[13]+n*this.elements[14]},transpose:function(){var e=this.elements[4];this.elements[4]=this.elements[1],this.elements[1]=e,e=this.elements[8],this.elements[8]=this.elements[2],this.elements[2]=e,e=this.elements[6],this.elements[6]=this.elements[9],this.elements[9]=e,e=this.elements[3],this.elements[3]=this.elements[12],this.elements[12]=e,e=this.elements[7],this.elements[7]=this.elements[13],this.elements[13]=e,e=this.elements[11],this.elements[11]=this.elements[14],this.elements[14]=e},mult:function(e,t){var n,r,i,s;return e instanceof PVector?(n=e.x,r=e.y,i=e.z,s=1,t||(t=new PVector)):e instanceof Array&&(n=e[0],r=e[1],i=e[2],s=e[3]||1,(!t||3!==t.length&&4!==t.length)&&(t=[0,0,0])),t instanceof Array&&(3===t.length?(t[0]=this.elements[0]*n+this.elements[1]*r+this.elements[2]*i+this.elements[3],t[1]=this.elements[4]*n+this.elements[5]*r+this.elements[6]*i+this.elements[7],t[2]=this.elements[8]*n+this.elements[9]*r+this.elements[10]*i+this.elements[11]):4===t.length&&(t[0]=this.elements[0]*n+this.elements[1]*r+this.elements[2]*i+this.elements[3]*s,t[1]=this.elements[4]*n+this.elements[5]*r+this.elements[6]*i+this.elements[7]*s,t[2]=this.elements[8]*n+this.elements[9]*r+this.elements[10]*i+this.elements[11]*s,t[3]=this.elements[12]*n+this.elements[13]*r+this.elements[14]*i+this.elements[15]*s)),t instanceof PVector&&(t.x=this.elements[0]*n+this.elements[1]*r+this.elements[2]*i+this.elements[3],t.y=this.elements[4]*n+this.elements[5]*r+this.elements[6]*i+this.elements[7],t.z=this.elements[8]*n+this.elements[9]*r+this.elements[10]*i+this.elements[11]),t},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof jt?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=0;r<4;r++)for(var i=0;i<4;i++,n++)t[n]+=this.elements[i+0]*e[4*r+0]+this.elements[i+4]*e[4*r+1]+this.elements[i+8]*e[4*r+2]+this.elements[i+12]*e[4*r+3];this.elements=t.slice()},apply:function(){var e;1===arguments.length&&arguments[0]instanceof jt?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=0;r<4;r++)for(var i=0;i<4;i++,n++)t[n]+=this.elements[4*r+0]*e[i+0]+this.elements[4*r+1]*e[i+4]+this.elements[4*r+2]*e[i+8]+this.elements[4*r+3]*e[i+12];this.elements=t.slice()},rotate:function(e,t,n,r){if(arguments.length<4)this.rotateZ(e);else{var i=new PVector(t,n,r),s=i.mag();if(0===s)return;1!=s&&(i.normalize(),t=i.x,n=i.y,r=i.z);var o=V.cos(e),a=V.sin(e),l=1-o;this.apply(l*t*t+o,l*t*n-a*r,l*t*r+a*n,0,l*t*n+a*r,l*n*n+o,l*n*r-a*t,0,l*t*r-a*n,l*n*r+a*t,l*r*r+o,0,0,0,0,1)}},invApply:function(){K===zn&&(K=new jt);var e=arguments;return K.set(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]),!!K.invert()&&(this.preApply(K),!0)},rotateX:function(e){var t=V.cos(e),n=V.sin(e);this.apply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},rotateY:function(e){var t=V.cos(e),n=V.sin(e);this.apply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},rotateZ:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},scale:function(e,t,n){!e||t||n?e&&t&&!n&&(n=1):t=n=e,e&&t&&n&&(this.elements[0]*=e,this.elements[1]*=t,this.elements[2]*=n,this.elements[4]*=e,this.elements[5]*=t,this.elements[6]*=n,this.elements[8]*=e,this.elements[9]*=t,this.elements[10]*=n,this.elements[12]*=e,this.elements[13]*=t,this.elements[14]*=n)},skewX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},skewY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},shearX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},shearY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},multX:function(e,t,n,r){return n?r?this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]*r:this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]:this.elements[0]*e+this.elements[1]*t+this.elements[3]},multY:function(e,t,n,r){return n?r?this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]*r:this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]:this.elements[4]*e+this.elements[5]*t+this.elements[7]},multZ:function(e,t,n,r){return r?this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]*r:this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]},multW:function(e,t,n,r){return r?this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]*r:this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]},invert:function(){var e=this.elements[0]*this.elements[5]-this.elements[1]*this.elements[4],t=this.elements[0]*this.elements[6]-this.elements[2]*this.elements[4],n=this.elements[0]*this.elements[7]-this.elements[3]*this.elements[4],r=this.elements[1]*this.elements[6]-this.elements[2]*this.elements[5],i=this.elements[1]*this.elements[7]-this.elements[3]*this.elements[5],s=this.elements[2]*this.elements[7]-this.elements[3]*this.elements[6],o=this.elements[8]*this.elements[13]-this.elements[9]*this.elements[12],a=this.elements[8]*this.elements[14]-this.elements[10]*this.elements[12],l=this.elements[8]*this.elements[15]-this.elements[11]*this.elements[12],h=this.elements[9]*this.elements[14]-this.elements[10]*this.elements[13],u=this.elements[9]*this.elements[15]-this.elements[11]*this.elements[13],c=this.elements[10]*this.elements[15]-this.elements[11]*this.elements[14],f=e*c-t*u+n*h+r*l-i*a+s*o;if(Math.abs(f)<=1e-9)return!1;var p=[];p[0]=+this.elements[5]*c-this.elements[6]*u+this.elements[7]*h,p[4]=-this.elements[4]*c+this.elements[6]*l-this.elements[7]*a,p[8]=+this.elements[4]*u-this.elements[5]*l+this.elements[7]*o,p[12]=-this.elements[4]*h+this.elements[5]*a-this.elements[6]*o,p[1]=-this.elements[1]*c+this.elements[2]*u-this.elements[3]*h,p[5]=+this.elements[0]*c-this.elements[2]*l+this.elements[3]*a,p[9]=-this.elements[0]*u+this.elements[1]*l-this.elements[3]*o,p[13]=+this.elements[0]*h-this.elements[1]*a+this.elements[2]*o,p[2]=+this.elements[13]*s-this.elements[14]*i+this.elements[15]*r,p[6]=-this.elements[12]*s+this.elements[14]*n-this.elements[15]*t,p[10]=+this.elements[12]*i-this.elements[13]*n+this.elements[15]*e,p[14]=-this.elements[12]*r+this.elements[13]*t-this.elements[14]*e,p[3]=-this.elements[9]*s+this.elements[10]*i-this.elements[11]*r,p[7]=+this.elements[8]*s-this.elements[10]*n+this.elements[11]*t,p[11]=-this.elements[8]*i+this.elements[9]*n-this.elements[11]*e,p[15]=+this.elements[8]*r-this.elements[9]*t+this.elements[10]*e;var m=1/f;return p[0]*=m,p[1]*=m,p[2]*=m,p[3]*=m,p[4]*=m,p[5]*=m,p[6]*=m,p[7]*=m,p[8]*=m,p[9]*=m,p[10]*=m,p[11]*=m,p[12]*=m,p[13]*=m,p[14]*=m,p[15]*=m,this.elements=p.slice(),!0},toString:function(){for(var e="",t=0;t<15;t++)e+=this.elements[t]+", ";return e+=this.elements[15]},print:function(){var e=Xt(this.elements),t=V.nfs(this.elements[0],e,4)+" "+V.nfs(this.elements[1],e,4)+" "+V.nfs(this.elements[2],e,4)+" "+V.nfs(this.elements[3],e,4)+"\n"+V.nfs(this.elements[4],e,4)+" "+V.nfs(this.elements[5],e,4)+" "+V.nfs(this.elements[6],e,4)+" "+V.nfs(this.elements[7],e,4)+"\n"+V.nfs(this.elements[8],e,4)+" "+V.nfs(this.elements[9],e,4)+" "+V.nfs(this.elements[10],e,4)+" "+V.nfs(this.elements[11],e,4)+"\n"+V.nfs(this.elements[12],e,4)+" "+V.nfs(this.elements[13],e,4)+" "+V.nfs(this.elements[14],e,4)+" "+V.nfs(this.elements[15],e,4)+"\n\n";V.println(t)},invTranslate:function(e,t,n){this.preApply(1,0,0,-e,0,1,0,-t,0,0,1,-n,0,0,0,1)},invRotateX:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},invRotateY:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},invRotateZ:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},invScale:function(e,t,n){this.preApply([1/e,0,0,0,0,1/t,0,0,0,0,1/n,0,0,0,0,1])}};var Kt=V.PMatrixStack=function(){this.matrixStack=[]};function Wt(e,t,n,r){var i,s,o,a;if(Re===Zn.HSB){var l=V.color.toRGB(e,t,n);i=l[0],s=l[1],o=l[2]}else i=Math.round(e/Pe*255),s=Math.round(t/Ce*255),o=Math.round(n/Me*255);return i=255<(i=i<0?0:i)?255:i,s=255<(s=s<0?0:s)?255:s,o=255<(o=o<0?0:o)?255:o,(a=255<(a=(a=Math.round(r/Se*255))<0?0:a)?255:a)<<24&Zn.ALPHA_MASK|i<<16&Zn.RED_MASK|s<<8&Zn.GREEN_MASK|o&Zn.BLUE_MASK}function Zt(e){var t,n,r;t=((e&Zn.RED_MASK)>>>16)/255,n=((e&Zn.GREEN_MASK)>>>8)/255,r=(e&Zn.BLUE_MASK)/255;var i,s=V.max(V.max(t,n),r),o=V.min(V.min(t,n),r);return o===s?[0,0,s*Me]:(i=t===s?(n-r)/(s-o):n===s?2+(r-t)/(s-o):4+(t-n)/(s-o),(i/=6)<0?i+=1:1>8)},V.peg=function(e){return e<0?0:255>8),f=r+((h-r)*t>>8),p=i+((u-i)*t>>8);return g(((4278190080&e)>>>24)+t,255)<<24|(c=(c<0?0:255>>24,r=e&f,i=e&p,s=e&m,o=t&f,a=t&p,l=t&m;return g(((e&c)>>>24)+n,255)<<24|r+((o-r)*n>>8)&f|i+((a-i)*n>>8)&p|s+((l-s)*n>>8)&m},add:function(e,t){var n=(t&c)>>>24;return g(((e&c)>>>24)+n,255)<<24|g((e&f)+((t&f)>>8)*n,f)&f|g((e&p)+((t&p)>>8)*n,p)&p|g((e&m)+((t&m)*n>>8),m)},subtract:function(e,t){var n=(t&c)>>>24;return g(((e&c)>>>24)+n,255)<<24|r((e&f)-((t&f)>>8)*n,p)&f|r((e&p)-((t&p)>>8)*n,m)&p|r((e&m)-((t&m)*n>>8),0)},lightest:function(e,t){var n=(t&c)>>>24;return g(((e&c)>>>24)+n,255)<<24|r(e&f,((t&f)>>8)*n)&f|r(e&p,((t&p)>>8)*n)&p|r(e&m,(t&m)*n>>8)},darkest:function(e,t){var n=(t&c)>>>24,r=e&f,i=e&p,s=e&m,o=g(e&f,((t&f)>>8)*n),a=g(e&p,((t&p)>>8)*n),l=g(e&m,(t&m)*n>>8);return g(((e&c)>>>24)+n,255)<<24|r+((o-r)*n>>8)&f|i+((a-i)*n>>8)&p|s+((l-s)*n>>8)&m},difference:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,s>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,n+s-(n*s>>7),r+o-(r*o>>7),i+a-(i*a>>7))},multiply:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,n*s>>8,r*o>>8,i*a>>8)},screen:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,255-((255-n)*(255-s)>>8),255-((255-r)*(255-o)>>8),255-((255-i)*(255-a)>>8))},hard_light:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,s<128?n*s>>7:255-((255-n)*(255-s)>>7),o<128?r*o>>7:255-((255-r)*(255-o)>>7),a<128?i*a>>7:255-((255-i)*(255-a)>>7))},soft_light:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,(n*s>>7)+(n*n>>8)-(n*n*s>>15),(r*o>>7)+(r*r>>8)-(r*r*o>>15),(i*a>>7)+(i*i>>8)-(i*i*a>>15))},overlay:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m;return d(e,(t&c)>>>24,n,r,i,0,0,0,n<128?n*s>>7:255-((255-n)*(255-s)>>7),r<128?r*o>>7:255-((255-r)*(255-o)>>7),i<128?i*a>>7:255-((255-i)*(255-a)>>7))},dodge:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m,l=255;255!==s&&(l=(l=(n<<8)/(255-s))<0?0:255>>24,n,r,i,0,0,0,l,h,u)},burn:function(e,t){var n=(e&f)>>16,r=(e&p)>>8,i=e&m,s=(t&f)>>16,o=(t&p)>>8,a=t&m,l=0;0!==s&&(l=255-((l=(255-n<<8)/s)<0?0:255>>24,n,r,i,0,0,0,l,h,u)}}}(),V.color=function(e,t,n,r){return e!==zn&&t!==zn&&n!==zn&&r!==zn?Wt(e,t,n,r):e!==zn&&t!==zn&&n!==zn?Wt(e,t,n,Se):e!==zn&&t!==zn?(s=t,(i=e)&Zn.ALPHA_MASK?(o=(o=255<(o=Math.round(s/Se*255))?255:o)<0?0:o,i-(i&Zn.ALPHA_MASK)+(o<<24&Zn.ALPHA_MASK)):Re===Zn.RGB?Wt(i,i,i,s):Re===Zn.HSB?Wt(0,0,i/Pe*Me,s):void 0):"number"==typeof e?function(e){if(e<=Pe&&0<=e){if(Re===Zn.RGB)return Wt(e,e,e,Se);if(Re===Zn.HSB)return Wt(0,0,e/Pe*Me,Se)}if(e)return 2147483647>>16)+","+((e&Zn.GREEN_MASK)>>>8)+","+(e&Zn.BLUE_MASK)+","+((e&Zn.ALPHA_MASK)>>>24)/255+")"},V.color.toInt=function(e,t,n,r){return r<<24&Zn.ALPHA_MASK|e<<16&Zn.RED_MASK|t<<8&Zn.GREEN_MASK|n&Zn.BLUE_MASK},V.color.toArray=function(e){return[(e&Zn.RED_MASK)>>>16,(e&Zn.GREEN_MASK)>>>8,e&Zn.BLUE_MASK,(e&Zn.ALPHA_MASK)>>>24]},V.color.toGLArray=function(e){return[((e&Zn.RED_MASK)>>>16)/255,((e&Zn.GREEN_MASK)>>>8)/255,(e&Zn.BLUE_MASK)/255,((e&Zn.ALPHA_MASK)>>>24)/255]},V.color.toRGB=function(e,t,n){e=(e=(e=Pe>>16)/255*Pe},V.green=function(e){return((e&Zn.GREEN_MASK)>>>8)/255*Ce},V.blue=function(e){return(e&Zn.BLUE_MASK)/255*Me},V.alpha=function(e){return((e&Zn.ALPHA_MASK)>>>24)/255*Se},V.lerpColor=function(e,t,n){var r,i,s,o,a,l,h,u,c,f,p,m,g,d,v,y,A=V.color(e),b=V.color(t);return Re===Zn.HSB?(m=Zt(A),h=((A&Zn.ALPHA_MASK)>>>24)/Se,g=Zt(b),p=((b&Zn.ALPHA_MASK)>>>24)/Se,v=V.lerp(m[0],g[0],n),y=V.lerp(m[1],g[1],n),s=V.lerp(m[2],g[2],n),d=V.color.toRGB(v,y,s),(V.lerp(h,p,n)*Se+.5|0)<<24&Zn.ALPHA_MASK|d[0]<<16&Zn.RED_MASK|d[1]<<8&Zn.GREEN_MASK|d[2]&Zn.BLUE_MASK):(o=(A&Zn.RED_MASK)>>>16,a=(A&Zn.GREEN_MASK)>>>8,l=A&Zn.BLUE_MASK,h=((A&Zn.ALPHA_MASK)>>>24)/Se,u=(b&Zn.RED_MASK)>>>16,c=(b&Zn.GREEN_MASK)>>>8,f=b&Zn.BLUE_MASK,p=((b&Zn.ALPHA_MASK)>>>24)/Se,r=V.lerp(o,u,n)+.5|0,i=V.lerp(a,c,n)+.5|0,s=V.lerp(l,f,n)+.5|0,(V.lerp(h,p,n)*Se+.5|0)<<24&Zn.ALPHA_MASK|r<<16&Zn.RED_MASK|i<<8&Zn.GREEN_MASK|s&Zn.BLUE_MASK)},V.colorMode=function(){Re=arguments[0],1=n.height||e>=n.width)throw"x and y must be non-negative and less than the dimensions of the image"}else e=n.width>>>1,t=n.height>>>1;var r='url("'+n.toDataURL()+'") '+e+" "+t+", default";l.style.cursor=r}else if(1===arguments.length){var i=arguments[0];l.style.cursor=i}else l.style.cursor=ve},V.noCursor=function(){l.style.cursor=Zn.NOCURSOR},V.link=function(e,t){t!==zn?jn.open(e,t):jn.location=e},V.beginDraw=Wn,V.endDraw=Wn,zt.prototype.toImageData=function(e,t,n,r){return e=e!==zn?e:0,t=t!==zn?t:0,n=n!==zn?n:V.width,r=r!==zn?r:V.height,d.getImageData(e,t,n,r)},Ut.prototype.toImageData=function(e,t,n,r){e=e!==zn?e:0,t=t!==zn?t:0,n=n!==zn?n:V.width,r=r!==zn?r:V.height;var i=Kn.createElement("canvas").getContext("2d").createImageData(n,r),s=new rr(n*r*4);d.readPixels(e,t,n,r,d.RGBA,d.UNSIGNED_BYTE,s);for(var o=0,a=s.length,l=i.data;o>>n-1&1);)n--;for(var r="";0>>--n&1?"1":"0";return r},V.unbinary=function(e){for(var t=e.length-1,n=1,r=0;0<=t;){var i=e[t--];if("0"!==i&&"1"!==i)throw"the value passed into unbinary was not an 8 bit binary number";"1"===i&&(r+=n),n<<=1}return r};function en(e){var t=parseInt("0x"+e,16);return 2147483647=t&&(n=n.substring(n.length-t,n.length)),n}(e,t)},V.unhex=function(e){if(e instanceof Array){for(var t=[],n=0;n 0.5){ discard; } } if(uIsDrawingText == 1){ float alpha = texture2D(uSampler, vTextureCoord).a; gl_FragColor = vec4(vFrontColor.rgb * alpha, alpha); } else{ gl_FragColor = vFrontColor; }}"),m=Ft(d,"varying vec4 vFrontColor;attribute vec3 aVertex;attribute vec4 aColor;uniform mat4 uView;uniform mat4 uProjection;uniform float uPointSize;void main(void) { vFrontColor = aColor; gl_PointSize = uPointSize; gl_Position = uProjection * uView * vec4(aVertex, 1.0);}","#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 vFrontColor;uniform bool uSmooth;void main(void){ if(uSmooth == true){ float dist = distance(gl_PointCoord, vec2(0.5)); if(dist > 0.5){ discard; } } gl_FragColor = vFrontColor;}"),V.strokeWeight(1),y=Ft(d,Rt,"#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 vFrontColor;uniform sampler2D uSampler;uniform bool uUsingTexture;varying vec2 vTexture;void main(void){ if( uUsingTexture ){ gl_FragColor = vec4(texture2D(uSampler, vTexture.xy)) * vFrontColor; } else{ gl_FragColor = vFrontColor; }}"),d.useProgram(y),It("usingTexture3d",y,"usingTexture",$e),V.lightFalloff(1,0,0),V.shininess(1),V.ambient(255,255,255),V.specular(0,0,0),V.emissive(0,0,0),A=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,A),d.bufferData(d.ARRAY_BUFFER,Pt,d.STATIC_DRAW),b=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,b),d.bufferData(d.ARRAY_BUFFER,Mt,d.STATIC_DRAW),x=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,x),d.bufferData(d.ARRAY_BUFFER,Ct,d.STATIC_DRAW),E=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,E),d.bufferData(d.ARRAY_BUFFER,Tt,d.STATIC_DRAW),S=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,S),d.bufferData(d.ARRAY_BUFFER,_t,d.STATIC_DRAW),P=d.createBuffer(),M=d.createBuffer(),T=d.createBuffer(),_=d.createBuffer(),R=d.createBuffer(),I=d.createBuffer(),L=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,L),d.bufferData(d.ARRAY_BUFFER,new er([0,0,0]),d.STATIC_DRAW),N=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,N),d.bufferData(d.ARRAY_BUFFER,new er([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),d.STATIC_DRAW),F=d.createBuffer(),d.bindBuffer(d.ARRAY_BUFFER,F),d.bufferData(d.ARRAY_BUFFER,new er([0,0,1,0,1,1,0,1]),d.STATIC_DRAW),k=d.createBuffer(),d.bindBuffer(d.ELEMENT_ARRAY_BUFFER,k),d.bufferData(d.ELEMENT_ARRAY_BUFFER,new nr([0,1,2,2,3,0]),d.STATIC_DRAW),z=new jt,U=new jt,H=new jt,X=new jt,W=new jt,V.camera(),V.perspective(),Y=new Kt,j=new Kt,a=new jt,u=new jt,C=new jt,g=new jt,c=new jt,(v=new jt).set(-1,3,-3,1,3,-6,3,0,-3,3,0,0,1,0,0,0),Vt.prototype.size.apply(this,arguments)}),zt.prototype.ambientLight=Vt.prototype.a3DOnlyFunction,Ut.prototype.ambientLight=function(e,t,n,r,i,s){if(tt===Zn.MAX_LIGHTS)throw"can only create "+Zn.MAX_LIGHTS+" lights";var o=new PVector(r,i,s),a=new jt;a.scale(1,-1,1),a.apply(H.array()),a.mult(o,o);var l=Wt(e,t,n,0),h=[((l&Zn.RED_MASK)>>>16)/255,((l&Zn.GREEN_MASK)>>>8)/255,(l&Zn.BLUE_MASK)/255];d.useProgram(y),Lt("uLights.color.3d."+tt,y,"uLights"+tt+".color",h),Lt("uLights.position.3d."+tt,y,"uLights"+tt+".position",o.array()),It("uLights.type.3d."+tt,y,"uLights"+tt+".type",0),It("uLightCount3d",y,"uLightCount",++tt)},zt.prototype.directionalLight=Vt.prototype.a3DOnlyFunction,Ut.prototype.directionalLight=function(e,t,n,r,i,s){if(tt===Zn.MAX_LIGHTS)throw"can only create "+Zn.MAX_LIGHTS+" lights";d.useProgram(y);var o=new jt;o.scale(1,-1,1),o.apply(H.array());var a=[(o=o.array())[0]*r+o[4]*i+o[8]*s,o[1]*r+o[5]*i+o[9]*s,o[2]*r+o[6]*i+o[10]*s],l=Wt(e,t,n,0),h=[((l&Zn.RED_MASK)>>>16)/255,((l&Zn.GREEN_MASK)>>>8)/255,(l&Zn.BLUE_MASK)/255];Lt("uLights.color.3d."+tt,y,"uLights"+tt+".color",h),Lt("uLights.position.3d."+tt,y,"uLights"+tt+".position",a),It("uLights.type.3d."+tt,y,"uLights"+tt+".type",1),It("uLightCount3d",y,"uLightCount",++tt)},zt.prototype.lightFalloff=Vt.prototype.a3DOnlyFunction,Ut.prototype.lightFalloff=function(e,t,n){d.useProgram(y),Lt("uFalloff3d",y,"uFalloff",[e,t,n])},zt.prototype.lightSpecular=Vt.prototype.a3DOnlyFunction,Ut.prototype.lightSpecular=function(e,t,n){var r=Wt(e,t,n,0),i=[((r&Zn.RED_MASK)>>>16)/255,((r&Zn.GREEN_MASK)>>>8)/255,(r&Zn.BLUE_MASK)/255];d.useProgram(y),Lt("uSpecular3d",y,"uSpecular",i)},V.lights=function(){V.ambientLight(128,128,128),V.directionalLight(128,128,128,0,0,-1),V.lightFalloff(1,0,0),V.lightSpecular(0,0,0)},zt.prototype.pointLight=Vt.prototype.a3DOnlyFunction,Ut.prototype.pointLight=function(e,t,n,r,i,s){if(tt===Zn.MAX_LIGHTS)throw"can only create "+Zn.MAX_LIGHTS+" lights";var o=new PVector(r,i,s),a=new jt;a.scale(1,-1,1),a.apply(H.array()),a.mult(o,o);var l=Wt(e,t,n,0),h=[((l&Zn.RED_MASK)>>>16)/255,((l&Zn.GREEN_MASK)>>>8)/255,(l&Zn.BLUE_MASK)/255];d.useProgram(y),Lt("uLights.color.3d."+tt,y,"uLights"+tt+".color",h),Lt("uLights.position.3d."+tt,y,"uLights"+tt+".position",o.array()),It("uLights.type.3d."+tt,y,"uLights"+tt+".type",2),It("uLightCount3d",y,"uLightCount",++tt)},zt.prototype.noLights=Vt.prototype.a3DOnlyFunction,Ut.prototype.noLights=function(){tt=0,d.useProgram(y),It("uLightCount3d",y,"uLightCount",tt)},zt.prototype.spotLight=Vt.prototype.a3DOnlyFunction,Ut.prototype.spotLight=function(e,t,n,r,i,s,o,a,l,h,u){if(tt===Zn.MAX_LIGHTS)throw"can only create "+Zn.MAX_LIGHTS+" lights";d.useProgram(y);var c=new PVector(r,i,s),f=new jt;f.scale(1,-1,1),f.apply(H.array()),f.mult(c,c);var p=[(f=f.array())[0]*o+f[4]*a+f[8]*l,f[1]*o+f[5]*a+f[9]*l,f[2]*o+f[6]*a+f[10]*l],m=Wt(e,t,n,0),g=[((m&Zn.RED_MASK)>>>16)/255,((m&Zn.GREEN_MASK)>>>8)/255,(m&Zn.BLUE_MASK)/255];Lt("uLights.color.3d."+tt,y,"uLights"+tt+".color",g),Lt("uLights.position.3d."+tt,y,"uLights"+tt+".position",c.array()),Lt("uLights.direction.3d."+tt,y,"uLights"+tt+".direction",p),Lt("uLights.concentration.3d."+tt,y,"uLights"+tt+".concentration",u),Lt("uLights.angle.3d."+tt,y,"uLights"+tt+".angle",h),It("uLights.type.3d."+tt,y,"uLights"+tt+".type",3),It("uLightCount3d",y,"uLightCount",++tt)},zt.prototype.beginCamera=function(){throw"beginCamera() is not available in 2D mode"},Ut.prototype.beginCamera=function(){if(ht)throw"You cannot call beginCamera() again before calling endCamera()";ht=!0,H=U,X=z},zt.prototype.endCamera=function(){throw"endCamera() is not available in 2D mode"},Ut.prototype.endCamera=function(){if(!ht)throw"You cannot call endCamera() before calling beginCamera()";H.set(z),X.set(U),ht=!1},V.camera=function(e,t,n,r,i,s,o,a,l){e===zn&&(ct=V.width/2,ft=V.height/2,n=pt=ft/Math.tan(ut/2),r=e=ct,i=t=ft,a=1,l=o=s=0);var h=new PVector(e-r,t-i,n-s),u=new PVector(o,a,l);h.normalize();var c=PVector.cross(u,h);u=PVector.cross(h,c),c.normalize(),u.normalize();var f=c.x,p=c.y,m=c.z,g=u.x,d=u.y,v=u.z,y=h.x,A=h.y,b=h.z;z.set(f,p,m,0,g,d,v,0,y,A,b,0,0,0,0,1),z.translate(-e,-t,-n),U.reset(),U.invApply(f,p,m,0,g,d,v,0,y,A,b,0,0,0,0,1),U.translate(e,t,n),H.set(z),X.set(U)},V.perspective=function(e,t,n,r){var i,s,o,a;0===arguments.length&&(ft=l.height/2,pt=ft/Math.tan(ut/2),mt=pt/10,gt=10*pt,dt=V.width/V.height,e=ut,t=dt,n=mt,r=gt),o=(i=n*Math.tan(e/2))*t,a=(s=-i)*t,V.frustum(a,o,s,i,n,r)},zt.prototype.frustum=function(){throw"Processing.js: frustum() is not supported in 2D mode"},Ut.prototype.frustum=function(e,t,n,r,i,s){!0,(W=new jt).set(2*i/(t-e),0,(t+e)/(t-e),0,0,2*i/(r-n),(r+n)/(r-n),0,0,0,-(s+i)/(s-i),-2*s*i/(s-i),0,0,-1,0);var o=new jt;o.set(W),o.transpose(),d.useProgram(p),Dt("projection2d",p,"uProjection",!1,o.array()),d.useProgram(y),Dt("projection3d",y,"uProjection",!1,o.array()),d.useProgram(m),Dt("uProjectionUS",m,"uProjection",!1,o.array())},V.ortho=function(e,t,n,r,i,s){0===arguments.length&&(e=0,t=V.width,n=0,r=V.height,i=-10,s=10);var o=2/(t-e),a=2/(r-n),l=-2/(s-i),h=-(t+e)/(t-e),u=-(r+n)/(r-n),c=-(s+i)/(s-i);(W=new jt).set(o,0,0,h,0,a,0,u,0,0,l,c,0,0,0,1);var f=new jt;f.set(W),f.transpose(),d.useProgram(p),Dt("projection2d",p,"uProjection",!1,f.array()),d.useProgram(y),Dt("projection3d",y,"uProjection",!1,f.array()),d.useProgram(m),Dt("uProjectionUS",m,"uProjection",!1,f.array()),!1},V.printProjection=function(){W.print()},V.printCamera=function(){z.print()},zt.prototype.box=Vt.prototype.a3DOnlyFunction,Ut.prototype.box=function(e,t,n){t&&n||(t=n=e);var r=new jt;r.scale(e,t,n);var i=new jt;if(i.scale(1,-1,1),i.apply(H.array()),i.transpose(),Z){if(d.useProgram(y),Dt("model3d",y,"uModel",!1,r.array()),Dt("view3d",y,"uView",!1,i.array()),d.enable(d.POLYGON_OFFSET_FILL),d.polygonOffset(1,1),Lt("color3d",y,"uColor",q),0Zn.TWO_PI&&(s=i+Zn.TWO_PI);var a,l,h,u,c,f=n/2,p=r/2,m=e+f,g=t+p,d=(a=m+.5,l=g+.5,h=i,u=1/(f+p),c=s,function(e,t,n,r,i){for(n=0,r=h,i=c+u,e.beginShape(),t&&e.vertex(a-.5,l-.5);r>>16,r[n+1]=(t&Zn.GREEN_MASK)>>>8,r[n+2]=t&Zn.BLUE_MASK,r[n+3]=(t&Zn.ALPHA_MASK)>>>24,u.__isDirty=!0}),toArray:(h=a,function(){var e=[],t=h.imageData.data,n=h.width*h.height;if(h.isRemote)throw"Image is loaded remotely. Cannot get pixels.";for(var r=0,i=0;r>>16,n[t+1]=(r&Zn.GREEN_MASK)>>>8,n[t+2]=r&Zn.BLUE_MASK,n[t+3]=(r&Zn.ALPHA_MASK)>>>24;l.__isDirty=!0})}};function An(e,t,n,r){var i=new yn(n,r,Zn.ARGB);return i.fromImageData(V.toImageData(e,t,n,r)),i}function bn(e,t,n,r,i){if(i.isRemote)throw"Image is loaded remotely. Cannot get x,y,w,h.";for(var s=new yn(n,r,Zn.ARGB),o=s.imageData.data,a=i.width,l=i.height,h=i.imageData.data,u=Math.max(0,-t),c=Math.max(0,-e),f=Math.min(r,l-t),p=Math.min(n,a-e),m=u;mqe&&xn())}yn.prototype={__isPImage:!0,updatePixels:function(){var e=this.sourceImg;e&&e instanceof Qn&&this.__isDirty&&e.getContext("2d").putImageData(this.imageData,0,0),this.__isDirty=!1},fromHTMLImageData:function(t){var e=vn(t);try{var n=e.context.getImageData(0,0,t.width,t.height);this.fromImageData(n)}catch(e){t.width&&t.height&&(this.isRemote=!0,this.width=t.width,this.height=t.height)}this.sourceImg=t},get:function(e,t,n,r){return arguments.length?2===arguments.length?V.get(e,t,this):4===arguments.length?V.get(e,t,n,r,this):void 0:V.get(this)},set:function(e,t,n){V.set(e,t,n,this),this.__isDirty=!0},blend:function(e,t,n,r,i,s,o,a,l,h){9===arguments.length?V.blend(this,e,t,n,r,i,s,o,a,l,this):10===arguments.length&&V.blend(e,t,n,r,i,s,o,a,l,h,this),delete this.sourceImg},copy:function(e,t,n,r,i,s,o,a,l){8===arguments.length?V.blend(this,e,t,n,r,i,s,o,a,Zn.REPLACE,this):9===arguments.length&&V.blend(e,t,n,r,i,s,o,a,l,Zn.REPLACE,this),delete this.sourceImg},filter:function(e,t){2===arguments.length?V.filter(e,t,this):1===arguments.length&&V.filter(e,null,this),delete this.sourceImg},save:function(e){V.save(e,this)},resize:function(e,t){if(this.isRemote)throw"Image is loaded remotely. Cannot resize.";if(0!==this.width||0!==this.height){0===e&&0!==t?e=Math.floor(this.width/this.height*t):0===t&&0!==e&&(t=Math.floor(this.height/this.width*e));var n=vn(vn(this.imageData).canvas,e,t).context.getImageData(0,0,e,t);this.fromImageData(n)}},mask:function(e){var t,n,r=this.toImageData();if(e instanceof yn||e.__isPImage){if(e.width!==this.width||e.height!==this.height)throw"mask must have the same dimensions as PImage.";for(e=e.toImageData(),t=2,n=this.width*this.height*4;t=V.width||e<0||t<0||t>=V.height)return 0;if(Ze){var r=4*((0|e)+V.width*(0|t));return(n=V.imageData.data)[r+3]<<24&Zn.ALPHA_MASK|n[r]<<16&Zn.RED_MASK|n[r+1]<<8&Zn.GREEN_MASK|n[r+2]&Zn.BLUE_MASK}return(n=V.toImageData(0|e,0|t,1,1).data)[3]<<24&Zn.ALPHA_MASK|n[0]<<16&Zn.RED_MASK|n[1]<<8&Zn.GREEN_MASK|n[2]&Zn.BLUE_MASK}(e,t):void 0!==e?bn(0,0,e.width,e.height,e):An(0,0,V.width,V.height)},V.createGraphics=function(e,t,n){var r=new or;return r.size(e,t,n),r.background(0,0),r},V.set=function(e,t,n,r){3===arguments.length?"number"==typeof n?En(e,t,n):(n instanceof yn||n.__isPImage)&&V.image(n,e,t):4===arguments.length&&function(e,t,n,r){if(r.isRemote)throw"Image is loaded remotely. Cannot set x,y.";var i=V.color.toArray(n),s=t*r.width*4+4*e,o=r.imageData.data;o[s]=i[0],o[s+1]=i[1],o[s+2]=i[2],o[s+3]=i[3]}(e,t,n,r)},V.imageData={},V.pixels={getLength:function(){return V.imageData.data.length?V.imageData.data.length/4:0},getPixel:function(e){var t=4*e,n=V.imageData.data;return n[t+3]<<24&4278190080|n[t+0]<<16&16711680|n[t+1]<<8&65280|255&n[t+2]},setPixel:function(e,t){var n=4*e,r=V.imageData.data;r[n+0]=(16711680&t)>>>16,r[n+1]=(65280&t)>>>8,r[n+2]=255&t,r[n+3]=(4278190080&t)>>>24},toArray:function(){for(var e=[],t=V.imageData.width*V.imageData.height,n=V.imageData.data,r=0,i=0;r>16&255)+151*(f>>8&255)+28*(255&f))<(o=77*(i>>16&255)+151*(i>>8&255)+28*(255&i))&&(s=f,o=d),(g=77*((c=t.pixels.getPixel(a))>>16&255)+151*(c>>8&255)+28*(255&c))>16&255)+151*(p>>8&255)+28*(255&p))>16&255)+151*(m>>8&255)+28*(255&m))>16&255)+151*(i>>8&255)+28*(255&i))<(d=77*(f>>16&255)+151*(f>>8&255)+28*(255&f))&&(s=f,o=d),o<(g=77*((c=t.pixels.getPixel(a))>>16&255)+151*(c>>8&255)+28*(255&c))&&(s=c,o=g),o<(v=77*(p>>16&255)+151*(p>>8&255)+28*(255&p))&&(s=p,o=v),o<(y=77*(m>>16&255)+151*(m>>8&255)+28*(255&m))&&(s=m,o=y),x[A++]=s;t.pixels.set(x)};V.filter=function(e,t,n){var r,i,s,o;if(3===arguments.length?(n.loadPixels(),r=n):(V.loadPixels(),r=V),t===zn&&(t=null),r.isRemote)throw"Image is loaded remotely. Cannot filter image.";var a=r.pixels.getLength();switch(e){case Zn.BLUR:Pn(t||1,r);break;case Zn.GRAY:if(r.format===Zn.ALPHA){for(o=0;o>16&255)+151*(i>>8&255)+28*(255&i)>>8,r.pixels.setPixel(o,i&Zn.ALPHA_MASK|s<<16|s<<8|s);break;case Zn.INVERT:for(o=0;o>16&255,c=r.pixels.getPixel(o)>>8&255,f=255&r.pixels.getPixel(o);u=255*(u*l>>8)/h,c=255*(c*l>>8)/h,f=255*(f*l>>8)/h,r.pixels.setPixel(o,4278190080&r.pixels.getPixel(o)|u<<16|c<<8|f)}break;case Zn.OPAQUE:for(o=0;o>16,V.max((r.pixels.getPixel(o)&Zn.GREEN_MASK)>>8,r.pixels.getPixel(o)&Zn.BLUE_MASK));r.pixels.setPixel(o,r.pixels.getPixel(o)&Zn.ALPHA_MASK|(m=e.width&&(r=e.width-1),i>=e.height&&(i=e.height-1);var g=r-t,d=i-n,v=u-l,y=c-h;if(!(v<=0||y<=0||g<=0||d<=0||o<=l||a<=h||t>=e.width||n>=e.height)){var A=Math.floor(g/v*Zn.PRECISIONF),b=Math.floor(d/y*Zn.PRECISIONF),x=V.shared;x.srcXOffset=Math.floor(l<0?-l*A:t*Zn.PRECISIONF),x.srcYOffset=Math.floor(h<0?-h*b:n*Zn.PRECISIONF),l<0&&(v+=l,l=0),h<0&&(y+=h,h=0),v=Math.min(v,o-l),y=Math.min(y,a-h);var w,E=h*o+l;x.srcBuffer=e.imageData.data,x.iw=e.width,x.iw1=e.width-1,x.ih1=e.height-1;V.filter_bilinear,V.filter_new_scanline;var S,P,C,M,T,_,R=Tn[f],L=Zn.ALPHA_MASK,I=Zn.RED_MASK,D=Zn.GREEN_MASK,O=Zn.BLUE_MASK,N=Zn.PREC_MAXVAL,F=Zn.PRECISIONB,k=Zn.PREC_RED_SHIFT,B=Zn.PREC_ALPHA_SHIFT,$=x.srcBuffer,G=Math.min;for(m=0;m>F)*x.iw,x.v2=G(1+(x.srcYOffset>>F),x.ih1)*x.iw,p=0;p>F,x.ll=x.ifU*x.fracV>>F,x.ur=x.fracU*x.ifV>>F,x.lr=x.fracU*x.fracV>>F,x.u1=x.sX>>F,x.u2=G(x.u1+1,x.iw1),C=4*(x.v1+x.u1),M=4*(x.v1+x.u2),T=4*(x.v2+x.u1),_=4*(x.v2+x.u2),x.cUL=$[C+3]<<24&L|$[C]<<16&I|$[C+1]<<8&D|$[C+2]&O,x.cUR=$[M+3]<<24&L|$[M]<<16&I|$[M+1]<<8&D|$[M+2]&O,x.cLL=$[T+3]<<24&L|$[T]<<16&I|$[T+1]<<8&D|$[T+2]&O,x.cLR=$[_+3]<<24&L|$[_]<<16&I|$[_+1]<<8&D|$[_+2]&O,x.r=x.ul*((x.cUL&I)>>16)+x.ll*((x.cLL&I)>>16)+x.ur*((x.cUR&I)>>16)+x.lr*((x.cLR&I)>>16)<>>F&D,x.b=x.ul*(x.cUL&O)+x.ll*(x.cLL&O)+x.ur*(x.cUR&O)+x.lr*(x.cLR&O)>>>F,x.a=x.ul*((x.cUL&L)>>>24)+x.ll*((x.cLL&L)>>>24)+x.ur*((x.cUR&L)>>>24)+x.lr*((x.cLR&L)>>>24)<>>16,s[P+1]=(S&D)>>>8,s[P+2]=S&O,s[P+3]=(S&L)>>>24,x.sX+=A;E+=o,x.srcYOffset+=b}}},V.loadFont=function(i,e){if(i===zn)throw"font name required in loadFont.";if(-1===i.indexOf(".svg"))return e===zn&&(e=Ke.size),PFont.get(i,e);var t=V.loadGlyphs(i);return{name:i,css:"12px sans-serif",glyph:!0,units_per_em:t.units_per_em,horiz_adv_x:1/t.units_per_em*t.horiz_adv_x,ascent:t.ascent,descent:t.descent,width:function(e){for(var t=0,n=e.length,r=0;r":return e.greater;case"?":return e.question;case"@":return e.at;case"[":return e.bracketleft;case"\\":return e.backslash;case"]":return e.bracketright;case"^":return e.asciicircum;case"`":return e.grave;case"{":return e.braceleft;case"|":return e.bar;case"}":return e.braceright;case"~":return e.asciitilde;default:return e[t]}}catch(e){or.debug(e)}},zt.prototype.text$line=function(e,t,n,r,i){var s=0,o=0;if(Ke.glyph){var a=V.glyphTable[Ue];qt(),d.translate(t,n+He),i!==Zn.RIGHT&&i!==Zn.CENTER||(s=a.width(e),o=i===Zn.RIGHT?-s:-s/2);var l=1/a.units_per_em*He;d.scale(l,l);for(var h=0,u=e.length;h= 15) { presto = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || (ie && ie_version >= 9); - - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") } - - var rmClass = function(node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - { e.removeChild(e.firstChild); } - return e - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e) - } - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) { e.className = className; } - if (style) { e.style.cssText = style; } - if (typeof content == "string") { e.appendChild(document.createTextNode(content)); } - else if (content) { for (var i = 0; i < content.length; ++i) { e.appendChild(content[i]); } } - return e - } - // wrapper for elt, which removes the elt from the accessibility tree - function eltP(tag, content, className, style) { - var e = elt(tag, content, className, style); - e.setAttribute("role", "presentation"); - return e - } - - var range; - if (document.createRange) { range = function(node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r - }; } - else { range = function(node, start, end) { - var r = document.body.createTextRange(); - try { r.moveToElementText(node.parentNode); } - catch(e) { return r } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r - }; } - - function contains(parent, child) { - if (child.nodeType == 3) // Android browser always returns false when child is a textnode - { child = child.parentNode; } - if (parent.contains) - { return parent.contains(child) } - do { - if (child.nodeType == 11) { child = child.host; } - if (child == parent) { return true } - } while (child = child.parentNode) - } - - function activeElt() { - // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement. - // IE < 10 will throw when accessed while the page is loading or in an iframe. - // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable. - var activeElement; - try { - activeElement = document.activeElement; - } catch(e) { - activeElement = document.body || null; - } - while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement) - { activeElement = activeElement.shadowRoot.activeElement; } - return activeElement - } - - function addClass(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; } - } - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) - { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } } - return b - } - - var selectInput = function(node) { node.select(); }; - if (ios) // Mobile Safari apparently has a bug where select() is broken. - { selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; } - else if (ie) // Suppress mysterious IE10 errors - { selectInput = function(node) { try { node.select(); } catch(_e) {} }; } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args)} - } - - function copyObj(obj, target, overwrite) { - if (!target) { target = {}; } - for (var prop in obj) - { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) - { target[prop] = obj[prop]; } } - return target - } - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - function countColumn(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) { end = string.length; } - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) - { return n + (end - i) } - n += nextTab - i; - n += tabSize - (n % tabSize); - i = nextTab + 1; - } - } - - var Delayed = function() { - this.id = null; - this.f = null; - this.time = 0; - this.handler = bind(this.onTimeout, this); - }; - Delayed.prototype.onTimeout = function (self) { - self.id = 0; - if (self.time <= +new Date) { - self.f(); - } else { - setTimeout(self.handler, self.time - +new Date); - } - }; - Delayed.prototype.set = function (ms, f) { - this.f = f; - var time = +new Date + ms; - if (!this.id || time < this.time) { - clearTimeout(this.id); - this.id = setTimeout(this.handler, ms); - this.time = time; - } - }; - - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - { if (array[i] == elt) { return i } } - return -1 - } - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = {toString: function(){return "CodeMirror.Pass"}}; - - // Reused option objects for setSelection & friends - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) { nextTab = string.length; } - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) - { return pos + Math.min(skipped, goal - col) } - col += nextTab - pos; - col += tabSize - (col % tabSize); - pos = nextTab + 1; - if (col >= goal) { return pos } - } - } - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - { spaceStrs.push(lst(spaceStrs) + " "); } - return spaceStrs[n] - } - - function lst(arr) { return arr[arr.length-1] } - - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); } - return out - } - - function insertSorted(array, value, score) { - var pos = 0, priority = score(value); - while (pos < array.length && score(array[pos]) <= priority) { pos++; } - array.splice(pos, 0, value); - } - - function nothing() {} - - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) { copyObj(props, inst); } - return inst - } - - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - function isWordCharBasic(ch) { - return /\w/.test(ch) || ch > "\x80" && - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)) - } - function isWordChar(ch, helper) { - if (!helper) { return isWordCharBasic(ch) } - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true } - return helper.test(ch) - } - - function isEmpty(obj) { - for (var n in obj) { if (obj.hasOwnProperty(n) && obj[n]) { return false } } - return true - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/fonts/browsers also treat other configurations - // of code points as a group. - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch) } - - // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range. - function skipExtendingChars(str, pos, dir) { - while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; } - return pos - } - - // Returns the value from the range [`from`; `to`] that satisfies - // `pred` and is closest to `from`. Assumes that at least `to` - // satisfies `pred`. Supports `from` being greater than `to`. - function findFirst(pred, from, to) { - // At any point we are certain `to` satisfies `pred`, don't know - // whether `from` does. - var dir = from > to ? -1 : 1; - for (;;) { - if (from == to) { return from } - var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF); - if (mid == from) { return pred(mid) ? from : to } - if (pred(mid)) { to = mid; } - else { from = mid + dir; } - } - } - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) { return f(from, to, "ltr", 0) } - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr", i); - found = true; - } - } - if (!found) { f(from, to, "ltr"); } - } - - var bidiOther = null; - function getBidiPartAt(order, ch, sticky) { - var found; - bidiOther = null; - for (var i = 0; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < ch && cur.to > ch) { return i } - if (cur.to == ch) { - if (cur.from != cur.to && sticky == "before") { found = i; } - else { bidiOther = i; } - } - if (cur.from == ch) { - if (cur.from != cur.to && sticky != "before") { found = i; } - else { bidiOther = i; } - } - } - return found != null ? found : bidiOther - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6f9 - var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111"; - function charType(code) { - if (code <= 0xf7) { return lowTypes.charAt(code) } - else if (0x590 <= code && code <= 0x5f4) { return "R" } - else if (0x600 <= code && code <= 0x6f9) { return arabicTypes.charAt(code - 0x600) } - else if (0x6ee <= code && code <= 0x8ac) { return "r" } - else if (0x2000 <= code && code <= 0x200b) { return "w" } - else if (code == 0x200c) { return "b" } - else { return "L" } - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - return function(str, direction) { - var outerType = direction == "ltr" ? "L" : "R"; - - if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false } - var len = str.length, types = []; - for (var i = 0; i < len; ++i) - { types.push(charType(str.charCodeAt(i))); } - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i$1 = 0, prev = outerType; i$1 < len; ++i$1) { - var type = types[i$1]; - if (type == "m") { types[i$1] = prev; } - else { prev = type; } - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i$2 = 0, cur = outerType; i$2 < len; ++i$2) { - var type$1 = types[i$2]; - if (type$1 == "1" && cur == "r") { types[i$2] = "n"; } - else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "R"; } } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) { - var type$2 = types[i$3]; - if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; } - else if (type$2 == "," && prev$1 == types[i$3+1] && - (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; } - prev$1 = type$2; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i$4 = 0; i$4 < len; ++i$4) { - var type$3 = types[i$4]; - if (type$3 == ",") { types[i$4] = "N"; } - else if (type$3 == "%") { - var end = (void 0); - for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; - for (var j = i$4; j < end; ++j) { types[j] = replace; } - i$4 = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) { - var type$4 = types[i$5]; - if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; } - else if (isStrong.test(type$4)) { cur$1 = type$4; } - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i$6 = 0; i$6 < len; ++i$6) { - if (isNeutral.test(types[i$6])) { - var end$1 = (void 0); - for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {} - var before = (i$6 ? types[i$6-1] : outerType) == "L"; - var after = (end$1 < len ? types[end$1] : outerType) == "L"; - var replace$1 = before == after ? (before ? "L" : "R") : outerType; - for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; } - i$6 = end$1 - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i$7 = 0; i$7 < len;) { - if (countsAsLeft.test(types[i$7])) { - var start = i$7; - for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {} - order.push(new BidiSpan(0, start, i$7)); - } else { - var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0; - for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {} - for (var j$2 = pos; j$2 < i$7;) { - if (countsAsNum.test(types[j$2])) { - if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; } - var nstart = j$2; - for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {} - order.splice(at, 0, new BidiSpan(2, nstart, j$2)); - at += isRTL; - pos = j$2; - } else { ++j$2; } - } - if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); } - } - } - if (direction == "ltr") { - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - } - - return direction == "rtl" ? order.reverse() : order - } - })(); - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line, direction) { - var order = line.order; - if (order == null) { order = line.order = bidiOrdering(line.text, direction); } - return order - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var noHandlers = []; - - var on = function(emitter, type, f) { - if (emitter.addEventListener) { - emitter.addEventListener(type, f, false); - } else if (emitter.attachEvent) { - emitter.attachEvent("on" + type, f); - } else { - var map$$1 = emitter._handlers || (emitter._handlers = {}); - map$$1[type] = (map$$1[type] || noHandlers).concat(f); - } - }; - - function getHandlers(emitter, type) { - return emitter._handlers && emitter._handlers[type] || noHandlers - } - - function off(emitter, type, f) { - if (emitter.removeEventListener) { - emitter.removeEventListener(type, f, false); - } else if (emitter.detachEvent) { - emitter.detachEvent("on" + type, f); - } else { - var map$$1 = emitter._handlers, arr = map$$1 && map$$1[type]; - if (arr) { - var index = indexOf(arr, f); - if (index > -1) - { map$$1[type] = arr.slice(0, index).concat(arr.slice(index + 1)); } - } - } - } - - function signal(emitter, type /*, values...*/) { - var handlers = getHandlers(emitter, type); - if (!handlers.length) { return } - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); } - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") - { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; } - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore - } - - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) { return } - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1) - { set.push(arr[i]); } } - } - - function hasHandler(emitter, type) { - return getHandlers(emitter, type).length > 0 - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - function e_preventDefault(e) { - if (e.preventDefault) { e.preventDefault(); } - else { e.returnValue = false; } - } - function e_stopPropagation(e) { - if (e.stopPropagation) { e.stopPropagation(); } - else { e.cancelBubble = true; } - } - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false - } - function e_stop(e) {e_preventDefault(e); e_stopPropagation(e);} - - function e_target(e) {return e.target || e.srcElement} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) { b = 1; } - else if (e.button & 2) { b = 3; } - else if (e.button & 4) { b = 2; } - } - if (mac && e.ctrlKey && b == 1) { b = 3; } - return b - } - - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie && ie_version < 9) { return false } - var div = elt('div'); - return "draggable" in div || "dragDrop" in div - }(); - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - { zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); } - } - var node = zwspSupported ? elt("span", "\u200b") : - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) { return badBidiRects } - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - var r1 = range(txt, 1, 2).getBoundingClientRect(); - removeChildren(measure); - if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780) - return badBidiRects = (r1.right - r0.right < 3) - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLinesAuto = "\n\nb".split(/\n/).length != 3 ? function (string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) { nl = string.length; } - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result - } : function (string) { return string.split(/\r\n?|\n/); }; - - var hasSelection = window.getSelection ? function (te) { - try { return te.selectionStart != te.selectionEnd } - catch(e) { return false } - } : function (te) { - var range$$1; - try {range$$1 = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range$$1 || range$$1.parentElement() != te) { return false } - return range$$1.compareEndPoints("StartToEnd", range$$1) != 0 - }; - - var hasCopyEvent = (function () { - var e = elt("div"); - if ("oncopy" in e) { return true } - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function" - })(); - - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) { return badZoomedRects } - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1 - } - - // Known modes, by name and by MIME - var modes = {}, mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - function defineMode(name, mode) { - if (arguments.length > 2) - { mode.dependencies = Array.prototype.slice.call(arguments, 2); } - modes[name] = mode; - } - - function defineMIME(mime, spec) { - mimeModes[mime] = spec; - } - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - function resolveMode(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") { found = {name: found}; } - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return resolveMode("application/xml") - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) { - return resolveMode("application/json") - } - if (typeof spec == "string") { return {name: spec} } - else { return spec || {name: "null"} } - } - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - function getMode(options, spec) { - spec = resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) { return getMode(options, "text/plain") } - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) { continue } - if (modeObj.hasOwnProperty(prop)) { modeObj["_" + prop] = modeObj[prop]; } - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) { modeObj.helperType = spec.helperType; } - if (spec.modeProps) { for (var prop$1 in spec.modeProps) - { modeObj[prop$1] = spec.modeProps[prop$1]; } } - - return modeObj - } - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = {}; - function extendMode(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - } - - function copyState(mode, state) { - if (state === true) { return state } - if (mode.copyState) { return mode.copyState(state) } - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) { val = val.concat([]); } - nstate[n] = val; - } - return nstate - } - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - function innerMode(mode, state) { - var info; - while (mode.innerMode) { - info = mode.innerMode(state); - if (!info || info.mode == mode) { break } - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state} - } - - function startState(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true - } - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = function(string, tabSize, lineOracle) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - this.lineOracle = lineOracle; - }; - - StringStream.prototype.eol = function () {return this.pos >= this.string.length}; - StringStream.prototype.sol = function () {return this.pos == this.lineStart}; - StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined}; - StringStream.prototype.next = function () { - if (this.pos < this.string.length) - { return this.string.charAt(this.pos++) } - }; - StringStream.prototype.eat = function (match) { - var ch = this.string.charAt(this.pos); - var ok; - if (typeof match == "string") { ok = ch == match; } - else { ok = ch && (match.test ? match.test(ch) : match(ch)); } - if (ok) {++this.pos; return ch} - }; - StringStream.prototype.eatWhile = function (match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start - }; - StringStream.prototype.eatSpace = function () { - var this$1 = this; - - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this$1.pos; } - return this.pos > start - }; - StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;}; - StringStream.prototype.skipTo = function (ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true} - }; - StringStream.prototype.backUp = function (n) {this.pos -= n;}; - StringStream.prototype.column = function () { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) - }; - StringStream.prototype.indentation = function () { - return countColumn(this.string, null, this.tabSize) - - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0) - }; - StringStream.prototype.match = function (pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function (str) { return caseInsensitive ? str.toLowerCase() : str; }; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) { this.pos += pattern.length; } - return true - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) { return null } - if (match && consume !== false) { this.pos += match[0].length; } - return match - } - }; - StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)}; - StringStream.prototype.hideFirstChars = function (n, inner) { - this.lineStart += n; - try { return inner() } - finally { this.lineStart -= n; } - }; - StringStream.prototype.lookAhead = function (n) { - var oracle = this.lineOracle; - return oracle && oracle.lookAhead(n) - }; - StringStream.prototype.baseToken = function () { - var oracle = this.lineOracle; - return oracle && oracle.baseToken(this.pos) - }; - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) { throw new Error("There is no line " + (n + doc.first) + " in the document.") } - var chunk = doc; - while (!chunk.lines) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break } - n -= sz; - } - } - return chunk.lines[n] - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function (line) { - var text = line.text; - if (n == end.line) { text = text.slice(0, end.ch); } - if (n == start.line) { text = text.slice(start.ch); } - out.push(text); - ++n; - }); - return out - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to) { - var out = []; - doc.iter(from, to, function (line) { out.push(line.text); }); // iter aborts when callback returns truthy value - return out - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) { for (var n = line; n; n = n.parent) { n.height += diff; } } - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) { return null } - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) { break } - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i$1 = 0; i$1 < chunk.children.length; ++i$1) { - var child = chunk.children[i$1], ch = child.height; - if (h < ch) { chunk = child; continue outer } - h -= ch; - n += child.chunkSize(); - } - return n - } while (!chunk.lines) - var i = 0; - for (; i < chunk.lines.length; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) { break } - h -= lh; - } - return n + i - } - - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size} - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)) - } - - // A Pos instance represents a position within the text. - function Pos(line, ch, sticky) { - if ( sticky === void 0 ) sticky = null; - - if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) } - this.line = line; - this.ch = ch; - this.sticky = sticky; - } - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - function cmp(a, b) { return a.line - b.line || a.ch - b.ch } - - function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 } - - function copyPos(x) {return Pos(x.line, x.ch)} - function maxPos(a, b) { return cmp(a, b) < 0 ? b : a } - function minPos(a, b) { return cmp(a, b) < 0 ? a : b } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1))} - function clipPos(doc, pos) { - if (pos.line < doc.first) { return Pos(doc.first, 0) } - var last = doc.first + doc.size - 1; - if (pos.line > last) { return Pos(last, getLine(doc, last).text.length) } - return clipToLen(pos, getLine(doc, pos.line).text.length) - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) { return Pos(pos.line, linelen) } - else if (ch < 0) { return Pos(pos.line, 0) } - else { return pos } - } - function clipPosArray(doc, array) { - var out = []; - for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); } - return out - } - - var SavedContext = function(state, lookAhead) { - this.state = state; - this.lookAhead = lookAhead; - }; - - var Context = function(doc, state, line, lookAhead) { - this.state = state; - this.doc = doc; - this.line = line; - this.maxLookAhead = lookAhead || 0; - this.baseTokens = null; - this.baseTokenPos = 1; - }; - - Context.prototype.lookAhead = function (n) { - var line = this.doc.getLine(this.line + n); - if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; } - return line - }; - - Context.prototype.baseToken = function (n) { - var this$1 = this; - - if (!this.baseTokens) { return null } - while (this.baseTokens[this.baseTokenPos] <= n) - { this$1.baseTokenPos += 2; } - var type = this.baseTokens[this.baseTokenPos + 1]; - return {type: type && type.replace(/( |^)overlay .*/, ""), - size: this.baseTokens[this.baseTokenPos] - n} - }; - - Context.prototype.nextLine = function () { - this.line++; - if (this.maxLookAhead > 0) { this.maxLookAhead--; } - }; - - Context.fromSaved = function (doc, saved, line) { - if (saved instanceof SavedContext) - { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) } - else - { return new Context(doc, copyState(doc.mode, saved), line) } - }; - - Context.prototype.save = function (copy) { - var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state; - return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state - }; - - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, context, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); }, - lineClasses, forceToEnd); - var state = context.state; - - // Run overlays, adjust style array. - var loop = function ( o ) { - context.baseTokens = st; - var overlay = cm.state.overlays[o], i = 1, at = 0; - context.state = true; - runMode(cm, line.text, overlay.mode, context, function (end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - { st.splice(i, 1, end, st[i+1], i_end); } - i += 2; - at = Math.min(end, i_end); - } - if (!style) { return } - if (overlay.opaque) { - st.splice(start, i - start, end, "overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = (cur ? cur + " " : "") + "overlay " + style; - } - } - }, lineClasses); - context.state = state; - context.baseTokens = null; - context.baseTokenPos = 1; - }; - - for (var o = 0; o < cm.state.overlays.length; ++o) loop( o ); - - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null} - } - - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var context = getContextBefore(cm, lineNo(line)); - var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state); - var result = highlightLine(cm, line, context); - if (resetState) { context.state = resetState; } - line.stateAfter = context.save(!resetState); - line.styles = result.styles; - if (result.classes) { line.styleClasses = result.classes; } - else if (line.styleClasses) { line.styleClasses = null; } - if (updateFrontier === cm.doc.highlightFrontier) - { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); } - } - return line.styles - } - - function getContextBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) { return new Context(doc, true, n) } - var start = findStartLine(cm, n, precise); - var saved = start > doc.first && getLine(doc, start - 1).stateAfter; - var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start); - - doc.iter(start, n, function (line) { - processLine(cm, line.text, context); - var pos = context.line; - line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null; - context.nextLine(); - }); - if (precise) { doc.modeFrontier = context.line; } - return context - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, context, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize, context); - stream.start = stream.pos = startAt || 0; - if (text == "") { callBlankLine(mode, context.state); } - while (!stream.eol()) { - readToken(mode, stream, context.state); - stream.start = stream.pos; - } - } - - function callBlankLine(mode, state) { - if (mode.blankLine) { return mode.blankLine(state) } - if (!mode.innerMode) { return } - var inner = innerMode(mode, state); - if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) } - } - - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) { inner[0] = innerMode(mode, state).mode; } - var style = mode.token(stream, state); - if (stream.pos > stream.start) { return style } - } - throw new Error("Mode " + mode.name + " failed to advance stream.") - } - - var Token = function(stream, type, state) { - this.start = stream.start; this.end = stream.pos; - this.string = stream.current(); - this.type = type || null; - this.state = state; - }; - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - var doc = cm.doc, mode = doc.mode, style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize, context), tokens; - if (asArray) { tokens = []; } - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, context.state); - if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); } - } - return asArray ? tokens : new Token(stream, style, context.state) - } - - function extractLineClasses(type, output) { - if (type) { for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) { break } - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop] == null) - { output[prop] = lineClass[2]; } - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) - { output[prop] += " " + lineClass[2]; } - } } - return type - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, context, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) { flattenSpans = cm.options.flattenSpans; } - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize, context), style; - var inner = cm.options.addModeClass && [null]; - if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); } - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) { processLine(cm, text, context, stream.pos); } - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) { style = "m-" + (style ? mName + " " + style : mName); } - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 5000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 - // characters, and returns inaccurate measurements in nodes - // starting around 5000 chars. - var pos = Math.min(stream.pos, curStart + 5000); - f(pos, curStyle); - curStart = pos; - } - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) { return doc.first } - var line = getLine(doc, search - 1), after = line.stateAfter; - if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier)) - { return search } - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline - } - - function retreatFrontier(doc, n) { - doc.modeFrontier = Math.min(doc.modeFrontier, n); - if (doc.highlightFrontier < n - 10) { return } - var start = doc.first; - for (var line = n - 1; line > start; line--) { - var saved = getLine(doc, line).stateAfter; - // change is on 3 - // state on line 1 looked ahead 2 -- so saw 3 - // test 1 + 2 < 3 should cover this - if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) { - start = line + 1; - break - } - } - doc.highlightFrontier = Math.min(doc.highlightFrontier, start); - } - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - function seeReadOnlySpans() { - sawReadOnlySpans = true; - } - - function seeCollapsedSpans() { - sawCollapsedSpans = true; - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) { for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) { return span } - } } - } - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - var r; - for (var i = 0; i < spans.length; ++i) - { if (spans[i] != span) { (r || (r = [])).push(spans[i]); } } - return r - } - // Add a span to a line. - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - var nw; - if (old) { for (var i = 0; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh) - ;(nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } } - return nw - } - function markedSpansAfter(old, endCh, isInsert) { - var nw; - if (old) { for (var i = 0; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh) - ;(nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, - span.to == null ? null : span.to - endCh)); - } - } } - return nw - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) { return null } - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) { return null } - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) { span.to = startCh; } - else if (sameLine) { span.to = found.to == null ? null : found.to + offset; } - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i$1 = 0; i$1 < last.length; ++i$1) { - var span$1 = last[i$1]; - if (span$1.to != null) { span$1.to += offset; } - if (span$1.from == null) { - var found$1 = getMarkedSpanFor(first, span$1.marker); - if (!found$1) { - span$1.from = offset; - if (sameLine) { (first || (first = [])).push(span$1); } - } - } else { - span$1.from += offset; - if (sameLine) { (first || (first = [])).push(span$1); } - } - } - } - // Make sure we didn't create any zero-length spans - if (first) { first = clearEmptySpans(first); } - if (last && last != first) { last = clearEmptySpans(last); } - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - { for (var i$2 = 0; i$2 < first.length; ++i$2) - { if (first[i$2].to == null) - { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } } - for (var i$3 = 0; i$3 < gap; ++i$3) - { newMarkers.push(gapMarkers); } - newMarkers.push(last); - } - return newMarkers - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) - { spans.splice(i--, 1); } - } - if (!spans.length) { return null } - return spans - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function (line) { - if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - { (markers || (markers = [])).push(mark); } - } } - }); - if (!markers) { return null } - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) { continue } - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) - { newParts.push({from: p.from, to: m.from}); } - if (dto > 0 || !mk.inclusiveRight && !dto) - { newParts.push({from: m.to, to: p.to}); } - parts.splice.apply(parts, newParts); - j += newParts.length - 3; - } - } - return parts - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) { return } - for (var i = 0; i < spans.length; ++i) - { spans[i].marker.detachLine(line); } - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) { return } - for (var i = 0; i < spans.length; ++i) - { spans[i].marker.attachLine(line); } - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0 } - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0 } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) { return lenDiff } - var aPos = a.find(), bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) { return -fromCmp } - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) { return toCmp } - return b.id - a.id - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) - { found = sp.marker; } - } } - return found - } - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true) } - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false) } - - function collapsedSpanAround(line, ch) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) { for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; } - } } - return found - } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo$$1, from, to, marker) { - var line = getLine(doc, lineNo$$1); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) { continue } - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) { continue } - if (fromCmp <= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) || - fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 0)) - { return true } - } } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - { line = merged.find(-1, true).line; } - return line - } - - function visualLineEnd(line) { - var merged; - while (merged = collapsedSpanAtEnd(line)) - { line = merged.find(1, true).line; } - return line - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line - ;(lines || (lines = [])).push(line); - } - return lines - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), vis = visualLine(line); - if (line == vis) { return lineN } - return lineNo(vis) - } - - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) { return lineN } - var line = getLine(doc, lineN), merged; - if (!lineIsHidden(doc, line)) { return lineN } - while (merged = collapsedSpanAtEnd(line)) - { line = merged.find(1, true).line; } - return lineNo(line) + 1 - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) { for (var sp = (void 0), i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) { continue } - if (sp.from == null) { return true } - if (sp.marker.widgetNode) { continue } - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - { return true } - } } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)) - } - if (span.marker.inclusiveRight && span.to == line.text.length) - { return true } - for (var sp = (void 0), i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && - (sp.to == null || sp.to != span.from) && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) { return true } - } - } - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) { break } - else { h += line.height; } - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i$1 = 0; i$1 < p.children.length; ++i$1) { - var cur = p.children[i$1]; - if (cur == chunk) { break } - else { h += cur.height; } - } - } - return h - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) { return 0 } - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found$1 = merged.find(0, true); - len -= cur.text.length - found$1.from.ch; - cur = found$1.to.line; - len += cur.text.length - found$1.to.ch; - } - return len - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function (line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - - Line.prototype.lineNo = function () { return lineNo(this) }; - eventMixin(Line); - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) { line.stateAfter = null; } - if (line.styles) { line.styles = null; } - if (line.order != null) { line.order = null; } - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) { updateLineHeight(line, estHeight); } - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) { return null } - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || - (cache[style] = style.replace(/\S+/g, "cm-$&")) - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = eltP("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content, - col: 0, pos: 0, cm: cm, - trailingSpace: false, - splitSpaces: cm.getOption("lineWrapping")}; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, order = (void 0); - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction))) - { builder.addToken = buildTokenBadBidi(builder.addToken, order); } - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) - { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); } - if (line.styleClasses.textClass) - { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); } - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) - { builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); } - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map) - ;(lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit) { - var last = builder.content.lastChild; - if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab"))) - { builder.content.className = "cm-tab-wrap-hack"; } - } - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); } - - return builder - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, css, attributes) { - if (!text) { return } - var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text; - var special = builder.cm.state.specialChars, mustWrap = false; - var content; - if (!special.test(text)) { - builder.col += text.length; - content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) { mustWrap = true; } - builder.pos += text.length; - } else { - content = document.createDocumentFragment(); - var pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) { content.appendChild(elt("span", [txt])); } - else { content.appendChild(txt); } - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) { break } - pos += skipped + 1; - var txt$1 = (void 0); - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt$1.setAttribute("role", "presentation"); - txt$1.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else if (m[0] == "\r" || m[0] == "\n") { - txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar")); - txt$1.setAttribute("cm-text", m[0]); - builder.col += 1; - } else { - txt$1 = builder.cm.options.specialCharPlaceholder(m[0]); - txt$1.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); } - else { content.appendChild(txt$1); } - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt$1); - builder.pos++; - } - } - builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32; - if (style || startStyle || endStyle || mustWrap || css) { - var fullStyle = style || ""; - if (startStyle) { fullStyle += startStyle; } - if (endStyle) { fullStyle += endStyle; } - var token = elt("span", [content], fullStyle, css); - if (attributes) { - for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class") - { token.setAttribute(attr, attributes[attr]); } } - } - return builder.content.appendChild(token) - } - builder.content.appendChild(content); - } - - // Change some spaces to NBSP to prevent the browser from collapsing - // trailing spaces at the end of a line when rendering text (issue #1362). - function splitSpaces(text, trailingBefore) { - if (text.length > 1 && !/ /.test(text)) { return text } - var spaceBefore = trailingBefore, result = ""; - for (var i = 0; i < text.length; i++) { - var ch = text.charAt(i); - if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32)) - { ch = "\u00a0"; } - result += ch; - spaceBefore = ch == " "; - } - return result - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function (builder, text, style, startStyle, endStyle, css, attributes) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - var part = (void 0); - for (var i = 0; i < order.length; i++) { - part = order[i]; - if (part.to > start && part.from <= start) { break } - } - if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) } - inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - } - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) { builder.map.push(builder.pos, builder.pos + size, widget); } - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) - { widget = builder.content.appendChild(document.createElement("span")); } - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - builder.trailingSpace = false; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i$1 = 1; i$1 < styles.length; i$1+=2) - { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); } - return - } - - var len = allText.length, pos = 0, i = 1, text = "", style, css; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = css = ""; - attributes = null; - collapsed = null; nextChange = Infinity; - var foundBookmarks = [], endStyles = (void 0); - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) { spanStyle += " " + m.className; } - if (m.css) { css = (css ? css + ";" : "") + m.css; } - if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; } - if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); } - // support for the old title property - // https://github.com/codemirror/CodeMirror/pull/5673 - if (m.title) { (attributes || (attributes = {})).title = m.title; } - if (m.attributes) { - for (var attr in m.attributes) - { (attributes || (attributes = {}))[attr] = m.attributes[attr]; } - } - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) - { collapsed = sp; } - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2) - { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } } - - if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2) - { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) { return } - if (collapsed.to == pos) { collapsed = false; } - } - } - if (pos >= len) { break } - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", css, attributes); - } - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break} - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder.cm.options); - } - } - } - - - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array - } - - var operationGroup = null; - - function pushOperation(op) { - if (operationGroup) { - operationGroup.ops.push(op); - } else { - op.ownsGroup = operationGroup = { - ops: [op], - delayedCallbacks: [] - }; - } - } - - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - var callbacks = group.delayedCallbacks, i = 0; - do { - for (; i < callbacks.length; i++) - { callbacks[i].call(null); } - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) - { while (op.cursorActivityCalled < op.cursorActivityHandlers.length) - { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } } - } - } while (i < callbacks.length) - } - - function finishOperation(op, endCb) { - var group = op.ownsGroup; - if (!group) { return } - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - endCb(group); - } - } - - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = getHandlers(emitter, type); - if (!arr.length) { return } - var args = Array.prototype.slice.call(arguments, 2), list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - var loop = function ( i ) { - list.push(function () { return arr[i].apply(null, args); }); - }; - - for (var i = 0; i < arr.length; ++i) - loop( i ); - } - - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) { delayed[i](); } - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") { updateLineText(cm, lineView); } - else if (type == "gutter") { updateLineGutter(cm, lineView, lineN, dims); } - else if (type == "class") { updateLineClasses(cm, lineView); } - else if (type == "widget") { updateLineWidgets(cm, lineView, dims); } - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) - { lineView.text.parentNode.replaceChild(lineView.node, lineView.text); } - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) { lineView.node.style.zIndex = 2; } - } - return lineView.node - } - - function updateLineBackground(cm, lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) { cls += " CodeMirror-linebackground"; } - if (lineView.background) { - if (cls) { lineView.background.className = cls; } - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - cm.display.input.setUneditable(lineView.background); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built - } - return buildLineContent(cm, lineView) - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) { lineView.node = built.pre; } - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(cm, lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - - function updateLineClasses(cm, lineView) { - updateLineBackground(cm, lineView); - if (lineView.line.wrapClass) - { ensureLineWrapped(lineView).className = lineView.line.wrapClass; } - else if (lineView.node != lineView.text) - { lineView.node.className = ""; } - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - if (lineView.gutterBackground) { - lineView.node.removeChild(lineView.gutterBackground); - lineView.gutterBackground = null; - } - if (lineView.line.gutterClass) { - var wrap = ensureLineWrapped(lineView); - lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass, - ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px")); - cm.display.input.setUneditable(lineView.gutterBackground); - wrap.insertBefore(lineView.gutterBackground, lineView.text); - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap$1 = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px")); - cm.display.input.setUneditable(gutterWrap); - wrap$1.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) - { gutterWrap.className += " " + lineView.line.gutterClass; } - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) - { lineView.lineNumber = gutterWrap.appendChild( - elt("div", lineNumberFor(cm.options, lineN), - "CodeMirror-linenumber CodeMirror-gutter-elt", - ("left: " + (dims.gutterLeft["CodeMirror-linenumbers"]) + "px; width: " + (cm.display.lineNumInnerWidth) + "px"))); } - if (markers) { for (var k = 0; k < cm.display.gutterSpecs.length; ++k) { - var id = cm.display.gutterSpecs[k].className, found = markers.hasOwnProperty(id) && markers[id]; - if (found) - { gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", - ("left: " + (dims.gutterLeft[id]) + "px; width: " + (dims.gutterWidth[id]) + "px"))); } - } } - } - } - - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) { lineView.alignable = null; } - var isWidget = classTest("CodeMirror-linewidget"); - for (var node = lineView.node.firstChild, next = (void 0); node; node = next) { - next = node.nextSibling; - if (isWidget.test(node.className)) { lineView.node.removeChild(node); } - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) { lineView.bgClass = built.bgClass; } - if (built.textClass) { lineView.textClass = built.textClass; } - - updateLineClasses(cm, lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node - } - - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) - { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } } - } - - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) { return } - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget" + (widget.className ? " " + widget.className : "")); - if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); } - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) - { wrap.insertBefore(node, lineView.gutter || lineView.text); } - else - { wrap.appendChild(node); } - signalLater(widget, "redraw"); - } - } - - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) { node.style.marginLeft = -dims.gutterTotalWidth + "px"; } - } - } - - function widgetHeight(widget) { - if (widget.height != null) { return widget.height } - var cm = widget.doc.cm; - if (!cm) { return 0 } - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) - { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; } - if (widget.noHScroll) - { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; } - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.parentNode.offsetHeight - } - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || - (n.parentNode == display.sizer && n != display.mover)) - { return true } - } - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight} - function paddingH(display) { - if (display.cachedPaddingH) { return display.cachedPaddingH } - var e = removeChildrenAndAdd(display.measure, elt("pre", "x", "CodeMirror-line-like")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; - if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; } - return data - } - - function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) - { heights.push((cur.bottom + next.top) / 2 - rect.top); } - } - } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) - { return {map: lineView.measure.map, cache: lineView.measure.cache} } - for (var i = 0; i < lineView.rest.length; i++) - { if (lineView.rest[i] == line) - { return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]} } } - for (var i$1 = 0; i$1 < lineView.rest.length; i$1++) - { if (lineNo(lineView.rest[i$1]) > lineN) - { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], before: true} } } - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias) - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) - { return cm.display.view[findViewIndex(cm, lineN)] } - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) - { return ext } - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) { - view = null; - } else if (view && view.changes) { - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - cm.curOp.forceUpdate = true; - } - if (!view) - { view = updateExternalMeasurement(cm, line); } - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false - } - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) { ch = -1; } - var key = ch + (bias || ""), found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) - { prepared.rect = prepared.view.text.getBoundingClientRect(); } - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) { prepared.cache[key] = found; } - } - return {left: found.left, right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom} - } - - var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; - - function nodeAndOffsetInLineMap(map$$1, ch, bias) { - var node, start, end, collapse, mStart, mEnd; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map$$1.length; i += 3) { - mStart = map$$1[i]; - mEnd = map$$1[i + 1]; - if (ch < mStart) { - start = 0; end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map$$1.length - 3 || ch == mEnd && map$$1[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) { collapse = "right"; } - } - if (start != null) { - node = map$$1[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) - { collapse = bias; } - if (bias == "left" && start == 0) - { while (i && map$$1[i - 2] == map$$1[i - 3] && map$$1[i - 1].insertLeft) { - node = map$$1[(i -= 3) + 2]; - collapse = "left"; - } } - if (bias == "right" && start == mEnd - mStart) - { while (i < map$$1.length - 3 && map$$1[i + 3] == map$$1[i + 4] && !map$$1[i + 5].insertLeft) { - node = map$$1[(i += 3) + 2]; - collapse = "right"; - } } - break - } - } - return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd} - } - - function getUsefulRect(rects, bias) { - var rect = nullRect; - if (bias == "left") { for (var i = 0; i < rects.length; i++) { - if ((rect = rects[i]).left != rect.right) { break } - } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) { - if ((rect = rects[i$1]).left != rect.right) { break } - } } - return rect - } - - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, start = place.start, end = place.end, collapse = place.collapse; - - var rect; - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. - for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; } - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; } - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) - { rect = node.parentNode.getBoundingClientRect(); } - else - { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); } - if (rect.left || rect.right || start == 0) { break } - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); } - } else { // If it is a widget, simply get the box for the whole widget. - if (start > 0) { collapse = bias = "right"; } - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) - { rect = rects[bias == "right" ? rects.length - 1 : 0]; } - else - { rect = node.getBoundingClientRect(); } - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) - { rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; } - else - { rect = nullRect; } - } - - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - var i = 0; - for (; i < heights.length - 1; i++) - { if (mid < heights[i]) { break } } - var top = i ? heights[i - 1] : 0, bot = heights[i]; - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, bottom: bot}; - if (!rect.left && !rect.right) { result.bogus = true; } - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } - - return result - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) - { return rect } - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return {left: rect.left * scaleX, right: rect.right * scaleX, - top: rect.top * scaleY, bottom: rect.bottom * scaleY} - } - - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++) - { lineView.measure.caches[i] = {}; } } - } - } - - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i = 0; i < cm.display.view.length; i++) - { clearLineMeasurementCacheFor(cm.display.view[i]); } - } - - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) { cm.display.maxLineChanged = true; } - cm.display.lineNumChars = null; - } - - function pageScrollX() { - // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206 - // which causes page_Offset and bounding client rects to use - // different reference viewports and invalidate our calculations. - if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) } - return window.pageXOffset || (document.documentElement || document.body).scrollLeft - } - function pageScrollY() { - if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) } - return window.pageYOffset || (document.documentElement || document.body).scrollTop - } - - function widgetTopHeight(lineObj) { - var height = 0; - if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above) - { height += widgetHeight(lineObj.widgets[i]); } } } - return height - } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"./null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) { - if (!includeWidgets) { - var height = widgetTopHeight(lineObj); - rect.top += height; rect.bottom += height; - } - if (context == "line") { return rect } - if (!context) { context = "local"; } - var yOff = heightAtLine(lineObj); - if (context == "local") { yOff += paddingTop(cm.display); } - else { yOff -= cm.display.viewOffset; } - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"./null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") { return coords } - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top} - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) { lineObj = getLine(cm.doc, pos.line); } - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context) - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - // A cursor Pos(line, char, "before") is on the same visual line as `char - 1` - // and after `char - 1` in writing order of `char - 1` - // A cursor Pos(line, char, "after") is on the same visual line as `char` - // and before `char` in writing order of `char` - // Examples (upper-case letters are RTL, lower-case are LTR): - // Pos(0, 1, ...) - // before after - // ab a|b a|b - // aB a|B aB| - // Ab |Ab A|b - // AB B|A B|A - // Every position after the last character on a line is considered to stick - // to the last character on the line. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) { m.left = m.right; } else { m.right = m.left; } - return intoCoordSystem(cm, lineObj, m, context) - } - var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky; - if (ch >= lineObj.text.length) { - ch = lineObj.text.length; - sticky = "before"; - } else if (ch <= 0) { - ch = 0; - sticky = "after"; - } - if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") } - - function getBidi(ch, partPos, invert) { - var part = order[partPos], right = part.level == 1; - return get(invert ? ch - 1 : ch, right != invert) - } - var partPos = getBidiPartAt(order, ch, sticky); - var other = bidiOther; - var val = getBidi(ch, partPos, sticky == "before"); - if (other != null) { val.other = getBidi(ch, other, sticky != "before"); } - return val - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0; - pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) { left = charWidth(cm.display) * pos.ch; } - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return {left: left, right: left, top: top, bottom: top + lineObj.height} - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, sticky, outside, xRel) { - var pos = Pos(line, ch, sticky); - pos.xRel = xRel; - if (outside) { pos.outside = outside; } - return pos - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) { return PosWithInfo(doc.first, 0, null, -1, -1) } - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineN > last) - { return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, null, 1, 1) } - if (x < 0) { x = 0; } - - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0)); - if (!collapsed) { return found } - var rangeEnd = collapsed.find(1); - if (rangeEnd.line == lineN) { return rangeEnd } - lineObj = getLine(doc, lineN = rangeEnd.line); - } - } - - function wrappedLineExtent(cm, lineObj, preparedMeasure, y) { - y -= widgetTopHeight(lineObj); - var end = lineObj.text.length; - var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0); - end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end); - return {begin: begin, end: end} - } - - function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) { - if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); } - var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top; - return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop) - } - - // Returns true if the given side of a box is after the given - // coordinates, in top-to-bottom, left-to-right order. - function boxIsAfter(box, x, y, left) { - return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x - } - - function coordsCharInner(cm, lineObj, lineNo$$1, x, y) { - // Move y into line-local coordinate space - y -= heightAtLine(lineObj); - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - // When directly calling `measureCharPrepared`, we have to adjust - // for the widgets at this line. - var widgetHeight$$1 = widgetTopHeight(lineObj); - var begin = 0, end = lineObj.text.length, ltr = true; - - var order = getOrder(lineObj, cm.doc.direction); - // If the line isn't plain left-to-right text, first figure out - // which bidi section the coordinates fall into. - if (order) { - var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart) - (cm, lineObj, lineNo$$1, preparedMeasure, order, x, y); - ltr = part.level != 1; - // The awkward -1 offsets are needed because findFirst (called - // on these below) will treat its first bound as inclusive, - // second as exclusive, but we want to actually address the - // characters in the part's range - begin = ltr ? part.from : part.to - 1; - end = ltr ? part.to : part.from - 1; - } - - // A binary search to find the first character whose bounding box - // starts after the coordinates. If we run across any whose box wrap - // the coordinates, store that. - var chAround = null, boxAround = null; - var ch = findFirst(function (ch) { - var box = measureCharPrepared(cm, preparedMeasure, ch); - box.top += widgetHeight$$1; box.bottom += widgetHeight$$1; - if (!boxIsAfter(box, x, y, false)) { return false } - if (box.top <= y && box.left <= x) { - chAround = ch; - boxAround = box; - } - return true - }, begin, end); - - var baseX, sticky, outside = false; - // If a box around the coordinates was found, use that - if (boxAround) { - // Distinguish coordinates nearer to the left or right side of the box - var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr; - ch = chAround + (atStart ? 0 : 1); - sticky = atStart ? "after" : "before"; - baseX = atLeft ? boxAround.left : boxAround.right; - } else { - // (Adjust for extended bound, if necessary.) - if (!ltr && (ch == end || ch == begin)) { ch++; } - // To determine which side to associate with, get the box to the - // left of the character and compare it's vertical position to the - // coordinates - sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" : - (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight$$1 <= y) == ltr ? - "after" : "before"; - // Now get accurate coordinates for this place, in order to get a - // base X position - var coords = cursorCoords(cm, Pos(lineNo$$1, ch, sticky), "line", lineObj, preparedMeasure); - baseX = coords.left; - outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0; - } - - ch = skipExtendingChars(lineObj.text, ch, 1); - return PosWithInfo(lineNo$$1, ch, sticky, outside, x - baseX) - } - - function coordsBidiPart(cm, lineObj, lineNo$$1, preparedMeasure, order, x, y) { - // Bidi parts are sorted left-to-right, and in a non-line-wrapping - // situation, we can take this ordering to correspond to the visual - // ordering. This finds the first part whose end is after the given - // coordinates. - var index = findFirst(function (i) { - var part = order[i], ltr = part.level != 1; - return boxIsAfter(cursorCoords(cm, Pos(lineNo$$1, ltr ? part.to : part.from, ltr ? "before" : "after"), - "line", lineObj, preparedMeasure), x, y, true) - }, 0, order.length - 1); - var part = order[index]; - // If this isn't the first part, the part's start is also after - // the coordinates, and the coordinates aren't on the same line as - // that start, move one part back. - if (index > 0) { - var ltr = part.level != 1; - var start = cursorCoords(cm, Pos(lineNo$$1, ltr ? part.from : part.to, ltr ? "after" : "before"), - "line", lineObj, preparedMeasure); - if (boxIsAfter(start, x, y, true) && start.top > y) - { part = order[index - 1]; } - } - return part - } - - function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) { - // In a wrapped line, rtl text on wrapping boundaries can do things - // that don't correspond to the ordering in our `order` array at - // all, so a binary search doesn't work, and we want to return a - // part that only spans one line so that the binary search in - // coordsCharInner is safe. As such, we first find the extent of the - // wrapped line, and then do a flat search in which we discard any - // spans that aren't on the line. - var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y); - var begin = ref.begin; - var end = ref.end; - if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; } - var part = null, closestDist = null; - for (var i = 0; i < order.length; i++) { - var p = order[i]; - if (p.from >= end || p.to <= begin) { continue } - var ltr = p.level != 1; - var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right; - // Weigh against spans ending before this, so that they are only - // picked if nothing ends after - var dist = endX < x ? x - endX + 1e9 : endX - x; - if (!part || closestDist > dist) { - part = p; - closestDist = dist; - } - } - if (!part) { part = order[order.length - 1]; } - // Clip the part to the wrapped line. - if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; } - if (part.to > end) { part = {from: part.from, to: end, level: part.level}; } - return part - } - - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) { return display.cachedTextHeight } - if (measureText == null) { - measureText = elt("pre", null, "CodeMirror-line-like"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) { display.cachedTextHeight = height; } - removeChildren(display.measure); - return height || 1 - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) { return display.cachedCharWidth } - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor], "CodeMirror-line-like"); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; - if (width > 2) { display.cachedCharWidth = width; } - return width || 10 - } - - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - var id = cm.display.gutterSpecs[i].className; - left[id] = n.offsetLeft + n.clientLeft + gutterLeft; - width[id] = n.clientWidth; - } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth} - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function (line) { - if (lineIsHidden(cm.doc, line)) { return 0 } - - var widgetsHeight = 0; - if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].height) { widgetsHeight += line.widgets[i].height; } - } } - - if (wrapping) - { return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th } - else - { return widgetsHeight + th } - } - } - - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function (line) { - var estHeight = est(line); - if (estHeight != line.height) { updateLineHeight(line, estHeight); } - }); - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") { return null } - - var x, y, space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX - space.left; y = e.clientY - space.top; } - catch (e) { return null } - var coords = coordsChar(cm, x, y), line; - if (forRect && coords.xRel > 0 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) { return null } - n -= cm.display.viewFrom; - if (n < 0) { return null } - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) { return i } - } - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) { from = cm.doc.first; } - if (to == null) { to = cm.doc.first + cm.doc.size; } - if (!lendiff) { lendiff = 0; } - - var display = cm.display; - if (lendiff && to < display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers > from)) - { display.updateLineNumbers = from; } - - cm.curOp.viewChanged = true; - - if (from >= display.viewTo) { // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) - { resetView(cm); } - } else if (to <= display.viewFrom) { // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { // Bottom overlap - var cut$1 = viewCuttingPoint(cm, from, from, -1); - if (cut$1) { - display.view = display.view.slice(0, cut$1.index); - display.viewTo = cut$1.lineN; - } else { - resetView(cm); - } - } else { // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index) - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) - .concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - { ext.lineN += lendiff; } - else if (from < ext.lineN + ext.size) - { display.externalMeasured = null; } - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) - { display.externalMeasured = null; } - - if (line < display.viewFrom || line >= display.viewTo) { return } - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) { return } - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) { arr.push(type); } - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), diff, view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) - { return {index: index, lineN: newN} } - var n = cm.display.viewFrom; - for (var i = 0; i < index; i++) - { n += view[i].size; } - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) { return null } - diff = (n + view[index].size) - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) { return null } - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return {index: index, lineN: newN} - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) - { display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); } - else if (display.viewFrom < from) - { display.view = display.view.slice(findViewIndex(cm, from)); } - display.viewFrom = from; - if (display.viewTo < to) - { display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); } - else if (display.viewTo > to) - { display.view = display.view.slice(0, findViewIndex(cm, to)); } - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) { ++dirty; } - } - return dirty - } - - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - - function prepareSelection(cm, primary) { - if ( primary === void 0 ) primary = true; - - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (!primary && i == doc.sel.primIndex) { continue } - var range$$1 = doc.sel.ranges[i]; - if (range$$1.from().line >= cm.display.viewTo || range$$1.to().line < cm.display.viewFrom) { continue } - var collapsed = range$$1.empty(); - if (collapsed || cm.options.showCursorWhenSelecting) - { drawSelectionCursor(cm, range$$1.head, curFragment); } - if (!collapsed) - { drawSelectionRange(cm, range$$1, selFragment); } - } - return result - } - - // Draws a cursor for the given range - function drawSelectionCursor(cm, head, output) { - var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine); - - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } - } - - function cmpCoords(a, b) { return a.top - b.top || a.left - b.left } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range$$1, output) { - var display = cm.display, doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - var docLTR = doc.direction == "ltr"; - - function add(left, top, width, bottom) { - if (top < 0) { top = 0; } - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n height: " + (bottom - top) + "px"))); - } - - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias) - } - - function wrapX(pos, dir, side) { - var extent = wrappedLineExtentChar(cm, lineObj, null, pos); - var prop = (dir == "ltr") == (side == "after") ? "left" : "right"; - var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1); - return coords(ch, prop)[prop] - } - - var order = getOrder(lineObj, doc.direction); - iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) { - var ltr = dir == "ltr"; - var fromPos = coords(from, ltr ? "left" : "right"); - var toPos = coords(to - 1, ltr ? "right" : "left"); - - var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen; - var first = i == 0, last = !order || i == order.length - 1; - if (toPos.top - fromPos.top <= 3) { // Single line - var openLeft = (docLTR ? openStart : openEnd) && first; - var openRight = (docLTR ? openEnd : openStart) && last; - var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left; - var right = openRight ? rightSide : (ltr ? toPos : fromPos).right; - add(left, fromPos.top, right - left, fromPos.bottom); - } else { // Multiple lines - var topLeft, topRight, botLeft, botRight; - if (ltr) { - topLeft = docLTR && openStart && first ? leftSide : fromPos.left; - topRight = docLTR ? rightSide : wrapX(from, dir, "before"); - botLeft = docLTR ? leftSide : wrapX(to, dir, "after"); - botRight = docLTR && openEnd && last ? rightSide : toPos.right; - } else { - topLeft = !docLTR ? leftSide : wrapX(from, dir, "before"); - topRight = !docLTR && openStart && first ? rightSide : fromPos.right; - botLeft = !docLTR && openEnd && last ? leftSide : toPos.left; - botRight = !docLTR ? rightSide : wrapX(to, dir, "after"); - } - add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom); - if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); } - add(botLeft, toPos.top, botRight - botLeft, toPos.bottom); - } - - if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; } - if (cmpCoords(toPos, start) < 0) { start = toPos; } - if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; } - if (cmpCoords(toPos, end) < 0) { end = toPos; } - }); - return {start: start, end: end} - } - - var sFrom = range$$1.from(), sTo = range$$1.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) - { add(leftSide, leftEnd.bottom, null, rightStart.top); } - } - - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) { return } - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - { display.blinker = setInterval(function () { return display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; }, - cm.options.cursorBlinkRate); } - else if (cm.options.cursorBlinkRate < 0) - { display.cursorDiv.style.visibility = "hidden"; } - } - - function ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } - } - - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function () { if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } }, 100); - } - - function onFocus(cm, e) { - if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; } - - if (cm.options.readOnly == "nocursor") { return } - if (!cm.state.focused) { - signal(cm, "focus", cm, e); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm, e) { - if (cm.state.delayingBlurEvent) { return } - - if (cm.state.focused) { - signal(cm, "blur", cm, e); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150); - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], wrapping = cm.options.lineWrapping; - var height = (void 0), width = 0; - if (cur.hidden) { continue } - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - // Check that lines don't extend past the right of the current - // editor width - if (!wrapping && cur.text.firstChild) - { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; } - } - var diff = cur.line.height - height; - if (diff > .005 || diff < -.005) { - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) { for (var j = 0; j < cur.rest.length; j++) - { updateWidgetHeight(cur.rest[j]); } } - } - if (width > cm.display.sizerWidth) { - var chWidth = Math.ceil(width / charWidth(cm.display)); - if (chWidth > cm.display.maxLineLength) { - cm.display.maxLineLength = chWidth; - cm.display.maxLine = cur.line; - cm.display.maxLineChanged = true; - } - } - } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) { for (var i = 0; i < line.widgets.length; ++i) { - var w = line.widgets[i], parent = w.node.parentNode; - if (parent) { w.height = parent.offsetHeight; } - } } - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return {from: from, to: Math.max(to, from + 1)} - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, rect) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) { return } - - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; - if (rect.top + box.top < 0) { doScroll = true; } - else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; } - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;")); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) { margin = 0; } - var rect; - if (!cm.options.lineWrapping && pos == end) { - // Set pos and end to the cursor positions around the character pos sticks to - // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch - // If pos == Pos(_, 0, "before"), pos and end are unchanged - pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos; - end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos; - } - for (var limit = 0; limit < 5; limit++) { - var changed = false; - var coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - rect = {left: Math.min(coords.left, endCoords.left), - top: Math.min(coords.top, endCoords.top) - margin, - right: Math.max(coords.left, endCoords.left), - bottom: Math.max(coords.bottom, endCoords.bottom) + margin}; - var scrollPos = calculateScrollPos(cm, rect); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - updateScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) { changed = true; } - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) { changed = true; } - } - if (!changed) { break } - } - return rect - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, rect) { - var scrollPos = calculateScrollPos(cm, rect); - if (scrollPos.scrollTop != null) { updateScrollTop(cm, scrollPos.scrollTop); } - if (scrollPos.scrollLeft != null) { setScrollLeft(cm, scrollPos.scrollLeft); } - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, rect) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (rect.top < 0) { rect.top = 0; } - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), result = {}; - if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; } - var docBottom = cm.doc.height + paddingVert(display); - var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin; - if (rect.top < screentop) { - result.scrollTop = atTop ? 0 : rect.top; - } else if (rect.bottom > screentop + screen) { - var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen); - if (newTop != screentop) { result.scrollTop = newTop; } - } - - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; - var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); - var tooWide = rect.right - rect.left > screenw; - if (tooWide) { rect.right = rect.left + screenw; } - if (rect.left < 10) - { result.scrollLeft = 0; } - else if (rect.left < screenleft) - { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); } - else if (rect.right > screenw + screenleft - 3) - { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; } - return result - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollTop(cm, top) { - if (top == null) { return } - resolveScrollToPos(cm); - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(); - cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin}; - } - - function scrollToCoords(cm, x, y) { - if (x != null || y != null) { resolveScrollToPos(cm); } - if (x != null) { cm.curOp.scrollLeft = x; } - if (y != null) { cm.curOp.scrollTop = y; } - } - - function scrollToRange(cm, range$$1) { - resolveScrollToPos(cm); - cm.curOp.scrollToPos = range$$1; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range$$1 = cm.curOp.scrollToPos; - if (range$$1) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range$$1.from), to = estimateCoords(cm, range$$1.to); - scrollToCoordsRange(cm, from, to, range$$1.margin); - } - } - - function scrollToCoordsRange(cm, from, to, margin) { - var sPos = calculateScrollPos(cm, { - left: Math.min(from.left, to.left), - top: Math.min(from.top, to.top) - margin, - right: Math.max(from.right, to.right), - bottom: Math.max(from.bottom, to.bottom) + margin - }); - scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop); - } - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function updateScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) { return } - if (!gecko) { updateDisplaySimple(cm, {top: val}); } - setScrollTop(cm, val, true); - if (gecko) { updateDisplaySimple(cm); } - startWorker(cm, 100); - } - - function setScrollTop(cm, val, forceScroll) { - val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val)); - if (cm.display.scroller.scrollTop == val && !forceScroll) { return } - cm.doc.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; } - } - - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller, forceScroll) { - val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth)); - if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return } - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; } - cm.display.scrollbars.setScrollLeft(val); - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - } - } - - var NativeScrollbars = function(place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - vert.tabIndex = horiz.tabIndex = -1; - place(vert); place(horiz); - - on(vert, "scroll", function () { - if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); } - }); - on(horiz, "scroll", function () { - if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); } - }); - - this.checkedZeroWidth = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; } - }; - - NativeScrollbars.prototype.update = function (measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = - Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - - if (!this.checkedZeroWidth && measure.clientHeight > 0) { - if (sWidth == 0) { this.zeroWidthHack(); } - this.checkedZeroWidth = true; - } - - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0} - }; - - NativeScrollbars.prototype.setScrollLeft = function (pos) { - if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; } - if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); } - }; - - NativeScrollbars.prototype.setScrollTop = function (pos) { - if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; } - if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); } - }; - - NativeScrollbars.prototype.zeroWidthHack = function () { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.height = this.vert.style.width = w; - this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none"; - this.disableHoriz = new Delayed; - this.disableVert = new Delayed; - }; - - NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) { - bar.style.pointerEvents = "auto"; - function maybeDisable() { - // To find out whether the scrollbar is still visible, we - // check whether the element under the pixel in the bottom - // right corner of the scrollbar box is the scrollbar box - // itself (when the bar is still visible) or its filler child - // (when the bar is hidden). If it is still visible, we keep - // it enabled, if it's hidden, we disable pointer events. - var box = bar.getBoundingClientRect(); - var elt$$1 = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2) - : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1); - if (elt$$1 != bar) { bar.style.pointerEvents = "none"; } - else { delay.set(1000, maybeDisable); } - } - delay.set(1000, maybeDisable); - }; - - NativeScrollbars.prototype.clear = function () { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - }; - - var NullScrollbars = function () {}; - - NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} }; - NullScrollbars.prototype.setScrollLeft = function () {}; - NullScrollbars.prototype.setScrollTop = function () {}; - NullScrollbars.prototype.clear = function () {}; - - function updateScrollbars(cm, measure) { - if (!measure) { measure = measureForScrollbars(cm); } - var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) - { updateHeightsInViewport(cm); } - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent"; - - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else { d.scrollbarFiller.style.display = ""; } - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else { d.gutterFiller.style.display = ""; } - } - - var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); } - } - - cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function () { - if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); } - }); - node.setAttribute("cm-not-content", "true"); - }, function (pos, axis) { - if (axis == "horizontal") { setScrollLeft(cm, pos); } - else { updateScrollTop(cm, pos); } - }, cm); - if (cm.display.scrollbars.addClass) - { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); } - } - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, // Used to detect need to update scrollbar - forceUpdate: false, // Used to force a redraw - updateInput: 0, // Whether to reset the input textarea - typing: false, // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, // Accumulated changes, for firing change events - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already - selectionChanged: false, // Whether the selection needs to be redrawn - updateMaxLine: false, // Set when the widest line needs to be determined anew - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, // Used to scroll to a specific position - focus: false, - id: ++nextOpId // Unique ID - }; - pushOperation(cm.curOp); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp; - if (op) { finishOperation(op, function (group) { - for (var i = 0; i < group.ops.length; i++) - { group.ops[i].cm.curOp = null; } - endOperations(group); - }); } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) // Read DOM - { endOperation_R1(ops[i]); } - for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe) - { endOperation_W1(ops[i$1]); } - for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM - { endOperation_R2(ops[i$2]); } - for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe) - { endOperation_W2(ops[i$3]); } - for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM - { endOperation_finish(ops[i$4]); } - } - - function endOperation_R1(op) { - var cm = op.cm, display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) { findMaxLine(cm); } - - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || - op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || - op.scrollToPos.to.line >= display.viewTo) || - display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && - new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); - } - - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } - - function endOperation_R2(op) { - var cm = op.cm, display = cm.display; - if (op.updatedDisplay) { updateHeightsInViewport(cm); } - - op.barMeasure = measureForScrollbars(cm); - - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = - Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - - if (op.updatedDisplay || op.selectionChanged) - { op.preparedSelection = display.input.prepareSelection(); } - } - - function endOperation_W2(op) { - var cm = op.cm; - - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) - { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); } - cm.display.maxLineChanged = false; - } - - var takeFocus = op.focus && op.focus == activeElt(); - if (op.preparedSelection) - { cm.display.input.showSelection(op.preparedSelection, takeFocus); } - if (op.updatedDisplay || op.startHeight != cm.doc.height) - { updateScrollbars(cm, op.barMeasure); } - if (op.updatedDisplay) - { setDocumentHeight(cm, op.barMeasure); } - - if (op.selectionChanged) { restartBlink(cm); } - - if (cm.state.focused && op.updateInput) - { cm.display.input.reset(op.typing); } - if (takeFocus) { ensureFocus(op.cm); } - } - - function endOperation_finish(op) { - var cm = op.cm, display = cm.display, doc = cm.doc; - - if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); } - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) - { display.wheelStartX = display.wheelStartY = null; } - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); } - - if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - maybeScrollWindow(cm, rect); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) { for (var i = 0; i < hidden.length; ++i) - { if (!hidden[i].lines.length) { signal(hidden[i], "hide"); } } } - if (unhidden) { for (var i$1 = 0; i$1 < unhidden.length; ++i$1) - { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } } - - if (display.wrapper.offsetHeight) - { doc.scrollTop = cm.display.scroller.scrollTop; } - - // Fire change events, and delayed event handlers - if (op.changeObjs) - { signal(cm, "changes", cm, op.changeObjs); } - if (op.update) - { op.update.finish(); } - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) { return f() } - startOperation(cm); - try { return f() } - finally { endOperation(cm); } - } - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm, f) { - return function() { - if (cm.curOp) { return f.apply(cm, arguments) } - startOperation(cm); - try { return f.apply(cm, arguments) } - finally { endOperation(cm); } - } - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - function methodOp(f) { - return function() { - if (this.curOp) { return f.apply(this, arguments) } - startOperation(this); - try { return f.apply(this, arguments) } - finally { endOperation(this); } - } - } - function docMethodOp(f) { - return function() { - var cm = this.cm; - if (!cm || cm.curOp) { return f.apply(this, arguments) } - startOperation(cm); - try { return f.apply(this, arguments) } - finally { endOperation(cm); } - } - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.highlightFrontier < cm.display.viewTo) - { cm.state.highlight.set(time, bind(highlightWorker, cm)); } - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.highlightFrontier >= cm.display.viewTo) { return } - var end = +new Date + cm.options.workTime; - var context = getContextBefore(cm, doc.highlightFrontier); - var changedLines = []; - - doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { - if (context.line >= cm.display.viewFrom) { // Visible - var oldStyles = line.styles; - var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null; - var highlighted = highlightLine(cm, line, context, true); - if (resetState) { context.state = resetState; } - line.styles = highlighted.styles; - var oldCls = line.styleClasses, newCls = highlighted.classes; - if (newCls) { line.styleClasses = newCls; } - else if (oldCls) { line.styleClasses = null; } - var ischange = !oldStyles || oldStyles.length != line.styles.length || - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; } - if (ischange) { changedLines.push(context.line); } - line.stateAfter = context.save(); - context.nextLine(); - } else { - if (line.text.length <= cm.options.maxHighlightLength) - { processLine(cm, line.text, context); } - line.stateAfter = context.line % 5 == 0 ? context.save() : null; - context.nextLine(); - } - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true - } - }); - doc.highlightFrontier = context.line; - doc.modeFrontier = Math.max(doc.modeFrontier, context.line); - if (changedLines.length) { runInOp(cm, function () { - for (var i = 0; i < changedLines.length; i++) - { regLineChange(cm, changedLines[i], "text"); } - }); } - } - - // DISPLAY DRAWING - - var DisplayUpdate = function(cm, viewport, force) { - var display = cm.display; - - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - }; - - DisplayUpdate.prototype.signal = function (emitter, type) { - if (hasHandler(emitter, type)) - { this.events.push(arguments); } - }; - DisplayUpdate.prototype.finish = function () { - var this$1 = this; - - for (var i = 0; i < this.events.length; i++) - { signal.apply(null, this$1.events[i]); } - }; - - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - - function selectionSnapshot(cm) { - if (cm.hasFocus()) { return null } - var active = activeElt(); - if (!active || !contains(cm.display.lineDiv, active)) { return null } - var result = {activeElt: active}; - if (window.getSelection) { - var sel = window.getSelection(); - if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) { - result.anchorNode = sel.anchorNode; - result.anchorOffset = sel.anchorOffset; - result.focusNode = sel.focusNode; - result.focusOffset = sel.focusOffset; - } - } - return result - } - - function restoreSelection(snapshot) { - if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return } - snapshot.activeElt.focus(); - if (snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) { - var sel = window.getSelection(), range$$1 = document.createRange(); - range$$1.setEnd(snapshot.anchorNode, snapshot.anchorOffset); - range$$1.collapse(false); - sel.removeAllRanges(); - sel.addRange(range$$1); - sel.extend(snapshot.focusNode, snapshot.focusOffset); - } - } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, doc = cm.doc; - - if (update.editorIsHidden) { - resetView(cm); - return false - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && - display.renderedView == display.view && countDirtyView(cm) == 0) - { return false } - - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); - } - - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) { from = Math.max(doc.first, display.viewFrom); } - if (display.viewTo > to && display.viewTo - to < 20) { to = Math.min(end, display.viewTo); } - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); - } - - var different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - { return false } - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var selSnapshot = selectionSnapshot(cm); - if (toUpdate > 4) { display.lineDiv.style.display = "none"; } - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) { display.lineDiv.style.display = ""; } - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - restoreSelection(selSnapshot); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = display.sizer.style.minHeight = 0; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - - display.updateLineNumbers = null; - - return true - } - - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) - { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; } - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) - { break } - } else if (first) { - update.visible = visibleLines(cm.display, cm.doc, viewport); - } - if (!updateDisplayIfNeeded(cm, update)) { break } - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.force = false; - } - - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; - } - } - - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - updateScrollbars(cm, barMeasure); - setDocumentHeight(cm, barMeasure); - update.finish(); - } - } - - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) - { node.style.display = "none"; } - else - { node.parentNode.removeChild(node); } - return next - } - - var view = display.view, lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) ; else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { // Already drawn - while (cur != lineView.node) { cur = rm(cur); } - var updateNumber = lineNumbers && updateNumbersFrom != null && - updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) { updateNumber = false; } - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) { cur = rm(cur); } - } - - function updateGutterSpace(display) { - var width = display.gutters.offsetWidth; - display.sizer.style.marginLeft = width + "px"; - } - - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - cm.display.heightForcer.style.top = measure.docHeight + "px"; - cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px"; - } - - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) { return } - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, left = comp + "px"; - for (var i = 0; i < view.length; i++) { if (!view[i].hidden) { - if (cm.options.fixedGutter) { - if (view[i].gutter) - { view[i].gutter.style.left = left; } - if (view[i].gutterBackground) - { view[i].gutterBackground.style.left = left; } - } - var align = view[i].alignable; - if (align) { for (var j = 0; j < align.length; j++) - { align[j].style.left = left; } } - } } - if (cm.options.fixedGutter) - { display.gutters.style.left = (comp + gutterW) + "px"; } - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) { return false } - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm.display); - return true - } - return false - } - - function getGutters(gutters, lineNumbers) { - var result = [], sawLineNumbers = false; - for (var i = 0; i < gutters.length; i++) { - var name = gutters[i], style = null; - if (typeof name != "string") { style = name.style; name = name.className; } - if (name == "CodeMirror-linenumbers") { - if (!lineNumbers) { continue } - else { sawLineNumbers = true; } - } - result.push({className: name, style: style}); - } - if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); } - return result - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function renderGutters(display) { - var gutters = display.gutters, specs = display.gutterSpecs; - removeChildren(gutters); - display.lineGutter = null; - for (var i = 0; i < specs.length; ++i) { - var ref = specs[i]; - var className = ref.className; - var style = ref.style; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className)); - if (style) { gElt.style.cssText = style; } - if (className == "CodeMirror-linenumbers") { - display.lineGutter = gElt; - gElt.style.width = (display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = specs.length ? "" : "none"; - updateGutterSpace(display); - } - - function updateGutters(cm) { - renderGutters(cm.display); - regChange(cm); - alignHorizontally(cm); - } - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input, options) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = eltP("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], - null, "position: relative; outline: none"); - var lines = eltP("div", [d.lineSpace], "CodeMirror-lines"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [lines], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; } - - if (place) { - if (place.appendChild) { place.appendChild(d.wrapper); } - else { place(d.wrapper); } - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - d.gutterSpecs = getGutters(options.gutters, options.lineNumbers); - renderGutters(d); - - input.init(d); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) { wheelPixelsPerUnit = -.53; } - else if (gecko) { wheelPixelsPerUnit = 15; } - else if (chrome) { wheelPixelsPerUnit = -.7; } - else if (safari) { wheelPixelsPerUnit = -1/3; } - - function wheelEventDelta(e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) { dx = e.detail; } - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) { dy = e.detail; } - else if (dy == null) { dy = e.wheelDelta; } - return {x: dx, y: dy} - } - function wheelEventPixels(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta - } - - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - var canScrollX = scroll.scrollWidth > scroll.clientWidth; - var canScrollY = scroll.scrollHeight > scroll.clientHeight; - if (!(dx && canScrollX || dy && canScrollY)) { return } - - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { - for (var i = 0; i < view.length; i++) { - if (view[i].node == cur) { - cm.display.currentWheelTarget = cur; - break outer - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { - if (dy && canScrollY) - { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); } - setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit)); - // Only prevent default scrolling if vertical scrolling is - // actually possible. Otherwise, it causes vertical scroll - // jitter on OSX trackpads when deltaX is small and deltaY - // is large (issue #3579) - if (!dy || (dy && canScrollY)) - { e_preventDefault(e); } - display.wheelStartX = null; // Abort measurement, if in progress - return - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) { top = Math.max(0, top + pixels - 50); } - else { bot = Math.min(cm.doc.height, bot + pixels + 50); } - updateDisplaySimple(cm, {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function () { - if (display.wheelStartX == null) { return } - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) { return } - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; - } - } - } - - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - var Selection = function(ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - }; - - Selection.prototype.primary = function () { return this.ranges[this.primIndex] }; - - Selection.prototype.equals = function (other) { - var this$1 = this; - - if (other == this) { return true } - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) { return false } - for (var i = 0; i < this.ranges.length; i++) { - var here = this$1.ranges[i], there = other.ranges[i]; - if (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false } - } - return true - }; - - Selection.prototype.deepCopy = function () { - var this$1 = this; - - var out = []; - for (var i = 0; i < this.ranges.length; i++) - { out[i] = new Range(copyPos(this$1.ranges[i].anchor), copyPos(this$1.ranges[i].head)); } - return new Selection(out, this.primIndex) - }; - - Selection.prototype.somethingSelected = function () { - var this$1 = this; - - for (var i = 0; i < this.ranges.length; i++) - { if (!this$1.ranges[i].empty()) { return true } } - return false - }; - - Selection.prototype.contains = function (pos, end) { - var this$1 = this; - - if (!end) { end = pos; } - for (var i = 0; i < this.ranges.length; i++) { - var range = this$1.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) - { return i } - } - return -1 - }; - - var Range = function(anchor, head) { - this.anchor = anchor; this.head = head; - }; - - Range.prototype.from = function () { return minPos(this.anchor, this.head) }; - Range.prototype.to = function () { return maxPos(this.anchor, this.head) }; - Range.prototype.empty = function () { return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(cm, ranges, primIndex) { - var mayTouch = cm && cm.options.selectionsMayTouch; - var prim = ranges[primIndex]; - ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], prev = ranges[i - 1]; - var diff = cmp(prev.to(), cur.from()); - if (mayTouch && !cur.empty() ? diff > 0 : diff >= 0) { - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) { --primIndex; } - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex) - } - - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0) - } - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - function changeEnd(change) { - if (!change.text) { return change.to } - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)) - } - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) { return pos } - if (cmp(pos, change.to) <= 0) { return changeEnd(change) } - - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) { ch += changeEnd(change).ch - change.to.ch; } - return Pos(line, ch) - } - - function computeSelAfterChange(doc, change) { - var out = []; - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - out.push(new Range(adjustForChange(range.anchor, change), - adjustForChange(range.head, change))); - } - return normalizeSelection(doc.cm, out, doc.sel.primIndex) - } - - function offsetPos(pos, old, nw) { - if (pos.line == old.line) - { return Pos(nw.line, pos.ch - old.ch + nw.ch) } - else - { return Pos(nw.line + (pos.line - old.line), pos.ch) } - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex) - } - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - - function resetModeState(cm) { - cm.doc.iter(function (line) { - if (line.stateAfter) { line.stateAfter = null; } - if (line.styles) { line.styles = null; } - }); - cm.doc.modeFrontier = cm.doc.highlightFrontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) { regChange(cm); } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore) - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight$$1) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight$$1); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - var result = []; - for (var i = start; i < end; ++i) - { result.push(new Line(text[i], spansFor(i), estimateHeight$$1)); } - return result - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) { doc.remove(from.line, nlines); } - if (added.length) { doc.insert(from.line, added); } - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added$1 = linesFor(1, text.length - 1); - added$1.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight$$1)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added$1); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added$2 = linesFor(1, text.length - 1); - if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); } - doc.insert(from.line + 1, added$2); - } - - signalLater(doc, "change", doc, change); - } - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) { for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) { continue } - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) { continue } - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) { throw new Error("This document is already in use.") } - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - setDirectionClass(cm); - if (!cm.options.lineWrapping) { findMaxLine(cm); } - cm.options.mode = doc.modeOption; - regChange(cm); - } - - function setDirectionClass(cm) { - (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl"); - } - - function directionChanged(cm) { - runInOp(cm, function () { - setDirectionClass(cm); - regChange(cm); - }); - } - - function History(startGen) { - // Arrays of change events and selections. Doing something adds an - // event to done and clears undo. Undoing moves events from done - // to undone, redoing moves them in the other direction. - this.done = []; this.undone = []; - this.undoDepth = Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = startGen || 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function (doc) { return attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); }, true); - return histChange - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) { array.pop(); } - else { break } - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done) - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done) - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done) - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, or are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur; - var last; - - if ((hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) || - change.origin.charAt(0) == "*")) && - (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) - { pushSelectionToHistory(doc.sel, hist.done); } - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation}; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) { hist.done.shift(); } - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - - if (!last) { signal(doc, "historyAdded"); } - } - - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || - ch == "+" && - prev.ranges.length == sel.ranges.length && - prev.somethingSelected() == sel.somethingSelected() && - new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500) - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || - (origin && hist.lastSelOrigin == origin && - (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) - { hist.done[hist.done.length - 1] = sel; } - else - { pushSelectionToHistory(sel, hist.done); } - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - { clearSelectionEvents(hist.undone); } - } - - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - { dest.push(sel); } - } - - // Used to store marked span information in the history. - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { - if (line.markedSpans) - { (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; } - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) { return null } - var out; - for (var i = 0; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) { out = spans.slice(0, i); } } - else if (out) { out.push(spans[i]); } - } - return !out ? spans : out.length ? out : null - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) { return null } - var nw = []; - for (var i = 0; i < change.text.length; ++i) - { nw.push(removeClearedSpans(found[i])); } - return nw - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) { return stretched } - if (!stretched) { return old } - - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - { if (oldCur[k].marker == span.marker) { continue spans } } - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - var copy = []; - for (var i = 0; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue - } - var changes = event.changes, newChanges = []; - copy.push({changes: newChanges}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m = (void 0); - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) { for (var prop in change) { if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } } } - } - } - return copy - } - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(range, head, other, extend) { - if (extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != (cmp(other, anchor) < 0)) { - anchor = head; - head = other; - } else if (posBefore != (cmp(head, other) < 0)) { - head = other; - } - } - return new Range(anchor, head) - } else { - return new Range(other || head, head) - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options, extend) { - if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); } - setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - var out = []; - var extend = doc.cm && (doc.cm.display.shift || doc.extend); - for (var i = 0; i < doc.sel.ranges.length; i++) - { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); } - var newSel = normalizeSelection(doc.cm, out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(doc.cm, ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel, options) { - var obj = { - ranges: sel.ranges, - update: function(ranges) { - var this$1 = this; - - this.ranges = []; - for (var i = 0; i < ranges.length; i++) - { this$1.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), - clipPos(doc, ranges[i].head)); } - }, - origin: options && options.origin - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); } - if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, obj.ranges, obj.ranges.length - 1) } - else { return sel } - } - - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); - } - } - - // Set a new selection. - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } - - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) - { sel = filterSelectionChange(doc, sel, options); } - - var bias = options && options.bias || - (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - - if (!(options && options.scroll === false) && doc.cm) - { ensureCursorVisible(doc.cm); } - } - - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) { return } - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = 1; - doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false)); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, old && old.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) { out = sel.ranges.slice(0, i); } - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(doc.cm, out, sel.primIndex) : sel - } - - function skipAtomicInner(doc, pos, oldPos, dir, mayClear) { - var line = getLine(doc, pos.line); - if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], m = sp.marker; - - // Determine if we should prevent the cursor being placed to the left/right of an atomic marker - // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it - // is with selectLeft/Right - var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft; - var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight; - - if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) && - (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) { break } - else {--i; continue} - } - } - if (!m.atomic) { continue } - - if (oldPos) { - var near = m.find(dir < 0 ? 1 : -1), diff = (void 0); - if (dir < 0 ? preventCursorRight : preventCursorLeft) - { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); } - if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0)) - { return skipAtomicInner(doc, near, pos, dir, mayClear) } - } - - var far = m.find(dir < 0 ? -1 : 1); - if (dir < 0 ? preventCursorLeft : preventCursorRight) - { far = movePos(doc, far, dir, far.line == pos.line ? line : null); } - return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null - } - } } - return pos - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, oldPos, bias, mayClear) { - var dir = bias || 1; - var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) || - (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) || - skipAtomicInner(doc, pos, oldPos, -dir, mayClear) || - (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true)); - if (!found) { - doc.cantEdit = true; - return Pos(doc.first, 0) - } - return found - } - - function movePos(doc, pos, dir, line) { - if (dir < 0 && pos.ch == 0) { - if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) } - else { return null } - } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) { - if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) } - else { return null } - } else { - return new Pos(pos.line, pos.ch + dir) - } - } - - function selectAll(cm) { - cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll); - } - - // UPDATING - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function () { return obj.canceled = true; } - }; - if (update) { obj.update = function (from, to, text, origin) { - if (from) { obj.from = clipPos(doc, from); } - if (to) { obj.to = clipPos(doc, to); } - if (text) { obj.text = text; } - if (origin !== undefined) { obj.origin = origin; } - }; } - signal(doc, "beforeChange", doc, obj); - if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); } - - if (obj.canceled) { - if (doc.cm) { doc.cm.curOp.updateInput = 2; } - return null - } - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin} - } - - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) { return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly) } - if (doc.cm.state.suppressEdits) { return } - } - - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) { return } - } - - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) - { makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text, origin: change.origin}); } - } else { - makeChangeInner(doc, change); - } - } - - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) { return } - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - - linkedDocs(doc, function (doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - var suppress = doc.cm && doc.cm.state.suppressEdits; - if (suppress && !allowSelectionOnly) { return } - - var hist = doc.history, event, selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - var i = 0; - for (; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) - { break } - } - if (i == source.length) { return } - hist.lastOrigin = hist.lastSelOrigin = null; - - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, {clearRedo: false}); - return - } - selAfter = event; - } else if (suppress) { - source.push(event); - return - } else { break } - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({changes: antiChanges, generation: hist.generation}); - hist.generation = event.generation || ++hist.maxGeneration; - - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - - var loop = function ( i ) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return {} - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); } - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function (doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - }; - - for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) { - var returned = loop( i$1 ); - - if ( returned ) return returned.v; - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) { return } - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function (range) { return new Range( - Pos(range.anchor.line + distance, range.anchor.ch), - Pos(range.head.line + distance, range.head.ch) - ); }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) - { regLineChange(doc.cm, l, "gutter"); } - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - { return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans) } - - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return - } - if (change.from.line > doc.lastLine()) { return } - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; - } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; - } - - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) { selAfter = computeSelAfterChange(doc, change); } - if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); } - else { updateDoc(doc, change, spans); } - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - - if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0))) - { doc.cantEdit = false; } - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function (line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - { signalCursorActivity(cm); } - - updateDoc(doc, change, spans, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function (line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) { cm.curOp.updateMaxLine = true; } - } - - retreatFrontier(doc, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) - { regChange(cm); } - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) - { regLineChange(cm, from.line, "text"); } - else - { regChange(cm, from.line, to.line + 1, lendiff); } - - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) { signalLater(cm, "change", cm, obj); } - if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); } - } - cm.display.selForContextMenu = null; - } - - function replaceRange(doc, code, from, to, origin) { - var assign; - - if (!to) { to = from; } - if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); } - if (typeof code == "string") { code = doc.splitLines(code); } - makeChange(doc, {from: from, to: to, text: code, origin: origin}); - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - if (sub.ranges) { - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue - } - for (var j$1 = 0; j$1 < sub.changes.length; ++j$1) { - var cur = sub.changes[j$1]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, line = handle; - if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); } - else { no = lineNo(handle); } - if (no == null) { return null } - if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); } - return line - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - var this$1 = this; - - this.lines = lines; - this.parent = null; - var height = 0; - for (var i = 0; i < lines.length; ++i) { - lines[i].parent = this$1; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length }, - - // Remove the n lines at offset 'at'. - removeInner: function(at, n) { - var this$1 = this; - - for (var i = at, e = at + n; i < e; ++i) { - var line = this$1.lines[i]; - this$1.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - - // Helper used to collapse a small branch into a single leaf. - collapse: function(lines) { - lines.push.apply(lines, this.lines); - }, - - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function(at, lines, height) { - var this$1 = this; - - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0; i < lines.length; ++i) { lines[i].parent = this$1; } - }, - - // Used to iterate over a part of the tree. - iterN: function(at, n, op) { - var this$1 = this; - - for (var e = at + n; at < e; ++at) - { if (op(this$1.lines[at])) { return true } } - } - }; - - function BranchChunk(children) { - var this$1 = this; - - this.children = children; - var size = 0, height = 0; - for (var i = 0; i < children.length; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this$1; - } - this.size = size; - this.height = height; - this.parent = null; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size }, - - removeInner: function(at, n) { - var this$1 = this; - - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this$1.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.removeInner(at, rm); - this$1.height -= oldHeight - child.height; - if (sz == rm) { this$1.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) { break } - at = 0; - } else { at -= sz; } - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - - collapse: function(lines) { - var this$1 = this; - - for (var i = 0; i < this.children.length; ++i) { this$1.children[i].collapse(lines); } - }, - - insertInner: function(at, lines, height) { - var this$1 = this; - - this.size += lines.length; - this.height += height; - for (var i = 0; i < this.children.length; ++i) { - var child = this$1.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced. - // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest. - var remaining = child.lines.length % 25 + 25; - for (var pos = remaining; pos < child.lines.length;) { - var leaf = new LeafChunk(child.lines.slice(pos, pos += 25)); - child.height -= leaf.height; - this$1.children.splice(++i, 0, leaf); - leaf.parent = this$1; - } - child.lines = child.lines.slice(0, remaining); - this$1.maybeSpill(); - } - break - } - at -= sz; - } - }, - - // When a node has grown, check whether it should be split. - maybeSpill: function() { - if (this.children.length <= 10) { return } - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10) - me.parent.maybeSpill(); - }, - - iterN: function(at, n, op) { - var this$1 = this; - - for (var i = 0; i < this.children.length; ++i) { - var child = this$1.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) { return true } - if ((n -= used) == 0) { break } - at = 0; - } else { at -= sz; } - } - } - }; - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = function(doc, node, options) { - var this$1 = this; - - if (options) { for (var opt in options) { if (options.hasOwnProperty(opt)) - { this$1[opt] = options[opt]; } } } - this.doc = doc; - this.node = node; - }; - - LineWidget.prototype.clear = function () { - var this$1 = this; - - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); - if (no == null || !ws) { return } - for (var i = 0; i < ws.length; ++i) { if (ws[i] == this$1) { ws.splice(i--, 1); } } - if (!ws.length) { line.widgets = null; } - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) { - runInOp(cm, function () { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - signalLater(cm, "lineWidgetCleared", cm, this, no); - } - }; - - LineWidget.prototype.changed = function () { - var this$1 = this; - - var oldH = this.height, cm = this.doc.cm, line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) { return } - if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); } - if (cm) { - runInOp(cm, function () { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line)); - }); - } - }; - eventMixin(LineWidget); - - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - { addToScrollTop(cm, diff); } - } - - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) { cm.display.alignWidgets = true; } - changeLine(doc, handle, "widget", function (line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) { widgets.push(widget); } - else { widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); } - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) { addToScrollTop(cm, widget.height); } - cm.curOp.forceUpdate = true; - } - return true - }); - if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); } - return widget - } - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - - var TextMarker = function(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - - // Clear the marker. - TextMarker.prototype.clear = function () { - var this$1 = this; - - if (this.explicitlyCleared) { return } - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) { startOperation(cm); } - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) { signalLater(this, "clear", found.from, found.to); } - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this$1.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this$1); - if (cm && !this$1.collapsed) { regLineChange(cm, lineNo(line), "text"); } - else if (cm) { - if (span.to != null) { max = lineNo(line); } - if (span.from != null) { min = lineNo(line); } - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this$1.collapsed && !lineIsHidden(this$1.doc, line) && cm) - { updateLineHeight(line, textHeight(cm.display)); } - } - if (cm && this.collapsed && !cm.options.lineWrapping) { for (var i$1 = 0; i$1 < this.lines.length; ++i$1) { - var visual = visualLine(this$1.lines[i$1]), len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } } - - if (min != null && cm && this.collapsed) { regChange(cm, min, max + 1); } - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) { reCheckSelection(cm.doc); } - } - if (cm) { signalLater(cm, "markerCleared", cm, this, min, max); } - if (withOp) { endOperation(cm); } - if (this.parent) { this.parent.clear(); } - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function (side, lineObj) { - var this$1 = this; - - if (side == null && this.type == "bookmark") { side = 1; } - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this$1.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this$1); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) { return from } - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) { return to } - } - } - return from && {from: from, to: to} - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function () { - var this$1 = this; - - var pos = this.find(-1, true), widget = this, cm = this.doc.cm; - if (!pos || !cm) { return } - runInOp(cm, function () { - var line = pos.line, lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) - { updateLineHeight(line, line.height + dHeight); } - } - signalLater(cm, "markerChanged", cm, this$1); - }); - }; - - TextMarker.prototype.attachLine = function (line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - { (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); } - } - this.lines.push(line); - }; - - TextMarker.prototype.detachLine = function (line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp - ;(op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - eventMixin(TextMarker); - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) { return markTextShared(doc, from, to, options, type) } - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) { return operation(doc.cm, markText)(doc, from, to, options, type) } - - var marker = new TextMarker(doc, type), diff = cmp(from, to); - if (options) { copyObj(options, marker, false); } - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) - { return marker } - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = eltP("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "true"); } - if (options.insertLeft) { marker.widgetNode.insertLeft = true; } - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || - from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) - { throw new Error("Inserting collapsed marker partially overlapping an existing one") } - seeCollapsedSpans(); - } - - if (marker.addToHistory) - { addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); } - - var curLine = from.line, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function (line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) - { updateMaxLine = true; } - if (marker.collapsed && curLine != from.line) { updateLineHeight(line, 0); } - addMarkedSpan(line, new MarkedSpan(marker, - curLine == from.line ? from.ch : null, - curLine == to.line ? to.ch : null)); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) { doc.iter(from.line, to.line + 1, function (line) { - if (lineIsHidden(doc, line)) { updateLineHeight(line, 0); } - }); } - - if (marker.clearOnEnter) { on(marker, "beforeCursorEnter", function () { return marker.clear(); }); } - - if (marker.readOnly) { - seeReadOnlySpans(); - if (doc.history.done.length || doc.history.undone.length) - { doc.clearHistory(); } - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) { cm.curOp.updateMaxLine = true; } - if (marker.collapsed) - { regChange(cm, from.line, to.line + 1); } - else if (marker.className || marker.startStyle || marker.endStyle || marker.css || - marker.attributes || marker.title) - { for (var i = from.line; i <= to.line; i++) { regLineChange(cm, i, "text"); } } - if (marker.atomic) { reCheckSelection(cm.doc); } - signalLater(cm, "markerAdded", cm, marker); - } - return marker - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = function(markers, primary) { - var this$1 = this; - - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) - { markers[i].parent = this$1; } - }; - - SharedTextMarker.prototype.clear = function () { - var this$1 = this; - - if (this.explicitlyCleared) { return } - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) - { this$1.markers[i].clear(); } - signalLater(this, "clear"); - }; - - SharedTextMarker.prototype.find = function (side, lineObj) { - return this.primary.find(side, lineObj) - }; - eventMixin(SharedTextMarker); - - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function (doc) { - if (widget) { options.widgetNode = widget.cloneNode(true); } - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) - { if (doc.linked[i].isParent) { return } } - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary) - } - - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; }) - } - - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], pos = marker.find(); - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - - function detachSharedMarkers(markers) { - var loop = function ( i ) { - var marker = markers[i], linked = [marker.primary.doc]; - linkedDocs(marker.primary.doc, function (d) { return linked.push(d); }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - }; - - for (var i = 0; i < markers.length; i++) loop( i ); - } - - var nextDocId = 0; - var Doc = function(text, mode, firstLine, lineSep, direction) { - if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) } - if (firstLine == null) { firstLine = 0; } - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.modeFrontier = this.highlightFrontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - this.lineSep = lineSep; - this.direction = (direction == "rtl") ? "rtl" : "ltr"; - this.extend = false; - - if (typeof text == "string") { text = this.splitLines(text); } - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function(from, to, op) { - if (op) { this.iterN(from - this.first, to - from, op); } - else { this.iterN(this.first, this.first + this.size, from); } - }, - - // Non-public interface for adding and removing lines. - insert: function(at, lines) { - var height = 0; - for (var i = 0; i < lines.length; ++i) { height += lines[i].height; } - this.insertInner(at - this.first, lines, height); - }, - remove: function(at, n) { this.removeInner(at - this.first, n); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function(lineSep) { - var lines = getLines(this, this.first, this.first + this.size); - if (lineSep === false) { return lines } - return lines.join(lineSep || this.lineSeparator()) - }, - setValue: docMethodOp(function(code) { - var top = Pos(this.first, 0), last = this.first + this.size - 1; - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), - text: this.splitLines(code), origin: "setValue", full: true}, true); - if (this.cm) { scrollToCoords(this.cm, 0, 0); } - setSelection(this, simpleSelection(top), sel_dontScroll); - }), - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) { return lines } - return lines.join(lineSep || this.lineSeparator()) - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text}, - - getLineHandle: function(line) {if (isLine(this, line)) { return getLine(this, line) }}, - getLineNumber: function(line) {return lineNo(line)}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") { line = getLine(this, line); } - return visualLine(line) - }, - - lineCount: function() {return this.size}, - firstLine: function() {return this.first}, - lastLine: function() {return this.first + this.size - 1}, - - clipPos: function(pos) {return clipPos(this, pos)}, - - getCursor: function(start) { - var range$$1 = this.sel.primary(), pos; - if (start == null || start == "head") { pos = range$$1.head; } - else if (start == "anchor") { pos = range$$1.anchor; } - else if (start == "end" || start == "to" || start === false) { pos = range$$1.to(); } - else { pos = range$$1.from(); } - return pos - }, - listSelections: function() { return this.sel.ranges }, - somethingSelected: function() {return this.sel.somethingSelected()}, - - setCursor: docMethodOp(function(line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function(anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function(head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function(heads, options) { - extendSelections(this, clipPosArray(this, heads), options); - }), - extendSelectionsBy: docMethodOp(function(f, options) { - var heads = map(this.sel.ranges, f); - extendSelections(this, clipPosArray(this, heads), options); - }), - setSelections: docMethodOp(function(ranges, primary, options) { - var this$1 = this; - - if (!ranges.length) { return } - var out = []; - for (var i = 0; i < ranges.length; i++) - { out[i] = new Range(clipPos(this$1, ranges[i].anchor), - clipPos(this$1, ranges[i].head)); } - if (primary == null) { primary = Math.min(ranges.length - 1, this.sel.primIndex); } - setSelection(this, normalizeSelection(this.cm, out, primary), options); - }), - addSelection: docMethodOp(function(anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(this.cm, ranges, ranges.length - 1), options); - }), - - getSelection: function(lineSep) { - var this$1 = this; - - var ranges = this.sel.ranges, lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) { return lines } - else { return lines.join(lineSep || this.lineSeparator()) } - }, - getSelections: function(lineSep) { - var this$1 = this; - - var parts = [], ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this$1, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) { sel = sel.join(lineSep || this$1.lineSeparator()); } - parts[i] = sel; - } - return parts - }, - replaceSelection: function(code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) - { dup[i] = code; } - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function(code, collapse, origin) { - var this$1 = this; - - var changes = [], sel = this.sel; - for (var i = 0; i < sel.ranges.length; i++) { - var range$$1 = sel.ranges[i]; - changes[i] = {from: range$$1.from(), to: range$$1.to(), text: this$1.splitLines(code[i]), origin: origin}; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i$1 = changes.length - 1; i$1 >= 0; i$1--) - { makeChange(this$1, changes[i$1]); } - if (newSel) { setSelectionReplaceHistory(this, newSel); } - else if (this.cm) { ensureCursorVisible(this.cm); } - }), - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend}, - - historySize: function() { - var hist = this.history, done = 0, undone = 0; - for (var i = 0; i < hist.done.length; i++) { if (!hist.done[i].ranges) { ++done; } } - for (var i$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } } - return {undo: done, redo: undone} - }, - clearHistory: function() { - var this$1 = this; - - this.history = new History(this.history.maxGeneration); - linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true); - }, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function(forceSplit) { - if (forceSplit) - { this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; } - return this.history.generation - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration) - }, - - getHistory: function() { - return {done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone)} - }, - setHistory: function(histData) { - var hist = this.history = new History(this.history.maxGeneration); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - - setGutterMarker: docMethodOp(function(line, gutterID, value) { - return changeLine(this, line, "gutter", function (line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) { line.gutterMarkers = null; } - return true - }) - }), - - clearGutter: docMethodOp(function(gutterID) { - var this$1 = this; - - this.iter(function (line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - changeLine(this$1, line, "gutter", function () { - line.gutterMarkers[gutterID] = null; - if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; } - return true - }); - } - }); - }), - - lineInfo: function(line) { - var n; - if (typeof line == "number") { - if (!isLine(this, line)) { return null } - n = line; - line = getLine(this, line); - if (!line) { return null } - } else { - n = lineNo(line); - if (n == null) { return null } - } - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, - widgets: line.widgets} - }, - - addLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) { line[prop] = cls; } - else if (classTest(cls).test(line[prop])) { return false } - else { line[prop] += " " + cls; } - return true - }) - }), - removeLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) { return false } - else if (cls == null) { line[prop] = null; } - else { - var found = cur.match(classTest(cls)); - if (!found) { return false } - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true - }) - }), - - addLineWidget: docMethodOp(function(handle, node, options) { - return addLineWidget(this, handle, node, options) - }), - removeLineWidget: function(widget) { widget.clear(); }, - - markText: function(from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "range") - }, - setBookmark: function(pos, options) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark") - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) { for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || span.to >= pos.ch)) - { markers.push(span.marker.parent || span.marker); } - } } - return markers - }, - findMarks: function(from, to, filter) { - from = clipPos(this, from); to = clipPos(this, to); - var found = [], lineNo$$1 = from.line; - this.iter(from.line, to.line + 1, function (line) { - var spans = line.markedSpans; - if (spans) { for (var i = 0; i < spans.length; i++) { - var span = spans[i]; - if (!(span.to != null && lineNo$$1 == from.line && from.ch >= span.to || - span.from == null && lineNo$$1 != from.line || - span.from != null && lineNo$$1 == to.line && span.from >= to.ch) && - (!filter || filter(span.marker))) - { found.push(span.marker.parent || span.marker); } - } } - ++lineNo$$1; - }); - return found - }, - getAllMarks: function() { - var markers = []; - this.iter(function (line) { - var sps = line.markedSpans; - if (sps) { for (var i = 0; i < sps.length; ++i) - { if (sps[i].from != null) { markers.push(sps[i].marker); } } } - }); - return markers - }, - - posFromIndex: function(off) { - var ch, lineNo$$1 = this.first, sepSize = this.lineSeparator().length; - this.iter(function (line) { - var sz = line.text.length + sepSize; - if (sz > off) { ch = off; return true } - off -= sz; - ++lineNo$$1; - }); - return clipPos(this, Pos(lineNo$$1, ch)) - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) { return 0 } - var sepSize = this.lineSeparator().length; - this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value - index += line.text.length + sepSize; - }); - return index - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), - this.modeOption, this.first, this.lineSep, this.direction); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc - }, - - linkedDoc: function(options) { - if (!options) { options = {}; } - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) { from = options.from; } - if (options.to != null && options.to < to) { to = options.to; } - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from, this.lineSep, this.direction); - if (options.sharedHist) { copy.history = this.history - ; }(this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy - }, - unlinkDoc: function(other) { - var this$1 = this; - - if (other instanceof CodeMirror) { other = other.doc; } - if (this.linked) { for (var i = 0; i < this.linked.length; ++i) { - var link = this$1.linked[i]; - if (link.doc != other) { continue } - this$1.linked.splice(i, 1); - other.unlinkDoc(this$1); - detachSharedMarkers(findSharedMarkers(this$1)); - break - } } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function (doc) { return splitIds.push(doc.id); }, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function(f) {linkedDocs(this, f);}, - - getMode: function() {return this.mode}, - getEditor: function() {return this.cm}, - - splitLines: function(str) { - if (this.lineSep) { return str.split(this.lineSep) } - return splitLinesAuto(str) - }, - lineSeparator: function() { return this.lineSep || "\n" }, - - setDirection: docMethodOp(function (dir) { - if (dir != "rtl") { dir = "ltr"; } - if (dir == this.direction) { return } - this.direction = dir; - this.iter(function (line) { return line.order = null; }); - if (this.cm) { directionChanged(this.cm); } - }) - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - - function onDrop(e) { - var cm = this; - clearDragCursor(cm); - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) - { return } - e_preventDefault(e); - if (ie) { lastDrop = +new Date; } - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || cm.isReadOnly()) { return } - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var markAsReadAndPasteIfAllFilesAreRead = function () { - if (++read == n) { - operation(cm, function () { - pos = clipPos(cm.doc, pos); - var change = {from: pos, to: pos, - text: cm.doc.splitLines( - text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())), - origin: "paste"}; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change)))); - })(); - } - }; - var readTextFromFile = function (file, i) { - if (cm.options.allowDropFileTypes && - indexOf(cm.options.allowDropFileTypes, file.type) == -1) { - markAsReadAndPasteIfAllFilesAreRead(); - return - } - var reader = new FileReader; - reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); }; - reader.onload = function () { - var content = reader.result; - if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) { - markAsReadAndPasteIfAllFilesAreRead(); - return - } - text[i] = content; - markAsReadAndPasteIfAllFilesAreRead(); - }; - reader.readAsText(file); - }; - for (var i = 0; i < files.length; i++) { readTextFromFile(files[i], i); } - } else { // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function () { return cm.display.input.focus(); }, 20); - return - } - try { - var text$1 = e.dataTransfer.getData("Text"); - if (text$1) { - var selected; - if (cm.state.draggingText && !cm.state.draggingText.copy) - { selected = cm.listSelections(); } - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1) - { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } } - cm.replaceSelection(text$1, "around", "paste"); - cm.display.input.focus(); - } - } - catch(e){} - } - } - - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) { return } - - e.dataTransfer.setData("Text", cm.getSelection()); - e.dataTransfer.effectAllowed = "copyMove"; - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) { img.parentNode.removeChild(img); } - } - } - - function onDragOver(cm, e) { - var pos = posFromMouse(cm, e); - if (!pos) { return } - var frag = document.createDocumentFragment(); - drawSelectionCursor(cm, pos, frag); - if (!cm.display.dragCursor) { - cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors"); - cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv); - } - removeChildrenAndAdd(cm.display.dragCursor, frag); - } - - function clearDragCursor(cm) { - if (cm.display.dragCursor) { - cm.display.lineSpace.removeChild(cm.display.dragCursor); - cm.display.dragCursor = null; - } - } - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.getElementsByClassName) { return } - var byClass = document.getElementsByClassName("CodeMirror"), editors = []; - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) { editors.push(cm); } - } - if (editors.length) { editors[0].operation(function () { - for (var i = 0; i < editors.length; i++) { f(editors[i]); } - }); } - } - - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) { return } - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function () { - if (resizeTimer == null) { resizeTimer = setTimeout(function () { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); } - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function () { return forEachCodeMirror(onBlur); }); - } - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - - var keyNames = { - 3: "Pause", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", - 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock", - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert" - }; - - // Number keys - for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); } - // Alphabetic keys - for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); } - // Function keys - for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; } - - var keyMap = {}; - - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", - "fallthrough": "basic" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars", - "Ctrl-O": "openLine" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", - "fallthrough": ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/); - name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; } - else if (/^a(lt)?$/i.test(mod)) { alt = true; } - else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; } - else if (/^s(hift)?$/i.test(mod)) { shift = true; } - else { throw new Error("Unrecognized modifier name: " + mod) } - } - if (alt) { name = "Alt-" + name; } - if (ctrl) { name = "Ctrl-" + name; } - if (cmd) { name = "Cmd-" + name; } - if (shift) { name = "Shift-" + name; } - return name - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - function normalizeKeyMap(keymap) { - var copy = {}; - for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue } - if (value == "...") { delete keymap[keyname]; continue } - - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val = (void 0), name = (void 0); - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) { copy[name] = val; } - else if (prev != val) { throw new Error("Inconsistent bindings for " + name) } - } - delete keymap[keyname]; - } } - for (var prop in copy) { keymap[prop] = copy[prop]; } - return keymap - } - - function lookupKey(key, map$$1, handle, context) { - map$$1 = getKeyMap(map$$1); - var found = map$$1.call ? map$$1.call(key, context) : map$$1[key]; - if (found === false) { return "nothing" } - if (found === "...") { return "multi" } - if (found != null && handle(found)) { return "handled" } - - if (map$$1.fallthrough) { - if (Object.prototype.toString.call(map$$1.fallthrough) != "[object Array]") - { return lookupKey(key, map$$1.fallthrough, handle, context) } - for (var i = 0; i < map$$1.fallthrough.length; i++) { - var result = lookupKey(key, map$$1.fallthrough[i], handle, context); - if (result) { return result } - } - } - } - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - function isModifierKey(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod" - } - - function addModifierNames(name, event, noShift) { - var base = name; - if (event.altKey && base != "Alt") { name = "Alt-" + name; } - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; } - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") { name = "Cmd-" + name; } - if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; } - return name - } - - // Look up the name of a key as indicated by an event object. - function keyName(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) { return false } - var name = keyNames[event.keyCode]; - if (name == null || event.altGraphKey) { return false } - // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause, - // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+) - if (event.keyCode == 3 && event.code) { name = event.code; } - return addModifierNames(name, event, noShift) - } - - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break - } - } - kill.push(toKill); - } - // Next, remove those actual ranges. - runInOp(cm, function () { - for (var i = kill.length - 1; i >= 0; i--) - { replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); } - ensureCursorVisible(cm); - }); - } - - function moveCharLogically(line, ch, dir) { - var target = skipExtendingChars(line.text, ch + dir, dir); - return target < 0 || target > line.text.length ? null : target - } - - function moveLogically(line, start, dir) { - var ch = moveCharLogically(line, start.ch, dir); - return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before") - } - - function endOfLine(visually, cm, lineObj, lineNo, dir) { - if (visually) { - if (cm.doc.direction == "rtl") { dir = -dir; } - var order = getOrder(lineObj, cm.doc.direction); - if (order) { - var part = dir < 0 ? lst(order) : order[0]; - var moveInStorageOrder = (dir < 0) == (part.level == 1); - var sticky = moveInStorageOrder ? "after" : "before"; - var ch; - // With a wrapped rtl chunk (possibly spanning multiple bidi parts), - // it could be that the last bidi part is not on the last visual line, - // since visual lines contain content order-consecutive chunks. - // Thus, in rtl, we are looking for the first (content-order) character - // in the rtl chunk that is on the last line (that is, the same line - // as the last (content-order) character). - if (part.level > 0 || cm.doc.direction == "rtl") { - var prep = prepareMeasureForLine(cm, lineObj); - ch = dir < 0 ? lineObj.text.length - 1 : 0; - var targetTop = measureCharPrepared(cm, prep, ch).top; - ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch); - if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); } - } else { ch = dir < 0 ? part.to : part.from; } - return new Pos(lineNo, ch, sticky) - } - } - return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after") - } - - function moveVisually(cm, line, start, dir) { - var bidi = getOrder(line, cm.doc.direction); - if (!bidi) { return moveLogically(line, start, dir) } - if (start.ch >= line.text.length) { - start.ch = line.text.length; - start.sticky = "before"; - } else if (start.ch <= 0) { - start.ch = 0; - start.sticky = "after"; - } - var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos]; - if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) { - // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines, - // nothing interesting happens. - return moveLogically(line, start, dir) - } - - var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); }; - var prep; - var getWrappedLineExtent = function (ch) { - if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} } - prep = prep || prepareMeasureForLine(cm, line); - return wrappedLineExtentChar(cm, line, prep, ch) - }; - var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch); - - if (cm.doc.direction == "rtl" || part.level == 1) { - var moveInStorageOrder = (part.level == 1) == (dir < 0); - var ch = mv(start, moveInStorageOrder ? 1 : -1); - if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) { - // Case 2: We move within an rtl part or in an rtl editor on the same visual line - var sticky = moveInStorageOrder ? "before" : "after"; - return new Pos(start.line, ch, sticky) - } - } - - // Case 3: Could not move within this bidi part in this visual line, so leave - // the current bidi part - - var searchInVisualLine = function (partPos, dir, wrappedLineExtent) { - var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder - ? new Pos(start.line, mv(ch, 1), "before") - : new Pos(start.line, ch, "after"); }; - - for (; partPos >= 0 && partPos < bidi.length; partPos += dir) { - var part = bidi[partPos]; - var moveInStorageOrder = (dir > 0) == (part.level != 1); - var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1); - if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) } - ch = moveInStorageOrder ? part.from : mv(part.to, -1); - if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) } - } - }; - - // Case 3a: Look for other bidi parts on the same visual line - var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent); - if (res) { return res } - - // Case 3b: Look for other bidi parts on the next visual line - var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1); - if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) { - res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh)); - if (res) { return res } - } - - // Case 4: Nowhere to move - return null - } - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = { - selectAll: selectAll, - singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); }, - killLine: function (cm) { return deleteNearSelection(cm, function (range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) - { return {from: range.head, to: Pos(range.head.line + 1, 0)} } - else - { return {from: range.head, to: Pos(range.head.line, len)} } - } else { - return {from: range.from(), to: range.to()} - } - }); }, - deleteLine: function (cm) { return deleteNearSelection(cm, function (range) { return ({ - from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0)) - }); }); }, - delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({ - from: Pos(range.from().line, 0), to: range.from() - }); }); }, - delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({left: 0, top: top}, "div"); - return {from: leftPos, to: range.from()} - }); }, - delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - return {from: range.from(), to: rightPos } - }); }, - undo: function (cm) { return cm.undo(); }, - redo: function (cm) { return cm.redo(); }, - undoSelection: function (cm) { return cm.undoSelection(); }, - redoSelection: function (cm) { return cm.redoSelection(); }, - goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); }, - goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); }, - goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, - {origin: "+move", bias: 1} - ); }, - goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); }, - {origin: "+move", bias: 1} - ); }, - goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, - {origin: "+move", bias: -1} - ); }, - goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div") - }, sel_move); }, - goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - return cm.coordsChar({left: 0, top: top}, "div") - }, sel_move); }, - goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) { - var top = cm.cursorCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({left: 0, top: top}, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) } - return pos - }, sel_move); }, - goLineUp: function (cm) { return cm.moveV(-1, "line"); }, - goLineDown: function (cm) { return cm.moveV(1, "line"); }, - goPageUp: function (cm) { return cm.moveV(-1, "page"); }, - goPageDown: function (cm) { return cm.moveV(1, "page"); }, - goCharLeft: function (cm) { return cm.moveH(-1, "char"); }, - goCharRight: function (cm) { return cm.moveH(1, "char"); }, - goColumnLeft: function (cm) { return cm.moveH(-1, "column"); }, - goColumnRight: function (cm) { return cm.moveH(1, "column"); }, - goWordLeft: function (cm) { return cm.moveH(-1, "word"); }, - goGroupRight: function (cm) { return cm.moveH(1, "group"); }, - goGroupLeft: function (cm) { return cm.moveH(-1, "group"); }, - goWordRight: function (cm) { return cm.moveH(1, "word"); }, - delCharBefore: function (cm) { return cm.deleteH(-1, "char"); }, - delCharAfter: function (cm) { return cm.deleteH(1, "char"); }, - delWordBefore: function (cm) { return cm.deleteH(-1, "word"); }, - delWordAfter: function (cm) { return cm.deleteH(1, "word"); }, - delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); }, - delGroupAfter: function (cm) { return cm.deleteH(1, "group"); }, - indentAuto: function (cm) { return cm.indentSelection("smart"); }, - indentMore: function (cm) { return cm.indentSelection("add"); }, - indentLess: function (cm) { return cm.indentSelection("subtract"); }, - insertTab: function (cm) { return cm.replaceSelection("\t"); }, - insertSoftTab: function (cm) { - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(spaceStr(tabSize - col % tabSize)); - } - cm.replaceSelections(spaces); - }, - defaultTab: function (cm) { - if (cm.somethingSelected()) { cm.indentSelection("add"); } - else { cm.execCommand("insertTab"); } - }, - // Swap the two chars left and right of each selection's head. - // Move cursor behind the two swapped characters afterwards. - // - // Doesn't consider line feeds a character. - // Doesn't scan more than one line above to find a character. - // Doesn't do anything on an empty line. - // Doesn't do anything with non-empty selections. - transposeChars: function (cm) { return runInOp(cm, function () { - var ranges = cm.listSelections(), newSel = []; - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) { continue } - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); } - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), - Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) { - cur = new Pos(cur.line, 1); - cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() + - prev.charAt(prev.length - 1), - Pos(cur.line - 1, prev.length - 1), cur, "+transpose"); - } - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); }, - newlineAndIndent: function (cm) { return runInOp(cm, function () { - var sels = cm.listSelections(); - for (var i = sels.length - 1; i >= 0; i--) - { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); } - sels = cm.listSelections(); - for (var i$1 = 0; i$1 < sels.length; i$1++) - { cm.indentLine(sels[i$1].from().line, null, true); } - ensureCursorVisible(cm); - }); }, - openLine: function (cm) { return cm.replaceSelection("\n", "start"); }, - toggleOverwrite: function (cm) { return cm.toggleOverwrite(); } - }; - - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) { lineN = lineNo(visual); } - return endOfLine(true, cm, visual, lineN, 1) - } - function lineEnd(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLineEnd(line); - if (visual != line) { lineN = lineNo(visual); } - return endOfLine(true, cm, line, lineN, -1) - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line, cm.doc.direction); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(start.ch, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky) - } - return start - } - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) { return false } - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, done = false; - try { - if (cm.isReadOnly()) { cm.state.suppressEdits = true; } - if (dropShift) { cm.display.shift = false; } - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done - } - - function lookupKeyForEditor(cm, name, handle) { - for (var i = 0; i < cm.state.keyMaps.length; i++) { - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); - if (result) { return result } - } - return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) - || lookupKey(name, cm.options.keyMap, handle, cm) - } - - // Note that, despite the name, this function is also used to check - // for bound mouse clicks. - - var stopSeq = new Delayed; - - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) { return "handled" } - if (/\'$/.test(name)) - { cm.state.keySeq = null; } - else - { stopSeq.set(50, function () { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); } - if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true } - } - return dispatchKeyInner(cm, name, e, handle) - } - - function dispatchKeyInner(cm, name, e, handle) { - var result = lookupKeyForEditor(cm, name, handle); - - if (result == "multi") - { cm.state.keySeq = name; } - if (result == "handled") - { signalLater(cm, "keyHandled", cm, name, e); } - - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - - return !!result - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) { return false } - - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); }) - || dispatchKey(cm, name, e, function (b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - { return doHandleBinding(cm, b) } - }) - } else { - return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }) - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); }) - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) { return } - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) { e.returnValue = false; } - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - { cm.replaceSelection("", null, "cut"); } - } - if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand) - { document.execCommand("cut"); } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) - { showCrossHair(cm); } - } - - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - - function onKeyUp(e) { - if (e.keyCode == 16) { this.doc.sel.shift = false; } - signalDOMEvent(this, e); - } - - function onKeyPress(e) { - var cm = this; - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { return } - var keyCode = e.keyCode, charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return} - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) { return } - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - // Some browsers fire keypress events for backspace - if (ch == "\x08") { return } - if (handleCharBinding(cm, e, ch)) { return } - cm.display.input.onKeyPress(e); - } - - var DOUBLECLICK_DELAY = 400; - - var PastClick = function(time, pos, button) { - this.time = time; - this.pos = pos; - this.button = button; - }; - - PastClick.prototype.compare = function (time, pos, button) { - return this.time + DOUBLECLICK_DELAY > time && - cmp(pos, this.pos) == 0 && button == this.button - }; - - var lastClick, lastDoubleClick; - function clickRepeat(pos, button) { - var now = +new Date; - if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) { - lastClick = lastDoubleClick = null; - return "triple" - } else if (lastClick && lastClick.compare(now, pos, button)) { - lastDoubleClick = new PastClick(now, pos, button); - lastClick = null; - return "double" - } else { - lastClick = new PastClick(now, pos, button); - lastDoubleClick = null; - return "single" - } - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, display = cm.display; - if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return } - display.input.ensurePolled(); - display.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function () { return display.scroller.draggable = true; }, 100); - } - return - } - if (clickInGutter(cm, e)) { return } - var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single"; - window.focus(); - - // #3261: make sure, that we're not starting a second selection - if (button == 1 && cm.state.selectingText) - { cm.state.selectingText(e); } - - if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return } - - if (button == 1) { - if (pos) { leftButtonDown(cm, pos, repeat, e); } - else if (e_target(e) == display.scroller) { e_preventDefault(e); } - } else if (button == 2) { - if (pos) { extendSelection(cm.doc, pos); } - setTimeout(function () { return display.input.focus(); }, 20); - } else if (button == 3) { - if (captureRightClick) { cm.display.input.onContextMenu(e); } - else { delayBlurEvent(cm); } - } - } - - function handleMappedButton(cm, button, pos, repeat, event) { - var name = "Click"; - if (repeat == "double") { name = "Double" + name; } - else if (repeat == "triple") { name = "Triple" + name; } - name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name; - - return dispatchKey(cm, addModifierNames(name, event), event, function (bound) { - if (typeof bound == "string") { bound = commands[bound]; } - if (!bound) { return false } - var done = false; - try { - if (cm.isReadOnly()) { cm.state.suppressEdits = true; } - done = bound(cm, pos) != Pass; - } finally { - cm.state.suppressEdits = false; - } - return done - }) - } - - function configureMouse(cm, repeat, event) { - var option = cm.getOption("configureMouse"); - var value = option ? option(cm, repeat, event) : {}; - if (value.unit == null) { - var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey; - value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line"; - } - if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; } - if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; } - if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); } - return value - } - - function leftButtonDown(cm, pos, repeat, event) { - if (ie) { setTimeout(bind(ensureFocus, cm), 0); } - else { cm.curOp.focus = activeElt(); } - - var behavior = configureMouse(cm, repeat, event); - - var sel = cm.doc.sel, contained; - if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() && - repeat == "single" && (contained = sel.contains(pos)) > -1 && - (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) && - (cmp(contained.to(), pos) > 0 || pos.xRel < 0)) - { leftButtonStartDrag(cm, event, pos, behavior); } - else - { leftButtonSelect(cm, event, pos, behavior); } - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, event, pos, behavior) { - var display = cm.display, moved = false; - var dragEnd = operation(cm, function (e) { - if (webkit) { display.scroller.draggable = false; } - cm.state.draggingText = false; - off(display.wrapper.ownerDocument, "mouseup", dragEnd); - off(display.wrapper.ownerDocument, "mousemove", mouseMove); - off(display.scroller, "dragstart", dragStart); - off(display.scroller, "drop", dragEnd); - if (!moved) { - e_preventDefault(e); - if (!behavior.addNew) - { extendSelection(cm.doc, pos, null, null, behavior.extend); } - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit || ie && ie_version == 9) - { setTimeout(function () {display.wrapper.ownerDocument.body.focus(); display.input.focus();}, 20); } - else - { display.input.focus(); } - } - }); - var mouseMove = function(e2) { - moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10; - }; - var dragStart = function () { return moved = true; }; - // Let the drag handler handle this. - if (webkit) { display.scroller.draggable = true; } - cm.state.draggingText = dragEnd; - dragEnd.copy = !behavior.moveOnDrag; - // IE's approach to draggable - if (display.scroller.dragDrop) { display.scroller.dragDrop(); } - on(display.wrapper.ownerDocument, "mouseup", dragEnd); - on(display.wrapper.ownerDocument, "mousemove", mouseMove); - on(display.scroller, "dragstart", dragStart); - on(display.scroller, "drop", dragEnd); - - delayBlurEvent(cm); - setTimeout(function () { return display.input.focus(); }, 20); - } - - function rangeForUnit(cm, pos, unit) { - if (unit == "char") { return new Range(pos, pos) } - if (unit == "word") { return cm.findWordAt(pos) } - if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) } - var result = unit(cm, pos); - return new Range(result.from, result.to) - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, event, start, behavior) { - var display = cm.display, doc = cm.doc; - e_preventDefault(event); - - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; - if (behavior.addNew && !behavior.extend) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) - { ourRange = ranges[ourIndex]; } - else - { ourRange = new Range(start, start); } - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - - if (behavior.unit == "rectangle") { - if (!behavior.addNew) { ourRange = new Range(start, start); } - start = posFromMouse(cm, event, true, true); - ourIndex = -1; - } else { - var range$$1 = rangeForUnit(cm, start, behavior.unit); - if (behavior.extend) - { ourRange = extendRange(ourRange, range$$1.anchor, range$$1.head, behavior.extend); } - else - { ourRange = range$$1; } - } - - if (!behavior.addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex), - {scroll: false, origin: "*mouse"}); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) { - setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0), - {scroll: false, origin: "*mouse"}); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) { return } - lastPos = pos; - - if (behavior.unit == "rectangle") { - var ranges = [], tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); - line <= end; line++) { - var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); - if (left == right) - { ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); } - else if (text.length > leftPos) - { ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); } - } - if (!ranges.length) { ranges.push(new Range(start, start)); } - setSelection(doc, normalizeSelection(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), - {origin: "*mouse", scroll: false}); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var range$$1 = rangeForUnit(cm, pos, behavior.unit); - var anchor = oldRange.anchor, head; - if (cmp(range$$1.anchor, anchor) > 0) { - head = range$$1.head; - anchor = minPos(oldRange.from(), range$$1.anchor); - } else { - head = range$$1.anchor; - anchor = maxPos(oldRange.to(), range$$1.head); - } - var ranges$1 = startSel.ranges.slice(0); - ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head)); - setSelection(doc, normalizeSelection(cm, ranges$1, ourIndex), sel_mouse); - } - } - - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, behavior.unit == "rectangle"); - if (!cur) { return } - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - { setTimeout(operation(cm, function () {if (counter == curCount) { extend(e); }}), 150); } - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) { setTimeout(operation(cm, function () { - if (counter != curCount) { return } - display.scroller.scrollTop += outside; - extend(e); - }), 50); } - } - } - - function done(e) { - cm.state.selectingText = false; - counter = Infinity; - // If e is null or undefined we interpret this as someone trying - // to explicitly cancel the selection rather than the user - // letting go of the mouse button. - if (e) { - e_preventDefault(e); - display.input.focus(); - } - off(display.wrapper.ownerDocument, "mousemove", move); - off(display.wrapper.ownerDocument, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - var move = operation(cm, function (e) { - if (e.buttons === 0 || !e_button(e)) { done(e); } - else { extend(e); } - }); - var up = operation(cm, done); - cm.state.selectingText = up; - on(display.wrapper.ownerDocument, "mousemove", move); - on(display.wrapper.ownerDocument, "mouseup", up); - } - - // Used when mouse-selecting to adjust the anchor to the proper side - // of a bidi jump depending on the visual position of the head. - function bidiSimplify(cm, range$$1) { - var anchor = range$$1.anchor; - var head = range$$1.head; - var anchorLine = getLine(cm.doc, anchor.line); - if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range$$1 } - var order = getOrder(anchorLine); - if (!order) { return range$$1 } - var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index]; - if (part.from != anchor.ch && part.to != anchor.ch) { return range$$1 } - var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1); - if (boundary == 0 || boundary == order.length) { return range$$1 } - - // Compute the relative visual position of the head compared to the - // anchor (<0 is to the left, >0 to the right) - var leftSide; - if (head.line != anchor.line) { - leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0; - } else { - var headIndex = getBidiPartAt(order, head.ch, head.sticky); - var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1); - if (headIndex == boundary - 1 || headIndex == boundary) - { leftSide = dir < 0; } - else - { leftSide = dir > 0; } - } - - var usePart = order[boundary + (leftSide ? -1 : 0)]; - var from = leftSide == (usePart.level == 1); - var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before"; - return anchor.ch == ch && anchor.sticky == sticky ? range$$1 : new Range(new Pos(anchor.line, ch, sticky), head) - } - - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent) { - var mX, mY; - if (e.touches) { - mX = e.touches[0].clientX; - mY = e.touches[0].clientY; - } else { - try { mX = e.clientX; mY = e.clientY; } - catch(e) { return false } - } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) { return false } - if (prevent) { e_preventDefault(e); } - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) { return e_defaultPrevented(e) } - mY -= lineBox.top - display.viewOffset; - - for (var i = 0; i < cm.display.gutterSpecs.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.display.gutterSpecs[i]; - signal(cm, type, cm, line, gutter.className, e); - return e_defaultPrevented(e) - } - } - } - - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true) - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return } - if (signalDOMEvent(cm, e, "contextmenu")) { return } - if (!captureRightClick) { cm.display.input.onContextMenu(e); } - } - - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) { return false } - return gutterEvent(cm, e, "gutterContextMenu", false) - } - - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + - cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - - var Init = {toString: function(){return "CodeMirror.Init"}}; - - var defaults = {}; - var optionHandlers = {}; - - function defineOptions(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) { optionHandlers[name] = - notOnInit ? function (cm, val, old) {if (old != Init) { handle(cm, val, old); }} : handle; } - } - - CodeMirror.defineOption = option; - - // Passed to option handlers when there is no old value. - CodeMirror.Init = Init; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function (cm, val) { return cm.setValue(val); }, true); - option("mode", null, function (cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function (cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - - option("lineSeparator", null, function (cm, val) { - cm.doc.lineSep = val; - if (!val) { return } - var newBreaks = [], lineNo = cm.doc.first; - cm.doc.iter(function (line) { - for (var pos = 0;;) { - var found = line.text.indexOf(val, pos); - if (found == -1) { break } - pos = found + val.length; - newBreaks.push(Pos(lineNo, found)); - } - lineNo++; - }); - for (var i = newBreaks.length - 1; i >= 0; i--) - { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); } - }); - option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != Init) { cm.refresh(); } - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function () { - throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME - }, true); - option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true); - option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true); - option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function (cm) { - themeChanged(cm); - updateGutters(cm); - }, true); - option("keyMap", "default", function (cm, val, old) { - var next = getKeyMap(val); - var prev = old != Init && getKeyMap(old); - if (prev && prev.detach) { prev.detach(cm, next); } - if (next.attach) { next.attach(cm, prev || null); } - }); - option("extraKeys", null); - option("configureMouse", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function (cm, val) { - cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers); - updateGutters(cm); - }, true); - option("fixedGutter", true, function (cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function (cm) { return updateScrollbars(cm); }, true); - option("scrollbarStyle", "native", function (cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function (cm, val) { - cm.display.gutterSpecs = getGutters(cm.options.gutters, val); - updateGutters(cm); - }, true); - option("firstLineNumber", 1, updateGutters, true); - option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - option("pasteLinesPerSelection", true); - option("selectionsMayTouch", false); - - option("readOnly", false, function (cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - } - cm.display.input.readOnlyChanged(val); - }); - - option("screenReaderLabel", null, function (cm, val) { - val = (val === '') ? null : val; - cm.display.input.screenReaderLabelChanged(val); - }); - - option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true); - option("dragDrop", true, dragDropChanged); - option("allowDropFileTypes", null); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function (cm, val) { return cm.doc.history.undoDepth = val; }); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function (cm, val) { - if (!val) { cm.display.input.resetPosition(); } - }); - - option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; }); - option("autofocus", null); - option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true); - option("phrases", null); - } - - function dragDropChanged(cm, value, old) { - var wasOn = old && old != Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.enter); - toggle(cm.display.scroller, "dragover", funcs.over); - toggle(cm.display.scroller, "dragleave", funcs.leave); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function () { return updateScrollbars(cm); }, 100); - } - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - var this$1 = this; - - if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) } - - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - - var doc = options.value; - if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); } - else if (options.mode) { doc.modeOption = options.mode; } - this.doc = doc; - - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input, options); - display.wrapper.CodeMirror = this; - themeChanged(this); - if (options.lineWrapping) - { this.display.wrapper.className += " CodeMirror-wrap"; } - initScrollbars(this); - - this.state = { - keyMaps: [], // stores maps added by addKeyMap - overlays: [], // highlighting overlays, as added by addOverlay - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode - pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll - selectingText: false, - draggingText: false, - highlight: new Delayed(), // stores highlight worker timeout - keySeq: null, // Unfinished key sequence - specialChars: null - }; - - if (options.autofocus && !mobile) { display.input.focus(); } - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); } - - registerEventHandlers(this); - ensureGlobalHandlers(); - - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - - if ((options.autofocus && !mobile) || this.hasFocus()) - { setTimeout(bind(onFocus, this), 20); } - else - { onBlur(this); } - - for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt)) - { optionHandlers[opt](this$1, options[opt], Init); } } - maybeUpdateLineNumberWidth(this); - if (options.finishInit) { options.finishInit(this); } - for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this$1); } - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") - { display.lineDiv.style.textRendering = "auto"; } - } - - // The default configuration options. - CodeMirror.defaults = defaults; - // Functions to run when options are changed. - CodeMirror.optionHandlers = optionHandlers; - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) - { on(d.scroller, "dblclick", operation(cm, function (e) { - if (signalDOMEvent(cm, e)) { return } - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) { return } - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); } - else - { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, e) || e_preventDefault(e); }); } - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); }); - on(d.input.getField(), "contextmenu", function (e) { - if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); } - }); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, prevTouch = {end: 0}; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date; - } - } - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) { return false } - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1 - } - function farAway(touch, other) { - if (other.left == null) { return true } - var dx = other.left - touch.left, dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20 - } - on(d.scroller, "touchstart", function (e) { - if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) { - d.input.ensurePolled(); - clearTimeout(touchFinished); - var now = +new Date; - d.activeTouch = {start: now, moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null}; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function () { - if (d.activeTouch) { d.activeTouch.moved = true; } - }); - on(d.scroller, "touchend", function (e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && - !touch.moved && new Date - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), range; - if (!touch.prev || farAway(touch, touch.prev)) // Single tap - { range = new Range(pos, pos); } - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap - { range = cm.findWordAt(pos); } - else // Triple tap - { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); } - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function () { - if (d.scroller.clientHeight) { - updateScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); - - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); }); - on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); }); - - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); - - d.dragFunctions = { - enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }}, - over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }}, - start: function (e) { return onDragStart(cm, e); }, - drop: operation(cm, onDrop), - leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }} - }; - - var inp = d.input.getField(); - on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", function (e) { return onFocus(cm, e); }); - on(inp, "blur", function (e) { return onBlur(cm, e); }); - } - - var initHooks = []; - CodeMirror.defineInitHook = function (f) { return initHooks.push(f); }; - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, state; - if (how == null) { how = "add"; } - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) { how = "prev"; } - else { state = getContextBefore(cm, n).state; } - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) { line.stateAfter = null; } - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) { return } - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) { indentation = countColumn(getLine(doc, n-1).text, null, tabSize); } - else { indentation = 0; } - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var indentString = "", pos = 0; - if (cm.options.indentWithTabs) - { for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} } - if (pos < indentation) { indentString += spaceStr(indentation - pos); } - - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i$1 = 0; i$1 < doc.sel.ranges.length; i$1++) { - var range = doc.sel.ranges[i$1]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos$1 = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i$1, new Range(pos$1, pos$1)); - break - } - } - } - } - - // This will be set to a {lineWise: bool, text: [string]} object, so - // that, when pasting, we know what kind of selections the copied - // text was made out of. - var lastCopied = null; - - function setLastCopied(newLastCopied) { - lastCopied = newLastCopied; - } - - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) { sel = doc.sel; } - - var recent = +new Date - 200; - var paste = origin == "paste" || cm.state.pasteIncoming > recent; - var textLines = splitLinesAuto(inserted), multiPaste = null; - // When pasting N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.text.join("\n") == inserted) { - if (sel.ranges.length % lastCopied.text.length == 0) { - multiPaste = []; - for (var i = 0; i < lastCopied.text.length; i++) - { multiPaste.push(doc.splitLines(lastCopied.text[i])); } - } - } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) { - multiPaste = map(textLines, function (l) { return [l]; }); - } - } - - var updateInput = cm.curOp.updateInput; - // Normal behavior is to insert the new text into every selection - for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) { - var range$$1 = sel.ranges[i$1]; - var from = range$$1.from(), to = range$$1.to(); - if (range$$1.empty()) { - if (deleted && deleted > 0) // Handle deletion - { from = Pos(from.line, from.ch - deleted); } - else if (cm.state.overwrite && !paste) // Handle overwrite - { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); } - else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == inserted) - { from = to = Pos(from.line, 0); } - } - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")}; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) - { triggerElectric(cm, inserted); } - - ensureCursorVisible(cm); - if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; } - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = -1; - } - - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("Text"); - if (pasted) { - e.preventDefault(); - if (!cm.isReadOnly() && !cm.options.disableInput) - { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); } - return true - } - } - - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) { return } - var sel = cm.doc.sel; - - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range$$1 = sel.ranges[i]; - if (range$$1.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range$$1.head.line)) { continue } - var mode = cm.getModeAt(range$$1.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) - { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range$$1.head.line, "smart"); - break - } } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range$$1.head.line).text.slice(0, range$$1.head.ch))) - { indented = indentLine(cm, range$$1.head.line, "smart"); } - } - if (indented) { signalLater(cm, "electricInput", cm, range$$1.head.line); } - } - } - - function copyableRanges(cm) { - var text = [], ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return {text: text, ranges: ranges} - } - - function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) { - field.setAttribute("autocorrect", autocorrect ? "" : "off"); - field.setAttribute("autocapitalize", autocapitalize ? "" : "off"); - field.setAttribute("spellcheck", !!spellcheck); - } - - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) { te.style.width = "1000px"; } - else { te.setAttribute("wrap", "off"); } - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) { te.style.border = "1px solid black"; } - disableBrowserMagic(te); - return div - } - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - function addEditorMethods(CodeMirror) { - var optionHandlers = CodeMirror.optionHandlers; - - var helpers = CodeMirror.helpers = {}; - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") { return } - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - { operation(this, optionHandlers[option])(this, value, old); } - signal(this, "optionChange", this, option); - }, - - getOption: function(option) {return this.options[option]}, - getDoc: function() {return this.doc}, - - addKeyMap: function(map$$1, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map$$1)); - }, - removeKeyMap: function(map$$1) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - { if (maps[i] == map$$1 || maps[i].name == map$$1) { - maps.splice(i, 1); - return true - } } - }, - - addOverlay: methodOp(function(spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) { throw new Error("Overlays may not be stateful.") } - insertSorted(this.state.overlays, - {mode: mode, modeSpec: spec, opaque: options && options.opaque, - priority: (options && options.priority) || 0}, - function (overlay) { return overlay.priority; }); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function(spec) { - var this$1 = this; - - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this$1.state.modeGen++; - regChange(this$1); - return - } - } - }), - - indentLine: methodOp(function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) { dir = this.options.smartIndent ? "smart" : "prev"; } - else { dir = dir ? "add" : "subtract"; } - } - if (isLine(this.doc, n)) { indentLine(this, n, dir, aggressive); } - }), - indentSelection: methodOp(function(how) { - var this$1 = this; - - var ranges = this.doc.sel.ranges, end = -1; - for (var i = 0; i < ranges.length; i++) { - var range$$1 = ranges[i]; - if (!range$$1.empty()) { - var from = range$$1.from(), to = range$$1.to(); - var start = Math.max(end, from.line); - end = Math.min(this$1.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) - { indentLine(this$1, j, how); } - var newRanges = this$1.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) - { replaceOneSelection(this$1.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); } - } else if (range$$1.head.line > end) { - indentLine(this$1, range$$1.head.line, how, true); - end = range$$1.head.line; - if (i == this$1.doc.sel.primIndex) { ensureCursorVisible(this$1); } - } - } - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - return takeToken(this, pos, precise) - }, - - getLineTokens: function(line, precise) { - return takeToken(this, Pos(line), precise, true) - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - var type; - if (ch == 0) { type = styles[2]; } - else { for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) { after = mid; } - else if (styles[mid * 2 + 1] < ch) { before = mid + 1; } - else { type = styles[mid * 2 + 2]; break } - } } - var cut = type ? type.indexOf("overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1) - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) { return mode } - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0] - }, - - getHelpers: function(pos, type) { - var this$1 = this; - - var found = []; - if (!helpers.hasOwnProperty(type)) { return found } - var help = helpers[type], mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) { found.push(help[mode[type]]); } - } else if (mode[type]) { - for (var i = 0; i < mode[type].length; i++) { - var val = help[mode[type][i]]; - if (val) { found.push(val); } - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i$1 = 0; i$1 < help._global.length; i$1++) { - var cur = help._global[i$1]; - if (cur.pred(mode, this$1) && indexOf(found, cur.val) == -1) - { found.push(cur.val); } - } - return found - }, - - getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getContextBefore(this, line + 1, precise).state - }, - - cursorCoords: function(start, mode) { - var pos, range$$1 = this.doc.sel.primary(); - if (start == null) { pos = range$$1.head; } - else if (typeof start == "object") { pos = clipPos(this.doc, start); } - else { pos = start ? range$$1.from() : range$$1.to(); } - return cursorCoords(this, pos, mode || "page") - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page") - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top) - }, - - lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset) - }, - heightAtLine: function(line, mode, includeWidgets) { - var end = false, lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) { line = this.doc.first; } - else if (line > last) { line = last; end = true; } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top + - (end ? this.doc.height - heightAtLine(lineObj) : 0) - }, - - defaultTextHeight: function() { return textHeight(this.display) }, - defaultCharWidth: function() { return charWidth(this.display) }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo}}, - - addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - { top = pos.top - node.offsetHeight; } - else if (pos.bottom + node.offsetHeight <= vspace) - { top = pos.bottom; } - if (left + node.offsetWidth > hspace) - { left = hspace - node.offsetWidth; } - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") { left = 0; } - else if (horiz == "middle") { left = (display.sizer.clientWidth - node.offsetWidth) / 2; } - node.style.left = left + "px"; - } - if (scroll) - { scrollIntoView(this, {left: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); } - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - triggerOnMouseDown: methodOp(onMouseDown), - - execCommand: function(cmd) { - if (commands.hasOwnProperty(cmd)) - { return commands[cmd].call(null, this) } - }, - - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), - - findPosH: function(from, amount, unit, visually) { - var this$1 = this; - - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - var cur = clipPos(this.doc, from); - for (var i = 0; i < amount; ++i) { - cur = findPosH(this$1.doc, cur, dir, unit, visually); - if (cur.hitSide) { break } - } - return cur - }, - - moveH: methodOp(function(dir, unit) { - var this$1 = this; - - this.extendSelectionsBy(function (range$$1) { - if (this$1.display.shift || this$1.doc.extend || range$$1.empty()) - { return findPosH(this$1.doc, range$$1.head, dir, unit, this$1.options.rtlMoveVisually) } - else - { return dir < 0 ? range$$1.from() : range$$1.to() } - }, sel_move); - }), - - deleteH: methodOp(function(dir, unit) { - var sel = this.doc.sel, doc = this.doc; - if (sel.somethingSelected()) - { doc.replaceSelection("", null, "+delete"); } - else - { deleteNearSelection(this, function (range$$1) { - var other = findPosH(doc, range$$1.head, dir, unit, false); - return dir < 0 ? {from: other, to: range$$1.head} : {from: range$$1.head, to: other} - }); } - }), - - findPosV: function(from, amount, unit, goalColumn) { - var this$1 = this; - - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - var cur = clipPos(this.doc, from); - for (var i = 0; i < amount; ++i) { - var coords = cursorCoords(this$1, cur, "div"); - if (x == null) { x = coords.left; } - else { coords.left = x; } - cur = findPosV(this$1, coords, dir, unit); - if (cur.hitSide) { break } - } - return cur - }, - - moveV: methodOp(function(dir, unit) { - var this$1 = this; - - var doc = this.doc, goals = []; - var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function (range$$1) { - if (collapse) - { return dir < 0 ? range$$1.from() : range$$1.to() } - var headPos = cursorCoords(this$1, range$$1.head, "div"); - if (range$$1.goalColumn != null) { headPos.left = range$$1.goalColumn; } - goals.push(headPos.left); - var pos = findPosV(this$1, headPos, dir, unit); - if (unit == "page" && range$$1 == doc.sel.primary()) - { addToScrollTop(this$1, charCoords(this$1, pos, "div").top - headPos.top); } - return pos - }, sel_move); - if (goals.length) { for (var i = 0; i < doc.sel.ranges.length; i++) - { doc.sel.ranges[i].goalColumn = goals[i]; } } - }), - - // Find the word at the given position (as returned by coordsChar). - findWordAt: function(pos) { - var doc = this.doc, line = getLine(doc, pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; } - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) - ? function (ch) { return isWordChar(ch, helper); } - : /\s/.test(startChar) ? function (ch) { return /\s/.test(ch); } - : function (ch) { return (!/\s/.test(ch) && !isWordChar(ch)); }; - while (start > 0 && check(line.charAt(start - 1))) { --start; } - while (end < line.length && check(line.charAt(end))) { ++end; } - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)) - }, - - toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) { return } - if (this.state.overwrite = !this.state.overwrite) - { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); } - else - { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); } - - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function() { return this.display.input.getField() == activeElt() }, - isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) }, - - scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }), - getScrollInfo: function() { - var scroller = this.display.scroller; - return {left: scroller.scrollLeft, top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), clientWidth: displayWidth(this)} - }, - - scrollIntoView: methodOp(function(range$$1, margin) { - if (range$$1 == null) { - range$$1 = {from: this.doc.sel.primary().head, to: null}; - if (margin == null) { margin = this.options.cursorScrollMargin; } - } else if (typeof range$$1 == "number") { - range$$1 = {from: Pos(range$$1, 0), to: null}; - } else if (range$$1.from == null) { - range$$1 = {from: range$$1, to: null}; - } - if (!range$$1.to) { range$$1.to = range$$1.from; } - range$$1.margin = margin || 0; - - if (range$$1.from.line != null) { - scrollToRange(this, range$$1); - } else { - scrollToCoordsRange(this, range$$1.from, range$$1.to, range$$1.margin); - } - }), - - setSize: methodOp(function(width, height) { - var this$1 = this; - - var interpret = function (val) { return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; }; - if (width != null) { this.display.wrapper.style.width = interpret(width); } - if (height != null) { this.display.wrapper.style.height = interpret(height); } - if (this.options.lineWrapping) { clearLineMeasurementCache(this); } - var lineNo$$1 = this.display.viewFrom; - this.doc.iter(lineNo$$1, this.display.viewTo, function (line) { - if (line.widgets) { for (var i = 0; i < line.widgets.length; i++) - { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo$$1, "widget"); break } } } - ++lineNo$$1; - }); - this.curOp.forceUpdate = true; - signal(this, "refresh", this); - }), - - operation: function(f){return runInOp(this, f)}, - startOperation: function(){return startOperation(this)}, - endOperation: function(){return endOperation(this)}, - - refresh: methodOp(function() { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this.display); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) - { estimateLineHeights(this); } - signal(this, "refresh", this); - }), - - swapDoc: methodOp(function(doc) { - var old = this.doc; - old.cm = null; - // Cancel the current text selection if any (#5821) - if (this.state.selectingText) { this.state.selectingText(); } - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - scrollToCoords(this, doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old - }), - - phrase: function(phraseText) { - var phrases = this.options.phrases; - return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText - }, - - getInputField: function(){return this.display.input.getField()}, - getWrapperElement: function(){return this.display.wrapper}, - getScrollerElement: function(){return this.display.scroller}, - getGutterElement: function(){return this.display.gutters} - }; - eventMixin(CodeMirror); - - CodeMirror.registerHelper = function(type, name, value) { - if (!helpers.hasOwnProperty(type)) { helpers[type] = CodeMirror[type] = {_global: []}; } - helpers[type][name] = value; - }; - CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { - CodeMirror.registerHelper(type, name, value); - helpers[type]._global.push({pred: predicate, val: value}); - }; - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "char", "column" (like char, but doesn't - // cross line boundaries), "word" (across next word), or "group" (to - // the start of next group of word or non-word-non-whitespace - // chars). The visually param controls whether, in right-to-left - // text, direction 1 means to move towards the next index in the - // string, or towards the character to the right of the current - // position. The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var oldPos = pos; - var origDir = dir; - var lineObj = getLine(doc, pos.line); - var lineDir = visually && doc.direction == "rtl" ? -dir : dir; - function findNextLine() { - var l = pos.line + lineDir; - if (l < doc.first || l >= doc.first + doc.size) { return false } - pos = new Pos(l, pos.ch, pos.sticky); - return lineObj = getLine(doc, l) - } - function moveOnce(boundToLine) { - var next; - if (visually) { - next = moveVisually(doc.cm, lineObj, pos, dir); - } else { - next = moveLogically(lineObj, pos, dir); - } - if (next == null) { - if (!boundToLine && findNextLine()) - { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); } - else - { return false } - } else { - pos = next; - } - return true - } - - if (unit == "char") { - moveOnce(); - } else if (unit == "column") { - moveOnce(true); - } else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) { break } - var cur = lineObj.text.charAt(pos.ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" - : group && cur == "\n" ? "n" - : !group || /\s/.test(cur) ? null - : "p"; - if (group && !first && !type) { type = "s"; } - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce(); pos.sticky = "after";} - break - } - - if (type) { sawType = type; } - if (dir > 0 && !moveOnce(!first)) { break } - } - } - var result = skipAtomic(doc, pos, oldPos, origDir, true); - if (equalCursorPos(oldPos, result)) { result.hitSide = true; } - return result - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3); - y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount; - - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - var target; - for (;;) { - target = coordsChar(cm, x, y); - if (!target.outside) { break } - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break } - y += dir * 5; - } - return target - } - - // CONTENTEDITABLE INPUT STYLE - - var ContentEditableInput = function(cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.composing = null; - this.gracePeriod = false; - this.readDOMTimeout = null; - }; - - ContentEditableInput.prototype.init = function (display) { - var this$1 = this; - - var input = this, cm = input.cm; - var div = input.div = display.lineDiv; - disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize); - - on(div, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } - // IE doesn't fire input events, so we schedule a read for the pasted content in this way - if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); } - }); - - on(div, "compositionstart", function (e) { - this$1.composing = {data: e.data, done: false}; - }); - on(div, "compositionupdate", function (e) { - if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; } - }); - on(div, "compositionend", function (e) { - if (this$1.composing) { - if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); } - this$1.composing.done = true; - } - }); - - on(div, "touchstart", function () { return input.forceCompositionEnd(); }); - - on(div, "input", function () { - if (!this$1.composing) { this$1.readFromDOMSoon(); } - }); - - function onCopyCut(e) { - if (signalDOMEvent(cm, e)) { return } - if (cm.somethingSelected()) { - setLastCopied({lineWise: false, text: cm.getSelections()}); - if (e.type == "cut") { cm.replaceSelection("", null, "cut"); } - } else if (!cm.options.lineWiseCopyCut) { - return - } else { - var ranges = copyableRanges(cm); - setLastCopied({lineWise: true, text: ranges.text}); - if (e.type == "cut") { - cm.operation(function () { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); - } - } - if (e.clipboardData) { - e.clipboardData.clearData(); - var content = lastCopied.text.join("\n"); - // iOS exposes the clipboard API, but seems to discard content inserted into it - e.clipboardData.setData("Text", content); - if (e.clipboardData.getData("Text") == content) { - e.preventDefault(); - return - } - } - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.text.join("\n"); - var hadFocus = document.activeElement; - selectInput(te); - setTimeout(function () { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - if (hadFocus == div) { input.showPrimarySelection(); } - }, 50); - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }; - - ContentEditableInput.prototype.screenReaderLabelChanged = function (label) { - // Label for screenreaders, accessibility - if(label) { - this.div.setAttribute('aria-label', label); - } else { - this.div.removeAttribute('aria-label'); - } - }; - - ContentEditableInput.prototype.prepareSelection = function () { - var result = prepareSelection(this.cm, false); - result.focus = document.activeElement == this.div; - return result - }; - - ContentEditableInput.prototype.showSelection = function (info, takeFocus) { - if (!info || !this.cm.display.view.length) { return } - if (info.focus || takeFocus) { this.showPrimarySelection(); } - this.showMultipleSelections(info); - }; - - ContentEditableInput.prototype.getSelection = function () { - return this.cm.display.wrapper.ownerDocument.getSelection() - }; - - ContentEditableInput.prototype.showPrimarySelection = function () { - var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary(); - var from = prim.from(), to = prim.to(); - - if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) { - sel.removeAllRanges(); - return - } - - var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && - cmp(minPos(curAnchor, curFocus), from) == 0 && - cmp(maxPos(curAnchor, curFocus), to) == 0) - { return } - - var view = cm.display.view; - var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) || - {node: view[0].measure.map[2], offset: 0}; - var end = to.line < cm.display.viewTo && posToDOM(cm, to); - if (!end) { - var measure = view[view.length - 1].measure; - var map$$1 = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = {node: map$$1[map$$1.length - 1], offset: map$$1[map$$1.length - 2] - map$$1[map$$1.length - 3]}; - } - - if (!start || !end) { - sel.removeAllRanges(); - return - } - - var old = sel.rangeCount && sel.getRangeAt(0), rng; - try { rng = range(start.node, start.offset, end.offset, end.node); } - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - if (!gecko && cm.state.focused) { - sel.collapse(start.node, start.offset); - if (!rng.collapsed) { - sel.removeAllRanges(); - sel.addRange(rng); - } - } else { - sel.removeAllRanges(); - sel.addRange(rng); - } - if (old && sel.anchorNode == null) { sel.addRange(old); } - else if (gecko) { this.startGracePeriod(); } - } - this.rememberSelection(); - }; - - ContentEditableInput.prototype.startGracePeriod = function () { - var this$1 = this; - - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function () { - this$1.gracePeriod = false; - if (this$1.selectionChanged()) - { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); } - }, 20); - }; - - ContentEditableInput.prototype.showMultipleSelections = function (info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }; - - ContentEditableInput.prototype.rememberSelection = function () { - var sel = this.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; - }; - - ContentEditableInput.prototype.selectionInEditor = function () { - var sel = this.getSelection(); - if (!sel.rangeCount) { return false } - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node) - }; - - ContentEditableInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor") { - if (!this.selectionInEditor() || document.activeElement != this.div) - { this.showSelection(this.prepareSelection(), true); } - this.div.focus(); - } - }; - ContentEditableInput.prototype.blur = function () { this.div.blur(); }; - ContentEditableInput.prototype.getField = function () { return this.div }; - - ContentEditableInput.prototype.supportsTouch = function () { return true }; - - ContentEditableInput.prototype.receivedFocus = function () { - var input = this; - if (this.selectionInEditor()) - { this.pollSelection(); } - else - { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); } - - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }; - - ContentEditableInput.prototype.selectionChanged = function () { - var sel = this.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset - }; - - ContentEditableInput.prototype.pollSelection = function () { - if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return } - var sel = this.getSelection(), cm = this.cm; - // On Android Chrome (version 56, at least), backspacing into an - // uneditable block element will put the cursor in that element, - // and then, because it's not editable, hide the virtual keyboard. - // Because Android doesn't allow us to actually detect backspace - // presses in a sane way, this code checks for when that happens - // and simulates a backspace press in this case. - if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) { - this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs}); - this.blur(); - this.focus(); - return - } - if (this.composing) { return } - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) { runInOp(cm, function () { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; } - }); } - }; - - ContentEditableInput.prototype.pollContent = function () { - if (this.readDOMTimeout != null) { - clearTimeout(this.readDOMTimeout); - this.readDOMTimeout = null; - } - - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); - var from = sel.from(), to = sel.to(); - if (from.ch == 0 && from.line > cm.firstLine()) - { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); } - if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine()) - { to = Pos(to.line + 1, 0); } - if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false } - - var fromIndex, fromLine, fromNode; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - fromLine = lineNo(display.view[0].line); - fromNode = display.view[0].node; - } else { - fromLine = lineNo(display.view[fromIndex].line); - fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - var toLine, toNode; - if (toIndex == display.view.length - 1) { - toLine = display.viewTo - 1; - toNode = display.lineDiv.lastChild; - } else { - toLine = lineNo(display.view[toIndex + 1].line) - 1; - toNode = display.view[toIndex + 1].node.previousSibling; - } - - if (!fromNode) { return false } - var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } - else { break } - } - - var cutFront = 0, cutEnd = 0; - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) - { ++cutFront; } - var newBot = lst(newText), oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) - { ++cutEnd; } - // Try to move start of change to start of selection if ambiguous - if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) { - while (cutFront && cutFront > from.ch && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) { - cutFront--; - cutEnd++; - } - } - - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, ""); - newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, ""); - - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true - } - }; - - ContentEditableInput.prototype.ensurePolled = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.reset = function () { - this.forceCompositionEnd(); - }; - ContentEditableInput.prototype.forceCompositionEnd = function () { - if (!this.composing) { return } - clearTimeout(this.readDOMTimeout); - this.composing = null; - this.updateFromDOM(); - this.div.blur(); - this.div.focus(); - }; - ContentEditableInput.prototype.readFromDOMSoon = function () { - var this$1 = this; - - if (this.readDOMTimeout != null) { return } - this.readDOMTimeout = setTimeout(function () { - this$1.readDOMTimeout = null; - if (this$1.composing) { - if (this$1.composing.done) { this$1.composing = null; } - else { return } - } - this$1.updateFromDOM(); - }, 80); - }; - - ContentEditableInput.prototype.updateFromDOM = function () { - var this$1 = this; - - if (this.cm.isReadOnly() || !this.pollContent()) - { runInOp(this.cm, function () { return regChange(this$1.cm); }); } - }; - - ContentEditableInput.prototype.setUneditable = function (node) { - node.contentEditable = "false"; - }; - - ContentEditableInput.prototype.onKeyPress = function (e) { - if (e.charCode == 0 || this.composing) { return } - e.preventDefault(); - if (!this.cm.isReadOnly()) - { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); } - }; - - ContentEditableInput.prototype.readOnlyChanged = function (val) { - this.div.contentEditable = String(val != "nocursor"); - }; - - ContentEditableInput.prototype.onContextMenu = function () {}; - ContentEditableInput.prototype.resetPosition = function () {}; - - ContentEditableInput.prototype.needsContentAttribute = true; - - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) { return null } - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - - var order = getOrder(line, cm.doc.direction), side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result - } - - function isInGutter(node) { - for (var scan = node; scan; scan = scan.parentNode) - { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } } - return false - } - - function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos } - - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false; - function recognizeMarker(id) { return function (marker) { return marker.id == id; } } - function close() { - if (closing) { - text += lineSep; - if (extraLinebreak) { text += lineSep; } - closing = extraLinebreak = false; - } - } - function addText(str) { - if (str) { - close(); - text += str; - } - } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText) { - addText(cmText); - return - } - var markerID = node.getAttribute("cm-marker"), range$$1; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range$$1 = found[0].find(0))) - { addText(getBetween(cm.doc, range$$1.from, range$$1.to).join(lineSep)); } - return - } - if (node.getAttribute("contenteditable") == "false") { return } - var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName); - if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return } - - if (isBlock) { close(); } - for (var i = 0; i < node.childNodes.length; i++) - { walk(node.childNodes[i]); } - - if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; } - if (isBlock) { closing = true; } - } else if (node.nodeType == 3) { - addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " ")); - } - } - for (;;) { - walk(from); - if (from == to) { break } - from = from.nextSibling; - extraLinebreak = false; - } - return text - } - - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) } - node = null; offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) { return null } - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break } - } - } - for (var i = 0; i < cm.display.view.length; i++) { - var lineView = cm.display.view[i]; - if (lineView.node == lineNode) - { return locateNodeInLineView(lineView, node, offset) } - } - } - - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, bad = false; - if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) } - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad) - } - } - - var textNode = node.nodeType == 3 ? node : null, topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) { offset = textNode.nodeValue.length; } - } - while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; } - var measure = lineView.measure, maps = measure.maps; - - function find(textNode, topNode, offset) { - for (var i = -1; i < (maps ? maps.length : 0); i++) { - var map$$1 = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map$$1.length; j += 3) { - var curNode = map$$1[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map$$1[j] + offset; - if (offset < 0 || curNode != textNode) { ch = map$$1[j + (offset ? 1 : 0)]; } - return Pos(line, ch) - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) { return badPos(found, bad) } - - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) - { return badPos(Pos(found.line, found.ch - dist), bad) } - else - { dist += after.textContent.length; } - } - for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) - { return badPos(Pos(found.line, found.ch + dist$1), bad) } - else - { dist$1 += before.textContent.length; } - } - } - - // TEXTAREA INPUT STYLE - - var TextareaInput = function(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; - - TextareaInput.prototype.init = function (display) { - var this$1 = this; - - var input = this, cm = this.cm; - this.createField(display); - var te = this.textarea; - - display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) { te.style.width = "0px"; } - - on(te, "input", function () { - if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; } - input.poll(); - }); - - on(te, "paste", function (e) { - if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return } - - cm.state.pasteIncoming = +new Date; - input.fastPoll(); - }); - - function prepareCopyCut(e) { - if (signalDOMEvent(cm, e)) { return } - if (cm.somethingSelected()) { - setLastCopied({lineWise: false, text: cm.getSelections()}); - } else if (!cm.options.lineWiseCopyCut) { - return - } else { - var ranges = copyableRanges(cm); - setLastCopied({lineWise: true, text: ranges.text}); - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") { cm.state.cutIncoming = +new Date; } - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - - on(display.scroller, "paste", function (e) { - if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return } - if (!te.dispatchEvent) { - cm.state.pasteIncoming = +new Date; - input.focus(); - return - } - - // Pass the `paste` event to the textarea so it's handled by its event listener. - var event = new Event("paste"); - event.clipboardData = e.clipboardData; - te.dispatchEvent(event); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function (e) { - if (!eventInWidget(display, e)) { e_preventDefault(e); } - }); - - on(te, "compositionstart", function () { - var start = cm.getCursor("from"); - if (input.composing) { input.composing.range.clear(); } - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) - }; - }); - on(te, "compositionend", function () { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }; - - TextareaInput.prototype.createField = function (_display) { - // Wraps and hides input textarea - this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - this.textarea = this.wrapper.firstChild; - }; - - TextareaInput.prototype.screenReaderLabelChanged = function (label) { - // Label for screenreaders, accessibility - if(label) { - this.textarea.setAttribute('aria-label', label); - } else { - this.textarea.removeAttribute('aria-label'); - } - }; - - TextareaInput.prototype.prepareSelection = function () { - // Redraw the selection and/or cursor - var cm = this.cm, display = cm.display, doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)); - } - - return result - }; - - TextareaInput.prototype.showSelection = function (drawn) { - var cm = this.cm, display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }; - - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - TextareaInput.prototype.reset = function (typing) { - if (this.contextMenuPending || this.composing) { return } - var cm = this.cm; - if (cm.somethingSelected()) { - this.prevInput = ""; - var content = cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) { selectInput(this.textarea); } - if (ie && ie_version >= 9) { this.hasSelection = content; } - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) { this.hasSelection = null; } - } - }; - - TextareaInput.prototype.getField = function () { return this.textarea }; - - TextareaInput.prototype.supportsTouch = function () { return false }; - - TextareaInput.prototype.focus = function () { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { this.textarea.focus(); } - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } - }; - - TextareaInput.prototype.blur = function () { this.textarea.blur(); }; - - TextareaInput.prototype.resetPosition = function () { - this.wrapper.style.top = this.wrapper.style.left = 0; - }; - - TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); }; - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - TextareaInput.prototype.slowPoll = function () { - var this$1 = this; - - if (this.pollingFast) { return } - this.polling.set(this.cm.options.pollInterval, function () { - this$1.poll(); - if (this$1.cm.state.focused) { this$1.slowPoll(); } - }); - }; - - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - TextareaInput.prototype.fastPoll = function () { - var missed = false, input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) {missed = true; input.polling.set(60, p);} - else {input.pollingFast = false; input.slowPoll();} - } - input.polling.set(20, p); - }; - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - TextareaInput.prototype.poll = function () { - var this$1 = this; - - var cm = this.cm, input = this.textarea, prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || - (hasSelection(input) && !prevInput && !this.composing) || - cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq) - { return false } - - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) { return false } - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || - mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false - } - - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) { prevInput = "\u200b"; } - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") } - } - // Find the part of the input that is actually new - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) { ++same; } - - runInOp(cm, function () { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, this$1.composing ? "*compose" : null); - - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; } - else { this$1.prevInput = text; } - - if (this$1.composing) { - this$1.composing.range.clear(); - this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"), - {className: "CodeMirror-composing"}); - } - }); - return true - }; - - TextareaInput.prototype.ensurePolled = function () { - if (this.pollingFast && this.poll()) { this.pollingFast = false; } - }; - - TextareaInput.prototype.onKeyPress = function () { - if (ie && ie_version >= 9) { this.hasSelection = null; } - this.fastPoll(); - }; - - TextareaInput.prototype.onContextMenu = function (e) { - var input = this, cm = input.cm, display = cm.display, te = input.textarea; - if (input.contextMenuPending) { input.contextMenuPending(); } - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || presto) { return } // Opera is difficult. - - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) - { operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); } - - var oldCSS = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText; - var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect(); - input.wrapper.style.cssText = "position: static"; - te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - var oldScrollY; - if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) { window.scrollTo(null, oldScrollY); } - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) { te.value = input.prevInput = " "; } - input.contextMenuPending = rehide; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - if (input.contextMenuPending != rehide) { return } - input.contextMenuPending = false; - input.wrapper.style.cssText = oldWrapperCSS; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); } - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); } - var i = 0, poll = function () { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && - te.selectionEnd > 0 && input.prevInput == "\u200b") { - operation(cm, selectAll)(cm); - } else if (i++ < 10) { - display.detectingSelectAll = setTimeout(poll, 500); - } else { - display.selForContextMenu = null; - display.input.reset(); - } - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - - if (ie && ie_version >= 9) { prepareSelectAllHack(); } - if (captureRightClick) { - e_stop(e); - var mouseup = function () { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }; - - TextareaInput.prototype.readOnlyChanged = function (val) { - if (!val) { this.reset(); } - this.textarea.disabled = val == "nocursor"; - }; - - TextareaInput.prototype.setUneditable = function () {}; - - TextareaInput.prototype.needsContentAttribute = false; - - function fromTextArea(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) - { options.tabindex = textarea.tabIndex; } - if (!options.placeholder && textarea.placeholder) - { options.placeholder = textarea.placeholder; } - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } - - function save() {textarea.value = cm.getValue();} - - var realSubmit; - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form; - realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function () { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch(e) {} - } - } - - options.finishInit = function (cm) { - cm.save = save; - cm.getTextArea = function () { return textarea; }; - cm.toTextArea = function () { - cm.toTextArea = isNaN; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function") - { textarea.form.submit = realSubmit; } - } - }; - }; - - textarea.style.display = "none"; - var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); }, - options); - return cm - } - - function addLegacyProps(CodeMirror) { - CodeMirror.off = off; - CodeMirror.on = on; - CodeMirror.wheelEventPixels = wheelEventPixels; - CodeMirror.Doc = Doc; - CodeMirror.splitLines = splitLinesAuto; - CodeMirror.countColumn = countColumn; - CodeMirror.findColumn = findColumn; - CodeMirror.isWordChar = isWordCharBasic; - CodeMirror.Pass = Pass; - CodeMirror.signal = signal; - CodeMirror.Line = Line; - CodeMirror.changeEnd = changeEnd; - CodeMirror.scrollbarModel = scrollbarModel; - CodeMirror.Pos = Pos; - CodeMirror.cmpPos = cmp; - CodeMirror.modes = modes; - CodeMirror.mimeModes = mimeModes; - CodeMirror.resolveMode = resolveMode; - CodeMirror.getMode = getMode; - CodeMirror.modeExtensions = modeExtensions; - CodeMirror.extendMode = extendMode; - CodeMirror.copyState = copyState; - CodeMirror.startState = startState; - CodeMirror.innerMode = innerMode; - CodeMirror.commands = commands; - CodeMirror.keyMap = keyMap; - CodeMirror.keyName = keyName; - CodeMirror.isModifierKey = isModifierKey; - CodeMirror.lookupKey = lookupKey; - CodeMirror.normalizeKeyMap = normalizeKeyMap; - CodeMirror.StringStream = StringStream; - CodeMirror.SharedTextMarker = SharedTextMarker; - CodeMirror.TextMarker = TextMarker; - CodeMirror.LineWidget = LineWidget; - CodeMirror.e_preventDefault = e_preventDefault; - CodeMirror.e_stopPropagation = e_stopPropagation; - CodeMirror.e_stop = e_stop; - CodeMirror.addClass = addClass; - CodeMirror.contains = contains; - CodeMirror.rmClass = rmClass; - CodeMirror.keyNames = keyNames; - } - - // EDITOR CONSTRUCTOR - - defineOptions(CodeMirror); - - addEditorMethods(CodeMirror); - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) { if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - { CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments)} - })(Doc.prototype[prop]); } } - - eventMixin(Doc); - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function(name/*, mode, …*/) { - if (!CodeMirror.defaults.mode && name != "null") { CodeMirror.defaults.mode = name; } - defineMode.apply(this, arguments); - }; - - CodeMirror.defineMIME = defineMIME; - - // Minimal default mode. - CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); }); - CodeMirror.defineMIME("text/plain", "null"); - - // EXTENSIONS - - CodeMirror.defineExtension = function (name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function (name, func) { - Doc.prototype[name] = func; - }; - - CodeMirror.fromTextArea = fromTextArea; - - addLegacyProps(CodeMirror); - - CodeMirror.version = "5.52.2"; - - return CodeMirror; - -}))); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")) - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod) - else // Plain browser env - mod(CodeMirror) -})(function(CodeMirror) { - "use strict" - var Pos = CodeMirror.Pos - - function regexpFlags(regexp) { - var flags = regexp.flags - return flags != null ? flags : (regexp.ignoreCase ? "i" : "") - + (regexp.global ? "g" : "") - + (regexp.multiline ? "m" : "") - } - - function ensureFlags(regexp, flags) { - var current = regexpFlags(regexp), target = current - for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1) - target += flags.charAt(i) - return current == target ? regexp : new RegExp(regexp.source, target) - } - - function maybeMultiline(regexp) { - return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source) - } - - function searchRegexpForward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g") - for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) { - regexp.lastIndex = ch - var string = doc.getLine(line), match = regexp.exec(string) - if (match) - return {from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match: match} - } - } - - function searchRegexpForwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start) - - regexp = ensureFlags(regexp, "gm") - var string, chunk = 1 - for (var line = start.line, last = doc.lastLine(); line <= last;) { - // This grows the search buffer in exponentially-sized chunks - // between matches, so that nearby matches are fast and don't - // require concatenating the whole document (in case we're - // searching for something that has tons of matches), but at the - // same time, the amount of retries is limited. - for (var i = 0; i < chunk; i++) { - if (line > last) break - var curLine = doc.getLine(line++) - string = string == null ? curLine : string + "\n" + curLine - } - chunk = chunk * 2 - regexp.lastIndex = start.ch - var match = regexp.exec(string) - if (match) { - var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n") - var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length - return {from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, - inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match: match} - } - } - } - - function lastMatchIn(string, regexp, endMargin) { - var match, from = 0 - while (from <= string.length) { - regexp.lastIndex = from - var newMatch = regexp.exec(string) - if (!newMatch) break - var end = newMatch.index + newMatch[0].length - if (end > string.length - endMargin) break - if (!match || end > match.index + match[0].length) - match = newMatch - from = newMatch.index + 1 - } - return match - } - - function searchRegexpBackward(doc, regexp, start) { - regexp = ensureFlags(regexp, "g") - for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) { - var string = doc.getLine(line) - var match = lastMatchIn(string, regexp, ch < 0 ? 0 : string.length - ch) - if (match) - return {from: Pos(line, match.index), - to: Pos(line, match.index + match[0].length), - match: match} - } - } - - function searchRegexpBackwardMultiline(doc, regexp, start) { - if (!maybeMultiline(regexp)) return searchRegexpBackward(doc, regexp, start) - regexp = ensureFlags(regexp, "gm") - var string, chunkSize = 1, endMargin = doc.getLine(start.line).length - start.ch - for (var line = start.line, first = doc.firstLine(); line >= first;) { - for (var i = 0; i < chunkSize && line >= first; i++) { - var curLine = doc.getLine(line--) - string = string == null ? curLine : curLine + "\n" + string - } - chunkSize *= 2 - - var match = lastMatchIn(string, regexp, endMargin) - if (match) { - var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n") - var startLine = line + before.length, startCh = before[before.length - 1].length - return {from: Pos(startLine, startCh), - to: Pos(startLine + inside.length - 1, - inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length), - match: match} - } - } - } - - var doFold, noFold - if (String.prototype.normalize) { - doFold = function(str) { return str.normalize("NFD").toLowerCase() } - noFold = function(str) { return str.normalize("NFD") } - } else { - doFold = function(str) { return str.toLowerCase() } - noFold = function(str) { return str } - } - - // Maps a position in a case-folded line back to a position in the original line - // (compensating for codepoints increasing in number during folding) - function adjustPos(orig, folded, pos, foldFunc) { - if (orig.length == folded.length) return pos - for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) { - if (min == max) return min - var mid = (min + max) >> 1 - var len = foldFunc(orig.slice(0, mid)).length - if (len == pos) return mid - else if (len > pos) max = mid - else min = mid + 1 - } - } - - function searchStringForward(doc, query, start, caseFold) { - // Empty string would match anything and never progress, so we - // define it to match nothing instead. - if (!query.length) return null - var fold = caseFold ? doFold : noFold - var lines = fold(query).split(/\r|\n\r?/) - - search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) { - var orig = doc.getLine(line).slice(ch), string = fold(orig) - if (lines.length == 1) { - var found = string.indexOf(lines[0]) - if (found == -1) continue search - var start = adjustPos(orig, string, found, fold) + ch - return {from: Pos(line, adjustPos(orig, string, found, fold) + ch), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)} - } else { - var cutFrom = string.length - lines[0].length - if (string.slice(cutFrom) != lines[0]) continue search - for (var i = 1; i < lines.length - 1; i++) - if (fold(doc.getLine(line + i)) != lines[i]) continue search - var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1] - if (endString.slice(0, lastLine.length) != lastLine) continue search - return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch), - to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))} - } - } - } - - function searchStringBackward(doc, query, start, caseFold) { - if (!query.length) return null - var fold = caseFold ? doFold : noFold - var lines = fold(query).split(/\r|\n\r?/) - - search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) { - var orig = doc.getLine(line) - if (ch > -1) orig = orig.slice(0, ch) - var string = fold(orig) - if (lines.length == 1) { - var found = string.lastIndexOf(lines[0]) - if (found == -1) continue search - return {from: Pos(line, adjustPos(orig, string, found, fold)), - to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))} - } else { - var lastLine = lines[lines.length - 1] - if (string.slice(0, lastLine.length) != lastLine) continue search - for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++) - if (fold(doc.getLine(start + i)) != lines[i]) continue search - var top = doc.getLine(line + 1 - lines.length), topString = fold(top) - if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search - return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)), - to: Pos(line, adjustPos(orig, string, lastLine.length, fold))} - } - } - } - - function SearchCursor(doc, query, pos, options) { - this.atOccurrence = false - this.doc = doc - pos = pos ? doc.clipPos(pos) : Pos(0, 0) - this.pos = {from: pos, to: pos} - - var caseFold - if (typeof options == "object") { - caseFold = options.caseFold - } else { // Backwards compat for when caseFold was the 4th argument - caseFold = options - options = null - } - - if (typeof query == "string") { - if (caseFold == null) caseFold = false - this.matches = function(reverse, pos) { - return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold) - } - } else { - query = ensureFlags(query, "gm") - if (!options || options.multiline !== false) - this.matches = function(reverse, pos) { - return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos) - } - else - this.matches = function(reverse, pos) { - return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos) - } - } - } - - SearchCursor.prototype = { - findNext: function() {return this.find(false)}, - findPrevious: function() {return this.find(true)}, - - find: function(reverse) { - var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to)) - - // Implements weird auto-growing behavior on null-matches for - // backwards-compatiblity with the vim code (unfortunately) - while (result && CodeMirror.cmpPos(result.from, result.to) == 0) { - if (reverse) { - if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1) - else if (result.from.line == this.doc.firstLine()) result = null - else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1))) - } else { - if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1) - else if (result.to.line == this.doc.lastLine()) result = null - else result = this.matches(reverse, Pos(result.to.line + 1, 0)) - } - } - - if (result) { - this.pos = result - this.atOccurrence = true - return this.pos.match || true - } else { - var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0) - this.pos = {from: end, to: end} - return this.atOccurrence = false - } - }, - - from: function() {if (this.atOccurrence) return this.pos.from}, - to: function() {if (this.atOccurrence) return this.pos.to}, - - replace: function(newText, origin) { - if (!this.atOccurrence) return - var lines = CodeMirror.splitLines(newText) - this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin) - this.pos.to = Pos(this.pos.from.line + lines.length - 1, - lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0)) - } - } - - CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this.doc, query, pos, caseFold) - }) - CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) { - return new SearchCursor(this, query, pos, caseFold) - }) - - CodeMirror.defineExtension("selectMatches", function(query, caseFold) { - var ranges = [] - var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold) - while (cur.findNext()) { - if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break - ranges.push({anchor: cur.from(), head: cur.to()}) - } - if (ranges.length) - this.setSelections(ranges, 0) - }) -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -// Highlighting text that matches the selection -// -// Defines an option highlightSelectionMatches, which, when enabled, -// will style strings that match the selection throughout the -// document. -// -// The option can be set to true to simply enable it, or to a -// {minChars, style, wordsOnly, showToken, delay} object to explicitly -// configure it. minChars is the minimum amount of characters that should be -// selected for the behavior to occur, and style is the token style to -// apply to the matches. This will be prefixed by "cm-" to create an -// actual CSS class name. If wordsOnly is enabled, the matches will be -// highlighted only if the selected text is a word. showToken, when enabled, -// will cause the current token to be highlighted when nothing is selected. -// delay is used to specify how much time to wait, in milliseconds, before -// highlighting the matches. If annotateScrollbar is enabled, the occurences -// will be highlighted on the scrollbar via the matchesonscrollbar addon. - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror"), require("./matchesonscrollbar")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror", "./matchesonscrollbar"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - var defaults = { - style: "matchhighlight", - minChars: 2, - delay: 100, - wordsOnly: false, - annotateScrollbar: false, - showToken: false, - trim: true - } - - function State(options) { - this.options = {} - for (var name in defaults) - this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name] - this.overlay = this.timeout = null; - this.matchesonscroll = null; - this.active = false; - } - - CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) { - removeOverlay(cm); - clearTimeout(cm.state.matchHighlighter.timeout); - cm.state.matchHighlighter = null; - cm.off("cursorActivity", cursorActivity); - cm.off("focus", onFocus) - } - if (val) { - var state = cm.state.matchHighlighter = new State(val); - if (cm.hasFocus()) { - state.active = true - highlightMatches(cm) - } else { - cm.on("focus", onFocus) - } - cm.on("cursorActivity", cursorActivity); - } - }); - - function cursorActivity(cm) { - var state = cm.state.matchHighlighter; - if (state.active || cm.hasFocus()) scheduleHighlight(cm, state) - } - - function onFocus(cm) { - var state = cm.state.matchHighlighter - if (!state.active) { - state.active = true - scheduleHighlight(cm, state) - } - } - - function scheduleHighlight(cm, state) { - clearTimeout(state.timeout); - state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay); - } - - function addOverlay(cm, query, hasBoundary, style) { - var state = cm.state.matchHighlighter; - cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style)); - if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) { - var searchFor = hasBoundary ? new RegExp("\\b" + query.replace(/[\\\[.+*?(){|^$]/g, "\\$&") + "\\b") : query; - state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false, - {className: "CodeMirror-selection-highlight-scrollbar"}); - } - } - - function removeOverlay(cm) { - var state = cm.state.matchHighlighter; - if (state.overlay) { - cm.removeOverlay(state.overlay); - state.overlay = null; - if (state.matchesonscroll) { - state.matchesonscroll.clear(); - state.matchesonscroll = null; - } - } - } - - function highlightMatches(cm) { - cm.operation(function() { - var state = cm.state.matchHighlighter; - removeOverlay(cm); - if (!cm.somethingSelected() && state.options.showToken) { - var re = state.options.showToken === true ? /[\w$]/ : state.options.showToken; - var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start; - while (start && re.test(line.charAt(start - 1))) --start; - while (end < line.length && re.test(line.charAt(end))) ++end; - if (start < end) - addOverlay(cm, line.slice(start, end), re, state.options.style); - return; - } - var from = cm.getCursor("from"), to = cm.getCursor("to"); - if (from.line != to.line) return; - if (state.options.wordsOnly && !isWord(cm, from, to)) return; - var selection = cm.getRange(from, to) - if (state.options.trim) selection = selection.replace(/^\s+|\s+$/g, "") - if (selection.length >= state.options.minChars) - addOverlay(cm, selection, false, state.options.style); - }); - } - - function isWord(cm, from, to) { - var str = cm.getRange(from, to); - if (str.match(/^\w+$/) !== null) { - if (from.ch > 0) { - var pos = {line: from.line, ch: from.ch - 1}; - var chr = cm.getRange(pos, from); - if (chr.match(/\W/) === null) return false; - } - if (to.ch < cm.getLine(from.line).length) { - var pos = {line: to.line, ch: to.ch + 1}; - var chr = cm.getRange(to, pos); - if (chr.match(/\W/) === null) return false; - } - return true; - } else return false; - } - - function boundariesAround(stream, re) { - return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) && - (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos))); - } - - function makeOverlay(query, hasBoundary, style) { - return {token: function(stream) { - if (stream.match(query) && - (!hasBoundary || boundariesAround(stream, hasBoundary))) - return style; - stream.next(); - stream.skipTo(query.charAt(0)) || stream.skipToEnd(); - }}; - } -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror"), require("./searchcursor"), require("../scroll/annotatescrollbar")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror", "./searchcursor", "../scroll/annotatescrollbar"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineExtension("showMatchesOnScrollbar", function(query, caseFold, options) { - if (typeof options == "string") options = {className: options}; - if (!options) options = {}; - return new SearchAnnotation(this, query, caseFold, options); - }); - - function SearchAnnotation(cm, query, caseFold, options) { - this.cm = cm; - this.options = options; - var annotateOptions = {listenForChanges: false}; - for (var prop in options) annotateOptions[prop] = options[prop]; - if (!annotateOptions.className) annotateOptions.className = "CodeMirror-search-match"; - this.annotation = cm.annotateScrollbar(annotateOptions); - this.query = query; - this.caseFold = caseFold; - this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1}; - this.matches = []; - this.update = null; - - this.findMatches(); - this.annotation.update(this.matches); - - var self = this; - cm.on("change", this.changeHandler = function(_cm, change) { self.onChange(change); }); - } - - var MAX_MATCHES = 1000; - - SearchAnnotation.prototype.findMatches = function() { - if (!this.gap) return; - for (var i = 0; i < this.matches.length; i++) { - var match = this.matches[i]; - if (match.from.line >= this.gap.to) break; - if (match.to.line >= this.gap.from) this.matches.splice(i--, 1); - } - var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), {caseFold: this.caseFold, multiline: this.options.multiline}); - var maxMatches = this.options && this.options.maxMatches || MAX_MATCHES; - while (cursor.findNext()) { - var match = {from: cursor.from(), to: cursor.to()}; - if (match.from.line >= this.gap.to) break; - this.matches.splice(i++, 0, match); - if (this.matches.length > maxMatches) break; - } - this.gap = null; - }; - - function offsetLine(line, changeStart, sizeChange) { - if (line <= changeStart) return line; - return Math.max(changeStart, line + sizeChange); - } - - SearchAnnotation.prototype.onChange = function(change) { - var startLine = change.from.line; - var endLine = CodeMirror.changeEnd(change).line; - var sizeChange = endLine - change.to.line; - if (this.gap) { - this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line); - this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line); - } else { - this.gap = {from: change.from.line, to: endLine + 1}; - } - - if (sizeChange) for (var i = 0; i < this.matches.length; i++) { - var match = this.matches[i]; - var newFrom = offsetLine(match.from.line, startLine, sizeChange); - if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch); - var newTo = offsetLine(match.to.line, startLine, sizeChange); - if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch); - } - clearTimeout(this.update); - var self = this; - this.update = setTimeout(function() { self.updateAfterChange(); }, 250); - }; - - SearchAnnotation.prototype.updateAfterChange = function() { - this.findMatches(); - this.annotation.update(this.matches); - }; - - SearchAnnotation.prototype.clear = function() { - this.cm.off("change", this.changeHandler); - this.annotation.clear(); - }; -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - var defaults = { - pairs: "()[]{}''\"\"", - closeBefore: ")]}'\":;>", - triples: "", - explode: "[]{}" - }; - - var Pos = CodeMirror.Pos; - - CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.removeKeyMap(keyMap); - cm.state.closeBrackets = null; - } - if (val) { - ensureBound(getOption(val, "pairs")) - cm.state.closeBrackets = val; - cm.addKeyMap(keyMap); - } - }); - - function getOption(conf, name) { - if (name == "pairs" && typeof conf == "string") return conf; - if (typeof conf == "object" && conf[name] != null) return conf[name]; - return defaults[name]; - } - - var keyMap = {Backspace: handleBackspace, Enter: handleEnter}; - function ensureBound(chars) { - for (var i = 0; i < chars.length; i++) { - var ch = chars.charAt(i), key = "'" + ch + "'" - if (!keyMap[key]) keyMap[key] = handler(ch) - } - } - ensureBound(defaults.pairs + "`") - - function handler(ch) { - return function(cm) { return handleChar(cm, ch); }; - } - - function getConfig(cm) { - var deflt = cm.state.closeBrackets; - if (!deflt || deflt.override) return deflt; - var mode = cm.getModeAt(cm.getCursor()); - return mode.closeBrackets || deflt; - } - - function handleBackspace(cm) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - - var pairs = getOption(conf, "pairs"); - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - for (var i = ranges.length - 1; i >= 0; i--) { - var cur = ranges[i].head; - cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete"); - } - } - - function handleEnter(cm) { - var conf = getConfig(cm); - var explode = conf && getOption(conf, "explode"); - if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass; - - var ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - if (!ranges[i].empty()) return CodeMirror.Pass; - var around = charsAround(cm, ranges[i].head); - if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass; - } - cm.operation(function() { - var linesep = cm.lineSeparator() || "\n"; - cm.replaceSelection(linesep + linesep, null); - cm.execCommand("goCharLeft"); - ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var line = ranges[i].head.line; - cm.indentLine(line, null, true); - cm.indentLine(line + 1, null, true); - } - }); - } - - function contractSelection(sel) { - var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0; - return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)), - head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))}; - } - - function handleChar(cm, ch) { - var conf = getConfig(cm); - if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass; - - var pairs = getOption(conf, "pairs"); - var pos = pairs.indexOf(ch); - if (pos == -1) return CodeMirror.Pass; - - var closeBefore = getOption(conf,"closeBefore"); - - var triples = getOption(conf, "triples"); - - var identical = pairs.charAt(pos + 1) == ch; - var ranges = cm.listSelections(); - var opening = pos % 2 == 0; - - var type; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i], cur = range.head, curType; - var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1)); - if (opening && !range.empty()) { - curType = "surround"; - } else if ((identical || !opening) && next == ch) { - if (identical && stringStartsAfter(cm, cur)) - curType = "both"; - else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch) - curType = "skipThree"; - else - curType = "skip"; - } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 && - cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) { - if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass; - curType = "addFour"; - } else if (identical) { - var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur) - if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both"; - else return CodeMirror.Pass; - } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) { - curType = "both"; - } else { - return CodeMirror.Pass; - } - if (!type) type = curType; - else if (type != curType) return CodeMirror.Pass; - } - - var left = pos % 2 ? pairs.charAt(pos - 1) : ch; - var right = pos % 2 ? ch : pairs.charAt(pos + 1); - cm.operation(function() { - if (type == "skip") { - cm.execCommand("goCharRight"); - } else if (type == "skipThree") { - for (var i = 0; i < 3; i++) - cm.execCommand("goCharRight"); - } else if (type == "surround") { - var sels = cm.getSelections(); - for (var i = 0; i < sels.length; i++) - sels[i] = left + sels[i] + right; - cm.replaceSelections(sels, "around"); - sels = cm.listSelections().slice(); - for (var i = 0; i < sels.length; i++) - sels[i] = contractSelection(sels[i]); - cm.setSelections(sels); - } else if (type == "both") { - cm.replaceSelection(left + right, null); - cm.triggerElectric(left + right); - cm.execCommand("goCharLeft"); - } else if (type == "addFour") { - cm.replaceSelection(left + left + left + left, "before"); - cm.execCommand("goCharRight"); - } - }); - } - - function charsAround(cm, pos) { - var str = cm.getRange(Pos(pos.line, pos.ch - 1), - Pos(pos.line, pos.ch + 1)); - return str.length == 2 ? str : null; - } - - function stringStartsAfter(cm, pos) { - var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1)) - return /\bstring/.test(token.type) && token.start == pos.ch && - (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos))) - } -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - var ie_lt8 = /MSIE \d/.test(navigator.userAgent) && - (document.documentMode == null || document.documentMode < 8); - - var Pos = CodeMirror.Pos; - - var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"}; - - function bracketRegex(config) { - return config && config.bracketRegex || /[(){}[\]]/ - } - - function findMatchingBracket(cm, where, config) { - var line = cm.getLineHandle(where.line), pos = where.ch - 1; - var afterCursor = config && config.afterCursor - if (afterCursor == null) - afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className) - var re = bracketRegex(config) - - // A cursor is defined as between two characters, but in in vim command mode - // (i.e. not insert mode), the cursor is visually represented as a - // highlighted box on top of the 2nd character. Otherwise, we allow matches - // from before or after the cursor. - var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) || - re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)]; - if (!match) return null; - var dir = match.charAt(1) == ">" ? 1 : -1; - if (config && config.strict && (dir > 0) != (pos == where.ch)) return null; - var style = cm.getTokenTypeAt(Pos(where.line, pos + 1)); - - var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config); - if (found == null) return null; - return {from: Pos(where.line, pos), to: found && found.pos, - match: found && found.ch == match.charAt(0), forward: dir > 0}; - } - - // bracketRegex is used to specify which type of bracket to scan - // should be a regexp, e.g. /[[\]]/ - // - // Note: If "where" is on an open bracket, then this bracket is ignored. - // - // Returns false when no bracket was found, null when it reached - // maxScanLines and gave up - function scanForBracket(cm, where, dir, style, config) { - var maxScanLen = (config && config.maxScanLineLength) || 10000; - var maxScanLines = (config && config.maxScanLines) || 1000; - - var stack = []; - var re = bracketRegex(config) - var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1) - : Math.max(cm.firstLine() - 1, where.line - maxScanLines); - for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) { - var line = cm.getLine(lineNo); - if (!line) continue; - var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1; - if (line.length > maxScanLen) continue; - if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0); - for (; pos != end; pos += dir) { - var ch = line.charAt(pos); - if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) { - var match = matching[ch]; - if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch); - else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch}; - else stack.pop(); - } - } - } - return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null; - } - - function matchBrackets(cm, autoclear, config) { - // Disable brace matching in long lines, since it'll cause hugely slow updates - var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000; - var marks = [], ranges = cm.listSelections(); - for (var i = 0; i < ranges.length; i++) { - var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config); - if (match && cm.getLine(match.from.line).length <= maxHighlightLen) { - var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket"; - marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style})); - if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen) - marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style})); - } - } - - if (marks.length) { - // Kludge to work around the IE bug from issue #1193, where text - // input stops going to the textare whever this fires. - if (ie_lt8 && cm.state.focused) cm.focus(); - - var clear = function() { - cm.operation(function() { - for (var i = 0; i < marks.length; i++) marks[i].clear(); - }); - }; - if (autoclear) setTimeout(clear, 800); - else return clear; - } - } - - function doMatchBrackets(cm) { - cm.operation(function() { - if (cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets); - }); - } - - CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) { - if (old && old != CodeMirror.Init) { - cm.off("cursorActivity", doMatchBrackets); - if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) { - cm.state.matchBrackets.currentlyHighlighted(); - cm.state.matchBrackets.currentlyHighlighted = null; - } - } - if (val) { - cm.state.matchBrackets = typeof val == "object" ? val : {}; - cm.on("cursorActivity", doMatchBrackets); - } - }); - - CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);}); - CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){ - // Backwards-compatibility kludge - if (oldConfig || typeof config == "boolean") { - if (!oldConfig) { - config = config ? {strict: true} : null - } else { - oldConfig.strict = config - config = oldConfig - } - } - return findMatchingBracket(this, pos, config) - }); - CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){ - return scanForBracket(this, pos, dir, style, config); - }); -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - function Bar(cls, orientation, scroll) { - this.orientation = orientation; - this.scroll = scroll; - this.screen = this.total = this.size = 1; - this.pos = 0; - - this.node = document.createElement("div"); - this.node.className = cls + "-" + orientation; - this.inner = this.node.appendChild(document.createElement("div")); - - var self = this; - CodeMirror.on(this.inner, "mousedown", function(e) { - if (e.which != 1) return; - CodeMirror.e_preventDefault(e); - var axis = self.orientation == "horizontal" ? "pageX" : "pageY"; - var start = e[axis], startpos = self.pos; - function done() { - CodeMirror.off(document, "mousemove", move); - CodeMirror.off(document, "mouseup", done); - } - function move(e) { - if (e.which != 1) return done(); - self.moveTo(startpos + (e[axis] - start) * (self.total / self.size)); - } - CodeMirror.on(document, "mousemove", move); - CodeMirror.on(document, "mouseup", done); - }); - - CodeMirror.on(this.node, "click", function(e) { - CodeMirror.e_preventDefault(e); - var innerBox = self.inner.getBoundingClientRect(), where; - if (self.orientation == "horizontal") - where = e.clientX < innerBox.left ? -1 : e.clientX > innerBox.right ? 1 : 0; - else - where = e.clientY < innerBox.top ? -1 : e.clientY > innerBox.bottom ? 1 : 0; - self.moveTo(self.pos + where * self.screen); - }); - - function onWheel(e) { - var moved = CodeMirror.wheelEventPixels(e)[self.orientation == "horizontal" ? "x" : "y"]; - var oldPos = self.pos; - self.moveTo(self.pos + moved); - if (self.pos != oldPos) CodeMirror.e_preventDefault(e); - } - CodeMirror.on(this.node, "mousewheel", onWheel); - CodeMirror.on(this.node, "DOMMouseScroll", onWheel); - } - - Bar.prototype.setPos = function(pos, force) { - if (pos < 0) pos = 0; - if (pos > this.total - this.screen) pos = this.total - this.screen; - if (!force && pos == this.pos) return false; - this.pos = pos; - this.inner.style[this.orientation == "horizontal" ? "left" : "top"] = - (pos * (this.size / this.total)) + "px"; - return true - }; - - Bar.prototype.moveTo = function(pos) { - if (this.setPos(pos)) this.scroll(pos, this.orientation); - } - - var minButtonSize = 10; - - Bar.prototype.update = function(scrollSize, clientSize, barSize) { - var sizeChanged = this.screen != clientSize || this.total != scrollSize || this.size != barSize - if (sizeChanged) { - this.screen = clientSize; - this.total = scrollSize; - this.size = barSize; - } - - var buttonSize = this.screen * (this.size / this.total); - if (buttonSize < minButtonSize) { - this.size -= minButtonSize - buttonSize; - buttonSize = minButtonSize; - } - this.inner.style[this.orientation == "horizontal" ? "width" : "height"] = - buttonSize + "px"; - this.setPos(this.pos, sizeChanged); - }; - - function SimpleScrollbars(cls, place, scroll) { - this.addClass = cls; - this.horiz = new Bar(cls, "horizontal", scroll); - place(this.horiz.node); - this.vert = new Bar(cls, "vertical", scroll); - place(this.vert.node); - this.width = null; - } - - SimpleScrollbars.prototype.update = function(measure) { - if (this.width == null) { - var style = window.getComputedStyle ? window.getComputedStyle(this.horiz.node) : this.horiz.node.currentStyle; - if (style) this.width = parseInt(style.height); - } - var width = this.width || 0; - - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - this.vert.node.style.display = needsV ? "block" : "none"; - this.horiz.node.style.display = needsH ? "block" : "none"; - - if (needsV) { - this.vert.update(measure.scrollHeight, measure.clientHeight, - measure.viewHeight - (needsH ? width : 0)); - this.vert.node.style.bottom = needsH ? width + "px" : "0"; - } - if (needsH) { - this.horiz.update(measure.scrollWidth, measure.clientWidth, - measure.viewWidth - (needsV ? width : 0) - measure.barLeft); - this.horiz.node.style.right = needsV ? width + "px" : "0"; - this.horiz.node.style.left = measure.barLeft + "px"; - } - - return {right: needsV ? width : 0, bottom: needsH ? width : 0}; - }; - - SimpleScrollbars.prototype.setScrollTop = function(pos) { - this.vert.setPos(pos); - }; - - SimpleScrollbars.prototype.setScrollLeft = function(pos) { - this.horiz.setPos(pos); - }; - - SimpleScrollbars.prototype.clear = function() { - var parent = this.horiz.node.parentNode; - parent.removeChild(this.horiz.node); - parent.removeChild(this.vert.node); - }; - - CodeMirror.scrollbarModel.simple = function(place, scroll) { - return new SimpleScrollbars("CodeMirror-simplescroll", place, scroll); - }; - CodeMirror.scrollbarModel.overlay = function(place, scroll) { - return new SimpleScrollbars("CodeMirror-overlayscroll", place, scroll); - }; -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineExtension("annotateScrollbar", function(options) { - if (typeof options == "string") options = {className: options}; - return new Annotation(this, options); - }); - - CodeMirror.defineOption("scrollButtonHeight", 0); - - function Annotation(cm, options) { - this.cm = cm; - this.options = options; - this.buttonHeight = options.scrollButtonHeight || cm.getOption("scrollButtonHeight"); - this.annotations = []; - this.doRedraw = this.doUpdate = null; - this.div = cm.getWrapperElement().appendChild(document.createElement("div")); - this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none"; - this.computeScale(); - - function scheduleRedraw(delay) { - clearTimeout(self.doRedraw); - self.doRedraw = setTimeout(function() { self.redraw(); }, delay); - } - - var self = this; - cm.on("refresh", this.resizeHandler = function() { - clearTimeout(self.doUpdate); - self.doUpdate = setTimeout(function() { - if (self.computeScale()) scheduleRedraw(20); - }, 100); - }); - cm.on("markerAdded", this.resizeHandler); - cm.on("markerCleared", this.resizeHandler); - if (options.listenForChanges !== false) - cm.on("changes", this.changeHandler = function() { - scheduleRedraw(250); - }); - } - - Annotation.prototype.computeScale = function() { - var cm = this.cm; - var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) / - cm.getScrollerElement().scrollHeight - if (hScale != this.hScale) { - this.hScale = hScale; - return true; - } - }; - - Annotation.prototype.update = function(annotations) { - this.annotations = annotations; - this.redraw(); - }; - - Annotation.prototype.redraw = function(compute) { - if (compute !== false) this.computeScale(); - var cm = this.cm, hScale = this.hScale; - - var frag = document.createDocumentFragment(), anns = this.annotations; - - var wrapping = cm.getOption("lineWrapping"); - var singleLineH = wrapping && cm.defaultTextHeight() * 1.5; - var curLine = null, curLineObj = null; - function getY(pos, top) { - if (curLine != pos.line) { - curLine = pos.line; - curLineObj = cm.getLineHandle(curLine); - } - if ((curLineObj.widgets && curLineObj.widgets.length) || - (wrapping && curLineObj.height > singleLineH)) - return cm.charCoords(pos, "local")[top ? "top" : "bottom"]; - var topY = cm.heightAtLine(curLineObj, "local"); - return topY + (top ? 0 : curLineObj.height); - } - - var lastLine = cm.lastLine() - if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) { - var ann = anns[i]; - if (ann.to.line > lastLine) continue; - var top = nextTop || getY(ann.from, true) * hScale; - var bottom = getY(ann.to, false) * hScale; - while (i < anns.length - 1) { - if (anns[i + 1].to.line > lastLine) break; - nextTop = getY(anns[i + 1].from, true) * hScale; - if (nextTop > bottom + .9) break; - ann = anns[++i]; - bottom = getY(ann.to, false) * hScale; - } - if (bottom == top) continue; - var height = Math.max(bottom - top, 3); - - var elt = frag.appendChild(document.createElement("div")); - elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: " - + (top + this.buttonHeight) + "px; height: " + height + "px"; - elt.className = this.options.className; - if (ann.id) { - elt.setAttribute("annotation-id", ann.id); - } - } - this.div.textContent = ""; - this.div.appendChild(frag); - }; - - Annotation.prototype.clear = function() { - this.cm.off("refresh", this.resizeHandler); - this.cm.off("markerAdded", this.resizeHandler); - this.cm.off("markerCleared", this.resizeHandler); - if (this.changeHandler) this.cm.off("changes", this.changeHandler); - this.div.parentNode.removeChild(this.div); - }; -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - var WRAP_CLASS = "CodeMirror-activeline"; - var BACK_CLASS = "CodeMirror-activeline-background"; - var GUTT_CLASS = "CodeMirror-activeline-gutter"; - - CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) { - var prev = old == CodeMirror.Init ? false : old; - if (val == prev) return - if (prev) { - cm.off("beforeSelectionChange", selectionChange); - clearActiveLines(cm); - delete cm.state.activeLines; - } - if (val) { - cm.state.activeLines = []; - updateActiveLines(cm, cm.listSelections()); - cm.on("beforeSelectionChange", selectionChange); - } - }); - - function clearActiveLines(cm) { - for (var i = 0; i < cm.state.activeLines.length; i++) { - cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS); - cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS); - cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS); - } - } - - function sameArray(a, b) { - if (a.length != b.length) return false; - for (var i = 0; i < a.length; i++) - if (a[i] != b[i]) return false; - return true; - } - - function updateActiveLines(cm, ranges) { - var active = []; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - var option = cm.getOption("styleActiveLine"); - if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty()) - continue - var line = cm.getLineHandleVisualStart(range.head.line); - if (active[active.length - 1] != line) active.push(line); - } - if (sameArray(cm.state.activeLines, active)) return; - cm.operation(function() { - clearActiveLines(cm); - for (var i = 0; i < active.length; i++) { - cm.addLineClass(active[i], "wrap", WRAP_CLASS); - cm.addLineClass(active[i], "background", BACK_CLASS); - cm.addLineClass(active[i], "gutter", GUTT_CLASS); - } - cm.state.activeLines = active; - }); - } - - function selectionChange(cm, sel) { - updateActiveLines(cm, sel.ranges); - } -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { - "use strict"; - - CodeMirror.defineOption("fullScreen", false, function(cm, val, old) { - if (old == CodeMirror.Init) old = false; - if (!old == !val) return; - if (val) setFullscreen(cm); - else setNormal(cm); - }); - - function setFullscreen(cm) { - var wrap = cm.getWrapperElement(); - cm.state.fullScreenRestore = {scrollTop: window.pageYOffset, scrollLeft: window.pageXOffset, - width: wrap.style.width, height: wrap.style.height}; - wrap.style.width = ""; - wrap.style.height = "auto"; - wrap.className += " CodeMirror-fullscreen"; - document.documentElement.style.overflow = "hidden"; - cm.refresh(); - } - - function setNormal(cm) { - var wrap = cm.getWrapperElement(); - wrap.className = wrap.className.replace(/\s*CodeMirror-fullscreen\b/, ""); - document.documentElement.style.overflow = ""; - var info = cm.state.fullScreenRestore; - wrap.style.width = info.width; wrap.style.height = info.height; - window.scrollTo(info.scrollLeft, info.scrollTop); - cm.refresh(); - } -}); -CodeMirror.defineMode("glsl", function(config, parserConfig) { - var indentUnit = config.indentUnit, - keywords = parserConfig.keywords || {}, - builtins = parserConfig.builtins || {}, - blockKeywords = parserConfig.blockKeywords || {}, - atoms = parserConfig.atoms || {}, - hooks = parserConfig.hooks || {}, - multiLineStrings = parserConfig.multiLineStrings; - var isOperatorChar = /[+\-*&%=<>!?|\/]/; - - var curPunc; - - function tokenBase(stream, state) { - var ch = stream.next(); - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } - if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - curPunc = ch; - return "bracket"; - } - if (/\d/.test(ch)) { - stream.eatWhile(/[\w\.]/); - return "number"; - } - if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } - if (stream.eat("/")) { - stream.skipToEnd(); - return "comment"; - } - } - if (isOperatorChar.test(ch)) { - stream.eatWhile(isOperatorChar); - return "operator"; - } - stream.eatWhile(/[\w\$_]/); - var cur = stream.current(); - if (keywords.propertyIsEnumerable(cur)) { - if (blockKeywords.propertyIsEnumerable(cur)) curPunc = "newstatement"; - return "keyword"; - } - if (builtins.propertyIsEnumerable(cur)) { - return "builtin"; - } - if (atoms.propertyIsEnumerable(cur)) return "atom"; - return "word"; - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next, end = false; - while ((next = stream.next()) != null) { - if (next == quote && !escaped) {end = true; break;} - escaped = !escaped && next == "\\"; - } - if (end || !(escaped || multiLineStrings)) - state.tokenize = tokenBase; - return "string"; - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return "comment"; - } - - function Context(indented, column, type, align, prev) { - this.indented = indented; - this.column = column; - this.type = type; - this.align = align; - this.prev = prev; - } - function pushContext(state, col, type) { - return state.context = new Context(state.indented, col, type, null, state.context); - } - function popContext(state) { - var t = state.context.type; - if (t == ")" || t == "]" || t == "}") - state.indented = state.context.indented; - return state.context = state.context.prev; - } - - // Interface - - return { - startState: function(basecolumn) { - return { - tokenize: null, - context: new Context((basecolumn || 0) - indentUnit, 0, "top", false), - indented: 0, - startOfLine: true - }; - }, - - token: function(stream, state) { - var ctx = state.context; - if (stream.sol()) { - if (ctx.align == null) ctx.align = false; - state.indented = stream.indentation(); - state.startOfLine = true; - } - if (stream.eatSpace()) return null; - curPunc = null; - var style = (state.tokenize || tokenBase)(stream, state); - if (style == "comment" || style == "meta") return style; - if (ctx.align == null) ctx.align = true; - - if ((curPunc == ";" || curPunc == ":") && ctx.type == "statement") popContext(state); - else if (curPunc == "{") pushContext(state, stream.column(), "}"); - else if (curPunc == "[") pushContext(state, stream.column(), "]"); - else if (curPunc == "(") pushContext(state, stream.column(), ")"); - else if (curPunc == "}") { - while (ctx.type == "statement") ctx = popContext(state); - if (ctx.type == "}") ctx = popContext(state); - while (ctx.type == "statement") ctx = popContext(state); - } - else if (curPunc == ctx.type) popContext(state); - else if (ctx.type == "}" || ctx.type == "top" || (ctx.type == "statement" && curPunc == "newstatement")) - pushContext(state, stream.column(), "statement"); - state.startOfLine = false; - return style; - }, - - indent: function(state, textAfter) { - if (state.tokenize != tokenBase && state.tokenize != null) return 0; - var firstChar = textAfter && textAfter.charAt(0), ctx = state.context, closing = firstChar == ctx.type; - if (ctx.type == "statement") return ctx.indented + (firstChar == "{" ? 0 : indentUnit); - else if (ctx.align) return ctx.column + (closing ? 0 : 1); - else return ctx.indented + (closing ? 0 : indentUnit); - }, - - electricChars: "{}" - }; -}); - -(function() { - function words(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } - var glslKeywords = "attribute const uniform varying break continue " + - "do for while if else in out inout float int void bool true false " + - "lowp mediump highp precision invariant discard return mat2 mat3 " + - "mat4 vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 sampler2D " + - "samplerCube struct gl_FragCoord gl_FragColor"; - var glslBuiltins = "radians degrees sin cos tan asin acos atan pow " + - "exp log exp2 log2 sqrt inversesqrt abs sign floor ceil fract mod " + - "min max clamp mix step smoothstep length distance dot cross " + - "normalize faceforward reflect refract matrixCompMult lessThan " + - "lessThanEqual greaterThan greaterThanEqual equal notEqual any all " + - "not dFdx dFdy fwidth texture2D texture2DProj texture2DLod " + - "texture2DProjLod textureCube textureCubeLod"; - - function cppHook(stream, state) { - if (!state.startOfLine) return false; - stream.skipToEnd(); - return "meta"; - } - - // C#-style strings where "" escapes a quote. - function tokenAtString(stream, state) { - var next; - while ((next = stream.next()) != null) { - if (next == '"' && !stream.eat('"')) { - state.tokenize = null; - break; - } - } - return "string"; - } - - CodeMirror.defineMIME("text/x-glsl", { - name: "glsl", - keywords: words(glslKeywords), - builtins: words(glslBuiltins), - blockKeywords: words("case do else for if switch while struct"), - atoms: words("null"), - hooks: {"#": cppHook} - }); -}());// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -CodeMirror.defineMode("javascript", function(config, parserConfig) { - var indentUnit = config.indentUnit; - var statementIndent = parserConfig.statementIndent; - var jsonldMode = parserConfig.jsonld; - var jsonMode = parserConfig.json || jsonldMode; - var isTS = parserConfig.typescript; - var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/; - - // Tokenizer - - var keywords = function(){ - function kw(type) {return {type: type, style: "keyword"};} - var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d"); - var operator = kw("operator"), atom = {type: "atom", style: "atom"}; - - return { - "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B, - "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C, - "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"), - "function": kw("function"), "catch": kw("catch"), - "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"), - "in": operator, "typeof": operator, "instanceof": operator, - "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom, - "this": kw("this"), "class": kw("class"), "super": kw("atom"), - "yield": C, "export": kw("export"), "import": kw("import"), "extends": C, - "await": C - }; - }(); - - var isOperatorChar = /[+\-*&%=<>!?|~^@]/; - var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/; - - function readRegexp(stream) { - var escaped = false, next, inSet = false; - while ((next = stream.next()) != null) { - if (!escaped) { - if (next == "/" && !inSet) return; - if (next == "[") inSet = true; - else if (inSet && next == "]") inSet = false; - } - escaped = !escaped && next == "\\"; - } - } - - // Used as scratch variables to communicate multiple values without - // consing up tons of objects. - var type, content; - function ret(tp, style, cont) { - type = tp; content = cont; - return style; - } - function tokenBase(stream, state) { - var ch = stream.next(); - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) { - return ret("number", "number"); - } else if (ch == "." && stream.match("..")) { - return ret("spread", "meta"); - } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) { - return ret(ch); - } else if (ch == "=" && stream.eat(">")) { - return ret("=>", "operator"); - } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) { - return ret("number", "number"); - } else if (/\d/.test(ch)) { - stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/); - return ret("number", "number"); - } else if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } else if (stream.eat("/")) { - stream.skipToEnd(); - return ret("comment", "comment"); - } else if (expressionAllowed(stream, state, 1)) { - readRegexp(stream); - stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/); - return ret("regexp", "string-2"); - } else { - stream.eat("="); - return ret("operator", "operator", stream.current()); - } - } else if (ch == "`") { - state.tokenize = tokenQuasi; - return tokenQuasi(stream, state); - } else if (ch == "#") { - stream.skipToEnd(); - return ret("error", "error"); - } else if (ch == "<" && stream.match("!--") || ch == "-" && stream.match("->")) { - stream.skipToEnd() - return ret("comment", "comment") - } else if (isOperatorChar.test(ch)) { - if (ch != ">" || !state.lexical || state.lexical.type != ">") { - if (stream.eat("=")) { - if (ch == "!" || ch == "=") stream.eat("=") - } else if (/[<>*+\-]/.test(ch)) { - stream.eat(ch) - if (ch == ">") stream.eat(ch) - } - } - return ret("operator", "operator", stream.current()); - } else if (wordRE.test(ch)) { - stream.eatWhile(wordRE); - var word = stream.current() - if (state.lastType != ".") { - if (keywords.propertyIsEnumerable(word)) { - var kw = keywords[word] - return ret(kw.type, kw.style, word) - } - if (word == "async" && stream.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/, false)) - return ret("async", "keyword", word) - } - return ret("variable", "variable", word) - } - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next; - if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){ - state.tokenize = tokenBase; - return ret("jsonld-keyword", "meta"); - } - while ((next = stream.next()) != null) { - if (next == quote && !escaped) break; - escaped = !escaped && next == "\\"; - } - if (!escaped) state.tokenize = tokenBase; - return ret("string", "string"); - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = tokenBase; - break; - } - maybeEnd = (ch == "*"); - } - return ret("comment", "comment"); - } - - function tokenQuasi(stream, state) { - var escaped = false, next; - while ((next = stream.next()) != null) { - if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && next == "\\"; - } - return ret("quasi", "string-2", stream.current()); - } - - var brackets = "([{}])"; - // This is a crude lookahead trick to try and notice that we're - // parsing the argument patterns for a fat-arrow function before we - // actually hit the arrow token. It only works if the arrow is on - // the same line as the arguments and there's no strange noise - // (comments) in between. Fallback is to only notice when we hit the - // arrow, and not declare the arguments as locals for the arrow - // body. - function findFatArrow(stream, state) { - if (state.fatArrowAt) state.fatArrowAt = null; - var arrow = stream.string.indexOf("=>", stream.start); - if (arrow < 0) return; - - if (isTS) { // Try to skip TypeScript return type declarations after the arguments - var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow)) - if (m) arrow = m.index - } - - var depth = 0, sawSomething = false; - for (var pos = arrow - 1; pos >= 0; --pos) { - var ch = stream.string.charAt(pos); - var bracket = brackets.indexOf(ch); - if (bracket >= 0 && bracket < 3) { - if (!depth) { ++pos; break; } - if (--depth == 0) { if (ch == "(") sawSomething = true; break; } - } else if (bracket >= 3 && bracket < 6) { - ++depth; - } else if (wordRE.test(ch)) { - sawSomething = true; - } else if (/["'\/`]/.test(ch)) { - for (;; --pos) { - if (pos == 0) return - var next = stream.string.charAt(pos - 1) - if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break } - } - } else if (sawSomething && !depth) { - ++pos; - break; - } - } - if (sawSomething && !depth) state.fatArrowAt = pos; - } - - // Parser - - var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true}; - - function JSLexical(indented, column, type, align, prev, info) { - this.indented = indented; - this.column = column; - this.type = type; - this.prev = prev; - this.info = info; - if (align != null) this.align = align; - } - - function inScope(state, varname) { - for (var v = state.localVars; v; v = v.next) - if (v.name == varname) return true; - for (var cx = state.context; cx; cx = cx.prev) { - for (var v = cx.vars; v; v = v.next) - if (v.name == varname) return true; - } - } - - function parseJS(state, style, type, content, stream) { - var cc = state.cc; - // Communicate our context to the combinators. - // (Less wasteful than consing up a hundred closures on every call.) - cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style; - - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = true; - - while(true) { - var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement; - if (combinator(type, content)) { - while(cc.length && cc[cc.length - 1].lex) - cc.pop()(); - if (cx.marked) return cx.marked; - if (type == "variable" && inScope(state, content)) return "variable-2"; - return style; - } - } - } - - // Combinator utils - - var cx = {state: null, column: null, marked: null, cc: null}; - function pass() { - for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]); - } - function cont() { - pass.apply(null, arguments); - return true; - } - function inList(name, list) { - for (var v = list; v; v = v.next) if (v.name == name) return true - return false; - } - function register(varname) { - var state = cx.state; - cx.marked = "def"; - if (state.context) { - if (state.lexical.info == "var" && state.context && state.context.block) { - // FIXME function decls are also not block scoped - var newContext = registerVarScoped(varname, state.context) - if (newContext != null) { - state.context = newContext - return - } - } else if (!inList(varname, state.localVars)) { - state.localVars = new Var(varname, state.localVars) - return - } - } - // Fall through means this is global - if (parserConfig.globalVars && !inList(varname, state.globalVars)) - state.globalVars = new Var(varname, state.globalVars) - } - function registerVarScoped(varname, context) { - if (!context) { - return null - } else if (context.block) { - var inner = registerVarScoped(varname, context.prev) - if (!inner) return null - if (inner == context.prev) return context - return new Context(inner, context.vars, true) - } else if (inList(varname, context.vars)) { - return context - } else { - return new Context(context.prev, new Var(varname, context.vars), false) - } - } - - function isModifier(name) { - return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly" - } - - // Combinators - - function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block } - function Var(name, next) { this.name = name; this.next = next } - - var defaultVars = new Var("this", new Var("arguments", null)) - function pushcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, false) - cx.state.localVars = defaultVars - } - function pushblockcontext() { - cx.state.context = new Context(cx.state.context, cx.state.localVars, true) - cx.state.localVars = null - } - function popcontext() { - cx.state.localVars = cx.state.context.vars - cx.state.context = cx.state.context.prev - } - popcontext.lex = true - function pushlex(type, info) { - var result = function() { - var state = cx.state, indent = state.indented; - if (state.lexical.type == "stat") indent = state.lexical.indented; - else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev) - indent = outer.indented; - state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info); - }; - result.lex = true; - return result; - } - function poplex() { - var state = cx.state; - if (state.lexical.prev) { - if (state.lexical.type == ")") - state.indented = state.lexical.indented; - state.lexical = state.lexical.prev; - } - } - poplex.lex = true; - - function expect(wanted) { - function exp(type) { - if (type == wanted) return cont(); - else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass(); - else return cont(exp); - }; - return exp; - } - - function statement(type, value) { - if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex); - if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex); - if (type == "keyword b") return cont(pushlex("form"), statement, poplex); - if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex); - if (type == "debugger") return cont(expect(";")); - if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext); - if (type == ";") return cont(); - if (type == "if") { - if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex) - cx.state.cc.pop()(); - return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse); - } - if (type == "function") return cont(functiondef); - if (type == "for") return cont(pushlex("form"), forspec, statement, poplex); - if (type == "class" || (isTS && value == "interface")) { - cx.marked = "keyword" - return cont(pushlex("form", type == "class" ? type : value), className, poplex) - } - if (type == "variable") { - if (isTS && value == "declare") { - cx.marked = "keyword" - return cont(statement) - } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) { - cx.marked = "keyword" - if (value == "enum") return cont(enumdef); - else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";")); - else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex) - } else if (isTS && value == "namespace") { - cx.marked = "keyword" - return cont(pushlex("form"), expression, statement, poplex) - } else if (isTS && value == "abstract") { - cx.marked = "keyword" - return cont(statement) - } else { - return cont(pushlex("stat"), maybelabel); - } - } - if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext, - block, poplex, poplex, popcontext); - if (type == "case") return cont(expression, expect(":")); - if (type == "default") return cont(expect(":")); - if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext); - if (type == "export") return cont(pushlex("stat"), afterExport, poplex); - if (type == "import") return cont(pushlex("stat"), afterImport, poplex); - if (type == "async") return cont(statement) - if (value == "@") return cont(expression, statement) - return pass(pushlex("stat"), expression, expect(";"), poplex); - } - function maybeCatchBinding(type) { - if (type == "(") return cont(funarg, expect(")")) - } - function expression(type, value) { - return expressionInner(type, value, false); - } - function expressionNoComma(type, value) { - return expressionInner(type, value, true); - } - function parenExpr(type) { - if (type != "(") return pass() - return cont(pushlex(")"), maybeexpression, expect(")"), poplex) - } - function expressionInner(type, value, noComma) { - if (cx.state.fatArrowAt == cx.stream.start) { - var body = noComma ? arrowBodyNoComma : arrowBody; - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext); - else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext); - } - - var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma; - if (atomicTypes.hasOwnProperty(type)) return cont(maybeop); - if (type == "function") return cont(functiondef, maybeop); - if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); } - if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression); - if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop); - if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression); - if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop); - if (type == "{") return contCommasep(objprop, "}", null, maybeop); - if (type == "quasi") return pass(quasi, maybeop); - if (type == "new") return cont(maybeTarget(noComma)); - if (type == "import") return cont(expression); - return cont(); - } - function maybeexpression(type) { - if (type.match(/[;\}\)\],]/)) return pass(); - return pass(expression); - } - - function maybeoperatorComma(type, value) { - if (type == ",") return cont(maybeexpression); - return maybeoperatorNoComma(type, value, false); - } - function maybeoperatorNoComma(type, value, noComma) { - var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma; - var expr = noComma == false ? expression : expressionNoComma; - if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext); - if (type == "operator") { - if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me); - if (isTS && value == "<" && cx.stream.match(/^([^>]|<.*?>)*>\s*\(/, false)) - return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me); - if (value == "?") return cont(expression, expect(":"), expr); - return cont(expr); - } - if (type == "quasi") { return pass(quasi, me); } - if (type == ";") return; - if (type == "(") return contCommasep(expressionNoComma, ")", "call", me); - if (type == ".") return cont(property, me); - if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me); - if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) } - if (type == "regexp") { - cx.state.lastType = cx.marked = "operator" - cx.stream.backUp(cx.stream.pos - cx.stream.start - 1) - return cont(expr) - } - } - function quasi(type, value) { - if (type != "quasi") return pass(); - if (value.slice(value.length - 2) != "${") return cont(quasi); - return cont(expression, continueQuasi); - } - function continueQuasi(type) { - if (type == "}") { - cx.marked = "string-2"; - cx.state.tokenize = tokenQuasi; - return cont(quasi); - } - } - function arrowBody(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expression); - } - function arrowBodyNoComma(type) { - findFatArrow(cx.stream, cx.state); - return pass(type == "{" ? statement : expressionNoComma); - } - function maybeTarget(noComma) { - return function(type) { - if (type == ".") return cont(noComma ? targetNoComma : target); - else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma) - else return pass(noComma ? expressionNoComma : expression); - }; - } - function target(_, value) { - if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); } - } - function targetNoComma(_, value) { - if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); } - } - function maybelabel(type) { - if (type == ":") return cont(poplex, statement); - return pass(maybeoperatorComma, expect(";"), poplex); - } - function property(type) { - if (type == "variable") {cx.marked = "property"; return cont();} - } - function objprop(type, value) { - if (type == "async") { - cx.marked = "property"; - return cont(objprop); - } else if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - if (value == "get" || value == "set") return cont(getterSetter); - var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params - if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false))) - cx.state.fatArrowAt = cx.stream.pos + m[0].length - return cont(afterprop); - } else if (type == "number" || type == "string") { - cx.marked = jsonldMode ? "property" : (cx.style + " property"); - return cont(afterprop); - } else if (type == "jsonld-keyword") { - return cont(afterprop); - } else if (isTS && isModifier(value)) { - cx.marked = "keyword" - return cont(objprop) - } else if (type == "[") { - return cont(expression, maybetype, expect("]"), afterprop); - } else if (type == "spread") { - return cont(expressionNoComma, afterprop); - } else if (value == "*") { - cx.marked = "keyword"; - return cont(objprop); - } else if (type == ":") { - return pass(afterprop) - } - } - function getterSetter(type) { - if (type != "variable") return pass(afterprop); - cx.marked = "property"; - return cont(functiondef); - } - function afterprop(type) { - if (type == ":") return cont(expressionNoComma); - if (type == "(") return pass(functiondef); - } - function commasep(what, end, sep) { - function proceed(type, value) { - if (sep ? sep.indexOf(type) > -1 : type == ",") { - var lex = cx.state.lexical; - if (lex.info == "call") lex.pos = (lex.pos || 0) + 1; - return cont(function(type, value) { - if (type == end || value == end) return pass() - return pass(what) - }, proceed); - } - if (type == end || value == end) return cont(); - if (sep && sep.indexOf(";") > -1) return pass(what) - return cont(expect(end)); - } - return function(type, value) { - if (type == end || value == end) return cont(); - return pass(what, proceed); - }; - } - function contCommasep(what, end, info) { - for (var i = 3; i < arguments.length; i++) - cx.cc.push(arguments[i]); - return cont(pushlex(end, info), commasep(what, end), poplex); - } - function block(type) { - if (type == "}") return cont(); - return pass(statement, block); - } - function maybetype(type, value) { - if (isTS) { - if (type == ":") return cont(typeexpr); - if (value == "?") return cont(maybetype); - } - } - function maybetypeOrIn(type, value) { - if (isTS && (type == ":" || value == "in")) return cont(typeexpr) - } - function mayberettype(type) { - if (isTS && type == ":") { - if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr) - else return cont(typeexpr) - } - } - function isKW(_, value) { - if (value == "is") { - cx.marked = "keyword" - return cont() - } - } - function typeexpr(type, value) { - if (value == "keyof" || value == "typeof" || value == "infer") { - cx.marked = "keyword" - return cont(value == "typeof" ? expressionNoComma : typeexpr) - } - if (type == "variable" || value == "void") { - cx.marked = "type" - return cont(afterType) - } - if (value == "|" || value == "&") return cont(typeexpr) - if (type == "string" || type == "number" || type == "atom") return cont(afterType); - if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType) - if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType) - if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType) - if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr) - } - function maybeReturnType(type) { - if (type == "=>") return cont(typeexpr) - } - function typeprop(type, value) { - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property" - return cont(typeprop) - } else if (value == "?" || type == "number" || type == "string") { - return cont(typeprop) - } else if (type == ":") { - return cont(typeexpr) - } else if (type == "[") { - return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop) - } else if (type == "(") { - return pass(functiondecl, typeprop) - } - } - function typearg(type, value) { - if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg) - if (type == ":") return cont(typeexpr) - if (type == "spread") return cont(typearg) - return pass(typeexpr) - } - function afterType(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) - if (value == "|" || type == "." || value == "&") return cont(typeexpr) - if (type == "[") return cont(typeexpr, expect("]"), afterType) - if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) } - if (value == "?") return cont(typeexpr, expect(":"), typeexpr) - } - function maybeTypeArgs(_, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType) - } - function typeparam() { - return pass(typeexpr, maybeTypeDefault) - } - function maybeTypeDefault(_, value) { - if (value == "=") return cont(typeexpr) - } - function vardef(_, value) { - if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)} - return pass(pattern, maybetype, maybeAssign, vardefCont); - } - function pattern(type, value) { - if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) } - if (type == "variable") { register(value); return cont(); } - if (type == "spread") return cont(pattern); - if (type == "[") return contCommasep(eltpattern, "]"); - if (type == "{") return contCommasep(proppattern, "}"); - } - function proppattern(type, value) { - if (type == "variable" && !cx.stream.match(/^\s*:/, false)) { - register(value); - return cont(maybeAssign); - } - if (type == "variable") cx.marked = "property"; - if (type == "spread") return cont(pattern); - if (type == "}") return pass(); - if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern); - return cont(expect(":"), pattern, maybeAssign); - } - function eltpattern() { - return pass(pattern, maybeAssign) - } - function maybeAssign(_type, value) { - if (value == "=") return cont(expressionNoComma); - } - function vardefCont(type) { - if (type == ",") return cont(vardef); - } - function maybeelse(type, value) { - if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex); - } - function forspec(type, value) { - if (value == "await") return cont(forspec); - if (type == "(") return cont(pushlex(")"), forspec1, poplex); - } - function forspec1(type) { - if (type == "var") return cont(vardef, forspec2); - if (type == "variable") return cont(forspec2); - return pass(forspec2) - } - function forspec2(type, value) { - if (type == ")") return cont() - if (type == ";") return cont(forspec2) - if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) } - return pass(expression, forspec2) - } - function functiondef(type, value) { - if (value == "*") {cx.marked = "keyword"; return cont(functiondef);} - if (type == "variable") {register(value); return cont(functiondef);} - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef) - } - function functiondecl(type, value) { - if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);} - if (type == "variable") {register(value); return cont(functiondecl);} - if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext); - if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl) - } - function typename(type, value) { - if (type == "keyword" || type == "variable") { - cx.marked = "type" - return cont(typename) - } else if (value == "<") { - return cont(pushlex(">"), commasep(typeparam, ">"), poplex) - } - } - function funarg(type, value) { - if (value == "@") cont(expression, funarg) - if (type == "spread") return cont(funarg); - if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); } - if (isTS && type == "this") return cont(maybetype, maybeAssign) - return pass(pattern, maybetype, maybeAssign); - } - function classExpression(type, value) { - // Class expressions may have an optional name. - if (type == "variable") return className(type, value); - return classNameAfter(type, value); - } - function className(type, value) { - if (type == "variable") {register(value); return cont(classNameAfter);} - } - function classNameAfter(type, value) { - if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter) - if (value == "extends" || value == "implements" || (isTS && type == ",")) { - if (value == "implements") cx.marked = "keyword"; - return cont(isTS ? typeexpr : expression, classNameAfter); - } - if (type == "{") return cont(pushlex("}"), classBody, poplex); - } - function classBody(type, value) { - if (type == "async" || - (type == "variable" && - (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) && - cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) { - cx.marked = "keyword"; - return cont(classBody); - } - if (type == "variable" || cx.style == "keyword") { - cx.marked = "property"; - return cont(isTS ? classfield : functiondef, classBody); - } - if (type == "number" || type == "string") return cont(isTS ? classfield : functiondef, classBody); - if (type == "[") - return cont(expression, maybetype, expect("]"), isTS ? classfield : functiondef, classBody) - if (value == "*") { - cx.marked = "keyword"; - return cont(classBody); - } - if (isTS && type == "(") return pass(functiondecl, classBody) - if (type == ";" || type == ",") return cont(classBody); - if (type == "}") return cont(); - if (value == "@") return cont(expression, classBody) - } - function classfield(type, value) { - if (value == "?") return cont(classfield) - if (type == ":") return cont(typeexpr, maybeAssign) - if (value == "=") return cont(expressionNoComma) - var context = cx.state.lexical.prev, isInterface = context && context.info == "interface" - return pass(isInterface ? functiondecl : functiondef) - } - function afterExport(type, value) { - if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); } - if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); } - if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";")); - return pass(statement); - } - function exportField(type, value) { - if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); } - if (type == "variable") return pass(expressionNoComma, exportField); - } - function afterImport(type) { - if (type == "string") return cont(); - if (type == "(") return pass(expression); - return pass(importSpec, maybeMoreImports, maybeFrom); - } - function importSpec(type, value) { - if (type == "{") return contCommasep(importSpec, "}"); - if (type == "variable") register(value); - if (value == "*") cx.marked = "keyword"; - return cont(maybeAs); - } - function maybeMoreImports(type) { - if (type == ",") return cont(importSpec, maybeMoreImports) - } - function maybeAs(_type, value) { - if (value == "as") { cx.marked = "keyword"; return cont(importSpec); } - } - function maybeFrom(_type, value) { - if (value == "from") { cx.marked = "keyword"; return cont(expression); } - } - function arrayLiteral(type) { - if (type == "]") return cont(); - return pass(commasep(expressionNoComma, "]")); - } - function enumdef() { - return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex) - } - function enummember() { - return pass(pattern, maybeAssign); - } - - function isContinuedStatement(state, textAfter) { - return state.lastType == "operator" || state.lastType == "," || - isOperatorChar.test(textAfter.charAt(0)) || - /[,.]/.test(textAfter.charAt(0)); - } - - function expressionAllowed(stream, state, backUp) { - return state.tokenize == tokenBase && - /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) || - (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0)))) - } - - // Interface - - return { - startState: function(basecolumn) { - var state = { - tokenize: tokenBase, - lastType: "sof", - cc: [], - lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false), - localVars: parserConfig.localVars, - context: parserConfig.localVars && new Context(null, null, false), - indented: basecolumn || 0 - }; - if (parserConfig.globalVars && typeof parserConfig.globalVars == "object") - state.globalVars = parserConfig.globalVars; - return state; - }, - - token: function(stream, state) { - if (stream.sol()) { - if (!state.lexical.hasOwnProperty("align")) - state.lexical.align = false; - state.indented = stream.indentation(); - findFatArrow(stream, state); - } - if (state.tokenize != tokenComment && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (type == "comment") return style; - state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type; - return parseJS(state, style, type, content, stream); - }, - - indent: function(state, textAfter) { - if (state.tokenize == tokenComment) return CodeMirror.Pass; - if (state.tokenize != tokenBase) return 0; - var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top - // Kludge to prevent 'maybelse' from blocking lexical scope pops - if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) { - var c = state.cc[i]; - if (c == poplex) lexical = lexical.prev; - else if (c != maybeelse) break; - } - while ((lexical.type == "stat" || lexical.type == "form") && - (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) && - (top == maybeoperatorComma || top == maybeoperatorNoComma) && - !/^[,\.=+\-*:?[\(]/.test(textAfter)))) - lexical = lexical.prev; - if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat") - lexical = lexical.prev; - var type = lexical.type, closing = firstChar == type; - - if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0); - else if (type == "form" && firstChar == "{") return lexical.indented; - else if (type == "form") return lexical.indented + indentUnit; - else if (type == "stat") - return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0); - else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false) - return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit); - else if (lexical.align) return lexical.column + (closing ? 0 : 1); - else return lexical.indented + (closing ? 0 : indentUnit); - }, - - electricInput: /^\s*(?:case .*?:|default:|\{|\})$/, - blockCommentStart: jsonMode ? null : "/*", - blockCommentEnd: jsonMode ? null : "*/", - blockCommentContinue: jsonMode ? null : " * ", - lineComment: jsonMode ? null : "//", - fold: "brace", - closeBrackets: "()[]{}''\"\"``", - - helperType: jsonMode ? "json" : "javascript", - jsonldMode: jsonldMode, - jsonMode: jsonMode, - - expressionAllowed: expressionAllowed, - - skipExpression: function(state) { - var top = state.cc[state.cc.length - 1] - if (top == expression || top == expressionNoComma) state.cc.pop() - } - }; -}); - -CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/); - -CodeMirror.defineMIME("text/javascript", "javascript"); -CodeMirror.defineMIME("text/ecmascript", "javascript"); -CodeMirror.defineMIME("application/javascript", "javascript"); -CodeMirror.defineMIME("application/x-javascript", "javascript"); -CodeMirror.defineMIME("application/ecmascript", "javascript"); -CodeMirror.defineMIME("application/json", {name: "javascript", json: true}); -CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true}); -CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true}); -CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true }); -CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true }); - -}); -// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: https://codemirror.net/LICENSE - -(function(mod) { - if (typeof exports == "object" && typeof module == "object") // CommonJS - mod(require("../../lib/codemirror")); - else if (typeof define == "function" && define.amd) // AMD - define(["../../lib/codemirror"], mod); - else // Plain browser env - mod(CodeMirror); -})(function(CodeMirror) { -"use strict"; - -function Context(indented, column, type, info, align, prev) { - this.indented = indented; - this.column = column; - this.type = type; - this.info = info; - this.align = align; - this.prev = prev; -} -function pushContext(state, col, type, info) { - var indent = state.indented; - if (state.context && state.context.type == "statement" && type != "statement") - indent = state.context.indented; - return state.context = new Context(indent, col, type, info, null, state.context); -} -function popContext(state) { - var t = state.context.type; - if (t == ")" || t == "]" || t == "}") - state.indented = state.context.indented; - return state.context = state.context.prev; -} - -function typeBefore(stream, state, pos) { - if (state.prevToken == "variable" || state.prevToken == "type") return true; - if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true; - if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true; -} - -function isTopScope(context) { - for (;;) { - if (!context || context.type == "top") return true; - if (context.type == "}" && context.prev.info != "namespace") return false; - context = context.prev; - } -} - -CodeMirror.defineMode("clike", function(config, parserConfig) { - var indentUnit = config.indentUnit, - statementIndentUnit = parserConfig.statementIndentUnit || indentUnit, - dontAlignCalls = parserConfig.dontAlignCalls, - keywords = parserConfig.keywords || {}, - types = parserConfig.types || {}, - builtin = parserConfig.builtin || {}, - blockKeywords = parserConfig.blockKeywords || {}, - defKeywords = parserConfig.defKeywords || {}, - atoms = parserConfig.atoms || {}, - hooks = parserConfig.hooks || {}, - multiLineStrings = parserConfig.multiLineStrings, - indentStatements = parserConfig.indentStatements !== false, - indentSwitch = parserConfig.indentSwitch !== false, - namespaceSeparator = parserConfig.namespaceSeparator, - isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/, - numberStart = parserConfig.numberStart || /[\d\.]/, - number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i, - isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/, - isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/, - // An optional function that takes a {string} token and returns true if it - // should be treated as a builtin. - isReservedIdentifier = parserConfig.isReservedIdentifier || false; - - var curPunc, isDefKeyword; - - function tokenBase(stream, state) { - var ch = stream.next(); - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } - if (ch == '"' || ch == "'") { - state.tokenize = tokenString(ch); - return state.tokenize(stream, state); - } - if (isPunctuationChar.test(ch)) { - curPunc = ch; - return null; - } - if (numberStart.test(ch)) { - stream.backUp(1) - if (stream.match(number)) return "number" - stream.next() - } - if (ch == "/") { - if (stream.eat("*")) { - state.tokenize = tokenComment; - return tokenComment(stream, state); - } - if (stream.eat("/")) { - stream.skipToEnd(); - return "comment"; - } - } - if (isOperatorChar.test(ch)) { - while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {} - return "operator"; - } - stream.eatWhile(isIdentifierChar); - if (namespaceSeparator) while (stream.match(namespaceSeparator)) - stream.eatWhile(isIdentifierChar); - - var cur = stream.current(); - if (contains(keywords, cur)) { - if (contains(blockKeywords, cur)) curPunc = "newstatement"; - if (contains(defKeywords, cur)) isDefKeyword = true; - return "keyword"; - } - if (contains(types, cur)) return "type"; - if (contains(builtin, cur) - || (isReservedIdentifier && isReservedIdentifier(cur))) { - if (contains(blockKeywords, cur)) curPunc = "newstatement"; - return "builtin"; - } - if (contains(atoms, cur)) return "atom"; - return "variable"; - } - - function tokenString(quote) { - return function(stream, state) { - var escaped = false, next, end = false; - while ((next = stream.next()) != null) { - if (next == quote && !escaped) {end = true; break;} - escaped = !escaped && next == "\\"; - } - if (end || !(escaped || multiLineStrings)) - state.tokenize = null; - return "string"; - }; - } - - function tokenComment(stream, state) { - var maybeEnd = false, ch; - while (ch = stream.next()) { - if (ch == "/" && maybeEnd) { - state.tokenize = null; - break; - } - maybeEnd = (ch == "*"); - } - return "comment"; - } - - function maybeEOL(stream, state) { - if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context)) - state.typeAtEndOfLine = typeBefore(stream, state, stream.pos) - } - - // Interface - - return { - startState: function(basecolumn) { - return { - tokenize: null, - context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false), - indented: 0, - startOfLine: true, - prevToken: null - }; - }, - - token: function(stream, state) { - var ctx = state.context; - if (stream.sol()) { - if (ctx.align == null) ctx.align = false; - state.indented = stream.indentation(); - state.startOfLine = true; - } - if (stream.eatSpace()) { maybeEOL(stream, state); return null; } - curPunc = isDefKeyword = null; - var style = (state.tokenize || tokenBase)(stream, state); - if (style == "comment" || style == "meta") return style; - if (ctx.align == null) ctx.align = true; - - if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false))) - while (state.context.type == "statement") popContext(state); - else if (curPunc == "{") pushContext(state, stream.column(), "}"); - else if (curPunc == "[") pushContext(state, stream.column(), "]"); - else if (curPunc == "(") pushContext(state, stream.column(), ")"); - else if (curPunc == "}") { - while (ctx.type == "statement") ctx = popContext(state); - if (ctx.type == "}") ctx = popContext(state); - while (ctx.type == "statement") ctx = popContext(state); - } - else if (curPunc == ctx.type) popContext(state); - else if (indentStatements && - (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") || - (ctx.type == "statement" && curPunc == "newstatement"))) { - pushContext(state, stream.column(), "statement", stream.current()); - } - - if (style == "variable" && - ((state.prevToken == "def" || - (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) && - isTopScope(state.context) && stream.match(/^\s*\(/, false))))) - style = "def"; - - if (hooks.token) { - var result = hooks.token(stream, state, style); - if (result !== undefined) style = result; - } - - if (style == "def" && parserConfig.styleDefs === false) style = "variable"; - - state.startOfLine = false; - state.prevToken = isDefKeyword ? "def" : style || curPunc; - maybeEOL(stream, state); - return style; - }, - - indent: function(state, textAfter) { - if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass; - var ctx = state.context, firstChar = textAfter && textAfter.charAt(0); - var closing = firstChar == ctx.type; - if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev; - if (parserConfig.dontIndentStatements) - while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info)) - ctx = ctx.prev - if (hooks.indent) { - var hook = hooks.indent(state, ctx, textAfter, indentUnit); - if (typeof hook == "number") return hook - } - var switchBlock = ctx.prev && ctx.prev.info == "switch"; - if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) { - while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev - return ctx.indented - } - if (ctx.type == "statement") - return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit); - if (ctx.align && (!dontAlignCalls || ctx.type != ")")) - return ctx.column + (closing ? 0 : 1); - if (ctx.type == ")" && !closing) - return ctx.indented + statementIndentUnit; - - return ctx.indented + (closing ? 0 : indentUnit) + - (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0); - }, - - electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/, - blockCommentStart: "/*", - blockCommentEnd: "*/", - blockCommentContinue: " * ", - lineComment: "//", - fold: "brace" - }; -}); - - function words(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } - function contains(words, word) { - if (typeof words === "function") { - return words(word); - } else { - return words.propertyIsEnumerable(word); - } - } - var cKeywords = "auto if break case register continue return default do sizeof " + - "static else struct switch extern typedef union for goto while enum const " + - "volatile inline restrict asm fortran"; - - // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20. - var cppKeywords = "alignas alignof and and_eq audit axiom bitand bitor catch " + - "class compl concept constexpr const_cast decltype delete dynamic_cast " + - "explicit export final friend import module mutable namespace new noexcept " + - "not not_eq operator or or_eq override private protected public " + - "reinterpret_cast requires static_assert static_cast template this " + - "thread_local throw try typeid typename using virtual xor xor_eq"; - - var objCKeywords = "bycopy byref in inout oneway out self super atomic nonatomic retain copy " + - "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " + - "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " + - "@public @package @private @protected @required @optional @try @catch @finally @import " + - "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"; - - var objCBuiltins = "FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION " + - " NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER " + - "NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION " + - "NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT" - - // Do not use this. Use the cTypes function below. This is global just to avoid - // excessive calls when cTypes is being called multiple times during a parse. - var basicCTypes = words("int long char short double float unsigned signed " + - "void bool"); - - // Do not use this. Use the objCTypes function below. This is global just to avoid - // excessive calls when objCTypes is being called multiple times during a parse. - var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL"); - - // Returns true if identifier is a "C" type. - // C type is defined as those that are reserved by the compiler (basicTypes), - // and those that end in _t (Reserved by POSIX for types) - // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html - function cTypes(identifier) { - return contains(basicCTypes, identifier) || /.+_t$/.test(identifier); - } - - // Returns true if identifier is a "Objective C" type. - function objCTypes(identifier) { - return cTypes(identifier) || contains(basicObjCTypes, identifier); - } - - var cBlockKeywords = "case do else for if switch while struct enum union"; - var cDefKeywords = "struct enum union"; - - function cppHook(stream, state) { - if (!state.startOfLine) return false - for (var ch, next = null; ch = stream.peek();) { - if (ch == "\\" && stream.match(/^.$/)) { - next = cppHook - break - } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) { - break - } - stream.next() - } - state.tokenize = next - return "meta" - } - - function pointerHook(_stream, state) { - if (state.prevToken == "type") return "type"; - return false; - } - - // For C and C++ (and ObjC): identifiers starting with __ - // or _ followed by a capital letter are reserved for the compiler. - function cIsReservedIdentifier(token) { - if (!token || token.length < 2) return false; - if (token[0] != '_') return false; - return (token[1] == '_') || (token[1] !== token[1].toLowerCase()); - } - - function cpp14Literal(stream) { - stream.eatWhile(/[\w\.']/); - return "number"; - } - - function cpp11StringHook(stream, state) { - stream.backUp(1); - // Raw strings. - if (stream.match(/(R|u8R|uR|UR|LR)/)) { - var match = stream.match(/"([^\s\\()]{0,16})\(/); - if (!match) { - return false; - } - state.cpp11RawStringDelim = match[1]; - state.tokenize = tokenRawString; - return tokenRawString(stream, state); - } - // Unicode strings/chars. - if (stream.match(/(u8|u|U|L)/)) { - if (stream.match(/["']/, /* eat */ false)) { - return "string"; - } - return false; - } - // Ignore this hook. - stream.next(); - return false; - } - - function cppLooksLikeConstructor(word) { - var lastTwo = /(\w+)::~?(\w+)$/.exec(word); - return lastTwo && lastTwo[1] == lastTwo[2]; - } - - // C#-style strings where "" escapes a quote. - function tokenAtString(stream, state) { - var next; - while ((next = stream.next()) != null) { - if (next == '"' && !stream.eat('"')) { - state.tokenize = null; - break; - } - } - return "string"; - } - - // C++11 raw string literal is "( anything )", where - // can be a string up to 16 characters long. - function tokenRawString(stream, state) { - // Escape characters that have special regex meanings. - var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&'); - var match = stream.match(new RegExp(".*?\\)" + delim + '"')); - if (match) - state.tokenize = null; - else - stream.skipToEnd(); - return "string"; - } - - function def(mimes, mode) { - if (typeof mimes == "string") mimes = [mimes]; - var words = []; - function add(obj) { - if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop)) - words.push(prop); - } - add(mode.keywords); - add(mode.types); - add(mode.builtin); - add(mode.atoms); - if (words.length) { - mode.helperType = mimes[0]; - CodeMirror.registerHelper("hintWords", mimes[0], words); - } - - for (var i = 0; i < mimes.length; ++i) - CodeMirror.defineMIME(mimes[i], mode); - } - - def(["text/x-csrc", "text/x-c", "text/x-chdr"], { - name: "clike", - keywords: words(cKeywords), - types: cTypes, - blockKeywords: words(cBlockKeywords), - defKeywords: words(cDefKeywords), - typeFirstDefinitions: true, - atoms: words("NULL true false"), - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - }, - modeProps: {fold: ["brace", "include"]} - }); - - def(["text/x-c++src", "text/x-c++hdr"], { - name: "clike", - keywords: words(cKeywords + " " + cppKeywords), - types: cTypes, - blockKeywords: words(cBlockKeywords + " class try catch"), - defKeywords: words(cDefKeywords + " class namespace"), - typeFirstDefinitions: true, - atoms: words("true false NULL nullptr"), - dontIndentStatements: /^template$/, - isIdentifierChar: /[\w\$_~\xa1-\uffff]/, - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - "u": cpp11StringHook, - "U": cpp11StringHook, - "L": cpp11StringHook, - "R": cpp11StringHook, - "0": cpp14Literal, - "1": cpp14Literal, - "2": cpp14Literal, - "3": cpp14Literal, - "4": cpp14Literal, - "5": cpp14Literal, - "6": cpp14Literal, - "7": cpp14Literal, - "8": cpp14Literal, - "9": cpp14Literal, - token: function(stream, state, style) { - if (style == "variable" && stream.peek() == "(" && - (state.prevToken == ";" || state.prevToken == null || - state.prevToken == "}") && - cppLooksLikeConstructor(stream.current())) - return "def"; - } - }, - namespaceSeparator: "::", - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-java", { - name: "clike", - keywords: words("abstract assert break case catch class const continue default " + - "do else enum extends final finally for goto if implements import " + - "instanceof interface native new package private protected public " + - "return static strictfp super switch synchronized this throw throws transient " + - "try volatile while @interface"), - types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " + - "Integer Long Number Object Short String StringBuffer StringBuilder Void"), - blockKeywords: words("catch class do else finally for if switch try while"), - defKeywords: words("class interface enum @interface"), - typeFirstDefinitions: true, - atoms: words("true false null"), - number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, - hooks: { - "@": function(stream) { - // Don't match the @interface keyword. - if (stream.match('interface', false)) return false; - - stream.eatWhile(/[\w\$_]/); - return "meta"; - } - }, - modeProps: {fold: ["brace", "import"]} - }); - - def("text/x-csharp", { - name: "clike", - keywords: words("abstract as async await base break case catch checked class const continue" + - " default delegate do else enum event explicit extern finally fixed for" + - " foreach goto if implicit in interface internal is lock namespace new" + - " operator out override params private protected public readonly ref return sealed" + - " sizeof stackalloc static struct switch this throw try typeof unchecked" + - " unsafe using virtual void volatile while add alias ascending descending dynamic from get" + - " global group into join let orderby partial remove select set value var yield"), - types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" + - " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" + - " UInt64 bool byte char decimal double short int long object" + - " sbyte float string ushort uint ulong"), - blockKeywords: words("catch class do else finally for foreach if struct switch try while"), - defKeywords: words("class interface namespace struct var"), - typeFirstDefinitions: true, - atoms: words("true false null"), - hooks: { - "@": function(stream, state) { - if (stream.eat('"')) { - state.tokenize = tokenAtString; - return tokenAtString(stream, state); - } - stream.eatWhile(/[\w\$_]/); - return "meta"; - } - } - }); - - function tokenTripleString(stream, state) { - var escaped = false; - while (!stream.eol()) { - if (!escaped && stream.match('"""')) { - state.tokenize = null; - break; - } - escaped = stream.next() == "\\" && !escaped; - } - return "string"; - } - - function tokenNestedComment(depth) { - return function (stream, state) { - var ch - while (ch = stream.next()) { - if (ch == "*" && stream.eat("/")) { - if (depth == 1) { - state.tokenize = null - break - } else { - state.tokenize = tokenNestedComment(depth - 1) - return state.tokenize(stream, state) - } - } else if (ch == "/" && stream.eat("*")) { - state.tokenize = tokenNestedComment(depth + 1) - return state.tokenize(stream, state) - } - } - return "comment" - } - } - - def("text/x-scala", { - name: "clike", - keywords: words( - /* scala */ - "abstract case catch class def do else extends final finally for forSome if " + - "implicit import lazy match new null object override package private protected return " + - "sealed super this throw trait try type val var while with yield _ " + - - /* package scala */ - "assert assume require print println printf readLine readBoolean readByte readShort " + - "readChar readInt readLong readFloat readDouble" - ), - types: words( - "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " + - "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " + - "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " + - "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " + - "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " + - - /* package java.lang */ - "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + - "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + - "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + - "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void" - ), - multiLineStrings: true, - blockKeywords: words("catch class enum do else finally for forSome if match switch try while"), - defKeywords: words("class enum def object package trait type val var"), - atoms: words("true false null"), - indentStatements: false, - indentSwitch: false, - isOperatorChar: /[+\-*&%=<>!?|\/#:@]/, - hooks: { - "@": function(stream) { - stream.eatWhile(/[\w\$_]/); - return "meta"; - }, - '"': function(stream, state) { - if (!stream.match('""')) return false; - state.tokenize = tokenTripleString; - return state.tokenize(stream, state); - }, - "'": function(stream) { - stream.eatWhile(/[\w\$_\xa1-\uffff]/); - return "atom"; - }, - "=": function(stream, state) { - var cx = state.context - if (cx.type == "}" && cx.align && stream.eat(">")) { - state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev) - return "operator" - } else { - return false - } - }, - - "/": function(stream, state) { - if (!stream.eat("*")) return false - state.tokenize = tokenNestedComment(1) - return state.tokenize(stream, state) - } - }, - modeProps: {closeBrackets: {pairs: '()[]{}""', triples: '"'}} - }); - - function tokenKotlinString(tripleString){ - return function (stream, state) { - var escaped = false, next, end = false; - while (!stream.eol()) { - if (!tripleString && !escaped && stream.match('"') ) {end = true; break;} - if (tripleString && stream.match('"""')) {end = true; break;} - next = stream.next(); - if(!escaped && next == "$" && stream.match('{')) - stream.skipTo("}"); - escaped = !escaped && next == "\\" && !tripleString; - } - if (end || !tripleString) - state.tokenize = null; - return "string"; - } - } - - def("text/x-kotlin", { - name: "clike", - keywords: words( - /*keywords*/ - "package as typealias class interface this super val operator " + - "var fun for is in This throw return annotation " + - "break continue object if else while do try when !in !is as? " + - - /*soft keywords*/ - "file import where by get set abstract enum open inner override private public internal " + - "protected catch finally out final vararg reified dynamic companion constructor init " + - "sealed field property receiver param sparam lateinit data inline noinline tailrec " + - "external annotation crossinline const operator infix suspend actual expect setparam" - ), - types: words( - /* package java.lang */ - "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " + - "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " + - "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " + - "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " + - "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " + - "LazyThreadSafetyMode LongArray Nothing ShortArray Unit" - ), - intendSwitch: false, - indentStatements: false, - multiLineStrings: true, - number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i, - blockKeywords: words("catch class do else finally for if where try while enum"), - defKeywords: words("class val var object interface fun"), - atoms: words("true false null this"), - hooks: { - "@": function(stream) { - stream.eatWhile(/[\w\$_]/); - return "meta"; - }, - '*': function(_stream, state) { - return state.prevToken == '.' ? 'variable' : 'operator'; - }, - '"': function(stream, state) { - state.tokenize = tokenKotlinString(stream.match('""')); - return state.tokenize(stream, state); - }, - "/": function(stream, state) { - if (!stream.eat("*")) return false; - state.tokenize = tokenNestedComment(1); - return state.tokenize(stream, state) - }, - indent: function(state, ctx, textAfter, indentUnit) { - var firstChar = textAfter && textAfter.charAt(0); - if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "") - return state.indented; - if ((state.prevToken == "operator" && textAfter != "}" && state.context.type != "}") || - state.prevToken == "variable" && firstChar == "." || - (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".") - return indentUnit * 2 + ctx.indented; - if (ctx.align && ctx.type == "}") - return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit); - } - }, - modeProps: {closeBrackets: {triples: '"'}} - }); - - def(["x-shader/x-vertex", "x-shader/x-fragment"], { - name: "clike", - keywords: words("sampler1D sampler2D sampler3D samplerCube " + - "sampler1DShadow sampler2DShadow " + - "const attribute uniform varying " + - "break continue discard return " + - "for while do if else struct " + - "in out inout"), - types: words("float int bool void " + - "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " + - "mat2 mat3 mat4"), - blockKeywords: words("for while do if else struct"), - builtin: words("radians degrees sin cos tan asin acos atan " + - "pow exp log exp2 sqrt inversesqrt " + - "abs sign floor ceil fract mod min max clamp mix step smoothstep " + - "length distance dot cross normalize ftransform faceforward " + - "reflect refract matrixCompMult " + - "lessThan lessThanEqual greaterThan greaterThanEqual " + - "equal notEqual any all not " + - "texture1D texture1DProj texture1DLod texture1DProjLod " + - "texture2D texture2DProj texture2DLod texture2DProjLod " + - "texture3D texture3DProj texture3DLod texture3DProjLod " + - "textureCube textureCubeLod " + - "shadow1D shadow2D shadow1DProj shadow2DProj " + - "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " + - "dFdx dFdy fwidth " + - "noise1 noise2 noise3 noise4"), - atoms: words("true false " + - "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " + - "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " + - "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " + - "gl_FogCoord gl_PointCoord " + - "gl_Position gl_PointSize gl_ClipVertex " + - "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " + - "gl_TexCoord gl_FogFragCoord " + - "gl_FragCoord gl_FrontFacing " + - "gl_FragData gl_FragDepth " + - "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " + - "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " + - "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " + - "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " + - "gl_ProjectionMatrixInverseTranspose " + - "gl_ModelViewProjectionMatrixInverseTranspose " + - "gl_TextureMatrixInverseTranspose " + - "gl_NormalScale gl_DepthRange gl_ClipPlane " + - "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " + - "gl_FrontLightModelProduct gl_BackLightModelProduct " + - "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " + - "gl_FogParameters " + - "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " + - "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " + - "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " + - "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " + - "gl_MaxDrawBuffers"), - indentSwitch: false, - hooks: {"#": cppHook}, - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-nesc", { - name: "clike", - keywords: words(cKeywords + " as atomic async call command component components configuration event generic " + - "implementation includes interface module new norace nx_struct nx_union post provides " + - "signal task uses abstract extends"), - types: cTypes, - blockKeywords: words(cBlockKeywords), - atoms: words("null true false"), - hooks: {"#": cppHook}, - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-objectivec", { - name: "clike", - keywords: words(cKeywords + " " + objCKeywords), - types: objCTypes, - builtin: words(objCBuiltins), - blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"), - defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"), - dontIndentStatements: /^@.*$/, - typeFirstDefinitions: true, - atoms: words("YES NO NULL Nil nil true false nullptr"), - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - }, - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-objectivec++", { - name: "clike", - keywords: words(cKeywords + " " + objCKeywords + " " + cppKeywords), - types: objCTypes, - builtin: words(objCBuiltins), - blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"), - defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class class namespace"), - dontIndentStatements: /^@.*$|^template$/, - typeFirstDefinitions: true, - atoms: words("YES NO NULL Nil nil true false nullptr"), - isReservedIdentifier: cIsReservedIdentifier, - hooks: { - "#": cppHook, - "*": pointerHook, - "u": cpp11StringHook, - "U": cpp11StringHook, - "L": cpp11StringHook, - "R": cpp11StringHook, - "0": cpp14Literal, - "1": cpp14Literal, - "2": cpp14Literal, - "3": cpp14Literal, - "4": cpp14Literal, - "5": cpp14Literal, - "6": cpp14Literal, - "7": cpp14Literal, - "8": cpp14Literal, - "9": cpp14Literal, - token: function(stream, state, style) { - if (style == "variable" && stream.peek() == "(" && - (state.prevToken == ";" || state.prevToken == null || - state.prevToken == "}") && - cppLooksLikeConstructor(stream.current())) - return "def"; - } - }, - namespaceSeparator: "::", - modeProps: {fold: ["brace", "include"]} - }); - - def("text/x-squirrel", { - name: "clike", - keywords: words("base break clone continue const default delete enum extends function in class" + - " foreach local resume return this throw typeof yield constructor instanceof static"), - types: cTypes, - blockKeywords: words("case catch class else for foreach if switch try while"), - defKeywords: words("function local class"), - typeFirstDefinitions: true, - atoms: words("true false null"), - hooks: {"#": cppHook}, - modeProps: {fold: ["brace", "include"]} - }); - - // Ceylon Strings need to deal with interpolation - var stringTokenizer = null; - function tokenCeylonString(type) { - return function(stream, state) { - var escaped = false, next, end = false; - while (!stream.eol()) { - if (!escaped && stream.match('"') && - (type == "single" || stream.match('""'))) { - end = true; - break; - } - if (!escaped && stream.match('``')) { - stringTokenizer = tokenCeylonString(type); - end = true; - break; - } - next = stream.next(); - escaped = type == "single" && !escaped && next == "\\"; - } - if (end) - state.tokenize = null; - return "string"; - } - } - - def("text/x-ceylon", { - name: "clike", - keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" + - " exists extends finally for function given if import in interface is let module new" + - " nonempty object of out outer package return satisfies super switch then this throw" + - " try value void while"), - types: function(word) { - // In Ceylon all identifiers that start with an uppercase are types - var first = word.charAt(0); - return (first === first.toUpperCase() && first !== first.toLowerCase()); - }, - blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"), - defKeywords: words("class dynamic function interface module object package value"), - builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" + - " native optional sealed see serializable shared suppressWarnings tagged throws variable"), - isPunctuationChar: /[\[\]{}\(\),;\:\.`]/, - isOperatorChar: /[+\-*&%=<>!?|^~:\/]/, - numberStart: /[\d#$]/, - number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i, - multiLineStrings: true, - typeFirstDefinitions: true, - atoms: words("true false null larger smaller equal empty finished"), - indentSwitch: false, - styleDefs: false, - hooks: { - "@": function(stream) { - stream.eatWhile(/[\w\$_]/); - return "meta"; - }, - '"': function(stream, state) { - state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single"); - return state.tokenize(stream, state); - }, - '`': function(stream, state) { - if (!stringTokenizer || !stream.match('`')) return false; - state.tokenize = stringTokenizer; - stringTokenizer = null; - return state.tokenize(stream, state); - }, - "'": function(stream) { - stream.eatWhile(/[\w\$_\xa1-\uffff]/); - return "atom"; - }, - token: function(_stream, state, style) { - if ((style == "variable" || style == "type") && - state.prevToken == ".") { - return "variable-2"; - } - } - }, - modeProps: { - fold: ["brace", "import"], - closeBrackets: {triples: '"'} - } - }); - -}); - -// showdown - https://github.com/showdownjs/showdown -/*! showdown v 1.8.6 - 22-12-2017 */ -(function(){function g(g){"use strict";var A={omitExtraWLInCodeBlocks:{defaultValue:!1,describe:"Omit the default extra whiteline added to code blocks",type:"boolean"},noHeaderId:{defaultValue:!1,describe:"Turn on/off generated header id",type:"boolean"},prefixHeaderId:{defaultValue:!1,describe:"Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic 'section-' prefix",type:"string"},rawPrefixHeaderId:{defaultValue:!1,describe:'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the " char is used in the prefix)',type:"boolean"},ghCompatibleHeaderId:{defaultValue:!1,describe:"Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)",type:"boolean"},rawHeaderId:{defaultValue:!1,describe:"Remove only spaces, ' and \" from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids",type:"boolean"},headerLevelStart:{defaultValue:!1,describe:"The header blocks level start",type:"integer"},parseImgDimensions:{defaultValue:!1,describe:"Turn on/off image dimension parsing",type:"boolean"},simplifiedAutoLink:{defaultValue:!1,describe:"Turn on/off GFM autolink style",type:"boolean"},excludeTrailingPunctuationFromURLs:{defaultValue:!1,describe:"Excludes trailing punctuation from links generated with autoLinking",type:"boolean"},literalMidWordUnderscores:{defaultValue:!1,describe:"Parse midword underscores as literal underscores",type:"boolean"},literalMidWordAsterisks:{defaultValue:!1,describe:"Parse midword asterisks as literal asterisks",type:"boolean"},strikethrough:{defaultValue:!1,describe:"Turn on/off strikethrough support",type:"boolean"},tables:{defaultValue:!1,describe:"Turn on/off tables support",type:"boolean"},tablesHeaderId:{defaultValue:!1,describe:"Add an id to table headers",type:"boolean"},ghCodeBlocks:{defaultValue:!0,describe:"Turn on/off GFM fenced code blocks support",type:"boolean"},tasklists:{defaultValue:!1,describe:"Turn on/off GFM tasklist support",type:"boolean"},smoothLivePreview:{defaultValue:!1,describe:"Prevents weird effects in live previews due to incomplete input",type:"boolean"},smartIndentationFix:{defaultValue:!1,description:"Tries to smartly fix indentation in es6 strings",type:"boolean"},disableForced4SpacesIndentedSublists:{defaultValue:!1,description:"Disables the requirement of indenting nested sublists by 4 spaces",type:"boolean"},simpleLineBreaks:{defaultValue:!1,description:"Parses simple line breaks as
(GFM Style)",type:"boolean"},requireSpaceBeforeHeadingText:{defaultValue:!1,description:"Makes adding a space between `#` and the header text mandatory (GFM Style)",type:"boolean"},ghMentions:{defaultValue:!1,description:"Enables github @mentions",type:"boolean"},ghMentionsLink:{defaultValue:"https://github.com/{u}",description:"Changes the link generated by @mentions. Only applies if ghMentions option is enabled.",type:"string"},encodeEmails:{defaultValue:!0,description:"Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities",type:"boolean"},openLinksInNewWindow:{defaultValue:!1,description:"Open all links in new windows",type:"boolean"},backslashEscapesHTMLTags:{defaultValue:!1,description:"Support for HTML Tag escaping. ex:
foo
",type:"boolean"},emoji:{defaultValue:!1,description:"Enable emoji support. Ex: `this is a :smile: emoji`",type:"boolean"},underline:{defaultValue:!1,description:"Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `` and ``",type:"boolean"},completeHTMLDocument:{defaultValue:!1,description:"Outputs a complete html document, including ``, `` and `` tags",type:"boolean"},metadata:{defaultValue:!1,description:"Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).",type:"boolean"},splitAdjacentBlockquotes:{defaultValue:!1,description:"Split adjacent blockquote blocks",type:"boolean"}};if(!1===g)return JSON.parse(JSON.stringify(A));var C={};for(var I in A)A.hasOwnProperty(I)&&(C[I]=A[I].defaultValue);return C}function A(g,A){"use strict";var C=A?"Error in "+A+" extension->":"Error in unnamed extension",e={valid:!0,error:""};I.helper.isArray(g)||(g=[g]);for(var r=0;r-1,i=new RegExp(A+"|"+C,"g"+o.replace(/g/g,"")),l=new RegExp(A,o.replace(/g/g,"")),c=[];do{for(e=0;t=i.exec(g);)if(l.test(t[0]))e++||(a=(r=i.lastIndex)-t[0].length);else if(e&&!--e){n=t.index+t[0].length;var u={left:{start:a,end:r},match:{start:r,end:t.index},right:{start:t.index,end:n},wholeMatch:{start:a,end:n}};if(c.push(u),!s)return c}}while(e&&(i.lastIndex=r));return c};I.helper.matchRecursiveRegExp=function(g,A,C,I){"use strict";for(var e=o(g,A,C,I),r=[],t=0;t0){var i=[];0!==a[0].wholeMatch.start&&i.push(g.slice(0,a[0].wholeMatch.start));for(var l=0;l=0?e+(C||0):e},I.helper.splitAtIndex=function(g,A){"use strict";if(!I.helper.isString(g))throw"InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string";return[g.substring(0,A),g.substring(A)]},I.helper.encodeEmailAddress=function(g){"use strict";var A=[function(g){return"&#"+g.charCodeAt(0)+";"},function(g){return"&#x"+g.charCodeAt(0).toString(16)+";"},function(g){return g}];return g=g.replace(/./g,function(g){if("@"===g)g=A[Math.floor(2*Math.random())](g);else{var C=Math.random();g=C>.9?A[2](g):C>.45?A[1](g):A[0](g)}return g})},"undefined"==typeof console&&(console={warn:function(g){"use strict";alert(g)},log:function(g){"use strict";alert(g)},error:function(g){"use strict";throw g}}),I.helper.regexes={asteriskDashAndColon:/([*_:~])/g},I.helper.emojis={"+1":"👍","-1":"👎",100:"💯",1234:"🔢","1st_place_medal":"🥇","2nd_place_medal":"🥈","3rd_place_medal":"🥉","8ball":"🎱",a:"🅰️",ab:"🆎",abc:"🔤",abcd:"🔡",accept:"🉑",aerial_tramway:"🚡",airplane:"✈️",alarm_clock:"⏰",alembic:"⚗️",alien:"👽",ambulance:"🚑",amphora:"🏺",anchor:"⚓️",angel:"👼",anger:"💢",angry:"😠",anguished:"😧",ant:"🐜",apple:"🍎",aquarius:"♒️",aries:"♈️",arrow_backward:"◀️",arrow_double_down:"⏬",arrow_double_up:"⏫",arrow_down:"⬇️",arrow_down_small:"🔽",arrow_forward:"▶️",arrow_heading_down:"⤵️",arrow_heading_up:"⤴️",arrow_left:"⬅️",arrow_lower_left:"↙️",arrow_lower_right:"↘️",arrow_right:"➡️",arrow_right_hook:"↪️",arrow_up:"⬆️",arrow_up_down:"↕️",arrow_up_small:"🔼",arrow_upper_left:"↖️",arrow_upper_right:"↗️",arrows_clockwise:"🔃",arrows_counterclockwise:"🔄",art:"🎨",articulated_lorry:"🚛",artificial_satellite:"🛰",astonished:"😲",athletic_shoe:"👟",atm:"🏧",atom_symbol:"⚛️",avocado:"🥑",b:"🅱️",baby:"👶",baby_bottle:"🍼",baby_chick:"🐤",baby_symbol:"🚼",back:"🔙",bacon:"🥓",badminton:"🏸",baggage_claim:"🛄",baguette_bread:"🥖",balance_scale:"⚖️",balloon:"🎈",ballot_box:"🗳",ballot_box_with_check:"☑️",bamboo:"🎍",banana:"🍌",bangbang:"‼️",bank:"🏦",bar_chart:"📊",barber:"💈",baseball:"⚾️",basketball:"🏀",basketball_man:"⛹️",basketball_woman:"⛹️‍♀️",bat:"🦇",bath:"🛀",bathtub:"🛁",battery:"🔋",beach_umbrella:"🏖",bear:"🐻",bed:"🛏",bee:"🐝",beer:"🍺",beers:"🍻",beetle:"🐞",beginner:"🔰",bell:"🔔",bellhop_bell:"🛎",bento:"🍱",biking_man:"🚴",bike:"🚲",biking_woman:"🚴‍♀️",bikini:"👙",biohazard:"☣️",bird:"🐦",birthday:"🎂",black_circle:"⚫️",black_flag:"🏴",black_heart:"🖤",black_joker:"🃏",black_large_square:"⬛️",black_medium_small_square:"◾️",black_medium_square:"◼️",black_nib:"✒️",black_small_square:"▪️",black_square_button:"🔲",blonde_man:"👱",blonde_woman:"👱‍♀️",blossom:"🌼",blowfish:"🐡",blue_book:"📘",blue_car:"🚙",blue_heart:"💙",blush:"😊",boar:"🐗",boat:"⛵️",bomb:"💣",book:"📖",bookmark:"🔖",bookmark_tabs:"📑",books:"📚",boom:"💥",boot:"👢",bouquet:"💐",bowing_man:"🙇",bow_and_arrow:"🏹",bowing_woman:"🙇‍♀️",bowling:"🎳",boxing_glove:"🥊",boy:"👦",bread:"🍞",bride_with_veil:"👰",bridge_at_night:"🌉",briefcase:"💼",broken_heart:"💔",bug:"🐛",building_construction:"🏗",bulb:"💡",bullettrain_front:"🚅",bullettrain_side:"🚄",burrito:"🌯",bus:"🚌",business_suit_levitating:"🕴",busstop:"🚏",bust_in_silhouette:"👤",busts_in_silhouette:"👥",butterfly:"🦋",cactus:"🌵",cake:"🍰",calendar:"📆",call_me_hand:"🤙",calling:"📲",camel:"🐫",camera:"📷",camera_flash:"📸",camping:"🏕",cancer:"♋️",candle:"🕯",candy:"🍬",canoe:"🛶",capital_abcd:"🔠",capricorn:"♑️",car:"🚗",card_file_box:"🗃",card_index:"📇",card_index_dividers:"🗂",carousel_horse:"🎠",carrot:"🥕",cat:"🐱",cat2:"🐈",cd:"💿",chains:"⛓",champagne:"🍾",chart:"💹",chart_with_downwards_trend:"📉",chart_with_upwards_trend:"📈",checkered_flag:"🏁",cheese:"🧀",cherries:"🍒",cherry_blossom:"🌸",chestnut:"🌰",chicken:"🐔",children_crossing:"🚸",chipmunk:"🐿",chocolate_bar:"🍫",christmas_tree:"🎄",church:"⛪️",cinema:"🎦",circus_tent:"🎪",city_sunrise:"🌇",city_sunset:"🌆",cityscape:"🏙",cl:"🆑",clamp:"🗜",clap:"👏",clapper:"🎬",classical_building:"🏛",clinking_glasses:"🥂",clipboard:"📋",clock1:"🕐",clock10:"🕙",clock1030:"🕥",clock11:"🕚",clock1130:"🕦",clock12:"🕛",clock1230:"🕧",clock130:"🕜",clock2:"🕑",clock230:"🕝",clock3:"🕒",clock330:"🕞",clock4:"🕓",clock430:"🕟",clock5:"🕔",clock530:"🕠",clock6:"🕕",clock630:"🕡",clock7:"🕖",clock730:"🕢",clock8:"🕗",clock830:"🕣",clock9:"🕘",clock930:"🕤",closed_book:"📕",closed_lock_with_key:"🔐",closed_umbrella:"🌂",cloud:"☁️",cloud_with_lightning:"🌩",cloud_with_lightning_and_rain:"⛈",cloud_with_rain:"🌧",cloud_with_snow:"🌨",clown_face:"🤡",clubs:"♣️",cocktail:"🍸",coffee:"☕️",coffin:"⚰️",cold_sweat:"😰",comet:"☄️",computer:"💻",computer_mouse:"🖱",confetti_ball:"🎊",confounded:"😖",confused:"😕",congratulations:"㊗️",construction:"🚧",construction_worker_man:"👷",construction_worker_woman:"👷‍♀️",control_knobs:"🎛",convenience_store:"🏪",cookie:"🍪",cool:"🆒",policeman:"👮",copyright:"©️",corn:"🌽",couch_and_lamp:"🛋",couple:"👫",couple_with_heart_woman_man:"💑",couple_with_heart_man_man:"👨‍❤️‍👨",couple_with_heart_woman_woman:"👩‍❤️‍👩",couplekiss_man_man:"👨‍❤️‍💋‍👨",couplekiss_man_woman:"💏",couplekiss_woman_woman:"👩‍❤️‍💋‍👩",cow:"🐮",cow2:"🐄",cowboy_hat_face:"🤠",crab:"🦀",crayon:"🖍",credit_card:"💳",crescent_moon:"🌙",cricket:"🏏",crocodile:"🐊",croissant:"🥐",crossed_fingers:"🤞",crossed_flags:"🎌",crossed_swords:"⚔️",crown:"👑",cry:"😢",crying_cat_face:"😿",crystal_ball:"🔮",cucumber:"🥒",cupid:"💘",curly_loop:"➰",currency_exchange:"💱",curry:"🍛",custard:"🍮",customs:"🛃",cyclone:"🌀",dagger:"🗡",dancer:"💃",dancing_women:"👯",dancing_men:"👯‍♂️",dango:"🍡",dark_sunglasses:"🕶",dart:"🎯",dash:"💨",date:"📅",deciduous_tree:"🌳",deer:"🦌",department_store:"🏬",derelict_house:"🏚",desert:"🏜",desert_island:"🏝",desktop_computer:"🖥",male_detective:"🕵️",diamond_shape_with_a_dot_inside:"💠",diamonds:"♦️",disappointed:"😞",disappointed_relieved:"😥",dizzy:"💫",dizzy_face:"😵",do_not_litter:"🚯",dog:"🐶",dog2:"🐕",dollar:"💵",dolls:"🎎",dolphin:"🐬",door:"🚪",doughnut:"🍩",dove:"🕊",dragon:"🐉",dragon_face:"🐲",dress:"👗",dromedary_camel:"🐪",drooling_face:"🤤",droplet:"💧",drum:"🥁",duck:"🦆",dvd:"📀","e-mail":"📧",eagle:"🦅",ear:"👂",ear_of_rice:"🌾",earth_africa:"🌍",earth_americas:"🌎",earth_asia:"🌏",egg:"🥚",eggplant:"🍆",eight_pointed_black_star:"✴️",eight_spoked_asterisk:"✳️",electric_plug:"🔌",elephant:"🐘",email:"✉️",end:"🔚",envelope_with_arrow:"📩",euro:"💶",european_castle:"🏰",european_post_office:"🏤",evergreen_tree:"🌲",exclamation:"❗️",expressionless:"😑",eye:"👁",eye_speech_bubble:"👁‍🗨",eyeglasses:"👓",eyes:"👀",face_with_head_bandage:"🤕",face_with_thermometer:"🤒",fist_oncoming:"👊",factory:"🏭",fallen_leaf:"🍂",family_man_woman_boy:"👪",family_man_boy:"👨‍👦",family_man_boy_boy:"👨‍👦‍👦",family_man_girl:"👨‍👧",family_man_girl_boy:"👨‍👧‍👦",family_man_girl_girl:"👨‍👧‍👧",family_man_man_boy:"👨‍👨‍👦",family_man_man_boy_boy:"👨‍👨‍👦‍👦",family_man_man_girl:"👨‍👨‍👧",family_man_man_girl_boy:"👨‍👨‍👧‍👦",family_man_man_girl_girl:"👨‍👨‍👧‍👧",family_man_woman_boy_boy:"👨‍👩‍👦‍👦",family_man_woman_girl:"👨‍👩‍👧",family_man_woman_girl_boy:"👨‍👩‍👧‍👦",family_man_woman_girl_girl:"👨‍👩‍👧‍👧",family_woman_boy:"👩‍👦",family_woman_boy_boy:"👩‍👦‍👦",family_woman_girl:"👩‍👧",family_woman_girl_boy:"👩‍👧‍👦",family_woman_girl_girl:"👩‍👧‍👧",family_woman_woman_boy:"👩‍👩‍👦",family_woman_woman_boy_boy:"👩‍👩‍👦‍👦",family_woman_woman_girl:"👩‍👩‍👧",family_woman_woman_girl_boy:"👩‍👩‍👧‍👦",family_woman_woman_girl_girl:"👩‍👩‍👧‍👧",fast_forward:"⏩",fax:"📠",fearful:"😨",feet:"🐾",female_detective:"🕵️‍♀️",ferris_wheel:"🎡",ferry:"⛴",field_hockey:"🏑",file_cabinet:"🗄",file_folder:"📁",film_projector:"📽",film_strip:"🎞",fire:"🔥",fire_engine:"🚒",fireworks:"🎆",first_quarter_moon:"🌓",first_quarter_moon_with_face:"🌛",fish:"🐟",fish_cake:"🍥",fishing_pole_and_fish:"🎣",fist_raised:"✊",fist_left:"🤛",fist_right:"🤜",flags:"🎏",flashlight:"🔦",fleur_de_lis:"⚜️",flight_arrival:"🛬",flight_departure:"🛫",floppy_disk:"💾",flower_playing_cards:"🎴",flushed:"😳",fog:"🌫",foggy:"🌁",football:"🏈",footprints:"👣",fork_and_knife:"🍴",fountain:"⛲️",fountain_pen:"🖋",four_leaf_clover:"🍀",fox_face:"🦊",framed_picture:"🖼",free:"🆓",fried_egg:"🍳",fried_shrimp:"🍤",fries:"🍟",frog:"🐸",frowning:"😦",frowning_face:"☹️",frowning_man:"🙍‍♂️",frowning_woman:"🙍",middle_finger:"🖕",fuelpump:"⛽️",full_moon:"🌕",full_moon_with_face:"🌝",funeral_urn:"⚱️",game_die:"🎲",gear:"⚙️",gem:"💎",gemini:"♊️",ghost:"👻",gift:"🎁",gift_heart:"💝",girl:"👧",globe_with_meridians:"🌐",goal_net:"🥅",goat:"🐐",golf:"⛳️",golfing_man:"🏌️",golfing_woman:"🏌️‍♀️",gorilla:"🦍",grapes:"🍇",green_apple:"🍏",green_book:"📗",green_heart:"💚",green_salad:"🥗",grey_exclamation:"❕",grey_question:"❔",grimacing:"😬",grin:"😁",grinning:"😀",guardsman:"💂",guardswoman:"💂‍♀️",guitar:"🎸",gun:"🔫",haircut_woman:"💇",haircut_man:"💇‍♂️",hamburger:"🍔",hammer:"🔨",hammer_and_pick:"⚒",hammer_and_wrench:"🛠",hamster:"🐹",hand:"✋",handbag:"👜",handshake:"🤝",hankey:"💩",hatched_chick:"🐥",hatching_chick:"🐣",headphones:"🎧",hear_no_evil:"🙉",heart:"❤️",heart_decoration:"💟",heart_eyes:"😍",heart_eyes_cat:"😻",heartbeat:"💓",heartpulse:"💗",hearts:"♥️",heavy_check_mark:"✔️",heavy_division_sign:"➗",heavy_dollar_sign:"💲",heavy_heart_exclamation:"❣️",heavy_minus_sign:"➖",heavy_multiplication_x:"✖️",heavy_plus_sign:"➕",helicopter:"🚁",herb:"🌿",hibiscus:"🌺",high_brightness:"🔆",high_heel:"👠",hocho:"🔪",hole:"🕳",honey_pot:"🍯",horse:"🐴",horse_racing:"🏇",hospital:"🏥",hot_pepper:"🌶",hotdog:"🌭",hotel:"🏨",hotsprings:"♨️",hourglass:"⌛️",hourglass_flowing_sand:"⏳",house:"🏠",house_with_garden:"🏡",houses:"🏘",hugs:"🤗",hushed:"😯",ice_cream:"🍨",ice_hockey:"🏒",ice_skate:"⛸",icecream:"🍦",id:"🆔",ideograph_advantage:"🉐",imp:"👿",inbox_tray:"📥",incoming_envelope:"📨",tipping_hand_woman:"💁",information_source:"ℹ️",innocent:"😇",interrobang:"⁉️",iphone:"📱",izakaya_lantern:"🏮",jack_o_lantern:"🎃",japan:"🗾",japanese_castle:"🏯",japanese_goblin:"👺",japanese_ogre:"👹",jeans:"👖",joy:"😂",joy_cat:"😹",joystick:"🕹",kaaba:"🕋",key:"🔑",keyboard:"⌨️",keycap_ten:"🔟",kick_scooter:"🛴",kimono:"👘",kiss:"💋",kissing:"😗",kissing_cat:"😽",kissing_closed_eyes:"😚",kissing_heart:"😘",kissing_smiling_eyes:"😙",kiwi_fruit:"🥝",koala:"🐨",koko:"🈁",label:"🏷",large_blue_circle:"🔵",large_blue_diamond:"🔷",large_orange_diamond:"🔶",last_quarter_moon:"🌗",last_quarter_moon_with_face:"🌜",latin_cross:"✝️",laughing:"😆",leaves:"🍃",ledger:"📒",left_luggage:"🛅",left_right_arrow:"↔️",leftwards_arrow_with_hook:"↩️",lemon:"🍋",leo:"♌️",leopard:"🐆",level_slider:"🎚",libra:"♎️",light_rail:"🚈",link:"🔗",lion:"🦁",lips:"👄",lipstick:"💄",lizard:"🦎",lock:"🔒",lock_with_ink_pen:"🔏",lollipop:"🍭",loop:"➿",loud_sound:"🔊",loudspeaker:"📢",love_hotel:"🏩",love_letter:"💌",low_brightness:"🔅",lying_face:"🤥",m:"Ⓜ️",mag:"🔍",mag_right:"🔎",mahjong:"🀄️",mailbox:"📫",mailbox_closed:"📪",mailbox_with_mail:"📬",mailbox_with_no_mail:"📭",man:"👨",man_artist:"👨‍🎨",man_astronaut:"👨‍🚀",man_cartwheeling:"🤸‍♂️",man_cook:"👨‍🍳",man_dancing:"🕺",man_facepalming:"🤦‍♂️",man_factory_worker:"👨‍🏭",man_farmer:"👨‍🌾",man_firefighter:"👨‍🚒",man_health_worker:"👨‍⚕️",man_in_tuxedo:"🤵",man_judge:"👨‍⚖️",man_juggling:"🤹‍♂️",man_mechanic:"👨‍🔧",man_office_worker:"👨‍💼",man_pilot:"👨‍✈️",man_playing_handball:"🤾‍♂️",man_playing_water_polo:"🤽‍♂️",man_scientist:"👨‍🔬",man_shrugging:"🤷‍♂️",man_singer:"👨‍🎤",man_student:"👨‍🎓",man_teacher:"👨‍🏫",man_technologist:"👨‍💻",man_with_gua_pi_mao:"👲",man_with_turban:"👳",tangerine:"🍊",mans_shoe:"👞",mantelpiece_clock:"🕰",maple_leaf:"🍁",martial_arts_uniform:"🥋",mask:"😷",massage_woman:"💆",massage_man:"💆‍♂️",meat_on_bone:"🍖",medal_military:"🎖",medal_sports:"🏅",mega:"📣",melon:"🍈",memo:"📝",men_wrestling:"🤼‍♂️",menorah:"🕎",mens:"🚹",metal:"🤘",metro:"🚇",microphone:"🎤",microscope:"🔬",milk_glass:"🥛",milky_way:"🌌",minibus:"🚐",minidisc:"💽",mobile_phone_off:"📴",money_mouth_face:"🤑",money_with_wings:"💸",moneybag:"💰",monkey:"🐒",monkey_face:"🐵",monorail:"🚝",moon:"🌔",mortar_board:"🎓",mosque:"🕌",motor_boat:"🛥",motor_scooter:"🛵",motorcycle:"🏍",motorway:"🛣",mount_fuji:"🗻",mountain:"⛰",mountain_biking_man:"🚵",mountain_biking_woman:"🚵‍♀️",mountain_cableway:"🚠",mountain_railway:"🚞",mountain_snow:"🏔",mouse:"🐭",mouse2:"🐁",movie_camera:"🎥",moyai:"🗿",mrs_claus:"🤶",muscle:"💪",mushroom:"🍄",musical_keyboard:"🎹",musical_note:"🎵",musical_score:"🎼",mute:"🔇",nail_care:"💅",name_badge:"📛",national_park:"🏞",nauseated_face:"🤢",necktie:"👔",negative_squared_cross_mark:"❎",nerd_face:"🤓",neutral_face:"😐",new:"🆕",new_moon:"🌑",new_moon_with_face:"🌚",newspaper:"📰",newspaper_roll:"🗞",next_track_button:"⏭",ng:"🆖",no_good_man:"🙅‍♂️",no_good_woman:"🙅",night_with_stars:"🌃",no_bell:"🔕",no_bicycles:"🚳",no_entry:"⛔️",no_entry_sign:"🚫",no_mobile_phones:"📵",no_mouth:"😶",no_pedestrians:"🚷",no_smoking:"🚭","non-potable_water":"🚱",nose:"👃",notebook:"📓",notebook_with_decorative_cover:"📔",notes:"🎶",nut_and_bolt:"🔩",o:"⭕️",o2:"🅾️",ocean:"🌊",octopus:"🐙",oden:"🍢",office:"🏢",oil_drum:"🛢",ok:"🆗",ok_hand:"👌",ok_man:"🙆‍♂️",ok_woman:"🙆",old_key:"🗝",older_man:"👴",older_woman:"👵",om:"🕉",on:"🔛",oncoming_automobile:"🚘",oncoming_bus:"🚍",oncoming_police_car:"🚔",oncoming_taxi:"🚖",open_file_folder:"📂",open_hands:"👐",open_mouth:"😮",open_umbrella:"☂️",ophiuchus:"⛎",orange_book:"📙",orthodox_cross:"☦️",outbox_tray:"📤",owl:"🦉",ox:"🐂",package:"📦",page_facing_up:"📄",page_with_curl:"📃",pager:"📟",paintbrush:"🖌",palm_tree:"🌴",pancakes:"🥞",panda_face:"🐼",paperclip:"📎",paperclips:"🖇",parasol_on_ground:"⛱",parking:"🅿️",part_alternation_mark:"〽️",partly_sunny:"⛅️",passenger_ship:"🛳",passport_control:"🛂",pause_button:"⏸",peace_symbol:"☮️",peach:"🍑",peanuts:"🥜",pear:"🍐",pen:"🖊",pencil2:"✏️",penguin:"🐧",pensive:"😔",performing_arts:"🎭",persevere:"😣",person_fencing:"🤺",pouting_woman:"🙎",phone:"☎️",pick:"⛏",pig:"🐷",pig2:"🐖",pig_nose:"🐽",pill:"💊",pineapple:"🍍",ping_pong:"🏓",pisces:"♓️",pizza:"🍕",place_of_worship:"🛐",plate_with_cutlery:"🍽",play_or_pause_button:"⏯",point_down:"👇",point_left:"👈",point_right:"👉",point_up:"☝️",point_up_2:"👆",police_car:"🚓",policewoman:"👮‍♀️",poodle:"🐩",popcorn:"🍿",post_office:"🏣",postal_horn:"📯",postbox:"📮",potable_water:"🚰",potato:"🥔",pouch:"👝",poultry_leg:"🍗",pound:"💷",rage:"😡",pouting_cat:"😾",pouting_man:"🙎‍♂️",pray:"🙏",prayer_beads:"📿",pregnant_woman:"🤰",previous_track_button:"⏮",prince:"🤴",princess:"👸",printer:"🖨",purple_heart:"💜",purse:"👛",pushpin:"📌",put_litter_in_its_place:"🚮",question:"❓",rabbit:"🐰",rabbit2:"🐇",racehorse:"🐎",racing_car:"🏎",radio:"📻",radio_button:"🔘",radioactive:"☢️",railway_car:"🚃",railway_track:"🛤",rainbow:"🌈",rainbow_flag:"🏳️‍🌈",raised_back_of_hand:"🤚",raised_hand_with_fingers_splayed:"🖐",raised_hands:"🙌",raising_hand_woman:"🙋",raising_hand_man:"🙋‍♂️",ram:"🐏",ramen:"🍜",rat:"🐀",record_button:"⏺",recycle:"♻️",red_circle:"🔴",registered:"®️",relaxed:"☺️",relieved:"😌",reminder_ribbon:"🎗",repeat:"🔁",repeat_one:"🔂",rescue_worker_helmet:"⛑",restroom:"🚻",revolving_hearts:"💞",rewind:"⏪",rhinoceros:"🦏",ribbon:"🎀",rice:"🍚",rice_ball:"🍙",rice_cracker:"🍘",rice_scene:"🎑",right_anger_bubble:"🗯",ring:"💍",robot:"🤖",rocket:"🚀",rofl:"🤣",roll_eyes:"🙄",roller_coaster:"🎢",rooster:"🐓",rose:"🌹",rosette:"🏵",rotating_light:"🚨",round_pushpin:"📍",rowing_man:"🚣",rowing_woman:"🚣‍♀️",rugby_football:"🏉",running_man:"🏃",running_shirt_with_sash:"🎽",running_woman:"🏃‍♀️",sa:"🈂️",sagittarius:"♐️",sake:"🍶",sandal:"👡",santa:"🎅",satellite:"📡",saxophone:"🎷",school:"🏫",school_satchel:"🎒",scissors:"✂️",scorpion:"🦂",scorpius:"♏️",scream:"😱",scream_cat:"🙀",scroll:"📜",seat:"💺",secret:"㊙️",see_no_evil:"🙈",seedling:"🌱",selfie:"🤳",shallow_pan_of_food:"🥘",shamrock:"☘️",shark:"🦈",shaved_ice:"🍧",sheep:"🐑",shell:"🐚",shield:"🛡",shinto_shrine:"⛩",ship:"🚢",shirt:"👕",shopping:"🛍",shopping_cart:"🛒",shower:"🚿",shrimp:"🦐",signal_strength:"📶",six_pointed_star:"🔯",ski:"🎿",skier:"⛷",skull:"💀",skull_and_crossbones:"☠️",sleeping:"😴",sleeping_bed:"🛌",sleepy:"😪",slightly_frowning_face:"🙁",slightly_smiling_face:"🙂",slot_machine:"🎰",small_airplane:"🛩",small_blue_diamond:"🔹",small_orange_diamond:"🔸",small_red_triangle:"🔺",small_red_triangle_down:"🔻",smile:"😄",smile_cat:"😸",smiley:"😃",smiley_cat:"😺",smiling_imp:"😈",smirk:"😏",smirk_cat:"😼",smoking:"🚬",snail:"🐌",snake:"🐍",sneezing_face:"🤧",snowboarder:"🏂",snowflake:"❄️",snowman:"⛄️",snowman_with_snow:"☃️",sob:"😭",soccer:"⚽️",soon:"🔜",sos:"🆘",sound:"🔉",space_invader:"👾",spades:"♠️",spaghetti:"🍝",sparkle:"❇️",sparkler:"🎇",sparkles:"✨",sparkling_heart:"💖",speak_no_evil:"🙊",speaker:"🔈",speaking_head:"🗣",speech_balloon:"💬",speedboat:"🚤",spider:"🕷",spider_web:"🕸",spiral_calendar:"🗓",spiral_notepad:"🗒",spoon:"🥄",squid:"🦑",stadium:"🏟",star:"⭐️",star2:"🌟",star_and_crescent:"☪️",star_of_david:"✡️",stars:"🌠",station:"🚉",statue_of_liberty:"🗽",steam_locomotive:"🚂",stew:"🍲",stop_button:"⏹",stop_sign:"🛑",stopwatch:"⏱",straight_ruler:"📏",strawberry:"🍓",stuck_out_tongue:"😛",stuck_out_tongue_closed_eyes:"😝",stuck_out_tongue_winking_eye:"😜",studio_microphone:"🎙",stuffed_flatbread:"🥙",sun_behind_large_cloud:"🌥",sun_behind_rain_cloud:"🌦",sun_behind_small_cloud:"🌤",sun_with_face:"🌞",sunflower:"🌻",sunglasses:"😎",sunny:"☀️",sunrise:"🌅",sunrise_over_mountains:"🌄",surfing_man:"🏄",surfing_woman:"🏄‍♀️",sushi:"🍣",suspension_railway:"🚟",sweat:"😓",sweat_drops:"💦",sweat_smile:"😅",sweet_potato:"🍠",swimming_man:"🏊",swimming_woman:"🏊‍♀️",symbols:"🔣",synagogue:"🕍",syringe:"💉",taco:"🌮",tada:"🎉",tanabata_tree:"🎋",taurus:"♉️",taxi:"🚕",tea:"🍵",telephone_receiver:"📞",telescope:"🔭",tennis:"🎾",tent:"⛺️",thermometer:"🌡",thinking:"🤔",thought_balloon:"💭",ticket:"🎫",tickets:"🎟",tiger:"🐯",tiger2:"🐅",timer_clock:"⏲",tipping_hand_man:"💁‍♂️",tired_face:"😫",tm:"™️",toilet:"🚽",tokyo_tower:"🗼",tomato:"🍅",tongue:"👅",top:"🔝",tophat:"🎩",tornado:"🌪",trackball:"🖲",tractor:"🚜",traffic_light:"🚥",train:"🚋",train2:"🚆",tram:"🚊",triangular_flag_on_post:"🚩",triangular_ruler:"📐",trident:"🔱",triumph:"😤",trolleybus:"🚎",trophy:"🏆",tropical_drink:"🍹",tropical_fish:"🐠",truck:"🚚",trumpet:"🎺",tulip:"🌷",tumbler_glass:"🥃",turkey:"🦃",turtle:"🐢",tv:"📺",twisted_rightwards_arrows:"🔀",two_hearts:"💕",two_men_holding_hands:"👬",two_women_holding_hands:"👭",u5272:"🈹",u5408:"🈴",u55b6:"🈺",u6307:"🈯️",u6708:"🈷️",u6709:"🈶",u6e80:"🈵",u7121:"🈚️",u7533:"🈸",u7981:"🈲",u7a7a:"🈳",umbrella:"☔️",unamused:"😒",underage:"🔞",unicorn:"🦄",unlock:"🔓",up:"🆙",upside_down_face:"🙃",v:"✌️",vertical_traffic_light:"🚦",vhs:"📼",vibration_mode:"📳",video_camera:"📹",video_game:"🎮",violin:"🎻",virgo:"♍️",volcano:"🌋",volleyball:"🏐",vs:"🆚",vulcan_salute:"🖖",walking_man:"🚶",walking_woman:"🚶‍♀️",waning_crescent_moon:"🌘",waning_gibbous_moon:"🌖",warning:"⚠️",wastebasket:"🗑",watch:"⌚️",water_buffalo:"🐃",watermelon:"🍉",wave:"👋",wavy_dash:"〰️",waxing_crescent_moon:"🌒",wc:"🚾",weary:"😩",wedding:"💒",weight_lifting_man:"🏋️",weight_lifting_woman:"🏋️‍♀️",whale:"🐳",whale2:"🐋",wheel_of_dharma:"☸️",wheelchair:"♿️",white_check_mark:"✅",white_circle:"⚪️",white_flag:"🏳️",white_flower:"💮",white_large_square:"⬜️",white_medium_small_square:"◽️",white_medium_square:"◻️",white_small_square:"▫️",white_square_button:"🔳",wilted_flower:"🥀",wind_chime:"🎐",wind_face:"🌬",wine_glass:"🍷",wink:"😉",wolf:"🐺",woman:"👩",woman_artist:"👩‍🎨",woman_astronaut:"👩‍🚀",woman_cartwheeling:"🤸‍♀️",woman_cook:"👩‍🍳",woman_facepalming:"🤦‍♀️",woman_factory_worker:"👩‍🏭",woman_farmer:"👩‍🌾",woman_firefighter:"👩‍🚒",woman_health_worker:"👩‍⚕️",woman_judge:"👩‍⚖️",woman_juggling:"🤹‍♀️",woman_mechanic:"👩‍🔧",woman_office_worker:"👩‍💼",woman_pilot:"👩‍✈️",woman_playing_handball:"🤾‍♀️",woman_playing_water_polo:"🤽‍♀️",woman_scientist:"👩‍🔬",woman_shrugging:"🤷‍♀️",woman_singer:"👩‍🎤",woman_student:"👩‍🎓",woman_teacher:"👩‍🏫",woman_technologist:"👩‍💻",woman_with_turban:"👳‍♀️",womans_clothes:"👚",womans_hat:"👒",women_wrestling:"🤼‍♀️",womens:"🚺",world_map:"🗺",worried:"😟",wrench:"🔧",writing_hand:"✍️",x:"❌",yellow_heart:"💛",yen:"💴",yin_yang:"☯️",yum:"😋",zap:"⚡️",zipper_mouth_face:"🤐",zzz:"💤",octocat:'',showdown:''},I.Converter=function(g){"use strict";function C(g,C){if(C=C||null,I.helper.isString(g)){if(g=I.helper.stdExtName(g),C=g,I.extensions[g])return console.warn("DEPRECATION WARNING: "+g+" is an old extension that uses a deprecated loading method.Please inform the developer that the extension should be updated!"),void function(g,C){"function"==typeof g&&(g=g(new I.Converter));I.helper.isArray(g)||(g=[g]);var e=A(g,C);if(!e.valid)throw Error(e.error);for(var r=0;r? ?(['"].*['"])?\)$/m)>-1)t="";else if(!t){if(r||(r=e.toLowerCase().replace(/ ?\n/g," ")),t="#"+r,I.helper.isUndefined(C.gUrls[r]))return g;t=C.gUrls[r],I.helper.isUndefined(C.gTitles[r])||(o=C.gTitles[r])}var s='"};return g=(g=C.converter._dispatch("anchors.before",g,A,C)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g,e),g=g.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,e),g=g.replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]??(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,e),g=g.replace(/\[([^\[\]]+)]()()()()()/g,e),A.ghMentions&&(g=g.replace(/(^|\s)(\\)?(@([a-z\d\-]+))(?=[.!?;,[\]()]|\s|$)/gim,function(g,C,e,r,t){if("\\"===e)return C+r;if(!I.helper.isString(A.ghMentionsLink))throw new Error("ghMentionsLink option must be a string");var a=A.ghMentionsLink.replace(/\{u}/g,t),n="";return A.openLinksInNewWindow&&(n=' target="¨E95Eblank"'),C+'"+r+""})),g=C.converter._dispatch("anchors.after",g,A,C)});var s=/([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,i=/([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,l=/()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,c=/(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gim,u=/<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,d=function(g){"use strict";return function(A,C,e,r,t,a,n){var o=e=e.replace(I.helper.regexes.asteriskDashAndColon,I.helper.escapeCharactersCallback),s="",i="",l=C||"",c=n||"";return/^www\./i.test(e)&&(e=e.replace(/^www\./i,"http://www.")),g.excludeTrailingPunctuationFromURLs&&a&&(s=a),g.openLinksInNewWindow&&(i=' target="¨E95Eblank"'),l+'"+o+""+s+c}},p=function(g,A){"use strict";return function(C,e,r){var t="mailto:";return e=e||"",r=I.subParser("unescapeSpecialChars")(r,g,A),g.encodeEmails?(t=I.helper.encodeEmailAddress(t+r),r=I.helper.encodeEmailAddress(r)):t+=r,e+''+r+""}};I.subParser("autoLinks",function(g,A,C){"use strict";return g=C.converter._dispatch("autoLinks.before",g,A,C),g=g.replace(l,d(A)),g=g.replace(u,p(A,C)),g=C.converter._dispatch("autoLinks.after",g,A,C)}),I.subParser("simplifiedAutoLinks",function(g,A,C){"use strict";return A.simplifiedAutoLink?(g=C.converter._dispatch("simplifiedAutoLinks.before",g,A,C),g=A.excludeTrailingPunctuationFromURLs?g.replace(i,d(A)):g.replace(s,d(A)),g=g.replace(c,p(A,C)),g=C.converter._dispatch("simplifiedAutoLinks.after",g,A,C)):g}),I.subParser("blockGamut",function(g,A,C){"use strict";return g=C.converter._dispatch("blockGamut.before",g,A,C),g=I.subParser("blockQuotes")(g,A,C),g=I.subParser("headers")(g,A,C),g=I.subParser("horizontalRule")(g,A,C),g=I.subParser("lists")(g,A,C),g=I.subParser("codeBlocks")(g,A,C),g=I.subParser("tables")(g,A,C),g=I.subParser("hashHTMLBlocks")(g,A,C),g=I.subParser("paragraphs")(g,A,C),g=C.converter._dispatch("blockGamut.after",g,A,C)}),I.subParser("blockQuotes",function(g,A,C){"use strict";g=C.converter._dispatch("blockQuotes.before",g,A,C),g+="\n\n";var e=/(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;return A.splitAdjacentBlockquotes&&(e=/^ {0,3}>[\s\S]*?(?:\n\n)/gm),g=g.replace(e,function(g){return g=g.replace(/^[ \t]*>[ \t]?/gm,""),g=g.replace(/¨0/g,""),g=g.replace(/^[ \t]+$/gm,""),g=I.subParser("githubCodeBlocks")(g,A,C),g=I.subParser("blockGamut")(g,A,C),g=g.replace(/(^|\n)/g,"$1 "),g=g.replace(/(\s*
[^\r]+?<\/pre>)/gm,function(g,A){var C=A;return C=C.replace(/^  /gm,"¨0"),C=C.replace(/¨0/g,"")}),I.subParser("hashBlock")("
\n"+g+"\n
",A,C)}),g=C.converter._dispatch("blockQuotes.after",g,A,C)}),I.subParser("codeBlocks",function(g,A,C){"use strict";g=C.converter._dispatch("codeBlocks.before",g,A,C);return g=(g+="¨0").replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=¨0))/g,function(g,e,r){var t=e,a=r,n="\n";return t=I.subParser("outdent")(t,A,C),t=I.subParser("encodeCode")(t,A,C),t=I.subParser("detab")(t,A,C),t=t.replace(/^\n+/g,""),t=t.replace(/\n+$/g,""),A.omitExtraWLInCodeBlocks&&(n=""),t="
"+t+n+"
",I.subParser("hashBlock")(t,A,C)+a}),g=g.replace(/¨0/,""),g=C.converter._dispatch("codeBlocks.after",g,A,C)}),I.subParser("codeSpans",function(g,A,C){"use strict";return void 0===(g=C.converter._dispatch("codeSpans.before",g,A,C))&&(g=""),g=g.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,function(g,e,r,t){var a=t;return a=a.replace(/^([ \t]*)/g,""),a=a.replace(/[ \t]*$/g,""),a=I.subParser("encodeCode")(a,A,C),a=e+""+a+"",a=I.subParser("hashHTMLSpans")(a,A,C)}),g=C.converter._dispatch("codeSpans.after",g,A,C)}),I.subParser("completeHTMLDocument",function(g,A,C){"use strict";if(!A.completeHTMLDocument)return g;g=C.converter._dispatch("completeHTMLDocument.before",g,A,C);var I="html",e="\n",r="",t='\n',a="",n="";void 0!==C.metadata.parsed.doctype&&(e="\n","html"!==(I=C.metadata.parsed.doctype.toString().toLowerCase())&&"html5"!==I||(t=''));for(var o in C.metadata.parsed)if(C.metadata.parsed.hasOwnProperty(o))switch(o.toLowerCase()){case"doctype":break;case"title":r=""+C.metadata.parsed.title+"\n";break;case"charset":t="html"===I||"html5"===I?'\n':'\n';break;case"language":case"lang":a=' lang="'+C.metadata.parsed[o]+'"',n+='\n';break;default:n+='\n'}return g=e+"\n\n"+r+t+n+"\n\n"+g.trim()+"\n\n",g=C.converter._dispatch("completeHTMLDocument.after",g,A,C)}),I.subParser("detab",function(g,A,C){"use strict";return g=C.converter._dispatch("detab.before",g,A,C),g=g.replace(/\t(?=\t)/g," "),g=g.replace(/\t/g,"¨A¨B"),g=g.replace(/¨B(.+?)¨A/g,function(g,A){for(var C=A,I=4-C.length%4,e=0;e/g,">"),g=C.converter._dispatch("encodeAmpsAndAngles.after",g,A,C)}),I.subParser("encodeBackslashEscapes",function(g,A,C){"use strict";return g=C.converter._dispatch("encodeBackslashEscapes.before",g,A,C),g=g.replace(/\\(\\)/g,I.helper.escapeCharactersCallback),g=g.replace(/\\([`*_{}\[\]()>#+.!~=|-])/g,I.helper.escapeCharactersCallback),g=C.converter._dispatch("encodeBackslashEscapes.after",g,A,C)}),I.subParser("encodeCode",function(g,A,C){"use strict";return g=C.converter._dispatch("encodeCode.before",g,A,C),g=g.replace(/&/g,"&").replace(//g,">").replace(/([*_{}\[\]\\=~-])/g,I.helper.escapeCharactersCallback),g=C.converter._dispatch("encodeCode.after",g,A,C)}),I.subParser("escapeSpecialCharsWithinTagAttributes",function(g,A,C){"use strict";return g=(g=C.converter._dispatch("escapeSpecialCharsWithinTagAttributes.before",g,A,C)).replace(/<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi,function(g){return g.replace(/(.)<\/?code>(?=.)/g,"$1`").replace(/([\\`*_~=|])/g,I.helper.escapeCharactersCallback)}),g=g.replace(/-]|-[^>])(?:[^-]|-[^-])*)--)>/gi,function(g){return g.replace(/([\\`*_~=|])/g,I.helper.escapeCharactersCallback)}),g=C.converter._dispatch("escapeSpecialCharsWithinTagAttributes.after",g,A,C)}),I.subParser("githubCodeBlocks",function(g,A,C){"use strict";return A.ghCodeBlocks?(g=C.converter._dispatch("githubCodeBlocks.before",g,A,C),g+="¨0",g=g.replace(/(?:^|\n)(```+|~~~+)([^\s`~]*)\n([\s\S]*?)\n\1/g,function(g,e,r,t){var a=A.omitExtraWLInCodeBlocks?"":"\n";return t=I.subParser("encodeCode")(t,A,C),t=I.subParser("detab")(t,A,C),t=t.replace(/^\n+/g,""),t=t.replace(/\n+$/g,""),t="
"+t+a+"
",t=I.subParser("hashBlock")(t,A,C),"\n\n¨G"+(C.ghCodeBlocks.push({text:g,codeblock:t})-1)+"G\n\n"}),g=g.replace(/¨0/,""),C.converter._dispatch("githubCodeBlocks.after",g,A,C)):g}),I.subParser("hashBlock",function(g,A,C){"use strict";return g=C.converter._dispatch("hashBlock.before",g,A,C),g=g.replace(/(^\n+|\n+$)/g,""),g="\n\n¨K"+(C.gHtmlBlocks.push(g)-1)+"K\n\n",g=C.converter._dispatch("hashBlock.after",g,A,C)}),I.subParser("hashCodeTags",function(g,A,C){"use strict";g=C.converter._dispatch("hashCodeTags.before",g,A,C);return g=I.helper.replaceRecursiveRegExp(g,function(g,e,r,t){var a=r+I.subParser("encodeCode")(e,A,C)+t;return"¨C"+(C.gHtmlSpans.push(a)-1)+"C"},"]*>","","gim"),g=C.converter._dispatch("hashCodeTags.after",g,A,C)}),I.subParser("hashElement",function(g,A,C){"use strict";return function(g,A){var I=A;return I=I.replace(/\n\n/g,"\n"),I=I.replace(/^\n/,""),I=I.replace(/\n+$/g,""),I="\n\n¨K"+(C.gHtmlBlocks.push(I)-1)+"K\n\n"}}),I.subParser("hashHTMLBlocks",function(g,A,C){"use strict";g=C.converter._dispatch("hashHTMLBlocks.before",g,A,C);var e=["pre","div","h1","h2","h3","h4","h5","h6","blockquote","table","dl","ol","ul","script","noscript","form","fieldset","iframe","math","style","section","header","footer","nav","article","aside","address","audio","canvas","figure","hgroup","output","video","p"],r=function(g,A,I,e){var r=g;return-1!==I.search(/\bmarkdown\b/)&&(r=I+C.converter.makeHtml(A)+e),"\n\n¨K"+(C.gHtmlBlocks.push(r)-1)+"K\n\n"};A.backslashEscapesHTMLTags&&(g=g.replace(/\\<(\/?[^>]+?)>/g,function(g,A){return"<"+A+">"}));for(var t=0;t]*>)","im"),o="<"+e[t]+"\\b[^>]*>",s="";-1!==(a=I.helper.regexIndexOf(g,n));){var i=I.helper.splitAtIndex(g,a),l=I.helper.replaceRecursiveRegExp(i[1],r,o,s,"im");if(l===i[1])break;g=i[0].concat(l)}return g=g.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,I.subParser("hashElement")(g,A,C)),g=I.helper.replaceRecursiveRegExp(g,function(g){return"\n\n¨K"+(C.gHtmlBlocks.push(g)-1)+"K\n\n"},"^ {0,3}\x3c!--","--\x3e","gm"),g=g.replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,I.subParser("hashElement")(g,A,C)),g=C.converter._dispatch("hashHTMLBlocks.after",g,A,C)}),I.subParser("hashHTMLSpans",function(g,A,C){"use strict";function I(g){return"¨C"+(C.gHtmlSpans.push(g)-1)+"C"}return g=C.converter._dispatch("hashHTMLSpans.before",g,A,C),g=g.replace(/<[^>]+?\/>/gi,function(g){return I(g)}),g=g.replace(/<([^>]+?)>[\s\S]*?<\/\1>/g,function(g){return I(g)}),g=g.replace(/<([^>]+?)\s[^>]+?>[\s\S]*?<\/\1>/g,function(g){return I(g)}),g=g.replace(/<[^>]+?>/gi,function(g){return I(g)}),g=C.converter._dispatch("hashHTMLSpans.after",g,A,C)}),I.subParser("unhashHTMLSpans",function(g,A,C){"use strict";g=C.converter._dispatch("unhashHTMLSpans.before",g,A,C);for(var I=0;I]*>\\s*]*>","^ {0,3}\\s*
","gim"),g=C.converter._dispatch("hashPreCodeTags.after",g,A,C)}),I.subParser("headers",function(g,A,C){"use strict";function e(g){var e,r;if(A.customizedHeaderId){var t=g.match(/\{([^{]+?)}\s*$/);t&&t[1]&&(g=t[1])}return e=g,r=I.helper.isString(A.prefixHeaderId)?A.prefixHeaderId:!0===A.prefixHeaderId?"section-":"",A.rawPrefixHeaderId||(e=r+e),e=A.ghCompatibleHeaderId?e.replace(/ /g,"-").replace(/&/g,"").replace(/¨T/g,"").replace(/¨D/g,"").replace(/[&+$,\/:;=?@"#{}|^¨~\[\]`\\*)(%.!'<>]/g,"").toLowerCase():A.rawHeaderId?e.replace(/ /g,"-").replace(/&/g,"&").replace(/¨T/g,"¨").replace(/¨D/g,"$").replace(/["']/g,"-").toLowerCase():e.replace(/[^\w]/g,"").toLowerCase(),A.rawPrefixHeaderId&&(e=r+e),C.hashLinkCounts[e]?e=e+"-"+C.hashLinkCounts[e]++:C.hashLinkCounts[e]=1,e}g=C.converter._dispatch("headers.before",g,A,C);var r=isNaN(parseInt(A.headerLevelStart))?1:parseInt(A.headerLevelStart),t=A.smoothLivePreview?/^(.+)[ \t]*\n={2,}[ \t]*\n+/gm:/^(.+)[ \t]*\n=+[ \t]*\n+/gm,a=A.smoothLivePreview?/^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm:/^(.+)[ \t]*\n-+[ \t]*\n+/gm;g=(g=g.replace(t,function(g,t){var a=I.subParser("spanGamut")(t,A,C),n=A.noHeaderId?"":' id="'+e(t)+'"',o=""+a+"";return I.subParser("hashBlock")(o,A,C)})).replace(a,function(g,t){var a=I.subParser("spanGamut")(t,A,C),n=A.noHeaderId?"":' id="'+e(t)+'"',o=r+1,s=""+a+"";return I.subParser("hashBlock")(s,A,C)});var n=A.requireSpaceBeforeHeadingText?/^(#{1,6})[ \t]+(.+?)[ \t]*#*\n+/gm:/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm;return g=g.replace(n,function(g,t,a){var n=a;A.customizedHeaderId&&(n=a.replace(/\s?\{([^{]+?)}\s*$/,""));var o=I.subParser("spanGamut")(n,A,C),s=A.noHeaderId?"":' id="'+e(a)+'"',i=r-1+t.length,l=""+o+"";return I.subParser("hashBlock")(l,A,C)}),g=C.converter._dispatch("headers.after",g,A,C)}),I.subParser("horizontalRule",function(g,A,C){"use strict";g=C.converter._dispatch("horizontalRule.before",g,A,C);var e=I.subParser("hashBlock")("
",A,C);return g=g.replace(/^ {0,2}( ?-){3,}[ \t]*$/gm,e),g=g.replace(/^ {0,2}( ?\*){3,}[ \t]*$/gm,e),g=g.replace(/^ {0,2}( ?_){3,}[ \t]*$/gm,e),g=C.converter._dispatch("horizontalRule.after",g,A,C)}),I.subParser("images",function(g,A,C){"use strict";function e(g,A,e,r,t,a,n,o){var s=C.gUrls,i=C.gTitles,l=C.gDimensions;if(e=e.toLowerCase(),o||(o=""),g.search(/\(? ?(['"].*['"])?\)$/m)>-1)r="";else if(""===r||null===r){if(""!==e&&null!==e||(e=A.toLowerCase().replace(/ ?\n/g," ")),r="#"+e,I.helper.isUndefined(s[e]))return g;r=s[e],I.helper.isUndefined(i[e])||(o=i[e]),I.helper.isUndefined(l[e])||(t=l[e].width,a=l[e].height)}A=A.replace(/"/g,""").replace(I.helper.regexes.asteriskDashAndColon,I.helper.escapeCharactersCallback);var c=''+A+'"}return g=(g=C.converter._dispatch("images.before",g,A,C)).replace(/!\[([^\]]*?)] ?(?:\n *)?\[([\s\S]*?)]()()()()()/g,e),g=g.replace(/!\[([^\]]*?)][ \t]*()\([ \t]??(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,function(g,A,C,I,r,t,a,n){return I=I.replace(/\s/g,""),e(g,A,C,I,r,t,0,n)}),g=g.replace(/!\[([^\]]*?)][ \t]*()\([ \t]?<([^>]*)>(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(?:(["'])([^"]*?)\6))?[ \t]?\)/g,e),g=g.replace(/!\[([^\]]*?)][ \t]*()\([ \t]??(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,e),g=g.replace(/!\[([^\[\]]+)]()()()()()/g,e),g=C.converter._dispatch("images.after",g,A,C)}),I.subParser("italicsAndBold",function(g,A,C){"use strict";function I(g,A,C){return A+g+C}return g=C.converter._dispatch("italicsAndBold.before",g,A,C),g=A.literalMidWordUnderscores?(g=(g=g.replace(/\b___(\S[\s\S]*)___\b/g,function(g,A){return I(A,"","")})).replace(/\b__(\S[\s\S]*)__\b/g,function(g,A){return I(A,"","")})).replace(/\b_(\S[\s\S]*?)_\b/g,function(g,A){return I(A,"","")}):(g=(g=g.replace(/___(\S[\s\S]*?)___/g,function(g,A){return/\S$/.test(A)?I(A,"",""):g})).replace(/__(\S[\s\S]*?)__/g,function(g,A){return/\S$/.test(A)?I(A,"",""):g})).replace(/_([^\s_][\s\S]*?)_/g,function(g,A){return/\S$/.test(A)?I(A,"",""):g}),g=A.literalMidWordAsterisks?(g=(g=g.replace(/([^*]|^)\B\*\*\*(\S[\s\S]+?)\*\*\*\B(?!\*)/g,function(g,A,C){return I(C,A+"","")})).replace(/([^*]|^)\B\*\*(\S[\s\S]+?)\*\*\B(?!\*)/g,function(g,A,C){return I(C,A+"","")})).replace(/([^*]|^)\B\*(\S[\s\S]+?)\*\B(?!\*)/g,function(g,A,C){return I(C,A+"","")}):(g=(g=g.replace(/\*\*\*(\S[\s\S]*?)\*\*\*/g,function(g,A){return/\S$/.test(A)?I(A,"",""):g})).replace(/\*\*(\S[\s\S]*?)\*\*/g,function(g,A){return/\S$/.test(A)?I(A,"",""):g})).replace(/\*([^\s*][\s\S]*?)\*/g,function(g,A){return/\S$/.test(A)?I(A,"",""):g}),g=C.converter._dispatch("italicsAndBold.after",g,A,C)}),I.subParser("lists",function(g,A,C){"use strict";function e(g,e){C.gListLevel++,g=g.replace(/\n{2,}$/,"\n");var r=/(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,t=/\n[ \t]*\n(?!¨0)/.test(g+="¨0");return A.disableForced4SpacesIndentedSublists&&(r=/(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0|\2([*+-]|\d+[.])[ \t]+))/gm),g=g.replace(r,function(g,e,r,a,n,o,s){s=s&&""!==s.trim();var i=I.subParser("outdent")(n,A,C),l="";return o&&A.tasklists&&(l=' class="task-list-item" style="list-style-type: none;"',i=i.replace(/^[ \t]*\[(x|X| )?]/m,function(){var g='-1?(i=I.subParser("githubCodeBlocks")(i,A,C),i=I.subParser("blockGamut")(i,A,C)):(i=(i=I.subParser("lists")(i,A,C)).replace(/\n$/,""),i=(i=I.subParser("hashHTMLBlocks")(i,A,C)).replace(/\n\n+/g,"\n\n"),i=t?I.subParser("paragraphs")(i,A,C):I.subParser("spanGamut")(i,A,C)),i=i.replace("¨A",""),i=""+i+"\n"}),g=g.replace(/¨0/g,""),C.gListLevel--,e&&(g=g.replace(/\s+$/,"")),g}function r(g,A){if("ol"===A){var C=g.match(/^ *(\d+)\./);if(C&&"1"!==C[1])return' start="'+C[1]+'"'}return""}function t(g,C,I){var t=A.disableForced4SpacesIndentedSublists?/^ ?\d+\.[ \t]/gm:/^ {0,3}\d+\.[ \t]/gm,a=A.disableForced4SpacesIndentedSublists?/^ ?[*+-][ \t]/gm:/^ {0,3}[*+-][ \t]/gm,n="ul"===C?t:a,o="";if(-1!==g.search(n))!function A(s){var i=s.search(n),l=r(g,C);-1!==i?(o+="\n\n<"+C+l+">\n"+e(s.slice(0,i),!!I)+"\n",n="ul"===(C="ul"===C?"ol":"ul")?t:a,A(s.slice(i))):o+="\n\n<"+C+l+">\n"+e(s,!!I)+"\n"}(g);else{var s=r(g,C);o="\n\n<"+C+s+">\n"+e(g,!!I)+"\n"}return o}return g=C.converter._dispatch("lists.before",g,A,C),g+="¨0",g=C.gListLevel?g.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,function(g,A,C){return t(A,C.search(/[*+-]/g)>-1?"ul":"ol",!0)}):g.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,function(g,A,C,I){return t(C,I.search(/[*+-]/g)>-1?"ul":"ol",!1)}),g=g.replace(/¨0/,""),g=C.converter._dispatch("lists.after",g,A,C)}),I.subParser("metadata",function(g,A,C){"use strict";function I(g){C.metadata.raw=g,(g=(g=g.replace(/&/g,"&").replace(/"/g,""")).replace(/\n {4}/g," ")).replace(/^([\S ]+): +([\s\S]+?)$/gm,function(g,A,I){return C.metadata.parsed[A]=I,""})}return A.metadata?(g=C.converter._dispatch("metadata.before",g,A,C),g=g.replace(/^\s*«««+(\S*?)\n([\s\S]+?)\n»»»+\n/,function(g,A,C){return I(C),"¨M"}),g=g.replace(/^\s*---+(\S*?)\n([\s\S]+?)\n---+\n/,function(g,A,e){return A&&(C.metadata.format=A),I(e),"¨M"}),g=g.replace(/¨M/g,""),g=C.converter._dispatch("metadata.after",g,A,C)):g}),I.subParser("outdent",function(g,A,C){"use strict";return g=C.converter._dispatch("outdent.before",g,A,C),g=g.replace(/^(\t|[ ]{1,4})/gm,"¨0"),g=g.replace(/¨0/g,""),g=C.converter._dispatch("outdent.after",g,A,C)}),I.subParser("paragraphs",function(g,A,C){"use strict";for(var e=(g=(g=(g=C.converter._dispatch("paragraphs.before",g,A,C)).replace(/^\n+/g,"")).replace(/\n+$/g,"")).split(/\n{2,}/g),r=[],t=e.length,a=0;a=0?r.push(n):n.search(/\S/)>=0&&(n=(n=I.subParser("spanGamut")(n,A,C)).replace(/^([ \t]*)/g,"

"),n+="

",r.push(n))}for(t=r.length,a=0;a]*>\s*]*>/.test(s)&&(i=!0)}r[a]=s}return g=r.join("\n"),g=g.replace(/^\n+/g,""),g=g.replace(/\n+$/g,""),C.converter._dispatch("paragraphs.after",g,A,C)}),I.subParser("runExtension",function(g,A,C,I){"use strict";if(g.filter)A=g.filter(A,I.converter,C);else if(g.regex){var e=g.regex;e instanceof RegExp||(e=new RegExp(e,"g")),A=A.replace(e,g.replace)}return A}),I.subParser("spanGamut",function(g,A,C){"use strict";return g=C.converter._dispatch("spanGamut.before",g,A,C),g=I.subParser("codeSpans")(g,A,C),g=I.subParser("escapeSpecialCharsWithinTagAttributes")(g,A,C),g=I.subParser("encodeBackslashEscapes")(g,A,C),g=I.subParser("images")(g,A,C),g=I.subParser("anchors")(g,A,C),g=I.subParser("autoLinks")(g,A,C),g=I.subParser("simplifiedAutoLinks")(g,A,C),g=I.subParser("emoji")(g,A,C),g=I.subParser("underline")(g,A,C),g=I.subParser("italicsAndBold")(g,A,C),g=I.subParser("strikethrough")(g,A,C),g=I.subParser("ellipsis")(g,A,C),g=I.subParser("hashHTMLSpans")(g,A,C),g=I.subParser("encodeAmpsAndAngles")(g,A,C),A.simpleLineBreaks?/\n\n¨K/.test(g)||(g=g.replace(/\n+/g,"
\n")):g=g.replace(/ +\n/g,"
\n"),g=C.converter._dispatch("spanGamut.after",g,A,C)}),I.subParser("strikethrough",function(g,A,C){"use strict";return A.strikethrough&&(g=(g=C.converter._dispatch("strikethrough.before",g,A,C)).replace(/(?:~){2}([\s\S]+?)(?:~){2}/g,function(g,e){return function(g){return A.simplifiedAutoLink&&(g=I.subParser("simplifiedAutoLinks")(g,A,C)),""+g+""}(e)}),g=C.converter._dispatch("strikethrough.after",g,A,C)),g}),I.subParser("stripLinkDefinitions",function(g,A,C){"use strict";var e=function(g,e,r,t,a,n,o){return e=e.toLowerCase(),r.match(/^data:.+?\/.+?;base64,/)?C.gUrls[e]=r.replace(/\s/g,""):C.gUrls[e]=I.subParser("encodeAmpsAndAngles")(r,A,C),n?n+o:(o&&(C.gTitles[e]=o.replace(/"|'/g,""")),A.parseImgDimensions&&t&&a&&(C.gDimensions[e]={width:t,height:a}),"")};return g=(g+="¨0").replace(/^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n\n|(?=¨0)|(?=\n\[))/gm,e),g=g.replace(/^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*\s]+)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=¨0))/gm,e),g=g.replace(/¨0/,"")}),I.subParser("tables",function(g,A,C){"use strict";function e(g){return/^:[ \t]*--*$/.test(g)?' style="text-align:left;"':/^--*[ \t]*:[ \t]*$/.test(g)?' style="text-align:right;"':/^:[ \t]*--*[ \t]*:$/.test(g)?' style="text-align:center;"':""}function r(g,e){var r="";return g=g.trim(),(A.tablesHeaderId||A.tableHeaderId)&&(r=' id="'+g.replace(/ /g,"_").toLowerCase()+'"'),g=I.subParser("spanGamut")(g,A,C),""+g+"\n"}function t(g,e){return""+I.subParser("spanGamut")(g,A,C)+"\n"}function a(g){var a,n=g.split("\n");for(a=0;a\n\n\n",e=0;e\n";for(var r=0;r\n"}return C+="\n\n"}(l,u)}if(!A.tables)return g;return g=C.converter._dispatch("tables.before",g,A,C),g=g.replace(/\\(\|)/g,I.helper.escapeCharactersCallback),g=g.replace(/^ {0,3}\|?.+\|.+\n {0,3}\|?[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:[-=]){2,}[\s\S]+?(?:\n\n|¨0)/gm,a),g=g.replace(/^ {0,3}\|.+\|[ \t]*\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n( {0,3}\|.+\|[ \t]*\n)*(?:\n|¨0)/gm,a),g=C.converter._dispatch("tables.after",g,A,C)}),I.subParser("underline",function(g,A,C){"use strict";return A.underline?(g=C.converter._dispatch("underline.before",g,A,C),g=A.literalMidWordUnderscores?g.replace(/\b_?__(\S[\s\S]*)___?\b/g,function(g,A){return""+A+""}):g.replace(/_?__(\S[\s\S]*?)___?/g,function(g,A){return/\S$/.test(A)?""+A+"":g}),g=g.replace(/(_)/g,I.helper.escapeCharactersCallback),g=C.converter._dispatch("underline.after",g,A,C)):g}),I.subParser("unescapeSpecialChars",function(g,A,C){"use strict";return g=C.converter._dispatch("unescapeSpecialChars.before",g,A,C),g=g.replace(/¨E(\d+)E/g,function(g,A){var C=parseInt(A);return String.fromCharCode(C)}),g=C.converter._dispatch("unescapeSpecialChars.after",g,A,C)});"function"==typeof define&&define.amd?define(function(){"use strict";return I}):"undefined"!=typeof module&&module.exports?module.exports=I:this.showdown=I}).call(this); - - -// clipboard.js - https://github.com/zenorocha/clipboard.js -/*! - * clipboard.js v1.7.1 - * https://zenorocha.github.io/clipboard.js - * - * Licensed MIT © Zeno Rocha - */ -!function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var e;e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,e.Clipboard=t()}}(function(){var t,e,n;return function t(e,n,o){function i(a,c){if(!n[a]){if(!e[a]){var l="function"==typeof require&&require;if(!c&&l)return l(a,!0);if(r)return r(a,!0);var s=new Error("Cannot find module '"+a+"'");throw s.code="MODULE_NOT_FOUND",s}var u=n[a]={exports:{}};e[a][0].call(u.exports,function(t){var n=e[a][1][t];return i(n||t)},u,u.exports,t,e,n,o)}return n[a].exports}for(var r="function"==typeof require&&require,a=0;a0&&void 0!==arguments[0]?arguments[0]:{};this.action=e.action,this.container=e.container,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""}},{key:"initSelection",value:function t(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function t(){var e=this,n="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return e.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[n?"right":"left"]="-9999px";var o=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=o+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.container.appendChild(this.fakeElem),this.selectedText=(0,i.default)(this.fakeElem),this.copyText()}},{key:"removeFake",value:function t(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function t(){this.selectedText=(0,i.default)(this.target),this.copyText()}},{key:"copyText",value:function t(){var e=void 0;try{e=document.execCommand(this.action)}catch(t){e=!1}this.handleResult(e)}},{key:"handleResult",value:function t(e){this.emitter.emit(e?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function t(){this.trigger&&this.trigger.focus(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function t(){this.removeFake()}},{key:"action",set:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function t(){return this._action}},{key:"target",set:function t(e){if(void 0!==e){if(!e||"object"!==(void 0===e?"undefined":r(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&e.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(e.hasAttribute("readonly")||e.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=e}},get:function t(){return this._target}}]),t}();t.exports=c})},{select:5}],8:[function(e,n,o){!function(i,r){if("function"==typeof t&&t.amd)t(["module","./clipboard-action","tiny-emitter","good-listener"],r);else if(void 0!==o)r(n,e("./clipboard-action"),e("tiny-emitter"),e("good-listener"));else{var a={exports:{}};r(a,i.clipboardAction,i.tinyEmitter,i.goodListener),i.clipboard=a.exports}}(this,function(t,e,n,o){"use strict";function i(t){return t&&t.__esModule?t:{default:t}}function r(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function a(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function c(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function l(t,e){var n="data-clipboard-"+t;if(e.hasAttribute(n))return e.getAttribute(n)}var s=i(e),u=i(n),f=i(o),d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},h=function(){function t(t,e){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText,this.container="object"===d(e.container)?e.container:document.body}},{key:"listenClick",value:function t(e){var n=this;this.listener=(0,f.default)(e,"click",function(t){return n.onClick(t)})}},{key:"onClick",value:function t(e){var n=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new s.default({action:this.action(n),target:this.target(n),text:this.text(n),container:this.container,trigger:n,emitter:this})}},{key:"defaultAction",value:function t(e){return l("action",e)}},{key:"defaultTarget",value:function t(e){var n=l("target",e);if(n)return document.querySelector(n)}},{key:"defaultText",value:function t(e){return l("text",e)}},{key:"destroy",value:function t(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],n="string"==typeof e?[e]:e,o=!!document.queryCommandSupported;return n.forEach(function(t){o=o&&!!document.queryCommandSupported(t)}),o}}]),e}(u.default);t.exports=p})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)}); -// sharedb - https://github.com/share/sharedb -!function(t){function e(n){if(i[n])return i[n].exports;var r=i[n]={exports:{},id:n,loaded:!1};return t[n].call(r.exports,r,r.exports,e),r.loaded=!0,r.exports}var i={};return e.m=t,e.c=i,e.p="",e(0)}([function(t,e,i){ShareDB=i(1)},function(t,e,i){e.Connection=i(2),e.Doc=i(4),e.Error=i(7),e.Query=i(14),e.types=i(9)},function(t,e,i){(function(e){function n(t){h.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.queries={},this.seq=1,this.id=null,this.agent=null,this.debug=!1,this.bindToSocket(t)}function r(t){return t.hasPending()}function s(t){return t.hasWritePending()}var o=i(4),l=i(14),h=i(5),c=i(7),p=i(9),a=i(15);t.exports=n,h.mixin(n),n.prototype.bindToSocket=function(t){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=t,this.state=0===t.readyState||1===t.readyState?"connecting":"disconnected",this.canSend=!1;var i=this;t.onmessage=function(t){try{var n="string"==typeof t.data?JSON.parse(t.data):t.data}catch(r){return void console.warn("Failed to parse message",t)}i.debug&&console.log("RECV",JSON.stringify(n));var s={data:n};if(i.emit("receive",s),s.data)try{i.handleMessage(s.data)}catch(r){e.nextTick(function(){i.emit("error",r)})}},t.onopen=function(){i._setState("connecting")},t.onerror=function(t){i.emit("connection error",t)},t.onclose=function(t){"closed"===t||"Closed"===t?i._setState("closed",t):"stopped"===t||"Stopped by server"===t?i._setState("stopped",t):i._setState("disconnected",t)}},n.prototype.handleMessage=function(t){var e=null;switch(t.error&&(e=new Error(t.error.message),e.code=t.error.code,e.data=t,delete t.error),t.a){case"init":return 1!==t.protocol?(e=new c(4019,"Invalid protocol version"),this.emit("error",e)):p.map[t.type]!==p.defaultType?(e=new c(4020,"Invalid default type"),this.emit("error",e)):"string"!=typeof t.id?(e=new c(4021,"Invalid client id"),this.emit("error",e)):(this.id=t.id,void this._setState("connected"));case"qf":var i=this.queries[t.id];return void(i&&i._handleFetch(e,t.data,t.extra));case"qs":var i=this.queries[t.id];return void(i&&i._handleSubscribe(e,t.data,t.extra));case"qu":return;case"q":var i=this.queries[t.id];if(!i)return;return e?i._handleError(e):(t.diff&&i._handleDiff(t.diff),void(t.hasOwnProperty("extra")&&i._handleExtra(t.extra)));case"bf":return this._handleBulkMessage(t,"_handleFetch");case"bs":return this._handleBulkMessage(t,"_handleSubscribe");case"bu":return this._handleBulkMessage(t,"_handleUnsubscribe");case"f":var n=this.getExisting(t.c,t.d);return void(n&&n._handleFetch(e,t.data));case"s":var n=this.getExisting(t.c,t.d);return void(n&&n._handleSubscribe(e,t.data));case"u":var n=this.getExisting(t.c,t.d);return void(n&&n._handleUnsubscribe(e));case"op":var n=this.getExisting(t.c,t.d);return void(n&&n._handleOp(e,t));default:console.warn("Ignorning unrecognized message",t)}},n.prototype._handleBulkMessage=function(t,e){if(t.data)for(var i in t.data){var n=this.getExisting(t.c,i);n&&n[e](t.error,t.data[i])}else if(Array.isArray(t.b))for(var r=0;r1)for(var i=1;ithis.version?this.fetch(e):e&&e()}if(this.version>t.v)return e&&e();this.version=t.v;var n=void 0===t.type?p.defaultType:t.type;this._setType(n),this.data=this.type&&this.type.deserialize?this.type.deserialize(t.data):t.data,this.emit("load"),e&&e()},n.prototype.whenNothingPending=function(t){return this.hasPending()?void this.once("nothing pending",t):void t()},n.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe.length||this.inflightUnsubscribe.length||this.pendingFetch.length)},n.prototype.hasWritePending=function(){return!(!this.inflightOp&&!this.pendingOps.length)},n.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),this.hasPending()||this.emit("nothing pending"))},n.prototype._emitResponseError=function(t,e){return e?(e(t),void this._emitNothingPending()):(this._emitNothingPending(),void this.emit("error",t))},n.prototype._handleFetch=function(t,e){var i=this.inflightFetch.shift();return t?this._emitResponseError(t,i):(this.ingestSnapshot(e,i),void this._emitNothingPending())},n.prototype._handleSubscribe=function(t,e){var i=this.inflightSubscribe.shift();return t?this._emitResponseError(t,i):(this.wantSubscribe&&(this.subscribed=!0),this.ingestSnapshot(e,i),void this._emitNothingPending())},n.prototype._handleUnsubscribe=function(t){var e=this.inflightUnsubscribe.shift();return t?this._emitResponseError(t,e):(e&&e(),void this._emitNothingPending())},n.prototype._handleOp=function(t,e){if(t)return this.inflightOp?(4002===t.code&&(t=null),this._rollback(t)):this.emit("error",t);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq)return void this._opAcknowledged(e);if(null==this.version||e.v>this.version)return void this.fetch();if(!(e.v1){this.applyStack||(this.applyStack=[]);for(var n=this.applyStack.length,r=0;r0)return void(this.applyStack.length=t);var e=this.applyStack[0];if(this.applyStack=null,e){var i=this.pendingOps.indexOf(e);if(i!==-1)for(var n=this.pendingOps.splice(i),i=0;i0&&this._events[t].length>r&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},i.prototype.on=i.prototype.addListener,i.prototype.once=function(t,e){function i(){this.removeListener(t,i),r||(r=!0,e.apply(this,arguments))}if(!n(e))throw TypeError("listener must be a function");var r=!1;return i.listener=e,this.on(t,i),this},i.prototype.removeListener=function(t,e){var i,r,o,l;if(!n(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=this._events[t],o=i.length,r=-1,i===e||n(i.listener)&&i.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(s(i)){for(l=o;l-- >0;)if(i[l]===e||i[l].listener&&i[l].listener===e){r=l;break}if(r<0)return this;1===i.length?(i.length=0,delete this._events[t]):i.splice(r,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},i.prototype.removeAllListeners=function(t){var e,i;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(i=this._events[t],n(i))this.removeListener(t,i);else if(i)for(;i.length;)this.removeListener(t,i[i.length-1]);return delete this._events[t],this},i.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?n(this._events[t])?[this._events[t]]:this._events[t].slice():[]},i.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(n(e))return 1;if(e)return e.length}return 0},i.listenerCount=function(t,e){return t.listenerCount(e)}},function(t,e,i){function n(t,e){n["super"].call(this,e),this.code=t}var r=i(8);r(n),t.exports=n},function(t,e){"use strict";function i(t){t&&r(this,"message",{configurable:!0,value:t,writable:!0});var e=this.constructor.name;e&&e!==this.name&&r(this,"name",{configurable:!0,value:e,writable:!0}),s(this,this.constructor)}function n(t,e){if(null==e||e===Error)e=i;else if("function"!=typeof e)throw new TypeError("super_ should be a function");var n;if("string"==typeof t)n=t,t=function(){e.apply(this,arguments)},o&&(o(t,n),n=null);else if("function"!=typeof t)throw new TypeError("constructor should be either a string or a function");t.super_=t["super"]=e;var r={constructor:{configurable:!0,value:t,writable:!0}};return null!=n&&(r.name={configurable:!0,value:n,writable:!0}),t.prototype=Object.create(e.prototype,r),t}var r=Object.defineProperty,s=Error.captureStackTrace;s||(s=function(t){var e=new Error;r(t,"stack",{configurable:!0,get:function(){var t=e.stack;return r(this,"stack",{value:t}),t},set:function(e){r(t,"stack",{configurable:!0,value:e,writable:!0})}})}),i.prototype=Object.create(Error.prototype,{constructor:{configurable:!0,value:i,writable:!0}});var o=function(){function t(t,e){return r(t,"name",{configurable:!0,value:e})}try{var e=function(){};if(t(e,"foo"),"foo"===e.name)return t}catch(i){}}();e=t.exports=n,e.BaseError=i},function(t,e,i){e.defaultType=i(10).type,e.map={},e.register=function(t){t.name&&(e.map[t.name]=t),t.uri&&(e.map[t.uri]=t)},e.register(e.defaultType)},function(t,e,i){t.exports={type:i(11)}},function(t,e,i){function n(t){t.t="text0";var e={p:t.p.pop()};null!=t.si&&(e.i=t.si),null!=t.sd&&(e.d=t.sd),t.o=[e]}function r(t){t.p.push(t.o[0].p),null!=t.o[0].i&&(t.si=t.o[0].i),null!=t.o[0].d&&(t.sd=t.o[0].d),delete t.t,delete t.o}var s=function(t){return"[object Array]"==Object.prototype.toString.call(t)},o=function(t){return!!t&&t.constructor===Object},l=function(t){return JSON.parse(JSON.stringify(t))},h={name:"json0",uri:"http://sharejs.org/types/JSONv0"},c={};h.registerSubtype=function(t){c[t.name]=t},h.create=function(t){return void 0===t?null:l(t)},h.invertComponent=function(t){var e={p:t.p};return t.t&&c[t.t]&&(e.t=t.t,e.o=c[t.t].invert(t.o)),void 0!==t.si&&(e.sd=t.si),void 0!==t.sd&&(e.si=t.sd),void 0!==t.oi&&(e.od=t.oi),void 0!==t.od&&(e.oi=t.od),void 0!==t.li&&(e.ld=t.li),void 0!==t.ld&&(e.li=t.ld),void 0!==t.na&&(e.na=-t.na),void 0!==t.lm&&(e.lm=t.p[t.p.length-1],e.p=t.p.slice(0,t.p.length-1).concat([t.lm])),e},h.invert=function(t){for(var e=t.slice().reverse(),i=[],n=0;n=n||s!==e.p[r])return null}return i},h.canOpAffectPath=function(t,e){return null!=h.commonLengthForOps({p:e},t)},h.transformComponent=function(t,e,i,s){e=l(e);var o=h.commonLengthForOps(i,e),p=h.commonLengthForOps(e,i),a=e.p.length,u=i.p.length;if((null!=e.na||e.t)&&a++,(null!=i.na||i.t)&&u++,null!=p&&u>a&&e.p[p]==i.p[p])if(void 0!==e.ld){var f=l(i);f.p=f.p.slice(a),e.ld=h.apply(l(e.ld),[f])}else if(void 0!==e.od){var f=l(i);f.p=f.p.slice(a),e.od=h.apply(l(e.od),[f])}if(null!=o){var d=a==u,f=i;if(null==e.si&&null==e.sd||null==i.si&&null==i.sd||(n(e),f=l(i),n(f)),f.t&&c[f.t]){if(e.t&&e.t===f.t){var v=c[e.t].transform(e.o,f.o,s);if(v.length>0)if(null!=e.si||null!=e.sd)for(var g=e.p,y=0;y_&&e.p[o]--,m>w?e.p[o]++:m===w&&_>w&&(e.p[o]++,m===b&&e.lm++),b>_?e.lm--:b===_&&b>m&&e.lm--,b>w?e.lm++:b===w&&(w>_&&b>m||w<_&&bm?e.lm++:b===_&&e.lm--)}else if(void 0!==e.li&&void 0===e.ld&&d){var m=i.p[o],b=i.lm;g=e.p[o],g>m&&e.p[o]--,g>b&&e.p[o]++}else{var m=i.p[o],b=i.lm;g=e.p[o],g===m?e.p[o]=b:(g>m&&e.p[o]--,g>b?e.p[o]++:g===b&&m>b&&e.p[o]++)}else if(void 0!==i.oi&&void 0!==i.od){if(e.p[o]===i.p[o]){if(void 0===e.oi||!d)return t;if("right"===s)return t;e.od=i.oi}}else if(void 0!==i.oi){if(void 0!==e.oi&&e.p[o]===i.p[o]){if("left"!==s)return t;h.append(t,{p:e.p,od:i.oi})}}else if(void 0!==i.od&&e.p[o]==i.p[o]){if(!d)return t;if(void 0===e.oi)return t;delete e.od}}return h.append(t,e),t},i(12)(h,h.transformComponent,h.checkValidOp,h.append);var a=i(13);h.registerSubtype(a),t.exports=h},function(t,e){function i(t,e,i,n){var r=function(t,i,n,r){e(n,t,i,"left"),e(r,i,t,"right")},s=t.transformX=function(t,e){i(t),i(e);for(var o=[],l=0;l=i.p+i.d.length)l(t,{d:e.d,p:e.p-i.d.length});else if(e.p+e.d.length<=i.p)l(t,e);else{var o={d:"",p:e.p};e.pi.p+i.d.length&&(o.d+=e.d.slice(i.p+i.d.length-e.p));var c=Math.max(e.p,i.p),p=Math.min(e.p+e.d.length,i.p+i.d.length),a=e.d.slice(c-e.p,p-e.p),u=i.d.slice(c-i.p,p-i.p);if(a!==u)throw new Error("Delete ops delete different text in the same region of the document");""!==o.d&&(o.p=h(o.p,i),l(t,o))}return t},p=function(t){return null!=t.i?{d:t.i,p:t.p}:{i:t.d,p:t.p}};n.invert=function(t){t=t.slice().reverse();for(var e=0;e0))throw Error("Object components must be deletes of size > 0");break;case"string":if(!(o.length>0))throw Error("Inserts cannot be empty");break;case"number":if(!(o>0))throw Error("Skip components must be >0");if("number"==typeof t)throw Error("Adjacent skip components should be combined")}t=o}if("number"==typeof t)throw Error("Op has a trailing skip")},o=function(e){return function(t){if(t&&0!==t.d)return 0===e.length?e.push(t):typeof t==typeof e[e.length-1]?"object"==typeof t?e[e.length-1].d+=t.d:e[e.length-1]+=t:e.push(t)}},i=function(e){var t=0,r=0,n=function(n,o){if(t===e.length)return n===-1?null:n;var i,s=e[t];return"number"==typeof s?n===-1||s-r<=n?(i=s-r,++t,r=0,i):(r+=n,n):"string"==typeof s?n===-1||"i"===o||s.length-r<=n?(i=s.slice(r),++t,r=0,i):(i=s.slice(r,r+n),r+=n,i):n===-1||"d"===o||s.d-r<=n?(i={d:s.d-r},++t,r=0,i):(r+=n,{d:n})},o=function(){return e[t]};return[n,o]},s=function(e){return"number"==typeof e?e:e.length||e.d},a=function(e){return e.length>0&&"number"==typeof e[e.length-1]&&e.pop(),e};t.normalize=function(e){for(var t=[],r=o(t),n=0;ne.length)throw Error("The op is too long for this document");r.push(e.slice(0,i)),e=e.slice(i);break;case"string":r.push(i);break;case"object":e=e.slice(i.d)}}return r.join("")+e},t.transform=function(e,t,r){if("left"!=r&&"right"!=r)throw Error("side ("+r+") must be 'left' or 'right'");n(e),n(t);for(var c=[],f=o(c),u=i(e),h=u[0],l=u[1],p=0;p0;)g=h(b,"i"),f(g),"string"!=typeof g&&(b-=s(g));break;case"string":"left"===r&&"string"==typeof l()&&f(h(-1)),f(m.length);break;case"object":for(b=m.d;b>0;)switch(g=h(b,"i"),typeof g){case"number":b-=g;break;case"string":f(g);break;case"object":b-=g.d}}}for(;m=h(-1);)f(m);return a(c)},t.compose=function(e,t){n(e),n(t);for(var r=[],c=o(r),f=i(e)[0],u=0;u0;)l=f(h,"d"),c(l),"object"!=typeof l&&(h-=s(l));break;case"string":c(p);break;case"object":for(h=p.d;h>0;)switch(l=f(h,"d"),typeof l){case"number":c({d:l}),h-=l;break;case"string":h-=l.length;break;case"object":c(l)}}}for(;p=f(-1);)c(p);return a(r)};var c=function(e,t){for(var r=0,n=0;n { - * // Iterate over the list of inputs returned - * access.inputs.forEach(midiInput => { - * // Send 'midimessage' events to the mpe.js `instrument` instance - * midiInput.addEventListener( - * 'midimessage', - * (event) => instrument.processMidiMessage(event.data) - * ); - * }); - * }); - * @param {Object} options - * @param {Boolean} [options.log=false] Log instrument state to the console on - * change - * @param {Boolean} [options.normalize=false] For all notes, remap `timbre`, - * `noteOnVelocity`, `noteOffVelocity` and `pressure` between 0 and 1, remap - * `pitchBend` between -1 and 1 - * @param {Boolean} [options.pitch=false] Adds a `pitch` property to all notes: - * uses scientific notation eg. `C4` when `true` or `'scientific'`, uses - * Helmholtz notation eg. `c'` when set to `'helmholtz'` - * @param {Boolean} [options.pitchBendRange=48] Converts `pitchBend` to the - * range specified, overriding `normalize` if both are set - * @return {Object} Instance representing an MPE compatible instrument - */ - var mpeInstrument = exports.mpeInstrument = function mpeInstrument(options) { - var defaults = { - log: false, - normalize: true, - pitch: false, - pitchBendRange: 48 - }; - var defaultedOptions = Object.assign({}, defaults, options); - var formatNote = _redux.compose.apply(undefined, _toConsumableArray([defaultedOptions.pitch && (0, _activeNoteUtils.addPitch)(defaultedOptions), defaultedOptions.pitchBendRange && (0, _activeNoteUtils.convertPitchBendRange)(defaultedOptions), defaultedOptions.normalize && _activeNoteUtils.normalize].filter(function (f) { - return f; - }))); - var formatActiveNotes = function formatActiveNotes(notes) { - return notes.map(formatNote); - }; - var middlewares = [defaultedOptions.log && (0, _middlewares.logger)(formatActiveNotes)].filter(function (f) { - return f; - }); - var store = (0, _redux.createStore)(_reducers2.default, _redux.applyMiddleware.apply(undefined, _toConsumableArray(middlewares))); - var rawActiveNotes = function rawActiveNotes() { - return store.getState().activeNotes; - }; - - /** - * Lists active notes of the `mpeInstrument` instance - * - * @example - * import mpeInstrument from 'mpe'; - * - * const instrument = mpeInstrument(); - * - * instrument.activeNotes(); - * // => [] - * - * instrument.processMidiMessage([145, 60, 127]); - * instrument.activeNotes(); - * // => [ { noteNumber: 60, - * // channel: 2, - * // noteOnVelocity: 1, - * // pitchBend: 0, - * // timbre: 0.5, - * // pressure: 0 } ] - * - * @memberof mpeInstrument - * @instance - * @return {Array} Active note objects - * @method activeNotes - */ - var activeNotes = function activeNotes() { - return formatActiveNotes(rawActiveNotes()); - }; - - /** - * Clears all active notes - * - * @example - * import mpeInstrument from 'mpe'; - * - * const instrument = mpeInstrument(); - * - * instrument.activeNotes(); - * // => [] - * - * instrument.processMidiMessage([145, 60, 127]); - * instrument.activeNotes(); - * // => [ { noteNumber: 60, - * // channel: 2, - * // noteOnVelocity: 1, - * // pitchBend: 0, - * // timbre: 0.5, - * // pressure: 0 } ] - * - * instrument.clear(); - * instrument.activeNotes() - * // => [] - * - * @memberof mpeInstrument - * @instance - * @return {undefined} - */ - var clear = function clear() { - return store.dispatch((0, _actions.clearActiveNotes)()); - }; - - /** - * Reads an MPE message and updates `mpeInstrument` state - * - * @example - * import mpeInstrument from 'mpe'; - * - * const instrument = mpeInstrument(); - * - * // Trigger a note on, channel 2, middle C, max velocity - * instrument.processMidiMessage([145, 60, 127]); - * @memberof mpeInstrument - * @instance - * @param {Uint8Array} midiMessage An MPE MIDI message - * @return {undefined} - */ - var processMidiMessage = function processMidiMessage(midiMessage) { - var actions = (0, _actions.generateMidiActions)(midiMessage, store.getState); - actions.forEach(store.dispatch); - }; - - /** - * Subscribes a callback to changes to the instance's active notes - * - * @example - * import mpeInstrument from 'mpe'; - * - * const instrument = mpeInstrument(); - * - * // Log `activeNotes` values to the console on change - * instrument.subscribe(console.log); - * @memberof mpeInstrument - * @instance - * @param {function} callback Callback for active note changes - * @return {function} Unsubscribe the callback - */ - var subscribe = function subscribe(callback) { - var currentActiveNotes = rawActiveNotes(); - return store.subscribe(function () { - var previousActiveNotes = currentActiveNotes; - currentActiveNotes = rawActiveNotes(); - if (currentActiveNotes !== previousActiveNotes) { - callback(activeNotes()); - } - }); - }; - - return { - processMidiMessage: processMidiMessage, - clear: clear, - activeNotes: activeNotes, - subscribe: subscribe - }; - }; - -/***/ }, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; - - var _createStore = __webpack_require__(4); - - var _createStore2 = _interopRequireDefault(_createStore); - - var _combineReducers = __webpack_require__(11); - - var _combineReducers2 = _interopRequireDefault(_combineReducers); - - var _bindActionCreators = __webpack_require__(13); - - var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); - - var _applyMiddleware = __webpack_require__(14); - - var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); - - var _compose = __webpack_require__(15); - - var _compose2 = _interopRequireDefault(_compose); - - var _warning = __webpack_require__(12); - - var _warning2 = _interopRequireDefault(_warning); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { "default": obj }; - } - - /* - * This is a dummy function to check if the function name has been altered by minification. - * If the function has been minified and NODE_ENV !== 'production', warn the user. - */ - function isCrushed() {} - - if (false) { - (0, _warning2["default"])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); - } - - exports.createStore = _createStore2["default"]; - exports.combineReducers = _combineReducers2["default"]; - exports.bindActionCreators = _bindActionCreators2["default"]; - exports.applyMiddleware = _applyMiddleware2["default"]; - exports.compose = _compose2["default"]; - -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - exports.__esModule = true; - exports.ActionTypes = undefined; - exports["default"] = createStore; - - var _isPlainObject = __webpack_require__(5); - - var _isPlainObject2 = _interopRequireDefault(_isPlainObject); - - var _symbolObservable = __webpack_require__(9); - - var _symbolObservable2 = _interopRequireDefault(_symbolObservable); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { "default": obj }; - } - - /** - * These are private action types reserved by Redux. - * For any unknown actions, you must return the current state. - * If the current state is undefined, you must return the initial state. - * Do not reference these action types directly in your code. - */ - var ActionTypes = exports.ActionTypes = { - INIT: '@@redux/INIT' - }; - - /** - * Creates a Redux store that holds the state tree. - * The only way to change the data in the store is to call `dispatch()` on it. - * - * There should only be a single store in your app. To specify how different - * parts of the state tree respond to actions, you may combine several reducers - * into a single reducer function by using `combineReducers`. - * - * @param {Function} reducer A function that returns the next state tree, given - * the current state tree and the action to handle. - * - * @param {any} [initialState] The initial state. You may optionally specify it - * to hydrate the state from the server in universal apps, or to restore a - * previously serialized user session. - * If you use `combineReducers` to produce the root reducer function, this must be - * an object with the same shape as `combineReducers` keys. - * - * @param {Function} enhancer The store enhancer. You may optionally specify it - * to enhance the store with third-party capabilities such as middleware, - * time travel, persistence, etc. The only store enhancer that ships with Redux - * is `applyMiddleware()`. - * - * @returns {Store} A Redux store that lets you read the state, dispatch actions - * and subscribe to changes. - */ - function createStore(reducer, initialState, enhancer) { - var _ref2; - - if (typeof initialState === 'function' && typeof enhancer === 'undefined') { - enhancer = initialState; - initialState = undefined; - } - - if (typeof enhancer !== 'undefined') { - if (typeof enhancer !== 'function') { - throw new Error('Expected the enhancer to be a function.'); - } - - return enhancer(createStore)(reducer, initialState); - } - - if (typeof reducer !== 'function') { - throw new Error('Expected the reducer to be a function.'); - } - - var currentReducer = reducer; - var currentState = initialState; - var currentListeners = []; - var nextListeners = currentListeners; - var isDispatching = false; - - function ensureCanMutateNextListeners() { - if (nextListeners === currentListeners) { - nextListeners = currentListeners.slice(); - } - } - - /** - * Reads the state tree managed by the store. - * - * @returns {any} The current state tree of your application. - */ - function getState() { - return currentState; - } - - /** - * Adds a change listener. It will be called any time an action is dispatched, - * and some part of the state tree may potentially have changed. You may then - * call `getState()` to read the current state tree inside the callback. - * - * You may call `dispatch()` from a change listener, with the following - * caveats: - * - * 1. The subscriptions are snapshotted just before every `dispatch()` call. - * If you subscribe or unsubscribe while the listeners are being invoked, this - * will not have any effect on the `dispatch()` that is currently in progress. - * However, the next `dispatch()` call, whether nested or not, will use a more - * recent snapshot of the subscription list. - * - * 2. The listener should not expect to see all state changes, as the state - * might have been updated multiple times during a nested `dispatch()` before - * the listener is called. It is, however, guaranteed that all subscribers - * registered before the `dispatch()` started will be called with the latest - * state by the time it exits. - * - * @param {Function} listener A callback to be invoked on every dispatch. - * @returns {Function} A function to remove this change listener. - */ - function subscribe(listener) { - if (typeof listener !== 'function') { - throw new Error('Expected listener to be a function.'); - } - - var isSubscribed = true; - - ensureCanMutateNextListeners(); - nextListeners.push(listener); - - return function unsubscribe() { - if (!isSubscribed) { - return; - } - - isSubscribed = false; - - ensureCanMutateNextListeners(); - var index = nextListeners.indexOf(listener); - nextListeners.splice(index, 1); - }; - } - - /** - * Dispatches an action. It is the only way to trigger a state change. - * - * The `reducer` function, used to create the store, will be called with the - * current state tree and the given `action`. Its return value will - * be considered the **next** state of the tree, and the change listeners - * will be notified. - * - * The base implementation only supports plain object actions. If you want to - * dispatch a Promise, an Observable, a thunk, or something else, you need to - * wrap your store creating function into the corresponding middleware. For - * example, see the documentation for the `redux-thunk` package. Even the - * middleware will eventually dispatch plain object actions using this method. - * - * @param {Object} action A plain object representing “what changed”. It is - * a good idea to keep actions serializable so you can record and replay user - * sessions, or use the time travelling `redux-devtools`. An action must have - * a `type` property which may not be `undefined`. It is a good idea to use - * string constants for action types. - * - * @returns {Object} For convenience, the same action object you dispatched. - * - * Note that, if you use a custom middleware, it may wrap `dispatch()` to - * return something else (for example, a Promise you can await). - */ - function dispatch(action) { - if (!(0, _isPlainObject2["default"])(action)) { - throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); - } - - if (typeof action.type === 'undefined') { - throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); - } - - if (isDispatching) { - throw new Error('Reducers may not dispatch actions.'); - } - - try { - isDispatching = true; - currentState = currentReducer(currentState, action); - } finally { - isDispatching = false; - } - - var listeners = currentListeners = nextListeners; - for (var i = 0; i < listeners.length; i++) { - listeners[i](); - } - - return action; - } - - /** - * Replaces the reducer currently used by the store to calculate the state. - * - * You might need this if your app implements code splitting and you want to - * load some of the reducers dynamically. You might also need this if you - * implement a hot reloading mechanism for Redux. - * - * @param {Function} nextReducer The reducer for the store to use instead. - * @returns {void} - */ - function replaceReducer(nextReducer) { - if (typeof nextReducer !== 'function') { - throw new Error('Expected the nextReducer to be a function.'); - } - - currentReducer = nextReducer; - dispatch({ type: ActionTypes.INIT }); - } - - /** - * Interoperability point for observable/reactive libraries. - * @returns {observable} A minimal observable of state changes. - * For more information, see the observable proposal: - * https://github.com/zenparsing/es-observable - */ - function observable() { - var _ref; - - var outerSubscribe = subscribe; - return _ref = { - /** - * The minimal observable subscription method. - * @param {Object} observer Any object that can be used as an observer. - * The observer object should have a `next` method. - * @returns {subscription} An object with an `unsubscribe` method that can - * be used to unsubscribe the observable from the store, and prevent further - * emission of values from the observable. - */ - - subscribe: function subscribe(observer) { - if ((typeof observer === 'undefined' ? 'undefined' : _typeof(observer)) !== 'object') { - throw new TypeError('Expected the observer to be an object.'); - } - - function observeState() { - if (observer.next) { - observer.next(getState()); - } - } - - observeState(); - var unsubscribe = outerSubscribe(observeState); - return { unsubscribe: unsubscribe }; - } - }, _ref[_symbolObservable2["default"]] = function () { - return this; - }, _ref; - } - - // When a store is created, an "INIT" action is dispatched so that every - // reducer returns their initial state. This effectively populates - // the initial state tree. - dispatch({ type: ActionTypes.INIT }); - - return _ref2 = { - dispatch: dispatch, - subscribe: subscribe, - getState: getState, - replaceReducer: replaceReducer - }, _ref2[_symbolObservable2["default"]] = observable, _ref2; - } - -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - var getPrototype = __webpack_require__(6), - isHostObject = __webpack_require__(7), - isObjectLike = __webpack_require__(8); - - /** `Object#toString` result references. */ - var objectTag = '[object Object]'; - - /** Used for built-in method references. */ - var objectProto = Object.prototype; - - /** Used to resolve the decompiled source of functions. */ - var funcToString = Function.prototype.toString; - - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; - - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); - - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ - var objectToString = objectProto.toString; - - /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, - * else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ - function isPlainObject(value) { - if (!isObjectLike(value) || objectToString.call(value) != objectTag || isHostObject(value)) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; - } - - module.exports = isPlainObject; - -/***/ }, -/* 6 */ -/***/ function(module, exports) { - - "use strict"; - - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeGetPrototype = Object.getPrototypeOf; - - /** - * Gets the `[[Prototype]]` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {null|Object} Returns the `[[Prototype]]`. - */ - function getPrototype(value) { - return nativeGetPrototype(Object(value)); - } - - module.exports = getPrototype; - -/***/ }, -/* 7 */ -/***/ function(module, exports) { - - 'use strict'; - - /** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ - function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; - } - - module.exports = isHostObject; - -/***/ }, -/* 8 */ -/***/ function(module, exports) { - - 'use strict'; - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ - function isObjectLike(value) { - return !!value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) == 'object'; - } - - module.exports = isObjectLike; - -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { - - /* WEBPACK VAR INJECTION */(function(global) {/* global window */ - 'use strict'; - - module.exports = __webpack_require__(10)(global || window || undefined); - /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) - -/***/ }, -/* 10 */ -/***/ function(module, exports) { - - 'use strict'; - - module.exports = function symbolObservablePonyfill(root) { - var result; - var _Symbol = root.Symbol; - - if (typeof _Symbol === 'function') { - if (_Symbol.observable) { - result = _Symbol.observable; - } else { - result = _Symbol('observable'); - _Symbol.observable = result; - } - } else { - result = '@@observable'; - } - - return result; - }; - -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - exports["default"] = combineReducers; - - var _createStore = __webpack_require__(4); - - var _isPlainObject = __webpack_require__(5); - - var _isPlainObject2 = _interopRequireDefault(_isPlainObject); - - var _warning = __webpack_require__(12); - - var _warning2 = _interopRequireDefault(_warning); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { "default": obj }; - } - - function getUndefinedStateErrorMessage(key, action) { - var actionType = action && action.type; - var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; - - return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; - } - - function getUnexpectedStateShapeWarningMessage(inputState, reducers, action) { - var reducerKeys = Object.keys(reducers); - var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'initialState argument passed to createStore' : 'previous state received by the reducer'; - - if (reducerKeys.length === 0) { - return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; - } - - if (!(0, _isPlainObject2["default"])(inputState)) { - return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); - } - - var unexpectedKeys = Object.keys(inputState).filter(function (key) { - return !reducers.hasOwnProperty(key); - }); - - if (unexpectedKeys.length > 0) { - return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); - } - } - - function assertReducerSanity(reducers) { - Object.keys(reducers).forEach(function (key) { - var reducer = reducers[key]; - var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); - - if (typeof initialState === 'undefined') { - throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); - } - - var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); - if (typeof reducer(undefined, { type: type }) === 'undefined') { - throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); - } - }); - } - - /** - * Turns an object whose values are different reducer functions, into a single - * reducer function. It will call every child reducer, and gather their results - * into a single state object, whose keys correspond to the keys of the passed - * reducer functions. - * - * @param {Object} reducers An object whose values correspond to different - * reducer functions that need to be combined into one. One handy way to obtain - * it is to use ES6 `import * as reducers` syntax. The reducers may never return - * undefined for any action. Instead, they should return their initial state - * if the state passed to them was undefined, and the current state for any - * unrecognized action. - * - * @returns {Function} A reducer function that invokes every reducer inside the - * passed object, and builds a state object with the same shape. - */ - function combineReducers(reducers) { - var reducerKeys = Object.keys(reducers); - var finalReducers = {}; - for (var i = 0; i < reducerKeys.length; i++) { - var key = reducerKeys[i]; - if (typeof reducers[key] === 'function') { - finalReducers[key] = reducers[key]; - } - } - var finalReducerKeys = Object.keys(finalReducers); - - var sanityError; - try { - assertReducerSanity(finalReducers); - } catch (e) { - sanityError = e; - } - - return function combination() { - var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; - var action = arguments[1]; - - if (sanityError) { - throw sanityError; - } - - if (false) { - var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action); - if (warningMessage) { - (0, _warning2["default"])(warningMessage); - } - } - - var hasChanged = false; - var nextState = {}; - for (var i = 0; i < finalReducerKeys.length; i++) { - var key = finalReducerKeys[i]; - var reducer = finalReducers[key]; - var previousStateForKey = state[key]; - var nextStateForKey = reducer(previousStateForKey, action); - if (typeof nextStateForKey === 'undefined') { - var errorMessage = getUndefinedStateErrorMessage(key, action); - throw new Error(errorMessage); - } - nextState[key] = nextStateForKey; - hasChanged = hasChanged || nextStateForKey !== previousStateForKey; - } - return hasChanged ? nextState : state; - }; - } - -/***/ }, -/* 12 */ -/***/ function(module, exports) { - - 'use strict'; - - exports.__esModule = true; - exports["default"] = warning; - /** - * Prints a warning in the console if it exists. - * - * @param {String} message The warning message. - * @returns {void} - */ - function warning(message) { - /* eslint-disable no-console */ - if (typeof console !== 'undefined' && typeof console.error === 'function') { - console.error(message); - } - /* eslint-enable no-console */ - try { - // This error was thrown as a convenience so that if you enable - // "break on all exceptions" in your console, - // it would pause the execution at this line. - throw new Error(message); - /* eslint-disable no-empty */ - } catch (e) {} - /* eslint-enable no-empty */ - } - -/***/ }, -/* 13 */ -/***/ function(module, exports) { - - 'use strict'; - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - exports.__esModule = true; - exports["default"] = bindActionCreators; - function bindActionCreator(actionCreator, dispatch) { - return function () { - return dispatch(actionCreator.apply(undefined, arguments)); - }; - } - - /** - * Turns an object whose values are action creators, into an object with the - * same keys, but with every function wrapped into a `dispatch` call so they - * may be invoked directly. This is just a convenience method, as you can call - * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. - * - * For convenience, you can also pass a single function as the first argument, - * and get a function in return. - * - * @param {Function|Object} actionCreators An object whose values are action - * creator functions. One handy way to obtain it is to use ES6 `import * as` - * syntax. You may also pass a single function. - * - * @param {Function} dispatch The `dispatch` function available on your Redux - * store. - * - * @returns {Function|Object} The object mimicking the original object, but with - * every action creator wrapped into the `dispatch` call. If you passed a - * function as `actionCreators`, the return value will also be a single - * function. - */ - function bindActionCreators(actionCreators, dispatch) { - if (typeof actionCreators === 'function') { - return bindActionCreator(actionCreators, dispatch); - } - - if ((typeof actionCreators === 'undefined' ? 'undefined' : _typeof(actionCreators)) !== 'object' || actionCreators === null) { - throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators === 'undefined' ? 'undefined' : _typeof(actionCreators)) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); - } - - var keys = Object.keys(actionCreators); - var boundActionCreators = {}; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var actionCreator = actionCreators[key]; - if (typeof actionCreator === 'function') { - boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); - } - } - return boundActionCreators; - } - -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - exports.__esModule = true; - - var _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i];for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - }return target; - }; - - exports["default"] = applyMiddleware; - - var _compose = __webpack_require__(15); - - var _compose2 = _interopRequireDefault(_compose); - - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { "default": obj }; - } - - /** - * Creates a store enhancer that applies middleware to the dispatch method - * of the Redux store. This is handy for a variety of tasks, such as expressing - * asynchronous actions in a concise manner, or logging every action payload. - * - * See `redux-thunk` package as an example of the Redux middleware. - * - * Because middleware is potentially asynchronous, this should be the first - * store enhancer in the composition chain. - * - * Note that each middleware will be given the `dispatch` and `getState` functions - * as named arguments. - * - * @param {...Function} middlewares The middleware chain to be applied. - * @returns {Function} A store enhancer applying the middleware. - */ - function applyMiddleware() { - for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { - middlewares[_key] = arguments[_key]; - } - - return function (createStore) { - return function (reducer, initialState, enhancer) { - var store = createStore(reducer, initialState, enhancer); - var _dispatch = store.dispatch; - var chain = []; - - var middlewareAPI = { - getState: store.getState, - dispatch: function dispatch(action) { - return _dispatch(action); - } - }; - chain = middlewares.map(function (middleware) { - return middleware(middlewareAPI); - }); - _dispatch = _compose2["default"].apply(undefined, chain)(store.dispatch); - - return _extends({}, store, { - dispatch: _dispatch - }); - }; - }; - } - -/***/ }, -/* 15 */ -/***/ function(module, exports) { - - "use strict"; - - var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - - exports.__esModule = true; - exports["default"] = compose; - /** - * Composes single-argument functions from right to left. The rightmost - * function can take multiple arguments as it provides the signature for - * the resulting composite function. - * - * @param {...Function} funcs The functions to compose. - * @returns {Function} A function obtained by composing the argument functions - * from right to left. For example, compose(f, g, h) is identical to doing - * (...args) => f(g(h(...args))). - */ - - function compose() { - for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { - funcs[_key] = arguments[_key]; - } - - if (funcs.length === 0) { - return function (arg) { - return arg; - }; - } else { - var _ret = function () { - var last = funcs[funcs.length - 1]; - var rest = funcs.slice(0, -1); - return { - v: function v() { - return rest.reduceRight(function (composed, f) { - return f(composed); - }, last.apply(undefined, arguments)); - } - }; - }(); - - if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v; - } - } - -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.generateMidiActions = exports.clearActiveNotes = undefined; - - var _statusByteUtils = __webpack_require__(17); - - var _defaults = __webpack_require__(19); - - var defaults = _interopRequireWildcard(_defaults); - - var _actionTypes = __webpack_require__(21); - - var types = _interopRequireWildcard(_actionTypes); - - var _dataByteUtils = __webpack_require__(23); - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - var clearActiveNotes = exports.clearActiveNotes = function clearActiveNotes() { - return { - type: types.ALL_NOTES_OFF - }; - }; - - var generateMidiActions = exports.generateMidiActions = function generateMidiActions(midiMessage, currentStateCallback) { - var channel = (0, _statusByteUtils.statusByteToChannel)(midiMessage[0]); - var dataBytes = midiMessage.slice(1); - - var midiMessageType = (0, _statusByteUtils.statusByteClassifier)(midiMessage[0]); - var type = deriveActionType(midiMessageType, channel, dataBytes); - var baseData = { type: type, midiMessageType: midiMessageType, channel: channel, dataBytes: dataBytes }; - var typeSpecificData = deriveTypeSpecificData(baseData, currentStateCallback); - var mainAction = Object.assign({}, baseData, typeSpecificData); - if (type === types.NOTE_OFF) { - return [mainAction, { type: types.NOTE_RELEASED }]; - } - return [mainAction]; - }; - - var deriveActionType = function deriveActionType(midiMessageType, channel, dataBytes) { - switch (midiMessageType) { - case types.NOTE_ON: - // A note on with velocity 0 is a treated as a note off - if (dataBytes[1] === 0) return types.NOTE_OFF; - break; - case types.CONTROL_CHANGE: - // CC 74 is used for timbre messages - if (dataBytes[0] === 74) return types.TIMBRE; - // CC 123 on the master channel is an all notes off message - if (dataBytes[0] === 123 && channel === 1) return types.ALL_NOTES_OFF; - break; - } - return midiMessageType; - }; - - var deriveTypeSpecificData = function deriveTypeSpecificData(baseData, currentStateCallback) { - var type = baseData.type, - midiMessageType = baseData.midiMessageType, - channel = baseData.channel, - dataBytes = baseData.dataBytes; - - switch (type) { - case types.NOTE_ON: - { - // Note On messages bundle channelScope to set expression values at creation. - var channelScope = currentStateCallback().channelScopes[channel]; - return { noteNumber: dataBytes[0], noteOnVelocity: dataBytes[1], channelScope: channelScope }; - } - case types.NOTE_OFF: - // A note on with velocity 0 is treated as a note off with velocity 64 - return midiMessageType === types.NOTE_ON ? { noteNumber: dataBytes[0], noteOffVelocity: defaults.NOTE_OFF_VELOCITY } : { noteNumber: dataBytes[0], noteOffVelocity: dataBytes[1] }; - case types.PITCH_BEND: - // This Control Change message's data bytes are ordered [LSB, MSB]. - return { pitchBend: (0, _dataByteUtils.dataBytesToUint14)(dataBytes.reverse()) }; - case types.TIMBRE: - return { timbre: (0, _dataByteUtils.dataBytesToUint14)([dataBytes[1]]) }; - case types.CHANNEL_PRESSURE: - return { pressure: (0, _dataByteUtils.dataBytesToUint14)(dataBytes) }; - } - }; - -/***/ }, -/* 17 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.statusByteToChannel = exports.statusByteClassifier = undefined; - - var _midiMessageTypes = __webpack_require__(18); - - var types = _interopRequireWildcard(_midiMessageTypes); - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - var statusByteClassifier = exports.statusByteClassifier = function statusByteClassifier(statusByte) { - var firstNibble = statusByte & 0xf0; - switch (firstNibble) { - case 0x80: - return types.NOTE_OFF; - case 0x90: - return types.NOTE_ON; - case 0xa0: - return types.AFTERTOUCH; - case 0xb0: - return types.CONTROL_CHANGE; - case 0xc0: - return types.PROGRAM_CHANGE; - case 0xd0: - return types.CHANNEL_PRESSURE; - case 0xe0: - return types.PITCH_BEND; - case 0xf0: - return types.SYSTEM_MESSAGE; - } - return types.UNCLASSIFIED; - }; /** - * Maps MIDI messages contents to message types. - * - * MIDI message information derived from this table: - * https://www.midi.org/specifications/item/table-1-summary-of-midi-message - */ - - var statusByteToChannel = exports.statusByteToChannel = function statusByteToChannel(statusByte) { - return (statusByte & 0x0f) + 1; - }; - -/***/ }, -/* 18 */ -/***/ function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - /** - * Constants to map MIDI messages contents to message types. - * - * MIDI message information derived from this table: - * https://www.midi.org/specifications/item/table-1-summary-of-midi-message - */ - - var CHANNEL_MESSAGE = exports.CHANNEL_MESSAGE = 'CHANNEL_MESSAGE'; - var SYSTEM_MESSAGE = exports.SYSTEM_MESSAGE = 'SYSTEM_MESSAGE'; - var NOTE_ON = exports.NOTE_ON = 'NOTE_ON'; - var NOTE_OFF = exports.NOTE_OFF = 'NOTE_OFF'; - var AFTERTOUCH = exports.AFTERTOUCH = 'AFTERTOUCH'; - var CONTROL_CHANGE = exports.CONTROL_CHANGE = 'CONTROL_CHANGE'; - var PROGRAM_CHANGE = exports.PROGRAM_CHANGE = 'PROGRAM_CHANGE'; - var CHANNEL_PRESSURE = exports.CHANNEL_PRESSURE = 'CHANNEL_PRESSURE'; - var PITCH_BEND = exports.PITCH_BEND = 'PITCH_BEND'; - var CHANNEL_MODE = exports.CHANNEL_MODE = 'CHANNEL_MODE'; - var ALL_SOUND_OFF = exports.ALL_SOUND_OFF = 'ALL_SOUND_OFF'; - var RESET_ALL_CONTROLLERS = exports.RESET_ALL_CONTROLLERS = 'RESET_ALL_CONTROLLERS'; - var LOCAL_CONTROL = exports.LOCAL_CONTROL = 'LOCAL_CONTROL'; - var ALL_NOTES_OFF = exports.ALL_NOTES_OFF = 'ALL_NOTES_OFF'; - var SYSTEM_EXCLUSIVE = exports.SYSTEM_EXCLUSIVE = 'SYSTEM_EXCLUSIVE'; - var MIDI_TIME_CODE_QUARTER_FRAME = exports.MIDI_TIME_CODE_QUARTER_FRAME = 'MIDI_TIME_CODE_QUARTER_FRAME'; - var SONG_POSITION_POINTER = exports.SONG_POSITION_POINTER = 'SONG_POSITION_POINTER'; - var SONG_SELECT = exports.SONG_SELECT = 'SONG_SELECT'; - var TUNE_REQUEST = exports.TUNE_REQUEST = 'TUNE_REQUEST'; - var END_OF_EXCLUSIVE = exports.END_OF_EXCLUSIVE = 'END_OF_EXCLUSIVE'; - var TIMING_CLOCK = exports.TIMING_CLOCK = 'TIMING_CLOCK'; - var UNDEFINED = exports.UNDEFINED = 'UNDEFINED'; - var START = exports.START = 'START'; - var CONTINUE = exports.CONTINUE = 'CONTINUE'; - var STOP = exports.STOP = 'STOP'; - var ACTIVE_SENSING = exports.ACTIVE_SENSING = 'ACTIVE_SENSING'; - var RESET = exports.RESET = 'RESET'; - var UNCLASSIFIED = exports.UNCLASSIFIED = 'UNCLASSIFIED'; - -/***/ }, -/* 19 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.CHANNEL_SCOPES = exports.CHANNEL_SCOPE = exports.ACTIVE_NOTE = exports.NOTE_STATE = exports.NOTE_OFF_VELOCITY = exports.TIMBRE = exports.PRESSURE = exports.PITCH_BEND = exports.NOTE_ON_VELOCITY = undefined; - - var _noteStates = __webpack_require__(20); - - var noteStates = _interopRequireWildcard(_noteStates); - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - var NOTE_ON_VELOCITY = exports.NOTE_ON_VELOCITY = 64; - var PITCH_BEND = exports.PITCH_BEND = 8192; - var PRESSURE = exports.PRESSURE = 0; - var TIMBRE = exports.TIMBRE = 8192; - var NOTE_OFF_VELOCITY = exports.NOTE_OFF_VELOCITY = 64; - var NOTE_STATE = exports.NOTE_STATE = noteStates.KEY_DOWN; - - var ACTIVE_NOTE = exports.ACTIVE_NOTE = { - noteOnVelocity: NOTE_ON_VELOCITY, - pitchBend: PITCH_BEND, - pressure: PRESSURE, - timbre: TIMBRE, - noteState: NOTE_STATE - }; - - var CHANNEL_SCOPE = exports.CHANNEL_SCOPE = { - pitchBend: PITCH_BEND, - timbre: TIMBRE, - pressure: PRESSURE - }; - - var CHANNEL_SCOPES = exports.CHANNEL_SCOPES = { - 1: CHANNEL_SCOPE, - 2: CHANNEL_SCOPE, - 3: CHANNEL_SCOPE, - 4: CHANNEL_SCOPE, - 5: CHANNEL_SCOPE, - 6: CHANNEL_SCOPE, - 7: CHANNEL_SCOPE, - 8: CHANNEL_SCOPE, - 9: CHANNEL_SCOPE, - 10: CHANNEL_SCOPE, - 11: CHANNEL_SCOPE, - 12: CHANNEL_SCOPE, - 13: CHANNEL_SCOPE, - 14: CHANNEL_SCOPE, - 15: CHANNEL_SCOPE, - 16: CHANNEL_SCOPE - }; - -/***/ }, -/* 20 */ -/***/ function(module, exports) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var OFF = exports.OFF = 0; - var KEY_DOWN = exports.KEY_DOWN = 1; - var SUSTAINED = exports.SUSTAINED = 2; - var KEY_DOWN_AND_SUSTAINED = exports.KEY_DOWN_AND_SUSTAINED = 3; - -/***/ }, -/* 21 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _midiMessageTypes = __webpack_require__(18); - - Object.keys(_midiMessageTypes).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _midiMessageTypes[key]; - } - }); - }); - - var _mpeMessageTypes = __webpack_require__(22); - - Object.keys(_mpeMessageTypes).forEach(function (key) { - if (key === "default" || key === "__esModule") return; - Object.defineProperty(exports, key, { - enumerable: true, - get: function get() { - return _mpeMessageTypes[key]; - } - }); - }); - -/***/ }, -/* 22 */ -/***/ function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var TIMBRE = exports.TIMBRE = 'TIMBRE'; - var NOTE_RELEASED = exports.NOTE_RELEASED = 'NOTE_RELEASED'; - -/***/ }, -/* 23 */ -/***/ function(module, exports) { - - "use strict"; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - /** - * Scales 7-bit values into the 14-bit range. - * - * @param {uint8} input Input 7-bit integer. - * @returns {uint16} Scaled 14-bit integer. - */ - var scale7To14Bit = exports.scale7To14Bit = function scale7To14Bit(input) { - if (input > 127) { - throw new RangeError("scale7To14Bit takes a 7-bit integer.\n" + ("scale7To14Bit(" + input + ") is invalid.")); - } - if (input <= 64) { - return input << 7; - } - return input / 127 * 16383; - }; - - /** - * Converts one or two MIDI data bytes into normalized 14-bit values. - * - * @param {uint8} midiDataBytes The encoded data from a standard MIDI message. - * @returns {uint16} Normalized 14-bit integer representation of the inputs. - */ - var dataBytesToUint14 = exports.dataBytesToUint14 = function dataBytesToUint14(midiDataBytes) { - // Discard identifier bit. - var midiDataByteContents = midiDataBytes.map(function (dataByte) { - return 127 & dataByte; - }); - switch (midiDataBytes.length) { - case 1: - // With one 7-bit value, scale to a 14-bit integer. - return scale7To14Bit(midiDataByteContents[0]); - case 2: - // With two 7-bit values, combine to make one 14-bit integer - return (midiDataByteContents[0] << 7) + midiDataByteContents[1]; - } - throw new Error("midiDataToMpeValue takes one or two 8-bit integers.\n" + ("midiDataToMpeValue(" + midiDataBytes + ") is invalid.")); - }; - - var int7ToUnsignedFloat = exports.int7ToUnsignedFloat = function int7ToUnsignedFloat(v) { - return v <= 64 ? 0.5 * v / 64 : 0.5 + 0.5 * (v - 64) / 63; - }; - - var int14ToUnsignedFloat = exports.int14ToUnsignedFloat = function int14ToUnsignedFloat(v) { - return v <= 8192 ? 0.5 * v / 8192 : 0.5 + 0.5 * (v - 8192) / 8191; - }; - - var int14ToSignedFloat = exports.int14ToSignedFloat = function int14ToSignedFloat(v) { - return v <= 8192 ? v / 8192 - 1 : (v - 8192) / 8191; - }; - -/***/ }, -/* 24 */ -/***/ function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var currentActiveNotes = void 0; - - /* eslint-disable no-console */ - var logger = exports.logger = function logger(formatActiveNotes) { - return function (store) { - return function (next) { - return function (action) { - var result = next(action); - var previousActiveNotes = currentActiveNotes; - currentActiveNotes = store.getState().activeNotes; - if (currentActiveNotes !== previousActiveNotes) { - console.log('active notes:', formatActiveNotes(currentActiveNotes)); - } - return result; - }; - }; - }; - }; - /* eslint-enable no-console */ - -/***/ }, -/* 25 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - exports.findActiveNoteIndexesByChannel = exports.findActiveNoteIndex = exports.convertPitchBendRange = exports.createPitchBendConverter = exports.addPitch = exports.addHelmholtzPitch = exports.addScientificPitch = exports.normalize = undefined; - - var _redux = __webpack_require__(3); - - var _objectUtils = __webpack_require__(26); - - var _dataByteUtils = __webpack_require__(23); - - var _noteNumberUtils = __webpack_require__(27); - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - var NORMALIZE_NOTE_TRANSFORMATIONS = { - noteOnVelocity: _dataByteUtils.int7ToUnsignedFloat, - noteOffVelocity: _dataByteUtils.int7ToUnsignedFloat, - pitchBend: _dataByteUtils.int14ToSignedFloat, - pressure: _dataByteUtils.int14ToUnsignedFloat, - timbre: _dataByteUtils.int14ToUnsignedFloat - }; - - var normalize = exports.normalize = function normalize(note) { - return (0, _objectUtils.transformObject)(note, NORMALIZE_NOTE_TRANSFORMATIONS); - }; - - var addScientificPitch = exports.addScientificPitch = function addScientificPitch(action) { - return typeof action.noteNumber === 'undefined' ? action : Object.assign({}, action, { pitch: (0, _noteNumberUtils.toScientificPitch)(action.noteNumber) }); - }; - - var addHelmholtzPitch = exports.addHelmholtzPitch = function addHelmholtzPitch(action) { - return typeof action.noteNumber === 'undefined' ? action : Object.assign({}, action, { pitch: (0, _noteNumberUtils.toHelmholtzPitch)(action.noteNumber) }); - }; - - var addPitch = exports.addPitch = function addPitch(_ref) { - var pitch = _ref.pitch; - return pitch === 'helmholtz' ? addHelmholtzPitch : addScientificPitch; - }; - - var createPitchBendConverter = exports.createPitchBendConverter = function createPitchBendConverter(pitchBendRange, normalize) { - var conversionFunctions = [pitchBendRange && function (v) { - return v * parseFloat(pitchBendRange); - }, !normalize && _dataByteUtils.int14ToSignedFloat].filter(function (f) { - return f; - }); - return _redux.compose.apply(undefined, _toConsumableArray(conversionFunctions)); - }; - - var convertPitchBendRange = exports.convertPitchBendRange = function convertPitchBendRange(_ref2) { - var pitchBendRange = _ref2.pitchBendRange, - normalize = _ref2.normalize; - return function (action) { - return Object.assign({}, action, { pitchBend: createPitchBendConverter(pitchBendRange, normalize)(action.pitchBend) }); - }; - }; - - var findActiveNoteIndex = exports.findActiveNoteIndex = function findActiveNoteIndex(state, action) { - var channel = action.channel, - noteNumber = action.noteNumber; - - return state.findIndex(function (activeNote) { - return activeNote.channel === channel && activeNote.noteNumber === noteNumber; - }); - }; - - var findActiveNoteIndexesByChannel = exports.findActiveNoteIndexesByChannel = function findActiveNoteIndexesByChannel(state, action) { - return state.reduce(function (indexes, activeNote, index) { - return activeNote.channel === action.channel ? [].concat(_toConsumableArray(indexes), [index]) : indexes; - }, []); - }; - -/***/ }, -/* 26 */ -/***/ function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var transformObject = exports.transformObject = function transformObject(object) { - var transformations = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var changedValues = Object.keys(transformations).reduce(function (acc, key) { - if (typeof object[key] !== 'undefined') { - acc[key] = transformations[key](object[key]); - } - return acc; - }, {}); - - return Object.assign({}, object, changedValues); - }; - -/***/ }, -/* 27 */ -/***/ function(module, exports) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - var PITCH_CLASS_NUMBER_TO_PITCH_NAME = { - 0: 'C', - 1: 'C#', - 2: 'D', - 3: 'Eb', - 4: 'E', - 5: 'F', - 6: 'F#', - 7: 'G', - 8: 'Ab', - 9: 'A', - 10: 'Bb', - 11: 'B' - }; - - var toPitchClassNumber = exports.toPitchClassNumber = function toPitchClassNumber(noteNumber) { - return Math.floor(noteNumber % 12); - }; - - var toOctaveNumber = exports.toOctaveNumber = function toOctaveNumber(noteNumber) { - return Math.floor(noteNumber / 12) - 1; - }; - - var toPitchClassName = exports.toPitchClassName = function toPitchClassName(noteNumber) { - return PITCH_CLASS_NUMBER_TO_PITCH_NAME[toPitchClassNumber(noteNumber)]; - }; - - var toHelmholtzCommas = exports.toHelmholtzCommas = function toHelmholtzCommas(noteNumber) { - var numCommas = Math.max(-1 * toOctaveNumber(noteNumber) + 2, 0); - return new Array(numCommas).fill(',').join(''); - }; - - var toHelmholtzApostrophes = exports.toHelmholtzApostrophes = function toHelmholtzApostrophes(noteNumber) { - var numApostrophes = Math.max(toOctaveNumber(noteNumber) - 3, 0); - return new Array(numApostrophes).fill('\'').join(''); - }; - - var toHelmholtzPitchName = exports.toHelmholtzPitchName = function toHelmholtzPitchName(noteNumber) { - return noteNumber >= 48 ? toPitchClassName(noteNumber).toLowerCase() : toPitchClassName(noteNumber); - }; - - var toHelmholtzPitch = exports.toHelmholtzPitch = function toHelmholtzPitch(noteNumber) { - return '' + toHelmholtzPitchName(noteNumber) + toHelmholtzCommas(noteNumber) + toHelmholtzApostrophes(noteNumber); - }; - - var toScientificPitch = exports.toScientificPitch = function toScientificPitch(noteNumber) { - return '' + toPitchClassName(noteNumber) + toOctaveNumber(noteNumber); - }; - -/***/ }, -/* 28 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _redux = __webpack_require__(3); - - var _activeNotes = __webpack_require__(29); - - var _activeNotes2 = _interopRequireDefault(_activeNotes); - - var _channelScopes = __webpack_require__(30); - - var _channelScopes2 = _interopRequireDefault(_channelScopes); - - function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - - exports.default = (0, _redux.combineReducers)({ - channelScopes: _channelScopes2.default, - activeNotes: _activeNotes2.default - }); - -/***/ }, -/* 29 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _actionTypes = __webpack_require__(21); - - var types = _interopRequireWildcard(_actionTypes); - - var _defaults = __webpack_require__(19); - - var defaults = _interopRequireWildcard(_defaults); - - var _noteStates = __webpack_require__(20); - - var noteStates = _interopRequireWildcard(_noteStates); - - var _activeNoteUtils = __webpack_require__(25); - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } - - var activeNotes = function activeNotes() { - var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var action = arguments[1]; - - if (!types[action.type]) { - return state; - } - switch (action.type) { - case types.NOTE_ON: - return [].concat(_toConsumableArray(state), [activeNote({}, action)]); - case types.NOTE_OFF: - { - var noteIndex = (0, _activeNoteUtils.findActiveNoteIndex)(state, action); - return noteIndex >= 0 ? [].concat(_toConsumableArray(state.slice(0, noteIndex)), [activeNote(state[noteIndex], action)], _toConsumableArray(state.slice(noteIndex + 1))) : state; - } - case types.PITCH_BEND: - case types.CHANNEL_PRESSURE: - case types.TIMBRE: - { - var noteIndexes = (0, _activeNoteUtils.findActiveNoteIndexesByChannel)(state, action); - noteIndexes.forEach(function (noteIndex) { - state = [].concat(_toConsumableArray(state.slice(0, noteIndex)), [activeNote(state[noteIndex], action)], _toConsumableArray(state.slice(noteIndex + 1))); - }); - return state; - } - case types.NOTE_RELEASED: - return state.length ? state.filter(function (activeNote) { - return activeNote.noteState !== noteStates.OFF; - }) : state; - case types.ALL_NOTES_OFF: - return []; - } - return state; - }; - - var activeNote = function activeNote() { - var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaults.ACTIVE_NOTE; - var action = arguments[1]; - var noteNumber = action.noteNumber, - channel = action.channel, - channelScope = action.channelScope, - noteOnVelocity = action.noteOnVelocity, - noteOffVelocity = action.noteOffVelocity, - pitch = action.pitch, - pitchBend = action.pitchBend, - pressure = action.pressure, - timbre = action.timbre; - - switch (action.type) { - case types.NOTE_ON: - return Object.assign({}, state, { noteNumber: noteNumber, channel: channel, noteOnVelocity: noteOnVelocity }, pitch && { pitch: pitch }, channelScope); - case types.NOTE_OFF: - return Object.assign({}, state, { noteOffVelocity: noteOffVelocity, noteState: noteStates.OFF }); - case types.PITCH_BEND: - return Object.assign({}, state, { pitchBend: pitchBend }); - case types.CHANNEL_PRESSURE: - return Object.assign({}, state, { pressure: pressure }); - case types.TIMBRE: - return Object.assign({}, state, { timbre: timbre }); - } - return state; - }; - - exports.default = activeNotes; - -/***/ }, -/* 30 */ -/***/ function(module, exports, __webpack_require__) { - - 'use strict'; - - Object.defineProperty(exports, "__esModule", { - value: true - }); - - var _actionTypes = __webpack_require__(21); - - var types = _interopRequireWildcard(_actionTypes); - - var _defaults = __webpack_require__(19); - - var defaults = _interopRequireWildcard(_defaults); - - function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } - - function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } - - var channelScopes = function channelScopes() { - var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaults.CHANNEL_SCOPES; - var action = arguments[1]; - - if (!types[action.type]) { - return state; - } - var channel = action.channel; - - return Object.assign({}, state, _defineProperty({}, channel, channelScope(state[channel], action))); - }; - - var channelScope = function channelScope(state, action) { - switch (action.type) { - case types.PITCH_BEND: - return Object.assign({}, state, { pitchBend: action.pitchBend }); - case types.CHANNEL_PRESSURE: - return Object.assign({}, state, { pressure: action.pressure }); - case types.TIMBRE: - return Object.assign({}, state, { timbre: action.timbre }); - case types.NOTE_ON: - case types.NOTE_OFF: - return defaults.CHANNEL_SCOPE; - } - return state; - }; - - exports.default = channelScopes; - -/***/ } -/******/ ]); -// https://github.com/eligrey/FileSaver.js/ -/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */ -var saveAs=saveAs||function(e){"use strict";if(typeof e==="undefined"||typeof navigator!=="undefined"&&/MSIE [1-9]\./.test(navigator.userAgent)){return}var t=e.document,n=function(){return e.URL||e.webkitURL||e},r=t.createElementNS("http://www.w3.org/1999/xhtml","a"),o="download"in r,a=function(e){var t=new MouseEvent("click");e.dispatchEvent(t)},i=/constructor/i.test(e.HTMLElement)||e.safari,f=/CriOS\/[\d]+/.test(navigator.userAgent),u=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s="application/octet-stream",d=1e3*40,c=function(e){var t=function(){if(typeof e==="string"){n().revokeObjectURL(e)}else{e.remove()}};setTimeout(t,d)},l=function(e,t,n){t=[].concat(t);var r=t.length;while(r--){var o=e["on"+t[r]];if(typeof o==="function"){try{o.call(e,n||e)}catch(a){u(a)}}}},p=function(e){if(/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)){return new Blob([String.fromCharCode(65279),e],{type:e.type})}return e},v=function(t,u,d){if(!d){t=p(t)}var v=this,w=t.type,m=w===s,y,h=function(){l(v,"writestart progress write writeend".split(" "))},S=function(){if((f||m&&i)&&e.FileReader){var r=new FileReader;r.onloadend=function(){var t=f?r.result:r.result.replace(/^data:[^;]*;/,"data:attachment/file;");var n=e.open(t,"_blank");if(!n)e.location.href=t;t=undefined;v.readyState=v.DONE;h()};r.readAsDataURL(t);v.readyState=v.INIT;return}if(!y){y=n().createObjectURL(t)}if(m){e.location.href=y}else{var o=e.open(y,"_blank");if(!o){e.location.href=y}}v.readyState=v.DONE;h();c(y)};v.readyState=v.INIT;if(o){y=n().createObjectURL(t);setTimeout(function(){r.href=y;r.download=u;a(r);h();c(y);v.readyState=v.DONE});return}S()},w=v.prototype,m=function(e,t,n){return new v(e,t||e.name||"download",n)};if(typeof navigator!=="undefined"&&navigator.msSaveOrOpenBlob){return function(e,t,n){t=t||e.name||"download";if(!n){e=p(e)}return navigator.msSaveOrOpenBlob(e,t)}}w.abort=function(){};w.readyState=w.INIT=0;w.WRITING=1;w.DONE=2;w.error=w.onwritestart=w.onprogress=w.onwrite=w.onabort=w.onerror=w.onwriteend=null;return m}(typeof self!=="undefined"&&self||typeof window!=="undefined"&&window||this.content);if(typeof module!=="undefined"&&module.exports){module.exports.saveAs=saveAs}else if(typeof define!=="undefined"&&define!==null&&define.amd!==null){define("FileSaver.js",function(){return saveAs})} - -// https://anseki.github.io/leader-line/ -/*! LeaderLine v1.0.5 (c) anseki https://anseki.github.io/leader-line/ */ -var LeaderLine=function(){"use strict";var te,g,y,S,_,o,t,h,f,p,a,i,l,v="leader-line",M=1,I=2,C=3,L=4,n={top:M,right:I,bottom:C,left:L},A=1,V=2,P=3,N=4,T=5,m={straight:A,arc:V,fluid:P,magnet:N,grid:T},ne="behind",r=v+"-defs",s='',ae={disc:{elmId:"leader-line-disc",noRotate:!0,bBox:{left:-5,top:-5,width:10,height:10,right:5,bottom:5},widthR:2.5,heightR:2.5,bCircle:5,sideLen:5,backLen:5,overhead:0,outlineBase:1,outlineMax:4},square:{elmId:"leader-line-square",noRotate:!0,bBox:{left:-5,top:-5,width:10,height:10,right:5,bottom:5},widthR:2.5,heightR:2.5,bCircle:5,sideLen:5,backLen:5,overhead:0,outlineBase:1,outlineMax:4},arrow1:{elmId:"leader-line-arrow1",bBox:{left:-8,top:-8,width:16,height:16,right:8,bottom:8},widthR:4,heightR:4,bCircle:8,sideLen:8,backLen:8,overhead:8,outlineBase:2,outlineMax:1.5},arrow2:{elmId:"leader-line-arrow2",bBox:{left:-7,top:-8,width:11,height:16,right:4,bottom:8},widthR:2.75,heightR:4,bCircle:8,sideLen:8,backLen:7,overhead:4,outlineBase:1,outlineMax:1.75},arrow3:{elmId:"leader-line-arrow3",bBox:{left:-4,top:-5,width:12,height:10,right:8,bottom:5},widthR:3,heightR:2.5,bCircle:8,sideLen:5,backLen:4,overhead:8,outlineBase:1,outlineMax:2.5},hand:{elmId:"leader-line-hand",bBox:{left:-3,top:-12,width:40,height:24,right:37,bottom:12},widthR:10,heightR:6,bCircle:37,sideLen:12,backLen:3,overhead:37},crosshair:{elmId:"leader-line-crosshair",noRotate:!0,bBox:{left:-96,top:-96,width:192,height:192,right:96,bottom:96},widthR:48,heightR:48,bCircle:96,sideLen:96,backLen:96,overhead:0}},E={behind:ne,disc:"disc",square:"square",arrow1:"arrow1",arrow2:"arrow2",arrow3:"arrow3",hand:"hand",crosshair:"crosshair"},ie={disc:"disc",square:"square",arrow1:"arrow1",arrow2:"arrow2",arrow3:"arrow3",hand:"hand",crosshair:"crosshair"},W=[M,I,C,L],x="auto",oe={x:"left",y:"top",width:"width",height:"height"},B=80,R=4,F=5,G=120,D=8,z=3.75,j=10,H=30,U=.5522847,Z=.25*Math.PI,u=/^\s*(\-?[\d\.]+)\s*(\%)?\s*$/,b="http://www.w3.org/2000/svg",e="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style&&!window.navigator.msPointerEnabled,le=!e&&!!document.uniqueID,re="MozAppearance"in document.documentElement.style,se=!(e||re||!window.chrome||!window.CSS),ue=!e&&!le&&!re&&!se&&!window.chrome&&"WebkitAppearance"in document.documentElement.style,he=le||e?.2:.1,pe={path:P,lineColor:"coral",lineSize:4,plugSE:[ne,"arrow1"],plugSizeSE:[1,1],lineOutlineEnabled:!1,lineOutlineColor:"indianred",lineOutlineSize:.25,plugOutlineEnabledSE:[!1,!1],plugOutlineSizeSE:[1,1]},k=(a={}.toString,i={}.hasOwnProperty.toString,l=i.call(Object),function(e){var t,n;return e&&"[object Object]"===a.call(e)&&(!(t=Object.getPrototypeOf(e))||(n=t.hasOwnProperty("constructor")&&t.constructor)&&"function"==typeof n&&i.call(n)===l)}),w=Number.isFinite||function(e){return"number"==typeof e&&window.isFinite(e)},c=function(){var e,x={ease:[.25,.1,.25,1],linear:[0,0,1,1],"ease-in":[.42,0,1,1],"ease-out":[0,0,.58,1],"ease-in-out":[.42,0,.58,1]},b=1e3/60/2,t=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){setTimeout(e,b)},n=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.msCancelAnimationFrame||function(e){clearTimeout(e)},a=Number.isFinite||function(e){return"number"==typeof e&&window.isFinite(e)},k=[],w=0;function l(){var i=Date.now(),o=!1;e&&(n.call(window,e),e=null),k.forEach(function(e){var t,n,a;if(e.framesStart){if((t=i-e.framesStart)>=e.duration&&e.count&&e.loopsLeft<=1)return a=e.frames[e.lastFrame=e.reverse?0:e.frames.length-1],e.frameCallback(a.value,!0,a.timeRatio,a.outputRatio),void(e.framesStart=null);if(t>e.duration){if(n=Math.floor(t/e.duration),e.count){if(n>=e.loopsLeft)return a=e.frames[e.lastFrame=e.reverse?0:e.frames.length-1],e.frameCallback(a.value,!0,a.timeRatio,a.outputRatio),void(e.framesStart=null);e.loopsLeft-=n}e.framesStart+=e.duration*n,t=i-e.framesStart}e.reverse&&(t=e.duration-t),a=e.frames[e.lastFrame=Math.round(t/b)],!1!==e.frameCallback(a.value,!1,a.timeRatio,a.outputRatio)?o=!0:e.framesStart=null}}),o&&(e=t.call(window,l))}function O(e,t){e.framesStart=Date.now(),null!=t&&(e.framesStart-=e.duration*(e.reverse?1-t:t)),e.loopsLeft=e.count,e.lastFrame=null,l()}return{add:function(n,e,t,a,i,o,l){var r,s,u,h,p,c,d,f,y,S,m,g,_,v=++w;function E(e,t){return{value:n(t),timeRatio:e,outputRatio:t}}if("string"==typeof i&&(i=x[i]),n=n||function(){},t=this._endIndex||this._string[this._currentIndex]<"0"||"9"=this._endIndex||this._string[this._currentIndex]<"0"||"9"=this._endIndex)return null;var e=null,t=this._string[this._currentIndex];if(this._currentIndex+=1,"0"===t)e=0;else{if("1"!==t)return null;e=1}return this._skipOptionalSpacesOrDelimiter(),e}};var a=function(e){if(!e||0===e.length)return[];var t=new o(e),n=[];if(t.initialCommandIsMoveTo())for(;t.hasMoreData();){var a=t.parseSegment();if(null===a)break;n.push(a)}return n},n=e.SVGPathElement.prototype.setAttribute,r=e.SVGPathElement.prototype.removeAttribute,d=e.Symbol?e.Symbol():"__cachedPathData",f=e.Symbol?e.Symbol():"__cachedNormalizedPathData",U=function(e,t,n,a,i,o,l,r,s,u){var h,p,c,d,f,y=function(e,t,n){return{x:e*Math.cos(n)-t*Math.sin(n),y:e*Math.sin(n)+t*Math.cos(n)}},S=(h=l,Math.PI*h/180),m=[];if(u)p=u[0],c=u[1],d=u[2],f=u[3];else{var g=y(e,t,-S);e=g.x,t=g.y;var _=y(n,a,-S),v=(e-(n=_.x))/2,E=(t-(a=_.y))/2,x=v*v/(i*i)+E*E/(o*o);1120*Math.PI/180){var C=c,L=n,A=a;c=s&&p=Math.abs(n)?0<=t?I:L:0<=n?C:M))})),E.position_path!==x.position_path||E.position_lineStrokeWidth!==x.position_lineStrokeWidth||[0,1].some(function(e){return E.position_plugOverheadSE[e]!==x.position_plugOverheadSE[e]||(i=b[e],o=x.position_socketXYSE[e],i.x!==o.x||i.y!==o.y||i.socketId!==o.socketId)||(t=_[e],n=x.position_socketGravitySE[e],(a=null==t?"auto":Array.isArray(t)?"array":"number")!==(null==n?"auto":Array.isArray(n)?"array":"number")||("array"===a?t[0]!==n[0]||t[1]!==n[1]:t!==n));var t,n,a,i,o})){switch(u.pathList.baseVal=v=[],u.pathList.animVal=null,E.position_path){case A:v.push([O(b[0]),O(b[1])]);break;case V:t="number"==typeof _[0]&&0<_[0]||"number"==typeof _[1]&&0<_[1],o=Z*(t?-1:1),l=Math.atan2(b[1].y-b[0].y,b[1].x-b[0].x),r=-l+o,c=Math.PI-l-o,d=_e(b[0],b[1])/Math.sqrt(2)*U,S={x:b[0].x+Math.cos(r)*d,y:b[0].y+Math.sin(r)*d*-1},m={x:b[1].x+Math.cos(c)*d,y:b[1].y+Math.sin(c)*d*-1},v.push([O(b[0]),S,m,O(b[1])]);break;case P:case N:s=[_[0],E.position_path===N?0:_[1]],h=[],p=[],b.forEach(function(e,t){var n,a,i,o,l,r=s[t];Array.isArray(r)?n={x:r[0],y:r[1]}:"number"==typeof r?n=e.socketId===M?{x:0,y:-r}:e.socketId===I?{x:r,y:0}:e.socketId===C?{x:0,y:r}:{x:-r,y:0}:(a=b[t?0:1],o=0<(i=E.position_plugOverheadSE[t])?G+(DR?(E.position_lineStrokeWidth-R)*F:0),e.socketId===M?((l=(e.y-a.y)/2)=t.x:t.dirId===r?e.y>=t.y:e.x<=t.x}function y(e,t){return t.dirId===o||t.dirId===r?e.x===t.x:e.y===t.y}function S(e){return e[0]?{contain:0,notContain:1}:{contain:1,notContain:0}}function m(e,t,n){return Math.abs(t[n]-e[n])}function g(e,t,n){return"x"===n?e.x=H?g(h[t.notContain],h[t.contain],o[t.contain]):h[t.contain].dirId)):(i=[{x:h[0].x,y:h[0].y},{x:h[1].x,y:h[1].y}],u.forEach(function(e,t){var n=0===t?1:0,a=m(i[t],i[n],o[t]);aj&&(y[a]-ej&&(y[a]-ea.outlineMax&&(t=a.outlineMax),t*=2*a.outlineBase,v=We(m,_.plugOutline_strokeWidthSE,e,t)||v,v=We(m,_.plugOutline_inStrokeWidthSE,e,_.plugOutline_colorTraSE[e]?t-he/(_.line_strokeWidth/pe.lineSize)/g.plugSizeSE[e]*2:t/2)||v)}),v)),(t.faces||ee.line||ee.plug||ee.lineOutline||ee.plugOutline)&&(ee.faces=(b=(E=e).curStats,k=E.aplStats,w=E.events,O=!1,!b.line_altColor&&We(E,k,"line_color",x=b.line_color,w.apl_line_color)&&(E.lineFace.style.stroke=x,O=!0),We(E,k,"line_strokeWidth",x=b.line_strokeWidth,w.apl_line_strokeWidth)&&(E.lineShape.style.strokeWidth=x+"px",O=!0,(re||le)&&(Ae(E,E.lineShape),le&&(Ae(E,E.lineFace),Ae(E,E.lineMaskCaps)))),We(E,k,"lineOutline_enabled",x=b.lineOutline_enabled,w.apl_lineOutline_enabled)&&(E.lineOutlineFace.style.display=x?"inline":"none",O=!0),b.lineOutline_enabled&&(We(E,k,"lineOutline_color",x=b.lineOutline_color,w.apl_lineOutline_color)&&(E.lineOutlineFace.style.stroke=x,O=!0),We(E,k,"lineOutline_strokeWidth",x=b.lineOutline_strokeWidth,w.apl_lineOutline_strokeWidth)&&(E.lineOutlineMaskShape.style.strokeWidth=x+"px",O=!0,le&&(Ae(E,E.lineOutlineMaskCaps),Ae(E,E.lineOutlineFace))),We(E,k,"lineOutline_inStrokeWidth",x=b.lineOutline_inStrokeWidth,w.apl_lineOutline_inStrokeWidth)&&(E.lineMaskShape.style.strokeWidth=x+"px",O=!0,le&&(Ae(E,E.lineOutlineMaskCaps),Ae(E,E.lineOutlineFace)))),We(E,k,"plug_enabled",x=b.plug_enabled,w.apl_plug_enabled)&&(E.plugsFace.style.display=x?"inline":"none",O=!0),b.plug_enabled&&[0,1].forEach(function(n){var e=b.plug_plugSE[n],t=e!==ne?ae[ie[e]]:null,a=Ne(n,t);We(E,k.plug_enabledSE,n,x=b.plug_enabledSE[n],w.apl_plug_enabledSE)&&(E.plugsFace.style[a.prop]=x?"url(#"+E.plugMarkerIdSE[n]+")":"none",O=!0),b.plug_enabledSE[n]&&(We(E,k.plug_plugSE,n,e,w.apl_plug_plugSE)&&(E.plugFaceSE[n].href.baseVal="#"+t.elmId,Pe(E,E.plugMarkerSE[n],a.orient,t.bBox,E.svg,E.plugMarkerShapeSE[n],E.plugsFace),O=!0,re&&Ae(E,E.plugsFace)),We(E,k.plug_colorSE,n,x=b.plug_colorSE[n],w.apl_plug_colorSE)&&(E.plugFaceSE[n].style.fill=x,O=!0,(se||ue||le)&&!b.line_colorTra&&Ae(E,le?E.lineMaskCaps:E.capsMaskLine)),["markerWidth","markerHeight"].forEach(function(e){var t="plug_"+e+"SE";We(E,k[t],n,x=b[t][n],w["apl_"+t])&&(E.plugMarkerSE[n][e].baseVal.value=x,O=!0)}),We(E,k.plugOutline_enabledSE,n,x=b.plugOutline_enabledSE[n],w.apl_plugOutline_enabledSE)&&(x?(E.plugFaceSE[n].style.mask="url(#"+E.plugMaskIdSE[n]+")",E.plugOutlineFaceSE[n].style.display="inline"):(E.plugFaceSE[n].style.mask="none",E.plugOutlineFaceSE[n].style.display="none"),O=!0),b.plugOutline_enabledSE[n]&&(We(E,k.plugOutline_plugSE,n,e,w.apl_plugOutline_plugSE)&&(E.plugOutlineFaceSE[n].href.baseVal=E.plugMaskShapeSE[n].href.baseVal=E.plugOutlineMaskShapeSE[n].href.baseVal="#"+t.elmId,[E.plugMaskSE[n],E.plugOutlineMaskSE[n]].forEach(function(e){e.x.baseVal.value=t.bBox.left,e.y.baseVal.value=t.bBox.top,e.width.baseVal.value=t.bBox.width,e.height.baseVal.value=t.bBox.height}),O=!0),We(E,k.plugOutline_colorSE,n,x=b.plugOutline_colorSE[n],w.apl_plugOutline_colorSE)&&(E.plugOutlineFaceSE[n].style.fill=x,O=!0,le&&(Ae(E,E.lineMaskCaps),Ae(E,E.lineOutlineMaskCaps))),We(E,k.plugOutline_strokeWidthSE,n,x=b.plugOutline_strokeWidthSE[n],w.apl_plugOutline_strokeWidthSE)&&(E.plugOutlineMaskShapeSE[n].style.strokeWidth=x+"px",O=!0),We(E,k.plugOutline_inStrokeWidthSE,n,x=b.plugOutline_inStrokeWidthSE[n],w.apl_plugOutline_inStrokeWidthSE)&&(E.plugMaskShapeSE[n].style.strokeWidth=x+"px",O=!0)))}),O)),(t.position||ee.line||ee.plug)&&(ee.position=Fe(e)),(t.path||ee.position)&&(ee.path=(C=(M=e).curStats,L=M.aplStats,A=M.pathList.animVal||M.pathList.baseVal,V=C.path_edge,P=!1,A&&(V.x1=V.x2=A[0][0].x,V.y1=V.y2=A[0][0].y,C.path_pathData=I=we(A,function(e){e.xV.x2&&(V.x2=e.x),e.y>V.y2&&(V.y2=e.y)}),Me(I,L.path_pathData)&&(M.linePath.setPathData(I),L.path_pathData=I,P=!0,le?(Ae(M,M.plugsFace),Ae(M,M.lineMaskCaps)):re&&Ae(M,M.linePath),M.events.apl_path&&M.events.apl_path.forEach(function(e){e(M,I)}))),P)),ee.viewBox=(B=(N=e).curStats,R=N.aplStats,F=B.path_edge,G=B.viewBox_bBox,D=R.viewBox_bBox,z=N.svg.viewBox.baseVal,j=N.svg.style,H=!1,T=Math.max(B.line_strokeWidth/2,B.viewBox_plugBCircleSE[0]||0,B.viewBox_plugBCircleSE[1]||0),W={x1:F.x1-T,y1:F.y1-T,x2:F.x2+T,y2:F.y2+T},N.events.new_edge4viewBox&&N.events.new_edge4viewBox.forEach(function(e){e(N,W)}),G.x=B.lineMask_x=B.lineOutlineMask_x=B.maskBGRect_x=W.x1,G.y=B.lineMask_y=B.lineOutlineMask_y=B.maskBGRect_y=W.y1,G.width=W.x2-W.x1,G.height=W.y2-W.y1,["x","y","width","height"].forEach(function(e){var t;(t=G[e])!==D[e]&&(z[e]=D[e]=t,j[oe[e]]=t+("x"===e||"y"===e?N.bodyOffset[e]:0)+"px",H=!0)}),H),ee.mask=(Y=(U=e).curStats,X=U.aplStats,q=!1,Y.plug_enabled?[0,1].forEach(function(e){Y.capsMaskMarker_enabledSE[e]=Y.plug_enabledSE[e]&&Y.plug_colorTraSE[e]||Y.plugOutline_enabledSE[e]&&Y.plugOutline_colorTraSE[e]}):Y.capsMaskMarker_enabledSE[0]=Y.capsMaskMarker_enabledSE[1]=!1,Y.capsMaskMarker_enabled=Y.capsMaskMarker_enabledSE[0]||Y.capsMaskMarker_enabledSE[1],Y.lineMask_outlineMode=Y.lineOutline_enabled,Y.caps_enabled=Y.capsMaskMarker_enabled||Y.capsMaskAnchor_enabledSE[0]||Y.capsMaskAnchor_enabledSE[1],Y.lineMask_enabled=Y.caps_enabled||Y.lineMask_outlineMode,(Y.lineMask_enabled&&!Y.lineMask_outlineMode||Y.lineOutline_enabled)&&["x","y"].forEach(function(e){var t="maskBGRect_"+e;We(U,X,t,Z=Y[t])&&(U.maskBGRect[e].baseVal.value=Z,q=!0)}),We(U,X,"lineMask_enabled",Z=Y.lineMask_enabled)&&(U.lineFace.style.mask=Z?"url(#"+U.lineMaskId+")":"none",q=!0,ue&&Ae(U,U.lineMask)),Y.lineMask_enabled&&(We(U,X,"lineMask_outlineMode",Z=Y.lineMask_outlineMode)&&(Z?(U.lineMaskBG.style.display="none",U.lineMaskShape.style.display="inline"):(U.lineMaskBG.style.display="inline",U.lineMaskShape.style.display="none"),q=!0),["x","y"].forEach(function(e){var t="lineMask_"+e;We(U,X,t,Z=Y[t])&&(U.lineMask[e].baseVal.value=Z,q=!0)}),We(U,X,"caps_enabled",Z=Y.caps_enabled)&&(U.lineMaskCaps.style.display=U.lineOutlineMaskCaps.style.display=Z?"inline":"none",q=!0,ue&&Ae(U,U.capsMaskLine)),Y.caps_enabled&&([0,1].forEach(function(e){var t;We(U,X.capsMaskAnchor_enabledSE,e,Z=Y.capsMaskAnchor_enabledSE[e])&&(U.capsMaskAnchorSE[e].style.display=Z?"inline":"none",q=!0,ue&&Ae(U,U.lineMask)),Y.capsMaskAnchor_enabledSE[e]&&(Me(t=Y.capsMaskAnchor_pathDataSE[e],X.capsMaskAnchor_pathDataSE[e])&&(U.capsMaskAnchorSE[e].setPathData(t),X.capsMaskAnchor_pathDataSE[e]=t,q=!0),We(U,X.capsMaskAnchor_strokeWidthSE,e,Z=Y.capsMaskAnchor_strokeWidthSE[e])&&(U.capsMaskAnchorSE[e].style.strokeWidth=Z+"px",q=!0))}),We(U,X,"capsMaskMarker_enabled",Z=Y.capsMaskMarker_enabled)&&(U.capsMaskLine.style.display=Z?"inline":"none",q=!0),Y.capsMaskMarker_enabled&&[0,1].forEach(function(n){var e=Y.capsMaskMarker_plugSE[n],t=e!==ne?ae[ie[e]]:null,a=Ne(n,t);We(U,X.capsMaskMarker_enabledSE,n,Z=Y.capsMaskMarker_enabledSE[n])&&(U.capsMaskLine.style[a.prop]=Z?"url(#"+U.lineMaskMarkerIdSE[n]+")":"none",q=!0),Y.capsMaskMarker_enabledSE[n]&&(We(U,X.capsMaskMarker_plugSE,n,e)&&(U.capsMaskMarkerShapeSE[n].href.baseVal="#"+t.elmId,Pe(U,U.capsMaskMarkerSE[n],a.orient,t.bBox,U.svg,U.capsMaskMarkerShapeSE[n],U.capsMaskLine),q=!0,re&&(Ae(U,U.capsMaskLine),Ae(U,U.lineFace))),["markerWidth","markerHeight"].forEach(function(e){var t="capsMaskMarker_"+e+"SE";We(U,X[t],n,Z=Y[t][n])&&(U.capsMaskMarkerSE[n][e].baseVal.value=Z,q=!0)}))}))),Y.lineOutline_enabled&&["x","y"].forEach(function(e){var t="lineOutlineMask_"+e;We(U,X,t,Z=Y[t])&&(U.lineOutlineMask[e].baseVal.value=Z,q=!0)}),q),t.effect&&(J=(Q=e).curStats,$=Q.aplStats,Object.keys(te).forEach(function(e){var t=te[e],n=e+"_enabled",a=e+"_options",i=J[a];We(Q,$,n,K=J[n])?(K&&($[a]=de(i)),t[K?"init":"remove"](Q)):K&&ce(i,$[a])&&(t.remove(Q),$[n]=!0,$[a]=de(i),t.init(Q))})),(se||ue)&&ee.line&&!ee.path&&Ae(e,e.lineShape),se&&ee.plug&&!ee.line&&Ae(e,e.plugsFace),Ve(e)}function ze(e,t){return{duration:w(e.duration)&&0i.x2&&(i.x2=t.x2),t.y2>i.y2&&(i.y2=t.y2),["x","y"].forEach(function(e){var t,n="dropShadow_"+e;o[n]=t=i[e+"1"],We(a,l,n,t)&&(a.efc_dropShadow_elmFilter[e].baseVal.value=t)}))}}},Object.keys(te).forEach(function(e){var t=te[e],n=t.stats;n[e+"_enabled"]={iniValue:!1},n[e+"_options"]={hasProps:!0},t.anim&&(n[e+"_animOptions"]={},n[e+"_animId"]={})}),g={none:{defaultAnimOptions:{},init:function(e,t){var n=e.curStats;n.show_animId&&(c.remove(n.show_animId),n.show_animId=null),g.none.start(e,t)},start:function(e,t){g.none.stop(e,!0)},stop:function(e,t,n){var a=e.curStats;return n=null!=n?n:e.aplStats.show_on,a.show_inAnim=!1,t&&Ge(e,n),n?1:0}},fade:{defaultAnimOptions:{duration:300,timing:"linear"},init:function(n,e){var t=n.curStats,a=n.aplStats;t.show_animId&&c.remove(t.show_animId),t.show_animId=c.add(function(e){return e},function(e,t){t?g.fade.stop(n,!0):(n.svg.style.opacity=e+"",le&&(Ae(n,n.svg),Ve(n)))},a.show_animOptions.duration,1,a.show_animOptions.timing,null,!1),g.fade.start(n,e)},start:function(e,t){var n,a=e.curStats;a.show_inAnim&&(n=c.stop(a.show_animId)),Ge(e,1),a.show_inAnim=!0,c.start(a.show_animId,!e.aplStats.show_on,null!=t?t:n)},stop:function(e,t,n){var a,i=e.curStats;return n=null!=n?n:e.aplStats.show_on,a=i.show_inAnim?c.stop(i.show_animId):n?1:0,i.show_inAnim=!1,t&&(e.svg.style.opacity=n?"":"0",Ge(e,n)),a}},draw:{defaultAnimOptions:{duration:500,timing:[.58,0,.42,1]},init:function(n,e){var t=n.curStats,a=n.aplStats,l=n.pathList.baseVal,i=Oe(l),r=i.segsLen,s=i.lenAll;t.show_animId&&c.remove(t.show_animId),t.show_animId=c.add(function(e){var t,n,a,i,o=-1;if(0===e)n=[[l[0][0],l[0][0]]];else if(1===e)n=l;else{for(t=s*e,n=[];t>=r[++o];)n.push(l[o]),t-=r[o];t&&(2===(a=l[o]).length?n.push([a[0],ve(a[0],a[1],t/r[o])]):(i=xe(a[0],a[1],a[2],a[3],ke(a[0],a[1],a[2],a[3],t)),n.push([a[0],i.fromP1,i.fromP2,i])))}return n},function(e,t){t?g.draw.stop(n,!0):(n.pathList.animVal=e,De(n,{path:!0}))},a.show_animOptions.duration,1,a.show_animOptions.timing,null,!1),g.draw.start(n,e)},start:function(e,t){var n,a=e.curStats;a.show_inAnim&&(n=c.stop(a.show_animId)),Ge(e,1),a.show_inAnim=!0,Ie(e,"apl_position",g.draw.update),c.start(a.show_animId,!e.aplStats.show_on,null!=t?t:n)},stop:function(e,t,n){var a,i=e.curStats;return n=null!=n?n:e.aplStats.show_on,a=i.show_inAnim?c.stop(i.show_animId):n?1:0,i.show_inAnim=!1,t&&(e.pathList.animVal=n?null:[[e.pathList.baseVal[0][0],e.pathList.baseVal[0][0]]],De(e,{path:!0}),Ge(e,n)),a},update:function(e){Ce(e,"apl_position",g.draw.update),e.curStats.show_inAnim?g.draw.init(e,g.draw.stop(e)):e.aplStats.show_animOptions={}}}},function(){function r(n){return function(e){var t={};t[n]=e,this.setOptions(t)}}[["start","anchorSE",0],["end","anchorSE",1],["color","lineColor"],["size","lineSize"],["startSocketGravity","socketGravitySE",0],["endSocketGravity","socketGravitySE",1],["startPlugColor","plugColorSE",0],["endPlugColor","plugColorSE",1],["startPlugSize","plugSizeSE",0],["endPlugSize","plugSizeSE",1],["outline","lineOutlineEnabled"],["outlineColor","lineOutlineColor"],["outlineSize","lineOutlineSize"],["startPlugOutline","plugOutlineEnabledSE",0],["endPlugOutline","plugOutlineEnabledSE",1],["startPlugOutlineColor","plugOutlineColorSE",0],["endPlugOutlineColor","plugOutlineColorSE",1],["startPlugOutlineSize","plugOutlineSizeSE",0],["endPlugOutlineSize","plugOutlineSizeSE",1]].forEach(function(e){var t=e[0],n=e[1],a=e[2];Object.defineProperty(Ye.prototype,t,{get:function(){var e=null!=a?K[this._id].options[n][a]:n?K[this._id].options[n]:K[this._id].options[t];return null==e?x:de(e)},set:r(t),enumerable:!0})}),[["path",m],["startSocket",n,"socketSE",0],["endSocket",n,"socketSE",1],["startPlug",E,"plugSE",0],["endPlug",E,"plugSE",1]].forEach(function(e){var a=e[0],i=e[1],o=e[2],l=e[3];Object.defineProperty(Ye.prototype,a,{get:function(){var t,n=null!=l?K[this._id].options[o][l]:o?K[this._id].options[o]:K[this._id].options[a];return n?Object.keys(i).some(function(e){return i[e]===n&&(t=e,!0)})?t:new Error("It's broken"):x},set:r(a),enumerable:!0})}),Object.keys(te).forEach(function(n){var a=te[n];Object.defineProperty(Ye.prototype,n,{get:function(){var u,e,t=K[this._id].options[n];return k(t)?(u=t,e=a.optionsConf.reduce(function(e,t){var n,a=t[0],i=t[1],o=t[2],l=t[3],r=t[4],s=null!=r?u[l][r]:l?u[l]:u[i];return e[i]="id"===a?s?Object.keys(o).some(function(e){return o[e]===s&&(n=e,!0)})?n:new Error("It's broken"):x:null==s?x:de(s),e},{}),a.anim&&(e.animation=de(u.animation)),e):t},set:r(n),enumerable:!0})}),["startLabel","endLabel","middleLabel"].forEach(function(e,n){Object.defineProperty(Ye.prototype,e,{get:function(){var e=K[this._id],t=e.options;return t.labelSEM[n]&&!e.optionIsAttach.labelSEM[n]?$[t.labelSEM[n]._id].text:t.labelSEM[n]||""},set:r(e),enumerable:!0})})}(),Ye.prototype.setOptions=function(e){return Ze(K[this._id],e),this},Ye.prototype.position=function(){return De(K[this._id],{position:!0}),this},Ye.prototype.remove=function(){var t=K[this._id],n=t.curStats;Object.keys(te).forEach(function(e){var t=e+"_animId";n[t]&&c.remove(n[t])}),n.show_animId&&c.remove(n.show_animId),t.attachments.slice().forEach(function(e){Ue(t,e)}),t.baseWindow&&t.svg&&t.baseWindow.document.body.removeChild(t.svg),delete K[this._id]},Ye.prototype.show=function(e,t){return je(K[this._id],!0,e,t),this},Ye.prototype.hide=function(e,t){return je(K[this._id],!1,e,t),this},o=function(t){t&&$[t._id]&&(t.boundTargets.slice().forEach(function(e){Ue(e.props,t,!0)}),t.conf.remove&&t.conf.remove(t),delete $[t._id])},S=function(){function e(e,t){var n,a={conf:e,curStats:{},aplStats:{},boundTargets:[]},i={};e.argOptions.every(function(e){return!(!t.length||("string"==typeof e.type?typeof t[0]!==e.type:"function"!=typeof e.type||!e.type(t[0])))&&(i[e.optionName]=t.shift(),!0)}),n=t.length&&k(t[0])?de(t[0]):{},Object.keys(i).forEach(function(e){n[e]=i[e]}),e.stats&&(Te(a.curStats,e.stats),Te(a.aplStats,e.stats)),Object.defineProperty(this,"_id",{value:++ee}),Object.defineProperty(this,"isRemoved",{get:function(){return!$[this._id]}}),a._id=this._id,e.init&&!e.init(a,n)||($[this._id]=a)}return e.prototype.remove=function(){var t=this,n=$[t._id];n&&(n.boundTargets.slice().forEach(function(e){n.conf.removeOption(n,e)}),Le(function(){var e=$[t._id];e&&(console.error("LeaderLineAttachment was not removed by removeOption"),o(e))}))},e}(),window.LeaderLineAttachment=S,_=function(e,t){return e instanceof S&&(!(e.isRemoved||t&&$[e._id].conf.type!==t)||null)},y={pointAnchor:{type:"anchor",argOptions:[{optionName:"element",type:ye}],init:function(e,t){return e.element=y.pointAnchor.checkElement(t.element),e.x=y.pointAnchor.parsePercent(t.x,!0)||[.5,!0],e.y=y.pointAnchor.parsePercent(t.y,!0)||[.5,!0],!0},removeOption:function(e,t){var n=t.props,a={},i=e.element,o=n.options.anchorSE["start"===t.optionName?1:0];i===o&&(i=o===document.body?new S(y.pointAnchor,[i]):document.body),a[t.optionName]=i,Ze(n,a)},getBBoxNest:function(e,t){var n=ge(e.element,t.baseWindow),a=n.width,i=n.height;return n.width=n.height=0,n.left=n.right=n.left+e.x[0]*(e.x[1]?a:1),n.top=n.bottom=n.top+e.y[0]*(e.y[1]?i:1),n},parsePercent:function(e,t){var n,a,i=!1;return w(e)?a=e:"string"==typeof e&&(n=u.exec(e))&&n[2]&&(i=0!==(a=parseFloat(n[1])/100)),null!=a&&(t||0<=a)?[a,i]:null},checkElement:function(e){if(null==e)e=document.body;else if(!ye(e))throw new Error("`element` must be Element");return e}},areaAnchor:{type:"anchor",argOptions:[{optionName:"element",type:ye},{optionName:"shape",type:"string"}],stats:{color:{},strokeWidth:{},elementWidth:{},elementHeight:{},elementLeft:{},elementTop:{},pathListRel:{},bBoxRel:{},pathData:{},viewBoxBBox:{hasProps:!0},dashLen:{},dashGap:{}},init:function(i,e){var t,n,a,o=[];return i.element=y.pointAnchor.checkElement(e.element),"string"==typeof e.color&&(i.color=e.color.trim()),"string"==typeof e.fillColor&&(i.fill=e.fillColor.trim()),w(e.size)&&0<=e.size&&(i.size=e.size),e.dash&&(i.dash=!0,w(e.dash.len)&&0i.right&&(i.right=t),ni.bottom&&(i.bottom=n)):i={left:t,right:t,top:n,bottom:n},o?P.pathListRel.push([o,{x:t,y:n}]):P.pathListRel=[],o={x:t,y:n}}),P.pathListRel.push([]),e=P.strokeWidth/2,l=[{x:i.left-e,y:i.top-e},{x:i.right+e,y:i.bottom+e}],P.bBoxRel={left:l[0].x,top:l[0].y,right:l[1].x,bottom:l[1].y,width:l[1].x-l[0].x,height:l[1].y-l[0].y}}W.pathListRel=W.bBoxRel=!0}return(W.pathListRel||W.elementLeft||W.elementTop)&&(P.pathData=we(P.pathListRel,function(e){e.x+=a.left,e.y+=a.top})),We(t,N,"strokeWidth",n=P.strokeWidth)&&(t.path.style.strokeWidth=n+"px"),Me(n=P.pathData,N.pathData)&&(t.path.setPathData(n),N.pathData=n,W.pathData=!0),t.dash&&(!W.pathData&&(!W.strokeWidth||t.dashLen&&t.dashGap)||(P.dashLen=t.dashLen||2*P.strokeWidth,P.dashGap=t.dashGap||P.strokeWidth),W.dash=We(t,N,"dashLen",P.dashLen)||W.dash,W.dash=We(t,N,"dashGap",P.dashGap)||W.dash,W.dash&&(t.path.style.strokeDasharray=N.dashLen+","+N.dashGap)),C=P.viewBoxBBox,L=N.viewBoxBBox,A=t.svg.viewBox.baseVal,V=t.svg.style,C.x=P.bBoxRel.left+a.left,C.y=P.bBoxRel.top+a.top,C.width=P.bBoxRel.width,C.height=P.bBoxRel.height,["x","y","width","height"].forEach(function(e){(n=C[e])!==L[e]&&(A[e]=L[e]=n,V[oe[e]]=n+("x"===e||"y"===e?t.bodyOffset[e]:0)+"px")}),W.strokeWidth||W.pathListRel||W.bBoxRel}},mouseHoverAnchor:{type:"anchor",argOptions:[{optionName:"element",type:ye},{optionName:"showEffectName",type:"string"}],style:{backgroundImage:"url('data:image/svg+xml;charset=utf-8;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0Ij48cG9seWdvbiBwb2ludHM9IjI0LDAgMCw4IDgsMTEgMCwxOSA1LDI0IDEzLDE2IDE2LDI0IiBmaWxsPSJjb3JhbCIvPjwvc3ZnPg==')",backgroundSize:"",backgroundRepeat:"no-repeat",backgroundColor:"#f8f881",cursor:"default"},hoverStyle:{backgroundImage:"none",backgroundColor:"#fadf8f"},padding:{top:1,right:15,bottom:1,left:2},minHeight:15,backgroundPosition:{right:2,top:2},backgroundSize:{width:12,height:12},dirKeys:[["top","Top"],["right","Right"],["bottom","Bottom"],["left","Left"]],init:function(a,i){var o,t,e,n,l,r,s,u,h,p,c,d=y.mouseHoverAnchor,f={};if(a.element=y.pointAnchor.checkElement(i.element),u=a.element,!((p=u.ownerDocument)&&(h=p.defaultView)&&h.HTMLElement&&u instanceof h.HTMLElement))throw new Error("`element` must be HTML element");return d.style.backgroundSize=d.backgroundSize.width+"px "+d.backgroundSize.height+"px",["style","hoverStyle"].forEach(function(e){var n=d[e];a[e]=Object.keys(n).reduce(function(e,t){return e[t]=n[t],e},{})}),"inline"===(o=a.element.ownerDocument.defaultView.getComputedStyle(a.element,"")).display?a.style.display="inline-block":"none"===o.display&&(a.style.display="block"),y.mouseHoverAnchor.dirKeys.forEach(function(e){var t=e[0],n="padding"+e[1];parseFloat(o[n])e.x2&&(e.x2=a.x2),a.y2>e.y2&&(e.y2=a.y2)},newText:function(e,t,n,a,i){var o,l,r,s,u,h;return(o=t.createElementNS(b,"text")).textContent=e,[o.x,o.y].forEach(function(e){var t=n.createSVGLength();t.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX,0),e.baseVal.initialize(t)}),"boolean"!=typeof f&&(f="paintOrder"in o.style),i&&!f?(r=t.createElementNS(b,"defs"),o.id=a,r.appendChild(o),(u=(l=t.createElementNS(b,"g")).appendChild(t.createElementNS(b,"use"))).href.baseVal="#"+a,(s=l.appendChild(t.createElementNS(b,"use"))).href.baseVal="#"+a,(h=u.style).strokeLinejoin="round",{elmPosition:o,styleText:o.style,styleFill:s.style,styleStroke:h,styleShow:l.style,elmsAppend:[r,l]}):(h=o.style,i&&(h.strokeLinejoin="round",h.paintOrder="stroke"),{elmPosition:o,styleText:h,styleFill:h,styleStroke:i?h:null,styleShow:h,elmsAppend:[o]})},getMidPoint:function(e,t){var n,a,i,o=Oe(e),l=o.segsLen,r=o.lenAll,s=-1;if((n=r/2+(t||0))<=0)return 2===(a=e[0]).length?ve(a[0],a[1],0):xe(a[0],a[1],a[2],a[3],0);if(r<=n)return 2===(a=e[e.length-1]).length?ve(a[0],a[1],1):xe(a[0],a[1],a[2],a[3],1);for(i=[];n>l[++s];)i.push(e[s]),n-=l[s];return 2===(a=e[s]).length?ve(a[0],a[1],n/l[s]):xe(a[0],a[1],a[2],a[3],ke(a[0],a[1],a[2],a[3],n))},initSvg:function(t,n){var e,a,i=y.captionLabel.newText(t.text,n.baseWindow.document,n.svg,v+"-captionLabel-"+t._id,t.outlineColor);["elmPosition","styleFill","styleShow","elmsAppend"].forEach(function(e){t[e]=i[e]}),t.isShown=!1,t.styleShow.visibility="hidden",y.captionLabel.textStyleProps.forEach(function(e){null!=t[e]&&(i.styleText[e]=t[e])}),i.elmsAppend.forEach(function(e){n.svg.appendChild(e)}),e=i.elmPosition.getBBox(),t.width=e.width,t.height=e.height,t.outlineColor&&(a=10<(a=e.height/9)?10:a<2?2:a,i.styleStroke.strokeWidth=a+"px",i.styleStroke.stroke=t.outlineColor),t.strokeWidth=a||0,Te(t.aplStats,y.captionLabel.stats),t.updateColor(n),t.refSocketXY?t.updateSocketXY(n):t.updatePath(n),ue&&De(n,{}),t.updateShow(n)},bind:function(e,t){var n=t.props;return e.color||Ie(n,"cur_line_color",e.updateColor),(e.refSocketXY="startLabel"===t.optionName||"endLabel"===t.optionName)?(e.socketIndex="startLabel"===t.optionName?0:1,Ie(n,"apl_position",e.updateSocketXY),e.offset||(Ie(n,"cur_attach_plugSideLenSE",e.updateSocketXY),Ie(n,"cur_line_strokeWidth",e.updateSocketXY))):Ie(n,"apl_path",e.updatePath),Ie(n,"svgShow",e.updateShow),ue&&Ie(n,"new_edge4viewBox",e.adjustEdge),y.captionLabel.initSvg(e,n),!0},unbind:function(e,t){var n=t.props;e.elmsAppend&&(e.elmsAppend.forEach(function(e){n.svg.removeChild(e)}),e.elmPosition=e.styleFill=e.styleShow=e.elmsAppend=null),Te(e.curStats,y.captionLabel.stats),Te(e.aplStats,y.captionLabel.stats),e.color||Ce(n,"cur_line_color",e.updateColor),e.refSocketXY?(Ce(n,"apl_position",e.updateSocketXY),e.offset||(Ce(n,"cur_attach_plugSideLenSE",e.updateSocketXY),Ce(n,"cur_line_strokeWidth",e.updateSocketXY))):Ce(n,"apl_path",e.updatePath),Ce(n,"svgShow",e.updateShow),ue&&(Ce(n,"new_edge4viewBox",e.adjustEdge),De(n,{}))},removeOption:function(e,t){var n=t.props,a={};a[t.optionName]="",Ze(n,a)},remove:function(t){t.boundTargets.length&&(console.error("LeaderLineAttachment was not unbound by remove"),t.boundTargets.forEach(function(e){y.captionLabel.unbind(t,e)}))}},pathLabel:{type:"label",argOptions:[{optionName:"text",type:"string"}],stats:{color:{},startOffset:{},pathData:{}},init:function(s,t){return"string"==typeof t.text&&(s.text=t.text.trim()),!!s.text&&("string"==typeof t.color&&(s.color=t.color.trim()),s.outlineColor="string"==typeof t.outlineColor?t.outlineColor.trim():"#fff",w(t.lineOffset)&&(s.lineOffset=t.lineOffset),y.captionLabel.textStyleProps.forEach(function(e){null!=t[e]&&(s[e]=t[e])}),s.updateColor=function(e){y.captionLabel.updateColor(s,e)},s.updatePath=function(e){var t,n=s.curStats,a=s.aplStats,i=e.curStats,o=e.pathList.animVal||e.pathList.baseVal;o&&(n.pathData=t=y.pathLabel.getOffsetPathData(o,i.line_strokeWidth/2+s.strokeWidth/2+s.height/4,1.25*s.height),Me(t,a.pathData)&&(s.elmPath.setPathData(t),a.pathData=t,s.bBox=s.elmPosition.getBBox(),s.updateStartOffset(e)))},s.updateStartOffset=function(e){var t,n,a,i,o=s.curStats,l=s.aplStats,r=e.curStats;o.pathData&&((2!==s.semIndex||s.lineOffset)&&(t=o.pathData.reduce(function(e,t){var n,a=t.values;switch(t.type){case"M":i={x:a[0],y:a[1]};break;case"L":n={x:a[0],y:a[1]},i&&(e+=_e(i,n)),i=n;break;case"C":n={x:a[4],y:a[5]},i&&(e+=be(i,{x:a[0],y:a[1]},{x:a[2],y:a[3]},n)),i=n}return e},0),a=0===s.semIndex?0:1===s.semIndex?t:t/2,2!==s.semIndex&&(n=Math.max(r.attach_plugBackLenSE[s.semIndex]||0,r.line_strokeWidth/2)+s.strokeWidth/2+s.height/4,a=(a+=0===s.semIndex?n:-n)<0?0:tx?((t=b.points)[1]=Ee(t[0],t[1],-x),b.len=_e(t[0],t[1])):(b.points=null,b.len=0),e.len>x+n?((t=e.points)[0]=Ee(t[1],t[0],-(x+n)),e.len=_e(t[0],t[1])):(e.points=null,e.len=0)),b=e):b=null}),k.reduce(function(t,e){var n=e.points;return n&&(a&&w(n[0],a)||t.push({type:"M",values:[n[0].x,n[0].y]}),"line"===e.type?t.push({type:"L",values:[n[1].x,n[1].y]}):(n.shift(),n.forEach(function(e){t.push({type:"L",values:[e.x,e.y]})})),a=n[n.length-1]),t},[])},newText:function(e,t,n,a){var i,o,l,r,s,u,h,p,c,d;return(r=(l=t.createElementNS(b,"defs")).appendChild(t.createElementNS(b,"path"))).id=i=n+"-path",(u=(s=t.createElementNS(b,"text")).appendChild(t.createElementNS(b,"textPath"))).href.baseVal="#"+i,u.startOffset.baseVal.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX,0),u.textContent=e,"boolean"!=typeof f&&(f="paintOrder"in s.style),a&&!f?(s.id=o=n+"-text",l.appendChild(s),(c=(h=t.createElementNS(b,"g")).appendChild(t.createElementNS(b,"use"))).href.baseVal="#"+o,(p=h.appendChild(t.createElementNS(b,"use"))).href.baseVal="#"+o,(d=c.style).strokeLinejoin="round",{elmPosition:s,elmPath:r,elmOffset:u,styleText:s.style,styleFill:p.style,styleStroke:d,styleShow:h.style,elmsAppend:[l,h]}):(d=s.style,a&&(d.strokeLinejoin="round",d.paintOrder="stroke"),{elmPosition:s,elmPath:r,elmOffset:u,styleText:d,styleFill:d,styleStroke:a?d:null,styleShow:d,elmsAppend:[l,s]})},initSvg:function(t,n){var e,a,i=y.pathLabel.newText(t.text,n.baseWindow.document,v+"-pathLabel-"+t._id,t.outlineColor);["elmPosition","elmPath","elmOffset","styleFill","styleShow","elmsAppend"].forEach(function(e){t[e]=i[e]}),t.isShown=!1,t.styleShow.visibility="hidden",y.captionLabel.textStyleProps.forEach(function(e){null!=t[e]&&(i.styleText[e]=t[e])}),i.elmsAppend.forEach(function(e){n.svg.appendChild(e)}),i.elmPath.setPathData([{type:"M",values:[0,100]},{type:"h",values:[100]}]),e=i.elmPosition.getBBox(),i.styleText.textAnchor=["start","end","middle"][t.semIndex],2!==t.semIndex||t.lineOffset||i.elmOffset.startOffset.baseVal.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PERCENTAGE,50),t.height=e.height,t.outlineColor&&(a=10<(a=e.height/9)?10:a<2?2:a,i.styleStroke.strokeWidth=a+"px",i.styleStroke.stroke=t.outlineColor),t.strokeWidth=a||0,Te(t.aplStats,y.pathLabel.stats),t.updateColor(n),t.updatePath(n),t.updateStartOffset(n),ue&&De(n,{}),t.updateShow(n)},bind:function(e,t){var n=t.props;return e.color||Ie(n,"cur_line_color",e.updateColor),Ie(n,"cur_line_strokeWidth",e.updatePath),Ie(n,"apl_path",e.updatePath),e.semIndex="startLabel"===t.optionName?0:"endLabel"===t.optionName?1:2,(2!==e.semIndex||e.lineOffset)&&Ie(n,"cur_attach_plugBackLenSE",e.updateStartOffset),Ie(n,"svgShow",e.updateShow),ue&&Ie(n,"new_edge4viewBox",e.adjustEdge),y.pathLabel.initSvg(e,n),!0},unbind:function(e,t){var n=t.props;e.elmsAppend&&(e.elmsAppend.forEach(function(e){n.svg.removeChild(e)}),e.elmPosition=e.elmPath=e.elmOffset=e.styleFill=e.styleShow=e.elmsAppend=null),Te(e.curStats,y.pathLabel.stats),Te(e.aplStats,y.pathLabel.stats),e.color||Ce(n,"cur_line_color",e.updateColor),Ce(n,"cur_line_strokeWidth",e.updatePath),Ce(n,"apl_path",e.updatePath),(2!==e.semIndex||e.lineOffset)&&Ce(n,"cur_attach_plugBackLenSE",e.updateStartOffset),Ce(n,"svgShow",e.updateShow),ue&&(Ce(n,"new_edge4viewBox",e.adjustEdge),De(n,{}))},removeOption:function(e,t){var n=t.props,a={};a[t.optionName]="",Ze(n,a)},remove:function(t){t.boundTargets.length&&(console.error("LeaderLineAttachment was not unbound by remove"),t.boundTargets.forEach(function(e){y.pathLabel.unbind(t,e)}))}}},Object.keys(y).forEach(function(e){Ye[e]=function(){return new S(y[e],Array.prototype.slice.call(arguments))}}),Ye.positionByWindowResize=!0,window.addEventListener("resize",O.add(function(){Ye.positionByWindowResize&&Object.keys(K).forEach(function(e){De(K[e],{position:!0})})}),!1),Ye}(); -// https://anseki.github.io/plain-overlay/ -/*! PlainOverlay v1.4.14 (c) anseki https://anseki.github.io/plain-overlay/ */ -var PlainOverlay=function(e){var t={};function n(o){if(t[o])return t[o].exports;var i=t[o]={i:o,l:!1,exports:{}};return e[o].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,o){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:o})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var o=Object.create(null);if(n.r(o),Object.defineProperty(o,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(o,i,function(t){return e[t]}.bind(null,i));return o},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t){e.exports=".plainoverlay,.plainoverlay:not(.plainoverlay-hide) .plainoverlay-builtin-face_01{-webkit-tap-highlight-color:rgba(0,0,0,0);transform:translateZ(0);box-shadow:0 0 1px rgba(0,0,0,0)}.plainoverlay{position:absolute;left:0;top:0;overflow:hidden;background-color:rgba(136,136,136,0.6);cursor:wait;z-index:9000;-webkit-transition-property:opacity;-moz-transition-property:opacity;-o-transition-property:opacity;transition-property:opacity;-webkit-transition-duration:200ms;-moz-transition-duration:200ms;-o-transition-duration:200ms;transition-duration:200ms;-webkit-transition-timing-function:linear;-moz-transition-timing-function:linear;-o-transition-timing-function:linear;transition-timing-function:linear;opacity:0}.plainoverlay.plainoverlay-show{opacity:1}.plainoverlay.plainoverlay-force{-webkit-transition-property:none;-moz-transition-property:none;-o-transition-property:none;transition-property:none}.plainoverlay.plainoverlay-hide{display:none}.plainoverlay.plainoverlay-doc{position:fixed;left:-200px;top:-200px;overflow:visible;padding:200px;width:100vw;height:100vh}.plainoverlay-body{width:100%;height:100%;display:-webkit-flex;display:flex;-webkit-justify-content:center;justify-content:center;-webkit-align-items:center;align-items:center}.plainoverlay.plainoverlay-doc .plainoverlay-body{width:100vw;height:100vh}.plainoverlay-builtin-face{width:90%;height:90%;max-width:320px;max-height:320px}#plainoverlay-builtin-face-defs{width:0;height:0;position:fixed;left:-100px;top:-100px}#plainoverlay-builtin-face_01 circle,#plainoverlay-builtin-face_01 path{fill:none;stroke-width:40px}#plainoverlay-builtin-face_01 circle{stroke:#fff;opacity:0.25}#plainoverlay-builtin-face_01 path{stroke-linecap:round}.plainoverlay:not(.plainoverlay-hide) .plainoverlay-builtin-face_01{-webkit-animation-name:plainoverlay-builtin-face_01-spin;-moz-animation-name:plainoverlay-builtin-face_01-spin;-ms-animation-name:plainoverlay-builtin-face_01-spin;-o-animation-name:plainoverlay-builtin-face_01-spin;animation-name:plainoverlay-builtin-face_01-spin;-webkit-animation-duration:1s;-moz-animation-duration:1s;-ms-animation-duration:1s;-o-animation-duration:1s;animation-duration:1s;-webkit-animation-timing-function:linear;-moz-animation-timing-function:linear;-ms-animation-timing-function:linear;-o-animation-timing-function:linear;animation-timing-function:linear;-webkit-animation-iteration-count:infinite;-moz-animation-iteration-count:infinite;-ms-animation-iteration-count:infinite;-o-animation-iteration-count:infinite;animation-iteration-count:infinite}@-moz-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-ms-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}"},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t,n){"use strict";function o(e){return e.substr(0,1).toUpperCase()+e.substr(1)}n.r(t);var i=["webkit","moz","ms","o"],r=i.reduce(function(e,t){return e.push(t),e.push(o(t)),e},[]),a=i.map(function(e){return"-"+e+"-"}),s=function(){var e=void 0;return function(){return e=e||document.createElement("div").style}}(),l=function(){var e=new RegExp("^(?:"+i.join("|")+")(.)","i"),t=/[A-Z]/;return function(n){return"float"===(n=(n+"").replace(/\s/g,"").replace(/-([\da-z])/gi,function(e,t){return t.toUpperCase()}).replace(e,function(e,n){return t.test(n)?n.toLowerCase():e})).toLowerCase()?"cssFloat":n}}(),d=function(){var e=new RegExp("^(?:"+a.join("|")+")","i");return function(t){return(null!=t?t+"":"").replace(/\s/g,"").replace(e,"")}}(),u=function(e,t){var n=s();return e=e.replace(/[A-Z]/g,function(e){return"-"+e.toLowerCase()}),n.setProperty(e,t),null!=n[e]&&n.getPropertyValue(e)===t},c={},f={};function m(e){if((e=l(e))&&null==c[e]){var t=s();if(null!=t[e])c[e]=e;else{var n=o(e);r.some(function(o){var i=o+n;return null!=t[i]&&(c[e]=i,!0)})||(c[e]=!1)}}return c[e]||void 0}var p={getName:m,getValue:function(e,t){var n=void 0;return(e=m(e))?(f[e]=f[e]||{},(Array.isArray(t)?t:[t]).some(function(t){return t=d(t),null!=f[e][t]?!1!==f[e][t]&&(n=f[e][t],!0):u(e,t)?(n=f[e][t]=t,!0):!!a.some(function(o){var i=o+t;return!!u(e,i)&&(n=f[e][t]=i,!0)})||(f[e][t]=!1,!1)}),"string"==typeof n?n:void 0):n}},g=500,y=[],h=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return setTimeout(e,1e3/60)},v=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.msCancelAnimationFrame||function(e){return clearTimeout(e)},w=Date.now(),b=void 0;function T(){var e=void 0,t=void 0;b&&(v.call(window,b),b=null),y.forEach(function(t){var n;(n=t.event)&&(t.event=null,t.listener(n),e=!0)}),e?(w=Date.now(),t=!0):Date.now()-w-1&&(y.splice(t,1),!y.length&&b&&(v.call(window,b),b=null))}};function _(e){return(e+"").trim()}function S(e,t){t.setAttribute("class",e.join(" "))}function B(e){return!B.ignoreNative&&e.classList||function(){var t=(e.getAttribute("class")||"").trim().split(/\s+/).filter(function(e){return!!e}),n={length:t.length,item:function(e){return t[e]},contains:function(e){return-1!==t.indexOf(_(e))},add:function(){return function(e,t,n){n.filter(function(t){return!(!(t=_(t))||-1!==e.indexOf(t)||(e.push(t),0))}).length&&S(e,t)}(t,e,Array.prototype.slice.call(arguments)),B.methodChain?n:void 0},remove:function(){return function(e,t,n){n.filter(function(t){var n=void 0;return!(!(t=_(t))||-1===(n=e.indexOf(t))||(e.splice(n,1),0))}).length&&S(e,t)}(t,e,Array.prototype.slice.call(arguments)),B.methodChain?n:void 0},toggle:function(n,o){return function(e,t,n,o){var i=e.indexOf(n=_(n));return-1!==i?!!o||(e.splice(i,1),S(e,t),!1):!1!==o&&(e.push(n),S(e,t),!0)}(t,e,n,o)},replace:function(o,i){return function(e,t,n,o){var i=void 0;(n=_(n))&&(o=_(o))&&n!==o&&-1!==(i=e.indexOf(n))&&(e.splice(i,1),-1===e.indexOf(o)&&e.push(o),S(e,t))}(t,e,o,i),B.methodChain?n:void 0}};return n}()}B.methodChain=!0;var k=B,D=function(){function e(e,t){for(var n=0;n0?e.timer=setTimeout(function(){K(e)},t):K(e)}}function U(e){clearTimeout(e.timer),e.state!==x&&(e.state=x,j(e,L))}function q(e,t){var n=e.options;function o(n){var o="number"==typeof t[n]?(e.window.getComputedStyle(e.element,"")[p.getName("transition-"+n)]||"").split(",")[t[n]]:t[n];return"string"==typeof o?o.trim():null}"string"==typeof t.pseudoElement&&(n.pseudoElement=t.pseudoElement);var i=o("property");"string"==typeof i&&"all"!==i&&"none"!==i&&(n.property=i),["duration","delay"].forEach(function(t){var i=o(t);if("string"==typeof i){var r=void 0,a=void 0;/^[0.]+$/.test(i)?(n[t]="0s",e[t]=0):(r=/^(.+?)(m)?s$/.exec(i))&&I(a=parseFloat(r[1]))&&("duration"!==t||a>=0)&&(n[t]=""+a+(r[2]||"")+"s",e[t]=a*(r[2]?1:1e3))}}),["procToOn","procToOff"].forEach(function(e){"function"==typeof t[e]?n[e]=t[e]:t.hasOwnProperty(e)&&null==t[e]&&(n[e]=void 0)})}var X=function(){function e(t,n,o){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var i={ins:this,options:{pseudoElement:"",property:""},duration:0,delay:0,isOn:!!o};if(Object.defineProperty(this,"_id",{value:++F}),i._id=this._id,M[this._id]=i,!t.nodeType||t.nodeType!==Node.ELEMENT_NODE)throw new Error("This `element` is not accepted.");i.element=t,n||(n={}),i.window=t.ownerDocument.defaultView||n.window||window,n.hasOwnProperty("property")||(n.property=0),n.hasOwnProperty("duration")||(n.duration=0),n.hasOwnProperty("delay")||(n.delay=0),q(i,n),Y(i)}return D(e,[{key:"remove",value:function(){var e=M[this._id];clearTimeout(e.timer),delete M[this._id]}},{key:"setOptions",value:function(e){return e&&q(M[this._id],e),this}},{key:"on",value:function(e,t){return arguments.length<2&&"boolean"!=typeof e&&(t=e,e=!1),this.setOptions(t),function(e,t,n){e.isOn&&e.state===x||e.isOn&&e.state!==x&&!t||(e.options.procToOn&&(n.unshift(!!t),e.options.procToOn.apply(e.ins,n)),t||!e.isOn&&e.state===N||-e.delay>e.duration?(U(e),e.isOn=!0,Y(e)):(H(e),U(e),e.state=N,e.isOn=!0,e.runTime=Date.now(),e.startTime=0,j(e,C),e.delay>0?e.timer=setTimeout(function(){W(e)},e.delay):(e.delay<0&&(e.currentPosition=Math.min(e.currentPosition-e.delay,e.duration)),W(e))))}(M[this._id],e,Array.prototype.slice.call(arguments,2)),this}},{key:"off",value:function(e,t){return arguments.length<2&&"boolean"!=typeof e&&(t=e,e=!1),this.setOptions(t),function(e,t,n){!e.isOn&&e.state===x||!e.isOn&&e.state!==x&&!t||(e.options.procToOff&&(n.unshift(!!t),e.options.procToOff.apply(e.ins,n)),t||e.isOn&&e.state===N||-e.delay>e.duration?(U(e),e.isOn=!1,Y(e)):(H(e),U(e),e.state=N,e.isOn=!1,e.runTime=Date.now(),e.startTime=0,j(e,C),e.delay>0?e.timer=setTimeout(function(){W(e)},e.delay):(e.delay<0&&(e.currentPosition=Math.max(e.currentPosition+e.delay,0)),W(e))))}(M[this._id],e,Array.prototype.slice.call(arguments,2)),this}},{key:"state",get:function(){return M[this._id].state}},{key:"element",get:function(){return M[this._id].element}},{key:"isReversing",get:function(){return M[this._id].isReversing}},{key:"pseudoElement",get:function(){return M[this._id].options.pseudoElement},set:function(e){q(M[this._id],{pseudoElement:e})}},{key:"property",get:function(){return M[this._id].options.property},set:function(e){q(M[this._id],{property:e})}},{key:"duration",get:function(){return M[this._id].options.duration},set:function(e){q(M[this._id],{duration:e})}},{key:"delay",get:function(){return M[this._id].options.delay},set:function(e){q(M[this._id],{delay:e})}},{key:"procToOn",get:function(){return M[this._id].options.procToOn},set:function(e){q(M[this._id],{procToOn:e})}},{key:"procToOff",get:function(){return M[this._id].options.procToOff},set:function(e){q(M[this._id],{procToOff:e})}}],[{key:"STATE_STOPPED",get:function(){return x}},{key:"STATE_DELAYING",get:function(){return N}},{key:"STATE_PLAYING",get:function(){return P}}]),e}(),G=n(0),V=n.n(G),Z=n(1),$=n.n(Z),J=n(2),Q=n.n(J),ee=function(){function e(e,t){for(var n=0;n0)return!1}return!0}(e.elmOverlayBody,t):!t.containsNode||we&&t.isCollapsed?function(e,t,n){var o=t.ownerDocument.createRange(),i=e.rangeCount;o.selectNodeContents(t);for(var r=0;r=0&&a.compareBoundaryPoints(Range.END_TO_START,o)<=0:a.compareBoundaryPoints(Range.START_TO_START,o)<0&&a.compareBoundaryPoints(Range.END_TO_END,o)>0)return!0}return!1}(t,e.elmTargetBody,!0):t.containsNode(e.elmTargetBody,!0))){try{t.removeAllRanges()}catch(e){}if(e.document.body.focus(),t.rangeCount>0)try{t.removeAllRanges()}catch(e){}return!0}return!1}function Ae(e){var t=e.elmTarget,n=e.elmTargetBody,o=n.getBoundingClientRect(),i=xe(e),r=-i.width,a=-i.height;if(_e(t,{overflow:"hidden"},e.savedStyleTarget),r+=(i=xe(e)).width,a+=i.height,r||a){var s=e.window.getComputedStyle(n,""),l=void 0,d=void 0;if(he||ye){var u=s.writingMode||s["writing-mode"],c=s.direction;r&&(l=function(e,t){var n="rl-tb"===e||"tb-rl"===e||"bt-rl"===e||"rl-bt"===e;return he&&n||ye&&(n||"rtl"===t&&("horizontal-tb"===e||"vertical-rl"===e)||"ltr"===t&&"vertical-rl"===e)}(u,c)?"marginLeft":"marginRight"),a&&(d=function(e,t){var n="bt-rl"===e||"bt-lr"===e||"lr-bt"===e||"rl-bt"===e;return he&&n||ye&&(n||"rtl"===t&&("vertical-lr"===e||"vertical-rl"===e))}(u,c)?"marginTop":"marginBottom")}else r&&(l="marginRight"),a&&(d="marginBottom");var f={};return r&&(f[l]=parseFloat(s[l])+r+"px"),a&&(f[d]=parseFloat(s[d])+a+"px"),_e(n,f,e.savedStyleTargetBody),function(e,t,n){var o=e.elmTargetBody,i=o.getBoundingClientRect();if(!(Math.abs(i.width-t)0?d.width+"px":0,height:d.height>0?d.height+"px":0},e.savedStyleTargetBody);var u={};i=o.getBoundingClientRect(),Math.abs(i.width-t)>=ge&&(u.width=d.width-(i.width-t)+"px"),i.height!==n&&(u.height=d.height-(i.height-n)+"px"),_e(o,u,e.savedStyleTargetBody)}}(e,o.width,o.height),Ne(e,t),!0}return Se(t,e.savedStyleTarget,["overflow"]),!1}function Re(e,t){var n=e.elmTargetBody,o=e.window.getComputedStyle(n,""),i=e.elmOverlay,r=e.window.getComputedStyle(i,""),a=Be(i,e.window),s=["Top","Right","Bottom","Left"].reduce(function(e,t){return e[t.toLowerCase()]=parseFloat(o["border"+t+"Width"]),e},{}),l=a.left-parseFloat(r.left),d=a.top-parseFloat(r.top),u={left:t.left-l+s.left+"px",top:t.top-d+s.top+"px",width:t.width-s.left-s.right+"px",height:t.height-s.top-s.bottom+"px"},c=/^([\d.]+)(px|%)$/;[{prop:"TopLeft",hBorder:"left",vBorder:"top"},{prop:"TopRight",hBorder:"right",vBorder:"top"},{prop:"BottomRight",hBorder:"right",vBorder:"bottom"},{prop:"BottomLeft",hBorder:"left",vBorder:"bottom"}].forEach(function(e){var n=p.getName("border"+e.prop+"Radius"),i=o[n].split(" "),r=i[0],a=i[1]||i[0],l=c.exec(r);r=l?"px"===l[2]?+l[1]:l[1]*t.width/100:0,a=(l=c.exec(a))?"px"===l[2]?+l[1]:l[1]*t.height/100:0,r-=s[e.hBorder],a-=s[e.vBorder],r>0&&a>0&&(u[n]=r+"px "+a+"px")}),_e(i,u),e.targetBodyBBox=t}function Le(e){var t=e.elmTargetBody,n=e.elmOverlay,o=[e.elmTarget];return e.isDoc?(o.push(t),Array.prototype.slice.call(t.childNodes).forEach(function(e){e.nodeType!==Node.ELEMENT_NODE||e===n||k(e).contains(oe)||e.id===de||(o.push(e),Array.prototype.push.apply(o,e.querySelectorAll("*")))})):Array.prototype.push.apply(o,t.querySelectorAll("*")),o}function ze(e){if(e.filterElements=null,!1!==e.options.blur){var t=p.getName("filter"),n=p.getValue("filter","blur("+e.options.blur+"px)");if(n){var o=e.isDoc?Array.prototype.slice.call(e.elmTargetBody.childNodes).filter(function(t){return t.nodeType===Node.ELEMENT_NODE&&t!==e.elmOverlay&&!k(t).contains(oe)&&t.id!==de}).map(function(e){return{element:e,savedStyle:{}}}):[{element:e.elmTargetBody,savedStyle:{}}];o.forEach(function(e){var o={};o[t]=n,_e(e.element,o,e.savedStyle)}),e.filterElements=o}}e.state=fe,e.options.onShow&&e.options.onShow.call(e.ins)}function Ie(e){if(k(e.elmOverlay).add(ae),Se(e.elmTarget,e.savedStyleTarget),Se(e.elmTargetBody,e.savedStyleTargetBody),e.savedStyleTarget={},e.savedStyleTargetBody={},function(e){e.savedElementsAccKeys.forEach(function(e){try{!1===e.tabIndex?e.element.removeAttribute("tabindex"):null!=e.tabIndex&&(e.element.tabIndex=e.tabIndex)}catch(e){}try{e.accessKey&&(e.element.accessKey=e.accessKey)}catch(e){}})}(e),e.savedElementsAccKeys=[],e.isDoc&&e.activeElement){var t=e.state;e.state=ue,e.elmTargetBody.removeEventListener("focus",e.focusListener,!0),e.activeElement.focus(),e.state=t}e.activeElement=null,e.timerRestoreAndFinish&&(clearTimeout(e.timerRestoreAndFinish),e.timerRestoreAndFinish=null),e.timerRestoreAndFinish=setTimeout(function(){e.timerRestoreAndFinish=null,e.state=ue,e.elmTargetBody.addEventListener("focus",e.focusListener,!0),Ne(e),e.savedElementsScroll=null,e.options.onHide&&e.options.onHide.call(e.ins)},0)}function Me(e,t){if(!(e.state===fe||e.state===ce&&!t||e.state!==ce&&e.options.onBeforeShow&&!1===e.options.onBeforeShow.call(e.ins))){if(e.state===ue){var n=e.elmOverlay,o=k(n);e.document.body.appendChild(n);var i=Le(e);if(o.remove(ae),!e.isDoc){var r=e.elmTargetBody;"inline"===e.window.getComputedStyle(r,"").display&&_e(r,{display:"inline-block"},e.savedStyleTargetBody),Re(e,Be(r,e.window))}e.savedElementsScroll=function(t,n){var o=[];return t.forEach(function(t,i){var r=n&&0===i;(function(t,n){var o=e.window.getComputedStyle(t,""),i=t.nodeName.toLowerCase();return"scroll"===o.overflow||"auto"===o.overflow||"scroll"===o.overflowX||"auto"===o.overflowX||"scroll"===o.overflowY||"auto"===o.overflowY||n&&("visible"===o.overflow||"visible"===o.overflowX||"visible"===o.overflowY)||!n&&("textarea"===i||"select"===i)})(t,r)&&o.push({element:t,isDoc:r,left:ke(t,r,e.window),top:De(t,r,e.window)})}),o}(i,e.isDoc),e.disabledDocBars=!1,e.isDoc&&e.savedElementsScroll.length&&e.savedElementsScroll[0].isDoc&&(e.disabledDocBars=Ae(e)),e.savedElementsAccKeys=function(e,t){var n=[];return e.forEach(function(e,o){if(!t||0!==o){var i={},r=e.tabIndex;-1!==r&&(i.element=e,i.tabIndex=!!e.hasAttribute("tabindex")&&r,e.tabIndex=-1);var a=e.accessKey;a&&(i.element=e,i.accessKey=a,e.accessKey=""),i.element&&n.push(i)}}),n}(i,e.isDoc),e.activeElement=e.document.activeElement,e.activeElement&&Pe(e,e.activeElement),Ce(e),n.offsetWidth,e.options.onPosition&&e.options.onPosition.call(e.ins)}e.transition.on(t),e.state=ce,t&&ze(e)}}function Fe(e,t){var n=e.options;if(t.hasOwnProperty("face")&&(null==t.face?void 0:t.face)!==n.face){for(var o=e.elmOverlayBody;o.firstChild;)o.removeChild(o.firstChild);if(!1===t.face)n.face=!1;else if(t.face&&t.face.nodeType===Node.ELEMENT_NODE)n.face=t.face,o.appendChild(t.face);else if(null==t.face){var i=e.document;if(!i.getElementById(de)){var r=(new e.window.DOMParser).parseFromString($.a,"image/svg+xml");i.body.appendChild(r.documentElement)}n.face=void 0,o.innerHTML=Q.a}}Te(t.duration)&&t.duration!==n.duration&&(n.duration=t.duration,e.elmOverlay.style[p.getName("transitionDuration")]=t.duration===pe?"":t.duration+"ms",e.transition.duration=t.duration+"ms"),(Te(t.blur)||!1===t.blur)&&(n.blur=t.blur),be(t.style)&&_e(e.elmOverlay,t.style),["onShow","onHide","onBeforeShow","onBeforeHide","onPosition"].forEach(function(e){"function"==typeof t[e]?n[e]=t[e]:t.hasOwnProperty(e)&&null==t[e]&&(n[e]=void 0)})}function je(e,t,n,o){var i=void 0,r=void 0;if(t){if(-1===Le(e).indexOf(t))return r;i="html"===t.nodeName.toLowerCase()}else t=e.elmTarget,i=e.isDoc;var a=null!=o&&e.savedElementsScroll&&(e.savedElementsScroll.find?e.savedElementsScroll.find(function(e){return e.element===t}):function(n){var o=void 0;return e.savedElementsScroll.some(function(e){return e.element===t&&(o=e,!0)}),o}());return r=(n?ke:De)(t,i,e.window,o),a&&(a[n?"left":"top"]=r),r}var He=function(){function e(t,n){function o(e){var t=void 0;if(e)if(e.nodeType){if(e.nodeType===Node.DOCUMENT_NODE)t=e.documentElement;else if(e.nodeType===Node.ELEMENT_NODE){var n=e.nodeName.toLowerCase();t="body"===n?e.ownerDocument.documentElement:"iframe"===n||"frame"===n?e.contentDocument.documentElement:e}if(!t)throw new Error("This element is not accepted.")}else e===e.window&&(t=e.document.documentElement);else t=document.documentElement;return t}!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var i={ins:this,options:{face:!1,duration:pe,blur:!1},state:ue,savedStyleTarget:{},savedStyleTargetBody:{},blockingDisabled:!1};if(Object.defineProperty(this,"_id",{value:++Oe}),i._id=this._id,Ee[this._id]=i,1===arguments.length){if(!(i.elmTarget=o(t))){if(!be(t))throw new Error("Invalid argument.");i.elmTarget=document.documentElement,n=t}}else if(!(i.elmTarget=o(t)))throw new Error("This target is not accepted.");if(n){if(!be(n))throw new Error("Invalid options.")}else n={};i.isDoc="html"===i.elmTarget.nodeName.toLowerCase();var r=i.document=i.elmTarget.ownerDocument;i.window=r.defaultView;var a=i.elmTargetBody=i.isDoc?r.body:i.elmTarget;if(!r.getElementById(ne)){var s=r.getElementsByTagName("head")[0]||r.documentElement,l=s.insertBefore(r.createElement("style"),s.firstChild);l.type="text/css",l.id=ne,l.textContent=V.a,(he||ye)&&function(e){setTimeout(function(){var t=e.parentNode,n=e.nextSibling;t.insertBefore(t.removeChild(e),n)},0)}(l)}var d=i.elmOverlay=r.createElement("div"),u=k(d);u.add(oe,ae),i.isDoc&&u.add(ie),i.transition=new X(d,{procToOn:function(e){var t=k(d);t.toggle(se,!!e),t.add(re)},procToOff:function(e){var t=k(d);t.toggle(se,!!e),t.remove(re)},property:"opacity",duration:pe+"ms"}),d.addEventListener("timedTransitionEnd",function(e){e.target===d&&"opacity"===e.propertyName&&(i.state===ce?ze(i):i.state===me&&Ie(i))},!0),(i.isDoc?i.window:a).addEventListener("scroll",function(e){var t=e.target;i.state!==ue&&!i.blockingDisabled&&Ne(i,!i.isDoc||t!==i.window&&t!==i.document&&t!==i.elmTargetBody?t:i.elmTarget)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),i.focusListener=function(e){i.state!==ue&&!i.blockingDisabled&&Pe(i,e.target)&&(e.preventDefault(),e.stopImmediatePropagation())},a.addEventListener("focus",i.focusListener,!0),function(e){["keyup","mouseup"].forEach(function(t){i.window.addEventListener(t,e,!0)})}(function(e){i.state!==ue&&!i.blockingDisabled&&Ce(i)&&(e.preventDefault(),e.stopImmediatePropagation())}),i.resizing=!1,i.window.addEventListener("resize",O.add(function(){if(!i.resizing){if(i.resizing=!0,i.state!==ue){if(i.isDoc)i.savedElementsScroll.length&&i.savedElementsScroll[0].isDoc&&(i.disabledDocBars&&(Se(i.elmTarget,i.savedStyleTarget,["overflow"]),Se(a,i.savedStyleTargetBody,["marginLeft","marginRight","marginTop","marginBottom","width","height"])),i.disabledDocBars=Ae(i));else{var e=Be(a,i.window),t=i.targetBodyBBox;e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height||Re(i,e)}i.options.onPosition&&i.options.onPosition.call(i.ins)}i.resizing=!1}}),!0),d.addEventListener("touchmove",function(e){i.state!==ue&&(e.preventDefault(),e.stopImmediatePropagation())},!0),(i.elmOverlayBody=d.appendChild(r.createElement("div"))).className=le,r.body.appendChild(d),n.hasOwnProperty("face")||(n.face=null),Fe(i,n)}return ee(e,[{key:"setOptions",value:function(e){return be(e)&&Fe(Ee[this._id],e),this}},{key:"show",value:function(e,t){return arguments.length<2&&"boolean"!=typeof e&&(t=e,e=!1),this.setOptions(t),Me(Ee[this._id],e),this}},{key:"hide",value:function(e){return function(e,t){if(!(e.state===ue||e.state===me&&!t||e.state!==me&&e.options.onBeforeHide&&!1===e.options.onBeforeHide.call(e.ins))){e.filterElements&&(e.filterElements.forEach(function(e){Se(e.element,e.savedStyle)}),e.filterElements=null);var n=e.document.activeElement;n&&n!==n.ownerDocument.body&&e.elmOverlay.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_CONTAINED_BY&&(n.blur?n.blur():n.ownerDocument.body.focus()),e.transition.off(t),e.state=me,t&&Ie(e)}}(Ee[this._id],e),this}},{key:"scrollLeft",value:function(e,t){return je(Ee[this._id],t,!0,e)}},{key:"scrollTop",value:function(e,t){return je(Ee[this._id],t,!1,e)}},{key:"position",value:function(){var e=Ee[this._id];return e.state!==ue&&(e.isDoc||Re(e,Be(e.elmTargetBody,e.window)),e.options.onPosition&&e.options.onPosition.call(e.ins)),this}},{key:"state",get:function(){return Ee[this._id].state}},{key:"style",get:function(){return Ee[this._id].elmOverlay.style}},{key:"blockingDisabled",get:function(){return Ee[this._id].blockingDisabled},set:function(e){"boolean"==typeof e&&(Ee[this._id].blockingDisabled=e)}},{key:"face",get:function(){return Ee[this._id].options.face},set:function(e){Fe(Ee[this._id],{face:e})}},{key:"duration",get:function(){return Ee[this._id].options.duration},set:function(e){Fe(Ee[this._id],{duration:e})}},{key:"blur",get:function(){return Ee[this._id].options.blur},set:function(e){Fe(Ee[this._id],{blur:e})}},{key:"onShow",get:function(){return Ee[this._id].options.onShow},set:function(e){Fe(Ee[this._id],{onShow:e})}},{key:"onHide",get:function(){return Ee[this._id].options.onHide},set:function(e){Fe(Ee[this._id],{onHide:e})}},{key:"onBeforeShow",get:function(){return Ee[this._id].options.onBeforeShow},set:function(e){Fe(Ee[this._id],{onBeforeShow:e})}},{key:"onBeforeHide",get:function(){return Ee[this._id].options.onBeforeHide},set:function(e){Fe(Ee[this._id],{onBeforeHide:e})}},{key:"onPosition",get:function(){return Ee[this._id].options.onPosition},set:function(e){Fe(Ee[this._id],{onPosition:e})}}],[{key:"show",value:function(t,n){return new e(t,n).show()}},{key:"STATE_HIDDEN",get:function(){return ue}},{key:"STATE_SHOWING",get:function(){return ce}},{key:"STATE_SHOWN",get:function(){return fe}},{key:"STATE_HIDING",get:function(){return me}}]),e}();t.default=He}]).default; -/* jslint browser: true */ - -/* global */ - -var ResizeThrottler = new (function() { - /*********************************************************** - Private section. - - Fields. - ************************************************************/ - var _callback_arr = [], - - _throttling_speed = 1000 / 8, // 8 fps by default - - _resize_timeout = null; - - - /*********************************************************** - Private section. - - Functions. - ************************************************************/ - var _throttler = function () { - if (_resize_timeout === null) { - _resize_timeout = setTimeout(function() { - _resize_timeout = null; - _callback_arr.forEach(function (func) { func(); }); - }, _throttling_speed); - } - }; - - var _add = function (callback) { - _callback_arr.push(callback); - }; - - /*********************************************************** - Public section. - - Functions. - ************************************************************/ - this.initialize = function (callback_arr) { - window.addEventListener("resize", _throttler, false); - - callback_arr.forEach(function (func) { _add(func); func(); }); - }; - - this.add = function (callback) { - _add(callback); - }; -})(); -window.onload = function() { - "use strict"; - - document.body.style.overflow = "hidden"; - -var FragmentSynth = function (params) { - "use strict"; - - /*********************************************************** - Globals. - ************************************************************/ - -/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _fs_palette = { - 0: [0, 0, 0], - 10: [75, 0, 159], - 20: [104, 0, 251], - 30: [131, 0, 255], - 40: [155, 18,157], - 50: [175, 37, 0], - 60: [191, 59, 0], - 70: [206, 88, 0], - 80: [223, 132, 0], - 90: [240, 188, 0], - 100: [255, 252, 0] - }, - - _midi_notes_map = [], - _notes_name = [ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" ], - - _spectrum_colors = []; - -/*********************************************************** - Functions. -************************************************************/ - -var _hzToMIDINote = function (freq) { - return 69 + 12 * Math.log2(freq / 440); -}; - -var _hzFromMIDI = function (midi_note) { - return 440 * Math.pow(2, (midi_note - 69) / 12); -}; - -var _getMIDIPan = function (l, r) { - return Math.min(Math.abs(Math.round((1. - (l - r))*64)), 127); -}; - -var _getMIDIBend = function (f1, fn) { - return Math.round(8192 + 4096 * 12 * Math.log2(f1 / _hzFromMIDI(fn))); -}; - -var _hzToOscillator = function (f, bf, o, h) { - return (h - (Math.log(f / bf) / Math.log(2.0)) * Math.floor(h / o + 0.5)); -}; - -var _MIDINoteName = function (midi_note) { - return _midi_notes_map[Math.round(midi_note)]; -}; - -var _randomInt = function (min, max) { - return Math.floor(Math.random() * (max - min + 1) + min); -}; - -var _random = function (min, max) { - return Math.random() * (max - min) + min; -}; - -var _webMIDISupport = function () { - if (navigator.requestMIDIAccess) { - return true; - } else { - return false; - } -}; - -var _objSwap = function (src, dst) { - var k = null, - - dst_data = null; - - for (k in src) { - dst_data = dst[k]; - - dst[k] = src[k]; - src[k] = dst_data; - } -}; - -var _cloneObj = function (obj) { - return JSON.parse(JSON.stringify(obj)); -}; - -var _swapArrayItem = function (arr, a, b) { - var temp = arr[a]; - - arr[a] = arr[b]; - arr[b] = temp; - - return arr; -}; - -var _isPowerOf2 = function (value) { - return (value & (value - 1)) === 0; -}; - -var _parseInt10 = function (value) { - return parseInt(value, 10); -}; - -var _getElementOffset = function (elem) { - var box = elem.getBoundingClientRect(), - body = document.body, - docEl = document.documentElement, - - scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop, - scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft, - - clientTop = docEl.clientTop || body.clientTop || 0, - clientLeft = docEl.clientLeft || body.clientLeft || 0, - - top = box.top + scrollTop - clientTop, - left = box.left + scrollLeft - clientLeft; - - return { top: Math.round(top), left: Math.round(left), width: box.width, height: box.height }; -}; - -var _getFundamentalFrequency = function (data, width, height) { - var i = 0, j = 0, - data_index = 0, - freq = Infinity; - - for (i = height - 1; i >= 0; i -= 1) { - for (j = 0; j < width; j += 1) { - data_index = i * (width * 4) + j * 4; - - if (((data[data_index] + data[data_index + 1]) / 2) > 0) { - freq = Math.min(freq, _getFrequency(i)); - } - } - } - - return freq; -}; - -var _getSonogramBoundary = function (data, width, height, backward) { - var i = 0, j = 0, - data_index = 0, - - x = width, - - rx = 0, - - f = Math.min, - - w_offset = 0; - - if (backward) { - w_offset = -(width - 1); - - f = Math.max; - - x = 0; - } - - for (i = height - 1; i >= 0; i -= 1) { - for (j = 0; j < width; j += 1) { - rx = Math.abs(j + w_offset); - - data_index = i * (width * 4) + rx * 4; - - if (data[data_index] > 0 || data[data_index + 1] > 0) { - x = f(x, rx); - - break; - } - } - } - - return x; -}; - -var _xhrContent = function (url, cb) { - var xmlhttp = new XMLHttpRequest(); - xmlhttp.open("GET", url, true); - xmlhttp.onreadystatechange = function() { - if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { - cb(xmlhttp.responseText); - } - } - xmlhttp.send(); -}; - -var _rgbToHex = function (r, g, b) { - return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); -}; - -var _decimalToHTMLColor = function (n) { - return ('00000' + (n | 0).toString(16)).substr(-6); -}; - -var _logScale = function (index, total, opt_base) { - var base = opt_base || 2, - logmax = Math.log(total + 1) / Math.log(base), - exp = logmax * index / total; - - return Math.round(Math.pow(base, exp) - 1); -}; - -var _melScale = function () { - -}; - -var _degToRad = function (angle) { - return angle * Math.PI / 180.0; -}; - -var _swapNode = function (elem1, elem2) { - if (elem1 && elem2) { - var P1 = elem1.parentNode, - T1 = document.createElement("span"), - P2, - T2; - - P1.insertBefore(T1, elem1); - - P2 = elem2.parentNode; - T2 = document.createElement("span"); - - P2.insertBefore(T2, elem2); - - P1.insertBefore(elem2, T1); - P2.insertBefore(elem1, T2); - - P1.removeChild(T1); - P2.removeChild(T2); - } -}; - -var _setImageSmoothing = function (ctx, state) { - if (ctx) { - ctx.mozImageSmoothingEnabled = state; - ctx.oImageSmoothingEnabled = state; - //ctx.webkitImageSmoothingEnabled = state; - ctx.msImageSmoothingEnabled = state; - ctx.imageSmoothingEnabled = state; - } -}; - -var _barkScale = function (length, sample_rate, buffer_size) { - var scale = new Float32Array(length), - - i = 0; - - for (i = 0; i < scale.length; i += 1) { - scale[i] = i * sample_rate / buffer_size; - scale[i] = 13 * Math.atan(scale[i] / 1315.8) + 3.5 * Math.atan(Math.pow((scale[i] / 7518), 2)); - } - - return scale; -}; - -var _getColorFromPalette = function (value) { - var decimalised = 100 * value / 255, - percent = decimalised / 100, - floored = 10 * Math.floor(decimalised / 10), - distFromFloor = decimalised - floored, - distFromFloorPercentage = distFromFloor/10, - rangeToNextColor, - color; - - if (decimalised < 100){ - rangeToNextColor = [ - _fs_palette[floored + 10][0] - _fs_palette[floored + 10][0], - _fs_palette[floored + 10][1] - _fs_palette[floored + 10][1], - _fs_palette[floored + 10][2] - _fs_palette[floored + 10][2] - ]; - } else { - rangeToNextColor = [0, 0, 0]; - } - - color = [ - _fs_palette[floored][0] + distFromFloorPercentage * rangeToNextColor[0], - _fs_palette[floored][1] + distFromFloorPercentage * rangeToNextColor[1], - _fs_palette[floored][2] + distFromFloorPercentage * rangeToNextColor[2] - ]; - - return "rgb(" + color[0] +", "+color[1] +"," + color[2]+")"; -}; - -var _truncateDecimals = function (num, digits) { - var n = (+num).toFixed(digits + 1); - return +(n.slice(0, n.length - 1)); -}; - -var _clipboardCopy = function (e) { - var copy_event = new ClipboardEvent("copy", { dataType: "text/plain", data: e.target.dataset.clipboard } ); - document.dispatchEvent(copy_event); -}; - -var _isFireFox = function () { - return (navigator.userAgent.toLowerCase().indexOf('firefox') > -1); -}; - -var _frequencyFromNoteNumber = function (note) { - return 440 * Math.pow(2, (note - 69) / 12); -}; - -// ms -var _getNoteTime = function (tempo, ppb) { - return (1.0 / ppb) * (60.0 / tempo); -}; - -var _lZeroPad = function (str, c, length) { - str = "" + str; - - while (str.length < length) { - str = c + str; - } - - return str; -}; - -var _setCookie = function (name, value, days) { - var d = new Date(); - - d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000)); - - document.cookie = name + "=" + value + ";" + ("expires=" + d.toUTCString()) + ";path=/"; -}; - -var _getCookie = function getCookie(name) { - var cookies, - cookie, - - i = 0; - - name = name + "="; - cookies = document.cookie.split(';'); - - for(i = 0; i < cookies.length; i += 1) { - cookie = cookies[i]; - - while (cookie.charAt(0) == ' ') { - cookie = cookie.substring(1); - } - - if (cookie.indexOf(name) === 0) { - return cookie.substring(name.length, cookie.length); - } - } - - return ""; -}; - -var _unfocus = function () { - var el = document.querySelector(':focus'); - if (el) { - el.blur(); - } -}; - -var _getTimeFunction = function () { - return performance.now() / 1000; -}; - -var _fnToImageData = function (img, done) { - return function () { - var tmp_canvas = document.createElement('canvas'), - tmp_canvas_context = tmp_canvas.getContext('2d'), - - tmp_image_data; - - tmp_canvas.width = img.naturalWidth; - tmp_canvas.height = img.naturalHeight; - - tmp_canvas_context.drawImage(img, 0, 0, tmp_canvas.width, tmp_canvas.height); - - tmp_image_data = tmp_canvas_context.getImageData(0, 0, tmp_canvas.width, tmp_canvas.height); - - done(tmp_image_data); - }; -}; - -var _imageToDataURL = function (image) { - var canvas = document.createElement("canvas"), - ctx = canvas.getContext("2d"); - - canvas.width = image.width; - canvas.height = image.height; - - ctx.drawImage(image, 0, 0); - - return canvas.toDataURL("image/png"); -}; - -var _fnCanvasToImage = function (tmp_canvas, done) { - var image_element = document.createElement("img"); - image_element.src = tmp_canvas.toDataURL(); - image_element.width = tmp_canvas.width; - image_element.height = tmp_canvas.height; - - image_element.onload = function () { - image_element.onload = null; - - done(image_element); - }; -}; - -var _fnFlipImage = function (img, done) { - return function () { - var tmp_canvas = document.createElement('canvas'), - tmp_canvas_context = tmp_canvas.getContext('2d'), - - tmp_image_data; - - tmp_canvas.width = img.naturalWidth; - tmp_canvas.height = img.naturalHeight; - - tmp_canvas_context.translate(0, tmp_canvas.height); - tmp_canvas_context.scale(1, -1); - tmp_canvas_context.drawImage(img, 0, 0, tmp_canvas.width, tmp_canvas.height); - - tmp_image_data = tmp_canvas_context.getImageData(0, 0, tmp_canvas.width, tmp_canvas.height); - - done({ canvas: tmp_canvas, image_data: tmp_image_data }); - }; -}; - -var _truncateString = function (source, size) { - return source.length > size ? source.slice(0, size - 1) + "…" : source; -}; - -var _flipImage = function (img, done) { - _fnFlipImage(img, done)(); -}; - -/*********************************************************** - Init. -************************************************************/ - -var _toolsInit = function () { - var i = 0, index, key, octave; - - for (i = 0; i < 256; i += 1) { - _spectrum_colors.push(_getColorFromPalette(i)); - } - - // generate notes name for MIDI to note name conversion - for(i = 0; i < 127; i += 1) { - index = i; - key = _notes_name[index % 12]; - octave = ((index / 12) | 0) - 1; - - key += octave; - - _midi_notes_map[i] = key; - } -}; - -_toolsInit();/* jslint browser: true */ - -/* - Simple double notifications system - - This show notification messages in corners of the score area, - generic notifications can be stacked and a duration can be set, - fail notification is used for notifications that should not disappear and should be solved (aka, GLSL compilation failed), - fail notification is always shown in the left corner, if a generic notification is shown at the same time, it will go to the right corner, - there is also the utter fail notification which is just used for critical, app. breaking stuff... -*/ - -/*********************************************************** - Fields. -************************************************************/ - -var _utter_fail_element = document.getElementById("fs_utter_fail"), - _fail_element = document.getElementById("fail"), - _notification_element = document.getElementById("fs_notification"); - -/*********************************************************** - Functions. -************************************************************/ - -var _fail = function (message, utter) { - if (message instanceof Element) { - _fail_element.innerHTML = ""; - _fail_element.appendChild(message); - - if (_notification_element.innerHTML !== "") { - _notification_element.classList.add("fs-text-align-right"); - } - } else { - _fail_element.innerHTML = message; - } - - if (utter) { - document.body.innerHTML = ""; - - _utter_fail_element.innerHTML = '' + message; - - document.body.appendChild(_utter_fail_element); - } -}; - -var _utterFailRemove = function () { - _utter_fail_element.parentElement.removeChild(_utter_fail_element); - - _utter_fail_element = null; -}; - -var _removeNotification = function (notification_div) { - return function () { - notification_div.parentElement.removeChild(notification_div); - }; -}; - -var _hideNotification = function (notification_div) { - return function () { - notification_div.classList.add("fs-opacity-transition"); - notification_div.classList.add("fs-transparent"); - - window.setTimeout(_removeNotification(notification_div), 2000); - }; -}; - -var _notification = function (message, duration_ms) { - var notification_div = document.createElement('div'); - - notification_div.innerHTML = message; - - if (duration_ms === undefined) { - duration_ms = 1500; - } - - if (_fail_element.innerHTML !== "") { - notification_div.classList.add("fs-text-align-right"); - } - - _notification_element.appendChild(notification_div); - - window.setTimeout(_hideNotification(notification_div), duration_ms); -}; - -/*********************************************************** - Init. -************************************************************/ - -_utter_fail_element.innerHTML = ""; - var _getSessionName = function () { - var url_parts; - - if (params.session_name) { - return params.session_name; - } else { - url_parts = window.location.pathname.split('/'); - - return url_parts[url_parts.length - 1]; - } - }; - - window.performance = window.performance || {}; - performance.now = (function() { - return performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function() { return new Date().getTime(); }; - })(); - - window.AudioContext = window.AudioContext || window.webkitAudioContext || false; - - window.requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || - window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; - window.cancelAnimationFrame = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame; - - if (!window.AudioContext) { - _fail("The Web Audio API is not available, please use a Web Audio capable browser.", true); - - return; - } - - if (!window.cancelAnimationFrame) { - _fail("The cancelAnimationFrame function is not available, please use a web browser with cancelAnimationFrame support.", true); - - return; - } - - if (!window.indexedDB) { - window.indexedDB = window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB; - - if (!window.indexedDB) { - _notification("The IndexedDB API is not available, imported data will not be saved.", 10000); - } else { - window.indexedDB = { - open: function () { return null; } - }; - } - } - - if (!window.localStorage) { - _fail("The localStorage API is not available, please use a web browser with localStorage support.", true); - - return; - } - - if (!window.FileReader) { - _fail("FileReader API is not available, please use a web browser with FileReader support.", true); - - return; - } - - if (!window.Blob) { - _fail("Blob API is not available, please use a web browser with Blob support.", true); - - return; - } - - if (!window.File) { - _fail("File API is not available, please use a web browser with File API support.", true); - - return; - } - - if (typeof(Worker) === "undefined") { - _fail("Web Workers are not available, please use a web browser with Web Workers support.", true); - - return; - } - - // check WebGL 2 support - var test_canvas = document.createElement("canvas"); - var test_opts = { - preserveDrawingBuffer: true, - antialias: true, - depth: false - }; - - if (!(test_canvas.getContext("webgl2", test_opts) || test_canvas.getContext("experimental-webgl2", test_opts))) { - _fail("WebGL 2 is not available, please use a web browser / device with WebGL 2 support.", true); - - return; - } - - /*********************************************************** - Fields. - ************************************************************/ - - var _motd = '', - - _webmidi_support_msg = '
WebMIDI API is not enabled/supported by this browser, please use a compatible browser.
', - - _showdown_converter = new showdown.Converter(), - - _fs_state = 1, - - _documentation_link = "https://www.fsynth.com/documentation/", - - _username = localStorage.getItem('fs-user-name'), - _local_session_settings = localStorage.getItem(_getSessionName()), - - _current_editor_target = 0, - - _synth_data_array = Uint8Array, - - _red_curtain_element = document.getElementById("fs_red_curtain"), - _user_name_element = document.getElementById("fs_user_name"), - _username_input = document.getElementById("fs_username_input"), - - _time_infos = document.getElementById("fs_time_infos"), - _hz_infos = document.getElementById("fs_hz_infos"), - _xy_infos = document.getElementById("fs_xy_infos"), - _osc_infos = document.getElementById("fs_osc_infos"), - _poly_infos_element = document.getElementById("fs_polyphony_infos"), - _fas_stream_load = document.getElementById("fs_fas_stream_load"), - _fas_stream_latency = document.getElementById("fs_fas_stream_latency"), - - _synth_output_element = document.getElementById("fs_synth_output"), - - _haxis_infos = document.getElementById("fs_haxis_infos"), - _vaxis_infos = document.getElementById("fs_vaxis_infos"), - - _canvas_container = document.getElementById("canvas_container"), - _canvas = document.createElement("canvas"), - - _record_canvas = document.getElementById("fs_record_canvas"), - _record_canvas_ctx = _record_canvas.getContext('2d'), - _record_slice_image, - _record_position = 0, - _record = false, - _record_input_count = 0, - _record_slice_fn = [function (i, j) { - return _data[i][j] + _osc_data[i][j] + _midi_data[i][j]; - }, function (i, j) { - return _data[i][j]; - }, function (i, j) { - return _osc_data[i][j]; - }, function (i, j) { - return _midi_data[i][j]; - }], - _record_type = 1, // record AUDIO output only by default - _record_opts = { - default: function (p, p2) { - return p2; - }, - additive: function (p, p2) { - return p + p2; - }, - substractive: function (p, p2) { - return p - p2; - }, - multiply: function (p, p2) { - return p * p2; - }, - f: null - }, - - // helper canvas - _c_helper = document.getElementById("fs_helper_canvas"), - _c_helper_ctx = _c_helper.getContext("2d"), - - // crude initial adaptation for mobiles / tablets / desktop - _canvas_width = (window.innerWidth < 500 ? 320 : (window.innerWidth < 800 ? 640 : (window.innerWidth < 1280 ? 800 : 1224))), - _canvas_height = (window.innerHeight <= 640 ? 200 : 439), - - _canvas_width_m1 = _canvas_width - 1, - _canvas_height_mul4 = _canvas_height * 4, - - _detached_canvas = null, - _detached_canvas_ctx = null, - _detached_canvas_buffer = new Uint8Array(_canvas_width * _canvas_height * 4), - _detached_canvas_image_data = null, - - _render_width = _canvas_width, - _render_height = _canvas_height, - - _feedback = { - enabled: true, - pframe: [], - index: 0, - program: null, - texture: null - }, - - // contain all workspace code editors - _code_editors = [ - { - name: "main", - container: document.getElementById("fs_code"), - marks: [], - editor: null, - index: 0, - default_value: document.getElementById("fragment-shader").text, - sharedb: { - doc: null, - rdy: false - }, - collaborative: true, - outline: { - element: function () { - var detachedWindow = WUI_Dialog.getDetachedDialog(_outline_dialog); - if (detachedWindow) { - return detachedWindow.document.getElementById("fs_main_outline"); - } - - return document.getElementById("fs_main_outline"); - }, - data: [] - }, - detached_windows: [], - line_widgets: [] - }, -/* - { - name: "buffer", - container: document.getElementById("fs_buffer_code"), - marks: [], - editor: null, - index: 1, - default_value: document.getElementById("fragment-shader-buffer").text, - sharedb: { - doc: null, - rdy: false - }, - collaborative: true, - outline: { - element: document.getElementById("fs_buffer_outline"), - data: [] - }, - detached_windows: [] - }, -*/ - { - name: "library", - container: document.getElementById("fs_library_code"), - marks: [], - editor: null, - index: 1, - default_value: localStorage.getItem('fs-user-library') ? localStorage.getItem('fs-user-library') : "// my library", - collaborative: false, - outline: { - element: function () { - var detachedWindow = WUI_Dialog.getDetachedDialog(_outline_dialog); - if (detachedWindow) { - return detachedWindow.document.getElementById("fs_library_outline"); - } - - return document.getElementById("fs_library_outline"); - }, - data: [] - }, - detached_windows: [], - line_widgets: [] - }, - { - name: "example", - container: document.getElementById("fs_example_code"), - marks: null, - editor: null, - index: 2, - default_value: "", - collaborative: false, - outline: null, - detached_windows: [], - line_widgets: [] - } - ], - _current_code_editor = _code_editors[0], - - _code_editor_font_size = localStorage.getItem('fs-editor-font-size'), - - _code_editor_theme = localStorage.getItem('fs-editor-theme'), - _code_editor_theme_link, - _code_editor_highlight = { - showToken: /\w/, - annotateScrollbar: true - }, - - _code_editor_settings = { - value: "", - theme: ((_code_editor_theme === null) ? "seti" : _code_editor_theme), - matchBrackets: true, - //autoCloseBrackets: true, - lineNumbers: true, - gutters: ["CodeMirror-linenumbers", "fs-mark"], - styleActiveLine: true, - scrollbarStyle: "native", - mode: "text/x-glsl", - extraKeys: { - "F11": function (cm) { - var fullscreen = !cm.getOption("fullScreen"); - - cm.setOption("fullScreen", fullscreen); - - // hide some UI stuff when fullscreen - var mid_panel = document.getElementById("fs_middle_panel"), - explorer = document.getElementById("fs_explorer"), - top_panel = document.getElementById("fs_top_panel"), - - i = 0; - - if (fullscreen) { - _current_code_editor.editor.setOption("lineNumbers", false); - mid_panel.style.display = "none"; - top_panel.style.display = "none"; - explorer.style.display = "none"; - - var marks = document.getElementsByClassName("fs-mark"); - for (i = 0; i < marks.length; i += 1) { - marks[i].style.display = "none"; - } - - var ppd = document.getElementsByClassName("play-position-triangle-vflip"); - for (i = 0; i < ppd.length; i += 1) { - ppd[i].style.display = "none"; - } - - _canvas.style.border = "none"; - } else { - _current_code_editor.editor.setOption("lineNumbers", _cm_show_linenumbers); - mid_panel.style.display = ""; - top_panel.style.display = ""; - explorer.style.display = ""; - - var marks = document.getElementsByClassName("fs-mark"); - for (i = 0; i < marks.length; i += 1) { - marks[i].style.display = ""; - } - - var ppd = document.getElementsByClassName("play-position-triangle-vflip"); - for (i = 0; i < ppd.length; i += 1) { - ppd[i].style.display = ""; - } - - _canvas.style.border = ""; - } - }, - "Esc": function (cm) { - if (cm.getOption("fullScreen")) { - cm.setOption("fullScreen", false); - - _current_code_editor.editor.setOption("lineNumbers", _cm_show_linenumbers); - - var mid_panel = document.getElementById("fs_middle_panel"), - explorer = document.getElementById("fs_explorer"), - top_panel = document.getElementById("fs_top_panel"); - - mid_panel.style.display = ""; - top_panel.style.display = ""; - explorer.style.display = ""; - - var marks = document.getElementsByClassName("fs-mark"); - for (i = 0; i < marks.length; i += 1) { - marks[i].style.display = ""; - } - - var ppd = document.getElementsByClassName("play-position-triangle-vflip"); - for (i = 0; i < ppd.length; i += 1) { - ppd[i].style.display = ""; - } - - _canvas.style.border = ""; - } - } - } - }, - - _show_output_channels = false, - - _audio_off = false, - - // this is the amount of free uniform vectors for Fragment regular uniforms and session custom uniforms - // this is also used to assign uniform vectors automatically for polyphonic uses - // if the GPU cannot have that much uniforms (with polyphonic uses), this will be divided by two and the polyphonic computation will be done again - // if the GPU cannot still have that much uniforms (with polyphonic uses), there will be a polyphony limit of 16 notes, this is a safe limit for all devices nowaday - _free_uniform_vectors = 320, - - // note-on/note-off related stuff (MIDI keyboard etc.) - _keyboard = { - data: [], - data_components: 8, - // polyphonic capabilities is set dynamically from MAX_FRAGMENT_UNIFORM_VECTORS parameter - // ~221 MAX_FRAGMENT_UNIFORM_VECTORS value will be generally the default for desktop - // this permit a polyphony of ~60 notes with 4 components for each notes and by considering the reserved uniform vectors - // all this is limited by the MAX_FRAGMENT_UNIFORM_VECTORS parameter on the GPU taking into account the other Fragment uniform PLUS sessions uniform - // at the time of this comment in 2017, 99.9% of desktop devices support up to 221 uniform vectors while there is a 83.9% support for up to 512 uniform vectors, - // this amount to ~192 notes polyphony, a capability of 1024 lead to ~704 notes polyphony and so on... - data_length: 60 * 8, - // amount of allocated uniform vectors - uniform_vectors: 0, - pressed: {}, - polyphony_max: 32, - polyphony: 0, // current polyphony - note_lifetime: 1000 // how much time the note is kept after note-off event (for release, in ms) - }, - - // last note-on/note-off (MIDI) - _pkeyboard = { - data: [], - data_components: 3, - }, - - _chn_settings = [], - - _webgl = { - max_fragment_uniform_vector: -1 - }, - - _compile_timer, - _update_marks_timer, - _save_marks_timer, - - _undock_code_editor = false, - - _xyf_grid = false, - - _glsl_error = false, - - _first_play = true, - - _OES_texture_float_linear = null, - _EXT_color_buffer_float = null, - - // settings - _show_globaltime = true, - _show_oscinfos = false, - _show_polyinfos = false, - _cm_highlight_matches = false, - _cm_show_linenumbers = true, - _cm_show_inerrors = true, - _cm_show_osderrors = true, - _cm_advanced_scrollbar = false, - _quickstart_on_startup = true, - _compile_delay_ms = 100, - - _clipboard, - - // mouse cursor over canvas - _cx, - _cy, - - _mx, - _my, - - _nmx, - _nmy, - - _cnmx, - _cnmy, - - _mouse_btn = 0, - - _LEFT_MOUSE_BTN = 1, - _RIGHT_MOUSE_BTN = 2, - - _raf, - - _gl, - _gl2 = true, - - _pbo = null, - _pbo_size = 0, - - _read_pixels_format, - - _play_position_markers = [], - - _webgl_opts = { - preserveDrawingBuffer: true, - antialias: true, - depth: false - }, - - _prev_data = [], - _temp_data = new Uint8Array(_canvas_height_mul4), - _data = [], - _prev_midi_data = [], - _midi_data = [], - _prev_osc_data = [], - _osc_data = [], - _output_channels = 0, - - _analysis_canvas, - _analysis_canvas_ctx, - - _analysis_canvas_tmp, - _analysis_canvas_tmp_ctx, - - _analysis_log_scale = true, - _analysis_colored = true, - _analysis_speed = 2, - - _midi_out = true, - - _quad_vertex_buffer, - - _program, - - _fragment_input_data = [], - - _input_panel_element = document.getElementById("fs_input_panel"), - - _wgl_support_element = document.getElementById("fs-wgl-support"), - _wgl_float_support_element = document.getElementById("fs-wgl-float-support"), - _wgl_lfloat_support_element = document.getElementById("fs-wgl-lfloat-support"), - - _globalFrame = 0, - - _time = 0, - - _pause_time = 0, - - _hover_freq = null, - - _input_channel_prefix = "iInput", - _input_video_prefix = "fvid"; - - /*********************************************************** - App. Includes. - ************************************************************/ - -/* - Client global configuration file - - This file is generated by a production system and filled with the correct settings (aka. domain where fss/fsdb is and the protocol used) -*/ - -var _ws_protocol = "ws", - _domain = "127.0.0.1";/* jslint browser: true */ - -/** - * IndexedDB initialization & interface - * - * Manage Fragment inputs storage (all except videos) - */ - -/*********************************************************** - Fields. -************************************************************/ - -var _request = null, - _db = null; - -/*********************************************************** - Functions. -************************************************************/ - -var _dbStoreInput = function (input_name, input_data) { - if (!_db) { - return; - } - - var object_store = _db.transaction(["inputs"], "readwrite").objectStore("inputs"), - - request = object_store.openCursor(input_name); - - request.onsuccess = function (event) { - var cursor = event.target.result; - if (!cursor) { - object_store.add(input_data, input_name); - } - }; -}; - -var _dbRemoveInput = function (name) { - if (!_db) { - return; - } - - var object_store = _db.transaction(["inputs"], "readwrite").objectStore("inputs"); - - object_store.delete(name); -}; - -var _dbClear = function () { - if (!_db) { - return; - } - - var object_store = _db.transaction(["inputs"], "readwrite").objectStore("inputs"); - - object_store.clear(); -}; - -var _dbUpdateInput = function (name, input_data) { - if (!_db) { - return; - } - - var object_store = _db.transaction(["inputs"], "readwrite").objectStore("inputs"), - request = object_store.get(name); - - request.onsuccess = function (event) { - object_store.put(input_data, name); - }; -}; - -var _dbRestoreInput = function (name, obj) { - if (!_db) { - return; - } - - var object_store = _db.transaction(["inputs"], "readwrite").objectStore("inputs"), - request = object_store.get(name); - - request.onsuccess = function (event) { - obj.db_obj = event.target.result; - }; -}; - -var _dbGetInputs = function (cb) { - if (!_db) { - return; - } - - var transaction = _db.transaction("inputs"); - var object_store = transaction.objectStore("inputs"); - var count_query = object_store.count(); - count_query.onsuccess = function () { - var count = count_query.result, - open_cursor = object_store.openCursor(), - - inputs = []; - - open_cursor.onsuccess = function (event) { - var cursor = event.target.result; - if (cursor) { - inputs[parseInt(cursor.key, 10)] = cursor.value; - - cursor.continue(); - } - }; - - transaction.oncomplete = async function (e) { - for (var i = 0; i < inputs.length; i += 1) { - await cb(i, inputs[i]); - } - }; - }; -}; - -/*********************************************************** - Init. -************************************************************/ - -var _initDb = function (db_name) { - _request = indexedDB.open(db_name, 1); - - if (_request !== null) { - _request.onsuccess = function (event) { - _db = _request.result; - - _db.onerror = function (ev) { - _notification("IndexedDB error '" + ev.error + "'"); - }; - - _dbGetInputs(async function (name, value) { - var image_element = null; - - if (!value) { - return; - } - - var input_id = parseInt(name, 10); - - if (value.type === "image" || - value.type === "canvas") { - if (value.data.length === 0) { - await _addFragmentInput(value.type, undefined, undefined, input_id); - return; - } - - image_element = document.createElement("img"); - image_element.src = value.data; - image_element.width = value.width; - image_element.height = value.height; - - await new Promise(function (resolve, reject) { - image_element.onload = function () { - image_element.onload = null; - - _addFragmentInput(value.type, image_element, value.settings, input_id); - - resolve(); - } - }); - } else if (value.type === "video") { - await _addFragmentInput(value.type, undefined, undefined, input_id); - } else if (value.type === "processing.js") { - await _addFragmentInput(value.type, value.data, undefined, input_id); - } else { - await _addFragmentInput(value.type, undefined, undefined, input_id); - } - }); - }; - - _request.onupgradeneeded = function (event) { - var db = event.target.result; - - db.createObjectStore("inputs"); - }; - } -};/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _audio_context = new window.AudioContext(), - - _sample_rate = _audio_context.sampleRate, - - _volume = 0.05, - - _audio_infos = { - h: 0, - base_freq: 0, - octaves: 0, - gain: _volume, - float_data: false - }, - - _oscillators = []; - -/*********************************************************** - Functions. -************************************************************/ - -var _setGain = function (gain) { - _volume = gain; - _audio_infos.gain = _volume; -}; - -var _getOscillator = function (y) { - if (y >= _oscillators.length || y < 0) { - return null; - } - - return _oscillators[y]; -}; - -var _getFrequency = function (y) { - var osc = _getOscillator(y); - - if (!osc) { - return null; - } - - return osc.freq; -}; - -var _attachMediaStream = function (stream) { - _audio_context.createMediaStreamSource(stream) -}; - -var _generateOscillatorSet = function (n, base_frequency, octaves) { - var y = 0, - frequency = 0.0, - octave_length = n / octaves; - - _oscillators = []; - - for (y = n - 1; y >= 0; y -= 1) { - frequency = base_frequency * Math.pow(2, y / octave_length); - - var osc = { - freq: frequency, - }; - - _oscillators.push(osc); - } - - _audio_infos.h = n; - _audio_infos.base_freq = base_frequency; - _audio_infos.octaves = octaves; -}; - -var _computeOutputChannels = function () { - var i = 0, j = 0, max = 0, marker; - - for (i = 0; i < _play_position_markers.length; i += 1) { - marker = _play_position_markers[i]; - - if (max < marker.output_channel) { - max = marker.output_channel; - } - } - - _output_channels = max; - - for (i = 0; i < _output_channels; i += 1) { - if (!_chn_settings[i]) { - _chn_settings[i] = { osc: [], efx: [], muted: 0, chn_output: 0 }; - } - } - - _allocateFramesData(); - _createFasSettingsContent(); - - _fasSendChannelsInfos(); - - _saveLocalSessionSettings(); -}; - -var _decodeAudioData = function (audio_data, done_cb) { - _audio_context.decodeAudioData(audio_data, function (buffer) { - done_cb(buffer); - }, - function (e) { - _notification("An error occured while decoding the audio data " + e.err); - }); -}; - -/*********************************************************** - Init. -************************************************************/ -/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - - - -/*********************************************************** - Functions. -************************************************************/ - -var _imageProcessingDone = function (image_ready_cb, options) { - return function (mdata) { - var tmp_canvas = document.createElement('canvas'), - tmp_canvas_context = tmp_canvas.getContext('2d'), - - image_data = tmp_canvas_context.createImageData(mdata.img_width, mdata.img_height), - - image_element; - - image_data.data.set(new Uint8ClampedArray(mdata.data)); - - tmp_canvas.width = image_data.width; - tmp_canvas.height = image_data.height; - - tmp_canvas_context.putImageData(image_data, 0, 0); - - image_element = document.createElement("img"); - image_element.src = tmp_canvas.toDataURL(); - image_element.width = image_data.width; - image_element.height = image_data.height; - - image_element.onload = function () { - image_element.onload = null; - - if (options) { - if (options.flip) { - tmp_canvas_context.clearRect(0, 0, tmp_canvas.width, tmp_canvas.height); - tmp_canvas_context.translate(0, tmp_canvas.height); - tmp_canvas_context.scale(1, -1); - tmp_canvas_context.drawImage(image_element, 0, 0, tmp_canvas.width, tmp_canvas.height); - - image_element.src = tmp_canvas.toDataURL(); - - image_element.onload = function () { - image_element.onload = null; - - image_ready_cb(image_element); - }; - } else { - image_ready_cb(image_element); - } - } else { - image_ready_cb(image_element); - } - }; - } -}; - -var _imageDataToInput = function (data, options) { - _notification("image processing in progress..."); - - _imageProcessor(data, _imageProcessingDone(function (image_element) { - _addFragmentInput("image", image_element); - }, options)); -}; - -var _loadImageFromFile = function (file) { - var img = new Image(); - - _notification("loading image '" + file.name + "' (" + file.size + ")"); - - img.onload = _fnToImageData(img, function (image_data) { - _imageDataToInput(image_data); - - window.URL.revokeObjectURL(img.src); - - img.onload = null; - img = null; - }); - - img.src = window.URL.createObjectURL(file); -}; - -var _loadImageFromURL = function (url, done_cb) { - var img = new Image(); - - img.onload = _fnToImageData(img, function (image_data) { - _imageProcessor(image_data, _imageProcessingDone(done_cb)); - - img.onload = null; - img = null; - }); - - img.src = url; -};/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _audio_to_image_worker = new Worker("dist/worker/audio_to_image.min.js"), - - _audio_import_settings = { - mapping: "logarithmic", - gain: 30, - deviation: 1, - padding: 0, - pps: 60, - height: 0, - minfreq: 0, - maxfreq: 0, - videotrack_import: false, - phase_import: false, - cam_width: 320, - cam_height: 240, - fft_size: 2048 - }; - -/*********************************************************** - Functions. -************************************************************/ - -var _convertAudioToImage = function (data) { - var l = data.getChannelData(0).buffer, - r = ((data.numberOfChannels > 1) ? data.getChannelData(1).buffer : null), - - params = { - settings: JSON.parse(JSON.stringify(_audio_import_settings)), - left: l, - right: r, - //note_time: _getNoteTime(_audio_import_settings.bpm, _audio_import_settings.ppb), - sample_rate: _sample_rate - }, - - barr = [l]; - - if (_audio_import_settings.height <= 0) { - params.settings.height = _canvas_height; - } - - if (_audio_import_settings.minfreq <= 0) { - params.settings.minfreq = _oscillators[_oscillators.length - 1].freq; - } - - if (_audio_import_settings.maxfreq <= 0) { - params.settings.maxfreq = _oscillators[0].freq; - } - - if (r) { - barr.push(r); - } - - _notification("conversion in progress...", 2000); - - _audio_to_image_worker.postMessage(params, barr); -}; - -var _loadAudioFromFile = function (file) { - var reader = new FileReader(); - - reader.onload = function (e) { - _decodeAudioData(e.target.result, _convertAudioToImage); - }; - - reader.onerror = function (e) { - var error = e.target.error; - switch(error.code) { - case error.NOT_FOUND_ERR: - _notification("File '" + file.name + " not found."); - break; - - case error.NOT_READABLE_ERR: - _notification("File '" + file.name + " not readable."); - break; - - case error.ABORT_ERR: - _notification("File '" + file.name + " operation was aborted."); - break; - - case error.SECURITY_ERR: - _notification("File '" + file.name + " is in a locked state."); - break; - - case error.ENCODING_ERR: - _notification("File '" + file.name + " encoding took too long."); - break; - - default: - _notification("File '" + file.name + " cannot be loaded."); - } - }; - - reader.onprogress = function (e) { - var percent = 0; - - if (e.lengthComputable) { - percent = Math.round((e.loaded * 100) / e.total); - - _notification("loading '" + file.name + "' " + percent + "%."); - } - }; - - reader.readAsArrayBuffer(file); -}; - -_audio_to_image_worker.addEventListener('message', function (m) { - if (m.data !== Object(m.data)) { - if ((typeof m.data) === "string") { - _notification(m.data, 10000); - } else { - _notification("Audio file conversion in progress : " + m.data + "%"); - } - return; - } - - var image_data = { - width: m.data.width, - height: m.data.height, - data: { - buffer: m.data.pbuffer - } - }; - - // now image processing step... - _imageDataToInput(image_data, { flip: false }); - - _notification("Audio file converted to " + image_data.width + "x" + image_data.height + "px image.") - }, false);/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _import_dropzone_elem = document.getElementById("fs_import_dropzone"); - -/*********************************************************** - Functions. -************************************************************/ - -var _fileChoice = function (cb) { - var detached_dialog = WUI_Dialog.getDetachedDialog(_import_dialog); - var input = detached_dialog ? detached_dialog.document.createElement("input") : document.createElement("input"); - - input.type = "file"; - input.multiple = true; - input.addEventListener("change", cb, false); - input.click(); -}; - -var _loadFile = function (type) { - return function (e) { - if (e === undefined) { - _fileChoice(_loadFile(type)); - - return; - } - - var target = e.target, - - files = target.files, - file, - - i = 0; - - if (files.length === 0) { - return; - } - - for (i = 0; i < files.length; i += 1) { - file = files[i]; - - if (file.type.match(type + '.*')) { - if (type === "image") { - _loadImageFromFile(file); - } else if (type === "audio") { - _loadAudioFromFile(file); - } else if (type === "video") { - _addFragmentInput("video", file); - if (_audio_import_settings.videotrack_import) { - _loadAudioFromFile(file); - } - } else { - _notification("Could not load the file '" + file.name + "', the filetype is unknown."); - } - } else { - _notification("Could not load the file '" + file.name + "' as " + type + "."); - } - } - - target.removeEventListener("change", _loadFile, false); - } -}; - -var _importDropzoneDrop = function (e) { - e.preventDefault(); - - var data = e.dataTransfer, - - file, - - i = 0; - - for (i = 0; i < data.files.length; i += 1) { - file = data.files[i]; - - if (file.type.match('image.*')) { - _loadImageFromFile(file); - } else if (file.type.match('audio.*')) { - _loadAudioFromFile(file); - } else if (file.type.match('video.*')) { - _addFragmentInput("video", file); - if (_audio_import_settings.videotrack_import) { - _loadAudioFromFile(file); - } - } else { - _notification("Could not load the file '" + file.name + "', the filetype is unknown."); - } - } - - e.target.style = ""; -}; - -var _createImportDropzone = function (element) { - element.addEventListener("drop", _importDropzoneDrop); - - element.addEventListener("dragleave", function (e) { - e.preventDefault(); - - e.target.style = ""; - }); - - element.addEventListener("dragover", function (e) { - e.preventDefault(); - - e.dataTransfer.dropEffect = "copy"; - }); - - element.addEventListener("dragenter", function (e) { - e.preventDefault(); - - e.target.style = "outline: dashed 1px #00ff00; background-color: #444444"; - }); -}; - -var _createImportListeners = function (doc) { - doc.getElementById("fs_import_audio_mapping").addEventListener('change', function (e) { - var mapping_type = e.target.value; - - _audio_import_settings.mapping = mapping_type; - }); - - doc.getElementById("fs_import_mic_fft_size").addEventListener('change', function (e) { - var fft_size = e.target.value; - - _audio_import_settings.fft_size = _parseInt10(fft_size); - }); - - doc.getElementById("fs_import_audio_ck_videotrack").addEventListener('change', function (e) { - var videotrack_import = this.checked; - - _audio_import_settings.videotrack_import = videotrack_import; - }); - - doc.getElementById("fs_import_audio_ck_phase").addEventListener('change', function (e) { - var phase_import = this.checked; - - _audio_import_settings.phase_import = phase_import; - }); -}; - -var _updateImportWidgets = function (doc) { - var current_doc = doc; - if (!doc) { - current_doc = document; - } - - // synchronize in case it was detached - current_doc.getElementById("fs_import_audio_mapping").value = _audio_import_settings.mapping; - current_doc.getElementById("fs_import_mic_fft_size").value = _audio_import_settings.fft_size; - current_doc.getElementById("fs_import_audio_ck_videotrack").checked = _audio_import_settings.videotrack_import; - current_doc.getElementById("fs_import_audio_ck_phase").checked = _audio_import_settings.phase_import; -}; - -/*********************************************************** - Init. -************************************************************/ - -_createImportDropzone(_import_dropzone_elem); - -_createImportListeners(document);/* jslint browser: true */ - -/** - * Manage graphics stuff. - */ - -var _main_program = null, - _main_attch0 = null, - _main_attch1 = null, - _main_fbo = null, - - _readSync = null, - - _generic_fragment_shader = [ - "precision mediump float;", - "uniform vec2 resolution;", - "uniform sampler2D texture;", - "void main () {", - " vec2 uv = gl_FragCoord.xy / resolution;", - " vec4 c = texture2D(texture, uv);", - " gl_FragColor = c;", - "}"].join(""); - -var _buildScreenAlignedQuad = function() { - var position; - - _quad_vertex_buffer = _gl.createBuffer(); - - _gl.bindBuffer(_gl.ARRAY_BUFFER, _quad_vertex_buffer); - _gl.bufferData(_gl.ARRAY_BUFFER, new Float32Array([-1, -1, 1, -1, -1, 1, 1, 1]), _gl.STATIC_DRAW); -}; - -var _createFramebuffer = function (texture, color_attachments) { - var framebuffer = _gl.createFramebuffer(), - buffers = [], - completeness_reason, - i; - - _gl.bindFramebuffer(_gl.FRAMEBUFFER, framebuffer); - - if (!color_attachments) { - _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, _gl.TEXTURE_2D, texture, 0); - } else { - - for (i = 0; i < color_attachments; i += 1) { - _gl.framebufferTexture2D(_gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0 + i, _gl.TEXTURE_2D, texture[i], 0); - - buffers.push(_gl.COLOR_ATTACHMENT0 + i); - } - - _gl.drawBuffers(buffers); - } - - completeness_reason = _gl.checkFramebufferStatus(_gl.FRAMEBUFFER); - - if (completeness_reason !== _gl.FRAMEBUFFER_COMPLETE) { - if (completeness_reason === _gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT) { - console.log("_createFramebuffer failed: incomplete attachment."); - } else if (completeness_reason === _gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) { - console.log("_createFramebuffer failed: incomplete mising attachment."); - } else if (completeness_reason === _gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS) { - console.log("_createFramebuffer failed: incomplete dimensions."); - } else if (completeness_reason === _gl.FRAMEBUFFER_UNSUPPORTED) { - console.log("_createFramebuffer failed: unsupported."); - } - - if (_gl2) { - if (completeness_reason === _gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE) { - console.log("_createFramebuffer failed: incomplete multisample."); - } else if (completeness_reason === _gl.RENDERBUFFER_SAMPLES) { - console.log("_createFramebuffer failed: renderbuffer samples."); - } - } - return null; - } - - _gl.bindFramebuffer(_gl.FRAMEBUFFER, null); - _gl.bindTexture(_gl.TEXTURE_2D, null); - - return framebuffer; -}; - -var _create2DTexture = function (image, default_wrap_filter, bind_now) { - var new_texture = _gl.createTexture(), - - ws = "clamp", - wt = "clamp", - - format = _gl.UNSIGNED_BYTE, - internal_format = _gl.RGBA; - - // WebGL 2 only - if (image.float) { - format = _gl.FLOAT; - - internal_format = _gl.RGBA32F; - } - - _gl.bindTexture(_gl.TEXTURE_2D, new_texture); - - if (!default_wrap_filter) { - if (!_OES_texture_float_linear && image.float) { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST); - } else { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR); - } - - if ((!_isPowerOf2(image.width) || !_isPowerOf2(image.height)) && !_gl2) { - _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); - - _notification("Non-power-of-2 image added, wrap mode is 'clamp' only.", 4000); - } - } - - if (image.empty) { - _gl.texImage2D(_gl.TEXTURE_2D, 0, internal_format, image.width, image.height, 0, _gl.RGBA, format, null); - } else { - if (bind_now) { - _gl.texImage2D(_gl.TEXTURE_2D, 0, internal_format, _gl.RGBA, format, image); - } - } - - _gl.bindTexture(_gl.TEXTURE_2D, null); - - return { image: image, texture: new_texture, wrap: { ws: ws, wt: wt} }; -}; - -var _replace2DTexture = function (image, texture) { - var data, - - filter_tex_parameter, - filter_wrap_s_parameter, - filter_wrap_t_parameter; - - _gl.bindTexture(_gl.TEXTURE_2D, texture); - - filter_tex_parameter = _gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER); - filter_wrap_s_parameter = _gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S); - filter_wrap_t_parameter = _gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T); - - _gl.deleteTexture(texture); - - data = _create2DTexture(image, true, true); - - _gl.bindTexture(_gl.TEXTURE_2D, data.texture); - - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, filter_tex_parameter); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, filter_tex_parameter); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, filter_wrap_s_parameter); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, filter_wrap_t_parameter); - - _gl.bindTexture(_gl.TEXTURE_2D, null); - - return data.texture; -}; - -var _setTextureFilter = function (texture, mode) { - _gl.bindTexture(_gl.TEXTURE_2D, texture); - - if (mode === "nearest") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST); - } else if (mode === "linear") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR); - } else if (mode === "mipmap") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.LINEAR); - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.LINEAR_MIPMAP_NEAREST); - - _gl.generateMipmap(_gl.TEXTURE_2D); - } - - _gl.bindTexture(_gl.TEXTURE_2D, null); -}; - -var _setTextureWrapS = function (texture, mode) { - _gl.bindTexture(_gl.TEXTURE_2D, texture); - - if (mode === "clamp") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE); - } else if (mode === "repeat") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.REPEAT); - } else if (mode === "mirror") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.MIRRORED_REPEAT); - } - - _gl.bindTexture(_gl.TEXTURE_2D, null); -}; - -var _setTextureWrapT = function (texture, mode) { - _gl.bindTexture(_gl.TEXTURE_2D, texture); - - if (mode === "clamp") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE); - } else if (mode === "repeat") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.REPEAT); - } else if (mode === "mirror") { - _gl.texParameteri(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.MIRRORED_REPEAT); - } - - _gl.bindTexture(_gl.TEXTURE_2D, null); -}; - -var _flipTexture = function (texture, image, done_cb) { - var tmp_canvas = document.createElement('canvas'), - tmp_canvas_context = tmp_canvas.getContext('2d'), - - image_element = document.createElement("img"); - - tmp_canvas.width = image.naturalWidth; - tmp_canvas.height = image.naturalHeight; - - tmp_canvas_context.translate(0, tmp_canvas.height); - tmp_canvas_context.scale(1, -1); - - tmp_canvas_context.drawImage(image, 0, 0); - - image_element.src = tmp_canvas.toDataURL(); - image_element.width = image.naturalWidth; - image_element.height = image.naturalHeight; - - image_element.onload = function () { - image_element.onload = null; - - done_cb(_replace2DTexture(image_element, texture)); - }; -}; - -var _flipYTexture = function (texture, flip) { - _gl.bindTexture(_gl.TEXTURE_2D, texture); - _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, flip); - _gl.bindTexture(_gl.TEXTURE_2D, null); -}; - -var _buildFeedback = function () { - var i = 0, j = 0, frame, fragment_shader, vertex_shader = document.getElementById("vertex-shader").text; - - if (_feedback.enabled) { - if (_feedback.program) { - _gl.deleteProgram(_program); - } - - if (_gl2) { - var predefined_fragment_code = [ - "#version 300 es\n", - "precision mediump float;", - "layout(location = 0) out vec4 synthOutput;", - "layout(location = 1) out vec4 fragColor;", - "uniform vec2 resolution;", - "uniform sampler2D synthInput;", - "uniform sampler2D colorInput;\n", - ].join(""); - - fragment_shader = predefined_fragment_code + document.getElementById("fragment-shader-buffer-2").text; - - vertex_shader = "#version 300 es\n" + document.getElementById("vertex-shader-2").text; - } else { - var predefined_fragment_code = [ - "precision mediump float;", - "uniform vec2 resolution;", - "uniform sampler2D texture;\n" - ].join(""); - fragment_shader = predefined_fragment_code + document.getElementById("fragment-shader-buffer").text; - } - - _feedback.program = _createAndLinkProgram( - _createShader(_gl.VERTEX_SHADER, vertex_shader), - _createShader(_gl.FRAGMENT_SHADER, fragment_shader) - ); - - if (!_feedback.program) { - _feedback.enabled = false; - - _notification("Could not enable feedback feature."); - - return; - } - - _useProgram(_feedback.program); - _gl.uniform2f(_gl.getUniformLocation(_feedback.program, "resolution"), _canvas.width, _canvas.height); - - for (i = 0; i < _feedback.pframe.length; i += 1) { - frame = _feedback.pframe[i]; - - if (frame.data) { - for (j = 0; j < frame.data.length; j += 1) { - if (frame.data[j].texture) { - _gl.deleteTexture(frame.data[j].texture); - } - } - } - - if (frame.buffer) { - _gl.deleteFramebuffer(frame.buffer); - } - } - - _feedback.pframe[0] = { data: [], buffer: null }; - _feedback.pframe[1] = { data: [], buffer: null }; - - if (!_gl2) { - _feedback.pframe[0].data[0] = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true }); - _feedback.pframe[0].buffer = _createFramebuffer(_feedback.pframe[0].data[0].texture); - - _feedback.pframe[1].data[0] = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true }); - _feedback.pframe[1].buffer = _createFramebuffer(_feedback.pframe[1].data[0].texture); - } else { - _feedback.pframe[0].data[0] = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true, float: true }); - _feedback.pframe[0].data[1] = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true, float: true }); - _feedback.pframe[0].buffer = _createFramebuffer([_feedback.pframe[0].data[0].texture, _feedback.pframe[0].data[1].texture], 2); - - _feedback.pframe[1].data[0] = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true, float: true }); - _feedback.pframe[1].data[1] = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true, float: true }); - _feedback.pframe[1].buffer = _createFramebuffer([_feedback.pframe[1].data[0].texture, _feedback.pframe[1].data[1].texture], 2); - } - } - - _compile(); -}; - -var _buildMainFBO = function () { - var float_textures = false; - - if (_gl2) { - if (_main_program) { - _gl.deleteProgram(_main_program); - } - - _main_program = _createAndLinkProgram( - _createShader(_gl.VERTEX_SHADER, document.getElementById("vertex-shader").text), - _createShader(_gl.FRAGMENT_SHADER, _generic_fragment_shader) - ); - - if (!_main_program) { - _notification("Could not enable multi-output feature."); - - return; - } - - _useProgram(_main_program); - _gl.uniform2f(_gl.getUniformLocation(_main_program, "resolution"), _canvas.width, _canvas.height); - - if (_main_attch0) { - _gl.deleteTexture(_main_attch0); - } - - if (_main_attch1) { - _gl.deleteTexture(_main_attch1); - } - - if (_main_fbo) { - _gl.deleteFramebuffer(_main_fbo); - } - - if (_EXT_color_buffer_float) { - float_textures = true; - } - - _main_attch0 = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true, float: float_textures }).texture; - _main_attch1 = _create2DTexture({ width: _canvas.width, height: _canvas.height, empty: true, float: float_textures }).texture; - _main_fbo = _createFramebuffer([_main_attch0, _main_attch1], 2); - } -}; - -var _transformData = function (slice_obj, data) { - var offset = 0, - i = 0, - j = 0; - - if (slice_obj.shift > 0) { - offset = slice_obj.shift * 4; - - data.copyWithin(offset, 0, _canvas_height_mul4 - offset); - - for (i = 0; i < offset; i += 1) { - data[i] = 0; - } - } else if (slice_obj.shift < 0) { - offset = -slice_obj.shift * 4; - - data.copyWithin(0, offset, _canvas_height_mul4 - offset); - - for (i = (_canvas_height_mul4 - offset); i < _canvas_height_mul4; i += 1) { - data[i] = 0; - } - } -}; - -var _drawTimeDomainSpectrum = function () { - var times = new Uint8Array(_analyser_node.frequencyBinCount), - bar_width = _analysis_canvas.width / times.length, - value = 0, - bar_height = 0, - i = 0; - - _analyser_node.getByteTimeDomainData(times); - - _analysis_canvas_ctx.fillStyle = 'black'; - - for (i = 0; i < times.length; i += 1) { - bar_height = _analysis_canvas.height * (times[i] / 256); - - _analysis_canvas_ctx.fillRect(i * bar_width, _analysis_canvas.height - bar_height - 1, 1, 1); - } -}; - -var _drawSpectrum = function () { - if (_is_analyser_node_connected) { - var freq_bin_length, - px_index = 0, - value = 0, - index = 0, - y = 0, - i = 0; - - if (!_fas.enabled) { - _analyser_node.getByteFrequencyData(_analyser_freq_bin); - } else { // TEMPORARY - return; - } - - freq_bin_length = _analyser_freq_bin.length; - - _analysis_canvas_tmp_ctx.drawImage(_analysis_canvas, 0, 0, _analysis_canvas.width, _analysis_canvas.height); - - for (i = 0; i < freq_bin_length; i += 1) { - if (_fas.enabled) { - //index = (_getFrequency(i) / _sample_rate * _analyser_freq_bin.length); - - px_index = Math.round(_getFrequency(i) / _sample_rate * _canvas_height) * 4; - value = Math.round((_data[px_index] + _data[px_index + 1]) / 2); - } else { - if (_analysis_log_scale) { - value = _analyser_freq_bin[_logScale(i, freq_bin_length)]; - } else { - value = _analyser_freq_bin[i]; - } - } - - y = Math.round(i / freq_bin_length * _analysis_canvas.height); - - if (_analysis_colored) { - _analysis_canvas_ctx.fillStyle = _spectrum_colors[value]; - } else { - value = (255 - value) + ''; - _analysis_canvas_ctx.fillStyle = 'rgb(' + value + ',' + value + ',' + value + ')'; - } - - _analysis_canvas_ctx.fillRect(_analysis_canvas.width - _analysis_speed, _analysis_canvas.height - y, _analysis_speed, _analysis_speed); - } - - _analysis_canvas_ctx.translate(-_analysis_speed, 0); - _analysis_canvas_ctx.drawImage(_analysis_canvas, 0, 0, _analysis_canvas.width, _analysis_canvas.height, 0, 0, _analysis_canvas.width, _analysis_canvas.height); - - _analysis_canvas_ctx.setTransform(1, 0, 0, 1, 0, 0); - } -}; - -var _allocateFramesData = function () { - var i = 0, j = 0; - - _data = []; - _prev_data = []; - _midi_data = []; - _prev_midi_data = []; - _osc_data = []; - _prev_osc_data = []; - - for (i = 0; i < _output_channels; i += 1) { - _midi_data.push(new _synth_data_array(_canvas_height_mul4)); - _prev_midi_data.push(new _synth_data_array(_canvas_height_mul4)); - } - - for (i = 0; i < _play_position_markers.length; i += 1) { - //for (j = 0; j < _output_channels; j += 1) { - _data.push(new _synth_data_array(_canvas_height_mul4)); - _prev_data.push(new _synth_data_array(_canvas_height_mul4)); - _osc_data.push(new _synth_data_array(_canvas_height_mul4)); - _prev_osc_data.push(new _synth_data_array(_canvas_height_mul4)); - //} - } -}; - -var _canvasRecord = function () { - var min_r = 255, max_r = 0, - min_g = 255, max_g = 0, - min_b = 255, max_b = 0, - - ro = 0, - go = 1, - bo = 2, - - slice, - - i = 0, j = 0, o = 0, m = 1, - - data, temp_data; - - if (_record) { - // merge all - temp_data = new Uint8ClampedArray(_canvas_height_mul4); - - if (_read_pixels_format === _gl.FLOAT) { - m = 255; - } - - if (_record_type === 0 || - _record_type === 1 || - _record_type === 2) { - for (i = 0; i < _play_position_markers.length; i += 1) { - slice = _play_position_markers[i]; - - for (j = 0; j <= _canvas_height_mul4; j += 1) { - temp_data[j] += (_record_slice_fn[_record_type](i,j) * m); - - temp_data[j] = Math.min(temp_data[j], 255); - } - } - } - - // midi - if (_record_type === 0 || _record_type === 3) { - for (i = 0; i < _output_channels; i += 1) { - for (j = 0; j <= _canvas_height_mul4; j += 1) { - temp_data[j] += (_record_slice_fn[_record_type](i,j) * m); - - temp_data[j] = Math.min(temp_data[j], 255); - } - } - } - - if (_record_opts.f !== _record_opts.default) { - data = _record_canvas_ctx.getImageData(_record_position, 0, 1, _record_canvas.height).data; - } else { - //data = new Uint8ClampedArray(_canvas_height_mul4 + 4); // with normalization - data = new Uint8ClampedArray(_canvas_height_mul4); - } - - for (i = 0; i < _canvas_height_mul4; i += 4) { - o = _canvas_height_mul4 - i - 4; - - data[o] = _record_opts.f(data[o], temp_data[i + ro]); - data[o + 1] = _record_opts.f(data[o + 1], temp_data[i + go]); - //data[o + 2] = _record_opts.f(data[o + 2], temp_data[i + bo]); - data[o + 3] = 255; -/* - min_r = Math.min(min_r, data[o]); - min_g = Math.min(min_g, data[o + 1]); - min_b = Math.min(min_b, data[o + 2]); - - max_r = Math.max(max_r, data[o]); - max_g = Math.max(max_g, data[o + 1]); - max_b = Math.max(max_b, data[o + 2]); -*/ - } -/* - // normalize, work but may introduce coherence issues with added data so disabled for now. - max_r = 255.0 / (max_r - min_r); - max_g = 255.0 / (max_g - min_g); - max_b = 255.0 / (max_b - min_b); - - for (i = 0; i < _canvas_height_mul4; i += 4) { - data[i] -= min_r; - data[i + 1] -= min_g; - data[i + 2] -= min_b; - - data[i] *= max_r; - data[i + 1] *= max_g; - data[i + 2] *= max_b; - } - - _record_slice_image.data.set(data.slice(0, _canvas_height_mul4 - 1)); -*/ - _record_slice_image.data.set(data); - - _record_canvas_ctx.putImageData(_record_slice_image, _record_position, 0); -/* - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input = _fragment_input_data[i]; - if (fragment_input.type === 2) { - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input.texture); - _gl.texSubImage2D(_gl.TEXTURE_2D, 0, 0, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, _record_canvas); - } - } -*/ - _record_position += 1; - if (_record_position > _canvas_width) { - _record_position = 0; - } - } -}; - -var _frame = function (raf_time) { - var i = 0, j = 0, o = 0, - - play_position_marker, - play_position_marker_x = 0, - - fragment_input, - - current_frame, - previous_frame, - - time_now = performance.now(), - - global_time = (raf_time - _time) / 1000, - - iglobal_time, - - target_data, - - date = new Date(), - - channel = 0, - channel_data, - - f, v, key, - - data, - - buffer = []; - - _MIDInotesUpdate(date); - - if (_feedback.enabled) { - current_frame = _feedback.pframe[_feedback.index]; - previous_frame = _feedback.pframe[(_feedback.index + 1) % 2]; - - _gl.bindFramebuffer(_gl.FRAMEBUFFER, current_frame.buffer); - _gl.viewport(0, 0, _canvas_width, _canvas_height); - - _useProgram(_program); - - o = _fragment_input_data.length; - - if (_gl2) { - _gl.activeTexture(_gl.TEXTURE0 + o); - _gl.bindTexture(_gl.TEXTURE_2D, previous_frame.data[0].texture); - _gl.uniform1i(_getUniformLocation("pFrameSynth", _program), o); - - _gl.activeTexture(_gl.TEXTURE0 + o + 1); - _gl.bindTexture(_gl.TEXTURE_2D, previous_frame.data[1].texture); - _gl.uniform1i(_getUniformLocation("pFrame", _program), o + 1); - } else { - _gl.activeTexture(_gl.TEXTURE0 + o); - _gl.bindTexture(_gl.TEXTURE_2D, previous_frame.data[0].texture); - _gl.uniform1i(_getUniformLocation("pFrame", _program), o); - } - - _feedback.index += 1; - _feedback.index = _feedback.index % 2; - } else { - _gl.bindFramebuffer(_gl.FRAMEBUFFER, _main_fbo); - _useProgram(_program); - } - - _gl.uniform4fv(_getUniformLocation("keyboard"), _keyboard.data); - - //_gl.useProgram(_program); - _gl.uniform1f(_getUniformLocation("globalTime"), global_time); - _gl.uniform1f(_getUniformLocation("octave"), _audio_infos.octaves); - _gl.uniform1f(_getUniformLocation("baseFrequency"), _audio_infos.base_freq); - _gl.uniform4f(_getUniformLocation("mouse"), _nmx, _nmy, _cnmx, _cnmy); - _gl.uniform4f(_getUniformLocation("date"), date.getFullYear(), date.getMonth(), date.getDay(), date.getSeconds()); - _gl.uniform1i(_getUniformLocation("frame", _program), _globalFrame); - - _pjsUpdateTexture(); - - // fragment inputs - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input = _fragment_input_data[i]; - - if (fragment_input.type === 0 || - fragment_input.type === 2) { // 2D texture from images - _gl.activeTexture(_gl.TEXTURE0 + i); - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input.texture); - _gl.uniform1i(_getUniformLocation(_input_channel_prefix + i), i); - } else if (fragment_input.type === 4) { // pjs - _gl.activeTexture(_gl.TEXTURE0 + i); - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input.texture); - _gl.uniform1i(_getUniformLocation(_input_channel_prefix + i), i); - - fragment_input.globalTime += 1; - } else if (fragment_input.type === 1 || - fragment_input.type === 3 || - fragment_input.type === 5) { // video/camera/desktop - if (fragment_input.video_elem.readyState === fragment_input.video_elem.HAVE_ENOUGH_DATA) { - if (fragment_input.type === 3) { - _gl.uniform1f(_getUniformLocation(_input_video_prefix + i), fragment_input.video_elem.currentTime / fragment_input.video_elem.duration); - } - - _gl.activeTexture(_gl.TEXTURE0 + i); - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input.texture); - _gl.uniform1i(_getUniformLocation(_input_channel_prefix + i), i); - - _gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, fragment_input.image); - } - } else if (fragment_input.type === 6) { // mic - fragment_input.analyzer_node.getByteFrequencyData(fragment_input.analysis_data); - - var canvas_ctx = fragment_input.canvas.getContext("2d"); - - canvas_ctx.drawImage(fragment_input.canvas, 0, 0, fragment_input.canvas.width, fragment_input.canvas.height); - - for (var y = 0; y < fragment_input.canvas.height; y += 1) { - var freq = _getFrequency(y); - - var bin_index = Math.round(freq * fragment_input.fft_size / _sample_rate); - - var color = Math.round(fragment_input.analysis_data[bin_index]); - - canvas_ctx.fillStyle = 'rgba(' + color + ',' + color + ',' + color + ',' + 1 + ')'; - canvas_ctx.fillRect(fragment_input.canvas.width - 1 - fragment_input.speed, y, fragment_input.speed, fragment_input.speed); - } - - canvas_ctx.translate(-fragment_input.speed, 0); - - canvas_ctx.drawImage(fragment_input.canvas, 0, 0, fragment_input.canvas.width, fragment_input.canvas.height, 0, 0, fragment_input.canvas.width, fragment_input.canvas.height); - - canvas_ctx.setTransform(1, 0, 0, 1, 0, 0); - - _gl.activeTexture(_gl.TEXTURE0 + i); - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input.texture); - _gl.uniform1i(_getUniformLocation(_input_channel_prefix + i), i); - - // update - _gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, _gl.RGBA, _gl.UNSIGNED_BYTE, fragment_input.canvas); - } - } - - //_gl.bindBuffer(_gl.ARRAY_BUFFER, _quad_vertex_buffer); - _gl.drawArrays(_gl.TRIANGLE_STRIP, 0, 4); - - if (_feedback.enabled) { - _gl.bindFramebuffer(_gl.FRAMEBUFFER, _main_fbo); - - _gl.viewport(0, 0, _canvas_width, _canvas_height); - _useProgram(_feedback.program); - - if (_main_fbo) { - _gl.activeTexture(_gl.TEXTURE0); - _gl.bindTexture(_gl.TEXTURE_2D, current_frame.data[0].texture); - _gl.uniform1i(_getUniformLocation("synthInput", _feedback.program), 0); - _gl.activeTexture(_gl.TEXTURE1); - _gl.bindTexture(_gl.TEXTURE_2D, current_frame.data[1].texture); - _gl.uniform1i(_getUniformLocation("colorInput", _feedback.program), 1); - } else { - _gl.activeTexture(_gl.TEXTURE0); - _gl.bindTexture(_gl.TEXTURE_2D, current_frame.data[0].texture); - _gl.uniform1i(_getUniformLocation("texture", _feedback.program), 0); - } - - _gl.drawArrays(_gl.TRIANGLE_STRIP, 0, 4); - } - - if (_main_fbo) { - _gl.bindFramebuffer(_gl.FRAMEBUFFER, null); - _gl.viewport(0, 0, _canvas_width, _canvas_height); - _useProgram(_main_program); - - _gl.activeTexture(_gl.TEXTURE0); - _gl.bindTexture(_gl.TEXTURE_2D, _main_attch1); - - _gl.uniform1i(_gl.getUniformLocation(_main_program, "texture"), 0); - - _gl.drawArrays(_gl.TRIANGLE_STRIP, 0, 4); - - _gl.bindFramebuffer(_gl.FRAMEBUFFER, _main_fbo); - } - - if (_play_position_markers.length > 0) { - if (_gl2) { - _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, _pbo); - _gl.bufferData(_gl.PIXEL_PACK_BUFFER, _pbo_size, _gl.STATIC_READ); - } - - // populate array first -/* - play_position_marker = _play_position_markers[0]; - - channel = play_position_marker.output_channel - 1; - - if (play_position_marker.mute) { - _data[channel] = new _synth_data_array(_canvas_height_mul4); - _midi_data[channel] = new _synth_data_array(_canvas_height_mul4); - } else { - if (play_position_marker.midi_out.device_uids.length === 0) { - target_data = _data[channel]; - } else { - target_data = _midi_data[channel]; - _midi_data[_output_channels + channel] = play_position_marker.midi_out; - } - - if (play_position_marker.frame_increment != 0) { - _setPlayPosition(play_position_marker.id, play_position_marker.x + play_position_marker.frame_increment, play_position_marker.y, false, true); - } - - play_position_marker_x = play_position_marker.x; - - if (_gl2) { - _gl.readPixels(play_position_marker_x, 0, 1, _canvas_height, _gl.RGBA, _read_pixels_format, 0); - _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, target_data); - } else { - _gl.readPixels(play_position_marker_x, 0, 1, _canvas_height, _gl.RGBA, _read_pixels_format, target_data); - } - - _transformData(play_position_marker, target_data); - } -*/ - - for (i = 0; i < _play_position_markers.length; i += 1) { - play_position_marker = _play_position_markers[i]; - - if (play_position_marker.mute) { - if (i === 0) { - _data[channel] = new _synth_data_array(_canvas_height_mul4); - _midi_data[channel] = new _synth_data_array(_canvas_height_mul4); - } - - continue; - } - - if (play_position_marker.frame_increment != 0) { - _setPlayPosition(play_position_marker.id, play_position_marker.x + play_position_marker.frame_increment, play_position_marker.y, false, true); - } - - play_position_marker_x = play_position_marker.x; - - channel = play_position_marker.output_channel - 1; - - if (_gl2) { - _gl.readPixels(play_position_marker_x, 0, 1, _canvas_height, _gl.RGBA, _read_pixels_format, 0); -/* - if (_gl.fenceSync) { - _readSync = _gl.fenceSync(_gl.SYNC_GPU_COMMANDS_COMPLETE, 0); - _gl.flush(); - var wait_status = _gl.clientWaitSync(_readSync, 0, 0); - - if (wait_status === _gl.CONDITION_SATISFIED || wait_status === _gl.ALREADY_SIGNALED) { - //_gl.deleteSync(_readSync); - continue; - } - } -*/ - _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, _temp_data); - } else { - _gl.readPixels(play_position_marker_x, 0, 1, _canvas_height, _gl.RGBA, _read_pixels_format, _temp_data); - } - - _transformData(play_position_marker, _temp_data); - - if (play_position_marker.audio_out) { - channel_data = _data[i]; - - for (j = 0; j < _canvas_height_mul4; j += 1) { - channel_data[j] = /*channel_data[j] + */_temp_data[j]; - } - } - - if (play_position_marker.osc_out) { - channel_data = _osc_data[i]; - - for (j = 0; j < _canvas_height_mul4; j += 1) { - channel_data[j] = /*channel_data[j] + */_temp_data[j]; - } - } - - if (play_position_marker.midi_out.enabled) { - if (play_position_marker.midi_out.device_uids.length > 0) { - channel_data = _midi_data[channel]; - _midi_data[_output_channels + channel] = play_position_marker.midi_out; - - for (j = 0; j < _canvas_height_mul4; j += 1) { - channel_data[j] = channel_data[j] + _temp_data[j]; - } - } - } - } - - for (i = 0; i < _play_position_markers.length; i += 1) { - buffer.push(new _synth_data_array(_canvas_height_mul4)); - } - - if (_show_oscinfos) { - var arr_infos = []; - for (j = 0; j < _play_position_markers.length; j += 1) { - var c = 0; - - for (i = 0; i < _canvas_height_mul4; i += 4) { - c += (_osc_data[j][i] > 0 || _osc_data[j][i + 1] > 0 || /*_midi_data[j][i] > 0 || _midi_data[j][i + 1] > 0 || */_data[j][i] > 0 || _data[j][i + 1] > 0); - } - - arr_infos.push(c); - } - - _osc_infos.textContent = arr_infos.join(" "); - } - - _canvasRecord(); - - // OSC - if (_osc.enabled) { - if (_osc.out) { - // make a copy of all channels again - var buffer_osc = []; - for (i = 0; i < _play_position_markers.length; i += 1) { - buffer_osc.push(new _synth_data_array(_osc_data[i])); - } - - // and prev_data - for (i = 0; i < _play_position_markers.length; i += 1) { - buffer_osc.push(new _synth_data_array(_prev_data[i])); - } - - _oscNotifyFast(_OSC_FRAME_DATA, buffer_osc); - - if (_fas.status) { - for (i = 0; i < _play_position_markers.length; i += 1) { - _prev_data[i] = new _synth_data_array(_data[i]); - } - } - } - } - - if (!_audio_off) { - if (_fas.status) { - _fasNotifyFast(_FAS_FRAME, _data); - } - } - - _data = buffer; - - // detached canvas (by a double click) TODO : Optimizations -/* - if (_detached_canvas_ctx) { - if (_gl2) { - _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, _pbo); - _gl.bufferData(_gl.PIXEL_PACK_BUFFER, _canvas_width * _canvas_height * 4, _gl.STATIC_READ); - _gl.readPixels(0, 0, _canvas_width, _canvas_height, _gl.RGBA, _gl.UNSIGNED_BYTE, 0); - _gl.getBufferSubData(_gl.PIXEL_PACK_BUFFER, 0, _detached_canvas_buffer); - } else { - _gl.readPixels(0, 0, _canvas_width, _canvas_height, _gl.RGBA, _gl.UNSIGNED_BYTE, _detached_canvas_buffer); - } - - for (i = 0; i < _detached_canvas_buffer.length; i += 4) { - _detached_canvas_buffer[i + 3] = 255; - } - - _detached_canvas_image_data.data.set(_detached_canvas_buffer); - - _detached_canvas_ctx.putImageData(_detached_canvas_image_data, 0, 0); - } -*/ - } - - if (_show_globaltime) { - iglobal_time = parseInt(global_time, 10); - if (parseInt(_time_infos.textContent, 10) !== iglobal_time) { - _time_infos.textContent = iglobal_time; - } - } - - if (_show_polyinfos) { - _poly_infos_element.textContent = _keyboard.polyphony; - } - - _globalFrame += 1; - - _MIDInotesCleanup(); - - _midiDataOut(_midi_data); - - _raf = window.requestAnimationFrame(_frame); -}; -/* jslint browser: true */ - - -/*********************************************************** - Fields. -************************************************************/ - -var _uniform_location_cache = {}, - _current_program, - - _glsl_compile_timeout = null, - - _glsl_parser_worker = new Worker("dist/worker/parse_glsl.min.js"); - - -/*********************************************************** - Functions. -************************************************************/ - -var _parseGLSL = function (target, glsl_code) { - _glsl_parser_worker.postMessage({ - target: target, - code: glsl_code - }); -}; - -var _createAndLinkProgram = function (vertex_shader, fragment_shader) { - if (!vertex_shader || !fragment_shader) { - return; - } - - var prog = _gl.createProgram(); - - _gl.attachShader(prog, vertex_shader); - _gl.attachShader(prog, fragment_shader); - - _gl.linkProgram(prog); - - if (!_gl.getProgramParameter(prog, _gl.LINK_STATUS)) { - _fail("Failed to link program: " + _gl.getProgramInfoLog(prog)); - } - - _gl.deleteShader(vertex_shader); - _gl.deleteShader(fragment_shader); - - return prog; -}; - -var _createShader = function (shader_type, shader_code) { - var shader = _gl.createShader(shader_type), - - parse_result, - - container, - elem, - - log, i = 0; - - _gl.shaderSource(shader, shader_code); - _gl.compileShader(shader); - - if (!_gl.getShaderParameter(shader, _gl.COMPILE_STATUS)) { - log = _gl.getShaderInfoLog(shader); - - parse_result = _parseCompileOutput(log); - - container = document.createElement("div"); - - container.innerHTML = 'Compilation errors\n'; - - for (i = 0; i < parse_result.length; i += 1) { - elem = document.createElement("span"); - elem.classList.add("fs-shader-error"); - elem.innerHTML = " " + parse_result[i].target + " " + parse_result[i].line + ": " + parse_result[i].msg + "\n"; - - container.appendChild(elem); - } - - if (_cm_show_osderrors) { - _fail(container); - } - - _gl.deleteShader(shader); - - shader = false; - } - - return shader; -}; - -var _useProgram = function (program) { - if (_current_program !== program) { - _gl.useProgram(program); - _current_program = program; - } -}; - -var _getUniformLocation = function (name, program) { - var prog = _program; - - if (!_uniform_location_cache[name]) { - if (program !== undefined) { - prog = program; - } - - _uniform_location_cache[name] = _gl.getUniformLocation(prog, name); - } - - return _uniform_location_cache[name]; -}; - -var _setUniform = function (gl_ctx, type_str, program, name, value) { - var uniform_location = _getUniformLocation(name, program); - - if (type_str === "bool" || type_str === "int" || type_str === "uint") { - gl_ctx.uniform1i(uniform_location, value); - } else if (type_str === "float") { - gl_ctx.uniform1f(uniform_location, value); - } -}; - -var _setUniforms = function (gl_ctx, type_str, program, name, values, comps) { - var uniform_location = _getUniformLocation(name, program); - - if (type_str === "bool" || - type_str === "int" || - type_str === "uint") { - gl_ctx.uniform1iv(uniform_location, new Int32Array(values)); - } else if (type_str === "float") { - gl_ctx.uniform1fv(uniform_location, new Float32Array(values)); - } else { - if (type_str === "bvec" || - type_str === "ivec" || - type_str === "uvec") { - if (comps === 2) { - gl_ctx.uniform2iv(uniform_location, new Int32Array(values)); - } else if (comps === 3) { - gl_ctx.uniform3iv(uniform_location, new Int32Array(values)); - } else if (comps === 4) { - gl_ctx.uniform4iv(uniform_location, new Int32Array(values)); - } - } else if (type_str === "vec") { - if (comps === 2) { - gl_ctx.uniform2fv(uniform_location, new Float32Array(values)); - } else if (comps === 3) { - gl_ctx.uniform3fv(uniform_location, new Float32Array(values)); - } else if (comps === 4) { - if (values.length > 0) { - gl_ctx.uniform4fv(uniform_location, new Float32Array(values)); - } - } - } - } -}; - -var _glsl_compilation = function () { - var frag, - - glsl_code = "", - glsl_code_to_compile = "", - - vertex_shader_code, - - example_code_editor = _code_editors[2], - - // library code + main code - library_code = (_current_code_editor === example_code_editor) ? '' : _code_editors[1].editor.getValue(), - main_code = (_current_code_editor === example_code_editor) ? example_code_editor.editor.getValue() : _code_editors[0].editor.getValue(), - editor_value = library_code + "\n" + main_code, - - position, - - fragment_input, - - ctrl_name, - ctrl_obj, - ctrl_obj_uniform, - ctrl_arr, - - temp_program, - - i = 0; - - // some minor changes when using WebGL 2 & GLSL 3 - if (_gl2) { - glsl_code += "#version 300 es\nprecision mediump float;layout(location = 0) out vec4 synthOutput;layout(location = 1) out vec4 fragColor;"; - - editor_value = editor_value.replace(/gl_FragColor/g, "fragColor"); - editor_value = editor_value.replace(/texture2D/g, "texture"); - - vertex_shader_code = "#version 300 es\n" + document.getElementById("vertex-shader-2").text; - } else { - glsl_code += "precision mediump float;"; - editor_value = editor_value.replace(/texture/g, "texture2D"); - editor_value = editor_value.replace(/fragColor/g, "gl_FragColor"); - editor_value = editor_value.replace(/synthOutput.*;/g, ""); - - vertex_shader_code = document.getElementById("vertex-shader").text; - } - - // add inputs uniforms - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input = _fragment_input_data[i]; - - if (fragment_input) { - if (fragment_input.type === 0 || - fragment_input.type === 1 || - fragment_input.type === 2 || - fragment_input.type === 4 || - fragment_input.type === 5 || - fragment_input.type === 6 || - fragment_input.type === 404) { // 2D texture from either image, webcam, canvas, pjs - glsl_code += "uniform sampler2D " + _input_channel_prefix + "" + i + ";"; - } else if (fragment_input.type === 3) { // video type - glsl_code += "uniform sampler2D " + _input_channel_prefix + "" + i + ";" + " uniform float " + _input_video_prefix + "" + i + ";"; - } - } - } - - if (_feedback.enabled) { - if (_gl2) { - glsl_code += "uniform sampler2D pFrame; uniform sampler2D pFrameSynth;"; - } else { - glsl_code += "uniform sampler2D pFrame;"; - } - } - - // add our uniforms - glsl_code += "uniform float globalTime; uniform int frame; uniform float octave; uniform float baseFrequency; uniform vec4 mouse; uniform vec4 date; uniform vec2 resolution; uniform vec4 keyboard[" + _keyboard.polyphony_max + "]; uniform vec3 pKey[" + 16 + "];" - - // add htoy - glsl_code += "float htoy(float frequency) {return resolution.y - (resolution.y - (log(frequency / baseFrequency) / log(2.)) * floor(resolution.y / octave + 0.5));}"; // round(resolution.y / octave) - - // add fline - glsl_code += "float fline(float frequency) {return step(abs(gl_FragCoord.y - htoy(frequency)), 0.5);}"; - - // add yfreq - glsl_code += "float yfreq(float y, float sample_rate) { return (baseFrequency * pow(2., (resolution.y - floor((y * resolution.y) + 0.5)) / octave)) / sample_rate; }"; - - // inputs uniform from OSC - for (ctrl_name in _osc.inputs) { - ctrl_arr = _osc.inputs[ctrl_name]; - - glsl_code += "uniform " + ((ctrl_arr.comps !== undefined) ? ctrl_arr.type + ctrl_arr.comps : ctrl_arr.type) + " " + ctrl_name + ((ctrl_arr.count > 1) ? "[" + ctrl_arr.count + "]" : "") + ";"; - } - - // add user fragment code - glsl_code += "\n" + editor_value; - - temp_program = _createAndLinkProgram( - _createShader(_gl.VERTEX_SHADER, vertex_shader_code), - _createShader(_gl.FRAGMENT_SHADER, glsl_code) - ); - - if (temp_program) { - if (_current_code_editor.index < 2) { - _parseGLSL(1, library_code); - _parseGLSL(0, main_code); - } - - _gl.deleteProgram(_program); - - _program = temp_program; - - _uniform_location_cache = {}; - - _fail(""); - - _clearCodeMirrorWidgets(); - - _useProgram(_program); - - _gl.uniform2f(_gl.getUniformLocation(_program, "resolution"), _canvas.width, _canvas.height); - - _setUniforms(_gl, "vec", _program, "keyboard", _keyboard.data, _keyboard.data_components); - - for (ctrl_name in _osc.inputs) { - ctrl_arr = _osc.inputs[ctrl_name]; - - _setUniforms(_gl, ctrl_arr.type, _program, ctrl_name, ctrl_arr.data, ctrl_arr.comps); - } - - if (_gl2) { - _gl.bindBuffer(_gl.ARRAY_BUFFER, _quad_vertex_buffer); - } - - position = _gl.getAttribLocation(_program, "position"); - - _gl.enableVertexAttribArray(position); - _gl.vertexAttribPointer(position, 2, _gl.FLOAT, false, 0, 0); - - if (_glsl_error) { - _glsl_error = false; - - if (_fs_state === 0) { - _play(false); - } - } - } else { - _glsl_error = true; - } -}; - -var _compile = function () { - clearTimeout(_glsl_compile_timeout); - - _glsl_compile_timeout = setTimeout(_glsl_compilation, _compile_delay_ms); -}; - -var setCursorCb = function (code_editor, position) { - return function () { - _showWorkspace("fs-workspace-item", code_editor.index)(); - - code_editor.editor.setCursor({ line: position.start.line - 1, ch: position.start.column }); - - var i = 0; - for (i = 0; i < code_editor.detached_windows.length; i += 1) { - var detached_window = code_editor.detached_windows[i]; - if (detached_window) { - detached_window.cm.setCursor({ line: position.start.line - 1, ch: position.start.column }); - } - } - }; -}; - -var _updateOutline = function (code_editor_index) { - var i = 0, j = 0, - statement, - - tmp, - param, - - code_editor = _code_editors[code_editor_index], - outline_element = code_editor.outline.element(), - outline_data = code_editor.outline.data, - - elem; - - outline_element.innerHTML = ""; - - for (i = 0; i < outline_data.length; i += 1) { - statement = outline_data[i]; - - if (statement.type === "function") { - elem = document.createElement("div"); - - elem.className = "fs-outline-item fs-outline-function"; - - tmp = []; - for (j = 0; j < statement.parameters.length; j += 1) { - param = statement.parameters[j]; - - tmp.push('' + param.type_name + " " + param.name); - } - - elem.innerHTML = '' + statement.returnType.name + " " + statement.name + " (" + tmp.join(", ") + ")"; - elem.title = "line: " + statement.position.start.line; - - outline_element.appendChild(elem); - - elem.addEventListener("click", setCursorCb(code_editor, statement.position)); - } else if (statement.type === "declarator") { - elem = document.createElement("div"); - - elem.className = "fs-outline-item fs-outline-declarator"; - - elem.innerHTML = '' + statement.returnType + " " + statement.name; - elem.title = "line: " + statement.position.start.line; - - outline_element.appendChild(elem); - - elem.addEventListener("click", setCursorCb(code_editor, statement.position)); - } else if (statement.type === "preprocessor") { - elem = document.createElement("div"); - - elem.className = "fs-outline-item fs-outline-preprocessor"; - - elem.innerHTML = statement.name + " = " + statement.value; - elem.title = "line: " + statement.position.start.line; - - outline_element.appendChild(elem); - - elem.addEventListener("click", setCursorCb(code_editor, statement.position)); - } - } - - var line = null; - for (i = 0; i < code_editor.marks.length; i += 1) { - line = code_editor.editor.getLineNumber(code_editor.marks[i]); - - elem = document.createElement("div"); - - elem.className = "fs-outline-item fs-outline-mark"; - - var outline_entry = code_editor.editor.getLine(line).trim(); - - if (outline_entry.indexOf("//") !== -1) { - outline_entry = outline_entry.replace(/.*\/\//g, '').trim().toUpperCase(); - } - - elem.innerHTML = outline_entry; - elem.title = "line: " + (line + 1); - - outline_element.appendChild(elem); - - elem.addEventListener("click", setCursorCb(code_editor, { start: { line: line + 2, column: 0 }})); - } -}; - -_glsl_parser_worker.onmessage = function(m) { - var code_editor_target = m.data.target; - - _code_editors[code_editor_target].outline.data = m.data.outline_data.slice(); - - _updateOutline(code_editor_target); -}; - -/*********************************************************** - Init. -************************************************************/ - -var _initOutline = function () { - var i = 0; - var outline_elements = document.getElementsByClassName("fs-outline"); - for (i = 0; i < outline_elements.length; i += 1) { - var outline_element = outline_elements[i]; - - var outline_fieldset = outline_element.parentElement; - var outline_fieldset_legend = outline_fieldset.firstElementChild; - - _applyCollapsible(outline_fieldset, outline_fieldset_legend, true); - } -};/* jslint browser: true */ - - -/*********************************************************** - Fields. -************************************************************/ - -var _socket, - - _fss_ws, - _fsync_ws, - - _address_fss = _domain + ":3001", - _address_sdb = _domain + ":3002", - _address_fsync = _domain + ":3100", - - _session, - - _share_ctrl_timeout, - _share_settings_timeout, - - _sharedb_timeout, - - _sharedb_connection, - _sharedb_doc, - _sharedb_doc_ready = false, - - _sharedb_ctrl_doc_ready = false, - - _sharedb_code_changes = [], - - _sharedb_ctrl_doc, - - _sync_client; - -/*********************************************************** - Functions. -************************************************************/ - -var _sharedbDocError = function (err) { - _notification(err, 5000); -}; - -var _subscribeSharedbEditor = function (code_editor) { - return function(err) { - if (err) { - _notification(err, 5000); - } - - if (!code_editor.sharedb.doc.data) { - code_editor.sharedb.doc.create(code_editor.editor.getValue()); - } else { - code_editor.editor.setValue(code_editor.sharedb.doc.data); - } - - _loadEditorsMarks(code_editor); - - code_editor.sharedb.doc.on('op', function(op, source) { - var i = 0, j = 0, - from, - to, - operation, - o; - - if (source === false) { // only changes from the server - for (i = 0; i < op.length; i += 1) { - operation = op[i]; - - for (j = 0; j < operation.o.length; j += 1) { - o = operation.o[j]; - - if (o["d"] !== undefined) { - from = code_editor.editor.posFromIndex(o.p); - to = code_editor.editor.posFromIndex(o.p + o.d.length); - code_editor.editor.replaceRange("", from, to, "remote"); - } else if (o["i"] !== undefined) { - from = code_editor.editor.posFromIndex(o.p); - code_editor.editor.replaceRange(o.i, from, from, "remote"); - } else { - _notification("Unknown operation type."); - } - } - } - } - }); - - code_editor.sharedb.rdy = true; - }; -}; - -var _shareDBConnect = function () { - var ws = new WebSocket(_ws_protocol + "://" + _address_sdb); - - ws.addEventListener("open", function (ev) { - var fs_sync = document.getElementById("fs_sync_status"); - - fs_sync.classList.add("fs-server-status-on"); - }); - - ws.addEventListener("close", function (ev) { - _sharedb_doc_ready = false; - _sharedb_ctrl_doc_ready = false; - - _notification("Data server connection lost, trying again in ~5s.", 2500); - - clearTimeout(_sharedb_timeout); - _sharedb_timeout = setTimeout(_shareDBConnect, 5000); - - var fs_sync = document.getElementById("fs_sync_status"); - - fs_sync.classList.remove("fs-server-status-on"); - }); - - ws.addEventListener("error", function (event) { - - }); - - _sharedb_connection = new ShareDB.Connection(ws); - - // get all collaborative editors document - var i = 0; - for (i = 0; i < _code_editors.length; i += 1) { - var code_editor = _code_editors[i]; - - if (!code_editor.collaborative) { - continue; - } - - code_editor.sharedb.doc = _sharedb_connection.get("_" + _session, "code_" + code_editor.name); - - code_editor.sharedb.doc.on('error', _sharedbDocError); - - code_editor.sharedb.doc.subscribe(_subscribeSharedbEditor(code_editor)); - } - - // document for session settings - _sharedb_ctrl_doc = _sharedb_connection.get("_" + _session, "ctrls"); - _sharedb_ctrl_doc.on('error', _sharedbDocError); - - _sharedb_ctrl_doc.subscribe(function(err) { - var i = 0, - - s; - - if (err) { - _notification(err, 5000); - } - - if (!_sharedb_ctrl_doc.data) { - _sharedb_ctrl_doc.create({ score_settings: [] }); - } else { - if (_sharedb_ctrl_doc.data.score_settings.length === 4) { - _updateScore({ - width: parseInt(_sharedb_ctrl_doc.data.score_settings[0], 10), - height: parseInt(_sharedb_ctrl_doc.data.score_settings[1], 10), - octave: parseInt(_sharedb_ctrl_doc.data.score_settings[2], 10), - base_freq: parseFloat(_sharedb_ctrl_doc.data.score_settings[3]) - }); - } - } - - _sharedb_ctrl_doc.on('op', function(op, source) { - var i = 0, - operation; - - if (source === false) { // only changes from the server - for (i = 0; i < op.length; i += 1) { - operation = op[i]; - - if (operation["ld"] && operation["li"] && operation["p"]) { - if (operation.p[0] === "score_settings") { - if (operation.p[1] === 0) { - _updateScore({ - width: parseInt(operation.li, 10) - }); - } else if (operation.p[1] === 1) { - _updateScore({ - height: parseInt(operation.li, 10) - }); - } else if (operation.p[1] === 2) { - _updateScore({ - octave: parseInt(operation.li, 10) - }); - } else if (operation.p[1] === 3) { - _updateScore({ - base_freq: parseFloat(operation.li) - }); - } - } - } - } - } - }); - - _sharedb_ctrl_doc_ready = true; - - }); -}; - -var _prepareMessage = function (type, obj) { - obj.type = type; - - return JSON.stringify(obj); -}; - -/* -// used to sync local clock to fss server clock for the globalTime -// https://github.com/collective-soundworks/sync -var _timeSyncInit = function () { - _sync_client = new SyncClient(_getTimeFunction); - - var timeSyncSendFn = function (pingId, clientPingTime) { - //console.log(`[ping] - id: %s, pingTime: %s`, pingId, clientPingTime); - _fss_ws.send(_prepareMessage("timeSync", { session: _session, id: pingId, time: clientPingTime })); - }; - - var timeSyncReceiveFn = function (callback) { - _fss_ws.addEventListener('message', function (event) { - var msg = JSON.parse(event.data); - - if (msg.type === "timeSync") { - var pingId = msg.id; - var clientPingTime = msg.clientTime; - var serverPingTime = msg.serverTime; - var serverPongTime = msg.serverPongTime; - //console.log(`[pong] - id: %s, clientPingTime: %s, serverPingTime: %s, serverPongTime: %s`, pingId, clientPingTime, serverPingTime, serverPongTime); - callback(pingId, clientPingTime, serverPingTime, serverPongTime); - } - }); - }; - - var timeSyncStatusFn = function (status) { - // JSON.stringify(status, null, 2); - console.log(status); - }; - - _sync_client.start(timeSyncSendFn, timeSyncReceiveFn, timeSyncStatusFn); -}; - -var _timeSyncReset = function () { - if (_fss_ws) { - _fss_ws.send(_prepareMessage("timeSyncReset", { session: _session })); - } -}; - -var _timeSyncDelete = function () { - if (_fss_ws) { - _fss_ws.send(_prepareMessage("timeSyncDelete", { session: _session })); - } -}; - -var _fsyncConnect = function () { - _fsync_ws = new WebSocket(_ws_protocol + "://" + _address_fsync); - - _fsync_ws.onopen = function (event) { - _setUsersList([]); - - var fs_server = document.getElementById("fs_fsync_status"); - - fs_server.classList.add("fs-server-status-on"); - - _fsync_ws.send(_prepareMessage("session", { session: _session, username: _username })); - - _timeSyncInit(); - }; - - _fsync_ws.onerror = function (event) { - - }; - - _fsync_ws.onclose = function (event) { - setTimeout(_fsyncConnect, 5000); - - _notification("Sync. server connection lost, trying again in ~5s.", 2500); - - var fs_server = document.getElementById("fs_fsync_status"); - - fs_server.classList.remove("fs-server-status-on"); - - _sync_client = null; - }; -}; -*/ - -var _fssConnect = function () { - _fss_ws = new WebSocket(_ws_protocol + "://" + _address_fss); - - _fss_ws.onopen = function (event) { - _setUsersList([]); - - var fs_server = document.getElementById("fs_server_status"); - - fs_server.classList.add("fs-server-status-on"); - - _fss_ws.send(_prepareMessage("session", { session: _session, username: _username })); - }; - - _fss_ws.addEventListener('message', function (event) { - var i = 0, msg; - - try { - msg = JSON.parse(event.data); - if (msg.type === "users") { - _setUsersList(msg.list); - } else if (msg.type === "userjoin") { - _addUser(msg.userid, msg.username); - } else if (msg.type === "userleave") { - _removeUser(msg.userid); - } else if (msg.type === "msg") { - _addMessage(msg.userid, msg.data); - } else if (msg.type === "addSlice") { - _addPlayPositionMarker(msg.data.x, msg.data.shift, msg.data.mute, msg.data.output_channel, msg.data.type, msg.instruments_settings); - } else if (msg.type === "delSlice") { - _removePlayPositionMarker(msg.data.id); - } else if (msg.type === "updSlice") { - _updatePlayMarker(msg.data.id, msg.data.obj); - } else if (msg.type === "slices") { - _removeAllSlices(); - for (i = 0; i < msg.data.length; i += 1) { - _addPlayPositionMarker(msg.data[i].x, msg.data[i].shift, msg.data[i].mute, msg.data[i].output_channel, msg.data[i].type, msg.data[i].instruments_settings); - } - } - } catch (e) { - _notification('JSON message parsing failed : ' + e, 3500); - - console.log(e); - } - }); - - _fss_ws.onerror = function (event) { - - }; - - _fss_ws.onclose = function (event) { - _removeUsers(); - - setTimeout(_fssConnect, 5000); - - _notification("Server connection lost, trying again in ~5s.", 2500); - - var fs_server = document.getElementById("fs_server_status"); - - fs_server.classList.remove("fs-server-status-on"); - }; -}; - -var _sendSlices = function (data) { - try { - _fss_ws.send(_prepareMessage("slices", { data: data })); - } catch (err) { - - } -}; - -var _sendSliceUpdate = function (id, data) { - try { - _fss_ws.send(_prepareMessage("updSlice", { data: { id: id, obj: data } })); - } catch (err) { - - } -}; - -var _sendAddSlice = function (x, shift, mute) { - try { - _fss_ws.send(_prepareMessage("addSlice", { data: { x: x, shift: shift, mute: mute } })); - } catch (err) { - - } -}; - -var _sendRemoveSlice = function (id) { - try { - _fss_ws.send(_prepareMessage("delSlice", { data: { id: id } })); - } catch (err) { - - } -}; - -var _sendMessage = function (message) { - try { - _fss_ws.send(_prepareMessage("msg", { data: message })); - } catch (err) { - _notification("An error occured whuile trying to send the message."); - } -}; - -var _shareSettingsUpdFn = function (settings) { - return function () { - var op = [{ p: ['score_settings', 0], ld: settings[0], li: settings[1] }, - { p: ['score_settings', 1], ld: settings[2], li: settings[3] }, - { p: ['score_settings', 2], ld: settings[4], li: settings[5] }, - { p: ['score_settings', 3], ld: settings[6], li: settings[7] }]; - - _sharedb_ctrl_doc.submitOp(op); - }; -}; - -var _shareSettingsUpd = function (settings) { - if (!_sharedb_ctrl_doc_ready) { - return; - } - - clearTimeout(_share_settings_timeout); - _share_settings_timeout = setTimeout(_shareSettingsUpdFn(settings), 500); -}; - -var _shareCodeEditorChanges = function (code_editor, changes) { - var op, - change, - start_pos, - chars, - - i = 0, j = 0; - - if (!code_editor.sharedb.rdy) { - return; - } - - // we must do it in order (this avoid issue with same-time op) - //changes.reverse(); - - for (i = 0; i < changes.length; i += 1) { - op = { - p: [], - t: "text0", - o: [] - }; - - change = changes[i]; - start_pos = 0; - j = 0; - - if (change.origin === "remote") { // do not submit back things pushed by remotes - continue; - } - - while (j < change.from.line) { - start_pos += code_editor.editor.lineInfo(j).text.length + 1; - j += 1; - } - - start_pos += change.from.ch; - - if (change.to.line != change.from.line || change.to.ch != change.from.ch) { - chars = ""; - - for (j = 0; j < change.removed.length; j += 1) { - chars += change.removed[j]; - - if (j !== (change.removed.length - 1)) { - chars += "\n"; - } - } - - op.o.push({ - p: start_pos, - d: chars - }); - } - - if (change.text) { - op.o.push({ - p: start_pos, - i: change.text.join('\n') - }); - } - - if (op.o.length > 0) { - code_editor.sharedb.doc.submitOp(op); - } - } -}; - -/*********************************************************** - Init. -************************************************************/ - -var _initNetwork = function () { - _session = _getSessionName(); - - _fssConnect(); - _shareDBConnect(); -}; -/* jslint browser: true */ - - -/* - Simple discussions window -*/ - -/*********************************************************** - Fields. -************************************************************/ - -var _discuss_dialog_id = "fs_right_dialog", - _right_dialog, - - _discuss_input = document.getElementById("fs_discuss_input"); - -/*********************************************************** - Functions. -************************************************************/ - -var _getUserListElement = function () { - return document.getElementById("fs_users_list"); -}; - -var _addUser = function (id, name, hex_color, bold) { - var users_list_element = _getUserListElement(), - li = document.createElement("li"), - detached_dialog = WUI_Dialog.getDetachedDialog(_discuss_dialog_id); - - li.innerHTML = name; - li.id = "user" + id; - - if (id === "self") { - li.title = "You!"; - } else { - li.title = name; - } - - if (hex_color) { - li.style.color = hex_color; - } - - if (bold) { - li.style.fontWeight = "bold"; - } - - users_list_element.appendChild(li); - - if (detached_dialog) { - detached_dialog.document.getElementById("fs_users_list").appendChild(li.cloneNode(true)); - } -}; - -var _removeUser = function (id) { - var user_li = document.getElementById("user" + id), - detached_user_li, - detached_dialog = WUI_Dialog.getDetachedDialog(_discuss_dialog_id); - - if (detached_dialog) { - detached_user_li = detached_dialog.document.getElementById("user" + id); - - detached_user_li.parentElement.removeChild(detached_user_li); - } - - user_li.parentElement.removeChild(user_li); -}; - -var _setUsersList = function (list) { - var users_list_element = _getUserListElement(), - detached_dialog = WUI_Dialog.getDetachedDialog(_discuss_dialog_id), - detached_dialog_list_element, - li, - i; - - users_list_element.innerHTML = ""; - - _addUser("self", _username, "#adff2f", false); - - for (i = 0; i < list.length; i += 1) { - li = document.createElement("li"); - li.innerHTML = list[i].username; - li.id = "user" + list[i].userid; - - users_list_element.appendChild(li); - } - - if (detached_dialog) { - detached_dialog_list_element = detached_dialog.document.getElementById("fs_users_list"); - - detached_dialog_list_element.parentElement.removeChild(detached_dialog_list_element); - - detached_dialog_list_element.parentElement.appendChild(users_list_element.cloneNode(true)); - } -}; - -var _removeUsers = function () { - _setUsersList([]); - - _removeUser("self"); -}; - -var _addMessage = function (userid, data) { - var discuss_element = document.getElementById("fs_discuss"), - user_li = document.getElementById("user" + userid), - li = document.createElement("li"), - detached_discuss_element, - - date_now = new Date(), - - detached_dialog; - - li.title = date_now.toLocaleString(); - li.innerHTML = "<" + user_li.innerHTML + "> " + data; - - if (userid === "self") { - li.style.color = "#adff2f"; - } else { - _notification(li.innerHTML); - } - - discuss_element.appendChild(li); - - detached_dialog = WUI_Dialog.getDetachedDialog(_discuss_dialog_id); - if (detached_dialog) { - detached_discuss_element = detached_dialog.document.getElementById("fs_discuss"); - - detached_discuss_element.appendChild(li.cloneNode(true)); - detached_discuss_element.scrollTop = detached_discuss_element.scrollHeight; - } - - discuss_element.scrollTop = discuss_element.scrollHeight; -}; - -var _chatKeypress = function (e) { - if (e.which === 13 || e.keyCode === 13) { - if (e.target.value.length <= 0) { - return true; - } - - _sendMessage(e.target.value); - - e.target.value = ""; - - return false; - } - - return true; -}; - -/*********************************************************** - Init. -************************************************************/ - -_right_dialog = WUI_Dialog.create(_discuss_dialog_id, { - title: "Chat - Session '" + _getSessionName() + "'", - width: "600px", - height: "300px", - halign: "right", - valign: "bottom", - - open: false, - - closable: true, - draggable: true, - minimizable: true, - resizable: true, - detachable: true, - - min_width: 300, - min_height: 200 -}); - -_setUsersList([]); - -_discuss_input.addEventListener("keypress", _chatKeypress);/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _pvx = 0, - _pvy = 0, - - _paint_start_time = 0, - - _paint_lock_x = false, - _paint_lock_y = false, - - _paint_delay = 0, - _paint_random = false, - - _paint_brush = null, - _paint_mode = "source-over", - _paint_scalex = 0.15, - _paint_scaley = 0.15, - _paint_opacity = 0.25, - _paint_angle = 0; - -/*********************************************************** - Functions. -************************************************************/ - -var _paint = function (ctx, brush, mode, x, y, scale_x, scale_y, angle, opacity) { - var brush_width, - brush_height, - brush_width_d2, - brush_height_d2, - drawing_x, - drawing_y, - xinc, - yinc, - step, - dx, - dy, - - i = 0; - - if (_paint_delay !== 0) { - if ((performance.now() - _paint_start_time) > _paint_delay) { - _draw(ctx, brush, mode, x, y, scale_x, scale_y, angle, opacity); - - _paint_start_time = performance.now(); - - return; - } else { - return; - } - } - - if (_paint_random) { - angle = _random(0, angle); - scale_x = _random(0, scale_x); - scale_y = _random(0, scale_y); - opacity = _random(0, opacity); - } - - ctx.globalAlpha = opacity; - - brush_width = brush.naturalWidth * scale_x; - brush_height = brush.naturalHeight * scale_y; - - brush_width_d2 = brush_width  / 2; - brush_height_d2 = brush_height / 2; - - if (_paint_lock_x) { - x = _pvx; - } - - if (_paint_lock_y) { - y = _pvy; - } - - dx = _pvx - x; - dy = _pvy - y; - - if (Math.abs(dx) > Math.abs(dy)) { - step = Math.abs(dx); - } else { - step = Math.abs(dy); - } - - xinc = dx / step; - yinc = dy / step; - - _pvx = x; - _pvy = y; - - for (i = 1; i <= step; i += 1) { - x += xinc; - y += yinc; - - drawing_x = Math.round(x - brush_width_d2); - drawing_y = Math.round(y - brush_height_d2); - - ctx.save(); - if (mode === 1) { - ctx.globalCompositeOperation = "destination-out"; - } else { - ctx.globalCompositeOperation = _paint_mode; - } - ctx.translate(x, y); - ctx.rotate(angle); - ctx.translate(drawing_x - x, drawing_y - y); - ctx.scale(scale_x, scale_y); - ctx.drawImage(brush, 0, 0); - ctx.restore(); - } -}; - -var _paintStart = function (x, y) { - _pvx = x; - _pvy = y; - - _paint_start_time = performance.now(); -}; - -var _draw = function (ctx, brush, mode, x, y, scale_x, scale_y, angle, opacity) { - var brush_width, - brush_height, - brush_width_d2, - brush_height_d2, - drawing_x, - drawing_y; - - if (_paint_random) { - angle = _random(0, angle); - scale_x = _random(0, scale_x); - scale_y = _random(0, scale_y); - opacity = _random(0, opacity); - } - - brush_width = brush.naturalWidth * scale_x; - brush_height = brush.naturalHeight * scale_y; - - brush_width_d2 = brush_width  / 2; - brush_height_d2 = brush_height / 2; - - drawing_x = Math.round(x - brush_width_d2); - drawing_y = Math.round(y - brush_height_d2); - - ctx.globalAlpha = opacity; - - ctx.save(); - - if (mode === 1) { - ctx.globalCompositeOperation = "destination-out"; - } else { - ctx.globalCompositeOperation = _paint_mode; - } - - ctx.translate(x, y); - ctx.rotate(angle); - ctx.translate(drawing_x - x, drawing_y - y); - ctx.scale(scale_x, scale_y); - ctx.drawImage(brush, 0, 0); - ctx.restore(); -}; - -var _setPaintCompositingMode = function (mode) { - return function (e) { - var detached_dialog = WUI_Dialog.getDetachedDialog(_paint_dialog), - updated_html = "Brushes (Mode : " + mode + ")"; - - _paint_mode = mode; - - document.getElementById("fs_brushes_info").innerHTML = updated_html; - - if (detached_dialog) { - detached_dialog.document.getElementById("fs_brushes_info").innerHTML = updated_html; - } - }; -} -/* jslint browser: true */ - -/*********************************************************** - Functions. -************************************************************/ - -var _onBrushClick = function (e) { - var p = e.target.parentElement, - brushes = e.hasOwnProperty("fs_detached_event") ? e.target.ownerDocument.getElementsByClassName("fs-brush") : document.getElementsByClassName("fs-brush"), - detached_dialog = WUI_Dialog.getDetachedDialog(_paint_dialog), - i; - - for (i = 0; i < brushes.length; i += 1) { - brushes[i].style.border = ""; - } - - if (p.classList.contains("fs-brush")) { - p.style.border = "solid 1px #00ff00"; - } else if (p.parentElement.classList.contains("fs-brushes")) { - return; - } else { - p.parentElement.style.border = "solid 1px #00ff00"; - } - - _paint_brush = p.getElementsByTagName('img')[0]; - - if (detached_dialog && !e.hasOwnProperty("fs_detached_event")) { - e.fs_detached_event = true; - - _onBrushClick(e); - } else { - _drawBrushHelper(); - } -}; - -var _applyBrushEvents = function (doc) { - var brushes = doc.getElementsByClassName("fs-brush"), - i; - - for (i = 0; i < brushes.length; i += 1) { - brushes[i].addEventListener("click", _onBrushClick); - } -}; - -var _addBrush = function (dom_image, id, detached) { - var detached_dialog = WUI_Dialog.getDetachedDialog(_paint_dialog), - - doc = detached ? detached_dialog.document : document, - - brushes_container = doc.getElementById("fs_brushes_container"), - - brush_container = doc.createElement("div"), - brush_name = doc.createElement("div"), - brush_img_container = doc.createElement("div"), - - brush_img = doc.createElement("img"); - - if (id) { - brush_img.dataset.inputId = id; - } - - brush_img.src = dom_image.src; - - brush_img_container.appendChild(brush_img); - - brush_container.classList.add("fs-brush"); - - brush_container.appendChild(brush_name); - brush_container.appendChild(brush_img_container); - - brushes_container.appendChild(brush_container); - - _applyBrushEvents(doc); - - if (detached_dialog && !detached) { - _addBrush(dom_image, id, true); - } -}; - -var _delBrush = function (id, detached) { - if (id === undefined) { - return; - } - - var detached_dialog = WUI_Dialog.getDetachedDialog(_paint_dialog), - - doc = detached ? detached_dialog.document : document, - - brushes = doc.getElementsByClassName("fs-brush"), - img, - i; - - for (i = 0; i < brushes.length; i += 1) { - img = brushes[i].getElementsByTagName('img')[0]; - - if (parseInt(img.dataset.inputId, 10) === id) { - brushes[i].parentElement.removeChild(brushes[i]); - break; - } - } - - if (detached_dialog && !detached) { - _delBrush(id, true); - } -}; - -var _addPreloaded = function () { - var i= 0; - - for (i = 1; i < 20; i += 1) { - _loadImageFromURL("data/brushes/" + i + ".png", _addBrush); - } -}; - - -/*********************************************************** - Init. -************************************************************/ - -_applyBrushEvents(document); - -// preload bundled brushes -_addPreloaded();/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -/*********************************************************** - Functions. -************************************************************/ - -var _canvasInputUpdate = function (input_obj) { - clearTimeout(input_obj.update_timeout); - input_obj.update_timeout = setTimeout(function () { - var image_data, - m; - - if (input_obj.db_obj.settings.flip) { - var tmp_canvas = document.createElement('canvas'), - tmp_canvas_context = tmp_canvas.getContext('2d'); - - tmp_canvas.width = input_obj.canvas.width; - tmp_canvas.height = input_obj.canvas.height; - - tmp_canvas_context.translate(0, input_obj.canvas.height); - tmp_canvas_context.scale(1, -1); - tmp_canvas_context.drawImage(input_obj.canvas, 0, 0, input_obj.canvas.width, input_obj.canvas.height); - - image_data = tmp_canvas_context.getImageData(0, 0, input_obj.canvas.width, input_obj.canvas.height); - - m = { img_width: image_data.width, img_height: image_data.height, data: image_data.data }; - } else { - image_data = input_obj.canvas_ctx.getImageData(0, 0, input_obj.canvas.width, input_obj.canvas.height); - - m = { img_width: image_data.width, img_height: image_data.height, data: image_data.data }; - } - - _gl.bindTexture(_gl.TEXTURE_2D, input_obj.texture); - _gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, m.img_width, m.img_height, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, new Uint8Array(m.data)); - _gl.bindTexture(_gl.TEXTURE_2D, null); - - input_obj.db_obj.data = input_obj.canvas.toDataURL(); - - var input_id = _parseInt10(input_obj.elem.dataset.inputId); - - _dbUpdateInput(input_id, input_obj.db_obj); - }, 250); -}; - -var _canvasInputDraw = function (input_obj, x, y, once) { - if (_paint_brush === null) { - return; - } - - if (once) { - _draw(input_obj.canvas_ctx, _paint_brush, input_obj.mouse_btn - 2, x, y, _paint_scalex, _paint_scaley, _paint_angle, _paint_opacity); - } else { - _paint(input_obj.canvas_ctx, _paint_brush, input_obj.mouse_btn - 2, x, y, _paint_scalex, _paint_scaley, _paint_angle, _paint_opacity); - } - - _canvasInputUpdate(input_obj); -}; - -var _canvasInputPaint = function (e) { - if (_selected_input_canvas) { - if (!_selected_input_canvas.canvas_enable) { - return false; - } - - var e = e || window.event, - - canvas_offset = _getElementOffset(_selected_input_canvas.canvas), - - x = e.pageX - canvas_offset.left, - y = e.pageY - canvas_offset.top; - - if (!_paint_brush) { - return; - } - - if (_selected_input_canvas.mouse_btn === 1 || - _selected_input_canvas.mouse_btn === 3) { - _canvasInputDraw(_selected_input_canvas, x, y); - } - } -}; - -var _canvasInputPaintStop = function () { - if (_selected_input_canvas) { - _selected_input_canvas.mouse_btn = 0; - } - - document.body.classList.remove("fs-no-select"); -}; - -var _canvasInputClear = function (input_obj) { - input_obj.canvas_ctx.clearRect(0, 0, input_obj.canvas.width, input_obj.canvas.height); -}; - -var _canvasInputDimensionsUpdate = function (new_width, new_height) { - var i = 0, - fragment_input_data, - tmp_canvas = document.createElement("canvas"), - tmp_canvas_ctx = tmp_canvas.getContext("2d"), - input_id; - - if (!new_width) { - new_width = _canvas_width; - } - - if (!new_height) { - new_height = _canvas_height; - } - - new_width = _parseInt10(new_width); - new_height = _parseInt10(new_height); - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - if (fragment_input_data.type === 2) { - tmp_canvas.width = new_width; - tmp_canvas.height = new_height; - tmp_canvas_ctx.fillRect(0, 0, new_width, new_height); - tmp_canvas_ctx.drawImage(fragment_input_data.canvas, 0, 0); - - fragment_input_data.canvas.width = new_width; - fragment_input_data.canvas.height = new_height; - fragment_input_data.db_obj.width = _canvas_width; - fragment_input_data.db_obj.height = _canvas_height; - fragment_input_data.canvas_ctx.drawImage(tmp_canvas, 0, 0, new_width, new_height); - - fragment_input_data.texture = _replace2DTexture({ empty: true, width: new_width, height: new_height }, fragment_input_data.texture); - - //_flipYTexture(fragment_input_data.texture, true); - - _canvasInputUpdate(fragment_input_data); - - input_id = _parseInt10(fragment_input_data.elem.dataset.inputId); - - _dbUpdateInput(input_id, fragment_input_data.db_obj); - } else if (fragment_input_data.type === 6) { - tmp_canvas.width = new_width; - tmp_canvas.height = new_height; - tmp_canvas_ctx.fillRect(0, 0, new_width, new_height); - tmp_canvas_ctx.drawImage(fragment_input_data.canvas, 0, 0); - - fragment_input_data.canvas.width = new_width; - fragment_input_data.canvas.height = new_height; - fragment_input_data.db_obj.width = _canvas_width; - fragment_input_data.db_obj.height = _canvas_height; - fragment_input_data.canvas_ctx.drawImage(tmp_canvas, 0, 0, new_width, new_height); - - fragment_input_data.texture = _replace2DTexture({ empty: true, width: new_width, height: new_height }, fragment_input_data.texture); - - //_flipYTexture(fragment_input_data.texture, true); - - //_canvasInputUpdate(fragment_input_data); - - input_id = _parseInt10(fragment_input_data.elem.dataset.inputId); - - _dbUpdateInput(input_id, fragment_input_data.db_obj); - } - } -}; -/* jslint browser: true */ - -/** - * Manage all Fragment inputs. - */ - -/*********************************************************** - Fields. -************************************************************/ - -var _dragged_input = null, - - _input_settings_dialog_id = 0, - _input_settings_dialog_prefix = "fs_channel_settings_dialog", - - _pjs_canvas_id = 0, - - _clicked_input_ev = null, - - _selected_input_canvas = null, - - _input_loading = false; - -/*********************************************************** - Functions. -************************************************************/ - -var _cbChannelSettingsClose = function (input_channel_id) { - return function () { - var fragment_input_channel = _fragment_input_data[input_channel_id]; - - WUI_RangeSlider.destroy("fs_channel_settings_playrate" + fragment_input_channel.dialog_id); - WUI_RangeSlider.destroy("fs_channel_settings_videostart" + fragment_input_channel.dialog_id); - WUI_RangeSlider.destroy("fs_channel_settings_videoend" + fragment_input_channel.dialog_id); - - if (fragment_input_channel) { - if (fragment_input_channel.dialog_id !== undefined && fragment_input_channel.dialog_id !== null) { - WUI_Dialog.destroy(_input_settings_dialog_prefix + fragment_input_channel.dialog_id); - } - } - }; -}; - -var _cbChannelSettingsChange = function (fic, ficd, cb) { - return function (value) { - cb(value, fic, ficd, this); - }; -}; - -var _openChannelSettingsDialog = function (input_channel_id) { - var fragment_input_channel = _fragment_input_data[input_channel_id]; - - WUI_Dialog.open(_input_settings_dialog_prefix + fragment_input_channel.dialog_id); -}; - -var _createChannelSettingsDialog = function (input_channel_id) { - var dialog_element = document.createElement("div"), - content_element = document.createElement("div"), - - video_playrate_element = "fs_channel_settings_playrate"+_input_settings_dialog_id, - video_start_element = "fs_channel_settings_videostart"+_input_settings_dialog_id, - video_end_element = "fs_channel_settings_videoend"+_input_settings_dialog_id, - - fragment_input_channel = _fragment_input_data[input_channel_id], - - channel_filter_select, - channel_wrap_s_select, - channel_wrap_t_select, - channel_vflip, - - channel_settings_dialog, - - dialog_height = "200px", - - vflip_style = "", - - tex_parameter, - - power_of_two_wrap_options = '' + - '', - - mipmap_option = ''; - - dialog_element.id = _input_settings_dialog_prefix + _input_settings_dialog_id; - - fragment_input_channel.dialog_id = _input_settings_dialog_id; - - if (!_gl2) { // WebGL 2 does not have those limitations - if (!_isPowerOf2(fragment_input_channel.image.width) || - !_isPowerOf2(fragment_input_channel.image.height) || - fragment_input_channel.type === 1 || - fragment_input_channel.type === 3 || - fragment_input_channel.type === 5 || - fragment_input_channel.type === 6) { - power_of_two_wrap_options = ""; - mipmap_option = ""; - } - } - - if (fragment_input_channel.type === 1 || - fragment_input_channel.type === 2 || - fragment_input_channel.type === 3 || - fragment_input_channel.type === 4 || - fragment_input_channel.type === 5 || - fragment_input_channel.type === 6 || - fragment_input_channel.type === 404) { - vflip_style = "display: none"; - } - - dialog_element.style.fontSize = "13px"; - - // create setting widgets - content_element.innerHTML = '
Filter:
 
' + - '
Wrap S:
 
' + - '
Wrap T:
 
' + - ' 
'; - - dialog_element.appendChild(content_element); - - document.body.appendChild(dialog_element); - - channel_filter_select = document.getElementById("fs_channel_filter"+input_channel_id); - channel_wrap_s_select = document.getElementById("fs_channel_wrap_s"+input_channel_id); - channel_wrap_t_select = document.getElementById("fs_channel_wrap_t"+input_channel_id); - channel_vflip = document.getElementById("fs_channel_vflip"+input_channel_id); - - if (fragment_input_channel.type === 3) { // video settings - dialog_height = "340px"; - - content_element.innerHTML += ' 
'; - - WUI_RangeSlider.create(video_playrate_element, { - width: 120, - height: 8, - - min: 0, - max: 10000.0, - - bar: false, - - midi: true, - - step: 0.001, - scroll_step: 0.01, - - default_value: fragment_input_channel.playrate, - value: fragment_input_channel.playrate, - - decimals: 3, - - title: "Playback rate", - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic) { - fic.video_elem.playbackRate = parseFloat(v); - fic.playrate = parseFloat(v); - }) - }); - - WUI_RangeSlider.create(video_start_element, { - width: 120, - height: 8, - - min: 0.0, - max: 1.0, - - bar: false, - - midi: true, - - step: 0.0001, - scroll_step: 0.001, - - default_value: fragment_input_channel.videostart, - value: fragment_input_channel.videostart, - - decimals: 4, - - title: "Video start", - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic) { - var fval = parseFloat(v); - if (fic.videostart === fval) { - return; - } - - fic.videostart = fval; - fic.video_elem.currentTime = fic.video_elem.duration * fval; - }) - }); - - WUI_RangeSlider.create(video_end_element, { - width: 120, - height: 8, - - min: 0.0, - max: 1.0, - - bar: false, - - midi: true, - - step: 0.0001, - scroll_step: 0.001, - - default_value: fragment_input_channel.videoend, - value: fragment_input_channel.videoend, - - decimals: 4, - - title: "Video end", - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic) { - fic.videoend = parseFloat(v); - }) - }); - } - - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input_channel.texture); - - if (_gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER) === _gl.NEAREST) { - channel_filter_select.value = "nearest"; - } else if (_gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER) === _gl.LINEAR_MIPMAP_NEAREST) { - channel_filter_select.value = "mipmap"; - } else if (_gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER) === _gl.LINEAR) { - channel_filter_select.value = "linear"; - } - - tex_parameter = _gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S); - - if (tex_parameter === _gl.CLAMP_TO_EDGE) { - channel_wrap_s_select.value = "clamp"; - } else if (tex_parameter === _gl.REPEAT) { - channel_wrap_s_select.value = "repeat"; - } else if (tex_parameter === _gl.MIRRORED_REPEAT) { - channel_wrap_s_select.value = "mirror"; - } - - tex_parameter = _gl.getTexParameter(_gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T); - - if (tex_parameter === _gl.CLAMP_TO_EDGE) { - channel_wrap_t_select.value = "clamp"; - } else if (tex_parameter === _gl.REPEAT) { - channel_wrap_t_select.value = "repeat"; - } else if (tex_parameter === _gl.MIRRORED_REPEAT) { - channel_wrap_t_select.value = "mirror"; - } - - if (fragment_input_channel.db_obj.settings.flip) { - channel_vflip.checked = true; - } else { - channel_vflip.checked = false; - } - - channel_vflip.addEventListener("change", _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic, ficd, self) { - var new_texture; - - fic.db_obj.settings.flip = self.checked; - - if (fic.db_obj.settings.flip) { - _flipTexture(fic.texture, fic.image, function (texture) { - fic.texture = texture; - - _dbUpdateInput(_parseInt10(ficd), fic.db_obj); - }); - } else { - new_texture = _replace2DTexture(fic.image, fic.texture); - fic.texture = new_texture; - - _dbUpdateInput(_parseInt10(ficd), fic.db_obj); - } - })); - - channel_filter_select.addEventListener("change", _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic, ficd, self) { - _setTextureFilter(fic.texture, self.value); - - fic.db_obj.settings.f = self.value; - _dbUpdateInput(_parseInt10(ficd), fic.db_obj); - })); - - channel_wrap_s_select.addEventListener("change", _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic, ficd, self) { - _setTextureWrapS(fic.texture, self.value); - - fic.db_obj.settings.wrap.s = self.value; - _dbUpdateInput(_parseInt10(ficd), fic.db_obj); - })); - - channel_wrap_t_select.addEventListener("change", _cbChannelSettingsChange(fragment_input_channel, input_channel_id, function (v, fic, ficd, self) { - _setTextureWrapT(fic.texture, self.value); - - fic.db_obj.settings.wrap.t = self.value; - _dbUpdateInput(_parseInt10(ficd), fic.db_obj); - })); - - channel_settings_dialog = WUI_Dialog.create(dialog_element.id, { - title: _input_channel_prefix + input_channel_id + " settings", - - width: "250px", - height: dialog_height, - - halign: "center", - valign: "center", - - open: false, - minimized: false, - - modal: false, - status_bar: false, - - closable: true, - draggable: true, - minimizable: true, - - resizable: false, - - detachable: false, - - min_width: 200, - min_height: 250, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "import/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _input_settings_dialog_id += 1; -}; - -var _imageProcessor = function (image_data, image_processing_done_cb) { - var worker = new Worker("dist/worker/image_processor.min.js"); - - worker.onmessage = function (e) { - worker.terminate(); - - image_processing_done_cb(e.data); - }; - - worker.postMessage({ img_width: image_data.width, img_height: image_data.height, buffer: image_data.data.buffer }, [image_data.data.buffer]); -}; - -var _cbChannelSettings = function (dialog_id) { - return function (e) { - e.preventDefault(); - - WUI_Dialog.open(_input_settings_dialog_prefix + dialog_id); - }; -}; - -var _inputThumbMenu = function (e) { - e.preventDefault(); - - var input_id = _parseInt10(e.target.dataset.inputId), - input = _fragment_input_data[input_id], - dom_image = input.elem, - - items = [ - { - icon: "fs-cross-45-icon", tooltip: "Delete", on_click: function () { - _input_panel_element.removeChild(dom_image); - - _removeInputChannel(input_id); - _delBrush(input_id); - } - } - ]; - - if (input.type !== 404) { - items.unshift({ - icon: "fs-gear-icon", tooltip: "Settings", on_click: function () { - _openChannelSettingsDialog(input_id); - } - }); - } - - if (input.type === 0) { - items.push({ - icon: "fs-xyf-icon", tooltip: "View image", on_click: function () { - var win = window.open(dom_image.src); - win.document.write(""); - } - }); - } - - if (input.type === 2) { - items.push({ - icon: "fs-brush-icon", tooltip: "Open draw tools & allow to draw", on_click: _selectCanvasInput - }); - } - - if (input.type === 3) { - items.push({ - icon: "fs-reset-icon", tooltip: "Rewind", on_click: function () { - if (input.video_elem.duration === NaN) { - input.video_elem.currentTime = 0; - } else { - input.video_elem.currentTime = input.video_elem.duration * input.videostart; - } - } - }); - } - - if (input.type === 4) { - items.push({ - icon: "fs-reset-icon", tooltip: "Rewind", on_click: function () { - input.globalTime = 0; - - _pjsCompile(input); - } - }); - - items.push({ - icon: "fs-code-icon", tooltip: "Pjs code editor", on_click: _openProcessingJSEditor - }); - } - - _clicked_input_ev = e; - - WUI_CircularMenu.create( - { - element: dom_image, - - rx: 32, - ry: 32, - - item_width: 32, - item_height: 32 - }, items - ); -}; - -var _openProcessingJSEditor = function (e) { - var input_id = null, - input = null; - - if (e) { - e.preventDefault(); - } else { - e = _clicked_input_ev; - } - - input_id = _parseInt10(e.target.dataset.inputId); - - input = _fragment_input_data[input_id]; - - _pjsSelectInput(input); - - WUI_Dialog.open("fs_pjs"); -}; - -var _selectCanvasInput = function (e) { - var input_id = null, - input = null; - - if (e) { - e.preventDefault(); - } else { - e = _clicked_input_ev; - } - - input_id = _parseInt10(e.target.dataset.inputId); - - input = _fragment_input_data[input_id] - - var input_tmp, - dom_image = input.elem, - - i = 0; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - input_tmp = _fragment_input_data[i]; - - if (i === input_id || - input_tmp.type !== 2) { - continue; - } - - input_tmp.elem.classList.remove("fs-selected-input"); - input_tmp.canvas_enable = false; - - input_tmp.canvas.style.display = "none"; - } - - input.canvas_enable = !input.canvas_enable; - - if (input.canvas_enable) { - dom_image.classList.add("fs-selected-input"); - - WUI_Dialog.open(_paint_dialog, false); - - input.canvas.style.display = ""; - - _selected_input_canvas = input; - } else { - dom_image.classList.remove("fs-selected-input"); - - input.canvas.style.display = "none"; - - _selected_input_canvas = null; - } -}; - -var _sortInputs = function () { - var i = 0, - fragment_input_data; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - if (fragment_input_data.elem) { - fragment_input_data.elem.title = _input_channel_prefix + i; - fragment_input_data.elem.dataset.inputId = i; - - WUI_Dialog.setTitle(_input_settings_dialog_prefix + fragment_input_data.dialog_id, "iInput" + i + " settings"); - } - } -}; - -var _removeInputChannel = function (input_id) { - var fragment_input_data = _fragment_input_data[input_id], - tracks, i; - - _gl.deleteTexture(fragment_input_data.texture); - - if (fragment_input_data.type === 1 || fragment_input_data.type === 3 || fragment_input_data === 5) { - fragment_input_data.video_elem.pause(); - window.URL.revokeObjectURL(fragment_input_data.video_elem.src); - fragment_input_data.video_elem.src = ""; - - if (fragment_input_data.media_stream) { - fragment_input_data.media_stream.getTracks().forEach(function(track) { - track.stop(); - }); - } - fragment_input_data.video_elem = null; - } else if (fragment_input_data.type === 6) { - if (fragment_input_data.media_stream) { - fragment_input_data.media_stream.getTracks().forEach(function(track) { - track.stop(); - }); - } - } - - if (fragment_input_data.canvas) { - fragment_input_data.canvas.remove(); - } - - _cbChannelSettingsClose(_parseInt10(input_id))(); - - _fragment_input_data.splice(_parseInt10(input_id), 1); - - _sortInputs(); - - _dbClear(); - - for (i = 0; i < _fragment_input_data.length; i += 1) { - if (_fragment_input_data[i].elem) { - _dbStoreInput(_parseInt10(_fragment_input_data[i].elem.dataset.inputId), _fragment_input_data[i].db_obj); - } - } - - _pjsUpdateInputs(); - - _compile(); -}; - -var _createInputThumb = function (input_id, image, thumb_title, src) { - var dom_image = document.createElement("img"), - - input = _fragment_input_data[input_id], - - tmp_canvas, - tmp_canvas_context; - - if (image) { - dom_image.src = image.src; - } - - dom_image.title = thumb_title; - - if (src) { - dom_image.src = src; - } - - dom_image.dataset.inputId = input_id; - - dom_image.classList.add("fs-input-thumb"); - - dom_image.draggable = true; - - dom_image.addEventListener("click", _inputThumbMenu); - - dom_image.addEventListener("auxclick", function (e) { - e.preventDefault(); - - if (e.button == 1) { - var input_id = _parseInt10(e.target.dataset.inputId), - input = _fragment_input_data[input_id], - dom_image = input.elem; - - _input_panel_element.removeChild(dom_image); - - _removeInputChannel(input_id); - _delBrush(input_id); - } - }); - - // drag & drop - dom_image.addEventListener("drop", function (e) { - e.preventDefault(); - - if (e.target.dataset.inputId === undefined) { - e.target.style = ""; - - _dragged_input = null; - - return; - } - - var src_input_id = _parseInt10(_dragged_input.dataset.inputId), - dst_input_id = _parseInt10(e.target.dataset.inputId), - - elem_src = _fragment_input_data[src_input_id].elem, - - dst_data = e.target.src, - src_title = _dragged_input.title, - - dst_input_data, - src_input_data; - - _fragment_input_data = _swapArrayItem(_fragment_input_data, src_input_id, dst_input_id); - - e.target.dataset.inputId = src_input_id; - _dragged_input.dataset.inputId = dst_input_id; - - e.target.title = "iInput" + src_input_id; - _dragged_input.title = "iInput" + dst_input_id; - - _swapNode(e.target, _dragged_input); - - dst_input_data = _fragment_input_data[dst_input_id]; - src_input_data = _fragment_input_data[src_input_id]; - - // db update - _dbUpdateInput(_parseInt10(dst_input_id), dst_input_data.db_obj); - _dbUpdateInput(_parseInt10(src_input_id), src_input_data.db_obj); - // - - WUI_Dialog.setTitle(_input_settings_dialog_prefix + dst_input_data.dialog_id, "iInput" + dst_input_id + " settings"); - WUI_Dialog.setTitle(_input_settings_dialog_prefix + src_input_data.dialog_id, "iInput" + src_input_id + " settings"); - - e.target.style = ""; - - _dragged_input = null; - - _pjsUpdateInputs(); - }); - - dom_image.addEventListener("dragstart", function (e) { - _dragged_input = e.target; - }); - - dom_image.addEventListener("dragleave", function (e) { - e.preventDefault(); - - e.target.style = ""; - }); - - dom_image.addEventListener("dragover", function (e) { - e.preventDefault(); - - if (e.target === _dragged_input) { - e.dataTransfer.dropEffect = "none"; - } else { - e.dataTransfer.dropEffect = "move"; - } - }); - - dom_image.addEventListener("dragenter", function (e) { - e.preventDefault(); - - if (e.target !== _dragged_input) { - e.target.style = "border: dashed 1px #00ff00; background-color: #444444"; - } - }); - - _input_panel_element.appendChild(dom_image); - - // add it as brush as well - if (input.type === 0) { - _addBrush(dom_image, dom_image.dataset.inputId); - } - - return dom_image; -}; - -var _addVideoEvents = function (video_element, input) { - video_element.addEventListener("ended", function () { - this.play(); - - this.currentTime = input.videostart * this.duration; - }); -}; - -var _fnReplaceInputTexture = function (input_id) { - var input_obj = _fragment_input_data[input_id]; - - return function (texture) { - input_obj.texture = texture; - }; -}; - -var _addNoneInput = function (type, input_id) { - var data = _create2DTexture({ empty: true }, false, false); - - _fragment_input_data.push({ - type: 404, - texture: data.texture, - db_obj: null - }); - - _dbRestoreInput(input_id, _fragment_input_data[input_id]); - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, null, _input_channel_prefix + input_id, "data/ui-icons/"+type+"_none.png"); - - _compile(); -}; - -var _addFragmentInput = async function (type, input, settings, id) { - var input_thumb, - - data, - image, - texture, - canvas, - - input_obj, - - video_element, - - db_obj = { type: type, width: null, height: null, data: null, settings: { f: "nearest", wrap: { s: null, t: null }, flip: false } }, - - input_id = id ? id : _fragment_input_data.length, - - promise = null; - - if (type === "image") { - data = _create2DTexture(input, false, true); - - db_obj.data = input.src; - db_obj.width = input.width; - db_obj.height = input.height; - db_obj.settings.wrap.s = data.wrap.ws; - db_obj.settings.wrap.t = data.wrap.wt; - db_obj.settings.flip = false; - - _dbStoreInput(input_id, db_obj); - - _fragment_input_data[input_id] = { - type: 0, - image: data.image, - texture: data.texture, - elem: null, - db_obj: db_obj - }; - - if (settings !== undefined) { - _setTextureFilter(data.texture, settings.f); - _setTextureWrapS(data.texture, settings.wrap.s); - _setTextureWrapT(data.texture, settings.wrap.t); - - db_obj.settings.f = settings.f; - db_obj.settings.wrap.s = settings.wrap.s; - db_obj.settings.wrap.t = settings.wrap.t; - db_obj.settings.flip = settings.flip; - - if (settings.flip) { - _flipTexture(data.texture, data.image, _fnReplaceInputTexture(input_id)); - } - } else { - db_obj.settings.f = "nearest"; - - _setTextureFilter(data.texture, db_obj.settings.f); - _setTextureWrapS(data.texture, db_obj.settings.wrap.s); - _setTextureWrapT(data.texture, db_obj.settings.wrap.t); - } - - input_thumb = input; - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, input_thumb, _input_channel_prefix + input_id); - - _createChannelSettingsDialog(input_id); - - _fragment_input_data[input_id].elem.addEventListener("contextmenu", _cbChannelSettings(_fragment_input_data[input_id].dialog_id)); - - _compile(); - } else if (type === "camera" || type === "video" || type === "desktop" || type === "mic") { - video_element = document.createElement('video'); - video_element.autoplay = true; - video_element.loop = true; - video_element.stream = null; - - if (type === "camera" || type === "mic") { - if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { - var user_media_options = { - video: { width: _audio_import_settings.cam_width, height: _audio_import_settings.cam_height, frameRate: 60 }, - audio: false - }; - - var input_type = 1; - var analysis_data = null; - var analyzer_node = null; - var primary_canvas = null; - - if (type === "mic") { - user_media_options = { - video: false, - audio: true - }; - - input_type = 6; - } - - try { - var media_stream = await navigator.mediaDevices.getUserMedia(user_media_options); - - if (type === "camera") { - var stream_settings = media_stream.getVideoTracks()[0].getSettings(); - video_element.width = stream_settings.width; - video_element.height = stream_settings.height; - - video_element.srcObject = /*window.URL.createObjectURL(*/media_stream/*)*/; - - data = _create2DTexture(video_element, false, false); - } else { - // create analysis canvas - primary_canvas = document.createElement("canvas"); - - primary_canvas.width = _canvas_width; - primary_canvas.height = _canvas_height; - - data = _create2DTexture(primary_canvas, false, true); - - // mic capture - analyzer_node = _audio_context.createAnalyser(); - analyzer_node.fftSize = _audio_import_settings.fft_size; - analyzer_node.smoothingTimeConstant = 0; - - var mic_node = _audio_context.createMediaStreamSource(media_stream); - - mic_node.connect(analyzer_node); - - analysis_data = new Uint8Array(analyzer_node.frequencyBinCount); - } - - _setTextureWrapS(data.texture, "clamp"); - _setTextureWrapT(data.texture, "clamp"); - - db_obj.settings.wrap.s = data.wrap.ws; - db_obj.settings.wrap.t = data.wrap.wt; - db_obj.settings.flip = false; - //db_obj.settings.audio = _audio_import_settings.videotrack_import; - - _dbStoreInput(input_id, db_obj); - - if (settings !== undefined) { - _setTextureFilter(data.texture, settings.f); - _setTextureWrapS(data.texture, settings.wrap.s); - _setTextureWrapT(data.texture, settings.wrap.t); - - db_obj.settings.f = settings.f; - db_obj.settings.wrap.s = settings.wrap.s; - db_obj.settings.wrap.t = settings.wrap.t; - db_obj.settings.flip = settings.flip; - db_obj.settings.audio = settings.audio; - } - - _fragment_input_data[input_id] = { - type: input_type, - image: data.image, - texture: data.texture, - video_elem: video_element, - elem: null, - media_stream: media_stream, - db_obj: db_obj, - analyzer_node: analyzer_node, - analysis_data: analysis_data, - canvas: primary_canvas, - fft_size: _audio_import_settings.fft_size, - speed: 1 - }; - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, null, _input_channel_prefix + input_id, "data/ui-icons/" + type + ".png"); - - _createChannelSettingsDialog(input_id); - - _fragment_input_data[input_id].elem.addEventListener("contextmenu", _cbChannelSettings(_fragment_input_data[input_id].dialog_id)); - - _compile(); - - promise = media_stream; -/* - if (db_obj.settings.audio) { - await _addFragmentInput("canvas", null, { linked: { input: input_id} }); - } -*/ - } catch (e) { - _notification("Unable to capture " + type + "."); - console.log(e); - } - } else { - _notification("Unable to capture " + type + ", getUserMedia may be not supported by your browser."); - } - } else if (type === "desktop") { - if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) { - try { - const media_stream = await navigator.mediaDevices.getDisplayMedia({ - video: true - }); - - video_element.srcObject = media_stream; - - data = _create2DTexture(video_element, false, false); - - _setTextureWrapS(data.texture, "clamp"); - _setTextureWrapT(data.texture, "clamp"); - - db_obj.settings.wrap.s = data.wrap.ws; - db_obj.settings.wrap.t = data.wrap.wt; - db_obj.settings.flip = false; - - _dbStoreInput(input_id, db_obj); - - if (settings !== undefined) { - _setTextureFilter(data.texture, settings.f); - _setTextureWrapS(data.texture, settings.wrap.s); - _setTextureWrapT(data.texture, settings.wrap.t); - - db_obj.settings.f = settings.f; - db_obj.settings.wrap.s = settings.wrap.s; - db_obj.settings.wrap.t = settings.wrap.t; - db_obj.settings.flip = settings.flip; - } - - _fragment_input_data[input_id] = { - type: 5, - image: data.image, - texture: data.texture, - video_elem: video_element, - elem: null, - media_stream: media_stream, - db_obj: db_obj - }; - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, null, _input_channel_prefix + input_id, "data/ui-icons/desktop.png"); - - _createChannelSettingsDialog(input_id); - - _fragment_input_data[input_id].elem.addEventListener("contextmenu", _cbChannelSettings(_fragment_input_data[input_id].dialog_id)); - - _compile(); - - promise = media_stream; - } catch (e) { - _notification("Unable to capture desktop."); - } - } else { - _notification("Unable to capture desktop, getDisplayMedia may be not supported by your browser."); - } - } else { // Video - // a "video without data" Fragment input; a dummy image basically which tell the user that a video was here - if (!input) { - _addNoneInput(type, input_id); - - return; - } - - if (Object.prototype.toString.call(input) === "[object String]") { - video_element.src = input; - } else { - video_element.src = window.URL.createObjectURL(input); - } - - video_element.autoplay = true; - video_element.loop = false; - video_element.muted = true; - - data = _create2DTexture(video_element, false, false); - - _setTextureWrapS(data.texture, "repeat"); - _setTextureWrapT(data.texture, "repeat"); - - if (settings !== undefined) { - _setTextureFilter(data.texture, settings.f); - _setTextureWrapS(data.texture, settings.wrap.s); - _setTextureWrapT(data.texture, settings.wrap.t); - - db_obj.settings.f = settings.f; - db_obj.settings.wrap.s = data.wrap.ws; - db_obj.settings.wrap.t = data.wrap.wt; - db_obj.settings.flip = false; - } - - _dbStoreInput(input_id, db_obj); - - input_obj = { - type: 3, - image: data.image, - texture: data.texture, - video_elem: video_element, - elem: null, - db_obj: db_obj, - videostart: 0.0, - videoend: 1.0, - playrate: 1.0 - }; - - _fragment_input_data[input_id] = input_obj; - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, null, _input_channel_prefix + input_id, "data/ui-icons/video.png"); - - _createChannelSettingsDialog(input_id); - - _fragment_input_data[input_id].elem.addEventListener("contextmenu", _cbChannelSettings(_fragment_input_data[input_id].dialog_id)); - - _compile(); - - _addVideoEvents(video_element, _fragment_input_data[input_id]); - - video_element.play(); - } - } else if (type === "canvas") { - var linked_input = null; - - if (settings && settings.linked) { - linked_input = settings.linked.input; - } - - data = _create2DTexture({ - empty: true, - width: _canvas_width, - height: _canvas_height, - }, false, true); - - if (input) { - db_obj.data = input.src; - } else { - db_obj.data = ""; - } - - _setTextureWrapS(data.texture, "repeat"); - _setTextureWrapT(data.texture, "repeat"); - - db_obj.width = _canvas_width; - db_obj.height = _canvas_height; - //db_obj.settings.wrap.s = data.wrap.ws; - //db_obj.settings.wrap.t = data.wrap.wt; - //db_obj.settings.flip = false; - - canvas = document.createElement("canvas"); - canvas.width = _canvas_width; - canvas.height = _canvas_height; - canvas.classList.add("fs-paint-canvas"); - - input_obj = { - type: 2, - image: canvas,//data.image, - texture: data.texture, - elem: null, - db_obj: db_obj, - canvas: canvas, - canvas_ctx: canvas.getContext("2d"), - canvas_enable: false, - mouse_btn: 0, - update_timeout: null - }; - - _fragment_input_data[input_id] = input_obj; - - var co = _getElementOffset(_canvas); - - canvas.style.position = "absolute"; - canvas.style.left = co.left + "px"; - canvas.style.top = co.top + "px"; - canvas.style.display = "none"; - - canvas.dataset.group = "canvas"; - - _setImageSmoothing(input_obj.canvas_ctx, false); - - if (input) { - input_obj.canvas_ctx.drawImage(input, 0, 0); - - _canvasInputUpdate(input_obj); - } - - document.body.appendChild(canvas); - - if (linked_input === null) { - canvas.addEventListener('mousedown', function (e) { - if (!input_obj.canvas_enable) { - return false; - } - - var e = e || window.event, - - canvas_offset = _getElementOffset(canvas), - - x = e.pageX - canvas_offset.left, - y = e.pageY - canvas_offset.top; - - input_obj.mouse_btn = e.which; - - if (input_obj.mouse_btn === 1 || - input_obj.mouse_btn === 3) { - _paintStart(x, y); - - _canvasInputDraw(input_obj, x, y, true); - - document.body.classList.add("fs-no-select"); - } - }); - } - - canvas.addEventListener('contextmenu', function (e) { - e.preventDefault(); - }); - - if (settings !== undefined) { - if (settings.f) { - _setTextureFilter(data.texture, settings.f); - db_obj.settings.f = settings.f; - } - - if (settings.wrap) { - _setTextureWrapS(data.texture, settings.wrap.s); - db_obj.settings.wrap.s = settings.wrap.s; - - _setTextureWrapT(data.texture, settings.wrap.t); - db_obj.settings.wrap.t = settings.wrap.t; - } - - if (settings.flip) { - db_obj.settings.flip = settings.flip; - } - } - - if (linked_input === null) { - _dbStoreInput(input_id, db_obj); - } - - input_thumb = input; - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, null, _input_channel_prefix + input_id, linked_input !== null ? "data/ui-icons/mic.png" : "data/ui-icons/paint_brush.png" ); - - _createChannelSettingsDialog(input_id); - - if (linked_input === null) { - _fragment_input_data[input_id].elem.addEventListener("contextmenu", _selectCanvasInput); - } - - _compile(); - } else if (type === "processing.js") { - data = _create2DTexture({ - empty: true, - width: _canvas_width, - height: _canvas_height, - }, false, true); - - if (input) { - db_obj.data = input; - } else { - db_obj.data = [ - "void setup() {", - " size(1224, 439);", // this is updated automatically - " background(0, 0, 0, 255);", - " noStroke();", - "}", - "", - "void draw() {", - " background(0, 0, 0, 255);", - "}"].join("\n");; - } - - _setTextureWrapS(data.texture, "repeat"); - _setTextureWrapT(data.texture, "repeat"); - - db_obj.width = _canvas_width; - db_obj.height = _canvas_height; - - canvas = document.createElement("canvas"); - canvas.width = _canvas_width; - canvas.height = _canvas_height; - canvas.style.position = "absolute"; - //canvas.style.visibility = "hidden"; - canvas.id = "fs_pjs_canvas_" + _pjs_canvas_id; - canvas.className = "fs-pjs-canvas"; - - var main_canvas_offset = _getElementOffset(_canvas); - canvas.style.top = "0"; - canvas.style.left = main_canvas_offset.left + "px"; - canvas.style.zIndex = "-1"; - - input_obj = { - type: 4, - image: canvas, - texture: data.texture, - elem: null, - db_obj: db_obj, - canvas: canvas, - canvas_ctx: canvas.getContext("2d"), - canvas_enable: false, - mouse_btn: 0, - update_timeout: null, - pjs_source_code: db_obj.data, - globalTime: 0, - pjs: null - }; - - _fragment_input_data[input_id] = input_obj; - - var co = _getElementOffset(_canvas); - - _setImageSmoothing(input_obj.canvas_ctx, false); - /* - if (input) { - input_obj.canvas_ctx.drawImage(input, 0, 0); - - _canvasInputUpdate(input_obj); - }*/ - - _canvas_container.appendChild(canvas); - - if (settings !== undefined) { - _setTextureFilter(data.texture, settings.f); - _setTextureWrapS(data.texture, settings.wrap.s); - _setTextureWrapT(data.texture, settings.wrap.t); - - db_obj.settings.f = settings.f; - db_obj.settings.wrap.s = settings.wrap.s; - db_obj.settings.wrap.t = settings.wrap.t; - db_obj.settings.flip = settings.flip; - } - - _dbStoreInput(input_id, db_obj); - - input_thumb = input; - - _fragment_input_data[input_id].elem = _createInputThumb(input_id, null, _input_channel_prefix + input_id, "data/ui-icons/pjs.png" ); - - _createChannelSettingsDialog(input_id); - - _fragment_input_data[input_id].elem.addEventListener("contextmenu", _openProcessingJSEditor); - - // don't compile the sketch when it is loaded from the db (it may depend on other inputs; a load order issue) - if (!input) { - try { - _fragment_input_data[input_id].pjs = new Processing(canvas.id, db_obj.data); - if (_fs_state !== 0 && _glsl_error !== false) { - input.pjs.noLoop(); - } - } catch (err) { - - } - } - - _pjsUpdateInputs(); - - _compile(); - - _pjs_canvas_id += 1; - } - - if (promise) { - return promise; - } else { - return Promise.resolve(); - } -}; - -/*********************************************************** - Init. -************************************************************/ -/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _workspace_code_elem = document.getElementById("fs_code_target"); - -/*********************************************************** - Functions. -************************************************************/ - -var _clearCodeMirrorWidgets = function () { - var i = 0, j = 0; - - for (j = 0; j < _code_editors.length; j += 1) { - for (i = 0; i < _code_editors[j].line_widgets.length; i += 1) { - _code_editors[j].editor.removeLineWidget(_code_editors[j].line_widgets[i]); - } - - _code_editors[j].line_widgets = []; - } -}; - -var _parseCompileOutput = function (output) { - var regex = /ERROR: \d+:(\d+): (.*)/g, - - msg_container, - msg_icon, - - concerned_editor = null, - - line = 0, - - result = [], - - m; - - _clearCodeMirrorWidgets(); - - while ((m = regex.exec(output)) !== null) { - if (m.index === regex.lastIndex) { - regex.lastIndex++; - } - - line = parseInt(m[1], 10); - - msg_container = document.createElement("div"); - msg_icon = msg_container.appendChild(document.createElement("div")); - msg_icon.className = "fs-error-icon"; - msg_container.appendChild(document.createTextNode(m[2])); - msg_container.className = "fs-compile-error"; - - line -= 1; - - if (_gl2) { - line = line - 1; - } - - if (line >= 1 && line <= _code_editors[1].editor.lineCount() && _current_code_editor !== _code_editors[2]) { - concerned_editor = _code_editors[1]; // library - } else if (_current_code_editor !== _code_editors[2]) { - line -= _code_editors[1].editor.lineCount(); - - concerned_editor = _current_code_editor; // main - } else { - line -= 1; - - concerned_editor = _current_code_editor; // examples - } - - result.push({ target: concerned_editor.name, line: line, msg: m[2]}); - - if (_cm_show_inerrors || concerned_editor.editor.getOption("fullScreen")) { - concerned_editor.line_widgets.push(concerned_editor.editor.addLineWidget(line - 1, msg_container, { coverGutter: false, noHScroll: true })); - } - } - - return result; -}; - -var _changeEditorsTheme = function (theme) { - if (_code_editor_theme_link) { - document.getElementsByTagName('head')[0].removeChild(_code_editor_theme_link); - } - - _code_editor_theme_link = document.createElement('link'); - - _code_editor_theme_link.onload = function(){ - var i = 0; - for (i = 0; i < _code_editors.length; i += 1) { - _code_editors[i].editor.setOption("theme", theme); - } - - _pjs_codemirror_instance.setOption("theme", theme); - _midi_codemirror_instance.setOption("theme", theme); - }; - _code_editor_theme_link.rel = "stylesheet"; - _code_editor_theme_link.media = "all"; - _code_editor_theme_link.href = "css/codemirror/theme/" + theme + ".css"; - - document.getElementsByTagName('head')[0].appendChild(_code_editor_theme_link); - - localStorage.setItem('fs-editor-theme', theme); - - _code_editor_theme = theme; - - // update select - var select_elem = document.getElementById("fs_select_editor_themes"); - var sibling = select_elem.firstElementChild; - while (sibling !== null) { - if (sibling.textContent === theme) { - sibling.selected = true; - break; - } - sibling = sibling.nextElementSibling; - } -}; - -var _changeEditorsFontSize = function (fontsize) { - var em_size = "1em"; - - if (fontsize === "XS") { - em_size = "1em"; - } else if (fontsize === "S") { - em_size = "1.25em"; - } else if (fontsize === "M") { - em_size = "1.5em"; - } else if (fontsize === "L") { - em_size = "1.75em"; - } else if (fontsize === "XL") { - em_size = "2em"; - } else if (fontsize === "XXL") { - em_size = "2.25em"; - } - - var i = 0; - for (i = 0; i < _code_editors.length; i += 1) { - _code_editors[i].container.style.fontSize = em_size; - } - - localStorage.setItem('fs-editor-font-size', fontsize); - - _code_editor_font_size = em_size; - - // update select - var select_elem = document.getElementById("fs_select_editor_fontsize"); - var sibling = select_elem.firstElementChild; - while (sibling !== null) { - if (sibling.textContent === fontsize) { - sibling.selected = true; - break; - } - sibling = sibling.nextElementSibling; - } -}; - -var _detachCodeEditor = function () { - // cm code will use these settings to setup its code editor - window.gb_code_editor_settings = _code_editor_settings; - window.gb_code_editor = _current_code_editor.editor; - window.gb_code_editor_theme = _code_editor_theme; - - var detached_window = window.open("", "_blank", [ - "toolbar=yes", - "location=no", - "directories=no", - "status=no", - "menubar=no", - "scrollbars=yes", - "resizable=yes", - "width=" + screen.width, - "height=" + screen.height, - "top=0", - "left=0"].join(',')); - - detached_window.document.write([ - '', - '', - '', - 'Fragment - ' + _current_code_editor.name, - '', - '', - '', - '', - '', - '', - '', - '', - '
', - '', - ''].join('')); - detached_window.document.close(); - - _current_code_editor.detached_windows.push(detached_window); - - // detached windows cleanup - var i = 0, j = 0; - for (i = 0; i < _code_editors.length; i += 1) { - var new_detached_windows = []; - - var detached_windows = _code_editors[i].detached_windows; - for (j = 0; j < detached_windows.length; j += 1) { - if (detached_windows[j] && !detached_windows[j].closed) { - new_detached_windows.push(detached_windows[j]); - } - } - - _code_editors[i].detached_windows = new_detached_windows; - } -}; - -var _getNewMark = function () { - var mark = document.createElement("div"); - mark.classList.add("fs-mark"); - mark.innerHTML = "*"; - - return mark; -}; - -var _findMark = function (code_editor, line) { - var i = 0; - for (i = 0; i < code_editor.marks.length; i += 1) { - if (code_editor.editor.getLineNumber(code_editor.marks[i]) === line) { - return true; - } - } - - return false; -}; - -var _deleteMark = function (code_editor, line) { - var i = 0; - for (i = 0; i < code_editor.marks.length; i += 1) { - if (code_editor.editor.getLineNumber(code_editor.marks[i]) === line) { - code_editor.marks.splice(i, 1); - break; - } - } - - clearTimeout(_save_marks_timer); - _save_marks_timer = setTimeout(_saveEditorMarks(code_editor), 5000); - - _updateOutline(code_editor.index); -}; - -var _addMarkDeleteEvent = function (code_editor, lineHandle) { - CodeMirror.on(lineHandle, 'delete', function () { - _deleteMark(code_editor, code_editor.editor.getLineNumber(lineHandle)); - }); -}; - -var _loadEditorsMarks = function (editor) { - var line = 0, - i = 0; - - if (_local_session_settings) { - if ('code_editors' in _local_session_settings) { - for (i = 0; i < _local_session_settings.code_editors.length; i += 1) { - var saved_code_editor = _local_session_settings.code_editors[i]; - - if (editor && editor.index !== i) { - continue; - } - - var code_editor = _code_editors[i]; - - if (!code_editor.marks) { - continue; - } - - code_editor.marks = []; - - var j = 0; - for (j = 0; j < saved_code_editor.marks.length; j += 1) { - line = saved_code_editor.marks[j]; - - code_editor.editor.setGutterMarker(line, "fs-mark", _getNewMark()); - - var lineHandle = code_editor.editor.getLineHandle(line); - code_editor.marks.push(lineHandle); - - _addMarkDeleteEvent(code_editor, lineHandle); - } - - _updateOutline(code_editor.index); - } - } - } -}; - -var _saveEditorMarks = function (code_editor) { - return function () { - var marks = [], - i = 0; - - for (i = 0; i < code_editor.marks.length; i += 1) { - marks.push(code_editor.editor.getLineNumber(code_editor.marks[i])); - } - - _local_session_settings.code_editors[code_editor.index].marks = marks.slice(); - _saveLocalSessionSettings(); - } -}; - -var _updateMarks = function (code_editor) { - return function () { - var found = 0; - var i, j; - for (i = 0; i < code_editor.marks.length; i += 1) { - var line = code_editor.editor.getLineNumber(code_editor.marks[i]); - for (j = 0; j < _local_session_settings.code_editors[code_editor.index].marks.length; j += 1) { - var line2 = _local_session_settings.code_editors[code_editor.index].marks[i]; - if (line == line2) { - found += 1; - } - } - - if (found === 0) { - break - } - } - - if (found === 0) { - _saveEditorMarks(code_editor)(); - } - }; -}; - -var _applyEditorsOption = function (key, value) { - var i = 0; - for (i = 0; i < _code_editors.length; i += 1) { - _code_editors[i].editor.setOption(key, value); - } -}; - -/*********************************************************** - Init. -************************************************************/ -/* jslint browser: true */ - -var _pause = function () { - if (!document.getElementById("fs_tb_pause").classList.contains("wui-toolbar-toggle-on")) { - WUI_ToolBar.toggle(_wui_main_toolbar, 6); - } - - window.cancelAnimationFrame(_raf); - - _fs_state = 1; - - _fasPause(); - - _pause_time = performance.now(); - - // clean playing MIDI notes - _MIDInotesCleanup(); - - // clean previous midi data (used to dectect note-on events) - for (var i = 0; i < _output_channels; i += 1) { - if (_prev_midi_data[i]) { - _prev_midi_data[i].fill(0, 0); - } - } - - _resetMIDIDevice(); - - _pjsPauseAll(); -}; - -var _play = function (update_global_time) { - _fs_state = 0; - - if (_glsl_error) { - return; - } - - window.cancelAnimationFrame(_raf); - _raf = window.requestAnimationFrame(_frame); - - if (update_global_time === undefined) { - _time += (performance.now() - _pause_time); - } - - try { - // compatibility - var ar = new Function("audio_ctx", "" + - "audio_ctx.resume().then(() => {" + - " console.log('Playback resumed successfully');" + - "});"); - - ar(_audio_context); - } catch (e) { - console.log(e); - } - - if (_first_play) { - _pjsCompileAll(); - - _first_play = false; - } - - _pjsResumeAll(); - - _fasUnpause(); -}; - -var _rewind = function () { - _globalFrame = 0; - - if (_fs_state === 0 && _glsl_error === false) { - _time = performance.now(); - } else { - _time = 0; - _pause_time = 0; - - if (_show_globaltime) { - _time_infos.innerHTML = parseInt(_time, 10); - } - } -}; - -var _stop = function () { - window.cancelAnimationFrame(_raf); - - _pause_time = performance.now(); - - _resetMIDIDevice(); -};/* jslint browser: true */ - - -/*********************************************************** - Fields. -************************************************************/ - -var _notes_renderer_worker = new Worker("dist/worker/notes_renderer.min.js"), - _audio_renderer_worker = new Worker("dist/worker/audio_renderer.min.js"), - _audio_recorder_worker = new Worker("dist/worker/recorder.min.js"); - -/*********************************************************** - Functions. -************************************************************/ - -var _exportRecord = function () { - var image_data = _record_canvas_ctx.getImageData(0, 0, _record_canvas.width, _record_canvas.height), - - sonogram_left_boundary, - sonogram_right_boundary, - - opts = { - float: _audio_infos.float_data, - ffreq: 0, - sps: _fas.fps, - octaves: _audio_infos.octaves, - baseFrequency: _audio_infos.base_freq, - flipY: false - }; - - sonogram_left_boundary = _getSonogramBoundary(image_data.data, _record_canvas.width, _record_canvas.height); - sonogram_right_boundary = _getSonogramBoundary(image_data.data, _record_canvas.width, _record_canvas.height, true); - - if (sonogram_left_boundary != -1 && sonogram_right_boundary != 1 && sonogram_left_boundary != sonogram_right_boundary) { - image_data = _record_canvas_ctx.getImageData(sonogram_left_boundary, 0, sonogram_right_boundary - sonogram_left_boundary, _record_canvas.height); - } - - opts.ffreq = _getFundamentalFrequency(image_data.data, image_data.width, image_data.height); - - _notification("image conversion in progress..."); - - _notes_renderer_worker.postMessage({ - data: image_data.data, - width: image_data.width, - height: image_data.height, - options: opts - }, [image_data.data.buffer]); -}; - -var _audioRecordToWav = function (audio_buffer, filename, ffreq) { - if (!audio_buffer) { - return; - } - - var date_now = (new Date().toLocaleDateString()).replace("/", "_"); - - if (!filename) { - filename = "fs_" + encodeURIComponent(_getSessionName()) + "_" + date_now + "_" + _truncateDecimals(ffreq, 2) + "hz_" + _MIDINoteName(_hzToMIDINote(ffreq)); - } - - _audio_recorder_worker.postMessage({ - command: 'init', - config: { - sampleRate: _audio_context.sampleRate, - numChannels: 2, - gain: _audio_infos.gain - } - }); - - _audio_recorder_worker.postMessage({ - command: 'record', - buffer: [ - audio_buffer.getChannelData(0), - audio_buffer.getChannelData(1) - ] - }); - - _audio_recorder_worker.postMessage({ - command: 'exportWAV', - type: 'audio/wav', - filename: filename - }); -}; - -_notes_renderer_worker.addEventListener("message", function (m) { - var w = m.data; - - w.sample_rate = _audio_context.sampleRate; - - _notification("image to sound conversion in progress..."); - - _audio_renderer_worker.postMessage(w); - }, false); - -_audio_renderer_worker.addEventListener("message", function (m) { - var w = m.data, - - data_l = new Float32Array(w.data_l), - data_r = new Float32Array(w.data_r), - - audio_buffer; - - _notification("exporting sound in progress..."); - - audio_buffer = _audio_context.createBuffer(2, w.length, _audio_context.sampleRate); - - audio_buffer.copyToChannel(data_l, 0, 0); - audio_buffer.copyToChannel(data_r, 1, 0); - - _audioRecordToWav(audio_buffer, null, w.opts.ffreq); - }, false); - -_audio_recorder_worker.addEventListener("message", function (m) { - var wav_blob = m.data.blob, - - file = new File([wav_blob], m.data.filename + ".wav", { - type: "audio/wav" - }); - - saveAs(file); - - _notification("exporting '" + m.data.filename + ".wav'"); - - _audio_recorder_worker.postMessage({ - command: 'clear' - }); - }, false); -/* jslint browser: true */ - - -/*********************************************************** - Fields. -************************************************************/ -var _last_workspace_target = 0; - -/*********************************************************** - Functions. -************************************************************/ - -var _updateWorkView = function () { - var explorer = document.getElementById("fs_explorer"), - //nodegraph_element = document.getElementById("fs_nodegraph"), - mid_panel = document.getElementById("fs_middle_panel"), - - mid_panel_offset = _getElementOffset(mid_panel), - - computed_height = (window.innerHeight - (mid_panel_offset.top + mid_panel_offset.height)) + "px"; - - explorer.style.height = computed_height; - //nodegraph_element.style.height = computed_height; - - var i = 0; - for (i = 0; i < _code_editors.length; i += 1) { - _code_editors[i].container.style.height = computed_height; - _code_editors[i].editor.refresh(); - } -/* - if (nodegraph_element.style.display !== "none") { - _lgraph_canvas.resize(); - } -*/ -}; - -var _workspaceClearSelection = function () { - var i = 0; - var active_items = document.getElementsByClassName("fs-workspace-item-active"); - - for (i = 0; i < active_items.length; i += 1) { - active_items[i].classList.remove("fs-workspace-item-active"); - } - - //document.getElementById("fs_nodegraph").style.display = "none"; - document.getElementById("fs_code").style.display = "none"; - //document.getElementById("fs_buffer_code").style.display = "none"; - document.getElementById("fs_library_code").style.display = "none"; - document.getElementById("fs_example_code").style.display = "none"; -}; - -var _isWorkspaceActive = function (id) { - var active_items = document.getElementsByClassName("fs-workspace-item-active"); - - return (active_items[0].id === id); -}; - -var _showWorkspace = function (target, i) { - return function () { - _workspaceClearSelection(); - - if (target === "fs-workspace-item") { - if (_last_workspace_target > 1) { - _pause(); - } - - if (i === 0) { - document.getElementById("fs_code").style.display = ""; - document.getElementById("fs_code_target").classList.add("fs-workspace-item-active"); - - _current_code_editor = _code_editors[i]; - - _last_workspace_target = 0; - } else if (i === 1) { - document.getElementById("fs_library_code").style.display = ""; - document.getElementById("fs_library_target").classList.add("fs-workspace-item-active"); - - _current_code_editor = _code_editors[i]; - - _last_workspace_target = 1; - } - - _compile(); - } else if (target === "fs-workspace-example-item") { - _pause(); - - var rootElement = document.getElementById("fs_examples_target"); - - rootElement.children[i].classList.add("fs-workspace-item-active"); - - document.getElementById("fs_example_code").style.display = ""; - - _current_code_editor = _code_editors[2]; - - _xhrContent("data/examples/" + rootElement.children[i].innerText + ".glsl", function (code) { - _current_code_editor.editor.setValue(code); - - _compile(); - }); - - _last_workspace_target = 2; - } - - _updateWorkView(); - }; -}; - -var _toggleReduce = function (ev) { - var content = this.parentElement.nextElementSibling; - - if (content.style.display === "none") { - content.style.display = ""; - this.textContent = "-"; - } else { - content.style.display = "none"; - this.textContent = "+"; - } -}; - -/*********************************************************** - Init. -************************************************************/ - -var _initWorkspace = function () { - var i = 0, - element; - - var workspace_items = document.getElementsByClassName("fs-workspace-item"); - - for (i = 0; i < workspace_items.length; i += 1) { - element = workspace_items[i]; - element.addEventListener("click", _showWorkspace("fs-workspace-item", i)); - } - - var workspace_example_items = document.getElementsByClassName("fs-workspace-example-item"); - - for (i = 0; i < workspace_example_items.length; i += 1) { - element = workspace_example_items[i]; - element.addEventListener("click", _showWorkspace("fs-workspace-example-item", i)); - } - - var workspace_reduce_btn = document.getElementsByClassName("fs-workspace-reduce-btn"); - - for (i = 0; i < workspace_reduce_btn.length; i += 1) { - element = workspace_reduce_btn[i]; - element.addEventListener("click", _toggleReduce); - } -}/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _ffs_address = _domain + ":3122", - _dir_state = new Map(), - _selected_files = new Map(), - _file_check_state = null; - -/*********************************************************** - Functions. -************************************************************/ - -var _minimizeFilesTree = function (key) { - return function (ev) { - if (ev.target.tagName === "INPUT") { - return; - } - - var target_elem = ev.currentTarget.nextElementSibling; - - if (target_elem.style.display) { - target_elem.style.display = ""; - ev.currentTarget.firstElementChild.classList.remove('fs-rotate-text-right'); - - _dir_state.set(key, true); - } else { - target_elem.style.display = "none"; - ev.currentTarget.firstElementChild.classList.add('fs-rotate-text-right'); - - _dir_state.set(key, false); - } - }; -}; - -var _onFmDragStart = function (e) { - e.preventDefault(); - e.stopPropagation(); -}; - -var _onFmDragOver = function (e) { - e.preventDefault(); - e.stopPropagation(); - - e.currentTarget.classList.add('fs-file-manager-dragover'); - - e.dataTransfer.dropEffect = "copy"; -}; - -var _onFmDragEnd = function (e) { - e.currentTarget.classList.remove('fs-file-manager-dragover'); - - e.preventDefault(); - e.stopPropagation(); -}; - -var _onFmDragDrop = function (src_element, target, target_element_id, target_name) { - return function (e) { - e.preventDefault(); - e.stopPropagation(); - - var files = e.dataTransfer.files; - - var form_data = new FormData(); - for (var i = 0; i < files.length; i++) { - form_data.append('file', files[i]); - } - - var xhr = new XMLHttpRequest(); - xhr.open('POST', 'http://' + _ffs_address + '/uploads?target=' + encodeURI(target), true); - xhr.upload.onprogress = function (e) { - if (e.lengthComputable) { - var complete = (e.loaded / e.total * 100 | 0); - - _notification('Files upload status : ' + complete + '%', 2000); - } - }; - xhr.onerror = function () { - _notification('File manager server error (is it up ?)', 4000); - - console.log(xhr.responseText); - - src_element.classList.remove('fs-file-manager-dragover'); - }; - xhr.onload = function () { - if (xhr.status === 200) { - _notification('Files upload status : done.', 2000); - - _refreshFileManager(target_element_id, target_name)(); - } else if (xhr.status === 500) { - _notification('Files upload error (unsupported file format ?)', 4000) - } else { - _notification('Files upload error (unknown)', 4000) - } - - src_element.classList.remove('fs-file-manager-dragover'); - }; - - xhr.send(form_data); - }; -}; - -var _fileCheckboxOver = function (id) { - return function (e) { - if (_mouse_btn === _LEFT_MOUSE_BTN) { - var checkbox = this.ownerDocument.getElementById(id); - - if (_file_check_state === null) { - _file_check_state = 1 - checkbox.checked; - } - - checkbox.checked = _file_check_state; - } else { - _file_check_state = null; - } - - e.stopPropagation(); - e.preventDefault(); - }; -} - -var _renderFilesTree = function (dom_node, target_element_id, target) { - return function (leaf_obj, dirname) { - var detached_window = WUI_Dialog.getDetachedDialog(target_element_id); - - var doc = detached_window ? detached_window.document : document; - var win = detached_window ? detached_window : window; - - var dir_container = doc.createElement('div'); - var header_container = doc.createElement('div'); - var min_btn = doc.createElement('div'); - var dir_name = doc.createElement('div'); - var dir_content = doc.createElement('div'); - var files_content = doc.createElement('div'); - var dir_checkbox = doc.createElement('input'); - - dir_checkbox.type = 'checkbox'; - dir_checkbox.className = 'fs-file-manager-file-checkbox'; - dir_checkbox.id = "fs_" + target + '_' + win.btoa(leaf_obj.basepath); - - dir_checkbox.dataset.fullpath = win.btoa(leaf_obj.basepath); - var basepath = dir_checkbox.dataset.fullpath; - basepath = basepath.split('/'); - basepath.pop(); - basepath = basepath.join('/'); - dir_checkbox.dataset.basepath = basepath; - dir_checkbox.dataset.filename = win.btoa(dirname); - - dir_container.classList.add('fs-file-manager-node'); - header_container.classList.add('fs-file-manager-header'); - min_btn.classList.add('fs-file-manager-min-btn'); - min_btn.classList.add('fs-rotate-text-right'); - min_btn.innerHTML = "⌄"; - dir_name.classList.add('fs-file-manager-dir-name'); - dir_content.classList.add('fs-file-manager-dir-content'); - files_content.classList.add('fs-file-manager-files-content'); - - // drag & drop - ['drag','dragstart'].forEach(function (event_name) { - files_content.addEventListener(event_name, _onFmDragStart) - header_container.addEventListener(event_name, _onFmDragStart) - }); - - ['dragover','dragenter'].forEach(function (event_name) { - files_content.addEventListener(event_name, _onFmDragOver) - header_container.addEventListener(event_name, _onFmDragOver) - }); - - ['dragleave','dragend'].forEach(function (event_name) { - files_content.addEventListener(event_name, _onFmDragEnd) - header_container.addEventListener(event_name, _onFmDragEnd) - }); - - header_container.addEventListener('drop', _onFmDragDrop(header_container, leaf_obj.basepath, target_element_id, target)); - files_content.addEventListener('drop', _onFmDragDrop(files_content, leaf_obj.basepath, target_element_id, target)); - // - - dir_content.style.display = "none"; - - header_container.addEventListener("click", _minimizeFilesTree(leaf_obj.basepath)); - - dir_name.innerText = dirname; - - var leaf = leaf_obj.leaf; - - leaf.forEach(_renderFilesTree(dir_content, target_element_id, target)) - - if (leaf_obj.items) { - var files = leaf_obj.items; - - dir_name.title += "Files : " + files.length; - - if (files.length > 1) { - dir_name.title += ' [' + files[0].index + ',' + files[files.length - 1].index + ']'; - } - - var i = 0; - for (i = 0; i < files.length; i += 1) { - var file_container = doc.createElement('div'); - var file_name = doc.createElement('label'); - var checkbox = doc.createElement('input'); - checkbox.type = 'checkbox'; - checkbox.className = 'fs-file-manager-file-checkbox'; - checkbox.id = "fs_" + target + '_' + files[i].index; - - var f = _fileCheckboxOver(checkbox.id); - - checkbox.addEventListener('mouseleave', f); - file_name.addEventListener('mouseleave', f); - checkbox.addEventListener('mouseenter', f); - file_name.addEventListener('mouseenter', f); - - file_container.classList.add('fs-file-manager-file-container'); - file_name.classList.add('fs-file-manager-file-name'); - - file_name.setAttribute('for', checkbox.id); - checkbox.dataset.fullpath = win.btoa(leaf_obj.basepath + "/" + files[i].filename); - checkbox.dataset.filename = win.btoa(files[i].filename); - checkbox.dataset.basepath = win.btoa(leaf_obj.basepath); - - file_name.innerText = files[i].index + " " + files[i].filename; - file_name.dataset.clipboardText = files[i].float_index; - file_name.title = files[i].float_index; - - file_container.appendChild(checkbox); - file_container.appendChild(file_name); - - files_content.appendChild(file_container); - } - } - - dir_content.appendChild(files_content); - - header_container.appendChild(min_btn); - header_container.appendChild(dir_checkbox); - header_container.appendChild(dir_name); - dir_container.appendChild(header_container); - - dir_container.appendChild(dir_content); - - dom_node.appendChild(dir_container); - - if (_dir_state.has(leaf_obj.basepath)) { - var state = _dir_state.get(leaf_obj.basepath); - if (state) { - dir_content.style.display = ""; - min_btn.classList.remove('fs-rotate-text-right'); - } else { - dir_content.style.display = "none"; - min_btn.classList.add('fs-rotate-text-right'); - } - } - }; -}; - -var _closeFileManager = function (target_element_id) { - return function () { - var element = document.getElementById(target_element_id).firstElementChild.nextElementSibling; - - element.innerHTML = ''; - }; -}; - -var _refreshFileManager = function (target_element_id, target) { - return function () { - var detached_window = WUI_Dialog.getDetachedDialog(target_element_id); - var doc = document; - var win = window; - var element = null; - - if (detached_window) { - doc = detached_window.document; - win = detached_window; - - element = doc.getElementById(target_element_id).firstElementChild; - } else { - element = doc.getElementById(target_element_id).firstElementChild.nextElementSibling; - } - - var req = new XMLHttpRequest(); - req.responseType = 'json'; - req.open('GET', 'http://' + _ffs_address + '/' + target, true); - req.onerror = function () { - _notification('File manager server error (is it up ?)'); - - var error_elem = doc.createElement('div'); - var reload_btn = doc.createElement('div'); - reload_btn.className = 'fs-btn fs-btn-default'; - reload_btn.innerText = 'refresh'; - - reload_btn.addEventListener('click', _refreshFileManager(target_element_id, target)); - - error_elem.classList.add('fs-file-manager-error'); - - error_elem.innerHTML = 'File manager server connection error...
Should be up at ' + 'http://' + _ffs_address + '

'; - - error_elem.appendChild(reload_btn); - element.appendChild(error_elem); - }; - req.onload = function () { - element.innerHTML = ''; - - var file_index = 0; - var leaf = new Map(); - var tree = { leaf: new Map(), basepath: target }; - leaf.set(target, tree); - var json_response = req.response; - var files = json_response.files; - var empty_dirs = json_response.empty_dirs; - - // files - var i = 0; - for (i = 0; i < files.length; i += 1) { - var dirs = files[i].split('/'); - - var leaf_map = tree.leaf; - var leaf_obj = tree; - var j = 0; - for (j = 0; j < dirs.length - 1; j += 1) { - var basepath = dirs.slice(0, j+1); - basepath = target + '/' + basepath.join('/'); - - var dir_name = dirs[j]; - - if (!leaf_map.has(dir_name)) { - leaf_map.set(dir_name, { leaf: new Map(), basepath: basepath }); - } - - leaf_obj = leaf_map.get(dir_name); - leaf_map = leaf_obj.leaf; - } - - if (!leaf_obj.items) { - leaf_obj.items = []; - } - - var filename = dirs[dirs.length - 1]; - leaf_obj.items.push({ filename: filename, index: file_index, float_index: _truncateDecimals(file_index / files.length, 7) }); - - file_index += 1; - } - - // add empty dirs (done in two pass to compute indexes easily) - for (i = 0; i < empty_dirs.length; i += 1) { - var dirs = empty_dirs[i].split('/'); - - var leaf_map = tree.leaf; - var leaf_obj = tree; - var j = 0; - for (j = 0; j < dirs.length; j += 1) { - var basepath = dirs.slice(0, j+1); - basepath = target + '/' + basepath.join('/'); - - var dir_name = dirs[j]; - if (!leaf_map.has(dir_name)) { - leaf_map.set(dir_name, { leaf: new Map(), basepath: basepath }); - } - - leaf_obj = leaf_map.get(dir_name); - leaf_map = leaf_obj.leaf; - } - } - - var file_manager_container = doc.createElement('div'); - var file_manager_node = doc.createElement('div'); - - file_manager_container.classList.add('fs-file-manager'); - file_manager_node.classList.add('fs-file-manager-node'); - - leaf.forEach(_renderFilesTree(file_manager_node, target_element_id, target)); - - file_manager_container.appendChild(file_manager_node); - - element.appendChild(file_manager_container); - - element.addEventListener('contextmenu', function (ev) { - ev.preventDefault(); - - if (ev.target.classList.contains('fs-file-manager-header') || - ev.target.classList.contains('fs-file-manager-min-btn') || - ev.target.classList.contains('fs-file-manager-dir-name')) { - WUI_CircularMenu.create( - { - x: ev.clientX, - y: ev.clientY, - - rx: 24, - ry: 24, - - angle: -90, - - item_width: 32, - item_height: 32, - - window: detached_window - }, - [ - { icon: "fs-plus-icon", tooltip: "New directory", on_click: function () { - var dir_target = ev.target; - if (ev.target.classList.contains('fs-file-manager-header')) { - dir_target = ev.target.firstElementChild.nextElementSibling; - } else if (ev.target.classList.contains('fs-file-manager-min-btn')) { - dir_target = ev.target.nextElementSibling; - } else if (ev.target.classList.contains('fs-file-manager-dir-name')) { - dir_target = ev.target.previousElementSibling; - } - - var target_path = win.atob(dir_target.dataset.fullpath); - target_path = target_path.split('/'); - target_path.shift(); - target_path = target_path.join('/'); - - var dir_name = win.prompt('Directory name', ''); - if (!dir_name || !dir_name.length) { - return; - } - - var directories = [target_path + '/' + dir_name]; - - var xhr = new XMLHttpRequest(); - xhr.open('PUT', 'http://' + _ffs_address + '/' + target + '?action=create', true); - xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); - xhr.onerror = function () { - _notification('File manager server error (is it up ?)', 4000); - - console.log(xhr.responseText); - }; - xhr.onload = function () { - if (xhr.status === 200) { - _refreshFileManager(target_element_id, target)(); - } else { - _notification('Files move / rename error (unknown)', 4000) - } - }; - - xhr.send(JSON.stringify(directories)); - } }, - { icon: "fs-replace-icon", tooltip: "Move selected files here", on_click: function () { - var dir_target = ev.target; - if (ev.target.classList.contains('fs-file-manager-header')) { - dir_target = ev.target.firstElementChild.nextElementSibling; - } else if (ev.target.classList.contains('fs-file-manager-min-btn')) { - dir_target = ev.target.nextElementSibling; - } else if (ev.target.classList.contains('fs-file-manager-dir-name')) { - dir_target = ev.target.previousElementSibling; - } - - var target_path = win.atob(dir_target.dataset.fullpath); - target_path = target_path.split('/'); - target_path.shift(); - target_path = target_path.join('/'); - - var selected_files = doc.querySelectorAll("input[id^='fs_" + target + "_']:checked"); - - if (!selected_files.length) { - return; - } - - var files = []; - - var i = 0; - for (i = 0; i < selected_files.length; i += 1) { - var fullpath = win.atob(selected_files[i].dataset.fullpath); - fullpath = fullpath.split('/'); - fullpath.shift(); - fullpath = fullpath.join('/'); - - files.push({ src: fullpath, dst: target_path }); - } - - var xhr = new XMLHttpRequest(); - xhr.open('PUT', 'http://' + _ffs_address + '/' + target + '?action=move', true); - xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); - xhr.onerror = function () { - _notification('File manager server error (is it up ?)', 4000); - - console.log(xhr.responseText); - }; - xhr.onload = function () { - if (xhr.status === 200) { - _refreshFileManager(target_element_id, target)(); - } else { - _notification('Files move / rename error (unknown)', 4000) - } - }; - - xhr.send(JSON.stringify(files)); - } } - ]); - return true; - } - - WUI_CircularMenu.create( - { - x: ev.clientX, - y: ev.clientY, - - rx: 32, - ry: 32, - - item_width: 32, - item_height: 32, - - window: detached_window - }, - [ - { icon: "fs-audio-file-icon", tooltip: "Download selected files", on_click: function () { - var selected_files = doc.querySelectorAll("input[id^='fs_" + target + "_']:checked"); - - if (!selected_files.length) { - return; - } - - var files_to_download = []; - - var i = 0; - for (i = 0; i < selected_files.length; i += 1) { - var fullpath = win.atob(selected_files[i].dataset.fullpath); - fullpath = fullpath.split('/'); - fullpath.shift(); - fullpath = fullpath.join('/'); - - files_to_download.push(fullpath); - } - - var xhr = new XMLHttpRequest(); - xhr.open("POST", 'http://' + _ffs_address + '/download/' + target, true); - xhr.responseType = 'blob'; - xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); - xhr.onerror = function () { - _notification('File manager server error (is it up ?)', 4000); - - console.log(xhr.responseText); - }; - xhr.onreadystatechange = function() { - if (this.readyState == 4 && this.status == 200) { - var blob = new Blob([this.response], {type: 'application/zip'}); - - var url = URL.createObjectURL(xhr.response); - var a = doc.createElement("a"); - - doc.body.appendChild(a); - a.style = "display: none"; - a.href = url; - a.download = ""; - - a.click(); - - win.URL.revokeObjectURL(url); - - doc.body.removeChild(a); - } else if (this.status == 200) { - _notification('Files download error (unknown)', 4000) - } - }; - xhr.send(JSON.stringify(files_to_download)); - } }, - { icon: "fs-code-icon", tooltip: "Rename selected file", on_click: function () { - var selected_files = doc.querySelectorAll("input[id^='fs_" + target + "_']:checked"); - - if (!selected_files.length || selected_files.length > 1) { - _notification("Must select a single file to rename", 4000); - return; - } - - var files_to_rename = []; - - var file = selected_files[0]; - var fullpath = win.atob(file.dataset.fullpath); - fullpath = fullpath.split('/'); - fullpath.shift(); - fullpath = fullpath.join('/'); - - var basepath = win.atob(file.dataset.basepath); - basepath = basepath.split('/'); - basepath.shift(); - basepath = basepath.join('/'); - var filename = win.atob(file.dataset.filename); - var new_name = win.prompt('Rename file', filename) - if (!new_name || !new_name.length) { - return; - } - - var file_obj = { src: fullpath, dst: basepath + new_name }; - - files_to_rename.push(file_obj); - - var xhr = new XMLHttpRequest(); - xhr.open('PUT', 'http://' + _ffs_address + '/' + target + '?action=rename', true); - xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); - xhr.onerror = function () { - _notification('File manager server error (is it up ?)', 4000); - - console.log(xhr.responseText); - }; - xhr.onload = function () { - if (xhr.status === 200) { - _refreshFileManager(target_element_id, target)(); - } else { - _notification('Files move / rename error (unknown)', 4000) - } - }; - - xhr.send(JSON.stringify(files_to_rename)); - } }, - { icon: "fp-trash-icon", tooltip: "Delete selected files", on_click: function () { - var selected_files = doc.querySelectorAll("input[id^='fs_" + target + "_']:checked"); - - if (!selected_files.length) { - return; - } - - var files_to_delete = []; - - var i = 0; - for (i = 0; i < selected_files.length; i += 1) { - var fullpath = win.atob(selected_files[i].dataset.fullpath); - fullpath = fullpath.split('/'); - fullpath.shift(); - fullpath = fullpath.join('/'); - - files_to_delete.push(fullpath); - } - - var xhr = new XMLHttpRequest(); - xhr.open('DELETE', 'http://' + _ffs_address + '/' + target, true); - xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); - xhr.onerror = function () { - _notification('File manager server error (is it up ?)', 4000); - - console.log(xhr.responseText); - }; - xhr.onload = function () { - if (xhr.status === 200) { - _refreshFileManager(target_element_id, target)(); - } else { - _notification('Files deletion error (unknown)', 4000) - } - }; - - xhr.send(JSON.stringify(files_to_delete)); - } } - ]); - - return false; - }, false); - - var clip = new Clipboard('.fs-file-manager-file-name'); - }; - req.send(null); - }; -}; - -/*********************************************************** - Init. -************************************************************/ - -/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _icon_class = { - plus: "fs-plus-icon" - }, - - _selected_slice, - - _brush_helper_timeout, - - _midi_out_editor, - - _midi_out_dialog_id = "fs_midi_out_dialog", - _midi_out_dialog, - - _paint_dialog_id = "fs_paint_dialog", - _paint_dialog, - - _settings_dialog_id = "fs_settings_dialog", - _settings_dialog, - - _midi_settings_dialog_id = "fs_midi_settings_dialog", - _midi_settings_dialog, - - _help_dialog_id = "fs_help_dialog", - _help_dialog, - - _analysis_dialog_id = "fs_analysis_dialog", - _analysis_dialog, - - _record_dialog_id = "fs_record_dialog", - _record_dialog, - - _outline_dialog_id = "fs_outline_dialog", - _outline_dialog, - - _slices_dialog_id = "fs_slices_dialog", - _slices_dialog, - - _samples_dialog_id = "fs_samples_dialog", - _samples_dialog, - - _waves_dialog_id = "fs_waves_dialog", - _waves_dialog, - - _impulses_dialog_id = "fs_impulses_dialog", - _impulses_dialog, - - _faust_gens_dialog_id = "fs_faust_gens_dialog", - _faust_gens_dialog, - - _faust_effs_dialog_id = "fs_faust_effs_dialog", - _faust_effs_dialog, - - _slices_dialog_timeout = null, - - _import_dialog_id = "fs_import_dialog", - _import_dialog, - - _quickstart_dialog_id = "fs_quickstart", - _quickstart_dialog, - - _fas_dialog_id = "fs_fas_dialog", - _fas_dialog, - - _fas_synth_params_dialog_id = "fs_fas_synth_params_dialog", - _fas_synth_params_dialog, - - _fas_chn_notify_timeout, - - _wui_main_toolbar, - - _collapsible_id = 0, - - _fas_settings_collapses = { - instruments: false, - channels: true, - actions: true, - file_managers: true - }, - - _send_slices_settings_timeout, - _add_slice_timeout, - _remove_slice_timeout, - - _synthesis_types = ["Additive", "Spectral", "Granular", "PM/FM", "Subtractive", "Physical Model", "Wavetable", "Bandpass (M)", "Formant (M)", "Phase Distorsion (M)", "String resonance (M)", "Modal (M)", "Modulation", "In", "Faust"], - _synthesis_enabled = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], - _synthesis_params = [0, 3, 3, 2, 1, 2, 1, 1, 0, 0, 0, 0, 5, 0, 5], - - _efx = [{ - name: "Convolution", - color: "#00ffff", - params: [{ - name: "Impulse index (l)", - type: 0, - min: 0, - step: 1, - value: 0, - decimals: 0 - }, { - name: "Partition length (l)", - type: [256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536], - value: 4 - }, - { - name: "Impulse index (r)", - type: 0, - min: 0, - step: 1, - value: 0, - decimals: 0 - }, { - name: "Partition length (r)", - type: [256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536], - value: 4 - }, - { - name: "Dry (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - }, - { - name: "Wet (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.02, - decimals: 4 - }, - { - name: "Dry (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - }, - { - name: "Wet (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.02, - decimals: 4 - }] - }, - { - name: "Zitareverb", - color: "#00bfff", - params: [{ - name: "In delay", - type: 0, - min: 0, - step: 1, - value: 60, - decimals: 0 - }, { - name: "Crossover freq.", - type: 0, - min: 0, - step: 1, - value: 200, - decimals: 0 - }, { - name: "RT60 low time", - type: 0, - min: 0, - step: 0.1, - value: 3.0, - decimals: 4 - }, { - name: "RT60 mid time", - type: 0, - min: 0, - step: 0.1, - value: 2.0, - decimals: 4 - }, { - name: "HF damping", - type: 0, - min: 0, - step: 1, - value: 6000.0, - decimals: 4 - }, { - name: "EQ1 frequency", - type: 0, - min: 0, - step: 0.1, - value: 315.0, - decimals: 4 - }, { - name: "EQ1 level", - type: 0, - min: 0, - step: 0.1, - value: 0, - decimals: 4 - }, { - name: "EQ2 frequency", - type: 0, - min: 0, - step: 1, - value: 1500.0, - decimals: 4 - }, { - name: "EQ2 level", - type: 0, - min: 0, - step: 0.1, - value: 0, - decimals: 4 - }, { - name: "Mix", - type: 0, - min: 0, - step: 0.0001, - value: 1, - decimals: 4 - }, { - name: "level", - type: 0, - step: 1, - value: 0, - decimals: 0 - }] - },{ - name: "8 FDN Stereo Reverb", - color: "#483d8b", - params: [{ - name: "feedback", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "lpfreq", - type: 0, - min: 1000, - step: 1, - value: 10000, - decimals: 0 - }, - { - name: "Dry", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - }, - { - name: "Wet", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.02, - decimals: 4 - }] - },{ - name: "Autowah", - color: "#000080", - params: [{ - name: "level (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "wah (l)", - type: 0, - min: 0, - step: 0.0001, - value: 0, - decimals: 4 - }, { - name: "mix (l)", - type: 0, - min: 0, - max: 100, - step: 1, - value: 50, - decimals: 0 - },{ - name: "level (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "wah (r)", - type: 0, - min: 0, - step: 0.0001, - value: 0, - decimals: 4 - }, { - name: "mix (r)", - type: 0, - min: 0, - max: 100, - step: 1, - value: 50, - decimals: 0 - }] - },{ - name: "Phaser", - color: "#9acd32", - params: [{ - name: "MaxNotch1Freq", - type: 0, - min: 20, - max: 10000, - step: 1, - value: 800, - decimals: 0 - }, { - name: "MinNotch1Freq", - type: 0, - min: 20, - max: 5000, - step: 1, - value: 100, - decimals: 0 - }, { - name: "NotchWidth", - type: 0, - min: 10, - max: 5000, - step: 1, - value: 100, - decimals: 0 - }, { - name: "NotchFreq", - type: 0, - min: 1.1, - max: 4, - step: 0.0001, - value: 1.5, - decimals: 4 - }, { - name: "VibratoMode", - type: 0, - min: 0, - max: 1, - step: 1, - value: 1, - decimals: 0 - }, { - name: "Depth", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - }, { - name: "Feedback gain", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0, - decimals: 4 - }, { - name: "Invert", - type: 0, - min: 0, - max: 1, - step: 1, - value: 1, - decimals: 0 - }, { - name: "level", - type: 0, - min: -60, - max: 10, - step: 1, - value: 0, - decimals: 0 - }, { - name: "lfo bpm", - type: 0, - min: 24, - max: 360, - step: 1, - value: 30, - decimals: 0 - }] - },{ - name: "Comb filter", - color: "#daa520", - params: [{ - name: "looptime (l)", - type: 0, - min: 0, - max: 5, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "revtime (l)", - type: 0, - min: 0, - max: 10, - step: 0.0001, - value: 3.5, - decimals: 4 - }, { - name: "looptime (r)", - type: 0, - min: 0, - max: 5, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "revtime (r)", - type: 0, - min: 0, - max: 10, - step: 0.0001, - value: 3.5, - decimals: 4 - }, - { - name: "Dry (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Dry (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Delay", - color: "#8b008b", - params: [{ - name: "delay time (l)", - type: 0, - min: 1, - max: 120, - step: 1, - value: 1.0, - decimals: 0 - }, { - name: "feedback (l)", - type: 0, - min: 0, - max: 1, - step: 0.000001, - value: 0, - decimals: 6 - }, - { - name: "delay time (r)", - type: 0, - min: 1, - max: 120, - step: 1, - value: 1.0, - decimals: 0 - }, { - name: "feedback (r)", - type: 0, - min: 0, - max: 1, - step: 0.000001, - value: 0, - decimals: 6 - }, - { - name: "Dry (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Dry (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Smooth Delay", - color: "#ff4500", - params: [{ - name: "maxdel (l)", - type: 0, - min: 0.0001, - max: 20, - step: 0.0001, - value: 1, - decimals: 4 - }, { - name: "interp. time (l)", - type: [64, 128, 256, 512, 1024, 2048, 4096], - value: 3 - }, { - name: "feedback (l)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "delay time (l)", - type: 0, - min: 0.0001, - max: 20, - step: 0.0001, - value: 0.5, - decimals: 4 - },{ - name: "maxdel (r)", - type: 0, - min: 0.0001, - max: 20, - step: 0.0001, - value: 1, - decimals: 4 - }, { - name: "interp. time (r)", - type: [64, 128, 256, 512, 1024, 2048, 4096], - value: 3 - }, { - name: "feedback (r)", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.1, - decimals: 4 - }, { - name: "delay time (r)", - type: 0, - min: 0.0001, - max: 20, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Decimator", - color: "#ffff00", - params: [{ - name: "bitdepth", - type: 0, - min: 1, - max: 16, - step: 1, - value: 8, - decimals: 0 - }, { - name: "srate", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 10000, - decimals: 0 - }, { - name: "Dry", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Distorsion", - color: "#7cfc00", - params: [{ - name: "pregain", - type: 0, - min: 0, - max: 4, - step: 0.0001, - value: 2, - decimals: 4 - },{ - name: "postgain", - type: 0, - min: 0, - max: 4, - step: 0.0001, - value: 0.5, - decimals: 4 - },{ - name: "shape1", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0, - decimals: 4 - },{ - name: "shape2", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0, - decimals: 4 - }, { - name: "Dry", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Saturator", - color: "#8a2be2", - params: [{ - name: "drive", - type: 0, - min: 0, - max: 20, - step: 1, - value: 1, - decimals: 0 - }, { - name: "dc offset", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0, - decimals: 4 - }, { - name: "Dry", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Compressor", - color: "#00ff7f", - params: [{ - name: "ratio", - type: 0, - min: 0, - max: 20, - step: 0.1, - value: 1, - decimals: 1 - }, { - name: "tresh", - type: 0, - min: -40, - max: 40, - step: 1, - value: 0, - decimals: 0 - }, { - name: "attack", - type: 0, - min: 0, - max: 4, - step: 0.01, - value: 0.1, - decimals: 2 - }, { - name: "release", - type: 0, - min: 0, - max: 4, - step: 0.01, - value: 0.1, - decimals: 2 - }] - },{ - name: "Peak Limiter", - color: "#dc143c", - params: [{ - name: "attack", - type: 0, - min: 0, - max: 4, - step: 0.01, - value: 0.01, - decimals: 2 - }, { - name: "release", - type: 0, - min: 0, - max: 4, - step: 0.01, - value: 0.01, - decimals: 2 - }, { - name: "tresh", - type: 0, - min: -20, - max: 40, - step: 1, - value: 0, - decimals: 0 - }, { - name: "Dry", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Clip", - color: "#696969", - params: [{ - name: "tresh", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - }, { - name: "Dry", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }, - { - name: "Wet", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - },{ - name: "Lowpass Butterworth", - color: "#856b2f", - params: [{ - name: "cutoff", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 1000, - decimals: 0 - }] - },{ - name: "Highpass Butterworth", - color: "#0000ff", - params: [{ - name: "cutoff", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 1000, - decimals: 0 - }] - },{ - name: "Bandpass Butterworth", - color: "#ff00ff", - params: [{ - name: "cutoff", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 1000, - decimals: 0 - },{ - name: "bw", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 10, - decimals: 0 - }] - },{ - name: "Bandreject Butterworth", - color: "#1e90ff", - params: [{ - name: "cutoff", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 1000, - decimals: 0 - },{ - name: "bw", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 1000, - decimals: 0 - }] - },{ - name: "Parametric EQ", - color: "#db7093", - params: [{ - name: "fc", - type: 0, - min: 1, - max: 96000, - step: 1, - value: 1000, - decimals: 0 - },{ - name: "v", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - },{ - name: "q", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 1, - decimals: 4 - },{ - name: "eq mode", - type: 0, - min: 0, - max: 2, - step: 1, - value: 0, - decimals: 0 - }] - },{ - name: "Moog LPF", - color: "#eee8aa", - params: [{ - name: "cutoff", - type: 0, - min: 1, - step: 1, - value: 1000, - decimals: 0 - }, { - name: "res", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.01, - decimals: 4 - }] - },{ - name: "Diode LPF", - color: "#ff1493", - params: [{ - name: "cutoff", - type: 0, - min: 1, - step: 1, - value: 1000, - decimals: 0 - }, { - name: "res", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.01, - decimals: 4 - }] - },{ - name: "Korg35 LPF", - color: "#ffa07a", - params: [{ - name: "cutoff", - type: 0, - min: 1, - step: 1, - value: 1000, - decimals: 0 - }, { - name: "res", - type: 0, - min: 0, - max: 2, - step: 0.0001, - value: 1, - decimals: 4 - }, { - name: "saturation", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.01, - decimals: 4 - }] - },{ - name: "18db LPF", - color: "#ee82ee", - params: [{ - name: "cutoff", - type: 0, - min: 1, - step: 1, - value: 1000, - decimals: 0 - }, { - name: "res", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.8, - decimals: 4 - }, { - name: "saturation", - type: 0, - min: 0, - max: 4, - step: 0.0001, - value: 2, - decimals: 4 - }] - },{ - name: "TB303 VCF", - color: "#f0f8ff", - params: [{ - name: "cutoff", - type: 0, - min: 1, - step: 1, - value: 500, - decimals: 0 - }, { - name: "res", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.8, - decimals: 4 - }, { - name: "distorsion", - type: 0, - min: 0, - max: 4, - step: 0.0001, - value: 2, - decimals: 4 - }, { - name: "asym", - type: 0, - min: 0, - max: 1, - step: 0.0001, - value: 0.5, - decimals: 4 - }] - }, - { - name: "Fold", - color: "#800040", - params: [{ - name: "Increment", - type: 0, - min: 0, - max: 2048, - step: 1, - value: 1, - decimals: 0 - }] - }, - { - name: "DC block filter", - color: "#80dd40", - params: [] - }, - { - name: "LPC", - color: "#20dd40", - params: [ - { - name: "Encoder frame size", - type: [64, 128, 256, 512, 1024, 2048, 4096], - value: 3 - } - ] - }, - { - name: "Time-Stretcher", - color: "#90aaaa", - params: [{ - name: "Buffer length (secs)", - type: 0, - min: 0, - step: 0.000001, - value: 1, - decimals: 6 - }, { - name: "Number of repeats", - type: 0, - min: 0, - step: 0.000001, - value: 1.5, - decimals: 6 - }] - }, - { - name: "Panner", - color: "#90aaaa", - params: [{ - name: "Type", - type: [0, 1, 2, 3], - value: 0 - }, { - name: "Panning", - type: 0, - min: -1, - max: 1, - step: 0.000001, - value: 0, - decimals: 6 - }] - }, - { - name: "Faust", - color: "#ffffff", - params: [{ - name: "Effect ID", - type: 0, - min: 0, - step: 1, - value: 0, - decimals: 0 - }, { - name: "p0", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p1", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p2", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p3", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p4", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p5", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p6", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p7", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p8", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }, { - name: "p9", - type: 0, - step: 0.000001, - value: 0, - decimals: 6 - }] - }], - - _fas_content_list = []; - -/*********************************************************** - Functions. -************************************************************/ - -var _togglePlay = function (toggle_ev) { - if (toggle_ev.state) { - _pause(); - } else { - _play(); - } -}; - -var _showHelpDialog = function () { - WUI_Dialog.open(_help_dialog); -}; - -var _showSettingsDialog = function () { - WUI_Dialog.open(_settings_dialog); -}; - -var _showMIDISettingsDialog = function () { - WUI_Dialog.open(_midi_settings_dialog); -}; - -var _showMIDIOutDialog = function () { - WUI_Dialog.open(_midi_out_dialog); -}; - -var _onChangeChannelSettings = function (instrument_index, target) { - return function (value) { - var v = parseFloat(value); - - //_chn_settings[channel].osc[value_index] = v; - - //_local_session_settings.chn_settings[channel] = _chn_settings[channel]; - //_saveLocalSessionSettings(); - - //_fasNotify(_FAS_CHN_INFOS, { target: Math.floor(value_index / 2), chn: channel, value: v }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: target, value: v }); - - var obj = { }; - obj["p" + (target - 3)] = v; - - _sendSliceUpdate(instrument_index, { instruments_settings : obj }); - - var slice = _play_position_markers[instrument_index]; - slice.instrument_params["p" + (target - 3)] = v; - }; -}; - -var _toggleCollapse = function (element, cb) { - return function (ev) { - var elem = ev.target.ownerDocument.getElementById(element.id); - - elem.classList.toggle("fs-collapsible"); - elem.classList.toggle("fs-collapsed"); - - ev.stopPropagation(); - - if (cb) { - if (elem.classList.contains("fs-collapsed")) { - cb(true); - } else { - cb(false); - } - } - }; -}; - -var _applyCollapsible = function (element, bind_to, collapsed, cb) { - element.id = "fs_collapsible_" + _collapsible_id; - - element.classList.add("fs-collapsible"); - - if (collapsed) { - element.classList.add("fs-collapsed"); - } - - if (element.classList.contains("fs-collapsed")) { - element.classList.toggle("fs-collapsible"); - } - - bind_to.addEventListener("click", _toggleCollapse(element, cb)); - - bind_to.id = "fs_collapsible_target_" + _collapsible_id; - - if (element !== bind_to) { - element.addEventListener("click", function (ev) { - var elem = ev.target.ownerDocument.getElementById(element.id); - var bto = ev.target.ownerDocument.getElementById(bind_to.id); - - if (elem.classList.contains("fs-collapsed")) { - bto.dispatchEvent(new UIEvent('click')); - bind_to.dispatchEvent(new UIEvent('click')); - } - - ev.stopPropagation(); - }); - } - - _collapsible_id += 1; -}; - -var _updateSlicesDialog = function () { - var slices_dialog_ul = document.createElement("ul"); - slices_dialog_ul.classList.add("fs-slices-list"); - var detached_window = WUI_Dialog.getDetachedDialog(_slices_dialog); - var slices_dialog_content = null; - var doc = null; - - if (detached_window) { - doc = detached_window.document; - } else { - doc = document; - } - - slices_dialog_content = doc.getElementById(_slices_dialog_id).getElementsByClassName('wui-dialog-content')[0]; - - slices_dialog_content.innerHTML = ""; - - if (!_play_position_markers.length) { - slices_dialog_ul.innerHTML = '
  • No instruments.
  • '; - } - - var i = 0; - for (i = 0; i < _play_position_markers.length; i += 1) { - var play_position_marker = _play_position_markers[i]; - - var slices_dialog_li = doc.createElement("li"); - - var li_content = [ - "CHN " + play_position_marker.output_channel + ""]; - - if (play_position_marker.mute) { - //li_content.push("MUTED"); - slices_dialog_li.style = "text-decoration: line-through"; - } - if (play_position_marker.audio_out) { - li_content.push("AUDIO OUT"); - } - if (play_position_marker.osc_out) { - li_content.push("OSC OUT"); - } - if (play_position_marker.midi_out.enabled) { - li_content.push("MIDI OUT"); - } - - slices_dialog_li.addEventListener("click", _openSliceSettingsDialogFn(play_position_marker)); - slices_dialog_li.addEventListener("contextmenu", _showSliceSettingsMenuFn(play_position_marker.element, _slices_dialog)); - - slices_dialog_li.innerHTML = play_position_marker.id + ": " + li_content.join(' - '); - - slices_dialog_ul.appendChild(slices_dialog_li); - } - - slices_dialog_content.appendChild(slices_dialog_ul); - - _slices_dialog_timeout = setTimeout(_updateSlicesDialog, 3000); -}; - -var _openedSlicesDialog = function () { - _updateSlicesDialog(); - - _slices_dialog_timeout = setTimeout(_updateSlicesDialog, 3000); -}; - -var _closedSlicesDialog = function () { - clearTimeout(_slices_dialog_timeout); -}; - -var _openSynthParameters = function () { - WUI_Dialog.open(_fas_synth_params_dialog); -}; - -var _onChangeEfxParameter = function (chn, efx, efxi, pid) { - return function (ev_value) { - var value, - elem = null, - detached_window = null; - - detached_window = WUI_Dialog.getDetachedDialog(_fas_dialog); - - if (detached_window) { - elem = detached_window.document.getElementById("fs_chn_" + chn + "_fx_" + efx + "_" + efxi); - } else { - elem = document.getElementById("fs_chn_" + chn + "_fx_" + efx + "_" + efxi); - } - - if (this) { - value = _efx[efx].params[pid].type[this.selectedIndex]; - } else { - value = ev_value; - } - - var slot = _parseInt10(elem.dataset.chn_fxid) / 3; - var fvalue = parseFloat(value); - - _chn_settings[chn].efx[_parseInt10(elem.dataset.chn_fxid) + 2][pid] = fvalue; - - _local_session_settings.chn_settings[chn] = _chn_settings[chn]; - _saveLocalSessionSettings(); - - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot, target: 2 + pid, value: fvalue }); - }; -}; - -var _createChnFxSettings = function (chn, ind, efxi, id) { - var dialog_id = null, - dialog_element = document.createElement("div"), - dialog_content = document.createElement("div"), - - slider_div = null, - - fieldset = null, - legend = null, - - param = null, - - label = null, - select = null, - option = null, - - selected_option = 0, - - fx = _efx[ind], - - i = 0, - j = 0; - - dialog_element.id = id + "_dialog"; - - WUI_Dialog.destroy(dialog_element.id); - - fieldset = document.createElement("fieldset"); - legend = document.createElement("legend"); - - fieldset.className = "fs-fieldset"; - legend.innerText = "Parameters"; - - for (i = 0; i < fx.params.length; i += 1) { - param = fx.params[i]; - - if (Array.isArray(param.type)) { - label = document.createElement("label"); - select = document.createElement("select"); - - for (j = 0; j < param.type.length; j += 1) { - option = document.createElement("option"); - option.innerHTML = param.type[j]; - - select.appendChild(option); - } - - label.classList.add("fs-input-label"); - label.style.width = "148px"; - label.innerHTML = param.name + ":  "; - label.htmlFor = id + "_" + i + "_param"; - - select.classList.add("fs-btn"); - select.style = "margin-top: 4px"; - select.dataset.chnId = chn; - select.dataset.efxId = ind; - select.id = label.htmlFor; - - selected_option = _chn_settings[chn].efx[efxi + 2][i]; - - if (selected_option) { - selected_option = _efx[ind].params[i].type.indexOf(selected_option); - - select.childNodes[selected_option].selected = true; - } else { - select.childNodes[_efx[ind].params[i].value].selected = true; - } - - select.addEventListener("change", _onChangeEfxParameter(chn, ind, efxi, i)); - fieldset.appendChild(label); - fieldset.appendChild(select); - - select.dispatchEvent(new UIEvent('change')); - } else if (param.type == 0) { - slider_div = document.createElement("div"); - slider_div.id = id + "_slider_" + i; - - WUI_RangeSlider.destroy(slider_div.id); - - var value = _chn_settings[chn].efx[efxi + 2][i]; - - WUI_RangeSlider.create(slider_div, { - width: 120, - height: 8, - - min: param.min, - max: param.max, - - bar: false, - - step: param.step, - scroll_step: param.step, - - default_value: param.value, - value: value !== undefined ? value : param.value, - - decimals: param.decimals, - - midi: true, - - title: param.name, - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeEfxParameter(chn, ind, efxi, i) - }); - - fieldset.appendChild(slider_div); - } - } - - fieldset.appendChild(legend); - - dialog_content.appendChild(fieldset); - - dialog_element.appendChild(dialog_content); - document.body.appendChild(dialog_element); - - dialog_id = WUI_Dialog.create(dialog_element.id, { - title: fx.name + " (" + chn + ":" + (efxi / 3) + ")", - - width: "auto", - height: "auto", - - min_width: 340, - min_height: 80, - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, -// detachable: true, - minimizable: true, - draggable: true, -/* - on_detach: function (new_window) { - - }, -*/ - }); -}; - -var _createSynthParametersContent = function () { - var dialog_div = document.getElementById(_fas_synth_params_dialog).lastElementChild, - - detached_window = WUI_Dialog.getDetachedDialog(_fas_synth_params_dialog), - - synth_type = 0, - chn_fieldset, - chn_legend, - - slice, - - chn_genv_type_label, - chn_genv_type_select, - chn_genv_option, - chn_genv_options = ["sine", "hann", "hamming", "tukey", "gaussian", "confined gaussian", "trapezoidal", "blackman", "blackman harris", "parzen", "nutall", "flattop", "kaiser"], - - chn_gden_input, - chn_gmin_size_input, - chn_gmax_size_input, - - gmin = 0.01, - gmax = 0.1, - gden = 0.00001, - - i = 0, j = 0; - - if (detached_window) { - dialog_div = detached_window.document.body; - } - - for (i = 0; i < _fas_content_list.length; i += 1) { - WUI_RangeSlider.destroy(_fas_content_list[i]); - } - - _fas_content_list = []; - - dialog_div.innerHTML = ""; - - for (j = 0; j < _play_position_markers.length; j += 1) { - //chn_settings = _chn_settings[j]; - slice = _play_position_markers[j]; - - synth_type = slice.instrument_type; -/* - synth_type = _chn_settings[j].osc[1]; -*/ - if (_synthesis_params[synth_type] <= 0) { - continue; - } - - chn_fieldset = document.createElement("fieldset"); - chn_legend = document.createElement("legend"); - - chn_fieldset.className = "fs-fieldset"; - - chn_legend.innerHTML = "Instr. " + (j + 1) + " / " + _synthesis_types[synth_type]; - - chn_fieldset.appendChild(chn_legend); - - // granular parameters - if (_synthesis_types[synth_type] === "Granular") { - chn_gmin_size_input = document.createElement("div"); - chn_gmin_size_input.id = "fs_chn_" + j + "_gmin"; - chn_gmax_size_input = document.createElement("div"); - chn_gmax_size_input.id = "fs_chn_" + j + "_gmax"; - chn_gden_input = document.createElement("div"); - chn_gden_input.id = "fs_chn_" + j + "_gden"; - - - chn_genv_type_label = document.createElement("label"); - chn_genv_type_select = document.createElement("select"); - - for (i = 0; i < chn_genv_options.length; i += 1) { - chn_genv_option = document.createElement("option"); - chn_genv_option.innerHTML = chn_genv_options[i]; - - chn_genv_type_select.appendChild(chn_genv_option); - } - - chn_genv_type_label.classList.add("fs-input-label"); - //chn_genv_type_label.style.display = "none"; - chn_genv_type_label.innerHTML = "Granular env:  "; - chn_genv_type_label.htmlFor = "fs_chn_" + j + "_genv_type_settings"; - - chn_genv_type_select.classList.add("fs-btn"); - chn_genv_type_select.style = "margin-top: 4px"; - //chn_genv_type_select.style.display = "none"; - chn_genv_type_select.dataset.chnId = j; - chn_genv_type_select.id = chn_genv_type_label.htmlFor; - - chn_genv_type_select.childNodes[slice.instrument_params.p0].selected = true; - - gmin = slice.instrument_params.p1; - gmax = slice.instrument_params.p2; - gden = slice.instrument_params.p3; - - chn_genv_type_select.addEventListener("change", function() { - var j = parseInt(this.dataset.chnId, 10), - value = parseInt(this.selectedIndex, 10); - - var slice = _play_position_markers[j]; - - slice.instrument_params.p0 = value; - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: j, target: 3, value: value }); - - _sendSliceUpdate(j, { instruments_settings : { p0: value } }); - }); - - chn_fieldset.appendChild(chn_genv_type_label); - chn_fieldset.appendChild(chn_genv_type_select); - chn_fieldset.appendChild(chn_gmin_size_input); - chn_fieldset.appendChild(chn_gmax_size_input); - chn_fieldset.appendChild(chn_gden_input); - - _fas_content_list.push(WUI_RangeSlider.create(chn_gmin_size_input, { - width: 120, - height: 8, - - min: 0.0, - max: 1.0, - - bar: false, - - step: 0.0000001, - scroll_step: 0.0001, - - default_value: gmin, - value: gmin, - - decimals: 7, - - midi: true, - - title: "Min. grain length", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 4) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_gmax_size_input, { - width: 120, - height: 8, - - min: 0.0, - max: 1.0, - - bar: false, - - step: 0.0000001, - scroll_step: 0.0001, - - default_value: gmax, - value: gmax, - - midi: true, - - decimals: 7, - - title: "Max. grain length", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 5) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_gden_input, { - width: 120, - height: 8, - - min: 0.0, - max: 1.0, - - bar: false, - - step: 0.0000001, - scroll_step: 0.0001, - - default_value: gden, - value: gden, - - midi: true, - - decimals: 7, - - title: "Spread", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 6) - })); - - chn_genv_type_select.dispatchEvent(new UIEvent('change')); - } else if (_synthesis_types[synth_type] === "Bandpass (M)") { - var chn_order_label = document.createElement("label"); - var chn_order_select = document.createElement("select"); - var chn_order_options = ["2", "4", "6", "8"]; - - for (i = 0; i < chn_order_options.length; i += 1) { - var chn_order_option = document.createElement("option"); - chn_order_option.innerHTML = chn_order_options[i]; - - chn_order_select.appendChild(chn_order_option); - } - - chn_order_label.classList.add("fs-input-label"); - - chn_order_label.innerHTML = "Filter order:  "; - chn_order_label.htmlFor = "fs_chn_" + j + "_bp_order_settings"; - - chn_order_select.classList.add("fs-btn"); - chn_order_select.style = "margin-top: 4px"; - - chn_order_select.dataset.chnId = j; - chn_order_select.id = chn_order_label.htmlFor; - - chn_order_select.childNodes[slice.instrument_params.p0].selected = true; - - chn_order_select.addEventListener("change", function() { - var j = parseInt(this.dataset.chnId, 10), - value = parseInt(this.selectedIndex, 10); - - var slice = _play_position_markers[j]; - - slice.instrument_params.p0 = value; - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: j, target: 3, value: value }); - - _sendSliceUpdate(j, { instruments_settings : { p0: value } }); - }); - - chn_fieldset.appendChild(chn_order_label); - chn_fieldset.appendChild(chn_order_select); - } else if (_synthesis_types[synth_type] === "Spectral") { - var chn_input = document.createElement("div"); - chn_input.id = "fs_chn_" + j + "_chn_input"; - var chn_mode = document.createElement("div"); - chn_mode.id = "fs_chn_" + j + "_chn_mode"; - var switch_mode = document.createElement("div"); - switch_mode.id = "fs_chn_" + j + "_switch_mode"; - - var chn_win_size_label = document.createElement("label"); - var chn_win_size_select = document.createElement("select"); - var chn_win_size_options = [32, 64, 128, 256, 512, 1024]; - - for (i = 0; i < chn_win_size_options.length; i += 1) { - var chn_win_size_option = document.createElement("option"); - chn_win_size_option.innerHTML = chn_win_size_options[i]; - - chn_win_size_select.appendChild(chn_win_size_option); - } - - chn_win_size_label.classList.add("fs-input-label"); - - chn_win_size_label.innerHTML = "Window size:  "; - chn_win_size_label.htmlFor = "fs_chn_" + j + "_win_size_settings"; - - chn_win_size_select.classList.add("fs-btn"); - chn_win_size_select.style = "margin-top: 4px"; - - chn_win_size_select.dataset.chnId = j; - chn_win_size_select.id = chn_win_size_label.htmlFor; - - chn_win_size_select.childNodes[chn_win_size_options.indexOf(slice.instrument_params.p1)].selected = true; - - var input = slice.instrument_params.p0; - var mode = slice.instrument_params.p2; - var switch_mode_value = slice.instrument_params.p3; - - chn_win_size_select.addEventListener("change", function() { - var j = parseInt(this.dataset.chnId, 10), - value = parseInt(this.selectedIndex, 10); - - var slice = _play_position_markers[j]; - - slice.instrument_params.p1 = chn_win_size_options[value]; - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: j, target: 4, value: chn_win_size_options[value] }); - - _sendSliceUpdate(j, { instruments_settings : { p1: chn_win_size_options[value] } }); - }); - - chn_fieldset.appendChild(chn_win_size_label); - chn_fieldset.appendChild(chn_win_size_select); - chn_fieldset.appendChild(chn_input); - chn_fieldset.appendChild(chn_mode); - chn_fieldset.appendChild(switch_mode); - - _fas_content_list.push(WUI_RangeSlider.create(chn_input, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: input, - value: input, - - decimals: 0, - - midi: true, - - title: "Source CHN / instrument", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 3) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_mode, { - width: 120, - height: 8, - - min: 0, - max: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: mode, - value: mode, - - midi: true, - - decimals: 0, - - title: "Mode (factor / direct)", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 5) - })); - - _fas_content_list.push(WUI_RangeSlider.create(switch_mode, { - width: 120, - height: 8, - - min: 0, - max: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: switch_mode_value, - value: switch_mode_value, - - midi: true, - - decimals: 0, - - title: "Source mode", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 6) - })); - - chn_win_size_select.dispatchEvent(new UIEvent('change')); - } else if (_synthesis_types[synth_type] === "PM/FM") { - var chn_wav1 = document.createElement("div"), - chn_wav2 = document.createElement("div"); - - chn_wav1.id = "fs_chn_" + j + "_chn_wav1"; - chn_wav2.id = "fs_chn_" + j + "_chn_wav2"; - - var wav1 = slice.instrument_params.p0, - wav2 = slice.instrument_params.p1; - - chn_fieldset.appendChild(chn_wav1); - chn_fieldset.appendChild(chn_wav2); - - _fas_content_list.push(WUI_RangeSlider.create(chn_wav1, { - width: 120, - height: 8, - - min: -1, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: wav1, - value: wav1, - - decimals: 0, - - midi: true, - - title: "Wavetable (carrier)", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 3) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_wav2, { - width: 120, - height: 8, - - min: -1, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: wav2, - value: wav2, - - decimals: 0, - - midi: true, - - title: "Wavetable (modulator)", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 4) - })); - } else if (_synthesis_types[synth_type] === "Modulation") { - var chn_mod = document.createElement("div"), - chn_mod2 = document.createElement("div"), - chn_mod3 = document.createElement("div"), - chn_mod4 = document.createElement("div"), - chn_mod5 = document.createElement("div"); - - chn_mod.id = "fs_chn_" + j + "_chn_mod"; - chn_mod2.id = "fs_chn_" + j + "_chn_mod2"; - chn_mod3.id = "fs_chn_" + j + "_chn_mod3"; - chn_mod4.id = "fs_chn_" + j + "_chn_mod4"; - chn_mod4.id = "fs_chn_" + j + "_chn_mod5"; - - var mode = slice.instrument_params.p0, - mode2 = slice.instrument_params.p1, - mode3 = slice.instrument_params.p2, - mode4 = slice.instrument_params.p3, - mode5 = slice.instrument_params.p4; - - chn_fieldset.appendChild(chn_mod); - chn_fieldset.appendChild(chn_mod2); - chn_fieldset.appendChild(chn_mod3); - chn_fieldset.appendChild(chn_mod4); - chn_fieldset.appendChild(chn_mod5); - - _fas_content_list.push(WUI_RangeSlider.create(chn_mod, { - width: 120, - height: 8, - - min: 0, - max: 2, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: mode, - value: mode, - - decimals: 0, - - midi: true, - - title: "Mode", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 3) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_mod2, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: mode2, - value: mode2, - - decimals: 0, - - midi: true, - - title: "Chn / Instrument", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 4) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_mod3, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: mode3, - value: mode3, - - decimals: 0, - - midi: true, - - title: "Slot / param", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 5) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_mod4, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: mode4, - value: mode4, - - decimals: 0, - - midi: true, - - title: "Target", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 6) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_mod5, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: mode5, - value: mode5, - - decimals: 0, - - midi: true, - - title: "Easing (interpolation)", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 7) - })); - } else if (_synthesis_types[synth_type] === "Faust") { - var chn_gen = document.createElement("div"), - chn_p0 = document.createElement("div"), - chn_p1 = document.createElement("div"), - chn_p2 = document.createElement("div"), - chn_p3 = document.createElement("div"); - chn_gen.id = "fs_chn_" + j + "_chn_gen"; - chn_p0.id = "fs_chn_" + j + "_chn_p0"; - chn_p1.id = "fs_chn_" + j + "_chn_p1"; - chn_p2.id = "fs_chn_" + j + "_chn_p2"; - chn_p3.id = "fs_chn_" + j + "_chn_p3"; - - var gen = slice.instrument_params.p0, - p0 = slice.instrument_params.p1, - p1 = slice.instrument_params.p2, - p2 = slice.instrument_params.p3, - p3 = slice.instrument_params.p4; - - chn_fieldset.appendChild(chn_gen); - chn_fieldset.appendChild(chn_p0); - chn_fieldset.appendChild(chn_p1); - chn_fieldset.appendChild(chn_p2); - chn_fieldset.appendChild(chn_p3); - - _fas_content_list.push(WUI_RangeSlider.create(chn_gen, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: gen, - value: gen, - - decimals: 0, - - midi: true, - - title: "Generator ID", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 3) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_p0, { - width: 120, - height: 8, - - bar: false, - - step: 0.000001, - scroll_step: 0.0001, - - default_value: p0, - value: p0, - - decimals: 6, - - midi: true, - - title: "p0", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 4) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_p1, { - width: 120, - height: 8, - - bar: false, - - step: 0.000001, - scroll_step: 0.0001, - - default_value: p1, - value: p1, - - decimals: 6, - - midi: true, - - title: "p1", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 5) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_p2, { - width: 120, - height: 8, - - bar: false, - - step: 0.000001, - scroll_step: 0.0001, - - default_value: p2, - value: p2, - - decimals: 6, - - midi: true, - - title: "p2", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 6) - })); - - _fas_content_list.push(WUI_RangeSlider.create(chn_p3, { - width: 120, - height: 8, - - bar: false, - - step: 0.000001, - scroll_step: 0.0001, - - default_value: p3, - value: p3, - - decimals: 6, - - midi: true, - - title: "p3", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 7) - })); - } else if (_synthesis_types[synth_type] === "Subtractive") { - var chn_filter_type_label, - chn_filter_type_select, - chn_filter_option, - chn_filters_option = ["Moog-ladder LPF", "Diode-ladder LPF", "Korg 35 LPF", "18db LPF"]; - - chn_filter_type_label = document.createElement("label"); - chn_filter_type_select = document.createElement("select"); - - for (i = 0; i < chn_filters_option.length; i += 1) { - chn_filter_option = document.createElement("option"); - chn_filter_option.innerHTML = chn_filters_option[i]; - - chn_filter_type_select.appendChild(chn_filter_option); - } - chn_filter_type_label.classList.add("fs-input-label"); - chn_filter_type_label.innerHTML = "Filter type:  "; - chn_filter_type_label.htmlFor = "fs_chn_" + j + "_filter_type_settings"; - - chn_filter_type_select.classList.add("fs-btn"); - chn_filter_type_select.style = "margin-top: 4px"; - chn_filter_type_select.dataset.chnId = j; - chn_filter_type_select.id = chn_filter_type_label.htmlFor; - - var selected_option = slice.instrument_params.p0; - chn_filter_type_select.childNodes[selected_option >= chn_filters_option.length ? 0 : selected_option].selected = true; - - chn_filter_type_select.addEventListener("change", function() { - var j = parseInt(this.dataset.chnId, 10), - value = parseInt(this.selectedIndex, 10); - - var slice = _play_position_markers[j]; - - slice.instrument_params.p0 = value; - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: j, target: 3, value: value }); - - _sendSliceUpdate(j, { instruments_settings : { p0: value } }); - }); - chn_fieldset.appendChild(chn_filter_type_label); - chn_fieldset.appendChild(chn_filter_type_select); - - chn_filter_type_select.dispatchEvent(new UIEvent('change')); - } else if (_synthesis_types[synth_type] === "Physical Model") { - var chn_model_type_label, - chn_model_type_select, - chn_model_option, - chn_models_option = ["Karplus-strong", "Water drop", "Metal bar"]; - - chn_model_type_label = document.createElement("label"); - chn_model_type_select = document.createElement("select"); - - for (i = 0; i < chn_models_option.length; i += 1) { - chn_model_option = document.createElement("option"); - chn_model_option.innerHTML = chn_models_option[i]; - - chn_model_type_select.appendChild(chn_model_option); - } - chn_model_type_label.classList.add("fs-input-label"); - chn_model_type_label.innerHTML = "Model:  "; - chn_model_type_label.htmlFor = "fs_chn_" + j + "_physical_model_type_settings"; - - chn_model_type_select.classList.add("fs-btn"); - chn_model_type_select.style = "margin-top: 4px"; - chn_model_type_select.dataset.chnId = j; - chn_model_type_select.id = chn_model_type_label.htmlFor; - - var selected_option = slice.instrument_params.p0; - chn_model_type_select.childNodes[selected_option >= chn_models_option.length ? 0 : selected_option].selected = true; - - chn_model_type_select.addEventListener("change", function() { - var j = parseInt(this.dataset.chnId, 10), - value = parseInt(this.selectedIndex, 10); - - var slice = _play_position_markers[j]; - - slice.instrument_params.p0 = value; - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: j, target: 3, value: value }); - - _sendSliceUpdate(j, { instruments_settings : { p0: value } }); - - }); - chn_fieldset.appendChild(chn_model_type_label); - chn_fieldset.appendChild(chn_model_type_select); - - chn_model_type_select.dispatchEvent(new UIEvent('change')); - - // droplet params - var drop_tubes = document.createElement("div"); - - drop_tubes.id = "fs_chn_" + j + "_drop_tubes"; - - var tubes = slice.instrument_params.p1; - - chn_fieldset.appendChild(drop_tubes); - - _fas_content_list.push(WUI_RangeSlider.create(drop_tubes, { - width: 120, - height: 8, - - min: 1, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: tubes, - value: tubes, - - decimals: 0, - - midi: true, - - title: "Droplet tubes", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 4) - })); - - var drop_deattack = document.createElement("div"); - - drop_deattack.id = "fs_chn_" + j + "_drop_deattack"; - - var deattack = slice.instrument_params.p2; - - chn_fieldset.appendChild(drop_deattack); - - _fas_content_list.push(WUI_RangeSlider.create(drop_deattack, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 0.0001, - scroll_step: 0.0001, - - default_value: deattack, - value: deattack, - - decimals: 4, - - midi: true, - - title: "Droplet deattack", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 5) - })); - - // bar params - var bar_bcl = document.createElement("div"); - - bar_bcl.id = "fs_chn_" + j + "_bar_bcl"; - - var bcl = slice.instrument_params.p1; - - chn_fieldset.appendChild(bar_bcl); - - _fas_content_list.push(WUI_RangeSlider.create(bar_bcl, { - width: 120, - height: 8, - - min: 1, - max: 3, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: bcl, - value: bcl, - - decimals: 0, - - midi: true, - - title: "Bar boundary left", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 4) - })); - - var bar_bcr = document.createElement("div"); - - bar_bcr.id = "fs_chn_" + j + "_bar_bcr"; - - var bcr = slice.instrument_params.p2; - - chn_fieldset.appendChild(bar_bcr); - - _fas_content_list.push(WUI_RangeSlider.create(bar_bcr, { - width: 120, - height: 8, - - min: 1, - max: 3, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: bcr, - value: bcr, - - decimals: 0, - - midi: true, - - title: "Bar boundary right", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 5) - })); - - var bar_vel = document.createElement("div"); - - bar_vel.id = "fs_chn_" + j + "_bar_vel"; - - var vel = slice.instrument_params.p3; - - chn_fieldset.appendChild(bar_vel); - - _fas_content_list.push(WUI_RangeSlider.create(bar_vel, { - width: 120, - height: 8, - - min: 0, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: vel, - value: vel, - - decimals: 0, - - midi: true, - - title: "Bar strike velocity", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 6) - })); - } else if (_synthesis_types[synth_type] === "Wavetable") { - var chn_wav1 = document.createElement("div"); - - chn_wav1.id = "fs_chn_" + j + "_chn_wav1"; - - var wav1 = slice.instrument_params.p0; - - chn_fieldset.appendChild(chn_wav1); - - _fas_content_list.push(WUI_RangeSlider.create(chn_wav1, { - width: 120, - height: 8, - - min: 0, - max: 1, - bar: false, - - step: 1, - scroll_step: 1, - - default_value: wav1, - value: wav1, - - decimals: 0, - - midi: true, - - title: "Note-on reset", - - title_min_width: 140, - value_min_width: 88, - - on_change: _onChangeChannelSettings(j, 3) - })); - } - - _applyCollapsible(chn_fieldset, chn_legend); - - dialog_div.appendChild(chn_fieldset); - } - - if (dialog_div.innerHTML.length <= 0) { - dialog_div.innerHTML = '
    No parameters.
    '; - } -}; - -var _chnFxMute = function (elem) { - var id = null, chn, efx, muted, slot; - - slot = Array.from(elem.parentElement.children).indexOf(elem); - - id = slot * 3; - chn = _parseInt10(elem.parentElement.dataset.chn); - efx = _chn_settings[chn].efx; - muted = efx[id + 1]; - - efx[id + 1] = muted ? 0 : 1; - - if (muted) { - elem.classList.remove("fs-fx-mute"); - } else { - elem.classList.add("fs-fx-mute"); - } - - // save settings - _local_session_settings.chn_settings[chn] = _chn_settings[chn]; - _saveLocalSessionSettings(); - - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot, target: 1, value: efx[id + 1] }); -}; - -var _onChnFxClick = function (ev) { - if (ev.button == 1) { - ev.preventDefault(); - - _unfocus(); - - _chnFxMute(ev.target); - } -}; - -var _onChnFxDblClick = function (ev) { - WUI_Dialog.open(ev.target.dataset.dialog_id); -}; - -var _onChnFxContextMenu = function (ev) { - var elem = ev.target, - mute_icon = elem.classList.contains("fx-fx-mute") ? "fs-unmute-icon" : "fs-mute-icon", - mute_tooltip = elem.classList.contains("fx-fx-mute") ? "Unbypass" : "Bypass"; - - ev.preventDefault(); - - WUI_CircularMenu.create({ - element: elem, - - angle: 90, - rx: 32, - ry: 32, - - item_width: 32, - item_height: 32, - - window: null - }, [{ - icon: "fs-cross-45-icon", tooltip: "Delete", on_click: function () { - var id = null, chn, efx, slot; - - var chn_nodes = Array.from(elem.parentElement.children); - - slot = chn_nodes.indexOf(elem); - - id = slot * 3; - - chn = _parseInt10(elem.parentElement.dataset.chn); - efx = _chn_settings[chn].efx; - - efx.splice(id, 3); - - var next_elem = elem.nextElementSibling; - - elem.parentElement.removeChild(elem); - - if (next_elem) { - // must update all fx after - chn_nodes = Array.from(next_elem.parentElement.children); - while (next_elem) { - var fxid = chn_nodes.indexOf(next_elem); - - next_elem.dataset.chn_fxid = fxid * 3; - - WUI_Dialog.setTitle(next_elem.dataset.dialog_id, _efx[efx[id]].name + " (" + chn + ":" + fxid + ")"); - - next_elem = next_elem.nextElementSibling; - } - } - - // save settings - _local_session_settings.chn_settings[chn] = _chn_settings[chn]; - _saveLocalSessionSettings(); - - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot, target: 0, value: -1 }); - - WUI_Dialog.destroy(elem.dataset.dialog_id); - }}, { - icon: mute_icon, tooltip: mute_tooltip, on_click: function () { - _chnFxMute(elem); - } - }]); - - return false; -}; - -var _dragChnFx = function (ev) { - ev.dataTransfer.setData("text", ev.target.id); - - ev.dataTransfer.dropEffect = "move"; -}; - -var _dragOverChnFx = function (ev) { - ev.preventDefault(); -}; - -var _dropChnFx = function (ev) { - ev.preventDefault(); - - var data = ev.dataTransfer.getData("text"), - detached_window = WUI_Dialog.getDetachedDialog(_fas_dialog), - src_node = detached_window ? detached_window.document.getElementById(data) : document.getElementById(data), - cpy_node = null, - - chn = null, - efx = null, - fxid = null, - - update = false, - - chn_content_node = ev.target; - - if (ev.target.classList.contains("fs-fx-chn-content")) { - cpy_node = src_node.cloneNode(true); - - chn = _parseInt10(chn_content_node.dataset.chn); - fxid = _parseInt10(cpy_node.dataset.fxid); - - cpy_node.innerText = ""; - cpy_node.style.width = "16px"; - cpy_node.style.border = "none"; - cpy_node.style.backgroundColor = _efx[fxid].color; - cpy_node.style.borderLeft = "none"; - - efx = _chn_settings[chn].efx; - - efx.push(fxid); // fx id - efx.push(0); // muted - efx.push([]); // params - - cpy_node.id = "fs_chn_" + chn + "_fx_" + fxid + "_" + (efx.length - 3); - cpy_node.dataset.dialog_id = cpy_node.id + "_dialog"; - cpy_node.dataset.chn_fxid = (efx.length - 3); - - cpy_node.addEventListener("dragstart", _dragChnFx) - ev.target.appendChild(cpy_node); - - cpy_node.addEventListener("auxclick", _onChnFxClick); - cpy_node.addEventListener("contextmenu", _onChnFxContextMenu); - - cpy_node.addEventListener("dblclick", _onChnFxDblClick); - _createChnFxSettings(chn, fxid, efx.length - 3, cpy_node.id); - - update = true; - } else { - if (ev.target.id !== src_node.id && ev.target.parentElement.classList.contains("fs-fx-chn-content")) { - var curr_style = ev.target.style.backgroundColor, - curr_title = ev.target.title, - curr_class = ev.target.className, - id = null, id2 = null; - - chn = _parseInt10(ev.target.parentElement.dataset.chn); - efx = _chn_settings[chn].efx; - - ev.target.title = src_node.title; - ev.target.className = src_node.className; - - fxid = _parseInt10(src_node.dataset.fxid); - - chn_content_node = ev.target.parentElement; - - id = Array.from(chn_content_node.children).indexOf(ev.target) * 3; - - if (src_node.parentElement.classList.contains("fs-fx-chn-content")) { - id2 = Array.from(chn_content_node.children).indexOf(src_node) * 3; - - ev.target.style.backgroundColor = src_node.style.backgroundColor; - - src_node.style.backgroundColor = curr_style; - src_node.title = curr_title; - src_node.className = curr_class; - - var src_chn_fx_id = src_node.dataset.chn_fxid; - src_node.dataset.chn_fxid = ev.target.dataset.chn_fxid; - ev.target.dataset.chn_fxid = src_chn_fx_id; - - var src_dialog_id = src_node.dataset.dialog_id; - src_node.dataset.dialog_id = ev.target.dataset.dialog_id; - ev.target.dataset.dialog_id = src_dialog_id; - - var pfxid = efx[id2]; - var pfxmu = efx[id2+1]; - var pfxpa = efx[id2+2]; - - efx[id2] = efx[id]; - efx[id2 + 1] = efx[id+1]; - efx[id2 + 2] = efx[id+2]; - efx[id] = pfxid; - efx[id + 1] = pfxmu; - efx[id + 2] = pfxpa; - - WUI_Dialog.setTitle(ev.target.dataset.dialog_id, _efx[efx[id]].name + " (" + chn + ":" + id / 3 + ")"); - WUI_Dialog.setTitle(src_node.dataset.dialog_id, _efx[efx[id2]].name + " (" + chn + ":" + id2 / 3 + ")"); - } else { - efx[id] = fxid; - efx[id + 1] = 0; - efx[id + 2] = []; - - ev.target.style.backgroundColor = _efx[fxid].color; - - ev.target.dataset.chn_fxid = id; - - WUI_Dialog.destroy(ev.target.dataset.dialog_id); - - ev.target.id = "fs_chn_" + chn + "_fx_" + fxid + "_" + id; - ev.target.dataset.dialog_id = ev.target.id + "_dialog"; - - _createChnFxSettings(chn, fxid, id, ev.target.id); - } - - update = true; - } - } - - if (update) { - // save settings - _local_session_settings.chn_settings[chn] = _chn_settings[chn]; - _saveLocalSessionSettings(); - - var j = 0, k = 0, slot_index = 0; - for (j = 0; j < _chn_settings[chn].efx.length; j += 3) { - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot_index, target: 0, value: _chn_settings[chn].efx[j] }); - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot_index, target: 1, value: _chn_settings[chn].efx[j + 1] }); - - var fx_settings = _chn_settings[chn].efx[j + 2]; - for (k = 0; k < fx_settings.length; k += 1) { - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot_index, target: 2 + k, value: fx_settings[k] }); - } - - slot_index += 1; - } - _fasNotify(_FAS_CHN_FX_INFOS, { chn: chn, slot: slot_index, target: 0, value: -1 }); - } -}; - -var _createFasFxCard = function (elem, fxid, muted, chn, index) { - var fx_card = document.createElement("div"); - - fx_card.classList.add("fs-fx-card"); - - fx_card.draggable = "true"; - - fx_card.dataset.fxid = fxid; - - fx_card.addEventListener("dragstart", _dragChnFx); - - if (muted) { - fx_card.classList.add("fs-fx-mute"); - } - - fx_card.id = "fs_chn_" + chn + "_fx_" + fxid; - if (index !== undefined) { - fx_card.id += "_" + index; - fx_card.dataset.dialog_id = fx_card.id + "_dialog"; - fx_card.dataset.chn_fxid = index; - fx_card.style.width = "16px"; - fx_card.style.border = "none"; - fx_card.style.backgroundColor = _efx[fxid].color; - } else { - fx_card.innerText = _efx[fxid].name; - //fx_card.style.borderTop = "solid 2px " + _efx[fxid].color; - fx_card.style.borderLeft = "solid 2px " + _efx[fxid].color; - } - - fx_card.title = _efx[fxid].name; - - elem.appendChild(fx_card); - - return fx_card; -}; - -var _createFasFxContent = function (div) { - var fx_fieldset = document.createElement("fieldset"), - fx_fieldset_legend = document.createElement("legend"), - - fx_card = null, - - i = 0, j = 0; - - fx_fieldset.className = "fs-fieldset"; - - fx_fieldset_legend.innerHTML = "Channels"; - - fx_fieldset.appendChild(fx_fieldset_legend); - - _applyCollapsible(fx_fieldset, fx_fieldset_legend, _fas_settings_collapses.channels, function (collapsed) { _fas_settings_collapses.channels = collapsed; }); - - // fx list - var fx_div = document.createElement("div"); - fx_div.classList.add("fs-fx-container"); - for (i = 0; i < _efx.length; i += 1) { - var fx_card = _createFasFxCard(fx_div, i); - } - - fx_fieldset.appendChild(fx_div); - - div.appendChild(fx_fieldset); - - // channels - for (i = 0; i < _chn_settings.length; i += 1) { - var fx_chn_div = document.createElement("div"), - fx_chn_legend = document.createElement("div"), - fx_chn_content = document.createElement("div"), - fx_chn_out_input = document.createElement("input"), - - chn_settings = _chn_settings[i], - chn_fx = chn_settings.efx; - - fx_chn_div.style.display = "flex"; - fx_chn_content.classList.add("fs-fx-chn-content"); - - fx_chn_content.addEventListener("dragover", _dragOverChnFx); - fx_chn_content.addEventListener("drop", _dropChnFx); - - fx_chn_content.dataset.chn = i; - - fx_chn_out_input.type = "number"; - fx_chn_out_input.min = -1; - fx_chn_out_input.step = 1; - fx_chn_out_input.value = chn_settings.chn_output; - fx_chn_out_input.classList.add("fs-fx-chn-out"); - - fx_chn_legend.title = "mute / unmute channel"; - fx_chn_legend.innerHTML = (i + 1) + " :"; - fx_chn_legend.style.userSelect = "none"; - fx_chn_legend.classList.add("fs-fas-chn-id"); - - if (chn_settings.muted) { - fx_chn_legend.style.textDecoration = "line-through"; - fx_chn_legend.style.color = "red"; - } - - // channel device output - fx_chn_out_input.addEventListener("change", function (e) { - var chn_index = parseInt(this.previousElementSibling.dataset.chn, 10); - - var output_chn = _parseInt10(e.target.value); - - _chn_settings[chn_index].chn_output = output_chn; - - // save settings - _local_session_settings.chn_settings[chn_index] = _chn_settings[chn_index]; - _saveLocalSessionSettings(); - - _fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn_index, value: output_chn }); - }); - - // mute channel - fx_chn_legend.addEventListener("click", function (e) { - e.preventDefault(); - - var chn_index = parseInt(this.nextElementSibling.dataset.chn, 10); - - var muted = _chn_settings[chn_index].muted; - if (muted) { - this.style.textDecoration = "none"; - this.style.color = "white"; - - _chn_settings[chn_index].muted = 0; - muted = 0; - } else { - this.style.textDecoration = "line-through"; - this.style.color = "red"; - - _chn_settings[chn_index].muted = 1; - muted = 1; - } - - // save settings - _local_session_settings.chn_settings[chn_index] = _chn_settings[chn_index]; - _saveLocalSessionSettings(); - - _fasNotify(_FAS_CHN_INFOS, { target: 0, chn: chn_index, value: muted }); - - //_sendSliceUpdate(instrument_index, { instruments_settings : { muted: slice.instrument_muted } }); - }); - - // channel action menu - fx_chn_legend.addEventListener("contextmenu", function (e) { - e.preventDefault(); - - var actions = []; - var deleteAction = { icon: "fs-cross-45-icon", tooltip: "Delete unused channels (start at the last used one)", on_click: function () { - // disable channels (probably help performances) - for (var j = _output_channels; j < _chn_settings.length; j += 1) { - _fasNotify(_FAS_CHN_INFOS, { target: 1, chn: j, value: -1 }); - } - - _chn_settings.splice(_output_channels); - - _createFasSettingsContent(); - _saveLocalSessionSettings(); - } }; - - actions.push(deleteAction); - - WUI_CircularMenu.create({ - element: e.target, - - angle: 90, - rx: 0, - ry: 0, - - item_width: 32, - item_height: 32, - - window: null - }, actions); - }); - - fx_chn_div.appendChild(fx_chn_legend); - fx_chn_div.appendChild(fx_chn_content); - fx_chn_div.appendChild(fx_chn_out_input); - - fx_fieldset.appendChild(fx_chn_div); - - if (chn_fx) { - for (j = 0; j < chn_fx.length; j += 3) { - fx_card = _createFasFxCard(fx_chn_content, chn_fx[j], chn_fx[j + 1], i, j); - fx_card.addEventListener("auxclick", _onChnFxClick); - fx_card.addEventListener("contextmenu", _onChnFxContextMenu); - fx_card.addEventListener("dblclick", _onChnFxDblClick); - - _createChnFxSettings(i, chn_fx[j], j, fx_card.id); - } - } - } -}; - -var _createFasSettingsButton = function (node, title, click_fn) { - var btn = document.createElement("button"); - - btn.innerHTML = title; - btn.className = "fs-btn fs-btn-default"; - - btn.style.width = "180px"; - btn.style.display = "block"; - btn.style.marginLeft = "auto"; - btn.style.marginRight = "auto"; - - btn.addEventListener("click", click_fn); - - node.appendChild(btn); -}; - -var _createFasSettingsContent = function () { - var dialog_div = document.getElementById(_fas_dialog).lastElementChild, - detached_window = WUI_Dialog.getDetachedDialog(_fas_dialog), - - load_samples_btn = document.createElement("button"), - load_faust_gens_btn = document.createElement("button"), - load_faust_effs_btn = document.createElement("button"), - load_wavs_btn = document.createElement("button"), - load_imps_btn = document.createElement("button"), - open_synth_params_btn = document.createElement("button"), - - synthesis_matrix_fieldset = document.createElement("fieldset"), - actions_fieldset = document.createElement("fieldset"), - files_fieldset = document.createElement("fieldset"), - - synthesis_matrix_table = document.createElement("table"), - - synthesis_matrix_fieldset_legend = document.createElement("legend"), - - actions_fieldset_legend = document.createElement("legend"), - - files_fieldset_legend = document.createElement("legend"), - - ck_tmp = [], - - chn_settings, - - row, - cell, - checkbox, - - triggered = true, - - i = 0, j = 0; - - if (detached_window) { - dialog_div = detached_window.document.body; - } - - // fieldset - synthesis_matrix_fieldset.className = "fs-fieldset"; - actions_fieldset.className = "fs-fieldset"; - files_fieldset.className = "fs-fieldset"; - - dialog_div.style = "overflow: auto"; - dialog_div.innerHTML = ""; - - synthesis_matrix_fieldset_legend.innerHTML = "Instruments"; - actions_fieldset_legend.innerHTML = "Actions"; - files_fieldset_legend.innerHTML = "File managers"; - - synthesis_matrix_fieldset.appendChild(synthesis_matrix_fieldset_legend); - actions_fieldset.appendChild(actions_fieldset_legend); - files_fieldset.appendChild(files_fieldset_legend); - - _applyCollapsible(synthesis_matrix_fieldset, synthesis_matrix_fieldset_legend, _fas_settings_collapses.instruments, function (collapsed) { _fas_settings_collapses.instruments = collapsed; }); - _applyCollapsible(actions_fieldset, actions_fieldset_legend, _fas_settings_collapses.actions, function (collapsed) { _fas_settings_collapses.actions = collapsed; }); - _applyCollapsible(files_fieldset, files_fieldset_legend, _fas_settings_collapses.file_managers, function (collapsed) { _fas_settings_collapses.file_managers = collapsed; }); - - // synthesis matrix - synthesis_matrix_table.className = "fs-matrix"; - synthesis_matrix_fieldset.appendChild(synthesis_matrix_table); - - row = document.createElement("tr"); - row.className = "fs-matrix-first-row"; - cell = document.createElement("th"); - row.appendChild(cell); - for (i = 0; i < _play_position_markers.length; i += 1) { -// chn_settings = _chn_settings[i]; - - cell = document.createElement("th"); - cell.innerHTML = i + 1; - - row.appendChild(cell); - } - - synthesis_matrix_table.appendChild(row); - - for (i = 0; i < _output_channels; i += 1) { - var chn_settings = _chn_settings[i]; - - if (!chn_settings) { - _chn_settings[i] = { - efx: [] - }; - } - } - - for (i = 0; i < _synthesis_types.length; i += 1) { - if (!_synthesis_enabled[i]) { - continue; - } - - row = document.createElement("tr"); - - cell = document.createElement("th"); - cell.className = "fs-matrix-first-cell"; - var label = document.createElement("label"); - label.htmlFor = "radio_instr_type" + i; - label.innerHTML = _synthesis_types[i]; - cell.appendChild(label); - row.appendChild(cell); - - for (j = 0; j < _play_position_markers.length; j += 1) { -// chn_settings = _chn_settings[j]; - - cell = document.createElement("th"); - cell.className = "fs-matrix-ck-cell"; - checkbox = document.createElement("input"); - checkbox.name = j; - checkbox.value = i; - checkbox.type = "radio"; - checkbox.id = "radio_instr_type" + i; - - // create channel settings if it does not exist -/* - if (!chn_settings) { - _chn_settings[j] = { - osc: [0, 0, 1, 0], - efx: [] - }; - chn_settings = _chn_settings[j]; - } - - // check synthesis type from saved settings - if (chn_settings.osc[1] === i) { - checkbox.checked = true; - } -*/ - if (_play_position_markers[j].instrument_type == i) { - checkbox.checked = true; - } - - checkbox.addEventListener("change", function () { - var instrument_index = parseInt(this.name, 10); - - var synth_type = parseInt(this.value, 10); - - //var osc_settings = _chn_settings[chn].osc; - //var synth_type = osc_settings[1]; - var slice = _play_position_markers[instrument_index]; - - // load default settings - if (!triggered) { - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 0, value: synth_type }); - - slice.instrument_type = synth_type; - - if (_synthesis_types[synth_type] === "Physical Model") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 0, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 4, value: 1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 5, value: 1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 6, value: 500 }); - - slice.instrument_params.p0 = 0; - slice.instrument_params.p1 = 1; - slice.instrument_params.p2 = 1; - slice.instrument_params.p3 = 500; - } else if (_synthesis_types[synth_type] === "Wavetable") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 0 }); - - slice.instrument_params.p0 = 0; - } else if (_synthesis_types[synth_type] === "Bandpass (M)") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 0 }); - - slice.instrument_params.p0 = 0; - } else if (_synthesis_types[synth_type] === "Subtractive") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 0 }); - - slice.instrument_params.p0 = 0; - } else if (_synthesis_types[synth_type] === "PM/FM") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, -1, 3, -1]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: -1 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 3, chn: chn, value: -1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: -1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 4, value: -1 }); - - slice.instrument_params.p0 = -1; - slice.instrument_params.p1 = -1; - } else if (_synthesis_types[synth_type] === "Modulation") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 3, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 4, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 5, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 6, chn: chn, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 4, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 5, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 6, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 7, value: 0 }); - - slice.instrument_params.p0 = 0; - slice.instrument_params.p1 = 0; - slice.instrument_params.p2 = 0; - slice.instrument_params.p3 = 0; - slice.instrument_params.p4 = 0; - } else if (_synthesis_types[synth_type] === "Granular") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 1, 3, 0.01, 4, 0.1, 5, 0.00001]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: 1 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 3, chn: chn, value: 0.01 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 4, chn: chn, value: 0.1 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 5, chn: chn, value: 0.00001 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 4, value: 0.01 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 5, value: 0.1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 6, value: 0.00001 }); - - slice.instrument_params.p0 = 1; - slice.instrument_params.p1 = 0.01; - slice.instrument_params.p2 = 0.1; - slice.instrument_params.p3 = 0.00001; - } else if (_synthesis_types[synth_type] === "Spectral") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0, 3, 1024, 4, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: 1 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 3, chn: chn, value: 1024 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 4, chn: chn, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 4, value: 1024 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 5, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 6, value: 0 }); - - slice.instrument_params.p0 = 1; - slice.instrument_params.p1 = 1024; - slice.instrument_params.p2 = 0; - slice.instrument_params.p3 = 0; - } else if (_synthesis_types[synth_type] === "Faust") { - //_chn_settings[chn].osc = [0, synth_type, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6, 0]; - //_fasNotify(_FAS_INSTRUMENT_INFOS, { target: 0, chn: chn, value: synth_type }); - //_fasNotify(_FAS_CHN_INFOS, { target: 1, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 2, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 3, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 4, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 5, chn: chn, value: 0 }); - //_fasNotify(_FAS_CHN_INFOS, { target: 6, chn: chn, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 3, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 4, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 5, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 6, value: 0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: instrument_index, target: 7, value: 0 }); - - slice.instrument_params.p0 = 0; - slice.instrument_params.p1 = 0; - slice.instrument_params.p2 = 0; - slice.instrument_params.p3 = 0; - slice.instrument_params.p4 = 0; - } else { - //_fasNotify(_FAS_CHN_INFOS, { target: 0, chn: chn, value: synth_type }); - } - - _submitSliceUpdate(5, instrument_index, { instruments_settings : { type: synth_type } }); - } - - // save settings - //_local_session_settings.chn_settings[chn] = _chn_settings[chn]; - //_saveLocalSessionSettings(); - - _createSynthParametersContent(); - }); - - ck_tmp.push(checkbox); - - cell.appendChild(checkbox); - row.appendChild(cell); - } - - // trigger change event on checked ones - for (j = 0; j < ck_tmp.length; j += 1) { - checkbox = ck_tmp[j]; - if (checkbox.checked) { - checkbox.dispatchEvent(new UIEvent('change')); - } - } - ck_tmp = []; - - synthesis_matrix_table.appendChild(row); - } - - // open parameters button - open_synth_params_btn.innerHTML = "Parameters"; - open_synth_params_btn.className = "fs-btn fs-btn-default"; - - open_synth_params_btn.style.width = "180px"; - open_synth_params_btn.style.display = "block"; - open_synth_params_btn.style.marginLeft = "auto"; - open_synth_params_btn.style.marginRight = "auto"; - open_synth_params_btn.style.marginTop = "12px"; - - open_synth_params_btn.addEventListener("click", _openSynthParameters); - - synthesis_matrix_fieldset.appendChild(open_synth_params_btn); - - // load sample action - load_samples_btn.innerHTML = "Reload samples / grains"; - load_samples_btn.className = "fs-btn fs-btn-default"; - - load_samples_btn.style.width = "180px"; - load_samples_btn.style.display = "block"; - load_samples_btn.style.marginLeft = "auto"; - load_samples_btn.style.marginRight = "auto"; - - load_samples_btn.addEventListener("click", function () { - _fasNotify(_FAS_ACTION, { type: 0 }); - }); - - // load Faust gens action - load_faust_gens_btn.innerHTML = "Reload Faust generators"; - load_faust_gens_btn.className = "fs-btn fs-btn-default"; - - load_faust_gens_btn.style.width = "180px"; - load_faust_gens_btn.style.display = "block"; - load_faust_gens_btn.style.marginLeft = "auto"; - load_faust_gens_btn.style.marginRight = "auto"; - - load_faust_gens_btn.addEventListener("click", function () { - _fasNotify(_FAS_ACTION, { type: 2 }); - }); - - // load Faust effs action - load_faust_effs_btn.innerHTML = "Reload Faust effects"; - load_faust_effs_btn.className = "fs-btn fs-btn-default"; - - load_faust_effs_btn.style.width = "180px"; - load_faust_effs_btn.style.display = "block"; - load_faust_effs_btn.style.marginLeft = "auto"; - load_faust_effs_btn.style.marginRight = "auto"; - - load_faust_effs_btn.addEventListener("click", function () { - _fasNotify(_FAS_ACTION, { type: 3 }); - }); - - // load wavs action - load_wavs_btn.innerHTML = "Reload waves (wavetable)"; - load_wavs_btn.className = "fs-btn fs-btn-default"; - - load_wavs_btn.style.width = "180px"; - load_wavs_btn.style.display = "block"; - load_wavs_btn.style.marginLeft = "auto"; - load_wavs_btn.style.marginRight = "auto"; - - load_wavs_btn.addEventListener("click", function () { - _fasNotify(_FAS_ACTION, { type: 6 }); - }); - - // load wavs action - load_imps_btn.innerHTML = "Reload impulses"; - load_imps_btn.className = "fs-btn fs-btn-default"; - - load_imps_btn.style.width = "180px"; - load_imps_btn.style.display = "block"; - load_imps_btn.style.marginLeft = "auto"; - load_imps_btn.style.marginRight = "auto"; - - load_imps_btn.addEventListener("click", function () { - _fasNotify(_FAS_ACTION, { type: 7 }); - }); - - actions_fieldset.appendChild(load_samples_btn); - actions_fieldset.appendChild(load_wavs_btn); - actions_fieldset.appendChild(load_imps_btn); - actions_fieldset.appendChild(load_faust_gens_btn); - actions_fieldset.appendChild(load_faust_effs_btn); - - _createFasSettingsButton(files_fieldset, "Grains / samples", function () { WUI_Dialog.open(_samples_dialog); }); - _createFasSettingsButton(files_fieldset, "Waves (wavetable)", function () { WUI_Dialog.open(_waves_dialog); }); - _createFasSettingsButton(files_fieldset, "Impulses", function () { WUI_Dialog.open(_impulses_dialog); }); - _createFasSettingsButton(files_fieldset, "Faust generators", function () { WUI_Dialog.open(_faust_gens_dialog); }); - _createFasSettingsButton(files_fieldset, "Faust effects", function () { WUI_Dialog.open(_faust_effs_dialog); }); - - dialog_div.appendChild(synthesis_matrix_fieldset); - _createFasFxContent(dialog_div); - dialog_div.appendChild(actions_fieldset); - dialog_div.appendChild(files_fieldset); - - _createSynthParametersContent(); - - triggered = false; -}; - -var _showFasDialog = function (toggle_ev) { - _createFasSettingsContent(); - WUI_Dialog.open(_fas_dialog); -}; - -var _toggleFas = function (toggle_ev) { - if (toggle_ev.state) { - document.getElementById("fs_fas_status").style = ""; - - _fasEnable(); - } else { - document.getElementById("fs_fas_status").style = "display: none"; - - _fasDisable(); - } -}; - -var _toggleGridInfos = function (toggle_ev) { - _xyf_grid = toggle_ev.state; -}; - -var _showSpectrumDialog = function () { - var analysis_dialog_content = document.getElementById(_analysis_dialog_id).childNodes[2]; - - _analysis_canvas = document.createElement("canvas"); - _analysis_canvas_ctx = _analysis_canvas.getContext('2d'); - - _analysis_canvas_tmp = document.createElement("canvas"); - _analysis_canvas_tmp_ctx = _analysis_canvas_tmp.getContext('2d'); - - _analysis_canvas.width = 380; - _analysis_canvas.height = 380; - - _analysis_canvas_tmp.width = _analysis_canvas.width; - _analysis_canvas_tmp.height = _analysis_canvas.height; - - analysis_dialog_content.innerHTML = ""; - analysis_dialog_content.appendChild(_analysis_canvas); - - _connectAnalyserNode(); - - WUI_Dialog.open(_analysis_dialog); -}; - -var _showRecordDialog = function () { - _record = true; - - //if (_record) { - // _record = false; - - // WUI_Dialog.close(_record_dialog); - //} else { - // _record = true; - - WUI_Dialog.open(_record_dialog); - //} -}; - -var _onImportDialogClose = function () { - WUI_ToolBar.toggle(_wui_main_toolbar, 13); - - WUI_Dialog.close(_import_dialog); - - _updateImportWidgets(); -}; - -var _onRecordDialogClose = function () { - //WUI_ToolBar.toggle(_wui_main_toolbar, 7); - - // reattach the correct canvas - var previous_canvas = _record_canvas; - - _record_canvas = _canvas.ownerDocument.getElementById("fs_record_canvas"); - _record_canvas_ctx = _record_canvas.getContext('2d'); - _record_canvas_ctx.drawImage(previous_canvas, 0, 0); - - _record = false; -}; - -var _showOutlineDialog = function () { - WUI_Dialog.open(_outline_dialog); -}; - -var _showImportDialog = function (toggle_ev) { - if (toggle_ev.state) { - WUI_Dialog.open(_import_dialog); - } else { - WUI_Dialog.close(_import_dialog); - } - - _updateImportWidgets(); -}; - -var _toggleMIDIRecord = function (toggle_ev) { - if (toggle_ev.state) { - _record_type = 3; - } else { - _record_type = 1; - } -}; - -var _toggleOSCRecord = function (toggle_ev) { - if (toggle_ev.state) { - _record_type = 2; - } else { - _record_type = 1; - } -}; - -var _toggleAUDIORecord = function (toggle_ev) { - _record_type = 1; -}; - -var _toggleALLRecord = function (toggle_ev) { - if (toggle_ev.state) { - _record_type = 0; - } else { - _record_type = 1; - } -}; - -var _toggleAdditiveRecord = function () { - if (_record_opts.f === _record_opts.additive) { - _record_opts.f = _record_opts.default; - } else { - _record_opts.f = _record_opts.additive; - } -}; - -var _toggleSubstractiveRecord = function () { - if (_record_opts.f === _record_opts.substractive) { - _record_opts.f = _record_opts.default; - } else { - _record_opts.f = _record_opts.substractive; - } -}; - -var _toggleMultiplyRecord = function () { - if (_record_opts.f === _record_opts.multiply) { - _record_opts.f = _record_opts.default; - } else { - _record_opts.f = _record_opts.multiply; - } -}; - -var _saveRecord = function () { - var data_url = _record_canvas.toDataURL('image/png'), - win; - - win = window.open(); - win.document.write(""); -}; - -var _rewindRecording = function () { - _record_position = 0; - - _record_canvas_ctx.clearRect(0, 0, _record_canvas.width, _record_canvas.height); -}; - -var _addRecordInput = function () { - var tmp_image_data; - - tmp_image_data = _record_canvas_ctx.getImageData(0, 0, _record_canvas.width, _record_canvas.height); - - _imageDataToInput(tmp_image_data); -}; - -var _drawBrushHelper = function () { - if (_paint_brush === null) { - return; - } - - var scale_x = _paint_scalex, - scale_y = _paint_scaley, - img = _paint_brush, - brush_width, - brush_height, - drawing_x, - drawing_y, - info_y = 0, - info_txt = "", - canvas_width_d2 = _c_helper.width / 2, - canvas_height_d2 = _c_helper.height / 2; - - brush_width = img.naturalWidth * scale_x; - brush_height = img.naturalHeight * scale_y; - - // clear - _c_helper.width = _c_helper.width; - - drawing_x = canvas_width_d2 - brush_width / 2; - drawing_y = canvas_height_d2 - brush_height / 2; - - _c_helper_ctx.save(); - _c_helper_ctx.translate(canvas_width_d2, canvas_height_d2); - _c_helper_ctx.rotate(_paint_angle); - _c_helper_ctx.translate(drawing_x - canvas_width_d2, drawing_y - canvas_height_d2); - _c_helper_ctx.scale(scale_x, scale_y); - _c_helper_ctx.globalAlpha = _paint_opacity; - _c_helper_ctx.drawImage(img, 0, 0); - _c_helper_ctx.restore(); - - brush_width = parseInt(brush_width, 10); - brush_height = parseInt(brush_height, 10); - - if (brush_height > (window.innerHeight - 224)) { - info_y = canvas_height_d2; - } else { - info_y = drawing_y + brush_height + 24; - } - - if (img.naturalWidth === brush_width && img.naturalHeight === brush_height) { - info_txt = parseInt(brush_width, 10) + "x" + parseInt(brush_height, 10); - } else { - info_txt = img.naturalWidth + "x" + img.naturalHeight + " - " + parseInt(brush_width, 10) + "x" + parseInt(brush_height, 10); - } - - _c_helper_ctx.font = "14px Arial"; - _c_helper_ctx.textAlign = "center"; - _c_helper_ctx.fillStyle = "white"; - _c_helper_ctx.fillText(info_txt, canvas_width_d2, info_y); - - WUI.fadeIn(_c_helper); - - clearTimeout(_brush_helper_timeout); - _brush_helper_timeout = setTimeout(function () { - WUI.fadeOut(_c_helper); - }, 2000); -}; - -/*********************************************************** - Init. -************************************************************/ - -var _uiInit = function () { - _xhrContent("data/md/quickstart.md", function (md_content) { - document.getElementById("fs_quickstart_content").innerHTML = _showdown_converter.makeHtml(md_content); - }); - - _xhrContent("data/md/uniforms.md", function (md_content) { - var md_fieldset = document.createElement("fieldset"), - md_fieldset_legend = document.createElement("legend"), - md_content_div = document.createElement("div"), - doc_uniforms = document.getElementById("fs_documentation_uniforms"); - - md_fieldset.className = "fs-fieldset"; - md_content_div.className = "fs-md-uniforms"; - - md_fieldset_legend.innerHTML = "Pre-defined uniforms"; - - md_fieldset.appendChild(md_fieldset_legend); - md_fieldset.appendChild(md_content_div); - doc_uniforms.appendChild(md_fieldset); - - _applyCollapsible(md_fieldset, md_fieldset_legend); - - md_content_div.innerHTML = _showdown_converter.makeHtml(md_content); - }); - - _xhrContent("data/md/pjs.md", function (md_content) { - var md_fieldset = document.createElement("fieldset"), - md_fieldset_legend = document.createElement("legend"), - md_content_div = document.createElement("div"), - doc_uniforms = document.getElementById("fs_documentation_pjs"); - - md_fieldset.className = "fs-fieldset"; - md_content_div.className = "fs-md-uniforms"; - - md_fieldset_legend.innerHTML = "Pre-defined variables"; - - md_fieldset.appendChild(md_fieldset_legend); - md_fieldset.appendChild(md_content_div); - doc_uniforms.appendChild(md_fieldset); - - _applyCollapsible(md_fieldset, md_fieldset_legend); - - md_content_div.innerHTML = _showdown_converter.makeHtml(md_content); - - md_content_div.innerHTML += '

    Processing.js reference'; - }); - - // may don't scale at all in the future! - var settings_ck_globaltime_elem = document.getElementById("fs_settings_ck_globaltime"), - settings_ck_polyinfos_elem = document.getElementById("fs_settings_ck_polyinfos"), - settings_ck_oscinfos_elem = document.getElementById("fs_settings_ck_oscinfos"), - settings_ck_hlmatches_elem = document.getElementById("fs_settings_ck_hlmatches"), - settings_ck_lnumbers_elem = document.getElementById("fs_settings_ck_lnumbers"), - settings_ck_inerrors_elem = document.getElementById("fs_settings_ck_inerrors"), - settings_ck_osderrors_elem = document.getElementById("fs_settings_ck_osderrors"), - settings_ck_xscrollbar_elem = document.getElementById("fs_settings_ck_xscrollbar"), - settings_ck_feedback_elem = document.getElementById("fs_settings_ck_feedback"), - settings_ck_osc_out_elem = document.getElementById("fs_settings_ck_oscout"), - settings_ck_osc_in_elem = document.getElementById("fs_settings_ck_oscin"), - settings_ck_slices_elem = document.getElementById("fs_settings_ck_slices"), - settings_ck_quickstart_elem = document.getElementById("fs_settings_ck_quickstart"), - settings_ck_audio_elem = document.getElementById("fs_settings_ck_audio"), - settings_ck_show_slice_chn_elem = document.getElementById("fs_settings_ck_show_slice_chn"), - settings_ck_show_toolbar_title = document.getElementById("fs_settings_ck_show_toolbar_title"), - - fs_settings_show_toolbar_title = localStorage.getItem('fs-show-toolbar-title'), - fs_settings_fps = localStorage.getItem('fs-fps'), - fs_settings_compile_delay = localStorage.getItem("fs-compile-delay"), - fs_settings_note_lifetime = localStorage.getItem('fs-note-lifetime'), - fs_settings_max_polyphony = localStorage.getItem('fs-max-polyphony'), - fs_settings_show_globaltime = localStorage.getItem('fs-show-globaltime'), - fs_settings_show_polyinfos = localStorage.getItem('fs-show-polyinfos'), - fs_settings_show_oscinfos = localStorage.getItem('fs-show-oscinfos'), - fs_settings_hlmatches = localStorage.getItem('fs-editor-hl-matches'), - fs_settings_lnumbers = localStorage.getItem('fs-editor-show-linenumbers'), - fs_settings_xscrollbar = localStorage.getItem('fs-editor-advanced-scrollbar'), - fs_settings_feedback = localStorage.getItem('fs-feedback'), - fs_settings_osc_in = localStorage.getItem('fs-osc-in'), - fs_settings_osc_out = localStorage.getItem('fs-osc-out'), - fs_settings_quickstart = localStorage.getItem('fs-quickstart'), - fs_settings_audio = localStorage.getItem('fs-audio'), - fs_settings_show_slice_chn = localStorage.getItem('fs-show-slice-chn'), - fs_settings_inerrors = localStorage.getItem('fs-editor-show-inerrors'), - fs_settings_osderrors = localStorage.getItem('fs-editor-show-osderrors'); - - _settings_dialog = WUI_Dialog.create(_settings_dialog_id, { - title: "Session & global settings", - - width: "320px", - height: "auto", - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: false, - minimizable: true, - draggable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "settings/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - if (fs_settings_osc_in === "true") { - settings_ck_osc_in_elem.checked = true; - } else { - settings_ck_osc_in_elem.checked = false; - } - - if (fs_settings_osc_out === "true") { - settings_ck_osc_out_elem.checked = true; - } else { - settings_ck_osc_out_elem.checked = false; - } - - if (fs_settings_feedback === "true") { - _feedback.enabled = true; - settings_ck_feedback_elem.checked = true; - } else if (fs_settings_feedback === null) { - if (_feedback.enabled) { - settings_ck_feedback_elem.checked = true; - } else { - settings_ck_feedback_elem.checked = false; - } - } else { - _feedback.enabled = false; - settings_ck_feedback_elem.checked = false; - } - - if (fs_settings_max_polyphony) { - _keyboard.polyphony_max = _parseInt10(fs_settings_max_polyphony); - } - - if (fs_settings_note_lifetime) { - _keyboard.note_lifetime = _parseInt10(fs_settings_note_lifetime); - } - - if (fs_settings_fps) { - _fas.fps = _parseInt10(fs_settings_fps); - } - - if (fs_settings_compile_delay) { - _compile_delay_ms = _parseInt10(fs_settings_compile_delay); - } - - if (fs_settings_show_globaltime !== null) { - _show_globaltime = (fs_settings_show_globaltime === "true"); - } - - if (fs_settings_show_oscinfos !== null) { - _show_oscinfos = (fs_settings_show_oscinfos === "true"); - } - - if (fs_settings_show_polyinfos !== null) { - _show_polyinfos = (fs_settings_show_polyinfos === "true"); - } - - if (fs_settings_hlmatches !== null) { - _cm_highlight_matches = (fs_settings_hlmatches === "true"); - } - - if (fs_settings_lnumbers !== null) { - _cm_show_linenumbers = (fs_settings_lnumbers === "true"); - } - - if (fs_settings_inerrors !== null) { - _cm_show_inerrors = (fs_settings_inerrors === "true"); - } - - if (fs_settings_osderrors !== null) { - _cm_show_osderrors = (fs_settings_osderrors === "true"); - } - - if (fs_settings_xscrollbar !== null) { - _cm_advanced_scrollbar = (fs_settings_xscrollbar === "true"); - } -/* - if (fs_settings_quickstart === "true") { - settings_ck_quickstart_elem.checked = true; - } else { - settings_ck_quickstart_elem.checked = false; - } -*/ - _quickstart_on_startup = fs_settings_quickstart; - - if (_cm_advanced_scrollbar) { - settings_ck_xscrollbar_elem.checked = true; - } else { - settings_ck_xscrollbar_elem.checked = false; - } - - if (_show_oscinfos) { - settings_ck_oscinfos_elem.checked = true; - } else { - settings_ck_oscinfos_elem.checked = false; - } - - if (_show_polyinfos) { - settings_ck_polyinfos_elem.checked = true; - } else { - settings_ck_polyinfos_elem.checked = false; - } - - if (_show_globaltime) { - settings_ck_globaltime_elem.checked = true; - } else { - settings_ck_globaltime_elem.checked = false; - } - - if (_cm_highlight_matches) { - settings_ck_hlmatches_elem.checked = true; - } else { - settings_ck_hlmatches_elem.checked = false; - } - - if (_cm_show_linenumbers) { - settings_ck_lnumbers_elem.checked = true; - } else { - settings_ck_lnumbers_elem.checked = false; - } - - if (_cm_show_inerrors) { - settings_ck_inerrors_elem.checked = true; - } else { - settings_ck_inerrors_elem.checked = false; - } - - if (_cm_show_osderrors) { - settings_ck_osderrors_elem.checked = true; - } else { - settings_ck_osderrors_elem.checked = false; - } - - if (fs_settings_audio !== null) { - _audio_off = !(fs_settings_audio === "true"); - } - - if (_audio_off) { - settings_ck_audio_elem.checked = true; - } else { - settings_ck_audio_elem.checked = false; - } - - if (fs_settings_show_slice_chn === "true") { - settings_ck_show_slice_chn_elem.checked = true; - } else { - settings_ck_show_slice_chn_elem.checked = false; - } - - if (fs_settings_show_toolbar_title === "true") { - settings_ck_show_toolbar_title.checked = true; - } else { - settings_ck_show_toolbar_title.checked = false; - } - - settings_ck_osc_in_elem.addEventListener("change", function () { - if (this.checked) { - _osc.in = true; - - _oscEnable(); - } else { - _osc.in = false; - - _oscDisable(); - } - - localStorage.setItem('fs-osc-in', this.checked); - }); - - settings_ck_osc_out_elem.addEventListener("change", function () { - if (this.checked) { - _osc.out = true; - - _oscEnable(); - } else { - _osc.out = false; - - _oscDisable(); - } - - localStorage.setItem('fs-osc-out', this.checked); - }); - - settings_ck_feedback_elem.addEventListener("change", function () { - //var buffer_target_element = document.getElementById("fs_buffer_target"); - - if (this.checked) { - _feedback.enabled = true; - - // buffer_target_element.style.display = ""; - } else { - _feedback.enabled = false; -/* - buffer_target_element.style.display = "none"; - - if (_isWorkspaceActive("fs_buffer_target")) { - _showWorkspace(0)(); - } -*/ - } - - localStorage.setItem('fs-feedback', this.checked); - - _buildFeedback(); - }); - - settings_ck_oscinfos_elem.addEventListener("change", function () { - _show_oscinfos = this.checked; - - if (!_show_oscinfos) { - _osc_infos.innerHTML = ""; - } - - localStorage.setItem('fs-show-oscinfos', _show_oscinfos); - }); - - settings_ck_polyinfos_elem.addEventListener("change", function () { - _show_polyinfos = this.checked; - - if (!_show_polyinfos) { - _poly_infos_element.innerHTML = ""; - } - - localStorage.setItem('fs-show-polyinfos', _show_polyinfos); - }); - - settings_ck_slices_elem.addEventListener("change", function () { - var elements = document.getElementsByClassName("play-position-marker"), - i = 0; - - if (!this.checked) { - for(i = elements.length - 1; i >= 0; --i) { - elements[i].classList.add("fs-hide"); - } - } else { - for(i = elements.length - 1; i >= 0; --i) { - elements[i].classList.remove("fs-hide"); - } - } - }); - - settings_ck_globaltime_elem.addEventListener("change", function () { - _show_globaltime = this.checked; - - if (!_show_globaltime) { - _time_infos.innerHTML = ""; - } - - localStorage.setItem('fs-show-globaltime', _show_globaltime); - }); - - settings_ck_hlmatches_elem.addEventListener("change", function () { - _cm_highlight_matches = this.checked; - - if (_cm_highlight_matches) { - _code_editor_settings.highlightSelectionMatches = _code_editor_highlight; - - _applyEditorsOption("highlightSelectionMatches", _code_editor_highlight); - } else { - delete _code_editor_settings.highlightSelectionMatches; - - _applyEditorsOption("highlightSelectionMatches", null); - } - - localStorage.setItem('fs-editor-hl-matches', _cm_highlight_matches); - }); - - settings_ck_lnumbers_elem.addEventListener("change", function () { - _cm_show_linenumbers = this.checked; - - _code_editor_settings.lineNumbers = _cm_show_linenumbers; - - _applyEditorsOption("lineNumbers", _cm_show_linenumbers); - - localStorage.setItem('fs-editor-show-linenumbers', _cm_show_linenumbers); - }); - - settings_ck_inerrors_elem.addEventListener("change", function () { - _cm_show_inerrors = this.checked; - - localStorage.setItem('fs-editor-show-inerrors', _cm_show_inerrors); - - _glsl_compilation(); - }); - - settings_ck_osderrors_elem.addEventListener("change", function () { - _cm_show_osderrors = this.checked; - - localStorage.setItem('fs-editor-show-osderrors', _cm_show_osderrors); - - _fail(""); - - _glsl_compilation(); - }); - - settings_ck_xscrollbar_elem.addEventListener("change", function () { - _cm_advanced_scrollbar = this.checked; - - if (_cm_advanced_scrollbar) { - _code_editor_settings.scrollbarStyle = "overlay"; - - _applyEditorsOption("scrollbarStyle", "overlay"); - } else { - _code_editor_settings.scrollbarStyle = "native"; - - _applyEditorsOption("scrollbarStyle", "native"); - } - - localStorage.setItem('fs-editor-advanced-scrollbar', _cm_advanced_scrollbar); - }); -/* - settings_ck_quickstart_elem.addEventListener("change", function () { - _quickstart_on_startup = this.checked; - - localStorage.setItem('fs-quickstart', _quickstart_on_startup); - - if (!_quickstart_on_startup) { - WUI_Dialog.close(_quickstart_dialog); - } - }); -*/ - - settings_ck_audio_elem.addEventListener("change", function () { - if (this.checked) { - _audio_off = true; - _fasDisable(); - } else { - _audio_off = false; - _fasEnable(); - } - - localStorage.setItem('fs-audio', !this.checked); - }); - - settings_ck_show_slice_chn_elem.addEventListener("change", function () { - if (this.checked) { - _show_output_channels = true; - } else { - _show_output_channels = false; - } - - _updateSliceChnVisibility(); - - localStorage.setItem('fs-show-slice-chn', this.checked); - }); - - settings_ck_show_toolbar_title.addEventListener("change", function () { - localStorage.setItem('fs-show-toolbar-title', this.checked); - }); - - settings_ck_oscinfos_elem.dispatchEvent(new UIEvent('change')); - settings_ck_polyinfos_elem.dispatchEvent(new UIEvent('change')); - settings_ck_globaltime_elem.dispatchEvent(new UIEvent('change')); - settings_ck_hlmatches_elem.dispatchEvent(new UIEvent('change')); - settings_ck_lnumbers_elem.dispatchEvent(new UIEvent('change')); - settings_ck_inerrors_elem.dispatchEvent(new UIEvent('change')); - settings_ck_osderrors_elem.dispatchEvent(new UIEvent('change')); - settings_ck_xscrollbar_elem.dispatchEvent(new UIEvent('change')); - settings_ck_feedback_elem.dispatchEvent(new UIEvent('change')); - settings_ck_osc_in_elem.dispatchEvent(new UIEvent('change')); - settings_ck_osc_out_elem.dispatchEvent(new UIEvent('change')); - settings_ck_slices_elem.dispatchEvent(new UIEvent('change')); -// settings_ck_quickstart_elem.dispatchEvent(new UIEvent('change')); - settings_ck_audio_elem.dispatchEvent(new UIEvent('change')); - settings_ck_show_slice_chn_elem.dispatchEvent(new UIEvent('change')); - settings_ck_show_toolbar_title.dispatchEvent(new UIEvent('change')); - - _midi_settings_dialog = WUI_Dialog.create(_midi_settings_dialog_id, { - title: "MIDI I/O", - - width: "320px", - height: "480px", - - min_height: 120, - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - minimizable: true, - draggable: true, - - on_detach: function (new_window) { - new_window.document.body.style.overflow = "hidden"; - }, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "midi/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _record_dialog = WUI_Dialog.create(_record_dialog_id, { - title: "Recording...", - - width: "auto", - height: "auto", - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - minimizable: false, - draggable: true, - - on_close: _onRecordDialogClose, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "record_dialog/"); - }, - class_name: "fs-help-icon" - } - ], - - on_detach: function (new_window) { - var previous_canvas = _record_canvas; - - _record_canvas = new_window.document.getElementById("fs_record_canvas"); - _record_canvas_ctx = _record_canvas.getContext('2d'); - - _record_canvas_ctx.drawImage(previous_canvas, 0, 0); - } - }); - - - _fas_dialog = WUI_Dialog.create(_fas_dialog_id, { - title: "Audio Server", - - width: "auto", - height: "auto", - - min_width: 340, - min_height: 80, - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - minimizable: true, - draggable: true, - - on_detach: function (new_window) { - _createFasSettingsContent(); - }, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "audio_server/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _fas_synth_params_dialog = WUI_Dialog.create(_fas_synth_params_dialog_id, { - title: "Instruments parameters", - - width: "auto", - height: "auto", - - min_width: 340, - min_height: 80, - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - minimizable: true, - draggable: true, - - on_detach: function (new_window) { - _createSynthParametersContent(); - }, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "audio_server/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _import_dialog = WUI_Dialog.create(_import_dialog_id, { - title: "Import dialog (images etc.)", - - width: "620px", - height: "auto", - min_height: "80px", - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - minimizable: true, - draggable: true, - - on_detach: function (new_window) { - var detached_dropzone = new_window.document.getElementById("fs_import_dropzone"); - _createImportDropzone(detached_dropzone); - - _createImportListeners(new_window.document); - - _updateImportWidgets(new_window.document); - }, - - on_close: _onImportDialogClose, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "import/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - WUI_ToolBar.create("fs_import_toolbar", { - allow_groups_minimize: false - }, - { - acts: [ - { - icon: "fs-image-file-icon", - on_click: (function () { _loadFile("image")(); }), - tooltip: "Image", - text: "Img" - }, - { - icon: "fs-audio-file-icon", - on_click: (function () { _loadFile("audio")(); }), - tooltip: "Audio", - text: "Snd" - }, - { - icon: "fs-video-icon", - on_click: (function () { _loadFile("video")(); }), - tooltip: "Video", - text: "Vid" - }, - { - icon: "fs-camera-icon", - on_click: (function () { _addFragmentInput("camera"); }), - tooltip: "Webcam", - text: "Cam" - }, - { - icon: "fs-mic-icon", - on_click: (function () { _addFragmentInput("mic"); }), - tooltip: "Microphone", - text: "Mic" - }, - { - icon: "fs-dsk-icon", - on_click: (function () { _addFragmentInput("desktop"); }), - tooltip: "Desktop", - text: "Dsk" - }, - { - icon: "fs-canvas-icon", - on_click: (function () { _addFragmentInput("canvas"); }), - tooltip: "Cvs", - text: "Cvs" - }, - { - icon: "fs-pjs-icon", - on_click: (function () { _addFragmentInput("processing.js"); }), - tooltip: "Pjs", - text: "Pjs" - } - ] - }); - - _outline_dialog = WUI_Dialog.create(_outline_dialog_id, { - title: "GLSL Outline", - - width: "380px", - height: "auto", - - min_height: 32, - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - minimizable: true, - draggable: true, - - on_detach: function (new_window) { - new_window.document.body.style.overflow = "hidden"; - }, - - on_open: function () { - _updateOutline(0); - _updateOutline(1); - } - }); - - WUI_Dialog.create("fs_username_dialog", { - title: "Global Username", - - width: "280px", - height: "auto", - - min_height: 32, - - halign: "center", - valign: "center", - - open: false, - modal: true, - - status_bar: false, - detachable: false, - draggable: true, - - on_open: function () { - var input = document.getElementById("fs_username_input"); - - input.focus(); - input.select(); - } - }); - - _slices_dialog = WUI_Dialog.create(_slices_dialog_id, { - title: "Instruments", - - width: "280px", - height: "auto", - - min_height: 16, - - halign: "center", - valign: "center", - - on_open: _openedSlicesDialog, - on_close: _closedSlicesDialog, - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "instruments/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _samples_dialog = WUI_Dialog.create(_samples_dialog_id, { - title: "File Manager - Grains / samples", - - width: "480px", - height: "540px", - - min_height: 16, - - halign: "center", - valign: "center", - - on_open: _refreshFileManager(_samples_dialog_id, "grains"), - on_close: _closeFileManager(_samples_dialog_id), - on_detach: _refreshFileManager(_samples_dialog_id, "grains"), - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - resizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "tools/#ffs-audio-server-files-manager"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _waves_dialog = WUI_Dialog.create(_waves_dialog_id, { - title: "File Manager - Waves (wavetable)", - - width: "480px", - height: "540px", - - min_height: 16, - - halign: "center", - valign: "center", - - on_open: _refreshFileManager(_waves_dialog_id, "waves"), - on_close: _closeFileManager(_waves_dialog_id), - on_detach: _refreshFileManager(_waves_dialog_id, "waves"), - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - resizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "tools/#ffs-audio-server-files-manager"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _impulses_dialog = WUI_Dialog.create(_impulses_dialog_id, { - title: "File Manager - Impulses", - - width: "480px", - height: "540px", - - min_height: 16, - - halign: "center", - valign: "center", - - on_open: _refreshFileManager(_impulses_dialog_id, "impulses"), - on_close: _closeFileManager(_impulses_dialog_id), - on_detach: _refreshFileManager(_impulses_dialog_id, "impulses"), - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - resizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "tools/#ffs-audio-server-files-manager"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _faust_gens_dialog = WUI_Dialog.create(_faust_gens_dialog_id, { - title: "File Manager - Faust generators", - - width: "480px", - height: "540px", - - min_height: 16, - - halign: "center", - valign: "center", - - on_open: _refreshFileManager(_faust_gens_dialog_id, "generators"), - on_close: _closeFileManager(_faust_gens_dialog_id), - on_detach: _refreshFileManager(_faust_gens_dialog_id, "generators"), - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - resizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "tools/#ffs-audio-server-files-manager"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _faust_effs_dialog = WUI_Dialog.create(_faust_effs_dialog_id, { - title: "File Manager - Faust effects", - - width: "480px", - height: "540px", - - min_height: 16, - - halign: "center", - valign: "center", - - on_open: _refreshFileManager(_faust_effs_dialog_id, "effects"), - on_close: _closeFileManager(_faust_effs_dialog_id), - on_detach: _refreshFileManager(_faust_effs_dialog_id, "effects"), - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - resizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "tools/#ffs-audio-server-files-manager"); - }, - class_name: "fs-help-icon" - } - ] - }); -/* - _analysis_dialog = WUI_Dialog.create(_analysis_dialog_id, { - title: "Audio analysis", - - width: "380px", - height: "380px", - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: false, - draggable: true, - - on_close: _disconnectAnalyserNode - }); -*/ - - _help_dialog = WUI_Dialog.create(_help_dialog_id, { - title: "Fragment - Help", - - width: "440px", - height: "auto", - - halign: "center", - valign: "center", - - open: false, - - status_bar: false, - detachable: true, - draggable: true, - minimizable: true, - - top: 200 - }); - - _paint_dialog = WUI_Dialog.create(_paint_dialog_id, { - title: "Paint tools", - - width: "400px", - height: "520px", - - halign: "center", - valign: "center", - - open: false, - - detachable: true, - resizable: true, - - status_bar: false, - draggable: true, - minimizable: true, - - on_detach: function (new_window) { - new_window.document.body.style.overflow = "hidden"; - }, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "canvas_import/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _quickstart_dialog = WUI_Dialog.create(_quickstart_dialog_id, { - title: "Fragment Quickstart guide", - - width: Math.min(Math.round(window.innerWidth * 0.9), 840) + "px", - height: Math.min(Math.round(window.innerHeight * 0.9), 740) + "px", - - halign: "center", - valign: "center", - - open: _quickstart_on_startup, - - detachable: true, - - status_bar: true, - status_bar_content: _motd, - draggable: true, - minimizable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "getting_started/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - WUI_Tabs.create("fs_help_tabs", { - height: "auto" - }); - - WUI_ToolBar.create("fs_record_toolbar", { - allow_groups_minimize: false - }, - { - ctrl: [ - { - icon: "fs-reset-icon", - on_click: _rewindRecording, - tooltip: "Reset recording" - } - ], - type: [ - { - icon: "fs-midi-icon", - type: "toggle", - toggle_state: false, - on_click: _toggleMIDIRecord, - tooltip: "Only show MIDI output", - toggle_group: 0 - }, - { - icon: "fs-osc-icon", - type: "toggle", - toggle_state: false, - on_click: _toggleOSCRecord, - tooltip: "Only show OSC output", - toggle_group: 0 - }, - { - icon: "fs-fas-icon", - type: "toggle", - toggle_state: true, - on_click: _toggleAUDIORecord, - tooltip: "Only show AUDIO output", - toggle_group: 0 - }, - { - icon: "fs-all-icon", - type: "toggle", - toggle_state: false, - on_click: _toggleALLRecord, - tooltip: "Show all output", - toggle_group: 0 - } - ], - opts: [ - { - icon: "fs-plus-symbol-icon", - type: "toggle", - toggle_state: false, - on_click: _toggleAdditiveRecord, - tooltip: "Additive", - toggle_group: 1 - }, - { - icon: "fs-minus-symbol-icon", - type: "toggle", - toggle_state: false, - on_click: _toggleSubstractiveRecord, - tooltip: "Substractive", - toggle_group: 1 - }, - { - icon: "fs-multiply-symbol-icon", - type: "toggle", - toggle_state: false, - on_click: _toggleMultiplyRecord, - tooltip: "Multiply", - toggle_group: 1 - } - ], - acts: [ - { - icon: "fs-plus-icon", - on_click: _addRecordInput, - tooltip: "Add as input" - }, - { - icon: "fs-audio-file-icon", - on_click: _exportRecord, - tooltip: "Export as .wav (additive synthesis)" - }, - { - icon: "fs-save-icon", - on_click: _saveRecord, - tooltip: "Save as PNG" - } - ] - }); - - WUI_ToolBar.create("fs_paint_toolbar", { - allow_groups_minimize: false - }, - { - acts: [ - { - icon: "fs-eraser-icon", - on_click: function () { - _canvasInputClear(_selected_input_canvas); - _canvasInputUpdate(_selected_input_canvas); - }, - tooltip: "Clear canvas" - }, - { - icon: "fs-lockx-icon", - type: "toggle", - toggle_state: false, - on_click: function () { - _paint_lock_x = !_paint_lock_x; - }, - tooltip: "Lock horizontal axis" - }, - { - icon: "fs-locky-icon", - type: "toggle", - toggle_state: false, - on_click: function () { - _paint_lock_y = !_paint_lock_y; - }, - tooltip: "Lock vertical axis" - }, - { - icon: "fs-dice-icon", - type: "toggle", - toggle_state: false, - on_click: function () { - _paint_random = !_paint_random; - }, - tooltip: "Randomize scale, opacity and angle" - } - ], - compositing: [ - { - text: "Compositing", - tooltip: "Compositing method", - type: "dropdown", - - orientation: "s", - dropdown_items_width: "80px", - - items: [ - { - title: "source-over", - on_click: _setPaintCompositingMode("source-over") - }, - { - title: "source-in", - on_click: _setPaintCompositingMode("source-in") - }, - { - title: "source-out", - on_click: _setPaintCompositingMode("source-out") - }, - { - title: "source-atop", - on_click: _setPaintCompositingMode("source-atop") - }, - { - title: "destination-over", - on_click: _setPaintCompositingMode("destination-over") - }, - { - title: "destination-in", - on_click: _setPaintCompositingMode("destination-in") - }, - { - title: "destination-out", - on_click: _setPaintCompositingMode("destination-out") - }, - { - title: "destination-atop", - on_click: _setPaintCompositingMode("destination-atop") - }, - { - title: "lighter", - on_click: _setPaintCompositingMode("lighter") - }, - { - title: "copy", - on_click: _setPaintCompositingMode("copy") - }, - { - title: "xor", - on_click: _setPaintCompositingMode("xor") - }, - { - title: "multiply", - on_click: _setPaintCompositingMode("multiply") - }, - { - title: "screen", - on_click: _setPaintCompositingMode("screen") - }, - { - title: "overlay", - on_click: _setPaintCompositingMode("overlay") - }, - { - title: "darken", - on_click: _setPaintCompositingMode("darken") - }, - { - title: "lighten", - on_click: _setPaintCompositingMode("lighten") - }, - { - title: "color-dodge", - on_click: _setPaintCompositingMode("color-dodge") - }, - { - title: "color-burn", - on_click: _setPaintCompositingMode("color-burn") - }, - { - title: "hard-light", - on_click: _setPaintCompositingMode("hard-light") - }, - { - title: "soft-light", - on_click: _setPaintCompositingMode("soft-light") - }, - { - title: "difference", - on_click: _setPaintCompositingMode("difference") - }, - { - title: "exclusion", - on_click: _setPaintCompositingMode("exclusion") - }, - { - title: "hue", - on_click: _setPaintCompositingMode("hue") - }, - { - title: "saturation", - on_click: _setPaintCompositingMode("saturation") - }, - { - title: "color", - on_click: _setPaintCompositingMode("color") - }, - { - title: "luminosity", - on_click: _setPaintCompositingMode("luminosity") - } - ] - } - ] - }); - - _wui_main_toolbar = WUI_ToolBar.create("fs_middle_toolbar", { - allow_groups_minimize: false, - show_groups_title: localStorage.getItem('fs-show-toolbar-title') === "true" ? true : false, - groups_title_orientation: "s" - }, - { - "Help": [ - { - id: "fs_tb_help", - icon: "fs-help-icon", - on_click: _showHelpDialog, - tooltip: "Help" - } - ], - "Social": [ - { - id: "fs_tb_chat", - icon: "fs-discuss-icon", - on_click: function () { - WUI_Dialog.open(_discuss_dialog_id); - }, - tooltip: "Session chat" - }, - { - id: "fs_tb_forum", - icon: "fs-board-icon", - on_click: function () { - window.open("https://quiet.fsynth.com", '_blank'); - }, - tooltip: "Message board" - } - ], - "Settings": [ - { - id: "fs_tb_settings", - icon: "fs-gear-icon", - on_click: _showSettingsDialog, - tooltip: "Settings" - }, - { - id: "fs_tb_midi_settings", - icon: "fs-midi-icon", - on_click: _showMIDISettingsDialog, - tooltip: "MIDI Settings" - } - ], - "Transport": [ - { - id: "fs_tb_reset", - icon: "fs-reset-icon", - on_click: _rewind, - tooltip: "Rewind (globalTime = 0)" - }, - { - id: "fs_tb_pause", - icon: "fs-pause-icon", - type: "toggle", - toggle_state: (_fs_state === 1 ? true : false), - on_click: _togglePlay, - tooltip: "Play/Pause" - }, - { - id: "fs_tb_record", - icon: "fs-record-icon", - on_click: _showRecordDialog, - tooltip: "Record" - } - ], - "Synth": [ - { - id: "fs_tb_fas_settings", - icon: "fs-fas-icon", - on_click: _showFasDialog, - tooltip: "Audio server settings" - } - ], - "Tools": [ - { - id: "fs_tb_shadertoy", - - icon: "fs-shadertoy-icon", - - toggle_state: false, - - tooltip: "Convert Shadertoy shader", - - on_click: function () { - var input_code = _current_code_editor.editor.getValue(), - output_code = input_code; - - output_code = output_code.replace(/void\s+mainImage\s*\(\s*out\s+vec4\s*[a-zA-Z]+,\s*(in)?\s+vec2\s+[a-zA-Z]+\s*\)/, "void main ()"); - output_code = output_code.replace(/fragCoord/g, "gl_FragCoord"); - output_code = output_code.replace(/fragColor/g, "gl_FragColor"); - output_code = output_code.replace(/iResolution/g, "resolution"); - output_code = output_code.replace(/iTime/g, "globalTime"); - output_code = output_code.replace(/iMouse/g, "mouse"); - output_code = output_code.replace(/iChannel/g, "iInput"); - - _current_code_editor.editor.setValue(output_code); - - _compile(); - } - }, - { - id: "fs_tb_xyf", - icon: "fs-xyf-icon", - type: "toggle", - toggle_state: _xyf_grid, - on_click: _toggleGridInfos, - tooltip: "Hide/Show mouse hover axis grid" - }/*, // DISABLED - { - icon: "fs-spectrum-icon", - on_click: _showSpectrumDialog, - tooltip: "Audio analysis dialog" - }*/, - { - id: "fs_tb_outline", - icon: "fs-function-icon", - on_click: _showOutlineDialog, - tooltip: "Outline" - }, - { - id: "fs_tb_code", - icon: "fs-code-icon", - on_click: _detachCodeEditor, - tooltip: "Clone the GLSL editor into a separate window" - } - ], - "Import": [ -/* - // DISABLED - { - icon: "fs-controls-icon", - on_click: _showControlsDialog, - tooltip: "Controllers input" - }, -*/ - { - id: "fs_tb_import", - icon: _icon_class.plus, - type: "toggle", - on_click: _showImportDialog, - tooltip: "Import Fragment input" - } - ] - }); - - WUI_RangeSlider.create("fs_paint_slider_delay", { - width: 120, - height: 8, - - min: 0, - max: 500, - - step: 1, - - midi: true, - - default_value: _paint_delay, - value: _paint_delay, - - title: "Brush spacing", - - title_min_width: 110, - value_min_width: 48, - - configurable: { - min: {}, - max: {}, - step: {}, - scroll_step: {} - }, - - on_change: function (value) { - _paint_delay = parseFloat(value); - } - }); - - WUI_RangeSlider.create("fs_paint_slider_scalex", { - width: 120, - height: 8, - - min: 0, - max: 10, - - //step: "any", - - midi: true, - - default_value: _paint_scalex, - value: _paint_scalex, - - title: "Brush scale x", - - title_min_width: 110, - value_min_width: 48, - - configurable: { - min: {}, - max: {}, - step: {}, - scroll_step: {} - }, - - on_change: function (value) { - _paint_scalex = value; - - _drawBrushHelper(); - } - }); - - WUI_RangeSlider.create("fs_paint_slider_scaley", { - width: 120, - height: 8, - - min: 0, - max: 10, - - //step: "any", - - midi: true, - - default_value: _paint_scaley, - value: _paint_scaley, - - title: "Brush scale y", - - title_min_width: 110, - value_min_width: 48, - - configurable: { - min: {}, - max: {}, - step: {}, - scroll_step: {} - }, - - on_change: function (value) { - _paint_scaley = parseFloat(value); - - _drawBrushHelper(); - } - }); - - WUI_RangeSlider.create("fs_paint_slider_opacity", { - width: 120, - height: 8, - - min: 0.0, - max: 1.0, - - //step: "any", - scroll_step: 0.01, - - midi: true, - - default_value: _paint_opacity, - value: _paint_opacity, - - title: "Brush opacity", - - title_min_width: 110, - value_min_width: 48, - - configurable: { - step: {}, - scroll_step: {} - }, - - on_change: function (value) { - _paint_opacity = parseFloat(value); - - _drawBrushHelper(); - } - }); - - WUI_RangeSlider.create("fs_paint_slider_angle", { - width: 120, - height: 8, - - min: 0.0, - max: 360.0, - - //step: "any", - scroll_step: 0.01, - - midi: true, - - default_value: _paint_angle, - value: _paint_angle, - - title: "Brush angle", - - title_min_width: 110, - value_min_width: 48, - - configurable: { - step: {}, - scroll_step: {} - }, - - on_change: function (value) { - _paint_angle = _degToRad(parseFloat(value)); - - _drawBrushHelper(); - } - }); - - WUI_RangeSlider.create("fs_score_width_input", { - width: 120, - height: 8, - - min: 0, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: _canvas_width, - value: _canvas_width, - - title: "Score width", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (new_width) { _updateScore({ width: new_width }, true); } - }); - - WUI_RangeSlider.create("fs_score_height_input", { - width: 120, - height: 8, - - min: 16, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: _canvas_height, - value: _canvas_height, - - title: "Score height (resolution)", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (new_height) { _updateScore({ height: new_height }, true); } - }); - - WUI_RangeSlider.create("fs_score_base_input", { - width: 120, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 0.01, - - decimals: 2, - - default_value: 16.34, - value: 16.34, - - title: "Score base frequency", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (new_base_freq) { _updateScore({ base_freq: new_base_freq }, true); } - }); - - WUI_RangeSlider.create("fs_score_octave_input", { - width: 120, - height: 8, - - min: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: 10, - value: 10, - - title: "Score octave range", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (new_range) { _updateScore({ octave: new_range }, true); } - }); - - WUI_RangeSlider.create("fs_settings_max_polyphony", { - width: 120, - height: 8, - - min: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: _keyboard.polyphony_max, - value: _keyboard.polyphony_max, - - title: "Polyphony", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (polyphony) { - if (polyphony <= 0) { - return; - } - - _keyboard.polyphony_max = polyphony; - - localStorage.setItem('fs-max-polyphony', _keyboard.polyphony_max); - - _keyboard.data = []; - _keyboard.data_length = _keyboard.polyphony_max * _keyboard.data_components; - - _MIDInotesCleanup(); - - _compile(); - } - }); - - WUI_RangeSlider.create("fs_settings_note_lifetime", { - width: 120, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 10, - - default_value: _keyboard.note_lifetime, - value: _keyboard.note_lifetime, - - title: "Note lifetime (ms)", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (note_lifetime) { - if (note_lifetime <= 0) { - return; - } - - _keyboard.note_lifetime = note_lifetime; - - localStorage.setItem('fs-note-lifetime', _keyboard.note_lifetime); - } - }); - - WUI_RangeSlider.create("fs_settings_fps", { - width: 120, - height: 8, - - min: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - default_value: _fas.fps, - value: _fas.fps, - - title: "FPS / Slices data rate", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (fps) { - if (fps <= 0) { - return; - } - - _fas.fps = fps; - - localStorage.setItem('fs-fps', _fas.fps); - - _fasNotify(_FAS_SYNTH_INFOS, { target: 0, value: _fas.fps }); - } - }); - - WUI_RangeSlider.create("fs_settings_compile_delay", { - width: 120, - height: 8, - - min: 0, - max: 5000, - - bar: false, - - step: 1, - scroll_step: 10, - - default_value: _compile_delay_ms, - value: _compile_delay_ms, - - title: "Compile delay (ms)", - - title_min_width: 140, - value_min_width: 88, - - on_change: function (delay) { - if (delay < 0) { - return; - } - - _compile_delay_ms = delay; - - localStorage.setItem('fs-compile-delay', _compile_delay_ms); - } - }); - - WUI_RangeSlider.create("mst_slider", { - width: 100, - height: 8, - - min: 0.0, - max: 1.0, - - bar: false, - - step: "any", - scroll_step: 0.0001, - - decimals: 4, - - midi: true, - - default_value: _volume, - value: _volume, - - title: "Gain", - - title_min_width: 32, - value_min_width: 48, - - on_change: function (value) { - _local_session_settings.gain = value; - _saveLocalSessionSettings(); - - _setGain(value); - - _fasNotify(_FAS_SYNTH_INFOS, { target: 1, value: _audio_infos.gain }); - } - }); - - WUI_RangeSlider.create("fs_import_audio_gain_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 0.0001, - - decimals: 4, - - midi: false, - - default_value: _audio_import_settings.gain, - value: _audio_import_settings.gain, - - title: "Gain factor", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.gain = value; - } - }); - - WUI_RangeSlider.create("fs_import_audio_deviation_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 0.0001, - - decimals: 4, - - midi: false, - - default_value: _audio_import_settings.deviation, - value: _audio_import_settings.deviation, - - title: "Deviation", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.deviation = value; - } - }); - - WUI_RangeSlider.create("fs_import_audio_padding_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 16, - - midi: false, - - default_value: _audio_import_settings.padding, - value: _audio_import_settings.padding, - - title: "Padding", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.padding = parseInt(value, 10); - } - }); - - WUI_RangeSlider.create("fs_import_audio_pps_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 1, - - midi: false, - - default_value: _audio_import_settings.pps, - value: _audio_import_settings.pps, - - title: "PPS", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.pps = parseInt(value, 10); - } - }); - - WUI_RangeSlider.create("fs_import_audio_height_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 1, - - midi: false, - - default_value: _audio_import_settings.height, - value: _audio_import_settings.height, - - title: "Height", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.height = parseInt(value, 10); - } - }); - - WUI_RangeSlider.create("fs_import_audio_minfreq_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 0.1, - - midi: false, - - default_value: _audio_import_settings.minfreq, - value: _audio_import_settings.minfreq, - - title: "Min. freq.", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.minfreq = value; - } - }); - - WUI_RangeSlider.create("fs_import_audio_maxfreq_settings", { - width: 100, - height: 8, - - min: 0, - - bar: false, - - step: "any", - scroll_step: 0.1, - - midi: false, - - default_value: _audio_import_settings.maxfreq, - value: _audio_import_settings.maxfreq, - - title: "Max. freq.", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.maxfreq = value; - } - }); - - WUI_RangeSlider.create("fs_import_cam_width", { - width: 100, - height: 8, - - min: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - midi: false, - - default_value: _audio_import_settings.cam_width, - value: _audio_import_settings.cam_width, - - title: "Cam. width", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.cam_width = value; - } - }); - - WUI_RangeSlider.create("fs_import_cam_height", { - width: 100, - height: 8, - - min: 1, - - bar: false, - - step: 1, - scroll_step: 1, - - midi: false, - - default_value: _audio_import_settings.cam_height, - value: _audio_import_settings.cam_height, - - title: "Cam. height", - - title_min_width: 84, - value_min_width: 64, - - on_change: function (value) { - _audio_import_settings.cam_height = value; - } - }); - - // initialize collapsable elements - var collapsibles = document.querySelectorAll(".fs-collapsible"), - legends, - i, j; - for (i = 0; i < collapsibles.length; i += 1) { - legends = collapsibles[i].getElementsByClassName("fs-collapsible-legend"); - if (legends.length > 0) { - _applyCollapsible(collapsibles[i], legends[0]); - } - } - - // now useless, just safe to remove! - _utterFailRemove(); -};/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _pjs_dialog_id = "fs_pjs", - _pjs_dialog, - - _current_pjs_input = null, - - _pjs_code_change_timeout = null, - _pjs_code_change_ms = 750, - - _pjs_codemirror_instance, - _pjs_codemirror_instance_detached, - - _pjs_wrapped_code_change, - _pjs_wrapped_code_change_detached; - -/*********************************************************** - Functions. -************************************************************/ - -var _pjsUpdateTexture = function () { - var fragment_input, - i = 0; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input = _fragment_input_data[i]; - - if (fragment_input.type === 4) { - _gl.bindTexture(_gl.TEXTURE_2D, fragment_input.texture); - _gl.texImage2D(_gl.TEXTURE_2D, 0, _gl.RGBA, fragment_input.canvas.width, fragment_input.canvas.height, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, fragment_input.canvas);//new Uint8Array(image_data.data)); - _gl.bindTexture(_gl.TEXTURE_2D, null); - } - } -}; - -var _pjsMouseMoveEvent = function () { - var fragment_input, - i = 0; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input = _fragment_input_data[i]; - - if (fragment_input) { - if (fragment_input.type === 4) { - fragment_input.canvas.dispatchEvent(new Event('mousemove')); - } - } - } -}; - -var _pjsCodeChange = function (source_code) { - var pjs, - pjs_source_code = (source_code !== undefined) ? source_code : _pjs_codemirror_instance.getValue(), - - inputs_source_code = "", - inputs_load_source_code = "", - - input_url = "", - - fragment_input, - - pjs_canvas = null, - pjs_gl = null, - - fs_pjs_size = "size(" + _canvas_width + "," + _canvas_height + "$1", - - fs_pjs_library = [ - 'float baseFrequency = ' + _audio_infos.base_freq + ";", - 'float octaves = ' + _audio_infos.octaves + ";", - 'int htoy (float f) {', - ' return (height - (log(f / baseFrequency) / log(2.0)) * floor(height / octaves + 0.5));', - '}', - 'float yfreq (float y, float sample_rate) {', - ' return (baseFrequency * pow(2., (height - round(y * height)) / octaves)) / sample_rate;', - "}" - ].join("\n"), - - pjs_error, - - i = 0; - - if (_current_pjs_input !== null) { - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input = _fragment_input_data[i]; - - if (fragment_input.type === 0) { - input_url = fragment_input.elem.title + "_str"; - - inputs_source_code += "String " + input_url + " = \"" + _imageToDataURL(fragment_input.image) + "\";\n"; - inputs_load_source_code += "" + fragment_input.elem.title + " = loadImage(" + input_url + ");" - } - } - - pjs_source_code = pjs_source_code.replace(/size.*?\([\d\w]+.*?[\d\w]+(,*)/gm, fs_pjs_size); - pjs_source_code = 'float globalTime = ' + _current_pjs_input.globalTime + ";\n" + fs_pjs_library + inputs_source_code + pjs_source_code.replace(/(void\s+setup\s*\(\)\s*{)/gm, "$1 " + "background(0, 0, 0, 255);" + inputs_load_source_code + "\n"); - - // NOTE : we must delete the old 3D context when using 3D mode - if (_current_pjs_input.pjs) { - pjs_canvas = _current_pjs_input.pjs.externals.canvas; - - _current_pjs_input.pjs.exit(); - - if (pjs_canvas) { - pjs_gl = pjs_canvas.getContext("webgl2", _webgl_opts) || - pjs_canvas.getContext("experimental-webgl2", _webgl_opts) || - pjs_canvas.getContext("webgl", _webgl_opts) || - pjs_canvas.getContext("experimental-webgl", _webgl_opts); - if (pjs_gl) { - if (pjs_gl.getExtension('WEBGL_lose_context')) { - pjs_gl.getExtension('WEBGL_lose_context').loseContext(); - } - } - } - - _current_pjs_input.pjs = null; - } - - WUI_Dialog.setStatusBarContent(_pjs_dialog, 'Successfully compiled" + pjs_error + ""); - } - } - - _current_pjs_input.pjs_source_code = _pjs_codemirror_instance.getValue(); - - _current_pjs_input.db_obj.data = _pjs_codemirror_instance.getValue(); - - _dbUpdateInput(_parseInt10(_current_pjs_input.elem.dataset.inputId), _current_pjs_input.db_obj); - - //_compile(); - } -}; - -var _pjsDimensionsUpdate = function (new_width, new_height) { - var i = 0, - fragment_input_data, - input_id; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - if (fragment_input_data.type === 4) { - fragment_input_data.db_obj.width = new_width; - fragment_input_data.db_obj.height = new_height; - - fragment_input_data.texture = _replace2DTexture({ empty: true, width: new_width, height: new_height }, fragment_input_data.texture); - - input_id = _parseInt10(fragment_input_data.elem.dataset.inputId); - - _dbUpdateInput(input_id, fragment_input_data.db_obj); - - _pjsUpdateTexture(); - } - } -}; - -var _pjsCompile = function (input) { - if (input.type === 4) { - var user_selected_input = _current_pjs_input; - - _pjsSelectInput(input); - - _pjsCodeChange(_current_pjs_input.pjs_source_code); - - _pjsSelectInput(user_selected_input); - } -}; - -var _pjsCompileAll = function () { - var i = 0, - fragment_input_data; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - _pjsCompile(fragment_input_data); - } -}; - -var _pjsPause = function (input) { - if (input.type !== 4) { - return; - } - - if (input.pjs) { - input.pjs.noLoop(); - } -}; - -var _pjsResume = function (input) { - if (input.type !== 4) { - return; - } - - if (input.pjs) { - input.pjs.loop(); - } -} - -var _pjsResumeAll = function () { - var i = 0, - fragment_input_data; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - _pjsResume(fragment_input_data); - } -}; - -var _pjsPauseAll = function () { - var i = 0, - fragment_input_data; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - _pjsPause(fragment_input_data); - } -}; - -var _pjsBindCodeChangeEvent = function () { - CodeMirror.on(_pjs_codemirror_instance, 'change', _pjs_wrapped_code_change); - - if (_pjs_codemirror_instance_detached) { - CodeMirror.on(_pjs_codemirror_instance_detached, 'change', _pjs_wrapped_code_change_detached); - } -}; - -var _pjsUnbindCodeChangeEvent = function () { - CodeMirror.off(_pjs_codemirror_instance, 'change', _pjs_wrapped_code_change); - - if (_pjs_codemirror_instance_detached) { - CodeMirror.off(_pjs_codemirror_instance_detached, 'change', _pjs_wrapped_code_change_detached); - } -}; - -var _pjsInit = function () { - var custom_message_area = document.createElement("textarea"), - - pjs_editor_div = document.getElementById("fs_pjs_editor"), - - cm_element; - - custom_message_area.className = "fs-textarea"; - custom_message_area.style.border = "1px solid #111111"; - - _pjs_dialog = WUI_Dialog.create(_pjs_dialog_id, { - title: "Processing.js Editor", - - width: "800px", - height: "360px", - min_height: "80px", - - halign: "center", - valign: "center", - - open: false, - - status_bar: true, - detachable: true, - draggable: true, - resizable: true, - minimizable: true, - - status_bar_content: "", - - on_open: function () { - _pjs_codemirror_instance.refresh(); - }, - - on_detach: function (new_window) { - _current_pjs_input = null; - - _pjsUnbindCodeChangeEvent(); - - var pjs_editor_div = new_window.document.getElementById("fs_pjs_editor"), - textarea = document.createElement("textarea"), - cm_element; - - new_window.document.head.innerHTML += ''; - - textarea.className = "fs-textarea"; - textarea.style.border = "1px solid #111111"; - - pjs_editor_div.innerHTML = ""; - - pjs_editor_div.appendChild(textarea); - - _pjs_codemirror_instance_detached = CodeMirror.fromTextArea(textarea, { - mode: "text/x-java", - styleActiveLine: true, - lineNumbers: true, - lineWrapping: true, - theme: ((_code_editor_theme === null) ? "seti" : _code_editor_theme), - matchBrackets: true, - scrollbarStyle: "native" - }); - - cm_element = _pjs_codemirror_instance_detached.getWrapperElement(); - cm_element.style = "font-size: 12pt"; - - _pjs_codemirror_instance_detached.setValue(_pjs_codemirror_instance.getValue()); - - _pjs_codemirror_instance_detached.refresh(); - - CodeMirror.on(_pjs_codemirror_instance_detached, 'change', _pjs_wrapped_code_change_detached); - - _pjsBindCodeChangeEvent(); - }, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "pjs_import/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - pjs_editor_div.appendChild(custom_message_area); - - _pjs_codemirror_instance = CodeMirror.fromTextArea(custom_message_area, { - mode: "text/x-java", - styleActiveLine: true, - lineNumbers: true, - lineWrapping: true, - theme: ((_code_editor_theme === null) ? "seti" : _code_editor_theme), - matchBrackets: true, - scrollbarStyle: "native" - }); - - cm_element = _pjs_codemirror_instance.getWrapperElement(); - cm_element.style = "font-size: 12pt"; - - _pjs_wrapped_code_change = function () { - clearTimeout(_pjs_code_change_timeout); - _pjs_code_change_timeout = setTimeout(_pjsCodeChange, _pjs_code_change_ms); - }; - - _pjs_wrapped_code_change_detached = function () { - clearTimeout(_pjs_code_change_timeout); - _pjs_code_change_timeout = setTimeout(_pjsCodeChange, _pjs_code_change_ms, _pjs_codemirror_instance_detached.getValue()); - - _pjsUnbindCodeChangeEvent(); - - _pjs_codemirror_instance.setValue(_pjs_codemirror_instance_detached.getValue()); - - _pjsBindCodeChangeEvent(); - }; - - _pjsBindCodeChangeEvent(); - - _pjsUpdateInputs(); - - var detached_dialog = WUI_Dialog.getDetachedDialog(_pjs_dialog); - if (detached_dialog) { - _pjsUpdateInputs(detached_dialog.document); - } -}; - -var _pjsSelectInput = function (input) { - if (_current_pjs_input === input || input === null) { - return; - } - - _current_pjs_input = input; - - _pjsUnbindCodeChangeEvent(); - - _pjs_codemirror_instance.setValue(input.pjs_source_code); - - if (_pjs_codemirror_instance_detached) { - _pjs_codemirror_instance_detached.setValue(input.pjs_source_code); - } - - _pjsUpdateInputs(); - - var detached_dialog = WUI_Dialog.getDetachedDialog(_pjs_dialog); - if (detached_dialog) { - _pjsUpdateInputs(detached_dialog.document); - } - - _pjsBindCodeChangeEvent(); -}; - -var _pjsChangeSourceCb = function (input) { - return function (e) { - var elem = e.target; - - _pjsSelectInput(input); - - if (elem.parentElement !== null) { - elem.parentElement.childNodes.forEach(function (item) { - item.classList.remove("fs-pjs-selected"); - }); - - elem.classList.add("fs-pjs-selected"); - } - }; -}; - -var _pjsUpdateInputs = function (doc) { - if (!doc) { - doc = document; - } - - var i = 0, - pjs_editor_inputs = doc.getElementById("fs_pjs_inputs"), - fragment_input_data, - - selected_input = _current_pjs_input, - - input_name_div; - - pjs_editor_inputs.innerHTML = ""; - - _current_pjs_input = null; - - for (i = 0; i < _fragment_input_data.length; i += 1) { - fragment_input_data = _fragment_input_data[i]; - - if (fragment_input_data.type === 4) { - input_name_div = doc.createElement("div"); - input_name_div.className = "fs-pjs-input"; - input_name_div.innerHTML = fragment_input_data.elem.title; - - if (selected_input === fragment_input_data) { - input_name_div.classList.add("fs-pjs-selected"); - - _current_pjs_input = fragment_input_data; - } - - pjs_editor_inputs.appendChild(input_name_div); - - input_name_div.addEventListener("click", _pjsChangeSourceCb(fragment_input_data)); - } - } -};/* jslint browser: true */ - -/** - * All things related to slices. - * - * This need a severe lifting! - */ - -var _selected_slice_marker = null, - _marker_midi_message_timeout = null, - - _slice_settings_dialog_prefix = "fs_slice_settings_dialog", - - _slice_update_timeout = [{}, {}, {}, {}, {}, {}], - - _slice_dialog_id = 0, - - _slice_type_color = ["#ffffff", "#ff0000"]; - -/*********************************************************** - Functions. -************************************************************/ - -var _openSliceSettingsDialogFn = function (slice_obj) { - return function () { - WUI_Dialog.open(_slice_settings_dialog_prefix + slice_obj.dialog_id); - } -}; - -var _updateSliceSettingsDialog = function (slice_obj, show) { - var i = 0; - - _selected_slice = slice_obj; - - if (show) { - WUI_Dialog.open(_slice_settings_dialog_prefix + slice_obj.dialog_id); - - //slice_obj.custom_midi_codemirror.refresh(); - } -}; - -var _saveMarkersSettings = function () { - _local_session_settings.markers = []; - _play_position_markers.forEach(function (obj) { - var marker_settings = { }; - marker_settings.midi_out = _cloneObj(obj.midi_out); - marker_settings.osc_out = obj.osc_out; - marker_settings.audio_out = obj.audio_out; - delete marker_settings.midi_out["custom_midi_message_fn"]; - _local_session_settings.markers.push(marker_settings); - }); - _saveLocalSessionSettings(); -}; - -var _domCreatePlayPositionMarker = function (hook_element, height) { - var play_position_marker_div = document.createElement("div"), - decoration_div = document.createElement("div"), - decoration_div2 = document.createElement("div"), - output_channel = document.createElement("div"); - - output_channel.className = "fs-slice-output"; - - play_position_marker_div.className = "play-position-marker"; - - decoration_div.style.top = "0px"; - //decoration_div2.style.top = "0"; - - play_position_marker_div.style.height = height + "px"; - - decoration_div.className = "play-position-triangle"; - decoration_div2.className = "play-position-triangle-vflip"; - - play_position_marker_div.appendChild(output_channel); - play_position_marker_div.appendChild(decoration_div); - play_position_marker_div.appendChild(decoration_div2); - - hook_element.parentElement.insertBefore(play_position_marker_div, hook_element); - - return { slice_div: play_position_marker_div, out_div: output_channel }; -}; - -var _getSlice = function (play_position_marker_id) { - return _play_position_markers[parseInt(play_position_marker_id, 10)]; -}; - -var _setPlayPosition = function (play_position_marker_id, x, y, submit, dont_update_slider) { - var play_position_marker = _getSlice(play_position_marker_id), - - canvas_offset = _getElementOffset(_canvas); - - if (play_position_marker.x < 0) { - x = _canvas_width_m1; - } else if (play_position_marker.x > _canvas_width_m1) { - x = 0; - } - - play_position_marker.x = x; - - play_position_marker.element.style.left = (parseInt(x, 10) + canvas_offset.left + 1) + "px"; - - if (dont_update_slider === undefined) { - WUI_RangeSlider.setValue("fs_slice_settings_x_input_" + play_position_marker.id, x); - } - - if (submit) { - _submitSliceUpdate(0, play_position_marker_id, { x : x }); - } -}; - -var _updateAllPlayPosition = function () { - var i = 0, - - canvas_offset = _getElementOffset(_canvas), - - play_position_marker; - - for (i = 0; i < _play_position_markers.length; i += 1) { - play_position_marker = _play_position_markers[i]; - - play_position_marker.element.style.left = (play_position_marker.x + canvas_offset.left) + "px"; - } -}; - -var _updatePlayMarkersHeight = function (height) { - var i = 0, - - play_position_marker; - - for (i = 0; i < _play_position_markers.length; i += 1) { - play_position_marker = _play_position_markers[i]; - - play_position_marker.element.style.height = height + "px"; - play_position_marker.height = height; - } -}; - -var _updatePlayMarker = function (id, obj) { - var slice = _play_position_markers[_parseInt10(id)]; - - if ('x' in obj) { - _setPlayPosition(slice.element.dataset.slice, _parseInt10(obj.x), 0); - } - - if ('mute' in obj) { - slice.mute = obj.mute; - - if (slice.mute) { - _muteSlice(slice); - } else { - _unmuteSlice(slice); - } - } - - if ('shift' in obj) { - slice.shift = _parseInt10(obj.shift); - - WUI_RangeSlider.setValue("fs_slice_settings_shift_input_" + slice.id, slice.shift); - } - - if ('output_channel' in obj) { - slice.output_channel = _parseInt10(obj.output_channel); - - WUI_RangeSlider.setValue("fs_slice_settings_channel_input_" + slice.id, slice.output_channel); - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: _parseInt10(id), target: 2, value: slice.output_channel - 1 }); - } - - if ('instruments_settings' in obj) { - if ('type' in obj.instruments_settings) { - slice.instrument_type = obj.instrument_settings.type; - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: _parseInt10(id), target: 0, value: slice.instruments_settings.type }); - } - - if ('muted' in obj.instruments_settings) { - slice.mute = obj.instrument_settings.muted; - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: _parseInt10(id), target: 1, value: slice.instruments_settings.muted }); - } - - if ('params' in obj.instruments_settings) { - for (var i = 0; i < 6; i += 1) { - if ("p"+i in obj.instruments_settings.params) { - var v = obj.instruments_settings.params["p"+i]; - - slice.instrument_params["p"+i] = v; - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: _parseInt10(id), target: 3 + i, value: v }); - } - } - } - } - - if ('type' in obj) { - _changeSliceType(slice, obj.type); - } - - _createFasSettingsContent(); -}; - -var _removePlayPositionMarker = function (marker_id, force, submit) { - var slice = _play_position_markers[parseInt(marker_id, 10)], - slice_tmp, - i; - - WUI.undraggable(slice.element); - WUI.undraggable(slice.element.firstElementChild); - WUI.undraggable(slice.element.firstElementChild.nextElementSibling); - WUI.undraggable(slice.element.lastElementChild); - - slice.element.parentElement.removeChild(slice.element); - - WUI_RangeSlider.destroy("fs_slice_settings_x_input_" + marker_id); - WUI_RangeSlider.destroy("fs_slice_settings_shift_input_" + marker_id); - WUI_RangeSlider.destroy("fs_slice_settings_channel_input_" + marker_id); - WUI_RangeSlider.destroy("fs_slice_settings_bpm_" + marker_id); - WUI_Dialog.destroy(_slice_settings_dialog_prefix + slice.dialog_id); - - _play_position_markers.splice(marker_id, 1); - - for (i = 0; i < _play_position_markers.length; i += 1) { - slice_tmp = _play_position_markers[i]; - - slice_tmp.element.dataset.slice = i; - slice_tmp.id = i; - - WUI_Dialog.setTitle(_slice_settings_dialog_prefix + slice_tmp.dialog_id, _getSliceTitle(slice_tmp)); - } - - if (submit) { - _submitRemoveSlice(marker_id); - } - - _midiUpdateSlices(); - - _computeOutputChannels(); - - _saveMarkersSettings(); - - if (_play_position_markers.length === 0) { - _osc_infos.textContent = ""; - _poly_infos_element.textContent = ""; - } - - _fasSendIntrumentsInfos(true); - - _createFasSettingsContent(); -}; - -var _cbMarkerSettingsChange = function (mobj, cb) { - return function (value) { - cb(this, value, mobj); - }; -}; - -var _buildMarkerMIDIDevices = function (marker_obj, midi_dev_list) { - var i = 0, j = 0, - midi_devices, - midi_dev_option, - uids = [], - key; - - midi_dev_list.innerHTML = ""; - - midi_devices = _getMIDIDevices("output"); - - for (j = 0; j < marker_obj.midi_out.device_uids.length; j += 1) { - if (!(marker_obj.midi_out.device_uids[i] in midi_devices)) { - _notification("Instrument '" + marker_obj.id + "' MIDI out '" + i + "' device does not exist anymore, defaulted to 'none'.", 4000); - } else { - uids.push(marker_obj.midi_out.device_uids[i]); - } - } - - marker_obj.midi_out.device_uids = uids; - - for (key in midi_devices) { - if (!midi_devices[key].id) { - continue; - } - - i += 1; - - midi_dev_option = document.createElement("option"); - midi_dev_option.innerHTML = midi_devices[key].name; - midi_dev_option.dataset.uid = midi_devices[key].id; - midi_dev_option.value = midi_devices[key].id; - midi_dev_option.id = "fs_slice_settings_midi_device_opt_" + marker_obj.id + "_" + i; - - for (j = 0; j < marker_obj.midi_out.device_uids.length; j += 1) { - if (marker_obj.midi_out.device_uids[j] === midi_devices[key].id) { - midi_dev_option.selected = true; - } - } - - midi_dev_list.appendChild(midi_dev_option); - } -}; - -var _rebuildMarkersMIDIDevices = function () { - var i = 0, - - play_position_marker, - - midi_dev_list; - - for (i = 0; i < _play_position_markers.length; i += 1) { - play_position_marker = _play_position_markers[i]; - - midi_dev_list = document.getElementById("fs_slice_settings_midi_device_" + play_position_marker.id); - - _buildMarkerMIDIDevices(play_position_marker, midi_dev_list); - } -}; - -var _updateSliceChnVisibility = function () { - var i = 0, - slice, - chn_div; - - for (i = 0; i < _play_position_markers.length; i += 1) { - slice = _play_position_markers[i]; - - slice.out_txt_div.style.display = (_show_output_channels === true) ? "" : "none"; - } -}; - -var _compileMarkerMIDIData = function (marker_obj) { - try { - marker_obj.midi_out.custom_midi_message_fn = new Function("type", "l", "r", "b", "a", "c", "var on, off, change;" + marker_obj.midi_out.custom_midi_message + "\nreturn { on: on, change: change, off: off };"); - - WUI_Dialog.setStatusBarContent(_midi_dialog, 'Successfully compiled' + e + ' 0) { - midi_custom_message_area.innerHTML = marker_obj.midi_out.custom_midi_message; - } - - midi_dev_list_label.className = "fs-select-label"; - midi_dev_list_label.htmlFor = "fs_slice_settings_midi_device_" + marker_obj.id; - midi_dev_list_label.innerHTML = "Device"; -*/ - - midi_out_editor_btn.innerHTML = "Open MIDI OUT editor"; - midi_out_editor_btn.className = "fs-btn fs-btn-default"; - - midi_out_editor_btn.style.width = "100%"; - - midi_out_editor_btn.addEventListener("click", function () { - _midiSelectSlice(marker_obj); - - _midiUpdateSlices(); - - var detached_window = WUI_Dialog.getDetachedDialog(_midi_dialog); - if (detached_window) { - _midiUpdateSlices(detached_window.document); - } - - if (marker_obj.midi_out.enabled) { - WUI_Dialog.open(_midi_dialog); - } - }); - - midi_dev_list.id = "fs_slice_settings_midi_device_" + marker_obj.id; - midi_dev_list.className = "fs-multiple-select"; - midi_dev_list.multiple = true; - - midi_dev_list_ck.innerHTML = "on/off  "; - midi_dev_list_ck_label.className = "fs-ck-label"; - midi_dev_list_ck_input.type = "checkbox"; - - if (marker_obj.midi_out.enabled) { - midi_dev_list_ck_input.checked = true; - } - - midi_dev_list_ck_input.addEventListener("change", _cbMarkerSettingsChange(marker_obj, function (self, instance, marker_obj) { - marker_obj.midi_out.enabled = self.checked; - _saveMarkersSettings(); - - _midiUpdateSlices(); - - var detached_window = WUI_Dialog.getDetachedDialog(_midi_dialog); - if (detached_window) { - _midiUpdateSlices(detached_window.document); - } - })); - - midi_dev_list_ck_label.appendChild(midi_dev_list_ck); - midi_dev_list_ck_label.appendChild(midi_dev_list_ck_input); - midi_dev_list_container.appendChild(midi_dev_list_ck_label); - - midi_dev_list_container.className = "fs-fieldset"; - midi_dev_list_container_legend.innerHTML = "MIDI out"; - - //midi_dev_out_container.appendChild(midi_dev_list_label); - //midi_dev_out_container.innerHTML += " "; - //midi_dev_out_container.appendChild(midi_dev_list); - - midi_dev_list_container.appendChild(midi_dev_list_container_legend); - - midi_device_fieldset.appendChild(midi_dev_list); - midi_dev_list_container.appendChild(midi_device_fieldset); - midi_dev_list_container.appendChild(midi_out_editor_btn); - - //midi_dev_out_container.style = "text-align: center"; - - //midi_dev_list_container.appendChild(midi_dev_out_container); - /* - midi_dev_list_container.appendChild(midi_custom_message_area); - - midi_custom_codemirror = CodeMirror.fromTextArea(midi_custom_message_area, { - mode: "text/javascript", - styleActiveLine: true, - lineNumbers: false, - lineWrapping: true, - theme: ((_code_editor_theme === null) ? "seti" : _code_editor_theme), - matchBrackets: true - }); - - cm_element = midi_custom_codemirror.getWrapperElement(); - cm_element.style = "font-size: 10pt"; - - CodeMirror.on(midi_custom_codemirror, 'change', _cbMarkerSettingsChange(marker_obj, function (self, instance, marker_obj) { - marker_obj.midi_out.custom_midi_message = instance.getValue(); - - clearTimeout(_marker_midi_message_timeout); - _marker_midi_message_timeout = setTimeout(_compileMarkerMIDIData, 1000, marker_obj, instance); - - _saveMarkersSettings(); - })); - */ - if (!_webMIDISupport()) { - midi_dev_out_container.style.display = "none"; - //cm_element.style.display = "none"; - - tmp_element = document.createElement("div"); - tmp_element.innerHTML = _webmidi_support_msg; - - midi_dev_list_container.removeChild(midi_dev_list_ck_label); - midi_dev_list_container.removeChild(midi_device_fieldset); - midi_dev_list_container.removeChild(midi_out_editor_btn); - - midi_dev_list_container.appendChild(tmp_element); - - _applyCollapsible(midi_dev_list_container, midi_dev_list_container_legend, true); - } else { - _applyCollapsible(midi_dev_list_container, midi_dev_list_container_legend, true); - - _buildMarkerMIDIDevices(marker_obj, midi_dev_list); - - midi_dev_list.addEventListener("change", _cbMarkerSettingsChange(marker_obj, function (self, value, marker_obj) { - var len = self.options.length, - opt = null, - uids = [], - i = 0; - - for (i = 0; i < len; i += 1) { - opt = self.options[i]; - - if (opt.selected) { - uids.push(opt.dataset.uid); - } - } - - marker_obj.midi_out.device_uids = uids; - - _saveMarkersSettings(); - })); - } - - //marker_obj.custom_midi_codemirror = midi_custom_codemirror; - - fs_slice_settings_x_input.id = "fs_slice_settings_x_input_" + marker_obj.id; - fs_slice_settings_shift_input.id = "fs_slice_settings_shift_input_" + marker_obj.id; - fs_slice_settings_channel_input.id = "fs_slice_settings_channel_input_" + marker_obj.id; - fs_slice_settings_synthesis_select.id = "fs_slice_settings_synthesis_select" + marker_obj.id; - fs_slice_settings_bpm.id = "fs_slice_settings_bpm_" + marker_obj.id; - - dialog_element.id = dialog_id; - - WUI_RangeSlider.create(fs_slice_settings_x_input, { - width: 120, - height: 8, - - bar: false, - - min: 0, - - step: 1, - - midi: { - type: "rel" - }, - - default_value: 0, - value: marker_obj.x, - - title: "X Offset (px)", - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbMarkerSettingsChange(marker_obj, function (self, value, marker_obj) { - var value = _parseInt10(value) % _canvas_width; - if (value < 0) { - value = _canvas_width - value; - } - _setPlayPosition(marker_obj.element.dataset.slice, value, 0, true); - }) - }); - - WUI_RangeSlider.create(fs_slice_settings_shift_input, { - width: 120, - height: 8, - - bar: false, - - step: 1, - - midi: { - type: "rel" - }, - - default_value: 0, - value: marker_obj.shift, - - title: "Y Shift (px)", - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbMarkerSettingsChange(marker_obj, function (self, value, marker_obj) { - var slice = _getSlice(marker_obj.element.dataset.slice); - - slice.shift = _parseInt10(value); - - _submitSliceUpdate(1, marker_obj.element.dataset.slice, { shift : value }); - }) - }); - - WUI_RangeSlider.create(fs_slice_settings_channel_input, { - width: 120, - height: 8, - - bar: false, - - step: 1, - - midi: { - type: "rel" - }, - - min: 1, - - default_value: 0, - value: marker_obj.output_channel, - - title: "Output channel", - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbMarkerSettingsChange(marker_obj, function (self, value, marker_obj) { - if (value <= 0) { - value = 1; - } - - var slice = _getSlice(marker_obj.element.dataset.slice); - - slice.output_channel = _parseInt10(value); - - _submitSliceUpdate(3, marker_obj.element.dataset.slice, { output_channel: value }); - - _fasNotify(_FAS_INSTRUMENT_INFOS, { target: 2, instrument: marker_obj.element.dataset.slice, value: value - 1}); - - slice.out_txt_div.innerHTML = slice.output_channel; - - _computeOutputChannels(); - }) - }); - - WUI_RangeSlider.create(fs_slice_settings_bpm, { - width: 120, - height: 8, - - bar: false, - - step: 0.01, - - midi: { - type: "rel" - }, - - default_value: 0, - value: marker_obj.frame_increment, - - title: "Increment / frame (px)", - - //decimals: 2, - - title_min_width: 140, - value_min_width: 88, - - on_change: _cbMarkerSettingsChange(marker_obj, function (self, value, marker_obj) { - var slice = _getSlice(marker_obj.element.dataset.slice); - - slice.frame_increment = parseFloat(value); - }) - }); - - fs_slice_settings_container.appendChild(fs_slice_settings_x_input); - fs_slice_settings_container.appendChild(fs_slice_settings_shift_input); - fs_slice_settings_container.appendChild(fs_slice_settings_bpm); - fs_slice_settings_container.appendChild(fs_slice_settings_channel_input); - fs_slice_settings_container.appendChild(audio_container); - fs_slice_settings_container.appendChild(osc_container); - fs_slice_settings_container.appendChild(midi_dev_list_container); - - content_element.appendChild(fs_slice_settings_container); - dialog_element.appendChild(content_element); - - document.body.appendChild(dialog_element); - - WUI_Dialog.create(dialog_element, { - title: _getSliceTitle(marker_obj), - - width: "360px", - height: "auto", - - halign: "center", - valign: "center", - - open: false, - - detachable: false, - - status_bar: false, - minimizable: true, - draggable: true, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "instruments/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - _slice_dialog_id += 1; -}; - -var _setSlicePositionFromAbsolute = function (play_position_marker_id, x, y) { - var canvas_offset = _getElementOffset(_canvas); - - if (x <= (canvas_offset.left + 1)) { - x = 0; - } else if (x > (canvas_offset.left + _canvas_width)) { - x = _canvas_width - 1; - } else { - x = x - canvas_offset.left - 2; - } - - _setPlayPosition(play_position_marker_id, x, y, true); -}; - -var _removeAllSlices = function () { - _play_position_markers.slice(0).forEach(function(slice_obj) { - _removePlayPositionMarker(slice_obj.id, true); - }); -}; - -var _submitSliceSettingsFn = function () { - var slices_settings = [], - play_position_marker, - i = 0; - for (i = 0; i < _play_position_markers.length; i += 1) { - play_position_marker = _play_position_markers[i]; - - slices_settings.push({ - x: play_position_marker.x, - shift: play_position_marker.shift, - mute: play_position_marker.mute, - output_channel: play_position_marker.output_channel - }); - } - - _sendSlices(slices_settings); -}; - -var _submitSliceUpdate = function (tid, id, obj) { - clearTimeout(_slice_update_timeout[tid][id]); - _slice_update_timeout[tid][id] = setTimeout(_sendSliceUpdate, 1000, id, obj); -}; - -var _submitAddSlice = function (x, shift, mute) { - setTimeout(_sendAddSlice, 500, x, shift, mute); -}; - -var _submitRemoveSlice = function (id) { - setTimeout(_sendRemoveSlice, 500, id); -}; - -var _muteSlice = function (slice_obj, submit) { - var play_position_top_hook_element = slice_obj.element.firstElementChild.nextElementSibling, - play_position_bottom_hook_element = slice_obj.element.lastElementChild; - - slice_obj.mute = true; - - _fasSendIntrumentsInfos(false); - - if (slice_obj.type === 1) { - play_position_top_hook_element.style.borderTopColor = "#550000"; - play_position_bottom_hook_element.style.borderBottomColor = "#550000"; - } else { - play_position_top_hook_element.style.borderTopColor = "#555555"; - play_position_bottom_hook_element.style.borderBottomColor = "#555555"; - } - - if (submit) { - _submitSliceUpdate(2, slice_obj.element.dataset.slice, { mute : true }); - } -}; - -var _unmuteSlice = function (slice_obj, submit) { - var play_position_top_hook_element = slice_obj.element.firstElementChild.nextElementSibling, - play_position_bottom_hook_element = slice_obj.element.lastElementChild; - - slice_obj.mute = false; - - _fasSendIntrumentsInfos(false); - - play_position_top_hook_element.style.borderTopColor = _slice_type_color[slice_obj.type]; - play_position_bottom_hook_element.style.borderBottomColor = _slice_type_color[slice_obj.type]; - - if (submit) { - _submitSliceUpdate(2, slice_obj.element.dataset.slice, { mute : false }); - } -}; - -var _sliceAuxClickFn = function (play_position_marker_element) { - return function (ev) { - ev.preventDefault(); - - var play_position_marker = _play_position_markers[parseInt(play_position_marker_element.dataset.slice, 10)]; - - if (ev.button === 1) { - _unfocus(); - - if (play_position_marker.mute) { - _unmuteSlice(play_position_marker, true); - } else { - _muteSlice(play_position_marker, true); - } - } - }; -}; - -var _showSliceSettingsMenuFn = function (play_position_marker_element, dialog) { - return function (ev) { - ev.preventDefault(); - - var play_position_marker = _play_position_markers[parseInt(play_position_marker_element.dataset.slice, 10)], - - mute_obj = { icon: "fs-mute-icon", tooltip: "Mute", on_click: function () { - _muteSlice(play_position_marker, true); - } }, - unmute_obj = { icon: "fs-unmute-icon", tooltip: "Unmute", on_click: function () { - _unmuteSlice(play_position_marker, true); - } }, - fx_obj = { icon: "fs-fx-icon", tooltip: "FX", on_click: function () { - _changeSliceType(play_position_marker, 1, true); - } }, - synth_obj = { icon: "fs-fas-icon", tooltip: "Synth", on_click: function () { - _changeSliceType(play_position_marker, 0, true); - } }, - obj, - type_obj; - - if (play_position_marker.type === 0 || play_position_marker.type === undefined) { - type_obj = fx_obj; - } else { - type_obj = synth_obj; - } - - if (!play_position_marker.mute) { - obj = mute_obj; - } else { - obj = unmute_obj; - } - - var target_window = null; - if (dialog) { - var detached_window = WUI_Dialog.getDetachedDialog(dialog); - if (detached_window) { - target_window = detached_window; - } - } - - WUI_CircularMenu.create( - { - x: ev.clientX, - y: ev.clientY, - - rx: 32, - ry: 32, - - item_width: 32, - item_height: 32, - - window: target_window - }, - [ - obj, - { icon: "fs-gear-icon", tooltip: "Settings", on_click: function () { - _updateSliceSettingsDialog(play_position_marker, true); - }}, - //type_obj, - { icon: "fs-cross-45-icon", tooltip: "Delete", on_click: function () { - _removePlayPositionMarker(play_position_marker_element.dataset.slice, true, true); - }} - ]); - - return false; - } -} - -var _changeSliceType = function (slice_obj, type, submit) { - var play_position_top_hook_element = slice_obj.element.firstElementChild.nextElementSibling, - play_position_bottom_hook_element = slice_obj.element.lastElementChild; - - slice_obj.type = type; - if (!slice_obj.mute) { - play_position_top_hook_element.style.borderTopColor = _slice_type_color[type]; - play_position_bottom_hook_element.style.borderBottomColor = _slice_type_color[type]; - } else { - if (slice_obj.type === 1) { - play_position_top_hook_element.style.borderTopColor = "#550000"; - play_position_bottom_hook_element.style.borderBottomColor = "#550000"; - } else { - play_position_top_hook_element.style.borderTopColor = "#555555"; - play_position_bottom_hook_element.style.borderBottomColor = "#555555"; - } - } - - _createFasSettingsContent(); - - if (submit) { - _submitSliceUpdate(4, slice_obj.element.dataset.slice, { type : type }); - } -}; - -var _addPlayPositionMarker = function (x, shift, mute, output_channel, slice_type, instrument_settings, submit) { - var slice_divs_obj = _domCreatePlayPositionMarker(_canvas, _canvas_height), - play_position_marker_element = slice_divs_obj.slice_div, - play_position_marker_id = _play_position_markers.length, - - play_position_marker, - - play_position_top_hook_element = play_position_marker_element.firstElementChild.nextElementSibling, - play_position_bottom_hook_element = play_position_marker_element.lastElementChild, - - local_session_marker, - - i = 0, - - is_mute = mute; - - if (x === undefined) { - x = 0; - } - - if (!is_mute) { - is_mute = false; - } - - if (!slice_type) { - slice_type = 0; - } - - play_position_top_hook_element.style.borderTopColor = _slice_type_color[slice_type]; - play_position_bottom_hook_element.style.borderBottomColor = _slice_type_color[slice_type]; - - play_position_marker_element.dataset.slice = play_position_marker_id; - - _play_position_markers.push({ - element: play_position_marker_element, - out_txt_div: slice_divs_obj.out_div, - x: x, - mute: is_mute, - min: 0, - max: 100, - shift: 0, - frame_increment: 0, - output_channel: 1, - instrument_type: 0, - instrument_params: { - p0: 0, - p1: 0, - p2: 0, - p3: 0, - p4: 0 - }, - //instrument_muted: 0, - dialog_id: -1, - y: 0, - height: _canvas_height, - id: play_position_marker_id, - type: slice_type, - midi_out: { - device_uids: [], - custom_midi_message: "", - custom_midi_message_fn: null, - enabled: false - }, - osc_out: false, - audio_out: true, - custom_midi_codemirror: null - }); - - play_position_marker = _play_position_markers[play_position_marker_id]; - - if (is_mute) { - _muteSlice(play_position_marker); - } - - if (_local_session_settings["markers"]) { - local_session_marker = _local_session_settings.markers[play_position_marker_id]; - if (local_session_marker) { - if (local_session_marker["midi_out"]) { - play_position_marker.midi_out.device_uids = local_session_marker["midi_out"].device_uids; - play_position_marker.midi_out.custom_midi_message = local_session_marker["midi_out"].custom_midi_message; - play_position_marker.midi_out.enabled = local_session_marker["midi_out"].enabled; - - _compileMarkerMIDIData(play_position_marker); - } - - if (local_session_marker["osc_out"]) { - play_position_marker.osc_out = local_session_marker["osc_out"]; - } - - if (local_session_marker["audio_out"]) { - play_position_marker.audio_out = local_session_marker["audio_out"]; - } - } - } - - if (output_channel !== undefined) { - play_position_marker.output_channel = output_channel; - } - - if (instrument_settings !== undefined) { - if ('type' in instrument_settings) { - play_position_marker.instrument_type = instrument_settings.type; - } - - if ('p0' in instrument_settings) { - play_position_marker.instrument_params.p0 = instrument_settings.p0; - } - - if ('p1' in instrument_settings) { - play_position_marker.instrument_params.p1 = instrument_settings.p1; - } - - if ('p2' in instrument_settings) { - play_position_marker.instrument_params.p2 = instrument_settings.p2; - } - - if ('p3' in instrument_settings) { - play_position_marker.instrument_params.p3 = instrument_settings.p3; - } - - if ('p4' in instrument_settings) { - play_position_marker.instrument_params.p4 = instrument_settings.p4; - } - - if ('muted' in instrument_settings) { - play_position_marker.mute = instrument_settings.muted; - } - } - - _computeOutputChannels(); - - if (shift !== undefined) { - play_position_marker.shift = shift; - } - - _setPlayPosition(play_position_marker_id, play_position_marker.x, 0); - - WUI.draggable(play_position_marker.out_txt_div, function (element, x, y) { - _setSlicePositionFromAbsolute(element.dataset.slice, x, y); - }, false, play_position_marker_element); - WUI.lockDraggable(play_position_marker.out_txt_div, 'y'); - WUI.draggable(play_position_top_hook_element, function (element, x, y) { - _setSlicePositionFromAbsolute(element.dataset.slice, x, y); - }, false, play_position_marker_element); - WUI.lockDraggable(play_position_top_hook_element, 'y'); - WUI.draggable(play_position_bottom_hook_element, function (element, x, y) { - _setSlicePositionFromAbsolute(element.dataset.slice, x, y); - }, false, play_position_marker_element); - WUI.lockDraggable(play_position_bottom_hook_element, 'y'); - - WUI.draggable(play_position_marker_element, function (element, x, y) { - _setSlicePositionFromAbsolute(element.dataset.slice, x, y); - }); - WUI.lockDraggable(play_position_marker_element, 'y'); - - play_position_marker_element.addEventListener('dblclick', function (ev) { - _updateSliceSettingsDialog(play_position_marker, true); - }); - - play_position_marker_element.addEventListener('contextmenu', _showSliceSettingsMenuFn(play_position_marker_element), false); - - play_position_marker_element.addEventListener('auxclick', _sliceAuxClickFn(play_position_marker_element), false); - - _createMarkerSettings(play_position_marker); - - if (submit) { - _submitAddSlice(x, shift, mute); - } - - _updateSliceChnVisibility(); - - _fasSendIntrumentsInfos(true); - - return play_position_marker; -}; -/* jslint browser: true */ - - -/*********************************************************** - Fields. -************************************************************/ - -var _midi_dialog_id = "fs_midi_output", - _midi_dialog, - - _current_midi_out_slice = null, - - _midi_code_change_timeout = null, - _midi_code_change_ms = 1500, - - _midi_codemirror_instance, - _midi_codemirror_instance_detached, - - _midi_wrapped_code_change, - _midi_wrapped_code_change_detached, - - _midi_access = null, - - _midi_devices = { - input: {}, - output: {}, - - i_total_active: 0, - o_total_active: 0 - }, - - _dead_notes_buffer, - - _mpe_instrument, - - _midi_notes = [], - - _midi_device_uid = 0; - -/*********************************************************** - Functions. -************************************************************/ - -var _midiCodeChange = function () { - if (_current_midi_out_slice !== null) { - _current_midi_out_slice.midi_out.custom_midi_message = _midi_codemirror_instance.getValue(); - - _compileMarkerMIDIData(_current_midi_out_slice); - - _saveMarkersSettings(); - } -}; - -var _midiBindCodeChangeEvent = function () { - CodeMirror.on(_midi_codemirror_instance, 'change', _midi_wrapped_code_change); - - if (_midi_codemirror_instance_detached) { - CodeMirror.on(_midi_codemirror_instance_detached, 'change', _midi_wrapped_code_change_detached); - } -}; - -var _midiUnbindCodeChangeEvent = function () { - CodeMirror.off(_midi_codemirror_instance, 'change', _midi_wrapped_code_change); - - if (_midi_codemirror_instance_detached) { - CodeMirror.off(_midi_codemirror_instance_detached, 'change', _midi_wrapped_code_change_detached); - } -}; - -var _midiDialogInit = function () { - var custom_message_area = document.createElement("textarea"), - - midi_editor_div = document.getElementById("fs_midi_editor"), - - cm_element; - - custom_message_area.className = "fs-textarea"; - custom_message_area.style.border = "1px solid #111111"; - - _midi_dialog = WUI_Dialog.create(_midi_dialog_id, { - title: "MIDI Out Editor", - - width: "800px", - height: "360px", - min_height: "80px", - - halign: "center", - valign: "center", - - open: false, - - status_bar: true, - detachable: true, - draggable: true, - resizable: true, - minimizable: true, - - status_bar_content: "", - - on_open: function () { - _midi_codemirror_instance.refresh(); - }, - - on_detach: function (new_window) { - _midiUnbindCodeChangeEvent(); - - var midi_editor_div = new_window.document.getElementById("fs_midi_editor"), - textarea = document.createElement("textarea"), - cm_element; - - new_window.document.head.innerHTML += ''; - - textarea.className = "fs-textarea"; - textarea.style.border = "1px solid #111111"; - - midi_editor_div.innerHTML = ""; - - midi_editor_div.appendChild(textarea); - - _midi_codemirror_instance_detached = CodeMirror.fromTextArea(textarea, { - mode: "text/javascript", - styleActiveLine: true, - lineNumbers: true, - lineWrapping: true, - theme: ((_code_editor_theme === null) ? "seti" : _code_editor_theme), - matchBrackets: true, - scrollbarStyle: "native" - }); - - cm_element = _midi_codemirror_instance_detached.getWrapperElement(); - cm_element.style = "font-size: 12pt"; - - _midi_codemirror_instance_detached.setValue(_midi_codemirror_instance.getValue()); - - _midi_codemirror_instance_detached.refresh(); - - //CodeMirror.on(_midi_codemirror_instance_detached, 'change', _midi_wrapped_code_change_detached); - - _midiBindCodeChangeEvent(); - }, - - on_close: function () { - _midi_codemirror_instance_detached = null; - - _midiUnbindCodeChangeEvent(); - }, - - header_btn: [ - { - title: "Help", - on_click: function () { - window.open(_documentation_link + "midi/"); - }, - class_name: "fs-help-icon" - } - ] - }); - - midi_editor_div.appendChild(custom_message_area); - - _midi_codemirror_instance = CodeMirror.fromTextArea(custom_message_area, { - mode: "text/javascript", - styleActiveLine: true, - lineNumbers: true, - lineWrapping: true, - theme: ((_code_editor_theme === null) ? "seti" : _code_editor_theme), - matchBrackets: true, - scrollbarStyle: "native" - }); - - cm_element = _midi_codemirror_instance.getWrapperElement(); - cm_element.style = "font-size: 12pt"; - - _midi_wrapped_code_change = function () { - clearTimeout(_midi_code_change_timeout); - _midi_code_change_timeout = setTimeout(_midiCodeChange, _midi_code_change_ms); - }; - - _midi_wrapped_code_change_detached = function () { - _midiUnbindCodeChangeEvent(); - - _midi_codemirror_instance.setValue(_midi_codemirror_instance_detached.getValue()); - - _midiBindCodeChangeEvent(); - - clearTimeout(_midi_code_change_timeout); - _midi_code_change_timeout = setTimeout(_midiCodeChange, _midi_code_change_ms, _midi_codemirror_instance_detached.getValue()); - }; - - _midiBindCodeChangeEvent(); - - _midiUpdateSlices(); - - var detached_window = WUI_Dialog.getDetachedDialog(_midi_dialog); - if (detached_window) { - _midiUpdateSlices(detached_window.document); - } -}; - -var _midiSelectSlice = function (slice) { - if (_current_midi_out_slice === slice || slice === null) { - return; - } - - _current_midi_out_slice = slice; - - _midiUnbindCodeChangeEvent(); - - _midi_codemirror_instance.setValue(slice.midi_out.custom_midi_message); - - if (_midi_codemirror_instance_detached) { - _midi_codemirror_instance_detached.setValue(slice.midi_out.custom_midi_message); - } - - _midiUpdateSlices(); - - var detached_window = WUI_Dialog.getDetachedDialog(_midi_dialog); - if (detached_window) { - _midiUpdateSlices(detached_window.document); - } - - _midiBindCodeChangeEvent(); - - _midiCodeChange(); -}; - -var _midiChangeSourceCb = function (slice) { - return function (e) { - var elem = e.target; - - _midiSelectSlice(slice); - - if (elem.parentElement !== null) { - elem.parentElement.childNodes.forEach(function (item) { - item.classList.remove("fs-midi-selected"); - }); - - elem.classList.add("fs-midi-selected"); - } - }; -}; - -var _midiUpdateSlices = function (doc) { - if (!doc) { - doc = document; - } - - var i = 0, - midi_editor_outputs = doc.getElementById("fs_midi_outputs"), - slice, - - selected_output = _current_midi_out_slice, - - output_name_div; - - midi_editor_outputs.innerHTML = ""; - - _current_midi_out_slice = null; - - for (i = 0; i < _play_position_markers.length; i += 1) { - slice = _play_position_markers[i]; - - if (slice.midi_out.enabled) { - output_name_div = doc.createElement("div"); - output_name_div.className = "fs-pjs-input"; - output_name_div.innerHTML = "Instrument " + i; - - if (selected_output === slice) { - output_name_div.classList.add("fs-midi-selected"); - - _current_midi_out_slice = slice; - } - - midi_editor_outputs.appendChild(output_name_div); - - output_name_div.addEventListener("click", _midiChangeSourceCb(slice)); - } - } -}; - -var _midiDeviceIOUpdate = function () { - var key; - - _midi_devices.i_total_active = 0; - _midi_devices.o_total_active = 0; - - for (key in _midi_devices.input) { - if(_midi_devices.input[key].enabled) { - _midi_devices.i_total_active += 1; - } - } - - for (key in _midi_devices.output) { - if(_midi_devices.output[key].enabled) { - _midi_devices.o_total_active += 1; - } - } -}; - -var _loadMIDISettings = function (midi_settings_json) { - var midi_settings_obj, - key, midi_device; - - if (!midi_settings_json) { - return null; - } - - try { - midi_settings_obj = JSON.parse(midi_settings_json); - - for(key in midi_settings_obj.i) { - midi_device = midi_settings_obj.i[key]; - - _midi_devices.input[key] = { - enabled: midi_device.enabled - }; - } - - for(key in midi_settings_obj.o) { - midi_device = midi_settings_obj.o[key]; - - _midi_devices.output[key] = { - enabled: midi_device.enabled - }; - } - - _midiDeviceIOUpdate(); - } catch (e) { - _notification('_loadMIDISettings JSON message parsing failed : ' + e); - } -}; - -var _saveMIDISettings = function () { - var key, midi_device, midi_settings_obj = { i: {}, o: {}}; - - for(key in _midi_devices.input) { - midi_device = _midi_devices.input[key]; - - midi_settings_obj.i[key] = { - enabled: midi_device.enabled - }; - } - - for(key in _midi_devices.output) { - midi_device = _midi_devices.output[key]; - - midi_settings_obj.o[key] = { - enabled: midi_device.enabled - }; - } - - _local_session_settings['midi_settings'] = JSON.stringify(midi_settings_obj); - _saveLocalSessionSettings(); -}; - -var _MIDIDeviceCheckboxChange = function () { - var midi_device = _midi_devices[this.dataset.type][this.dataset.did], - - midi_enabled_ck_id = "fs_midi_settings_ck_" + midi_device.iid; - - midi_device.enabled = this.checked; - - _saveMIDISettings(); - - if (this.checked) { - document.getElementById(midi_enabled_ck_id).setAttribute("checked", "checked"); - document.getElementById(midi_enabled_ck_id + '_status').style.color = 'lightgreen'; - } else { - document.getElementById(midi_enabled_ck_id).removeAttribute("checked"); - document.getElementById(midi_enabled_ck_id + '_status').style.color = 'grey'; - } - - _midiDeviceIOUpdate(); -}; - -var _resetMIDIDevice = function () { - var i = 0; - - for (i = 0; i < 16; i += 1) { - _midiSendAllActive([0xB0 + i, 0x7B, 0x0, 0xB0 + i, 0x78, 0x0]); - } -}; - -var _addMIDIDevice = function (midi, io_type) { - var midi_element = document.createElement("div"), - midi_enabled_ck_id = "fs_midi_settings_ck_" + _midi_device_uid, - midi_settings_in_element = document.getElementById("fs_midi_in_container"), - midi_settings_out_element = document.getElementById("fs_midi_out_container"), - midi_device_enabled = (io_type === "output"), - midi_device_enabled_ck = (io_type === "output" ? "checked" : ""), - - tmp_element = null, - - i = 0, - - detached_dialog = WUI_Dialog.getDetachedDialog(_midi_settings_dialog), - detached_dialog_midi_in_element = null, - detached_dialog_midi_out_element = null; - - // settings were loaded previously - if (midi.id in _midi_devices[io_type]) { - midi_device_enabled = _midi_devices[io_type][midi.id].enabled; - if (midi_device_enabled) { - midi_device_enabled_ck = "checked"; - } - - if (_midi_devices[io_type][midi.id].connected) { - return; - } - } - - midi_element.classList.add("fs-midi-settings-device"); - - midi_element.innerHTML = [ - '
    ', - midi.name, - '
    ', - ' '].join(''); - - if (io_type === "input") { - midi_settings_in_element.appendChild(midi_element); - } else { - midi_settings_out_element.appendChild(midi_element); - } - - _midi_devices[io_type][midi.id] = { - obj: midi, - type: midi.type, - id: midi.id, - manufacturer: midi.manufacturer, - name: midi.name, - version: midi.version, - iid: _midi_device_uid, - enabled: midi_device_enabled, - element: midi_element, - detached_element: null, - connected: true - }; - - document.getElementById(midi_enabled_ck_id).addEventListener("change", _MIDIDeviceCheckboxChange); - - if (detached_dialog) { - tmp_element = midi_element.cloneNode(true); - - if (io_type === "input") { - detached_dialog_midi_in_element = detached_dialog.document.getElementById("fs_midi_in_container"); - detached_dialog_midi_in_element.appendChild(tmp_element); - } else { - detached_dialog_midi_out_element = detached_dialog.document.getElementById("fs_midi_out_container"); - detached_dialog_midi_out_element.appendChild(tmp_element); - } - - _midi_devices[io_type][midi.id].detached_element = tmp_element; - } - - if (io_type === "input") { - midi.onmidimessage = _onMIDIMessage; - } - - _midi_device_uid += 1; - - _midiDeviceIOUpdate(); - - // re-initialize MIDI device, default program change - for (i = 0; i < 16; i += 1) { - _midiSendToDevice([0xC0 + i, 0x00], "output", midi.id); - } - - _rebuildMarkersMIDIDevices(); -}; - -var _deleteMIDIDevice = function (id, type) { - var midi_device = _midi_devices[type][id], - - detached_dialog = WUI_Dialog.getDetachedDialog(_midi_settings_dialog), - - nodes; - - if (!midi_device) { - console.log("_deleteMIDIDevice: MIDI Device ", id, " does not exist."); - return; - } - - midi_device.element.parentElement.removeChild(midi_device.element); - - if (detached_dialog) { - nodes = detached_dialog.document.querySelectorAll("[data-did='" + id + "']"); - - if (nodes.length > 0) { - nodes[0].parentElement.parentElement.parentElement.removeChild(nodes[0].parentElement.parentElement); - } - } - - delete _midi_devices[type][id]; - - _midiDeviceIOUpdate(); - - _rebuildMarkersMIDIDevices(); -}; - -var _getMIDIDevices = function (io_type) { - return _midi_devices[io_type]; -}; - -var _onMIDIAccessChange = function (connection_event) { - var device = connection_event.port; - - if (device.type !== "input" && device.type !== "output") { - return; - } - - if (device.state === "connected") { - _addMIDIDevice(device, device.type); - } else if (device.state === "disconnected") { - _deleteMIDIDevice(device.id, device.type); - } -}; - -var _midiSendAllActive = function (msg_arr) { - var key, midi_device; - - for(key in _midi_devices.output) { - midi_device = _midi_devices.output[key]; - - if (midi_device.enabled) { - if (midi_device.obj) { - midi_device.obj.send(msg_arr); - } - } - } -}; - -var _midiSendToDevice = function (msg_arr, device_type, device_uids) { - var i = 0, - midi_device; - - for (i = 0; i < device_uids.length; i += 1) { - midi_device = _midi_devices[device_type][device_uids[i]]; - - if (!midi_device) { - return; - } - - if (midi_device.enabled) { - try { - midi_device.obj.send(msg_arr); - } catch (e) { - console.log("_midiSendToDevice: Tried to send invalid MIDI data.", e); - } - } - } -}; - -var _getMIDINoteObj = function (chn, note) { - if (!_midi_notes[chn][note]) { - _midi_notes[chn][note] = { on: false, chn: 0 }; - } - - return _midi_notes[chn][note]; -}; - -var _midiDataOut = function (pixels_data) { - if (_midi_devices.o_total_active === 0 && pixels_data.length > 1) { - return; - } - - var data_length, - buffer = [], - data, - prev_data, - osc = null, - l = 0, pl = 0, - r = 0, pr = 0, - pb = 0, pa = 0, - y = 0, - li = 0, - ri = 1, - bi = 2, - ai = 3, - i = 0, - k = 0, - j = 0, - b = 0, - a = 0, - chn, - - midi_chn_data_index = _output_channels, - - notes, - - inv_full_brightness = 1, - - midi_volume, - midi_panning, - - midi_message = [], - - midi_bend = 0, - - midi_obj, - - midi_note = 0, - midi_note_fractional = 0, - midi_note_obj; - - if (!_audio_infos.float_data) { - inv_full_brightness = 1 / 255.0; - } - - for (i = 0; i < _output_channels; i += 1) { - buffer.push(new _synth_data_array(_canvas_height_mul4)); - } - - for (k = 0; k < midi_chn_data_index; k += 1) { - data = pixels_data[k]; - prev_data = _prev_midi_data[k]; - data_length = data.length - 1; - - y = _oscillators.length - 1; - - for (i = 0; i < data_length; i += 4) { - l = data[i + li]; - r = data[i + ri]; - b = data[i + bi]; - a = data[i + ai]; - - pl = prev_data[i + li]; - pr = prev_data[i + ri]; - pb = prev_data[i + bi]; - pa = prev_data[i + ai]; - - osc = _oscillators[y]; - - midi_obj = pixels_data[midi_chn_data_index + k]; - - if (!midi_obj) { - y -= 1; - continue; - } - - if (l > 0 || r > 0) { - l *= inv_full_brightness; - r *= inv_full_brightness; - b *= inv_full_brightness; - a *= inv_full_brightness; - - midi_note_fractional = _hzToMIDINote(osc.freq); - midi_note = Math.min(Math.round(midi_note_fractional), 127); - - midi_note_obj = _getMIDINoteObj(k, midi_note_fractional); - - midi_volume = Math.min(Math.round((l + r) / 2 * 127), 127); - - if ((pl <= 0 || pr <= 0) /*&& !midi_note_obj.on*/) { - chn = 0; - notes = Infinity; - - for (j = 0; j < 16; j += 1) { - if (_midi_notes[j].notes === 0) { - chn = j; - break; - } - - if (_midi_notes[j].notes < notes) { - chn = j; - notes = _midi_notes[chn].notes; - } - } - - if (midi_note_obj.on) { - _midi_notes[midi_note_obj.chn].notes -= 1; - - midi_message = [0x80 + midi_note_obj.chn, midi_note, 127]; - - if (midi_obj.custom_midi_message_fn) { - midi_message = midi_message.concat(midi_obj.custom_midi_message_fn("off", l, r, b, a, midi_note_obj.chn).off); - } - - _midiSendToDevice(midi_message, "output", midi_obj.device_uids); - } - - _midi_notes[chn].notes += 1; - - midi_bend = _getMIDIBend(osc.freq, midi_note); - - midi_panning = _getMIDIPan(l, r); - - midi_message = []; - - if (midi_obj.custom_midi_message_fn) { - midi_message = midi_obj.custom_midi_message_fn("on", l, r, b, a, chn).on; - } - - if (midi_message) { - midi_message = midi_message.concat([0xE0 + chn, midi_bend & 0x7F, (midi_bend >> 7), - 0xB0 + chn, 0x0A, midi_panning, - 0x90 + chn, midi_note, midi_volume]); - - _midiSendToDevice(midi_message, "output", midi_obj.device_uids); - - midi_note_obj.on = true; - midi_note_obj.chn = chn; - } - } - - if (pl !== l || pr !== r || pb !== b || pa !== a) { - if (midi_note_obj.on && _midi_notes[midi_note_obj.chn].notes <= 1) { - if (midi_obj.custom_midi_message_fn) { - midi_message = midi_obj.custom_midi_message_fn("change", l, r, b, a, midi_note_obj.chn).change; - - _midiSendToDevice(midi_message, "output", midi_obj.device_uids); - } - } - } - } else { - if (pl > 0 || pr > 0) { - midi_note_fractional = _hzToMIDINote(osc.freq); - midi_note = Math.min(Math.round(midi_note_fractional), 127); - - midi_note_obj = _getMIDINoteObj(k, midi_note_fractional); - - if (midi_note_obj.on) { - _midi_notes[midi_note_obj.chn].notes -= 1; - - midi_message = [0x80 + midi_note_obj.chn, midi_note, 127]; - - if (midi_obj.custom_midi_message_fn) { - midi_message = midi_message.concat(midi_obj.custom_midi_message_fn("off", l, r, b, a, midi_note_obj.chn).off); - } - - if (midi_message) { - _midiSendToDevice(midi_message, "output", midi_obj.device_uids); - - midi_note_obj.on = false; - } - } - } - } - - y -= 1; - } - } - - for (i = 0; i < _output_channels; i += 1) { - _prev_midi_data[i] = pixels_data[i]; - } - - _midi_data = buffer; -}; - -var _MIDInotesCleanup = function () { - var key, value, i = 0, v; - - // cleanup all MIDI dead notes - for (key in _dead_notes_buffer) { - v = _dead_notes_buffer[key]; - - _keyboard.data.splice(v.i, _keyboard.data_components); - - delete _keyboard.pressed[v.k]; - - for (key in _keyboard.pressed) { - value = _keyboard.pressed[key]; - - if (value.id > v.i) { - value.id -= _keyboard.data_components; - - if (_dead_notes_buffer[key]) { - _dead_notes_buffer[key].i = value.id; - } - } - } - } -}; - -var _MIDInotesUpdate = function (date) { - var et = 0, key, v; - - _dead_notes_buffer = {}; - - // update notes time - for (key in _keyboard.pressed) { - v = _keyboard.pressed[key]; - - // check if we need to cleanup the note - if (v.noteoff) { - et = date - v.noteoff_time; - - if (et >= _keyboard.note_lifetime) { - _dead_notes_buffer[key] = { - k: key, - i: v.id - }; - - // dead notes will be cleaned up before the next frame begin (see _MIDInotesCleanup) - - continue; - } - } - - et = date - v.time; - - _keyboard.data[v.id + 2] = et / 1000; - } - - _keyboard.polyphony = _keyboard.data.length / _keyboard.data_components - 1; -} - -// general MIDI messages processing -var _onMIDIMessage = function (midi_message) { - var i = 0, midi_device = _midi_devices.input[this.id]; - - if (!midi_device.enabled) { - return; - } - - _mpe_instrument.processMidiMessage(midi_message.data); - - WUI_RangeSlider.submitMIDIMessage(midi_message); -}; - -var _fasRetrigger = function (frq) { - var j = 0; - if (_fasEnabled()) { - for (j = 0; j < _play_position_markers.length; j += 1) { - var slice = _play_position_markers[j]; - // re-trigger on FAS side for physical modelling / wavetable (because this type of synthesis require it) - if ((slice.instrument_type === 5 || (slice.instrument_type === 6 && slice.instrument_params.p0))) { - var osc = _hzToOscillator(frq, _audio_infos.base_freq, _audio_infos.octaves, _audio_infos.h); - _fasNotify(_FAS_ACTION, { type: 1, note: osc, instrument: j }); - } - } - } -}; - -// MPE/MIDI messages (provided by mpejs) -var _mpeMIDIMessage = function (notes) { - var i = 0, - data, note, key, chn, d; - - for (i = 0; i < notes.length; i += 1) { - data = notes[i]; - chn = data.channel - 1; - - key = chn + "_" + data.noteNumber; - note = _keyboard.pressed[key]; - - if (data.noteState !== 0) { - if (!data.frq) { - data.frq = _frequencyFromNoteNumber(data.noteNumber); - } - - if (note) { // note update / re-trigger - if (note.noteoff) { // re-trigger - d = _keyboard.pressed[key]; - - d.time = Date.now(); - d.noteoff = false; - d.noteoff_time = 0; - d.pressure = data.pressure; - d.timbre = data.timbre; - d.pitchBend = data.pitchBend; - d.noteOnVelocity = data.noteOnVelocity; - d.frq = data.frq; - - _keyboard.data[note.id] = note.frq; - _keyboard.data[note.id + 1] = note.noteOnVelocity; - _keyboard.data[note.id + 2] = note.time; - _keyboard.data[note.id + 4] = note.pitchBend; - _keyboard.data[note.id + 5] = note.timbre; - _keyboard.data[note.id + 6] = note.pressure; - - _fasRetrigger(data.frq); - } else { // note update - if (note.pitchBend === data.pitchBend && - note.timbre === data.timbre && - note.pressure === data.pressure) { - continue; - } - - note.pitchBend = data.pitchBend; - note.timbre = data.timbre; - note.pressure = data.pressure; - - //_keyboard.data[note.id + 2] = Date.now(); - _keyboard.data[note.id + 4] = note.pitchBend; - _keyboard.data[note.id + 5] = note.timbre; - _keyboard.data[note.id + 6] = note.pressure; - } - } else { // note-on - if (_keyboard.data.length > _keyboard.data_length) { - _notification("Maximum polyphony reached. Please increase maximum polyphony."); - } - - // remove the empty data - _keyboard.data.splice(_keyboard.data.length - _keyboard.data_components, _keyboard.data_components); - - note = { - frq: data.frq, - noteOnVelocity: data.noteOnVelocity, - pitchBend: data.pitchBend, - timbre: data.timbre, - pressure: data.pressure, - time: Date.now(), - channel: chn, - noteoff: false, - noteoff_time: 0, - id: _keyboard.data.length - }; - - _keyboard.data.push(note.frq, note.noteOnVelocity, note.time, note.channel, note.pitchBend, note.timbre, note.pressure, 0); - _keyboard.data.push(0, 0, 0, 0, 0, 0, 0, 0); // fill up with empty data ("stop point") - - _keyboard.pressed[key] = note; - } - } else { // note-off - if (note) { - _keyboard.data[note.id + 7] = data.noteOffVelocity; - - _pkeyboard.data[note.channel * 3] = note.frq; - _pkeyboard.data[note.channel * 3 + 1] = note.noteOnVelocity; - _pkeyboard.data[note.channel * 3 + 2] = note.time; - - note.noteoff_time = Date.now(); - note.noteoff = true; - - _useProgram(_program); - _setUniforms(_gl, "vec", _program, "pKey", _pkeyboard.data, _pkeyboard.data_components); - - //_fasRetrigger(note.frq); - } - } - } -}; - -var _midiAccessSuccess = function (midi_access) { - _midi_access = midi_access; - - _mpe_instrument = mpe({ - log: null, - normalize: true - }); - - _mpe_instrument.subscribe(_mpeMIDIMessage); - - _midi_access.inputs.forEach( - function (midi_in) { - _addMIDIDevice(midi_in, midi_in.type); - } - ); - - _midi_access.outputs.forEach( - function (midi_out) { - _addMIDIDevice(midi_out, midi_out.type); - } - ); - - _midi_access.onstatechange = _onMIDIAccessChange; -}; - -var _midiAccessFailure = function (msg) { - var midi_settings_element = document.getElementById(_midi_settings_dialog_id).lastElementChild; - - midi_settings_element.innerHTML = "
    Failed to get WebMIDI API access : " + msg + "
    "; -}; - -/*********************************************************** - Init. -************************************************************/ - -var _midiInit = function () { - var i = 0, - midi_settings_element = document.getElementById(_midi_settings_dialog_id).lastElementChild; - - _keyboard.data = [0, 0, 0, 0, 0, 0, 0, 0]; - - if (_webMIDISupport()) { - for (i = 0; i < 16; i += 1) { - _midi_notes[i] = { notes: 0 }; - } - - navigator.requestMIDIAccess().then(_midiAccessSuccess, _midiAccessFailure); - } else { - midi_settings_element.style.paddingTop = "12px"; - midi_settings_element.innerHTML = _webmidi_support_msg; - } - - _midiDialogInit(); -}/* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _fas = { - address: "127.0.0.1:3003", - enabled: false, - status: null, - worker: new Worker("dist/worker/fas.min.js"), - fps: 60 - }, - - _fas_address_input = document.getElementById("fs_fas_address"), - - _fas_paused = false, - - _FAS_ENABLE = 0, - _FAS_DISABLE = 1, - _FAS_BANK_INFOS = 2, - _FAS_SYNTH_INFOS = 3, - _FAS_FRAME = 4, - _FAS_CHN_INFOS = 5, - _FAS_CHN_FX_INFOS = 6, - _FAS_ACTION = 7, - _FAS_INSTRUMENT_INFOS = 8; - -/*********************************************************** - Functions. -************************************************************/ - -var _fasNotify = function (cmd, data) { - _fas.worker.postMessage({ - cmd: cmd, - arg: data - }); -}; - -var _fasNotifyFast = function (cmd, data) { - if (_fas_paused) { - return; - } - - var output_data_buffer = [], - i = 0; - - for (i = 0; i < data.length; i += 1) { - output_data_buffer.push(data[i].buffer); - } - - _fas.worker.postMessage({ - cmd: cmd, - arg: output_data_buffer, - float: _audio_infos.float_data - }, output_data_buffer); -}; - -var _fasUnpause = function () { - if (!_fas.enabled) { - return; - } - - _fas_paused = false; - - _fasNotify(_FAS_ACTION, { type: 5 }); -}; - -var _fasPause = function () { - if (!_fas.enabled || _fas_paused) { - return; - } - - _fas_paused = true; - - _fasNotify(_FAS_ACTION, { type: 4 }); -}; - -var _fasEnable = function () { - _fasNotify(_FAS_ENABLE, { - address: _fas.address, - //audio_infos: _audio_infos, - //chn_settings: _chn_settings - }); - - _fas.enabled = true; - - var fs_fas_element = document.getElementById("fs_fas_status"); - fs_fas_element.style.display = ""; -}; - -var _fasDisable = function () { - _fasNotify(_FAS_DISABLE); - - _fas_stream_load.textContent = ""; - _fas_stream_latency.textContent = ""; - - _fas.enabled = false; - - var fs_fas_element = document.getElementById("fs_fas_status"); - fs_fas_element.style.display = "none"; -}; - -var _fasEnabled = function () { - return _fas.enabled; -}; - -var _fasStatus = function (status) { - var fs_fas_element = document.getElementById("fs_fas_status"); - - if (status) { - fs_fas_element.classList.add("fs-server-status-on"); - } else { - fs_fas_element.classList.remove("fs-server-status-on"); - } - - _fas.status = status; -}; - -var _fasSendIntrumentsInfos = function (send_parameters) { - var i = 0; - for (i = 0; i < _play_position_markers.length; i += 1) { - var slice = _play_position_markers[i]; - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 0, value: slice.instrument_type }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 1, value: slice.mute }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 2, value: slice.output_channel - 1 }); - - if (send_parameters) { - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 3, value: slice.instrument_params.p0 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 4, value: slice.instrument_params.p1 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 5, value: slice.instrument_params.p2 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 6, value: slice.instrument_params.p3 }); - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: i, target: 7, value: slice.instrument_params.p4 }); - } - } - - _fasNotify(_FAS_INSTRUMENT_INFOS, { instrument: _play_position_markers.length, target: 0, value: 15 }); // FAS_VOID -}; - -var _fasSendChannelsInfos = function () { - var i = 0, j = 0, k = 0; - for (i = 0; i < _chn_settings.length; i += 1) { - if (_chn_settings[i].muted === undefined) { - _chn_settings[i].muted = 0; - } - - if (_chn_settings[i].chn_output === undefined) { - _chn_settings[i].chn_output = 0; - } - - _fasNotify(_FAS_CHN_INFOS, { target: 0, chn: i, value: _chn_settings[i].muted }); - _fasNotify(_FAS_CHN_INFOS, { target: 1, chn: i, value: _chn_settings[i].chn_output }); - } -}; - -var _fasSendAll = function () { - _fasNotify(_FAS_BANK_INFOS, _audio_infos); - _fasNotify(_FAS_SYNTH_INFOS, { target: 0, value: _fas.fps }); - _fasNotify(_FAS_SYNTH_INFOS, { target: 1, value: _audio_infos.gain }); - - var i = 0, j = 0, k = 0; - for (i = 0; i < _chn_settings.length; i += 1) { - if (_chn_settings[i].muted === undefined) { - _chn_settings[i].muted = 0; - } - - if (_chn_settings[i].chn_output === undefined) { - _chn_settings[i].chn_output = 0; - } - - _fasNotify(_FAS_CHN_INFOS, { target: 0, chn: i, value: _chn_settings[i].muted }); - _fasNotify(_FAS_CHN_INFOS, { target: 1, chn: i, value: _chn_settings[i].chn_output }); - /* - for (j = 0; j < _chn_settings[i].osc.length; j += 2) { - var value = _chn_settings[i].osc[j + 1]; - _fasNotify(_FAS_CHN_INFOS, { target: _chn_settings[i].osc[j], chn: i, value: value }); - } - */ - - var slot_index = 0; - for (j = 0; j < _chn_settings[i].efx.length; j += 3) { - _fasNotify(_FAS_CHN_FX_INFOS, { chn: i, slot: slot_index, target: 0, value: _chn_settings[i].efx[j] }); - _fasNotify(_FAS_CHN_FX_INFOS, { chn: i, slot: slot_index, target: 1, value: _chn_settings[i].efx[j + 1] }); - - var fx_settings = _chn_settings[i].efx[j + 2]; - for (k = 0; k < fx_settings.length; k += 1) { - _fasNotify(_FAS_CHN_FX_INFOS, { chn: i, slot: slot_index, target: 2 + k, value: fx_settings[k] }); - } - - slot_index += 1; - } - _fasNotify(_FAS_CHN_FX_INFOS, { chn: i, slot: slot_index, target: 0, value: -1 }); - } - - _fasSendIntrumentsInfos(true); -}; - -/*********************************************************** - Init. -************************************************************/ - -var _fasInit = function () { - var address = localStorage.getItem("fas-address"); - if (address !== null) { - _fas.address = address; - } - - _fas_address_input.value = _fas.address; - - _fas_address_input.addEventListener('input', function () { - _fas.address = this.value; - - localStorage.setItem("fas-address", _fas.address); - - if (_fas.enabled) { - _fasDisable(); - _fasEnable(); - } - }); - - _fas.worker.addEventListener("message", function (m) { - var data = m.data; - - if (data.status === "open") { - _fasStatus(true); - - _fasSendAll(); - } else if (data.status === "streaminfos") { - _fas_stream_load.textContent = data.load + "%"; - _fas_stream_latency.textContent = _truncateDecimals(data.latency, 1) + "ms"; - } else if (data.status === "error") { - _fasStatus(false); - - _fas_stream_load.textContent = ""; - _fas_stream_latency.textContent = ""; - } else if (data.status === "close") { - _fasStatus(false); - - _fas_stream_load.textContent = ""; - _fas_stream_latency.textContent = ""; - - _notification("Audio server connection lost, trying again in ~5s.", 2500); - } - }, false); -}; -/* jslint browser: true */ - -// UX helper / guide / tour - -/*********************************************************** - Fields. -************************************************************/ - -var _ux_helper_overlay = new PlainOverlay(), - _ux_helper_anchor = null, - _ux_helper_scenario = null, - _ux_helper_end_infos = { - content: "Not enough informations ?", - sub_content: [ - 'The help dialog (?) has many useful helpers / informations', - 'Fragment full documentation is available here', - 'Fragment forum is available here' - ] - }, - _ux_helper_quickstart_scenario = [ - { - style: "font-size: 19pt; color: white; margin: 4px; padding: 4px; text-align: center;", - content: "Quickstart", - sub_content: [ - "This will show you the interface layout and how to start playing sounds" - ] - }, - { - content: "The top bar contain various informations including master gain level", - target: "fs_top_panel", - leaderline: { - endSocket: "bottom" - } - }, - { - content: "Canvas (generated visual content)", - target: "canvas_container", - point_anchor: true - }, - { - content: "Main toolbar", - target: "fs_middle_toolbar", - point_anchor: true - }, - { - content: "Data / inputs (images, videos, etc.)", - sub_content: [ - "Content must be added with the import dialog (last toolbar button)" - ], - target: "fs_input_panel", - point_anchor: true - }, - { - content: "Fragment / GLSL code editor", - sub_content: [ - 'This is where you type GLSL code to produce visual / sound content' - ], - target: "fs_code", - point_anchor: true - }, - { - content: "Right click here then click on the + button to add a slice", - sub_content: [ - "Slices capture the pixels data which is sent to the sound synthesis engine in real-time." - ], - target: "canvas_container", - point_anchor: true - }, - { - content: "Click here to unpause and hear the 440hz tone", - target: "fs_tb_pause", - point_anchor: true - }, - _ux_helper_end_infos - ], - _ux_helper_ui_scenario = [ - { - style: "font-size: 19pt; color: white; margin: 4px; padding: 4px; text-align: center;", - content: "Data server status", - sub_content: [ - "Collaborative features are managed by this server" - ], - target: "fs_sync_status", - leaderline: { - endSocket: "bottom" - } - }, - { - content: "Chat and settings server status", - sub_content: [ - "" - ], - target: "fs_server_status", - leaderline: { - endSocket: "bottom" - } - }, - { - content: "Audio server status", - sub_content: [ - "" - ], - target: "fs_fas_status", - leaderline: { - endSocket: "bottom" - } - }, - { - content: "Username", - sub_content: [ - "Can be edited by a left click" - ], - target: "fs_user_name", - leaderline: { - endSocket: "bottom" - } - }, - { - content: "Global clock", - sub_content: [ - "Accessible in the fragment shader as globalTime" - ], - target: "fs_time_infos", - point_anchor: true - }, - { - content: "Master gain level", - target: "mst_slider", - leaderline: { - endSocket: "bottom" - } - }, - { - content: "Canvas (accelerated drawing surface)", - sub_content: [ - "Right click to add a slice / instrument", - "Double click to open slices / instruments panel" - ], - target: "canvas_container", - point_anchor: true - }, - { - content: "Main toolbar", - target: "fs_middle_toolbar", - point_anchor: true - }, - { - content: "Data / inputs container (images, videos, etc.)", - sub_content: [ - "Textures accessible as iInput0, iInput1 etc. (in order of appearance)", - "Inputs can be reordered in realtime by a drag and drop", - "Click on an input to open its action menu", - "Some data / inputs have a shortcut accessible by a right click" - ], - target: "fs_input_panel", - point_anchor: true - }, - { - content: "Workspaces pane", - sub_content: [ - "The session workspace with main code, library and examples" - ], - target: "fs_explorer", - point_anchor: true - }, - { - content: "Fragment / GLSL code editor", - sub_content: [ - "This is where you type to produce visual / sound content" - ], - target: "fs_code", - point_anchor: true - }, - _ux_helper_end_infos - ], - _ux_helper_step = -1, - _ux_helper_current_line = null, - _ux_helper_help_overlay = null; - -/*********************************************************** - Functions. -************************************************************/ - -var _startUXHelper = function (scenario) { - _ux_helper_scenario = scenario; - - WUI_Dialog.closeAll(); - - // create anchor points - _ux_helper_anchor = document.createElement("div"); - - // create overlay and attach anchor on top - _ux_helper_overlay.setOptions({ - face: _ux_helper_anchor, - style: { - backgroundColor: 'rgba(16, 16, 16, 0.3)', - cursor: 'pointer', - zIndex: 9000 - } - }); - - _ux_helper_overlay.show(); - - _nextUXHelper(); - - document.getElementsByClassName("plainoverlay")[0].addEventListener("click", _nextUXHelper); - - _ux_helper_help_overlay = document.createElement("div"); - _ux_helper_help_overlay.style = "position: absolute; bottom: 14px; width: 100%; text-align: center; font-size: 13pt; z-index: 900000; color: white"; - _ux_helper_help_overlay.innerHTML = "click to continue"; - document.body.appendChild(_ux_helper_help_overlay); -}; - -var _stopUXHelper = function () { - _ux_helper_overlay.hide(); - - if (_ux_helper_current_line) { - _ux_helper_current_line.remove(); - _ux_helper_current_line = null; - } - - _ux_helper_step = -1; - - document.body.removeChild(_ux_helper_help_overlay); - - _ux_helper_scenario = null; -}; - -var _nextUXHelper = function () { - if (_ux_helper_overlay.state === PlainOverlay.STATE_HIDDEN || - _ux_helper_overlay.state === PlainOverlay.STATE_HIDING) { - return; - } - - if (_ux_helper_current_line) { - _ux_helper_current_line.remove(); - _ux_helper_current_line = null; - } - - _ux_helper_step += 1; - - if (_ux_helper_step >= _ux_helper_scenario.length) { - _stopUXHelper(); - - return; - } - - var step_data = _ux_helper_scenario[_ux_helper_step]; - - if (step_data.style) { - _ux_helper_anchor.style = step_data.style; - } - - if (step_data.content) { - _ux_helper_anchor.innerHTML = step_data.content; - } - - if (step_data.sub_content) { - var sub_content_html = step_data.sub_content.map(function (content, index) { - if (index) { - return '
    ' + content + '
    '; - } else { - return '
    ' + content + '
    '; - } - }).join(""); - _ux_helper_anchor.innerHTML += sub_content_html; - } - - if (step_data.target) { - var leaderline_options = { - //animOptions: { duration: 400, timing: [0.58, 0, 0.42, 1] }, - startPlug: 'behind', - endPlug: 'arrow1', - startPlugSize: 1, - endPlugSize: 1, - color: 'white', - endPlugColor: 'white'/*, - startSocketGravity: 400, - gradient: { - startColor: 'white', - endColor: 'green' - }*/ - }; - - if (step_data.leaderline) { - if (step_data.leaderline.endSocket) { - leaderline_options["endSocket"] = step_data.leaderline.endSocket; - } - } - - var target_elem = document.getElementById(step_data.target); - if (step_data.point_anchor) { - target_elem = LeaderLine.pointAnchor(target_elem); - } - - _ux_helper_current_line = new LeaderLine(_ux_helper_anchor, target_elem, leaderline_options); - } -}; - -/*********************************************************** - Init. -************************************************************/ - -document.body.addEventListener("keydown", function (evt) { - if (evt.key === 'Escape' && _ux_helper_step !== -1) { - _stopUXHelper(); - } -}); - -document.getElementById("fs_ux_tour").addEventListener("click", function () { - _ux_helper_ui_scenario[_ux_helper_ui_scenario.length - 2].target = _current_code_editor.container.id; - _startUXHelper(_ux_helper_ui_scenario); -}); -/* -document.getElementById("fs_quickstart_tour").addEventListener("click", function () { - _startUXHelper(_ux_helper_quickstart_scenario); -}); -*//* jslint browser: true */ - -/*********************************************************** - Fields. -************************************************************/ - -var _osc = { - address: "127.0.0.1:8081", - in: false, - out: false, - enabled: false, - status: null, - worker: new Worker("dist/worker/osc.min.js"), - inputs: [], - queue: [], - queue_timeout: null - }, - - _osc_address_input = document.getElementById("fs_osc_inout_address"), - - _OSC_ENABLE = 0, - _OSC_DISABLE = 1, - _OSC_FRAME_DATA = 2; - -/*********************************************************** - Functions. -************************************************************/ - -var _oscNotify = function (cmd, data) { - _osc.worker.postMessage({ - cmd: cmd, - arg: data - }); -}; - -var _oscNotifyFast = function (cmd, data) { - var output_data_buffer = [], - i = 0; - - for (i = 0; i < data.length; i += 1) { - output_data_buffer.push(data[i].buffer); - } - - _osc.worker.postMessage({ - cmd: cmd, - arg: output_data_buffer, - float: _audio_infos.float_data, - base_frequency: _audio_infos.base_freq, - octave_length: _audio_infos.h / _audio_infos.octaves, - channels: _output_channels - }, output_data_buffer); -}; - -var _oscEnable = function () { - if (!_osc.enabled) { - _oscNotify(_OSC_ENABLE, { - address: _osc.address, - }); - - _osc.enabled = true; - } -}; - -var _oscDisable = function () { - if (!_osc.in && !_osc.out) { - _oscNotify(_OSC_DISABLE); - - _osc.enabled = false; - } -}; - -var _oscEnabled = function () { - return _osc.enabled; -}; - -var _processOSCInputsQueue = function () { - var i = 0, - - name; - - if (!_program) { - clearTimeout(_osc.queue_timeout); - _osc.queue_timeout = setTimeout(_processOSCInputsQueue, 2000); - - return; - } - - _useProgram(_program); - for (i = 0; i < _osc.queue.length; i += 1) { - name = _osc.queue[i]; - - _setUniforms(_gl, _osc.inputs[name].type, _program, name, _osc.inputs[name].data); - } - - _osc.queue = []; -}; - -/*********************************************************** - Init. -************************************************************/ - -var _oscInit = function () { - var address = localStorage.getItem("osc-address"), - input; - if (address !== null) { - _osc.address = address; - } - - _osc_address_input.value = _osc.address; - - _osc_address_input.addEventListener('input', function () { - _osc.address = this.value; - - localStorage.setItem("osc-address", _osc.address); - - if (_oscEnabled) { - _oscDisable(); - _oscEnable(); - } - }); - - _osc.worker.addEventListener("message", function (m) { - var data = m.data, i; - - if (data.status === "data") { - if (!_osc.inputs.hasOwnProperty(data.osc_input.name)) { - if (!data.osc_input.i) { - data.osc_input.i = data.osc_input.v.length; - } - - _osc.inputs[data.osc_input.name] = { - comps: undefined, - type: "float", - count: data.osc_input.i, - data: [] - }; - - _glsl_compilation(); - } - - if (data.osc_input.hasOwnProperty("i")) { - _osc.inputs[data.osc_input.name].data[data.osc_input.i] = data.osc_input.v; - - for (i = 0; i < _osc.inputs[data.osc_input.name].data.length; i += 1) { - if (_osc.inputs[data.osc_input.name].data[i] === undefined) { - _osc.inputs[data.osc_input.name].data[i] = 0; - } - } - - if (_osc.inputs[data.osc_input.name].count != _osc.inputs[data.osc_input.name].data.length) { - _osc.inputs[data.osc_input.name].count = _osc.inputs[data.osc_input.name].data.length; - _glsl_compilation(); - } - } else if (data.osc_input.hasOwnProperty("v")) { - _osc.inputs[data.osc_input.name].data = data.osc_input.v; - } - - if (!_program) { - _osc.queue.push(data.osc_input.name); - - clearTimeout(_osc.queue_timeout); - _osc.queue_timeout = setTimeout(_processOSCInputsQueue, 2000); - } else { - _useProgram(_program); - _setUniforms(_gl, _osc.inputs[data.osc_input.name].type, _program, data.osc_input.name, _osc.inputs[data.osc_input.name].data); - } - } else if (data.status === "videoData") { - input = _fragment_input_data[Math.round(data.videoData[0])]; - if (input.type === 3) { - if (data.videoData[1]) { - input.playrate = data.videoData[1]; - input.video_elem.playbackRate = data.videoData[1]; - } else if (data.videoData[2]) { - input.videostart = data.videoData[2]; - } else if (data.videoData[3]) { - input.videoend = data.videoData[3]; - } else if (data.videoData[4]) { - input.video_elem.currentTime = input.video_elem.duration * data.videoData[4]; - } - } - } else if (data.status === "clear") { // clear up OSC set uniforms - _osc.inputs = []; - _osc.queue = []; - - _glsl_compilation(); - } else if (data.status === "ready") { - _notification("OSC: Connected to " + _osc.address, 2500); - } else if (data.status === "error") { - console.log(data.error); - - _notification("OSC: Connection error!", 2500); - } else if (data.status === "close") { - _notification("OSC connection lost, trying again in ~5s!", 2500); - } - }, false); -}; - - /*********************************************************** - Functions. - ************************************************************/ - - var _initializePBO = function () { - if (_gl2) { - if (_pbo) { - _gl.deleteBuffer(_pbo); - } - - _pbo = _gl.createBuffer(); - _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, _pbo); - if (_gl2 && _EXT_color_buffer_float) { - _pbo_size = 1 * _canvas.height * 4 * 4; - } else { - _pbo_size = 1 * _canvas.height * 4; - } - _gl.bufferData(_gl.PIXEL_PACK_BUFFER, _pbo_size, _gl.STATIC_READ); - - _gl.bindBuffer(_gl.PIXEL_PACK_BUFFER, null); - } - }; - - var _saveLocalSessionSettings = function () { - var session_name = _getSessionName(); - - return function () { - try { - localStorage.setItem(session_name, JSON.stringify(_local_session_settings)); - } catch (e) { - _notification("Can't save session local settings due to localStorage error. (local storage is likely full)"); - } - }; - }(); - - var _loadLocalSessionSettings = function () { - // setup user last settings for this session if any - if (_local_session_settings) { - _local_session_settings = JSON.parse(_local_session_settings); - if ('gain' in _local_session_settings) { - _volume = _local_session_settings.gain; - - WUI_RangeSlider.setValue("mst_slider", _volume, true); - } - - if ('midi_settings' in _local_session_settings) { - _loadMIDISettings(_local_session_settings.midi_settings); - } - - if ('chn_settings' in _local_session_settings) { - _chn_settings = _local_session_settings.chn_settings; - } - } else { - _local_session_settings = { - gain: _volume, - chn_settings: [{ osc: [], efx: [], muted: 0, output_chn: 0 }], - markers: [], - code_editors: [] - }; - - _code_editors.forEach(function (code_editor) { - _local_session_settings.code_editors.push({ marks: [] }) - }); - } - }; - - var _updateScore = function (update_obj, update) { - var prev_base_freq = _audio_infos.base_freq, - prev_octave = _audio_infos.octaves, - - base_freq = _audio_infos.base_freq, - octave = _audio_infos.octaves, - - prev_width = _canvas_width, - prev_height = _canvas_height; - - if (update_obj["base_freq"] !== undefined) { - base_freq = update_obj.base_freq; - } - - if (update_obj["octave"] !== undefined) { - octave = update_obj.octave; - } - - if (update_obj.height) { - _canvas_height = update_obj.height; - _canvas.height = _canvas_height; - _canvas.style.height = _canvas_height + 'px'; - _canvas_height_mul4 = _canvas_height * 4; - - _record_canvas.height = _canvas_height; - _record_slice_image = _record_canvas_ctx.createImageData(1, _canvas_height); - - _vaxis_infos.style.height = _canvas_height + "px"; - - _temp_data = new _synth_data_array(_canvas_height_mul4); - _allocateFramesData(); - - _gl.viewport(0, 0, _canvas.width, _canvas.height); - - _updatePlayMarkersHeight(_canvas_height); - - _initializePBO(); - } - - if (update_obj.width) { - _canvas_width = update_obj.width; - _canvas.width = _canvas_width; - _canvas.style.width = _canvas_width + 'px'; - - _record_canvas.width = _canvas_width; - - _gl.viewport(0, 0, _canvas.width, _canvas.height); - - _initializePBO(); - } - - if (update_obj.width || update_obj.height) { - _canvasInputDimensionsUpdate(update_obj.width, update_obj.height); - _pjsDimensionsUpdate(update_obj.width, update_obj.height); - } - - _pjsCompileAll(); - - // detached canvas - _detached_canvas_buffer = new Uint8Array(_canvas_width * _canvas_height * 4); - if (_detached_canvas_ctx) { - _detached_canvas.width = _canvas_width; - _detached_canvas.height = _canvas_height; - _detached_canvas_image_data = _detached_canvas_ctx.createImageData(_canvas_width, _canvas_height); - } - // - - _generateOscillatorSet(_canvas_height, base_freq, octave); - - _compile(); - - _updateWorkView(); - - _updateAllPlayPosition(); - - _fasSendAll(); - - //_fasNotify(_FAS_BANK_INFOS, _audio_infos); - - WUI_RangeSlider.setValue("fs_score_width_input", _canvas_width); - WUI_RangeSlider.setValue("fs_score_height_input", _canvas_height); - WUI_RangeSlider.setValue("fs_score_octave_input", octave); - WUI_RangeSlider.setValue("fs_score_base_input", base_freq); - - if (update) { - _shareSettingsUpd([ - prev_width, _canvas_width, - prev_height, _canvas_height, - prev_octave, octave, - prev_base_freq, base_freq - ]); - } - - _buildMainFBO(); - - _buildFeedback(); - }; - - /*********************************************************** - Init. - ************************************************************/ - - if (localStorage.getItem("fs-show-toolbar-title") === null) { - localStorage.setItem("fs-show-toolbar-title", true); - } - - document.getElementById("copy_year").innerHTML = new Date().getFullYear(); - - _record_opts.f = _record_opts.default; - - if (!_username) { - _username = "Anonymous"; - } - - _user_name_element.innerHTML = _username; - _username_input.value = _username; - - //_canvas_width = _getElementOffset(_canvas_container).width; - - _render_width = _canvas_width; - - _canvas.width = _render_width; - _canvas.height = _render_height; - - _canvas.style.width = _canvas_width + 'px'; - _canvas.style.height = _canvas_height + 'px'; - - _canvas_container.appendChild(_canvas); - - /* - _canvas_container.addEventListener("click", function () { - var childs = _canvas_container.children; - var i = 0; - for (i = 0; i < childs.length; i++) { - if (childs[i].nodeName === "CANVAS") { - childs[i].dispatchEvent(new UIEvent('click')); - } - } - }); - */ - - _record_canvas.width = _canvas_width; - _record_canvas.height = _canvas_height; - - _record_slice_image = _record_canvas_ctx.createImageData(1, _canvas_height); - - _vaxis_infos.style.height = _canvas_height + "px"; - - // CodeMirror / code editors - if (!_code_editor_theme) { - _code_editor_theme = "seti"; - } - - _changeEditorsTheme(_code_editor_theme); - - if (!_code_editor_font_size) { - _code_editor_font_size = "S"; - } - - _changeEditorsFontSize(_code_editor_font_size); - - var _onEditorGutterClick = function (code_editor) { - return function (cm, n) { - var info = cm.lineInfo(n), - lineHandle = cm.getLineHandle(n), - - i = 0; - - if (info.gutterMarkers) { - for (i = 0; i < code_editor.marks.length; i += 1) { - if (cm.getLineNumber(code_editor.marks[i]) === n) { - code_editor.marks.splice(i, 1); - break; - } - } - } else { - code_editor.marks.push(lineHandle); - - _addMarkDeleteEvent(code_editor, lineHandle); - } - - cm.setGutterMarker(n, "fs-mark", info.gutterMarkers ? null : _getNewMark()); - - _saveEditorMarks(code_editor)(); - - _updateOutline(code_editor.index); - }; - } - - var _onEditorChanges = function (code_editor) { - return function (instance, changes) { - if (code_editor.collaborative) { - _shareCodeEditorChanges(code_editor, changes); - } else if (code_editor.index === 1) { - localStorage.setItem("fs-user-library", code_editor.editor.getValue()); - } - }; - }; - - var _onEditorChange = function (code_editor) { - return function (instance, change_obj) { - clearTimeout(_compile_timer); - _compile_timer = setTimeout(_compile, 500); - - if (code_editor.marks) { - clearTimeout(_update_marks_timer); - _update_marks_timer = setTimeout(_updateMarks(code_editor), 2000); - } - }; - }; - - _code_editors.forEach(function (code_editor) { - code_editor.editor = new CodeMirror(code_editor.container, _code_editor_settings); - - var ce_instance = code_editor.editor; - - ce_instance.setValue(code_editor.default_value); - - CodeMirror.on(ce_instance, 'change', _onEditorChange(code_editor)); - - CodeMirror.on(ce_instance, 'changes', _onEditorChanges(code_editor)); - - if (code_editor.marks) { - CodeMirror.on(ce_instance, "gutterClick", _onEditorGutterClick(code_editor)); - } - }); - - // WebGL 2 check & init - _gl = _canvas.getContext("webgl2", _webgl_opts) || _canvas.getContext("experimental-webgl2", _webgl_opts); - if (_gl) { - _gl2 = true; - - _wgl_support_element.innerHTML = "Supported"; - _wgl_support_element.style.color = "#00ff00"; - - _OES_texture_float_linear = _gl.getExtension("OES_texture_float_linear"); - _EXT_color_buffer_float = _gl.getExtension("EXT_color_buffer_float"); - - _initializePBO(); - - if (_OES_texture_float_linear) { - _wgl_lfloat_support_element.innerHTML = "Supported"; - _wgl_lfloat_support_element.style.color = "#00ff00"; - } else { - _wgl_lfloat_support_element.innerHTML = "Not supported"; - _wgl_lfloat_support_element.style.color = "#ff0000"; - } - - if (_EXT_color_buffer_float) { - _audio_infos.float_data = true; - - _synth_data_array = Float32Array; - - _read_pixels_format = _gl.FLOAT; - - _wgl_float_support_element.innerHTML = "Supported"; - _wgl_float_support_element.style.color = "#00ff00"; - } else { - _read_pixels_format = _gl.UNSIGNED_BYTE; - - _wgl_float_support_element.innerHTML = "Not supported (8-bit)"; - _wgl_float_support_element.style.color = "#ff0000"; - } - } - - if (!_gl) { - _fail("The WebGL API is not available, please try with a WebGL ready browser.", true); - - return; - } - - // compute default polyphony max based on GPU capabilities - _webgl.max_fragment_uniform_vector = _gl.getParameter(_gl.MAX_FRAGMENT_UNIFORM_VECTORS); - - _keyboard.uniform_vectors = _webgl.max_fragment_uniform_vector - _free_uniform_vectors; - - _keyboard.data_length = _keyboard.uniform_vectors * _keyboard.data_components; - _keyboard.polyphony_max = _keyboard.uniform_vectors; - - if (_keyboard.uniform_vectors <= 16) { - _keyboard.uniform_vectors = _webgl.max_fragment_uniform_vector - (_free_uniform_vectors / 2); - - // still not? default to 8, all devices should be fine nowaday with 32 uniform vectors - if (_keyboard.uniform_vectors <= 16) { - _keyboard.data_length = 16 * _keyboard.data_components; - _keyboard.polyphony_max = 16; - } else { - _keyboard.data_length = _keyboard.uniform_vectors * _keyboard.data_components; - _keyboard.polyphony_max = _keyboard.uniform_vectors; - } - } - - _buildScreenAlignedQuad(); - - _gl.viewport(0, 0, _canvas.width, _canvas.height); - - _gl.pixelStorei(_gl.UNPACK_FLIP_Y_WEBGL, true); - - _compile(); - - _initWorkspace(); - - _loadLocalSessionSettings(); - - _loadEditorsMarks(); - - _allocateFramesData(); - - _fasInit(); - - _uiInit(); - - _pjsInit(); - - _midiInit(); - - _oscInit(); - - _initNetwork(); - -/* jslint browser: true */ - -_user_name_element.addEventListener('click', function (e) { - WUI_Dialog.open("fs_username_dialog"); - }); - -_username_input.addEventListener("change", function () { - var user_name = this.value; - - if (user_name === null) { - return; - } - - if (user_name === "") { - user_name = "Anonymous"; - } - - _user_name_element.innerHTML = user_name; - - localStorage.setItem('fs-user-name', user_name); -}); - -_canvas.addEventListener('contextmenu', function(ev) { - ev.preventDefault(); - - WUI_CircularMenu.create( - { - x: _mx, - y: _my, - - rx: 0, - ry: 0, - - item_width: 32, - item_height: 32 - }, - [ - { - icon: "fs-plus-icon", - tooltip: "add slice (middle click = muted, right click = muted with settings)", - on_click: function () { - _addPlayPositionMarker(_cx, 0, false, 1, 0, { synthesis_type: 0 }, true); - }, - on_middle_click: function () { - _addPlayPositionMarker(_cx, 0, true, 1, 0, { synthesis_type: 0 }, true); - }, - on_right_click: function () { - var slice = _addPlayPositionMarker(_cx, 0, true, 1, 0, { synthesis_type: 0 }, true); - - _updateSliceSettingsDialog(slice, true); - } - } - ]); - - return false; - }, false); - - -_canvas.addEventListener('dblclick', function() { - WUI_Dialog.open(_slices_dialog); -}); -/* -// slow -_canvas.addEventListener('dblclick', function() { - var child_window = null, - screen_left = typeof window.screenLeft !== "undefined" ? window.screenLeft : screen.left, - screen_top = typeof window.screenTop !== "undefined" ? window.screenTop : screen.top, - dbc = _canvas.getBoundingClientRect(), - title = "", - child_gl; - - child_window = window.open("", title, [ - "toolbar=no", - "location=no", - "directories=no", - "status=no", - "menubar=no", - "scrollbars=yes", - "resizable=yes", - "width=" + dbc.width, - "height=" + dbc.height, - "top=" + (dbc.top + screen_top), - "left=" + (dbc.left + screen_left)].join(',')); - - child_window.document.open(); - child_window.document.write(['', - '', - '' + title + '', - '', - '', - '', - '', - ''].join('')); - child_window.document.close(); - - _detached_canvas = child_window.document.body.firstElementChild; - - _detached_canvas.width = _canvas.width; - _detached_canvas.height = _canvas.height; - - _detached_canvas_ctx = _detached_canvas.getContext('2d'); - - _detached_canvas_image_data = _detached_canvas_ctx.createImageData(_canvas_width, _canvas_height); - - child_window.addEventListener("beforeunload", function () { - _detached_canvas = null; - _detached_canvas_ctx = null; - _detached_canvas_image_data = null; - }); -}); -*/ - -document.addEventListener('mousedown', function (e) { - var e = e || window.event, - - canvas_offset = _getElementOffset(_canvas); - - _cnmx = 1. - (e.pageX - canvas_offset.left - 1) / _canvas_width; - _cnmy = 1. - (e.pageY - canvas_offset.top) / _canvas_height; - - _mouse_btn = e.which; -}); - -document.getElementById("fs_select_editor_themes").addEventListener('change', function (e) { - var theme = e.target.value; - - if (theme === "default") { - theme = "seti"; - } - - _changeEditorsTheme(theme); -}); - -document.getElementById("fs_select_editor_fontsize").addEventListener('change', function (e) { - var size = e.target.value; - - _changeEditorsFontSize(size); -}); - -document.getElementById("fs_show_quickstart").addEventListener('click', function (e) { - WUI_Dialog.open(_quickstart_dialog); -}); - -document.getElementById("fs_remove_comments").addEventListener('click', function (e) { - var input_code = _current_code_editor.editor.getValue(), - output_code = input_code; - - output_code = output_code.replace(/(\/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+\/)|(\/\/.*)/g, ""); - - _current_code_editor.editor.setValue(output_code); - - _compile(); -}); - -document.getElementById("fs_remove_spaces").addEventListener('click', function (e) { - var input_code = _current_code_editor.editor.getValue(), - output_code = input_code; - - output_code = output_code.replace(/^\s{2,}$/gm, ""); - - _current_code_editor.editor.setValue(output_code); - - _compile(); -}); - -document.getElementById("fs_center_all_dialogs").addEventListener('click', WUI_Dialog.centerAll); - -document.addEventListener('mouseup', function (e) { - _mouse_btn = 0; - - _canvasInputPaintStop(); - - // controller - //_hit_curr = null; -}); - -document.addEventListener('mousemove', function (e) { - var e = e || window.event, - - canvas_offset; - - if (e.target === _canvas || (e.target && e.target.dataset.group === "canvas")) { - canvas_offset = _getElementOffset(_canvas); - - _cx = e.pageX; - _cy = e.pageY - canvas_offset.top; - - _cx = (_cx - canvas_offset.left - 1); - - _hover_freq = _getFrequency(_cy); - - if (_hover_freq !== null && (_cx >= 0 && _cx < _canvas_width)) { - if (_xyf_grid) { - if (_haxis_infos.style.display !== "block" || - _vaxis_infos.style.display !== "block") { - _haxis_infos.style.display = "block"; - _vaxis_infos.style.display = "block"; - } - - _haxis_infos.firstElementChild.textContent = _cy; - _haxis_infos.lastElementChild.style.left = e.pageX + "px"; - _haxis_infos.lastElementChild.textContent = _truncateDecimals(_hover_freq + "", 2) + "Hz"; - _vaxis_infos.firstElementChild.textContent = _cx; - - _haxis_infos.style.top = _cy + "px"; - _vaxis_infos.style.left = e.pageX + "px"; - } else { - _xy_infos.textContent = "x " + _cx + " y " + _cy; - _hz_infos.textContent = " " + _truncateDecimals(_hover_freq + "", 2) + "Hz"; - } - } else { - if (_xyf_grid) { - if (_haxis_infos.style.display !== "none" || - _vaxis_infos.style.display !== "none") { - _haxis_infos.style.display = "none"; - _vaxis_infos.style.display = "none"; - } - } else { - _xy_infos.textContent = ""; - _hz_infos.textContent = ""; - } - } - - if (_mouse_btn === _LEFT_MOUSE_BTN) { - _nmx = 1. - _cx / _canvas_width; - _nmy = 1. - _cy / _canvas_height; - } - } else if (e.target === _record_canvas) { - if (_mouse_btn === _LEFT_MOUSE_BTN) { - canvas_offset = _getElementOffset(_record_canvas); - - var cx = e.pageX; - var cy = e.pageY - canvas_offset.top; - - cx = (cx - canvas_offset.left - 1); - - _record_position = cx; - } - } else { - if (_xyf_grid) { - if (_haxis_infos.style.display !== "none" || - _vaxis_infos.style.display !== "none") { - _haxis_infos.style.display = "none"; - _vaxis_infos.style.display = "none"; - } - } else { - _xy_infos.textContent = ""; - _hz_infos.textContent = ""; - } - } - -// if (e.target === _workspace_nodegraph_canvas) { -// _lgraph_canvas.processMouseMove(e); -// } else { - _pjsMouseMoveEvent(); -// } - - _mx = e.pageX; - _my = e.pageY; - - _canvasInputPaint(e); - - - }); - -var _onWindowResize = function () { - _updateAllPlayPosition(); - - _updateWorkView(); - - _c_helper.width = window.innerWidth; - _c_helper.height = window.innerHeight; -}; - -ResizeThrottler.initialize([_onWindowResize]); - -_red_curtain_element.classList.add("fs-open-red-curtain"); -_red_curtain_element.addEventListener("transitionend", function () { - _red_curtain_element.parentElement.removeChild(_red_curtain_element); - }, false); - - if (localStorage.getItem('fs-audio') !== "true") { - _fasDisable(); - } - - _buildFeedback(); - - _initDb("fs" + _getSessionName()); - - _clipboard = new Clipboard(".fs-documentation-keyword"); - - _initOutline(); - - //_startUXHelper(_ux_helper_quickstart_scenario); -}; - - FragmentSynth({}); -} +var WUI_Form=new function(){"use strict";var e={},t="wui-form",n="wui-form-main-group",i="wui-form-sub-group",r="wui-form-sub-group-div",o="wui-form-tn",a="wui-form-sm",s="wui-form-md",l="wui-form-xl",c="wui-form-align-right",u="wui-form-inline",d={width:"auto",on_change:null},h="wui_form_item_",f="wui_form_std_item_",p={checkbox:"input",text:"input",color:"input",date:"input","datetime-local":"input",email:"input",file:"input",hidden:"input",image:"input",month:"input",number:"input",radio:"input",range:"input",reset:"input",search:"input",submit:"input",tel:"input",time:"input",url:"input",week:"input",password:"input"},g=["button","datalist","input","label","legend","meter","select","textarea","checkbox","text","color","date","datetime-local","email","file","hidden","image","month","number","radio","range","reset","search","submit","tel","time","url","week","password"],m=["WUI_RangeSlider","WUI_Input","WUI_DropDown"],v=function(e){window.WUI_Reporting&&"undefined"!=typeof console&&console.log(e)},C=function(e,t){var n;for(n in e)e.hasOwnProperty(n)&&t.setAttribute(n,e[n])},y=function(t,n,i){return function(r){r.target?t.name?"checkbox"===t.type?(e[t.wid].sitems[t.name].value=r.target.checked,t.value=r.target.checked):(e[t.wid].sitems[t.name].value=r.target.value,t.value=r.target.value):"checkbox"===t.type?t.value=r.target.checked:t.value=r.target.value:(t.name&&(e[t.wid].sitems[t.name].value=r),t.value=r),void 0!==n&&n(t.value,r,t),void 0!==i&&i(t.value,r,t)}},A=function(t,n,d,v,I,_,b){var w,x,E,S,k,T,L,M,O,P,R,D,N,B=0,F=0,U=_;for(void 0===n?(w=document.createElement("div"),E=document.createElement("legend")):(w=document.createElement("fieldset"),(E=document.createElement("legend")).innerHTML=n),void 0!==d&&C(d,w),w.appendChild(E),B=0;B100&&(n.style.zIndex=100));for(i=r.dialog.parentElement;null!==i;)i.classList.contains(d)&&(i.style.zIndex=101),i=i.parentElement;e.style.zIndex=101}},P=function(e){var t=document.createElement("div");return t.className="wui-dialog-modal",t.addEventListener("click",function(t){t.preventDefault(),M(e,!0,!0,!0)}),t.style.zIndex=16777270,t},R=function(e){var n=t[e.id].opts,i=e.parentElement.offsetWidth,r=e.parentElement.offsetHeight,o=e.offsetWidth,a=e.offsetHeight;"center"===n.halign?e.style.left=Math.round((i-o)/2+n.left)+"px":"right"===n.halign?e.style.left=i-o+n.left+"px":e.style.left=n.left+"px","center"===n.valign?e.style.top=Math.round((r-a)/2+n.top)+"px":"bottom"===n.valign?e.style.top=r-a+n.top+"px":e.style.top=n.top+"px"},D=function(e,n){var i=t[n.id],r=i.resize_handler;i.dialog!==n&&D(i.header_minimaxi_btn,i.dialog),e.classList.toggle(v),e.classList.toggle(C),n.classList.toggle(m),n.classList.contains(m)?(n.style.borderStyle="solid",n.style.borderColor="#808080",n.style.borderWidth="1px"):(n.style.borderStyle="",n.style.borderColor="",n.style.borderWidth=""),r&&r.classList.toggle(A),i.status_bar&&i.status_bar.classList.toggle(A)},N=function(e){null===c&&(c=setTimeout(function(){c=null;var n,i,r,o,a,s,l=document;if(e)for(n=(l=e.document).getElementsByClassName(h),s=0;s0?r.style.height=e.innerHeight-32+"px":r.style.height=e.innerHeight+"px",a=r.getBoundingClientRect(),i.opts.on_resize&&i.opts.on_resize(a.width,a.height);else for(n=l.getElementsByClassName(h),s=0;s0?r.style.height=o.offsetHeight-64+"px":r.style.height=o.offsetHeight-32+"px",R(o),a=r.getBoundingClientRect(),(i=t[o.id]).opts.on_resize&&i.opts.on_resize(a.width,a.height)},125))},B=function(e,t){var n,i;do{if(1==e.nodeType&&e.eventListenerList)for(n in e.eventListenerList)if("length"!==n&&e.eventListenerList.hasOwnProperty(n))for(i=0;i","",""+h+"",s,"",'',"",""].join("")),f.document.close(),f.document.body.appendChild(e.children[1].cloneNode(!0));var g=e.getElementsByClassName(E);if(g.length>0){var v=g[0].cloneNode(!0);v.classList.add(A),f.document.body.appendChild(v)}f.addEventListener("keyup",function(t){27===t.keyCode&&M(e,!0,!0,!0)},!1),f.addEventListener("resize",function(){N(f)},!1),f.addEventListener("beforeunload",function(){M(e,!0,!0,!0),c.modal_element&&document.body.removeChild(c.modal_element)},!1),u.push(f)},U=function(e){e.preventDefault();var t=e.target,n=null;t.classList.contains(p)?(n=t.parentElement.parentElement,M(n,!1,!0,!0)):t.classList.contains(C)||t.classList.contains(v)?(n=t.parentElement.parentElement,D(t,n)):t.classList.contains(g)&&(n=t.parentElement.parentElement,F(n))},z=function(e){if(n){e.preventDefault();var i,s,l,c=t[n.id],u=e.clientX,d=e.clientY,h=e.changedTouches;if(h)for(i=0;i0&&(i[0].innerHTML=n))):L('Cannot setTitle of WUI dialog "'+e+'".')},this.setStatusBarContent=function(e,n){var i,r,o=t[e];void 0!==o?o.status_bar&&(o.status_bar.innerHTML=n,(r=o.detachable_ref)&&(r.closed||(i=r.document.body.getElementsByClassName(E)).length>0&&(i[0].innerHTML=n))):L('Cannot setStatusBarContent of WUI dialog "'+e+'".')},this.open=function(e,n){var i,r,o,a=t[e];if(void 0!==a)if(!a.detachable_ref||a.detachable_ref.closed){if(o=a.dialog,a.opts.modal)for(i=P(o),a.dialog.style.zIndex=16777271,a.modal_element=i,document.body.appendChild(i),r=0;r0)for(;i--;)n*=10;return(e*n>>0)/n},b=function(e){return e.classList.contains(l)?e:e.classList.contains(u)?e.firstElementChild:e.firstElementChild?e.firstElementChild.firstElementChild:null},w=function(t,n,i){var r,o,a,s,l=t,u=e[l.id],d=n.opts.width,h=n.opts.height,f=Math.abs((i-n.opts.min)/n.opts.range);a=(o=(r=l.getElementsByClassName(c)[0]).firstElementChild).firstElementChild,s=r.nextElementSibling,n.opts.vertical?(f=Math.round(f*r.offsetHeight),o.style.position="absolute",o.style.bottom="0",o.style.width="100%",o.style.height=f+"px",a.style.marginTop=-d+"px",a.style.marginLeft=-d/2-1+"px",a.style.width=2*d+"px",a.style.height=2*d+"px",s.style.marginTop="13px",u.element!==l&&(u.filler.style.position="absolute",u.filler.style.bottom="0",u.filler.style.width="100%",u.filler.style.height=f+"px",u.hook.style.marginTop=-d+"px",u.hook.style.marginLeft=-d/2-1+"px",u.hook.style.width=2*d+"px",u.hook.style.height=2*d+"px",u.value_input.style.marginTop="13px")):(f=Math.round(f*d),o.style.width=f+"px",o.style.height="100%",a.style.left=f+"px",a.style.marginTop=-h/2+"px",a.style.marginLeft=-h+"px",a.style.width=2*h+"px",a.style.height=2*h+"px",u.element!==l&&(u.filler.style.width=f+"px",u.filler.style.height="100%",u.hook.style.left=f+"px",u.hook.style.marginTop=-h/2+"px",u.hook.style.marginLeft=-h+"px",u.hook.style.width=2*h+"px",u.hook.style.height=2*h+"px")),u.value_input.value=i,s.value=i,n.value=i},x=function(e){if(e.preventDefault(),null!==i){var o,a,s=i.parentElement,l=s.parentElement,c=l.nextElementSibling,u=y(l),d=l.offsetWidth,h=0,f=e.clientX,p=e.clientY,g=e.changedTouches;if(g)for(o=0;od?(h=d,t=n.opts.max):h<0?(h=0,t=n.opts.min):t=Math.round((n.opts.min+h/d*n.opts.range)/n.opts.step)*n.opts.step,n.value===t)return;n.value=t,a=I(t,n.opts.decimals),c.value=a,n.value_input.value=a,n.opts.vertical?(s.style.height=h+"px",n.filler.style.height=h+"px"):(s.style.width=h+"px",n.filler.style.width=h+"px",i.style.left=h+"px",n.hook.style.left=h+"px"),A(n.opts.on_change,t)}},E=function(e){if(i){e.preventDefault();var t,o=e.changedTouches,a=!1,s=i.ownerDocument,l=s.defaultView||s.parentWindow;if(o){for(t=0;t=0?o+=r.opts.scroll_step:o-=r.opts.scroll_step,r.endless||(r.opts.max&&o>r.opts.max?o=r.opts.max:o0&&(a[0].style=""),r.learn_elem&&(r.learn_elem.style=""));u.learn=!0,l.style="background-color: #00ff00",o=c.id},R=function(t){t.preventDefault(),t.stopPropagation();var n,i,r,o,a,s,l,c=t.target,u=c.parentElement,d=e[u.id],f=d.opts,p=c.ownerDocument,m=d.element.id+"_wui_container",v=1;if(document.getElementById(m)||(d.configure_panel_open=!1),!0!==d.configure_panel_open){for(i in(o=p.createElement("div")).className="wui-rangeslider-configure-container",(l=p.createElement("div")).className="wui-rangeslider-configure-close",n=function(e){d.configure_panel_open=!1;var t=document.getElementById(m),n=e.target.ownerDocument.getElementById(m);t&&t.parentElement&&t.parentElement.removeChild(t),n&&n.parentElement&&n.parentElement.removeChild(n)},l.addEventListener("click",n,!1),l.addEventListener("touchstart",n,!1),o.id=m,o.appendChild(l),f.configurable)f.configurable.hasOwnProperty(i)&&void 0!==g[i]&&(r=f.configurable[i],(a=p.createElement("div")).style.display="inline-block",a.style.marginRight="8px",a.style.width="80px",a.style.textAlign="right",a.innerHTML=i.replace("_"," ")+" : ",(s=p.createElement("input")).className=h,o.appendChild(a),o.appendChild(s),v%2==0&&o.appendChild(p.createElement("div")),s.setAttribute("type","number"),s.setAttribute("step","any"),void 0!==r&&(void 0!==r.min&&(s.setAttribute("min",r.min),s.title=s.title+" min: "+r.min),void 0!==r.max&&(s.setAttribute("max",r.max),s.title=s.title+" max: "+r.max),void 0!==r.val?s.setAttribute("value",r.val):"min"===i?s.setAttribute("value",f.min):"max"===i?s.setAttribute("value",f.max):"step"===i?s.setAttribute("value",f.step):"scroll_step"===i&&s.setAttribute("value",f.scroll_step)),s.addEventListener("input",M(0,d,i),!1),v+=1);y(c),u.insertBefore(o,c),d.configure_panel_open=!0}},D=function(){v("WUI_RangeSlider 'create' failed, first argument not an id nor a DOM element.")};this.create=function(t,n){var i,r,o,a={};if("string"==typeof t)i=document.getElementById(t);else{if("object"!=typeof t)return void D();if("string"!=typeof t.innerHTML)return void D();t=(i=t).id}if(void 0===e[t]){for(o in p)p.hasOwnProperty(o)&&(a[o]=p[o]);if(void 0!==n){for(o in n)n.hasOwnProperty(o)&&void 0!==p[o]&&(a[o]=n[o]);void 0!==n.max&&(a.range=n.max),void 0!==n.step&&(a.step=n.step,void 0===n.scroll_step&&(a.scroll_step=a.step)),void 0!==n.title_on_top?a.title_on_top=n.title_on_top:a.vertical&&(a.title_on_top=!0),void 0!==n.default_value?a.default_value=n.default_value:void 0!==n.min&&void 0!==n.max&&(a.default_value=a.min+a.max/2)}a.min0){var E=document.createElement("div");E.classList.add("wui-rangeslider-configurable-btn"),E.addEventListener("click",R,!1),E.addEventListener("touchstart",R,!1),a.title_on_top&&!a.vertical?(E.style.bottom="0",d.style.marginBottom="4px"):a.title_on_top&&a.vertical?(d.style.marginLeft="16px",d.style.marginRight="16px",E.style.top="0"):(d.style.marginLeft="16px",E.style.top="0"),a.vertical?i.appendChild(E):i.insertBefore(E,d)}}if(a.midi)if(navigator.requestMIDIAccess){var M=document.createElement("div");M.classList.add(f),M.title=s,M.addEventListener("click",P,!1),M.addEventListener("touchstart",P,!1),b.learn_elem=M,a.midi.type&&(b.midi.ctrl_type=a.midi.type),i.appendChild(M)}else v("WUI_RangeSlider id '"+t+"' : Web MIDI API is disabled. (not supported by your browser?)");return r="onwheel"in document.createElement("div")?"wheel":void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll",a.bar?(m.addEventListener("mousedown",S,!1),m.addEventListener("touchstart",S,!1),m.addEventListener(r,T,!1),y.addEventListener("dblclick",k,!1)):_.addEventListener(r,T,!1),_.addEventListener("input",L,!1),e[t]=b,w(i,b,a.value),A(b.opts.on_change,b.value),t}v("WUI_RangeSlider id '"+t+"' already created, aborting.")},this.destroy=function(t){var n,i,r,a=e[t];void 0!==a?(o===t&&(o=null),O(t),(n=a.element).parentElement.removeChild(n),(r=(i=n.ownerDocument).getElementById(t+"_wui_container"))&&i.removeChild(r),delete e[t]):v("Element id '"+t+"' is not a WUI_RangeSlider, destroying aborted.")},this.getParameters=function(t){var n,i=e[t],r={};if(void 0===i)return v("Element id '"+t+"' is not a WUI_RangeSlider, getParameters aborted."),null;for(n in i)i.hasOwnProperty(n)&&void 0!==m[n]&&(r[n]=i[n]);return r},this.setParameters=function(t,n,i){var r,o=e[t];if(void 0!==o){if(n){for(r in o)o.hasOwnProperty(r)&&void 0!==n[r]&&(o[r]=n[r]);o.midi.device&&o.midi.controller&&a["d"+o.midi.device]["c"+o.midi.controller].widgets.push(t),w(o.element,o,o.value),i&&A(o.opts.on_change,o.value)}}else v("Element id '"+t+"' is not a WUI_RangeSlider, setParameters aborted.")},this.setValue=function(t,n,i){var r=e[t];void 0!==r?(w(r.element,r,n),i&&A(r.opts.on_change,n)):v("Element id '"+t+"' is not a WUI_RangeSlider, setParameters aborted.")},this.submitMIDIMessage=function(t){var n,i,r,s,l,c,u=o,d=t.data[0],h=t.data[1],p=parseInt(t.data[2],10),g="d"+d,m="c"+h,v=0;if(o){if(n=e[u]){a[g]||(a[g]={}),a[g][m]||(a[g][m]={prev_value:p,widgets:[],increments:1}),a[g][m].widgets.push(u);var y="abs"===n.midi.ctrl_type&&void 0!==n.opts.range&&void 0!==n.opts.min?"abs":"rel";return(l=C(u))&&(r=l.getElementsByClassName(f)).length>0&&(r[0].style="",r[0].title=g+" "+m+" ("+y+")"),n.midi.device=d,n.midi.controller=h,n.learn=!1,n.learn_elem.style="",n.learn_elem.title=g+" "+m+" ("+y+")",void(o=null)}o=null}if(a[g]&&a[g][m])for(i=a[g][m],v=0;vp){if(i.increments=-I,(c=n.value-I)n.opts.max&&!n.endless&&void 0!==n.opts.max)continue;i.prev_value=p}else if(c=n.value+i.increments,!n.endless&&void 0!==n.opts.min&&void 0!==n.opts.max){if(c>n.opts.max)continue;if(c0&&(a=o[0].element).parentElement.removeChild(a);delete e[t]}else y("Element id '"+t+"' is not a WUI_ToolBar, destroying aborted.")}},WUI_CircularMenu=new function(){"use strict";var e=[],t=0,n="wui-circularmenu-item",i="wui-circularmenu-show",r="wui-circularmenu-content",o={x:null,y:null,rx:64,ry:48,angle:0,item_width:32,item_height:32,window:null,element:null},a=function(t){var n,i;for(i=0;i"),n.print.apply(n,e),n.BufferArray.length>n.BufferMax?n.BufferArray.splice(0,1):n.javaconsole.scrollTop=n.javaconsole.scrollHeight},n.showconsole=function(){n.wrapper.classList.remove("hidden")},n.hideconsole=function(){n.wrapper.classList.add("hidden")},n.closer.onclick=function(){n.hideconsole()},n.hideconsole(),n}},{}],6:[function(e,t,n){t.exports=function(e){function t(){}t.prototype=e.PConstants;var n=new t;function i(e,t,n){if(e.hasOwnProperty(t)&&"function"==typeof e[t]){var i=e[t];if("$overloads"in i)i.$defaultOverload=n;else if("$overloads"in n||i.length!==n.length){var r,o;"$overloads"in n?((r=n.$overloads.slice(0))[i.length]=i,o=n.$defaultOverload):((r=[])[n.length]=n,o=r[i.length]=i);var a=function(){return(a.$overloads[arguments.length]||("$methodArgsIndex"in a&&arguments.length>a.$methodArgsIndex?a.$overloads[a.$methodArgsIndex]:null)||a.$defaultOverload).apply(this,arguments)};a.$overloads=r,"$methodArgsIndex"in n&&(a.$methodArgsIndex=n.$methodArgsIndex),a.$defaultOverload=o,e[a.name=t]=a}}else e[t]=n}function r(e,t){function r(i){n.defineProperty(e,i,{get:function(){return t[i]},set:function(e){t[i]=e},enumerable:!0})}var o=[];for(var a in t)"function"==typeof t[a]?i(e,a,t[a]):"$"===a.charAt(0)||a in e||o.push(a);for(;0a.$methodArgsIndex?a.$overloads[a.$methodArgsIndex]:null)||a.$defaultOverload).apply(this,arguments)},s=[];r&&(s[r.length]=r),s[o]=n,a.$overloads=s,a.$defaultOverload=r||n,i&&(a.$methodArgsIndex=o),e[a.name=t]=a}}else e[t]=n},n.createJavaArray=function(e,t){var i,r=null,o=null;if("string"==typeof e&&("boolean"===e?o=!1:"string"==typeof(i=e)&&-1!==["byte","int","char","color","float","long","double"].indexOf(i)&&(o=0)),"number"==typeof t[0]){var a=0|t[0];if(t.length<=1){(r=[]).length=a;for(var s=0;s "+i),u===c){if(0!==l.length)throw"Processing.js: Unable to load pjs sketch files: "+l.join("\n");var r=new e(t,s.join("\n"));a&&a(r)}}if("#"!==d.charAt(0)){var f,p,g;f=d,p=h,(g=new r).onreadystatechange=function(){var e;4===g.readyState&&(200!==g.status&&0!==g.status?e="Invalid XHR status "+g.status:""===g.responseText&&(e="withCredentials"in new r&&!1===(new r).withCredentials&&"file:"===n.location.protocol?"XMLHttpRequest failure, possibly due to a same-origin policy violation. You can try loading this page in another browser, or load it from http://localhost using a local webserver. See the Processing.js README for a more detailed explanation of this problem and solutions.":"File is empty."),p(g.responseText,e))},g.open("GET",f,!0),g.overrideMimeType&&g.overrideMimeType("application/json"),g.setRequestHeader("If-Modified-Since","Fri, 01 Jan 1960 00:00:00 GMT"),g.send(null)}else{var m=i.getElementById(d.substring(1));m?h(m.text||m.textContent):h("","Unable to load pjs sketch: element with id '"+d.substring(1)+"' was not found")}}for(var h=0;hi.length)throw"Index out of bounds for addAll: "+e+" greater or equal than "+i.length;for(n=new ObjectIterator(t);n.hasNext();)i.splice(e++,0,n.next())}else for(n=new ObjectIterator(e);n.hasNext();)i.push(n.next())},this.set=function(){if(2!==arguments.length)throw"Please use the proper number of parameters.";var e=arguments[0];if("number"!=typeof e)throw typeof e+" is not a number";if(!(0<=e&&e=o.length)a=!0;else{if(!(void 0===o[i]||r>=o[i].length))return;r=-1,++i}}this.hasNext=function(){return!a},this.next=function(){return n=e(o[i][r]),s(),n},this.remove=function(){void 0!==n&&(t(n),--r,s())},s()}(e,n)},this.remove=function(e){return!!this.contains(e)&&(n(e),!0)},this.removeAll=function(e){for(var t=e.iterator();t.hasNext();){var i=t.next();this.contains(i)&&n(i)}return!0},this.retainAll=function(e){for(var t=this.iterator(),i=[];t.hasNext();){var r=t.next();e.contains(r)||i.push(r)}for(var o=0;o"+s,n.body.appendChild(l);var c=r.width,u=r.height,d=u/2;a.fillStyle="white",a.fillRect(0,0,c,u),a.fillStyle="black",a.fillText(s,0,d);for(var h=a.getImageData(0,0,c,u).data,f=0,p=4*c,g=h.length;++f=2*e.size&&(e.leading=Math.round(C/2))}if(n.body.removeChild(l),e.caching)return a}(this),this.css=this.getCSSDefinition(),this.context2d&&(this.context2d.font=this.css)}return r.prototype.caching=!0,r.prototype.getCSSDefinition=function(e,n){return e===t&&(e=this.size+"px"),n===t&&(n=this.leading+"px"),[this.style,"normal",this.weight,e+"/"+n,this.family].join(" ")},r.prototype.measureTextWidth=function(e){return this.context2d.measureText(e).width},r.prototype.measureTextWidthFallback=function(e){var t=n.createElement("canvas").getContext("2d");return t.font=this.css,t.measureText(e).width},r.PFontCache={length:0},r.get=function(e,t){var n=r.PFontCache,i=e+"/"+(t=(10*t+.5|0)/10);if(!n[i]){if(n[i]=new r(e,t),n.length++,50===n.length){var o;for(o in r.prototype.measureTextWidth=r.prototype.measureTextWidthFallback,r.prototype.caching=!1,n)"length"!==o&&(n[o].context2d=null);return new r(e,t)}if(400===n.length)return r.PFontCache={},r.get=r.getFallback,new r(e,t)}return n[i]},r.getFallback=function(e,t){return new r(e,t)},r.list=function(){return["sans-serif","serif","monospace","fantasy","cursive"]},r.preloading={template:{},initialized:!1,initialize:function(){var e=n.createElement("style");e.setAttribute("type","text/css"),e.innerHTML='@font-face {\n font-family: "PjsEmptyFont";\n src: url(\'data:application/x-font-ttf;base64,'+"#E3KAI2wAgT1MvMg7Eo3VmNtYX7ABi3CxnbHlm7Abw3kaGVhZ7ACs3OGhoZWE7A53CRobXR47AY3AGbG9jYQ7G03Bm1heH7ABC3CBuYW1l7Ae3AgcG9zd7AI3AE#B3AQ2kgTY18PPPUACwAg3ALSRoo3#yld0xg32QAB77#E777773B#E3C#I#Q77773E#Q7777777772CMAIw7AB77732B#M#Q3wAB#g3B#E#E2BB//82BB////w#B7#gAEg3E77x2B32B#E#Q#MTcBAQ32gAe#M#QQJ#E32M#QQJ#I#g32Q77#".replace(/[#237]/g,function(e){return"AAAAAAAA".substr(~~e?7-e:6)})+"')\n format('truetype');\n}",n.head.appendChild(e);var t=n.createElement("span");t.style.cssText='position: absolute; top: -1000; left: 0; opacity: 0; font-family: "PjsEmptyFont", fantasy;',t.innerHTML="AAAAAAAA",n.body.appendChild(t),this.template=t,this.initialized=!0},getElementWidth:function(e){return n.defaultView.getComputedStyle(e,"").getPropertyValue("width")},timeAttempted:0,pending:function(e){this.initialized||this.initialize();for(var t,i,r=this.getElementWidth(this.template),o=0;oPConstants.MIN_INT){var t=this.elements[0],n=this.elements[1],i=this.elements[2],r=this.elements[3],o=this.elements[4],a=this.elements[5];return this.elements[0]=o/e,this.elements[3]=-r/e,this.elements[1]=-n/e,this.elements[4]=t/e,this.elements[2]=(n*a-o*i)/e,this.elements[5]=(r*i-t*a)/e,!0}return!1},scale:function(e,n){e&&n===t&&(n=e),e&&n&&(this.elements[0]*=e,this.elements[1]*=n,this.elements[3]*=e,this.elements[4]*=n)},invScale:function(e,t){e&&!t&&(t=e),this.scale(1/e,1/t)},apply:function(){var e;1===arguments.length&&arguments[0]instanceof i?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,this.elements[2],0,0,this.elements[5]],n=0,r=0;r<2;r++)for(var o=0;o<3;o++,n++)t[n]+=this.elements[3*r+0]*e[o+0]+this.elements[3*r+1]*e[o+3];this.elements=t.slice()},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof i?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);var t=[0,0,e[2],0,0,e[5]];t[2]=e[2]+this.elements[2]*e[0]+this.elements[5]*e[1],t[5]=e[5]+this.elements[2]*e[3]+this.elements[5]*e[4],t[0]=this.elements[0]*e[0]+this.elements[3]*e[1],t[3]=this.elements[0]*e[3]+this.elements[3]*e[4],t[1]=this.elements[1]*e[0]+this.elements[4]*e[1],t[4]=this.elements[1]*e[3]+this.elements[4]*e[4],this.elements=t.slice()},rotate:function(e){var t=Math.cos(e),n=Math.sin(e),i=this.elements[0],r=this.elements[1];this.elements[0]=t*i+n*r,this.elements[1]=-n*i+t*r,i=this.elements[3],r=this.elements[4],this.elements[3]=t*i+n*r,this.elements[4]=-n*i+t*r},rotateZ:function(e){this.rotate(e)},invRotateZ:function(e){this.rotateZ(e-Math.PI)},print:function(){var e=printMatrixHelper(this.elements),t=n.nfs(this.elements[0],e,4)+" "+n.nfs(this.elements[1],e,4)+" "+n.nfs(this.elements[2],e,4)+"\n"+n.nfs(this.elements[3],e,4)+" "+n.nfs(this.elements[4],e,4)+" "+n.nfs(this.elements[5],e,4)+"\n\n";n.println(t)}},i}},{}],15:[function(e,t,n){t.exports=function(e,t){var n=e.p,i=function(){this.reset()};return i.prototype={set:function(){16===arguments.length?this.elements=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof i?this.elements=arguments[0].array():1===arguments.length&&arguments[0]instanceof Array&&(this.elements=arguments[0].slice())},get:function(){var e=new i;return e.set(this.elements),e},reset:function(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},array:function(){return this.elements.slice()},translate:function(e,n,i){i===t&&(i=0),this.elements[3]+=e*this.elements[0]+n*this.elements[1]+i*this.elements[2],this.elements[7]+=e*this.elements[4]+n*this.elements[5]+i*this.elements[6],this.elements[11]+=e*this.elements[8]+n*this.elements[9]+i*this.elements[10],this.elements[15]+=e*this.elements[12]+n*this.elements[13]+i*this.elements[14]},transpose:function(){var e=this.elements[4];this.elements[4]=this.elements[1],this.elements[1]=e,e=this.elements[8],this.elements[8]=this.elements[2],this.elements[2]=e,e=this.elements[6],this.elements[6]=this.elements[9],this.elements[9]=e,e=this.elements[3],this.elements[3]=this.elements[12],this.elements[12]=e,e=this.elements[7],this.elements[7]=this.elements[13],this.elements[13]=e,e=this.elements[11],this.elements[11]=this.elements[14],this.elements[14]=e},mult:function(e,t){var n,i,r,o;return e instanceof PVector?(n=e.x,i=e.y,r=e.z,o=1,t||(t=new PVector)):e instanceof Array&&(n=e[0],i=e[1],r=e[2],o=e[3]||1,(!t||3!==t.length&&4!==t.length)&&(t=[0,0,0])),t instanceof Array&&(3===t.length?(t[0]=this.elements[0]*n+this.elements[1]*i+this.elements[2]*r+this.elements[3],t[1]=this.elements[4]*n+this.elements[5]*i+this.elements[6]*r+this.elements[7],t[2]=this.elements[8]*n+this.elements[9]*i+this.elements[10]*r+this.elements[11]):4===t.length&&(t[0]=this.elements[0]*n+this.elements[1]*i+this.elements[2]*r+this.elements[3]*o,t[1]=this.elements[4]*n+this.elements[5]*i+this.elements[6]*r+this.elements[7]*o,t[2]=this.elements[8]*n+this.elements[9]*i+this.elements[10]*r+this.elements[11]*o,t[3]=this.elements[12]*n+this.elements[13]*i+this.elements[14]*r+this.elements[15]*o)),t instanceof PVector&&(t.x=this.elements[0]*n+this.elements[1]*i+this.elements[2]*r+this.elements[3],t.y=this.elements[4]*n+this.elements[5]*i+this.elements[6]*r+this.elements[7],t.z=this.elements[8]*n+this.elements[9]*i+this.elements[10]*r+this.elements[11]),t},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof i?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=0;r<4;r++)for(var o=0;o<4;o++,n++)t[n]+=this.elements[o+0]*e[4*r+0]+this.elements[o+4]*e[4*r+1]+this.elements[o+8]*e[4*r+2]+this.elements[o+12]*e[4*r+3];this.elements=t.slice()},apply:function(){var e;1===arguments.length&&arguments[0]instanceof i?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,r=0;r<4;r++)for(var o=0;o<4;o++,n++)t[n]+=this.elements[4*r+0]*e[o+0]+this.elements[4*r+1]*e[o+4]+this.elements[4*r+2]*e[o+8]+this.elements[4*r+3]*e[o+12];this.elements=t.slice()},rotate:function(e,t,n,i){if(n){var r=Math.cos(e),o=Math.sin(e),a=1-r;this.apply(a*t*t+r,a*t*n-o*i,a*t*i+o*n,0,a*t*n+o*i,a*n*n+r,a*n*i-o*t,0,a*t*i-o*n,a*n*i+o*t,a*i*i+r,0,0,0,0,1)}else this.rotateZ(e)},invApply:function(){inverseCopy===t&&(inverseCopy=new i);var e=arguments;return inverseCopy.set(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]),!!inverseCopy.invert()&&(this.preApply(inverseCopy),!0)},rotateX:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},rotateY:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},rotateZ:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},scale:function(e,n,i){e&&n===t&&i===t?n=i=e:e&&n&&i===t&&(i=1),e&&n&&i&&(this.elements[0]*=e,this.elements[1]*=n,this.elements[2]*=i,this.elements[4]*=e,this.elements[5]*=n,this.elements[6]*=i,this.elements[8]*=e,this.elements[9]*=n,this.elements[10]*=i,this.elements[12]*=e,this.elements[13]*=n,this.elements[14]*=i)},skewX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},skewY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},shearX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},shearY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},multX:function(e,t,n,i){return n?i?this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]*i:this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]:this.elements[0]*e+this.elements[1]*t+this.elements[3]},multY:function(e,t,n,i){return n?i?this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]*i:this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]:this.elements[4]*e+this.elements[5]*t+this.elements[7]},multZ:function(e,t,n,i){return i?this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]*i:this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]},multW:function(e,t,n,i){return i?this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]*i:this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]},invert:function(){var e=this.elements[0]*this.elements[5]-this.elements[1]*this.elements[4],t=this.elements[0]*this.elements[6]-this.elements[2]*this.elements[4],n=this.elements[0]*this.elements[7]-this.elements[3]*this.elements[4],i=this.elements[1]*this.elements[6]-this.elements[2]*this.elements[5],r=this.elements[1]*this.elements[7]-this.elements[3]*this.elements[5],o=this.elements[2]*this.elements[7]-this.elements[3]*this.elements[6],a=this.elements[8]*this.elements[13]-this.elements[9]*this.elements[12],s=this.elements[8]*this.elements[14]-this.elements[10]*this.elements[12],l=this.elements[8]*this.elements[15]-this.elements[11]*this.elements[12],c=this.elements[9]*this.elements[14]-this.elements[10]*this.elements[13],u=this.elements[9]*this.elements[15]-this.elements[11]*this.elements[13],d=this.elements[10]*this.elements[15]-this.elements[11]*this.elements[14],h=e*d-t*u+n*c+i*l-r*s+o*a;if(Math.abs(h)<=1e-9)return!1;var f=[];f[0]=+this.elements[5]*d-this.elements[6]*u+this.elements[7]*c,f[4]=-this.elements[4]*d+this.elements[6]*l-this.elements[7]*s,f[8]=+this.elements[4]*u-this.elements[5]*l+this.elements[7]*a,f[12]=-this.elements[4]*c+this.elements[5]*s-this.elements[6]*a,f[1]=-this.elements[1]*d+this.elements[2]*u-this.elements[3]*c,f[5]=+this.elements[0]*d-this.elements[2]*l+this.elements[3]*s,f[9]=-this.elements[0]*u+this.elements[1]*l-this.elements[3]*a,f[13]=+this.elements[0]*c-this.elements[1]*s+this.elements[2]*a,f[2]=+this.elements[13]*o-this.elements[14]*r+this.elements[15]*i,f[6]=-this.elements[12]*o+this.elements[14]*n-this.elements[15]*t,f[10]=+this.elements[12]*r-this.elements[13]*n+this.elements[15]*e,f[14]=-this.elements[12]*i+this.elements[13]*t-this.elements[14]*e,f[3]=-this.elements[9]*o+this.elements[10]*r-this.elements[11]*i,f[7]=+this.elements[8]*o-this.elements[10]*n+this.elements[11]*t,f[11]=-this.elements[8]*r+this.elements[9]*n-this.elements[11]*e,f[15]=+this.elements[8]*i-this.elements[9]*t+this.elements[10]*e;var p=1/h;return f[0]*=p,f[1]*=p,f[2]*=p,f[3]*=p,f[4]*=p,f[5]*=p,f[6]*=p,f[7]*=p,f[8]*=p,f[9]*=p,f[10]*=p,f[11]*=p,f[12]*=p,f[13]*=p,f[14]*=p,f[15]*=p,this.elements=f.slice(),!0},toString:function(){for(var e="",t=0;t<15;t++)e+=this.elements[t]+", ";return e+this.elements[15]},print:function(){var e=printMatrixHelper(this.elements),t=n.nfs(this.elements[0],e,4)+" "+n.nfs(this.elements[1],e,4)+" "+n.nfs(this.elements[2],e,4)+" "+n.nfs(this.elements[3],e,4)+"\n"+n.nfs(this.elements[4],e,4)+" "+n.nfs(this.elements[5],e,4)+" "+n.nfs(this.elements[6],e,4)+" "+n.nfs(this.elements[7],e,4)+"\n"+n.nfs(this.elements[8],e,4)+" "+n.nfs(this.elements[9],e,4)+" "+n.nfs(this.elements[10],e,4)+" "+n.nfs(this.elements[11],e,4)+"\n"+n.nfs(this.elements[12],e,4)+" "+n.nfs(this.elements[13],e,4)+" "+n.nfs(this.elements[14],e,4)+" "+n.nfs(this.elements[15],e,4)+"\n\n";n.println(t)},invTranslate:function(e,t,n){this.preApply(1,0,0,-e,0,1,0,-t,0,0,1,-n,0,0,0,1)},invRotateX:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},invRotateY:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},invRotateZ:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},invScale:function(e,t,n){this.preApply([1/e,0,0,0,0,1/t,0,0,0,0,1/n,0,0,0,0,1])}},i}},{}],16:[function(e,t,n){t.exports=function(e){var t=e.PConstants,n=e.PMatrix2D,i=e.PMatrix3D,r=function(e){this.family=e||t.GROUP,this.visible=!0,this.style=!0,this.children=[],this.nameTable=[],this.params=[],this.name="",this.image=null,this.matrix=null,this.kind=null,this.close=null,this.width=null,this.height=null,this.parent=null};return r.prototype={isVisible:function(){return this.visible},setVisible:function(e){this.visible=e},disableStyle:function(){this.style=!1;for(var e=0,t=this.children.length;e, it's <"+this.element.getName()+">"}else 2===arguments.length&&("string"==typeof arguments[1]?-1 tag of this file.";this.parseColors(this.element),this.parseChildren(this.element)};return(a.prototype=new i).parseMatrix=function(){function e(e){var t=[];return e.replace(/\((.*?)\)/,function(e,n){t=n.replace(/,+/g," ").split(/\s+/)}),t}return function(n){this.checkMatrix(2);var i=[];if(n.replace(/\s*(\w+)\((.*?)\)/g,function(e){i.push(t.trim(e))}),0===i.length)return null;for(var r=0,o=i.length;r"},a.prototype.parseEllipse=function(e){var t,i;if(this.kind=n.ELLIPSE,this.family=n.PRIMITIVE,this.params=[],this.params[0]=0|this.element.getFloatAttribute("cx"),this.params[1]=0|this.element.getFloatAttribute("cy"),e){if((t=i=this.element.getFloatAttribute("r"))<0)throw"svg error: negative radius found while parsing "}else if(t=this.element.getFloatAttribute("rx"),i=this.element.getFloatAttribute("ry"),t<0||i<0)throw"svg error: negative x-axis radius or y-axis radius found while parsing ";this.params[0]-=t,this.params[1]-=i,this.params[2]=2*t,this.params[3]=2*i},a.prototype.parseLine=function(){this.kind=n.LINE,this.family=n.PRIMITIVE,this.params=[],this.params[0]=this.element.getFloatAttribute("x1"),this.params[1]=this.element.getFloatAttribute("y1"),this.params[2]=this.element.getFloatAttribute("x2"),this.params[3]=this.element.getFloatAttribute("y2")},a.prototype.parseColors=function(e){if(e.hasAttribute("opacity")&&this.setOpacity(e.getAttribute("opacity")),e.hasAttribute("stroke")&&this.setStroke(e.getAttribute("stroke")),e.hasAttribute("stroke-width")&&this.setStrokeWeight(e.getAttribute("stroke-width")),e.hasAttribute("stroke-linejoin")&&this.setStrokeJoin(e.getAttribute("stroke-linejoin")),e.hasAttribute("stroke-linecap")&&this.setStrokeCap(e.getStringAttribute("stroke-linecap")),e.hasAttribute("fill")&&this.setFill(e.getStringAttribute("fill")),e.hasAttribute("style"))for(var n=e.getStringAttribute("style").toString().split(";"),i=0,r=n.length;ie&&(this.normalize(),this.mult(e))},heading:function(){return-Math.atan2(-this.y,this.x)},heading2D:function(){return this.heading()},toString:function(){return"["+this.x+", "+this.y+", "+this.z+"]"},array:function(){return[this.x,this.y,this.z]}})i.prototype.hasOwnProperty(o)&&!i.hasOwnProperty(o)&&(i[o]=r(o));return i}},{}],19:[function(e,t,n){t.exports=function(){var e=function(e,t,n,i,r){this.fullName=e||"",this.name=t||"",this.namespace=n||"",this.value=i,this.type=r};return e.prototype={getName:function(){return this.name},getFullName:function(){return this.fullName},getNamespace:function(){return this.namespace},getValue:function(){return this.value},getType:function(){return this.type},setValue:function(e){this.value=e}},e}},{}],20:[function(e,t,n){t.exports=function(e,t){var n=e.Browser,i=n.ajax,r=n.window,o=(r.XMLHttpRequest,r.DOMParser),a=e.XMLAttribute,s=function(e,n,i,r){this.attributes=[],this.children=[],this.fullName=null,this.name=null,this.namespace="",this.content=null,this.parent=null,this.lineNr="",this.systemID="",this.type="ELEMENT",e&&("string"==typeof e?n===t&&-1":">","'":"'",'"':"""};for(n in i)Object.hasOwnProperty(i,n)||(e=e.replace(new RegExp(n,"g"),i[n]));return t.cdata=e,t},hasAttribute:function(){return 1===arguments.length?null!==this.getAttribute(arguments[0]):2===arguments.length?null!==this.getAttribute(arguments[0],arguments[1]):void 0},equals:function(e){if(!(e instanceof s))return!1;var t,n,i,r,o;if(this.fullName!==e.fullName)return!1;if(this.attributes.length!==e.getAttributeCount())return!1;if(this.attributes.length!==e.attributes.length)return!1;for(t=0,n=this.attributes.length;te&&this.children.splice(e,1)},findAttribute:function(e,t){this.namespace=t||"";for(var n=0,i=this.attributes.length;n":i+=">"+this.content+"";else{for(i+=">",t=0;t"}return i}},s.parse=function(e){var t=new s;return t.parse(e),t},s}},{}],21:[function(e,t,n){t.exports={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32"}},{}],22:[function(e,t,n){t.exports=function(e,t,n){return function(i,r){i.__contains=function(e,t){return"string"!=typeof e?e.contains.apply(e,r(arguments)):null!==e&&null!==t&&"string"==typeof t&&-1e.length||""!==t&&t!==e&&e.indexOf(t)!==n)},i.__endsWith=function(e,t){if("string"!=typeof e)return e.endsWith.apply(e,r(arguments));var n=t?t.length:0;return""===t||t===e||e.indexOf(t)===e.length-n},i.__hashCode=function(t){return t.hashCode instanceof Function?t.hashCode.apply(t,r(arguments)):e(t)},i.__printStackTrace=function(e){i.println("Exception: "+e.toString())}}}},{}],23:[function(e,t,n){t.exports=function(e,t){var n=function(){return Math.random()};function i(e,t){var n=e||362436069,i=t||521288629,r=function(){return 4294967295&((65535&(n=36969*(65535&n)+(n>>>16)&4294967295))<<16|65535&(i=18e3*(65535&i)+(i>>>16)&4294967295))};this.doubleGenerator=function(){var e=r()/4294967296;return e<0?1+e:e},this.intGenerator=r}function r(e){var n,r,o=e!==t?new i(e,(e<<16)+(e>>16)):i.createRandomized(),a=new Uint8Array(512);for(n=0;n<256;++n)a[n]=n;for(n=0;n<256;++n){var s=a[r=255&o.intGenerator()];a[r]=a[n],a[n]=s}for(n=0;n<256;++n)a[n+256]=a[n];function l(e,t,n,i){var r=15&e,o=r<8?t:n,a=r<4?n:12===r||14===r?t:i;return(0==(1&r)?o:-o)+(0==(2&r)?a:-a)}function c(e,t,n){var i=0==(1&e)?t:n;return 0==(2&e)?-i:i}function u(e,t){return 0==(1&e)?-t:t}function d(e,t,n){return t+e*(n-t)}this.noise3d=function(e,t,n){var i=255&Math.floor(e),r=255&Math.floor(t),o=255&Math.floor(n),s=(3-2*(e-=Math.floor(e)))*e*e,c=(3-2*(t-=Math.floor(t)))*t*t,u=(3-2*(n-=Math.floor(n)))*n*n,h=a[i]+r,f=a[h]+o,p=a[h+1]+o,g=a[i+1]+r,m=a[g]+o,v=a[g+1]+o;return d(u,d(c,d(s,l(a[f],e,t,n),l(a[m],e-1,t,n)),d(s,l(a[p],e,t-1,n),l(a[v],e-1,t-1,n))),d(c,d(s,l(a[f+1],e,t,n-1),l(a[m+1],e-1,t,n-1)),d(s,l(a[p+1],e,t-1,n-1),l(a[v+1],e-1,t-1,n-1))))},this.noise2d=function(e,t){var n=255&Math.floor(e),i=255&Math.floor(t),r=(3-2*(e-=Math.floor(e)))*e*e,o=(3-2*(t-=Math.floor(t)))*t*t,s=a[n]+i,l=a[n+1]+i;return d(o,d(r,c(a[s],e,t),c(a[l],e-1,t)),d(r,c(a[s+1],e,t-1),c(a[l+1],e-1,t-1)))},this.noise1d=function(e){var t=255&Math.floor(e);return d((3-2*(e-=Math.floor(e)))*e*e,u(a[t],e),u(a[t+1],e-1))}}e.abs=Math.abs,e.ceil=Math.ceil,e.exp=Math.exp,e.floor=Math.floor,e.log=Math.log,e.pow=Math.pow,e.round=Math.round,e.sqrt=Math.sqrt,e.acos=Math.acos,e.asin=Math.asin,e.atan=Math.atan,e.atan2=Math.atan2,e.cos=Math.cos,e.sin=Math.sin,e.tan=Math.tan,e.constrain=function(e,t,n){return ne[i]&&(t=e[i]);return t},e.norm=function(e,t,n){return(e-t)/(n-t)},e.sq=function(e){return e*e},e.degrees=function(e){return 180*e/Math.PI},e.random=function(e,t){if(0===arguments.length?(t=1,e=0):1===arguments.length&&(t=e,e=0),e===t)return e;for(var i=0;i<100;i++){var r=n()*(t-e)+e;if(r!==t)return r}return e},i.createRandomized=function(){var e=new Date;return new i(e/6e4&4294967295,4294967295&e)},e.randomSeed=function(e){n=new i(e,(e<<16)+(e>>16)).doubleGenerator,this.haveNextNextGaussian=!1},e.randomGaussian=function(){if(this.haveNextNextGaussian)return this.haveNextNextGaussian=!1,this.nextNextGaussian;for(var e,t,i;1<=(i=(e=2*n()-1)*e+(t=2*n()-1)*t)||0===i;);var r=Math.sqrt(-2*Math.log(i)/i);return this.nextNextGaussian=t*r,this.haveNextNextGaussian=!0,e*r};var o={generator:t,octaves:4,fallout:.5,seed:t};e.noise=function(e,n,i){o.generator===t&&(o.generator=new r(o.seed));for(var a=o.generator,s=1,l=1,c=0,u=0;u([=]?)/g,g),d;);var m,v,C,y,A,I,_,b=function(e){for(var t=[],n=e.split(/([\{\[\(\)\]\}])/),i=n[0],r=[],o=1;o\=]+)/g,function(e,t){var n=s(t);return n.untrim("__int_cast("+n.middle+")")})).replace(/\bsuper(\s*"B\d+")/g,"$$superCstr$1").replace(/\bsuper(\s*\.)/g,"$$super$1")).replace(/\b0+((\d*)(?:\.[\d*])?(?:[eE][\-\+]?\d+)?[fF]?)\b/,function(e,t,n){return t===n?e:""===n?"0"+t:t})).replace(/\b(\.?\d+\.?)[fF]\b/g,"$1")).replace(/([^\s])%([^=\s])/g,"$1 % $2")).replace(/\b(frameRate|keyPressed|mousePressed)\b(?!\s*"B)/g,"__$1")).replace(/\b(boolean|byte|char|float|int)\s*"B/g,function(e,t){return"parse"+t.substring(0,1).toUpperCase()+t.substring(1)+'"B'})).replace(/\bpixels\b\s*(("C(\d+)")|\.length)?(\s*=(?!=)([^,\]\)\}]+))?/g,function(e,t,n,i,r,o){if(n){var a=b[i];return r?"pixels.setPixel"+E("("+a.substring(1,a.length-1)+","+o+")","B"):"pixels.getPixel"+E("("+a.substring(1,a.length-1)+")","B")}return t?"pixels.getLength"+E("()","B"):r?"pixels.set"+E("("+o+")","B"):"pixels.toArray"+E("()","B")});t=!1,n=n.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*\.\s*(?:[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*\.\s*)*)(replace|replaceAll|replaceFirst|contains|equals|equalsIgnoreCase|hashCode|toCharArray|printStackTrace|split|startsWith|endsWith|codePointAt|matches)\s*"B(\d+)"/g,i),t;);function r(e,n,i){return t=!0,"__instanceof"+E("("+n+", "+i+")","B")}for(;t=!1,n=n.replace(/((?:'\d+'|\b[A-Za-z_$][\w$]*\s*(?:"[BC]\d+")*)\s*(?:\.\s*[A-Za-z_$][\w$]*\s*(?:"[BC]\d+"\s*)*)*)instanceof\s+([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)/g,r),t;);return n.replace(/\bthis(\s*"B\d+")/g,"$$constr$1")}(n.middle);return i=i.replace(/"[ABC](\d+)"/g,function(t,n){return e(b[n])}),n.untrim(i)}(e);return new V(n=(n=(n=n.replace(/"H(\d+)"/g,function(e,n){return t.push(H(b[n])),'"!'+(t.length-1)+'"'})).replace(/"F(\d+)"/g,function(e,n){return t.push(function(e){var t=new RegExp(/\bnew\s*([A-Za-z_$][\w$]*\s*(?:\.\s*[A-Za-z_$][\w$]*)*)\s*"B\d+"\s*"A(\d+)"/).exec(e),n=v,i=S();v=i;var r=t[1]+"$"+i,o=new z(r,C(b[t[2]],r,"","implements "+t[1]));return k(o,i,n),v=n,o}(b[n])),'"!'+(t.length-1)+'"'})).replace(/"I(\d+)"/g,function(e,n){return t.push(function(e){for(var t=e.split(","),n=0;n=":"===")+" "+k+") { $constr_"+k+".apply("+e+", arguments); }")}return 0";var y=[],A={},I=this.Processing=function(e,r,C){if(!(this instanceof I))throw"called Processing constructor as if it were a function: missing 'new'.";var _={},b=e===t&&r===t;if(!("getContext"in(_=b?l.createElement("canvas"):"string"==typeof e?l.getElementById(e):e)))throw"called Processing constructor without passing canvas element reference or id.";var w=[];function x(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent("on"+t,n),w.push({elem:e,type:t,fn:n})}function E(e){var t=e.elem,n=e.type,i=e.fn;t.removeEventListener?t.removeEventListener(n,i,!1):t.detachEvent&&t.detachEvent("on"+n,i)}var S=this;S.Char=S.Character=Char,w=[],i.withCommonFunctions(S),i.withMath(S),i.withProxyFunctions(S,function(e){return Array.prototype.slice.call(e,1)}),i.withTouch(S,_,x,function(e,t){Object.keys(w).forEach(function(n){-1 cos( light.angle ) ) { spotAttenuation = pow( spotDot, light.concentration ); } else{ spotAttenuation = 0.0; } attenuation *= spotAttenuation;")+" float nDotVP = max( 0.0, dot( vertNormal, VP ) ); vec3 halfVector = normalize( VP - normalize(ecPos) ); float nDotHV = max( 0.0, dot( vertNormal, halfVector ) ); if( nDotVP != 0.0 ) { powerFactor = pow( nDotHV, uShininess ); } spec += uSpecular * powerFactor * attenuation; col += light.color * nDotVP * attenuation;}void main(void) { vec3 finalAmbient = vec3( 0.0 ); vec3 finalDiffuse = vec3( 0.0 ); vec3 finalSpecular = vec3( 0.0 ); vec4 col = uColor; if ( uColor[0] == -1.0 ){ col = aColor; } vec3 norm = normalize(vec3( uNormalTransform * vec4( aNormal, 0.0 ) )); vec4 ecPos4 = uView * uModel * vec4(aVertex, 1.0); vec3 ecPos = (vec3(ecPos4))/ecPos4.w; if( uLightCount == 0 ) { vFrontColor = col + vec4(uMaterialSpecular, 1.0); } else { for( int i = 0; i < 8; i++ ) { Light l = getLight(i); if( i >= uLightCount ){ break; } if( l.type == 0 ) { AmbientLight( finalAmbient, ecPos, l ); } else if( l.type == 1 ) { DirectionalLight( finalDiffuse, finalSpecular, norm, ecPos, l ); } else if( l.type == 2 ) { PointLight( finalDiffuse, finalSpecular, norm, ecPos, l ); } else { SpotLight( finalDiffuse, finalSpecular, norm, ecPos, l ); } } if( uUsingMat == false ) { vFrontColor = vec4( vec3( col ) * finalAmbient + vec3( col ) * finalDiffuse + vec3( col ) * finalSpecular, col[3] ); } else{ vFrontColor = vec4( uMaterialEmissive + (vec3(col) * uMaterialAmbient * finalAmbient ) + (vec3(col) * finalDiffuse) + (uMaterialSpecular * finalSpecular), col[3] ); } } vTexture.xy = aTexture.xy; gl_Position = uProjection * uView * uModel * vec4( aVertex, 1.0 );}";function Zt(e,n,i,r){var o=tt.locations[e];o===t&&(o=k.getUniformLocation(n,i),tt.locations[e]=o),null!==o&&(4===r.length?k.uniform4fv(o,r):3===r.length?k.uniform3fv(o,r):2===r.length?k.uniform2fv(o,r):k.uniform1f(o,r))}function $t(e,n,i,r){var o=tt.locations[e];o===t&&(o=k.getUniformLocation(n,i),tt.locations[e]=o),null!==o&&(4===r.length?k.uniform4iv(o,r):3===r.length?k.uniform3iv(o,r):2===r.length?k.uniform2iv(o,r):k.uniform1i(o,r))}function Qt(e,n,i,r,o){var a=tt.locations[e];a===t&&(a=k.getUniformLocation(n,i),tt.locations[e]=a),-1!==a&&(16===o.length?k.uniformMatrix4fv(a,r,o):9===o.length?k.uniformMatrix3fv(a,r,o):k.uniformMatrix2fv(a,r,o))}function Jt(e,n,i,r,o){var a=tt.attributes[e];a===t&&(a=k.getAttribLocation(n,i),tt.attributes[e]=a),-1!==a&&(k.bindBuffer(k.ARRAY_BUFFER,o),k.vertexAttribPointer(a,r,k.FLOAT,!1,0,0),k.enableVertexAttribArray(a))}function en(e,n,i){var r=tt.attributes[e];r===t&&(r=k.getAttribLocation(n,i),tt.attributes[e]=r),-1!==r&&k.disableVertexAttribArray(r)}var tn=function(e,t,n){var i=e.createShader(e.VERTEX_SHADER);if(e.shaderSource(i,t),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS))throw e.getShaderInfoLog(i);var r=e.createShader(e.FRAGMENT_SHADER);if(e.shaderSource(r,n),e.compileShader(r),!e.getShaderParameter(r,e.COMPILE_STATUS))throw e.getShaderInfoLog(r);var o=e.createProgram();if(e.attachShader(o,i),e.attachShader(o,r),e.linkProgram(o),!e.getProgramParameter(o,e.LINK_STATUS))throw"Error linking shaders.";return o},nn=function(e,t,n,i,r){return{x:e,y:t,w:n,h:i}},rn=nn,on=function(e,t,n,i,r){return{x:e,y:t,w:r?n:n-e,h:r?i:i-t}},an=function(e,t,n,i,r){return{x:e-n/2,y:t-i/2,w:n,h:i}},sn=function(){},ln=function(){},cn=function(){},un=function(){};ln.prototype=new sn,ln.prototype.constructor=ln,cn.prototype=new sn,cn.prototype.constructor=cn,un.prototype=new sn,un.prototype.constructor=un,sn.prototype.a3DOnlyFunction=c,S.shape=function(e,t,n,i,r){1<=arguments.length&&null!==e&&e.isVisible()&&(S.pushMatrix(),Ht===u.CENTER?5===arguments.length?(S.translate(t-i/2,n-r/2),S.scale(i/e.getWidth(),r/e.getHeight())):3===arguments.length?S.translate(t-e.getWidth()/2,-e.getHeight()/2):S.translate(-e.getWidth()/2,-e.getHeight()/2):Ht===u.CORNER?5===arguments.length?(S.translate(t,n),S.scale(i/e.getWidth(),r/e.getHeight())):3===arguments.length&&S.translate(t,n):Ht===u.CORNERS&&(5===arguments.length?(i-=t,r-=n,S.translate(t,n),S.scale(i/e.getWidth(),r/e.getHeight())):3===arguments.length&&S.translate(t,n)),e.draw(S),(1===arguments.length&&Ht===u.CENTER||1u.MIN_INT){var t=this.elements[0],n=this.elements[1],i=this.elements[2],r=this.elements[3],o=this.elements[4],a=this.elements[5];return this.elements[0]=o/e,this.elements[3]=-r/e,this.elements[1]=-n/e,this.elements[4]=t/e,this.elements[2]=(n*a-o*i)/e,this.elements[5]=(r*i-t*a)/e,!0}return!1},scale:function(e,t){e&&!t&&(t=e),e&&t&&(this.elements[0]*=e,this.elements[1]*=t,this.elements[3]*=e,this.elements[4]*=t)},invScale:function(e,t){e&&!t&&(t=e),this.scale(1/e,1/t)},apply:function(){var e;1===arguments.length&&arguments[0]instanceof hn?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,this.elements[2],0,0,this.elements[5]],n=0,i=0;i<2;i++)for(var r=0;r<3;r++,n++)t[n]+=this.elements[3*i+0]*e[r+0]+this.elements[3*i+1]*e[r+3];this.elements=t.slice()},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof hn?e=arguments[0].array():6===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);var t=[0,0,e[2],0,0,e[5]];t[2]=e[2]+this.elements[2]*e[0]+this.elements[5]*e[1],t[5]=e[5]+this.elements[2]*e[3]+this.elements[5]*e[4],t[0]=this.elements[0]*e[0]+this.elements[3]*e[1],t[3]=this.elements[0]*e[3]+this.elements[3]*e[4],t[1]=this.elements[1]*e[0]+this.elements[4]*e[1],t[4]=this.elements[1]*e[3]+this.elements[4]*e[4],this.elements=t.slice()},rotate:function(e){var t=Math.cos(e),n=Math.sin(e),i=this.elements[0],r=this.elements[1];this.elements[0]=t*i+n*r,this.elements[1]=-n*i+t*r,i=this.elements[3],r=this.elements[4],this.elements[3]=t*i+n*r,this.elements[4]=-n*i+t*r},rotateZ:function(e){this.rotate(e)},invRotateZ:function(e){this.rotateZ(e-Math.PI)},print:function(){var e=dn(this.elements),t=S.nfs(this.elements[0],e,4)+" "+S.nfs(this.elements[1],e,4)+" "+S.nfs(this.elements[2],e,4)+"\n"+S.nfs(this.elements[3],e,4)+" "+S.nfs(this.elements[4],e,4)+" "+S.nfs(this.elements[5],e,4)+"\n\n";S.println(t)}};var fn=S.PMatrix3D=function(){this.reset()};fn.prototype={set:function(){16===arguments.length?this.elements=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof fn?this.elements=arguments[0].array():1===arguments.length&&arguments[0]instanceof Array&&(this.elements=arguments[0].slice())},get:function(){var e=new fn;return e.set(this.elements),e},reset:function(){this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]},array:function(){return this.elements.slice()},translate:function(e,n,i){i===t&&(i=0),this.elements[3]+=e*this.elements[0]+n*this.elements[1]+i*this.elements[2],this.elements[7]+=e*this.elements[4]+n*this.elements[5]+i*this.elements[6],this.elements[11]+=e*this.elements[8]+n*this.elements[9]+i*this.elements[10],this.elements[15]+=e*this.elements[12]+n*this.elements[13]+i*this.elements[14]},transpose:function(){var e=this.elements[4];this.elements[4]=this.elements[1],this.elements[1]=e,e=this.elements[8],this.elements[8]=this.elements[2],this.elements[2]=e,e=this.elements[6],this.elements[6]=this.elements[9],this.elements[9]=e,e=this.elements[3],this.elements[3]=this.elements[12],this.elements[12]=e,e=this.elements[7],this.elements[7]=this.elements[13],this.elements[13]=e,e=this.elements[11],this.elements[11]=this.elements[14],this.elements[14]=e},mult:function(e,t){var n,i,r,o;return e instanceof PVector?(n=e.x,i=e.y,r=e.z,o=1,t||(t=new PVector)):e instanceof Array&&(n=e[0],i=e[1],r=e[2],o=e[3]||1,(!t||3!==t.length&&4!==t.length)&&(t=[0,0,0])),t instanceof Array&&(3===t.length?(t[0]=this.elements[0]*n+this.elements[1]*i+this.elements[2]*r+this.elements[3],t[1]=this.elements[4]*n+this.elements[5]*i+this.elements[6]*r+this.elements[7],t[2]=this.elements[8]*n+this.elements[9]*i+this.elements[10]*r+this.elements[11]):4===t.length&&(t[0]=this.elements[0]*n+this.elements[1]*i+this.elements[2]*r+this.elements[3]*o,t[1]=this.elements[4]*n+this.elements[5]*i+this.elements[6]*r+this.elements[7]*o,t[2]=this.elements[8]*n+this.elements[9]*i+this.elements[10]*r+this.elements[11]*o,t[3]=this.elements[12]*n+this.elements[13]*i+this.elements[14]*r+this.elements[15]*o)),t instanceof PVector&&(t.x=this.elements[0]*n+this.elements[1]*i+this.elements[2]*r+this.elements[3],t.y=this.elements[4]*n+this.elements[5]*i+this.elements[6]*r+this.elements[7],t.z=this.elements[8]*n+this.elements[9]*i+this.elements[10]*r+this.elements[11]),t},preApply:function(){var e;1===arguments.length&&arguments[0]instanceof fn?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,i=0;i<4;i++)for(var r=0;r<4;r++,n++)t[n]+=this.elements[r+0]*e[4*i+0]+this.elements[r+4]*e[4*i+1]+this.elements[r+8]*e[4*i+2]+this.elements[r+12]*e[4*i+3];this.elements=t.slice()},apply:function(){var e;1===arguments.length&&arguments[0]instanceof fn?e=arguments[0].array():16===arguments.length?e=Array.prototype.slice.call(arguments):1===arguments.length&&arguments[0]instanceof Array&&(e=arguments[0]);for(var t=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],n=0,i=0;i<4;i++)for(var r=0;r<4;r++,n++)t[n]+=this.elements[4*i+0]*e[r+0]+this.elements[4*i+1]*e[r+4]+this.elements[4*i+2]*e[r+8]+this.elements[4*i+3]*e[r+12];this.elements=t.slice()},rotate:function(e,t,n,i){if(arguments.length<4)this.rotateZ(e);else{var r=new PVector(t,n,i),o=r.mag();if(0===o)return;1!=o&&(r.normalize(),t=r.x,n=r.y,i=r.z);var a=S.cos(e),s=S.sin(e),l=1-a;this.apply(l*t*t+a,l*t*n-s*i,l*t*i+s*n,0,l*t*n+s*i,l*n*n+a,l*n*i-s*t,0,l*t*i-s*n,l*n*i+s*t,l*i*i+a,0,0,0,0,1)}},invApply:function(){fe===t&&(fe=new fn);var e=arguments;return fe.set(e[0],e[1],e[2],e[3],e[4],e[5],e[6],e[7],e[8],e[9],e[10],e[11],e[12],e[13],e[14],e[15]),!!fe.invert()&&(this.preApply(fe),!0)},rotateX:function(e){var t=S.cos(e),n=S.sin(e);this.apply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},rotateY:function(e){var t=S.cos(e),n=S.sin(e);this.apply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},rotateZ:function(e){var t=Math.cos(e),n=Math.sin(e);this.apply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},scale:function(e,t,n){!e||t||n?e&&t&&!n&&(n=1):t=n=e,e&&t&&n&&(this.elements[0]*=e,this.elements[1]*=t,this.elements[2]*=n,this.elements[4]*=e,this.elements[5]*=t,this.elements[6]*=n,this.elements[8]*=e,this.elements[9]*=t,this.elements[10]*=n,this.elements[12]*=e,this.elements[13]*=t,this.elements[14]*=n)},skewX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},skewY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},shearX:function(e){var t=Math.tan(e);this.apply(1,t,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},shearY:function(e){var t=Math.tan(e);this.apply(1,0,0,0,t,1,0,0,0,0,1,0,0,0,0,1)},multX:function(e,t,n,i){return n?i?this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]*i:this.elements[0]*e+this.elements[1]*t+this.elements[2]*n+this.elements[3]:this.elements[0]*e+this.elements[1]*t+this.elements[3]},multY:function(e,t,n,i){return n?i?this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]*i:this.elements[4]*e+this.elements[5]*t+this.elements[6]*n+this.elements[7]:this.elements[4]*e+this.elements[5]*t+this.elements[7]},multZ:function(e,t,n,i){return i?this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]*i:this.elements[8]*e+this.elements[9]*t+this.elements[10]*n+this.elements[11]},multW:function(e,t,n,i){return i?this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]*i:this.elements[12]*e+this.elements[13]*t+this.elements[14]*n+this.elements[15]},invert:function(){var e=this.elements[0]*this.elements[5]-this.elements[1]*this.elements[4],t=this.elements[0]*this.elements[6]-this.elements[2]*this.elements[4],n=this.elements[0]*this.elements[7]-this.elements[3]*this.elements[4],i=this.elements[1]*this.elements[6]-this.elements[2]*this.elements[5],r=this.elements[1]*this.elements[7]-this.elements[3]*this.elements[5],o=this.elements[2]*this.elements[7]-this.elements[3]*this.elements[6],a=this.elements[8]*this.elements[13]-this.elements[9]*this.elements[12],s=this.elements[8]*this.elements[14]-this.elements[10]*this.elements[12],l=this.elements[8]*this.elements[15]-this.elements[11]*this.elements[12],c=this.elements[9]*this.elements[14]-this.elements[10]*this.elements[13],u=this.elements[9]*this.elements[15]-this.elements[11]*this.elements[13],d=this.elements[10]*this.elements[15]-this.elements[11]*this.elements[14],h=e*d-t*u+n*c+i*l-r*s+o*a;if(Math.abs(h)<=1e-9)return!1;var f=[];f[0]=+this.elements[5]*d-this.elements[6]*u+this.elements[7]*c,f[4]=-this.elements[4]*d+this.elements[6]*l-this.elements[7]*s,f[8]=+this.elements[4]*u-this.elements[5]*l+this.elements[7]*a,f[12]=-this.elements[4]*c+this.elements[5]*s-this.elements[6]*a,f[1]=-this.elements[1]*d+this.elements[2]*u-this.elements[3]*c,f[5]=+this.elements[0]*d-this.elements[2]*l+this.elements[3]*s,f[9]=-this.elements[0]*u+this.elements[1]*l-this.elements[3]*a,f[13]=+this.elements[0]*c-this.elements[1]*s+this.elements[2]*a,f[2]=+this.elements[13]*o-this.elements[14]*r+this.elements[15]*i,f[6]=-this.elements[12]*o+this.elements[14]*n-this.elements[15]*t,f[10]=+this.elements[12]*r-this.elements[13]*n+this.elements[15]*e,f[14]=-this.elements[12]*i+this.elements[13]*t-this.elements[14]*e,f[3]=-this.elements[9]*o+this.elements[10]*r-this.elements[11]*i,f[7]=+this.elements[8]*o-this.elements[10]*n+this.elements[11]*t,f[11]=-this.elements[8]*r+this.elements[9]*n-this.elements[11]*e,f[15]=+this.elements[8]*i-this.elements[9]*t+this.elements[10]*e;var p=1/h;return f[0]*=p,f[1]*=p,f[2]*=p,f[3]*=p,f[4]*=p,f[5]*=p,f[6]*=p,f[7]*=p,f[8]*=p,f[9]*=p,f[10]*=p,f[11]*=p,f[12]*=p,f[13]*=p,f[14]*=p,f[15]*=p,this.elements=f.slice(),!0},toString:function(){for(var e="",t=0;t<15;t++)e+=this.elements[t]+", ";return e+this.elements[15]},print:function(){var e=dn(this.elements),t=S.nfs(this.elements[0],e,4)+" "+S.nfs(this.elements[1],e,4)+" "+S.nfs(this.elements[2],e,4)+" "+S.nfs(this.elements[3],e,4)+"\n"+S.nfs(this.elements[4],e,4)+" "+S.nfs(this.elements[5],e,4)+" "+S.nfs(this.elements[6],e,4)+" "+S.nfs(this.elements[7],e,4)+"\n"+S.nfs(this.elements[8],e,4)+" "+S.nfs(this.elements[9],e,4)+" "+S.nfs(this.elements[10],e,4)+" "+S.nfs(this.elements[11],e,4)+"\n"+S.nfs(this.elements[12],e,4)+" "+S.nfs(this.elements[13],e,4)+" "+S.nfs(this.elements[14],e,4)+" "+S.nfs(this.elements[15],e,4)+"\n\n";S.println(t)},invTranslate:function(e,t,n){this.preApply(1,0,0,-e,0,1,0,-t,0,0,1,-n,0,0,0,1)},invRotateX:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([1,0,0,0,0,t,-n,0,0,n,t,0,0,0,0,1])},invRotateY:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,0,n,0,0,1,0,0,-n,0,t,0,0,0,0,1])},invRotateZ:function(e){var t=Math.cos(-e),n=Math.sin(-e);this.preApply([t,-n,0,0,n,t,0,0,0,0,1,0,0,0,0,1])},invScale:function(e,t,n){this.preApply([1/e,0,0,0,0,1/t,0,0,0,0,1/n,0,0,0,0,1])}};var pn,gn=S.PMatrixStack=function(){this.matrixStack=[]};function mn(e,t,n,i){var r,o,a,s;if(Ke===u.HSB){var l=S.color.toRGB(e,t,n);r=l[0],o=l[1],a=l[2]}else r=Math.round(e/Ve*255),o=Math.round(t/Ge*255),a=Math.round(n/Xe*255);return r=255<(r=r<0?0:r)?255:r,o=255<(o=o<0?0:o)?255:o,a=255<(a=a<0?0:a)?255:a,(s=255<(s=(s=Math.round(i/je*255))<0?0:s)?255:s)<<24&u.ALPHA_MASK|r<<16&u.RED_MASK|o<<8&u.GREEN_MASK|a&u.BLUE_MASK}function vn(e){var t,n,i;t=((e&u.RED_MASK)>>>16)/255,n=((e&u.GREEN_MASK)>>>8)/255,i=(e&u.BLUE_MASK)/255;var r,o=S.max(S.max(t,n),i),a=S.min(S.min(t,n),i);return a===o?[0,0,o*Xe]:(r=t===o?(n-i)/(o-a):n===o?2+(i-t)/(o-a):4+(t-n)/(o-a),(r/=6)<0?r+=1:1>8)},S.peg=function(e){return e<0?0:255>8),f=i+((u-i)*t>>8),p=o+((d-o)*t>>8);return r(((4278190080&e)>>>24)+t,255)<<24|(h=(h<0?0:255>>24,l=o&t,c=o&n,u=o&i,d=a&t,h=a&n,f=a&i;return r(((o&e)>>>24)+s,255)<<24|l+((d-l)*s>>8)&t|c+((h-c)*s>>8)&n|u+((f-u)*s>>8)&i},add:function(o,a){var s=(a&e)>>>24;return r(((o&e)>>>24)+s,255)<<24|r((o&t)+((a&t)>>8)*s,t)&t|r((o&n)+((a&n)>>8)*s,n)&n|r((o&i)+((a&i)*s>>8),i)},subtract:function(a,s){var l=(s&e)>>>24;return r(((a&e)>>>24)+l,255)<<24|o((a&t)-((s&t)>>8)*l,n)&t|o((a&n)-((s&n)>>8)*l,i)&n|o((a&i)-((s&i)*l>>8),0)},lightest:function(a,s){var l=(s&e)>>>24;return r(((a&e)>>>24)+l,255)<<24|o(a&t,((s&t)>>8)*l)&t|o(a&n,((s&n)>>8)*l)&n|o(a&i,(s&i)*l>>8)},darkest:function(o,a){var s=(a&e)>>>24,l=o&t,c=o&n,u=o&i,d=r(o&t,((a&t)>>8)*s),h=r(o&n,((a&n)>>8)*s),f=r(o&i,(a&i)*s>>8);return r(((o&e)>>>24)+s,255)<<24|l+((d-l)*s>>8)&t|c+((h-c)*s>>8)&n|u+((f-u)*s>>8)&i},difference:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,u>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,s+u-(s*u>>7),l+d-(l*d>>7),c+h-(c*h>>7))},multiply:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,s*((o&t)>>16)>>8,l*((o&n)>>8)>>8,c*(o&i)>>8)},screen:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,255-((255-s)*(255-((o&t)>>16))>>8),255-((255-l)*(255-((o&n)>>8))>>8),255-((255-c)*(255-(o&i))>>8))},hard_light:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,u<128?s*u>>7:255-((255-s)*(255-u)>>7),d<128?l*d>>7:255-((255-l)*(255-d)>>7),h<128?c*h>>7:255-((255-c)*(255-h)>>7))},soft_light:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,(s*u>>7)+(s*s>>8)-(s*s*u>>15),(l*d>>7)+(l*l>>8)-(l*l*d>>15),(c*h>>7)+(c*c>>8)-(c*c*h>>15))},overlay:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i;return a(r,(o&e)>>>24,s,l,c,0,0,0,s<128?s*u>>7:255-((255-s)*(255-u)>>7),l<128?l*d>>7:255-((255-l)*(255-d)>>7),c<128?c*h>>7:255-((255-c)*(255-h)>>7))},dodge:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i,f=255;255!==u&&(f=(f=(s<<8)/(255-u))<0?0:255>>24,s,l,c,0,0,0,f,p,g)},burn:function(r,o){var s=(r&t)>>16,l=(r&n)>>8,c=r&i,u=(o&t)>>16,d=(o&n)>>8,h=o&i,f=0;0!==u&&(f=255-((f=(255-s<<8)/u)<0?0:255>>24,s,l,c,0,0,0,f,p,g)}}}(),S.color=function(e,n,i,r){return e!==t&&n!==t&&i!==t&&r!==t?mn(e,n,i,r):e!==t&&n!==t&&i!==t?mn(e,n,i,je):e!==t&&n!==t?(a=n,(o=e)&u.ALPHA_MASK?(s=(s=255<(s=Math.round(a/je*255))?255:s)<0?0:s,o-(o&u.ALPHA_MASK)+(s<<24&u.ALPHA_MASK)):Ke===u.RGB?mn(o,o,o,a):Ke===u.HSB?mn(0,0,o/Ve*Xe,a):void 0):"number"==typeof e?function(e){if(e<=Ve&&0<=e){if(Ke===u.RGB)return mn(e,e,e,je);if(Ke===u.HSB)return mn(0,0,e/Ve*Xe,je)}if(e)return 2147483647>>16)+","+((e&u.GREEN_MASK)>>>8)+","+(e&u.BLUE_MASK)+","+((e&u.ALPHA_MASK)>>>24)/255+")"},S.color.toInt=function(e,t,n,i){return i<<24&u.ALPHA_MASK|e<<16&u.RED_MASK|t<<8&u.GREEN_MASK|n&u.BLUE_MASK},S.color.toArray=function(e){return[(e&u.RED_MASK)>>>16,(e&u.GREEN_MASK)>>>8,e&u.BLUE_MASK,(e&u.ALPHA_MASK)>>>24]},S.color.toGLArray=function(e){return[((e&u.RED_MASK)>>>16)/255,((e&u.GREEN_MASK)>>>8)/255,(e&u.BLUE_MASK)/255,((e&u.ALPHA_MASK)>>>24)/255]},S.color.toRGB=function(e,t,n){e=(e=(e=Ve>>16)/255*Ve},S.green=function(e){return((e&u.GREEN_MASK)>>>8)/255*Ge},S.blue=function(e){return(e&u.BLUE_MASK)/255*Xe},S.alpha=function(e){return((e&u.ALPHA_MASK)>>>24)/255*je},S.lerpColor=function(e,t,n){var i,r,o,a,s,l,c,d,h,f,p,g,m,v,C,y,A=S.color(e),I=S.color(t);return Ke===u.HSB?(g=vn(A),c=((A&u.ALPHA_MASK)>>>24)/je,m=vn(I),p=((I&u.ALPHA_MASK)>>>24)/je,C=S.lerp(g[0],m[0],n),y=S.lerp(g[1],m[1],n),o=S.lerp(g[2],m[2],n),v=S.color.toRGB(C,y,o),(S.lerp(c,p,n)*je+.5|0)<<24&u.ALPHA_MASK|v[0]<<16&u.RED_MASK|v[1]<<8&u.GREEN_MASK|v[2]&u.BLUE_MASK):(a=(A&u.RED_MASK)>>>16,s=(A&u.GREEN_MASK)>>>8,l=A&u.BLUE_MASK,c=((A&u.ALPHA_MASK)>>>24)/je,d=(I&u.RED_MASK)>>>16,h=(I&u.GREEN_MASK)>>>8,f=I&u.BLUE_MASK,p=((I&u.ALPHA_MASK)>>>24)/je,i=S.lerp(a,d,n)+.5|0,r=S.lerp(s,h,n)+.5|0,o=S.lerp(l,f,n)+.5|0,(S.lerp(c,p,n)*je+.5|0)<<24&u.ALPHA_MASK|i<<16&u.RED_MASK|r<<8&u.GREEN_MASK|o&u.BLUE_MASK)},S.colorMode=function(){Ke=arguments[0],1=n.height||e>=n.width)throw"x and y must be non-negative and less than the dimensions of the image"}else e=n.width>>>1,t=n.height>>>1;var i='url("'+n.toDataURL()+'") '+e+" "+t+", default";_.style.cursor=i}else if(1===arguments.length){var r=arguments[0];_.style.cursor=r}else _.style.cursor=Ne},S.noCursor=function(){_.style.cursor=u.NOCURSOR},S.link=function(e,n){n!==t?s.open(e,n):s.location=e},S.beginDraw=c,S.endDraw=c,ln.prototype.toImageData=function(e,n,i,r){return e=e!==t?e:0,n=n!==t?n:0,i=i!==t?i:S.width,r=r!==t?r:S.height,k.getImageData(e,n,i,r)},cn.prototype.toImageData=function(e,n,i,r){e=e!==t?e:0,n=n!==t?n:0,i=i!==t?i:S.width,r=r!==t?r:S.height;var o=l.createElement("canvas").getContext("2d").createImageData(i,r),a=new v(i*r*4);k.readPixels(e,n,i,r,k.RGBA,k.UNSIGNED_BYTE,a);for(var s=0,c=a.length,u=o.data;s>>n-1&1);)n--;for(var i="";0>>--n&1?"1":"0";return i},S.unbinary=function(e){for(var t=e.length-1,n=1,i=0;0<=t;){var r=e[t--];if("0"!==r&&"1"!==r)throw"the value passed into unbinary was not an 8 bit binary number";"1"===r&&(i+=n),n<<=1}return i},S.hex=function(e,n){return 1===arguments.length&&(n=e instanceof Char?4:8),function(e,n){n=n===t||null===n?n=8:n,e<0&&(e=4294967295+e+1);for(var i=Number(e).toString(16).toUpperCase();i.length=n&&(i=i.substring(i.length-n,i.length)),i}(e,n)},S.unhex=function(e){if(e instanceof Array){for(var t=[],n=0;n 0.5){ discard; } } if(uIsDrawingText == 1){ float alpha = texture2D(uSampler, vTextureCoord).a; gl_FragColor = vec4(vFrontColor.rgb * alpha, alpha); } else{ gl_FragColor = vFrontColor; }}"),z=tn(k,"varying vec4 vFrontColor;attribute vec3 aVertex;attribute vec4 aColor;uniform mat4 uView;uniform mat4 uProjection;uniform float uPointSize;void main(void) { vFrontColor = aColor; gl_PointSize = uPointSize; gl_Position = uProjection * uView * vec4(aVertex, 1.0);}","#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 vFrontColor;uniform bool uSmooth;void main(void){ if(uSmooth == true){ float dist = distance(gl_PointCoord, vec2(0.5)); if(dist > 0.5){ discard; } } gl_FragColor = vFrontColor;}"),S.strokeWeight(1),F=tn(k,Kt,"#ifdef GL_ES\nprecision highp float;\n#endif\nvarying vec4 vFrontColor;uniform sampler2D uSampler;uniform bool uUsingTexture;varying vec2 vTexture;void main(void){ if( uUsingTexture ){ gl_FragColor = vec4(texture2D(uSampler, vTexture.xy)) * vFrontColor; } else{ gl_FragColor = vFrontColor; }}"),k.useProgram(F),$t("usingTexture3d",F,"usingTexture",rt),S.lightFalloff(1,0,0),S.shininess(1),S.ambient(255,255,255),S.specular(0,0,0),S.emissive(0,0,0),W=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,W),k.bufferData(k.ARRAY_BUFFER,Vt,k.STATIC_DRAW),H=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,H),k.bufferData(k.ARRAY_BUFFER,Xt,k.STATIC_DRAW),j=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,j),k.bufferData(k.ARRAY_BUFFER,Gt,k.STATIC_DRAW),V=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,V),k.bufferData(k.ARRAY_BUFFER,Yt,k.STATIC_DRAW),G=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,G),k.bufferData(k.ARRAY_BUFFER,qt,k.STATIC_DRAW),X=k.createBuffer(),Y=k.createBuffer(),q=k.createBuffer(),K=k.createBuffer(),Z=k.createBuffer(),Q=k.createBuffer(),$=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,$),k.bufferData(k.ARRAY_BUFFER,new p([0,0,0]),k.STATIC_DRAW),te=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,te),k.bufferData(k.ARRAY_BUFFER,new p([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),k.STATIC_DRAW),ne=k.createBuffer(),k.bindBuffer(k.ARRAY_BUFFER,ne),k.bufferData(k.ARRAY_BUFFER,new p([0,0,1,0,1,1,0,1]),k.STATIC_DRAW),ie=k.createBuffer(),k.bindBuffer(k.ELEMENT_ARRAY_BUFFER,ie),k.bufferData(k.ELEMENT_ARRAY_BUFFER,new m([0,1,2,2,3,0]),k.STATIC_DRAW),se=new fn,le=new fn,ce=new fn,ue=new fn,pe=new fn,S.camera(),S.perspective(),de=new gn,he=new gn,O=new fn,P=new fn,R=new fn,D=new fn,N=new fn,(B=new fn).set(-1,3,-3,1,3,-6,3,0,-3,3,0,0,1,0,0,0),sn.prototype.size.apply(this,arguments)}),ln.prototype.ambientLight=sn.prototype.a3DOnlyFunction,cn.prototype.ambientLight=function(e,t,n,i,r,o){if(At===u.MAX_LIGHTS)throw"can only create "+u.MAX_LIGHTS+" lights";var a=new PVector(i,r,o),s=new fn;s.scale(1,-1,1),s.apply(ce.array()),s.mult(a,a);var l=mn(e,t,n,0),c=[((l&u.RED_MASK)>>>16)/255,((l&u.GREEN_MASK)>>>8)/255,(l&u.BLUE_MASK)/255];k.useProgram(F),Zt("uLights.color.3d."+At,F,"uLights"+At+".color",c),Zt("uLights.position.3d."+At,F,"uLights"+At+".position",a.array()),$t("uLights.type.3d."+At,F,"uLights"+At+".type",0),$t("uLightCount3d",F,"uLightCount",++At)},ln.prototype.directionalLight=sn.prototype.a3DOnlyFunction,cn.prototype.directionalLight=function(e,t,n,i,r,o){if(At===u.MAX_LIGHTS)throw"can only create "+u.MAX_LIGHTS+" lights";k.useProgram(F);var a=new fn;a.scale(1,-1,1),a.apply(ce.array());var s=[(a=a.array())[0]*i+a[4]*r+a[8]*o,a[1]*i+a[5]*r+a[9]*o,a[2]*i+a[6]*r+a[10]*o],l=mn(e,t,n,0),c=[((l&u.RED_MASK)>>>16)/255,((l&u.GREEN_MASK)>>>8)/255,(l&u.BLUE_MASK)/255];Zt("uLights.color.3d."+At,F,"uLights"+At+".color",c),Zt("uLights.position.3d."+At,F,"uLights"+At+".position",s),$t("uLights.type.3d."+At,F,"uLights"+At+".type",1),$t("uLightCount3d",F,"uLightCount",++At)},ln.prototype.lightFalloff=sn.prototype.a3DOnlyFunction,cn.prototype.lightFalloff=function(e,t,n){k.useProgram(F),Zt("uFalloff3d",F,"uFalloff",[e,t,n])},ln.prototype.lightSpecular=sn.prototype.a3DOnlyFunction,cn.prototype.lightSpecular=function(e,t,n){var i=mn(e,t,n,0),r=[((i&u.RED_MASK)>>>16)/255,((i&u.GREEN_MASK)>>>8)/255,(i&u.BLUE_MASK)/255];k.useProgram(F),Zt("uSpecular3d",F,"uSpecular",r)},S.lights=function(){S.ambientLight(128,128,128),S.directionalLight(128,128,128,0,0,-1),S.lightFalloff(1,0,0),S.lightSpecular(0,0,0)},ln.prototype.pointLight=sn.prototype.a3DOnlyFunction,cn.prototype.pointLight=function(e,t,n,i,r,o){if(At===u.MAX_LIGHTS)throw"can only create "+u.MAX_LIGHTS+" lights";var a=new PVector(i,r,o),s=new fn;s.scale(1,-1,1),s.apply(ce.array()),s.mult(a,a);var l=mn(e,t,n,0),c=[((l&u.RED_MASK)>>>16)/255,((l&u.GREEN_MASK)>>>8)/255,(l&u.BLUE_MASK)/255];k.useProgram(F),Zt("uLights.color.3d."+At,F,"uLights"+At+".color",c),Zt("uLights.position.3d."+At,F,"uLights"+At+".position",a.array()),$t("uLights.type.3d."+At,F,"uLights"+At+".type",2),$t("uLightCount3d",F,"uLightCount",++At)},ln.prototype.noLights=sn.prototype.a3DOnlyFunction,cn.prototype.noLights=function(){At=0,k.useProgram(F),$t("uLightCount3d",F,"uLightCount",At)},ln.prototype.spotLight=sn.prototype.a3DOnlyFunction,cn.prototype.spotLight=function(e,t,n,i,r,o,a,s,l,c,d){if(At===u.MAX_LIGHTS)throw"can only create "+u.MAX_LIGHTS+" lights";k.useProgram(F);var h=new PVector(i,r,o),f=new fn;f.scale(1,-1,1),f.apply(ce.array()),f.mult(h,h);var p=[(f=f.array())[0]*a+f[4]*s+f[8]*l,f[1]*a+f[5]*s+f[9]*l,f[2]*a+f[6]*s+f[10]*l],g=mn(e,t,n,0),m=[((g&u.RED_MASK)>>>16)/255,((g&u.GREEN_MASK)>>>8)/255,(g&u.BLUE_MASK)/255];Zt("uLights.color.3d."+At,F,"uLights"+At+".color",m),Zt("uLights.position.3d."+At,F,"uLights"+At+".position",h.array()),Zt("uLights.direction.3d."+At,F,"uLights"+At+".direction",p),Zt("uLights.concentration.3d."+At,F,"uLights"+At+".concentration",d),Zt("uLights.angle.3d."+At,F,"uLights"+At+".angle",c),$t("uLights.type.3d."+At,F,"uLights"+At+".type",3),$t("uLightCount3d",F,"uLightCount",++At)},ln.prototype.beginCamera=function(){throw"beginCamera() is not available in 2D mode"},cn.prototype.beginCamera=function(){if(kt)throw"You cannot call beginCamera() again before calling endCamera()";kt=!0,ce=le,ue=se},ln.prototype.endCamera=function(){throw"endCamera() is not available in 2D mode"},cn.prototype.endCamera=function(){if(!kt)throw"You cannot call endCamera() before calling beginCamera()";ce.set(se),ue.set(le),kt=!1},S.camera=function(e,n,i,r,o,a,s,l,c){e===t&&(Lt=S.width/2,Mt=S.height/2,i=Ot=Mt/Math.tan(Tt/2),r=e=Lt,o=n=Mt,l=1,c=s=a=0);var u=new PVector(e-r,n-o,i-a),d=new PVector(s,l,c);u.normalize();var h=PVector.cross(d,u);d=PVector.cross(u,h),h.normalize(),d.normalize();var f=h.x,p=h.y,g=h.z,m=d.x,v=d.y,C=d.z,y=u.x,A=u.y,I=u.z;se.set(f,p,g,0,m,v,C,0,y,A,I,0,0,0,0,1),se.translate(-e,-n,-i),le.reset(),le.invApply(f,p,g,0,m,v,C,0,y,A,I,0,0,0,0,1),le.translate(e,n,i),ce.set(se),ue.set(le)},S.perspective=function(e,t,n,i){var r,o,a,s;0===arguments.length&&(Mt=_.height/2,Ot=Mt/Math.tan(Tt/2),Pt=Ot/10,Rt=10*Ot,Dt=S.width/S.height,e=Tt,t=Dt,n=Pt,i=Rt),a=(r=n*Math.tan(e/2))*t,s=(o=-r)*t,S.frustum(s,a,o,r,n,i)},ln.prototype.frustum=function(){throw"Processing.js: frustum() is not supported in 2D mode"},cn.prototype.frustum=function(e,t,n,i,r,o){(pe=new fn).set(2*r/(t-e),0,(t+e)/(t-e),0,0,2*r/(i-n),(i+n)/(i-n),0,0,0,-(o+r)/(o-r),-2*o*r/(o-r),0,0,-1,0);var a=new fn;a.set(pe),a.transpose(),k.useProgram(U),Qt("projection2d",U,"uProjection",!1,a.array()),k.useProgram(F),Qt("projection3d",F,"uProjection",!1,a.array()),k.useProgram(z),Qt("uProjectionUS",z,"uProjection",!1,a.array())},S.ortho=function(e,t,n,i,r,o){0===arguments.length&&(e=0,t=S.width,n=0,i=S.height,r=-10,o=10);var a=2/(t-e),s=2/(i-n),l=-2/(o-r),c=-(t+e)/(t-e),u=-(i+n)/(i-n),d=-(o+r)/(o-r);(pe=new fn).set(a,0,0,c,0,s,0,u,0,0,l,d,0,0,0,1);var h=new fn;h.set(pe),h.transpose(),k.useProgram(U),Qt("projection2d",U,"uProjection",!1,h.array()),k.useProgram(F),Qt("projection3d",F,"uProjection",!1,h.array()),k.useProgram(z),Qt("uProjectionUS",z,"uProjection",!1,h.array())},S.printProjection=function(){pe.print()},S.printCamera=function(){se.print()},ln.prototype.box=sn.prototype.a3DOnlyFunction,cn.prototype.box=function(e,t,n){t&&n||(t=n=e);var i=new fn;i.scale(e,t,n);var r=new fn;if(r.scale(1,-1,1),r.apply(ce.array()),r.transpose(),ge){if(k.useProgram(F),Qt("model3d",F,"uModel",!1,i.array()),Qt("view3d",F,"uView",!1,r.array()),k.enable(k.POLYGON_OFFSET_FILL),k.polygonOffset(1,1),Zt("color3d",F,"uColor",me),0u.TWO_PI&&(o=r+u.TWO_PI);var s,l,c,d,h,f=n/2,p=i/2,g=e+f,m=t+p,v=(s=g+.5,l=m+.5,c=r,d=1/(f+p),h=o,function(e,t,n,i,r){for(n=0,i=c,r=h+d,e.beginShape(),t&&e.vertex(s-.5,l-.5);i>>16,i[n+1]=(t&u.GREEN_MASK)>>>8,i[n+2]=t&u.BLUE_MASK,i[n+3]=(t&u.ALPHA_MASK)>>>24,h.__isDirty=!0}),toArray:(d=s,function(){var e=[],t=d.imageData.data,n=d.width*d.height;if(d.isRemote)throw"Image is loaded remotely. Cannot get pixels.";for(var i=0,r=0;i>>16,n[t+1]=(i&u.GREEN_MASK)>>>8,n[t+2]=i&u.BLUE_MASK,n[t+3]=(i&u.ALPHA_MASK)>>>24;c.__isDirty=!0})}};function Fn(e,t,n,i){var r=new Bn(n,i,u.ARGB);return r.fromImageData(S.toImageData(e,t,n,i)),r}function Un(e,t,n,i,r){if(r.isRemote)throw"Image is loaded remotely. Cannot get x,y,w,h.";for(var o=new Bn(n,i,u.ARGB),a=o.imageData.data,s=r.width,l=r.height,c=r.imageData.data,d=Math.max(0,-t),h=Math.max(0,-e),f=Math.min(i,l-t),p=Math.min(n,s-e),g=d;gmt&&zn())}Bn.prototype={__isPImage:!0,updatePixels:function(){var e=this.sourceImg;e&&e instanceof h&&this.__isDirty&&e.getContext("2d").putImageData(this.imageData,0,0),this.__isDirty=!1},fromHTMLImageData:function(e){var t=Nn(e);try{var n=t.context.getImageData(0,0,e.width,e.height);this.fromImageData(n)}catch(t){e.width&&e.height&&(this.isRemote=!0,this.width=e.width,this.height=e.height)}this.sourceImg=e},get:function(e,t,n,i){return arguments.length?2===arguments.length?S.get(e,t,this):4===arguments.length?S.get(e,t,n,i,this):void 0:S.get(this)},set:function(e,t,n){S.set(e,t,n,this),this.__isDirty=!0},blend:function(e,t,n,i,r,o,a,s,l,c){9===arguments.length?S.blend(this,e,t,n,i,r,o,a,s,l,this):10===arguments.length&&S.blend(e,t,n,i,r,o,a,s,l,c,this),delete this.sourceImg},copy:function(e,t,n,i,r,o,a,s,l){8===arguments.length?S.blend(this,e,t,n,i,r,o,a,s,u.REPLACE,this):9===arguments.length&&S.blend(e,t,n,i,r,o,a,s,l,u.REPLACE,this),delete this.sourceImg},filter:function(e,t){2===arguments.length?S.filter(e,t,this):1===arguments.length&&S.filter(e,null,this),delete this.sourceImg},save:function(e){S.save(e,this)},resize:function(e,t){if(this.isRemote)throw"Image is loaded remotely. Cannot resize.";if(0!==this.width||0!==this.height){0===e&&0!==t?e=Math.floor(this.width/this.height*t):0===t&&0!==e&&(t=Math.floor(this.height/this.width*e));var n=Nn(Nn(this.imageData).canvas,e,t).context.getImageData(0,0,e,t);this.fromImageData(n)}},mask:function(e){var t,n,i=this.toImageData();if(e instanceof Bn||e.__isPImage){if(e.width!==this.width||e.height!==this.height)throw"mask must have the same dimensions as PImage.";for(e=e.toImageData(),t=2,n=this.width*this.height*4;t=S.width||e<0||t<0||t>=S.height)return 0;if(gt){var i=4*((0|e)+S.width*(0|t));return(n=S.imageData.data)[i+3]<<24&u.ALPHA_MASK|n[i]<<16&u.RED_MASK|n[i+1]<<8&u.GREEN_MASK|n[i+2]&u.BLUE_MASK}return(n=S.toImageData(0|e,0|t,1,1).data)[3]<<24&u.ALPHA_MASK|n[0]<<16&u.RED_MASK|n[1]<<8&u.GREEN_MASK|n[2]&u.BLUE_MASK}(e,t):void 0!==e?Un(0,0,e.width,e.height,e):Fn(0,0,S.width,S.height)},S.createGraphics=function(e,t,n){var i=new I;return i.size(e,t,n),i.background(0,0),i},S.set=function(e,t,n,i){3===arguments.length?"number"==typeof n?Wn(e,t,n):(n instanceof Bn||n.__isPImage)&&S.image(n,e,t):4===arguments.length&&function(e,t,n,i){if(i.isRemote)throw"Image is loaded remotely. Cannot set x,y.";var r=S.color.toArray(n),o=t*i.width*4+4*e,a=i.imageData.data;a[o]=r[0],a[o+1]=r[1],a[o+2]=r[2],a[o+3]=r[3]}(e,t,n,i)},S.imageData={},S.pixels={getLength:function(){return S.imageData.data.length?S.imageData.data.length/4:0},getPixel:function(e){var t=4*e,n=S.imageData.data;return n[t+3]<<24&4278190080|n[t+0]<<16&16711680|n[t+1]<<8&65280|255&n[t+2]},setPixel:function(e,t){var n=4*e,i=S.imageData.data;i[n+0]=(16711680&t)>>>16,i[n+1]=(65280&t)>>>8,i[n+2]=255&t,i[n+3]=(4278190080&t)>>>24},toArray:function(){for(var e=[],t=S.imageData.width*S.imageData.height,n=S.imageData.data,i=0,r=0;i>16&255)+151*(h>>8&255)+28*(255&h))<(a=77*(r>>16&255)+151*(r>>8&255)+28*(255&r))&&(o=h,a=v),(m=77*((d=t.pixels.getPixel(s))>>16&255)+151*(d>>8&255)+28*(255&d))>16&255)+151*(f>>8&255)+28*(255&f))>16&255)+151*(p>>8&255)+28*(255&p))>16&255)+151*(r>>8&255)+28*(255&r))<(v=77*(h>>16&255)+151*(h>>8&255)+28*(255&h))&&(o=h,a=v),a<(m=77*((d=t.pixels.getPixel(s))>>16&255)+151*(d>>8&255)+28*(255&d))&&(o=d,a=m),a<(C=77*(f>>16&255)+151*(f>>8&255)+28*(255&f))&&(o=f,a=C),a<(y=77*(p>>16&255)+151*(p>>8&255)+28*(255&p))&&(o=p,a=y),_[A++]=o;t.pixels.set(_)};S.filter=function(e,n,i){var r,o,a,s;if(3===arguments.length?(i.loadPixels(),r=i):(S.loadPixels(),r=S),n===t&&(n=null),r.isRemote)throw"Image is loaded remotely. Cannot filter image.";var l=r.pixels.getLength();switch(e){case u.BLUR:!function(e,t){var n,i,r,o,a,s,l,c,u,d,h,f,g,m,v,C=t.pixels.getLength(),y=new p(C),A=new p(C),I=new p(C),_=new p(C),b=0;!function(e){var t,n=S.floor(3.5*e);if(n=n<1?1:n<248?n:248,S.shared.blurRadius!==n){S.shared.blurRadius=n,S.shared.blurKernelSize=1+(S.shared.blurRadius<<1),S.shared.blurKernel=new p(S.shared.blurKernelSize);var i=S.shared.blurKernel,r=S.shared.blurKernelSize;for(S.shared.blurRadius,t=0;t>16&255)+151*(o>>8&255)+28*(255&o)>>8,r.pixels.setPixel(s,o&u.ALPHA_MASK|a<<16|a<<8|a);break;case u.INVERT:for(s=0;s>16&255,f=r.pixels.getPixel(s)>>8&255,g=255&r.pixels.getPixel(s);h=255*(h*c>>8)/d,f=255*(f*c>>8)/d,g=255*(g*c>>8)/d,r.pixels.setPixel(s,4278190080&r.pixels.getPixel(s)|h<<16|f<<8|g)}break;case u.OPAQUE:for(s=0;s>16,S.max((r.pixels.getPixel(s)&u.GREEN_MASK)>>8,r.pixels.getPixel(s)&u.BLUE_MASK));r.pixels.setPixel(s,r.pixels.getPixel(s)&u.ALPHA_MASK|(v=e.width&&(i=e.width-1),r>=e.height&&(r=e.height-1);var m=i-t,v=r-n,C=d-l,y=h-c;if(!(C<=0||y<=0||m<=0||v<=0||a<=l||s<=c||t>=e.width||n>=e.height)){var A=Math.floor(m/C*u.PRECISIONF),I=Math.floor(v/y*u.PRECISIONF),_=S.shared;_.srcXOffset=Math.floor(l<0?-l*A:t*u.PRECISIONF),_.srcYOffset=Math.floor(c<0?-c*I:n*u.PRECISIONF),l<0&&(C+=l,l=0),c<0&&(y+=c,c=0),C=Math.min(C,a-l),y=Math.min(y,s-c);var b,w=c*a+l;_.srcBuffer=e.imageData.data,_.iw=e.width,_.iw1=e.width-1,_.ih1=e.height-1,S.filter_bilinear,S.filter_new_scanline;var x,E,k,T,L,M,O=Gn[f],P=u.ALPHA_MASK,R=u.RED_MASK,D=u.GREEN_MASK,N=u.BLUE_MASK,B=u.PREC_MAXVAL,F=u.PRECISIONB,U=u.PREC_RED_SHIFT,z=u.PREC_ALPHA_SHIFT,W=_.srcBuffer,H=Math.min;for(g=0;g>F)*_.iw,_.v2=H(1+(_.srcYOffset>>F),_.ih1)*_.iw,p=0;p>F,_.ll=_.ifU*_.fracV>>F,_.ur=_.fracU*_.ifV>>F,_.lr=_.fracU*_.fracV>>F,_.u1=_.sX>>F,_.u2=H(_.u1+1,_.iw1),k=4*(_.v1+_.u1),T=4*(_.v1+_.u2),L=4*(_.v2+_.u1),M=4*(_.v2+_.u2),_.cUL=W[k+3]<<24&P|W[k]<<16&R|W[k+1]<<8&D|W[k+2]&N,_.cUR=W[T+3]<<24&P|W[T]<<16&R|W[T+1]<<8&D|W[T+2]&N,_.cLL=W[L+3]<<24&P|W[L]<<16&R|W[L+1]<<8&D|W[L+2]&N,_.cLR=W[M+3]<<24&P|W[M]<<16&R|W[M+1]<<8&D|W[M+2]&N,_.r=_.ul*((_.cUL&R)>>16)+_.ll*((_.cLL&R)>>16)+_.ur*((_.cUR&R)>>16)+_.lr*((_.cLR&R)>>16)<>>F&D,_.b=_.ul*(_.cUL&N)+_.ll*(_.cLL&N)+_.ur*(_.cUR&N)+_.lr*(_.cLR&N)>>>F,_.a=_.ul*((_.cUL&P)>>>24)+_.ll*((_.cLL&P)>>>24)+_.ur*((_.cUR&P)>>>24)+_.lr*((_.cLR&P)>>>24)<>>16,o[E+1]=(x&D)>>>8,o[E+2]=x&N,o[E+3]=(x&P)>>>24,_.sX+=A;w+=a,_.srcYOffset+=I}}},S.loadFont=function(e,n){if(e===t)throw"font name required in loadFont.";if(-1===e.indexOf(".svg"))return n===t&&(n=ft.size),PFont.get(e,n);var i=S.loadGlyphs(e);return{name:e,css:"12px sans-serif",glyph:!0,units_per_em:i.units_per_em,horiz_adv_x:1/i.units_per_em*i.horiz_adv_x,ascent:i.ascent,descent:i.descent,width:function(t){for(var n=0,i=t.length,r=0;r":return e.greater;case"?":return e.question;case"@":return e.at;case"[":return e.bracketleft;case"\\":return e.backslash;case"]":return e.bracketright;case"^":return e.asciicircum;case"`":return e.grave;case"{":return e.braceleft;case"|":return e.bar;case"}":return e.braceright;case"~":return e.asciitilde;default:return e[t]}}catch(e){I.debug(e)}},ln.prototype.text$line=function(e,t,n,i,r){var o=0,a=0;if(ft.glyph){var s=S.glyphTable[lt];Cn(),k.translate(t,n+ct),r!==u.RIGHT&&r!==u.CENTER||(o=s.width(e),a=r===u.RIGHT?-o:-o/2);var l=1/s.units_per_em*ct;k.scale(l,l);for(var c=0,d=e.length;c=15&&(d=!1,l=!0);var _=C&&(c||d&&(null==I||I<12.11)),b=n||a&&s>=9;function w(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}var x,E=function(e,t){var n=e.className,i=w(t).exec(n);if(i){var r=n.slice(i.index+i[0].length);e.className=n.slice(0,i.index)+(r?i[1]+r:"")}};function S(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function k(e,t){return S(e).appendChild(t)}function T(e,t,n,i){var r=document.createElement(e);if(n&&(r.className=n),i&&(r.style.cssText=i),"string"==typeof t)r.appendChild(document.createTextNode(t));else if(t)for(var o=0;o=t)return a+(t-o);a+=s-o,a+=n-a%n,o=s+1}}g?D=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:a&&(D=function(e){try{e.select()}catch(e){}});var U=function(){this.id=null,this.f=null,this.time=0,this.handler=N(this.onTimeout,this)};function z(e,t){for(var n=0;n=t)return i+Math.min(a,t-r);if(r+=o-i,i=o+1,(r+=n-r%n)>=t)return i}}var Y=[""];function q(e){for(;Y.length<=e;)Y.push(K(Y)+" ");return Y[e]}function K(e){return e[e.length-1]}function Z(e,t){for(var n=[],i=0;i"€"&&(e.toUpperCase()!=e.toLowerCase()||J.test(e))}function te(e,t){return t?!!(t.source.indexOf("\\w")>-1&&ee(e))||t.test(e):ee(e)}function ne(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}var ie=/[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/;function re(e){return e.charCodeAt(0)>=768&&ie.test(e)}function oe(e,t,n){for(;(n<0?t>0:tn?-1:1;;){if(t==n)return t;var r=(t+n)/2,o=i<0?Math.ceil(r):Math.floor(r);if(o==t)return e(o)?t:n;e(o)?n=o:t=o+i}}var se=null;function le(e,t,n){var i;se=null;for(var r=0;rt)return r;o.to==t&&(o.from!=o.to&&"before"==n?i=r:se=r),o.from==t&&(o.from!=o.to&&"before"!=n?i=r:se=r)}return null!=i?i:se}var ce=function(){var e="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",t="nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";var n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,i=/[stwN]/,r=/[LRr]/,o=/[Lb1n]/,a=/[1n]/;function s(e,t,n){this.level=e,this.from=t,this.to=n}return function(l,c){var u="ltr"==c?"L":"R";if(0==l.length||"ltr"==c&&!n.test(l))return!1;for(var d,h=l.length,f=[],p=0;p-1&&(i[t]=r.slice(0,o).concat(r.slice(o+1)))}}}function ge(e,t){var n=fe(e,t);if(n.length)for(var i=Array.prototype.slice.call(arguments,2),r=0;r0}function ye(e){e.prototype.on=function(e,t){he(this,e,t)},e.prototype.off=function(e,t){pe(this,e,t)}}function Ae(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function Ie(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function _e(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function be(e){Ae(e),Ie(e)}function we(e){return e.target||e.srcElement}function xe(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),C&&e.ctrlKey&&1==t&&(t=3),t}var Ee,Se,ke=function(){if(a&&s<9)return!1;var e=T("div");return"draggable"in e||"dragDrop"in e}();function Te(e){if(null==Ee){var t=T("span","​");k(e,T("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(Ee=t.offsetWidth<=1&&t.offsetHeight>2&&!(a&&s<8))}var n=Ee?T("span","​"):T("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return n.setAttribute("cm-text",""),n}function Le(e){if(null!=Se)return Se;var t=k(e,document.createTextNode("AخA")),n=x(t,0,1).getBoundingClientRect(),i=x(t,1,2).getBoundingClientRect();return S(e),!(!n||n.left==n.right)&&(Se=i.right-n.right<3)}var Me,Oe=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],i=e.length;t<=i;){var r=e.indexOf("\n",t);-1==r&&(r=e.length);var o=e.slice(t,"\r"==e.charAt(r-1)?r-1:r),a=o.indexOf("\r");-1!=a?(n.push(o.slice(0,a)),t+=a+1):(n.push(o),t=r+1)}return n}:function(e){return e.split(/\r\n?|\n/)},Pe=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(e){return!1}}:function(e){var t;try{t=e.ownerDocument.selection.createRange()}catch(e){}return!(!t||t.parentElement()!=e)&&0!=t.compareEndPoints("StartToEnd",t)},Re="oncopy"in(Me=T("div"))||(Me.setAttribute("oncopy","return;"),"function"==typeof Me.oncopy),De=null;var Ne={},Be={};function Fe(e){if("string"==typeof e&&Be.hasOwnProperty(e))e=Be[e];else if(e&&"string"==typeof e.name&&Be.hasOwnProperty(e.name)){var t=Be[e.name];"string"==typeof t&&(t={name:t}),(e=Q(t,e)).name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return Fe("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return Fe("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function Ue(e,t){t=Fe(t);var n=Ne[t.name];if(!n)return Ue(e,"text/plain");var i=n(e,t);if(ze.hasOwnProperty(t.name)){var r=ze[t.name];for(var o in r)r.hasOwnProperty(o)&&(i.hasOwnProperty(o)&&(i["_"+o]=i[o]),i[o]=r[o])}if(i.name=t.name,t.helperType&&(i.helperType=t.helperType),t.modeProps)for(var a in t.modeProps)i[a]=t.modeProps[a];return i}var ze={};function We(e,t){B(t,ze.hasOwnProperty(e)?ze[e]:ze[e]={})}function He(e,t){if(!0===t)return t;if(e.copyState)return e.copyState(t);var n={};for(var i in t){var r=t[i];r instanceof Array&&(r=r.concat([])),n[i]=r}return n}function je(e,t){for(var n;e.innerMode&&(n=e.innerMode(t))&&n.mode!=e;)t=n.state,e=n.mode;return n||{mode:e,state:t}}function Ve(e,t,n){return!e.startState||e.startState(t,n)}var Ge=function(e,t,n){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Xe(e,t){if((t-=e.first)<0||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var i=0;;++i){var r=n.children[i],o=r.chunkSize();if(t=e.first&&tn?et(n,Xe(e,n).text.length):function(e,t){var n=e.ch;return null==n||n>t?et(e.line,t):n<0?et(e.line,0):e}(t,Xe(e,t.line).text.length)}function lt(e,t){for(var n=[],i=0;i=this.string.length},Ge.prototype.sol=function(){return this.pos==this.lineStart},Ge.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ge.prototype.next=function(){if(this.post},Ge.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},Ge.prototype.skipToEnd=function(){this.pos=this.string.length},Ge.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},Ge.prototype.backUp=function(e){this.pos-=e},Ge.prototype.column=function(){return this.lastColumnPos0?null:(i&&!1!==t&&(this.pos+=i[0].length),i)}var r=function(e){return n?e.toLowerCase():e};if(r(this.string.substr(this.pos,e.length))==r(e))return!1!==t&&(this.pos+=e.length),!0},Ge.prototype.current=function(){return this.string.slice(this.start,this.pos)},Ge.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}},Ge.prototype.lookAhead=function(e){var t=this.lineOracle;return t&&t.lookAhead(e)},Ge.prototype.baseToken=function(){var e=this.lineOracle;return e&&e.baseToken(this.pos)};var ct=function(e,t){this.state=e,this.lookAhead=t},ut=function(e,t,n,i){this.state=t,this.doc=e,this.line=n,this.maxLookAhead=i||0,this.baseTokens=null,this.baseTokenPos=1};function dt(e,t,n,i){var r=[e.state.modeGen],o={};At(e,t.text,e.doc.mode,n,function(e,t){return r.push(e,t)},o,i);for(var a=n.state,s=function(i){n.baseTokens=r;var s=e.state.overlays[i],l=1,c=0;n.state=!0,At(e,t.text,s.mode,n,function(e,t){for(var n=l;ce&&r.splice(l,1,e,r[l+1],i),l+=2,c=Math.min(e,i)}if(t)if(s.opaque)r.splice(n,l-n,e,"overlay "+t),l=n+2;else for(;ne.options.maxHighlightLength&&He(e.doc.mode,i.state),o=dt(e,t,i);r&&(i.state=r),t.stateAfter=i.save(!r),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),n===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function ft(e,t,n){var i=e.doc,r=e.display;if(!i.mode.startState)return new ut(i,!0,t);var o=function(e,t,n){for(var i,r,o=e.doc,a=n?-1:t-(e.doc.mode.innerMode?1e3:100),s=t;s>a;--s){if(s<=o.first)return o.first;var l=Xe(o,s-1),c=l.stateAfter;if(c&&(!n||s+(c instanceof ct?c.lookAhead:0)<=o.modeFrontier))return s;var u=F(l.text,null,e.options.tabSize);(null==r||i>u)&&(r=s-1,i=u)}return r}(e,t,n),a=o>i.first&&Xe(i,o-1).stateAfter,s=a?ut.fromSaved(i,a,o):new ut(i,Ve(i.mode),o);return i.iter(o,t,function(n){pt(e,n.text,s);var i=s.line;n.stateAfter=i==t-1||i%5==0||i>=r.viewFrom&&it.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}ut.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},ut.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},ut.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},ut.fromSaved=function(e,t,n){return t instanceof ct?new ut(e,He(e.mode,t.state),n,t.lookAhead):new ut(e,He(e.mode,t),n)},ut.prototype.save=function(e){var t=!1!==e?He(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new ct(t,this.maxLookAhead):t};var vt=function(e,t,n){this.start=e.start,this.end=e.pos,this.string=e.current(),this.type=t||null,this.state=n};function Ct(e,t,n,i){var r,o,a=e.doc,s=a.mode,l=Xe(a,(t=st(a,t)).line),c=ft(e,t.line,n),u=new Ge(l.text,e.options.tabSize,c);for(i&&(o=[]);(i||u.pose.options.maxHighlightLength?(s=!1,a&&pt(e,t,i,d.pos),d.pos=t.length,l=null):l=yt(mt(n,d,i.state,h),o),h){var f=h[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!s||u!=l){for(;c=t:o.to>t);(i||(i=[])).push(new bt(a,o.from,s?null:o.to))}}return i}(n,r,a),l=function(e,t,n){var i;if(e)for(var r=0;r=t:o.to>t)||o.from==t&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var s=null==o.from||(a.inclusiveLeft?o.from<=t:o.from0&&s)for(var y=0;yt)&&(!n||Ot(n,o.marker)<0)&&(n=o.marker)}return n}function Bt(e,t,n,i,r){var o=Xe(e,t),a=_t&&o.markedSpans;if(a)for(var s=0;s=0&&d<=0||u<=0&&d>=0)&&(u<=0&&(l.marker.inclusiveRight&&r.inclusiveLeft?tt(c.to,n)>=0:tt(c.to,n)>0)||u>=0&&(l.marker.inclusiveRight&&r.inclusiveLeft?tt(c.from,i)<=0:tt(c.from,i)<0)))return!0}}}function Ft(e){for(var t;t=Rt(e);)e=t.find(-1,!0).line;return e}function Ut(e,t){var n=Xe(e,t),i=Ft(n);return n==i?t:Ze(i)}function zt(e,t){if(t>e.lastLine())return t;var n,i=Xe(e,t);if(!Wt(e,i))return t;for(;n=Dt(i);)i=n.find(1,!0).line;return Ze(i)+1}function Wt(e,t){var n=_t&&t.markedSpans;if(n)for(var i=void 0,r=0;rt.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)})}var Xt=function(e,t,n){this.text=e,Tt(this,t),this.height=n?n(this):1};function Yt(e){e.parent=null,kt(e)}Xt.prototype.lineNo=function(){return Ze(this)},ye(Xt);var qt={},Kt={};function Zt(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?Kt:qt;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function $t(e,t){var n=L("span",null,null,l?"padding-right: .1px":null),i={pre:L("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:e,trailingSpace:!1,splitSpaces:e.getOption("lineWrapping")};t.measure={};for(var r=0;r<=(t.rest?t.rest.length:0);r++){var o=r?t.rest[r-1]:t.line,a=void 0;i.pos=0,i.addToken=Jt,Le(e.display.measure)&&(a=ue(o,e.doc.direction))&&(i.addToken=en(i.addToken,a)),i.map=[],nn(o,i,ht(e,o,t!=e.display.externalMeasured&&Ze(o))),o.styleClasses&&(o.styleClasses.bgClass&&(i.bgClass=R(o.styleClasses.bgClass,i.bgClass||"")),o.styleClasses.textClass&&(i.textClass=R(o.styleClasses.textClass,i.textClass||""))),0==i.map.length&&i.map.push(0,0,i.content.appendChild(Te(e.display.measure))),0==r?(t.measure.map=i.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(i.map),(t.measure.caches||(t.measure.caches=[])).push({}))}if(l){var s=i.content.lastChild;(/\bcm-tab\b/.test(s.className)||s.querySelector&&s.querySelector(".cm-tab"))&&(i.content.className="cm-tab-wrap-hack")}return ge(e,"renderLine",e,t.line,i.pre),i.pre.className&&(i.textClass=R(i.pre.className,i.textClass||"")),i}function Qt(e){var t=T("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t.setAttribute("aria-label",t.title),t}function Jt(e,t,n,i,r,o,l){if(t){var c,u=e.splitSpaces?function(e,t){if(e.length>1&&!/ /.test(e))return e;for(var n=t,i="",r=0;rc&&d.from<=c);h++);if(d.to>=u)return e(n,i,r,o,a,s,l);e(n,i.slice(0,d.to-c),r,o,null,s,l),o=null,i=i.slice(d.to-c),c=d.to}}}function tn(e,t,n,i){var r=!i&&n.widgetNode;r&&e.map.push(e.pos,e.pos+t,r),!i&&e.cm.display.input.needsContentAttribute&&(r||(r=e.content.appendChild(document.createElement("span"))),r.setAttribute("cm-marker",n.id)),r&&(e.cm.display.input.setUneditable(r),e.content.appendChild(r)),e.pos+=t,e.trailingSpace=!1}function nn(e,t,n){var i=e.markedSpans,r=e.text,o=0;if(i)for(var a,s,l,c,u,d,h,f=r.length,p=0,g=1,m="",v=0;;){if(v==p){l=c=u=s="",h=null,d=null,v=1/0;for(var C=[],y=void 0,A=0;Ap||_.collapsed&&I.to==p&&I.from==p)){if(null!=I.to&&I.to!=p&&v>I.to&&(v=I.to,c=""),_.className&&(l+=" "+_.className),_.css&&(s=(s?s+";":"")+_.css),_.startStyle&&I.from==p&&(u+=" "+_.startStyle),_.endStyle&&I.to==v&&(y||(y=[])).push(_.endStyle,I.to),_.title&&((h||(h={})).title=_.title),_.attributes)for(var b in _.attributes)(h||(h={}))[b]=_.attributes[b];_.collapsed&&(!d||Ot(d.marker,_)<0)&&(d=I)}else I.from>p&&v>I.from&&(v=I.from)}if(y)for(var w=0;w=f)break;for(var E=Math.min(f,v);;){if(m){var S=p+m.length;if(!d){var k=S>E?m.slice(0,E-p):m;t.addToken(t,k,a?a+l:l,u,p+k.length==v?c:"",s,h)}if(S>=E){m=m.slice(E-p),p=E;break}p=S,u=""}m=r.slice(o,o=n[g++]),a=Zt(n[g++],t.cm.options)}}else for(var T=1;Tn)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function Ln(e,t,n,i){return Pn(e,On(e,t),n,i)}function Mn(e,t){if(t>=e.display.viewFrom&&t=n.lineN&&t2&&o.push((l.bottom+c.top)/2-n.top)}}o.push(n.bottom-n.top)}}(e,t.view,t.rect),t.hasHeights=!0),(o=function(e,t,n,i){var r,o=Nn(t.map,n,i),l=o.node,c=o.start,u=o.end,d=o.collapse;if(3==l.nodeType){for(var h=0;h<4;h++){for(;c&&re(t.line.text.charAt(o.coverStart+c));)--c;for(;o.coverStart+u1}(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,i=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*i,bottom:t.bottom*i}}(e.display.measure,r))}else{var f;c>0&&(d=i="right"),r=e.options.lineWrapping&&(f=l.getClientRects()).length>1?f["right"==i?f.length-1:0]:l.getBoundingClientRect()}if(a&&s<9&&!c&&(!r||!r.left&&!r.right)){var p=l.parentNode.getClientRects()[0];r=p?{left:p.left,right:p.left+ni(e.display),top:p.top,bottom:p.bottom}:Dn}for(var g=r.top-t.rect.top,m=r.bottom-t.rect.top,v=(g+m)/2,C=t.view.measure.heights,y=0;yt)&&(r=(o=l-s)-1,t>=l&&(a="right")),null!=r){if(i=e[c+2],s==l&&n==(i.insertLeft?"left":"right")&&(a=n),"left"==n&&0==r)for(;c&&e[c-2]==e[c-3]&&e[c-1].insertLeft;)i=e[2+(c-=3)],a="left";if("right"==n&&r==l-s)for(;c=0&&(n=e[r]).left==n.right;r--);return n}function Fn(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t=i.text.length?(l=i.text.length,c="before"):l<=0&&(l=0,c="after"),!s)return a("before"==c?l-1:l,"before"==c);function u(e,t,n){var i=1==s[t].level;return a(n?e-1:e,i!=n)}var d=le(s,l,c),h=se,f=u(l,d,"before"==c);return null!=h&&(f.other=u(l,h,"before"!=c)),f}function qn(e,t){var n=0;t=st(e.doc,t),e.options.lineWrapping||(n=ni(e.display)*t.ch);var i=Xe(e.doc,t.line),r=jt(i)+bn(e.display);return{left:n,right:n,top:r,bottom:r+i.height}}function Kn(e,t,n,i,r){var o=et(e,t,n);return o.xRel=r,i&&(o.outside=i),o}function Zn(e,t,n){var i=e.doc;if((n+=e.display.viewOffset)<0)return Kn(i.first,0,null,-1,-1);var r=$e(i,n),o=i.first+i.size-1;if(r>o)return Kn(i.first+i.size-1,Xe(i,o).text.length,null,1,1);t<0&&(t=0);for(var a=Xe(i,r);;){var s=ei(e,a,r,t,n),l=Nt(a,s.ch+(s.xRel>0||s.outside>0?1:0));if(!l)return s;var c=l.find(1);if(c.line==r)return c;a=Xe(i,r=c.line)}}function $n(e,t,n,i){i-=jn(t);var r=t.text.length,o=ae(function(t){return Pn(e,n,t-1).bottom<=i},r,0);return{begin:o,end:r=ae(function(t){return Pn(e,n,t).top>i},o,r)}}function Qn(e,t,n,i){return n||(n=On(e,t)),$n(e,t,n,Vn(e,t,Pn(e,n,i),"line").top)}function Jn(e,t,n,i){return!(e.bottom<=n)&&(e.top>n||(i?e.left:e.right)>t)}function ei(e,t,n,i,r){r-=jt(t);var o=On(e,t),a=jn(t),s=0,l=t.text.length,c=!0,u=ue(t,e.doc.direction);if(u){var d=(e.options.lineWrapping?function(e,t,n,i,r,o,a){var s=$n(e,t,i,a),l=s.begin,c=s.end;/\s/.test(t.text.charAt(c-1))&&c--;for(var u=null,d=null,h=0;h=c||f.to<=l)){var p=1!=f.level,g=Pn(e,i,p?Math.min(c,f.to)-1:Math.max(l,f.from)).right,m=gm)&&(u=f,d=m)}}u||(u=r[r.length-1]);u.fromc&&(u={from:u.from,to:c,level:u.level});return u}:function(e,t,n,i,r,o,a){var s=ae(function(s){var l=r[s],c=1!=l.level;return Jn(Yn(e,et(n,c?l.to:l.from,c?"before":"after"),"line",t,i),o,a,!0)},0,r.length-1),l=r[s];if(s>0){var c=1!=l.level,u=Yn(e,et(n,c?l.from:l.to,c?"after":"before"),"line",t,i);Jn(u,o,a,!0)&&u.top>a&&(l=r[s-1])}return l})(e,t,n,o,u,i,r);s=(c=1!=d.level)?d.from:d.to-1,l=c?d.to:d.from-1}var h,f,p=null,g=null,m=ae(function(t){var n=Pn(e,o,t);return n.top+=a,n.bottom+=a,!!Jn(n,i,r,!1)&&(n.top<=r&&n.left<=i&&(p=t,g=n),!0)},s,l),v=!1;if(g){var C=i-g.left=A.bottom?1:0}return Kn(n,m=oe(t.text,m,1),f,v,i-h)}function ti(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Rn){Rn=T("pre",null,"CodeMirror-line-like");for(var t=0;t<49;++t)Rn.appendChild(document.createTextNode("x")),Rn.appendChild(T("br"));Rn.appendChild(document.createTextNode("x"))}k(e.measure,Rn);var n=Rn.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),S(e.measure),n||1}function ni(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=T("span","xxxxxxxxxx"),n=T("pre",[t],"CodeMirror-line-like");k(e.measure,n);var i=t.getBoundingClientRect(),r=(i.right-i.left)/10;return r>2&&(e.cachedCharWidth=r),r||10}function ii(e){for(var t=e.display,n={},i={},r=t.gutters.clientLeft,o=t.gutters.firstChild,a=0;o;o=o.nextSibling,++a){var s=e.display.gutterSpecs[a].className;n[s]=o.offsetLeft+o.clientLeft+r,i[s]=o.clientWidth}return{fixedPos:ri(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:i,wrapperWidth:t.wrapper.clientWidth}}function ri(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function oi(e){var t=ti(e.display),n=e.options.lineWrapping,i=n&&Math.max(5,e.display.scroller.clientWidth/ni(e.display)-3);return function(r){if(Wt(e.doc,r))return 0;var o=0;if(r.widgets)for(var a=0;a0&&(l=Xe(e.doc,c.line).text).length==c.ch){var u=F(l,l.length,e.options.tabSize)-l.length;c=et(c.line,Math.max(0,Math.round((o-xn(e.display).left)/ni(e.display))-u))}return c}function li(e,t){if(t>=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var n=e.display.view,i=0;it)&&(r.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=r.viewTo)_t&&Ut(e.doc,t)r.viewFrom?di(e):(r.viewFrom+=i,r.viewTo+=i);else if(t<=r.viewFrom&&n>=r.viewTo)di(e);else if(t<=r.viewFrom){var o=hi(e,n,n+i,1);o?(r.view=r.view.slice(o.index),r.viewFrom=o.lineN,r.viewTo+=i):di(e)}else if(n>=r.viewTo){var a=hi(e,t,t,-1);a?(r.view=r.view.slice(0,a.index),r.viewTo=a.lineN):di(e)}else{var s=hi(e,t,t,-1),l=hi(e,n,n+i,1);s&&l?(r.view=r.view.slice(0,s.index).concat(on(e,s.lineN,l.lineN)).concat(r.view.slice(l.index)),r.viewTo+=i):di(e)}var c=r.externalMeasured;c&&(n=r.lineN&&t=i.viewTo)){var o=i.view[li(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==z(a,n)&&a.push(n)}}}function di(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function hi(e,t,n,i){var r,o=li(e,t),a=e.display.view;if(!_t||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var s=e.display.viewFrom,l=0;l0){if(o==a.length-1)return null;r=s+a[o].size-t,o++}else r=s-t;t+=r,n+=r}for(;Ut(e.doc,n)!=n;){if(o==(i<0?0:a.length-1))return null;n+=i*a[o-(i<0?1:0)].size,o+=i}return{index:o,lineN:n}}function fi(e){for(var t=e.display.view,n=0,i=0;i=e.display.viewTo||s.to().linet||t==n&&a.to==t)&&(i(Math.max(a.from,t),Math.min(a.to,n),1==a.level?"rtl":"ltr",o),r=!0)}r||i(t,n,"ltr")}(g,n||0,null==i?h:i,function(e,t,r,d){var m="ltr"==r,v=f(e,m?"left":"right"),C=f(t-1,m?"right":"left"),y=null==n&&0==e,A=null==i&&t==h,I=0==d,_=!g||d==g.length-1;if(C.top-v.top<=3){var b=(c?A:y)&&_,w=(c?y:A)&&I?s:(m?v:C).left,x=b?l:(m?C:v).right;u(w,v.top,x-w,v.bottom)}else{var E,S,k,T;m?(E=c&&y&&I?s:v.left,S=c?l:p(e,r,"before"),k=c?s:p(t,r,"after"),T=c&&A&&_?l:C.right):(E=c?p(e,r,"before"):s,S=!c&&y&&I?l:v.right,k=!c&&A&&_?s:C.left,T=c?p(t,r,"after"):l),u(E,v.top,S-E,v.bottom),v.bottom0?t.blinker=setInterval(function(){return t.cursorDiv.style.visibility=(n=!n)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function Ai(e){e.state.focused||(e.display.input.focus(),_i(e))}function Ii(e){e.state.delayingBlurEvent=!0,setTimeout(function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,bi(e))},100)}function _i(e,t){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(ge(e,"focus",e,t),e.state.focused=!0,P(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),l&&setTimeout(function(){return e.display.input.reset(!0)},20)),e.display.input.receivedFocus()),yi(e))}function bi(e,t){e.state.delayingBlurEvent||(e.state.focused&&(ge(e,"blur",e,t),e.state.focused=!1,E(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout(function(){e.state.focused||(e.display.shift=!1)},150))}function wi(e){for(var t=e.display,n=t.lineDiv.offsetTop,i=0;i.005||h<-.005)&&(Ke(r.line,l),xi(r.line),r.rest))for(var f=0;fe.display.sizerWidth){var p=Math.ceil(c/ni(e.display));p>e.display.maxLineLength&&(e.display.maxLineLength=p,e.display.maxLine=r.line,e.display.maxLineChanged=!0)}}}}function xi(e){if(e.widgets)for(var t=0;t=a&&(o=$e(t,jt(Xe(t,l))-e.wrapper.clientHeight),a=l)}return{from:o,to:Math.max(a,o+1)}}function Si(e,t){var n=e.display,i=ti(e.display);t.top<0&&(t.top=0);var r=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:n.scroller.scrollTop,o=kn(e),a={};t.bottom-t.top>o&&(t.bottom=t.top+o);var s=e.doc.height+wn(n),l=t.tops-i;if(t.topr+o){var u=Math.min(t.top,(c?s:t.bottom)-o);u!=r&&(a.scrollTop=u)}var d=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:n.scroller.scrollLeft,h=Sn(e)-(e.options.fixedGutter?n.gutters.offsetWidth:0),f=t.right-t.left>h;return f&&(t.right=t.left+h),t.left<10?a.scrollLeft=0:t.lefth+d-3&&(a.scrollLeft=t.right+(f?0:10)-h),a}function ki(e,t){null!=t&&(Mi(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function Ti(e){Mi(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function Li(e,t,n){null==t&&null==n||Mi(e),null!=t&&(e.curOp.scrollLeft=t),null!=n&&(e.curOp.scrollTop=n)}function Mi(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,Oi(e,qn(e,t.from),qn(e,t.to),t.margin))}function Oi(e,t,n,i){var r=Si(e,{left:Math.min(t.left,n.left),top:Math.min(t.top,n.top)-i,right:Math.max(t.right,n.right),bottom:Math.max(t.bottom,n.bottom)+i});Li(e,r.scrollLeft,r.scrollTop)}function Pi(e,t){Math.abs(e.doc.scrollTop-t)<2||(n||or(e,{top:t}),Ri(e,t,!0),n&&or(e),er(e,100))}function Ri(e,t,n){t=Math.max(0,Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t)),(e.display.scroller.scrollTop!=t||n)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function Di(e,t,n,i){t=Math.max(0,Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth)),(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!i||(e.doc.scrollLeft=t,lr(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function Ni(e){var t=e.display,n=t.gutters.offsetWidth,i=Math.round(e.doc.height+wn(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:i,scrollHeight:i+En(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}var Bi=function(e,t,n){this.cm=n;var i=this.vert=T("div",[T("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),r=this.horiz=T("div",[T("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");i.tabIndex=r.tabIndex=-1,e(i),e(r),he(i,"scroll",function(){i.clientHeight&&t(i.scrollTop,"vertical")}),he(r,"scroll",function(){r.clientWidth&&t(r.scrollLeft,"horizontal")}),this.checkedZeroWidth=!1,a&&s<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};Bi.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,n=e.scrollHeight>e.clientHeight+1,i=e.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=t?i+"px":"0";var r=e.viewHeight-(t?i:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+r)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=n?i+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(n?i:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&e.clientHeight>0&&(0==i&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?i:0,bottom:t?i:0}},Bi.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},Bi.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},Bi.prototype.zeroWidthHack=function(){var e=C&&!f?"12px":"18px";this.horiz.style.height=this.vert.style.width=e,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new U,this.disableVert=new U},Bi.prototype.enableZeroWidthBar=function(e,t,n){e.style.pointerEvents="auto",t.set(1e3,function i(){var r=e.getBoundingClientRect();("vert"==n?document.elementFromPoint(r.right-1,(r.top+r.bottom)/2):document.elementFromPoint((r.right+r.left)/2,r.bottom-1))!=e?e.style.pointerEvents="none":t.set(1e3,i)})},Bi.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};var Fi=function(){};function Ui(e,t){t||(t=Ni(e));var n=e.display.barWidth,i=e.display.barHeight;zi(e,t);for(var r=0;r<4&&n!=e.display.barWidth||i!=e.display.barHeight;r++)n!=e.display.barWidth&&e.options.lineWrapping&&wi(e),zi(e,Ni(e)),n=e.display.barWidth,i=e.display.barHeight}function zi(e,t){var n=e.display,i=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=i.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=i.bottom)+"px",n.heightForcer.style.borderBottom=i.bottom+"px solid transparent",i.right&&i.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=i.bottom+"px",n.scrollbarFiller.style.width=i.right+"px"):n.scrollbarFiller.style.display="",i.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=i.bottom+"px",n.gutterFiller.style.width=t.gutterWidth+"px"):n.gutterFiller.style.display=""}Fi.prototype.update=function(){return{bottom:0,right:0}},Fi.prototype.setScrollLeft=function(){},Fi.prototype.setScrollTop=function(){},Fi.prototype.clear=function(){};var Wi={native:Bi,null:Fi};function Hi(e){e.display.scrollbars&&(e.display.scrollbars.clear(),e.display.scrollbars.addClass&&E(e.display.wrapper,e.display.scrollbars.addClass)),e.display.scrollbars=new Wi[e.options.scrollbarStyle](function(t){e.display.wrapper.insertBefore(t,e.display.scrollbarFiller),he(t,"mousedown",function(){e.state.focused&&setTimeout(function(){return e.display.input.focus()},0)}),t.setAttribute("cm-not-content","true")},function(t,n){"horizontal"==n?Di(e,t):Pi(e,t)},e),e.display.scrollbars.addClass&&P(e.display.wrapper,e.display.scrollbars.addClass)}var ji=0;function Vi(e){var t;e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++ji},t=e.curOp,an?an.ops.push(t):t.ownsGroup=an={ops:[t],delayedCallbacks:[]}}function Gi(e){var t=e.curOp;t&&function(e,t){var n=e.ownsGroup;if(n)try{!function(e){var t=e.delayedCallbacks,n=0;do{for(;n=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new nr(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function Yi(e){var t=e.cm,n=t.display;e.updatedDisplay&&wi(t),e.barMeasure=Ni(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=Ln(t,n.maxLine,n.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+En(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-Sn(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=n.input.prepareSelection())}function qi(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft(window.innerHeight||document.documentElement.clientHeight)&&(r=!1),null!=r&&!p){var o=T("div","​",null,"position: absolute;\n top: "+(t.top-n.viewOffset-bn(e.display))+"px;\n height: "+(t.bottom-t.top+En(e)+n.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(r),e.display.lineSpace.removeChild(o)}}}(t,function(e,t,n,i){var r;null==i&&(i=0),e.options.lineWrapping||t!=n||(n="before"==(t=t.ch?et(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t).sticky?et(t.line,t.ch+1,"before"):t);for(var o=0;o<5;o++){var a=!1,s=Yn(e,t),l=n&&n!=t?Yn(e,n):s,c=Si(e,r={left:Math.min(s.left,l.left),top:Math.min(s.top,l.top)-i,right:Math.max(s.left,l.left),bottom:Math.max(s.bottom,l.bottom)+i}),u=e.doc.scrollTop,d=e.doc.scrollLeft;if(null!=c.scrollTop&&(Pi(e,c.scrollTop),Math.abs(e.doc.scrollTop-u)>1&&(a=!0)),null!=c.scrollLeft&&(Di(e,c.scrollLeft),Math.abs(e.doc.scrollLeft-d)>1&&(a=!0)),!a)break}return r}(t,st(i,e.scrollToPos.from),st(i,e.scrollToPos.to),e.scrollToPos.margin));var r=e.maybeHiddenMarkers,o=e.maybeUnhiddenMarkers;if(r)for(var a=0;a=e.display.viewTo)){var n=+new Date+e.options.workTime,i=ft(e,t.highlightFrontier),r=[];t.iter(i.line,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(i.line>=e.display.viewFrom){var a=o.styles,s=o.text.length>e.options.maxHighlightLength?He(t.mode,i.state):null,l=dt(e,o,i,!0);s&&(i.state=s),o.styles=l.styles;var c=o.styleClasses,u=l.classes;u?o.styleClasses=u:c&&(o.styleClasses=null);for(var d=!a||a.length!=o.styles.length||c!=u&&(!c||!u||c.bgClass!=u.bgClass||c.textClass!=u.textClass),h=0;!d&&hn)return er(e,e.options.workDelay),!0}),t.highlightFrontier=i.line,t.modeFrontier=Math.max(t.modeFrontier,i.line),r.length&&Zi(e,function(){for(var t=0;t=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==fi(e))return!1;cr(e)&&(di(e),t.dims=ii(e));var r=i.first+i.size,o=Math.max(t.visible.from-e.options.viewportMargin,i.first),a=Math.min(r,t.visible.to+e.options.viewportMargin);n.viewFroma&&n.viewTo-a<20&&(a=Math.min(r,n.viewTo)),_t&&(o=Ut(e.doc,o),a=zt(e.doc,a));var s=o!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;!function(e,t,n){var i=e.display;0==i.view.length||t>=i.viewTo||n<=i.viewFrom?(i.view=on(e,t,n),i.viewFrom=t):(i.viewFrom>t?i.view=on(e,t,i.viewFrom).concat(i.view):i.viewFromn&&(i.view=i.view.slice(0,li(e,n)))),i.viewTo=n}(e,o,a),n.viewOffset=jt(Xe(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var c=fi(e);if(!s&&0==c&&!t.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=function(e){if(e.hasFocus())return null;var t=O();if(!t||!M(e.display.lineDiv,t))return null;var n={activeElt:t};if(window.getSelection){var i=window.getSelection();i.anchorNode&&i.extend&&M(e.display.lineDiv,i.anchorNode)&&(n.anchorNode=i.anchorNode,n.anchorOffset=i.anchorOffset,n.focusNode=i.focusNode,n.focusOffset=i.focusOffset)}return n}(e);return c>4&&(n.lineDiv.style.display="none"),function(e,t,n){var i=e.display,r=e.options.lineNumbers,o=i.lineDiv,a=o.firstChild;function s(t){var n=t.nextSibling;return l&&C&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var c=i.view,u=i.viewFrom,d=0;d-1&&(f=!1),un(e,h,u,n)),f&&(S(h.lineNumber),h.lineNumber.appendChild(document.createTextNode(Je(e.options,u)))),a=h.node.nextSibling}else{var p=vn(e,h,u,n);o.insertBefore(p,a)}u+=h.size}for(;a;)a=s(a)}(e,n.updateLineNumbers,t.dims),c>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,function(e){if(e&&e.activeElt&&e.activeElt!=O()&&(e.activeElt.focus(),e.anchorNode&&M(document.body,e.anchorNode)&&M(document.body,e.focusNode))){var t=window.getSelection(),n=document.createRange();n.setEnd(e.anchorNode,e.anchorOffset),n.collapse(!1),t.removeAllRanges(),t.addRange(n),t.extend(e.focusNode,e.focusOffset)}}(u),S(n.cursorDiv),S(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,s&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,er(e,400)),n.updateLineNumbers=null,!0}function rr(e,t){for(var n=t.viewport,i=!0;;i=!1){if(i&&e.options.lineWrapping&&t.oldDisplayWidth!=Sn(e))i&&(t.visible=Ei(e.display,e.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(e.doc.height+wn(e.display)-kn(e),n.top)}),t.visible=Ei(e.display,e.doc,n),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!ir(e,t))break;wi(e);var r=Ni(e);pi(e),Ui(e,r),sr(e,r),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function or(e,t){var n=new nr(e,t);if(ir(e,n)){wi(e),rr(e,n);var i=Ni(e);pi(e),Ui(e,i),sr(e,i),n.finish()}}function ar(e){var t=e.gutters.offsetWidth;e.sizer.style.marginLeft=t+"px"}function sr(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+En(e)+"px"}function lr(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var i=ri(t)-t.scroller.scrollLeft+e.doc.scrollLeft,r=t.gutters.offsetWidth,o=i+"px",a=0;as.clientWidth,u=s.scrollHeight>s.clientHeight;if(r&&c||o&&u){if(o&&C&&l)e:for(var h=t.target,f=a.view;h!=s;h=h.parentNode)for(var p=0;p=0&&tt(e,i.to())<=0)return n}return-1};var yr=function(e,t){this.anchor=e,this.head=t};function Ar(e,t,n){var i=e&&e.options.selectionsMayTouch,r=t[n];t.sort(function(e,t){return tt(e.from(),t.from())}),n=z(t,r);for(var o=1;o0:l>=0){var c=ot(s.from(),a.from()),u=rt(s.to(),a.to()),d=s.empty()?a.from()==a.head:s.from()==s.head;o<=n&&--n,t.splice(--o,2,new yr(d?u:c,d?c:u))}}return new Cr(t,n)}function Ir(e,t){return new Cr([new yr(e,t||e)],0)}function _r(e){return e.text?et(e.from.line+e.text.length-1,K(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function br(e,t){if(tt(e,t.from)<0)return e;if(tt(e,t.to)<=0)return _r(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,i=e.ch;return e.line==t.to.line&&(i+=_r(t).ch-t.to.ch),et(n,i)}function wr(e,t){for(var n=[],i=0;i1&&e.remove(s.line+1,p-1),e.insert(s.line+1,v)}ln(e,"change",e,t)}function Lr(e,t,n){!function e(i,r,o){if(i.linked)for(var a=0;as-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(o=function(e,t){return t?(Dr(e.done),K(e.done)):e.done.length&&!K(e.done).ranges?K(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),K(e.done)):void 0}(r,r.lastOp==i)))a=K(o.changes),0==tt(t.from,t.to)&&0==tt(t.from,a.to)?a.to=_r(t):o.changes.push(Rr(e,t));else{var l=K(r.done);for(l&&l.ranges||Fr(e.sel,r.done),o={changes:[Rr(e,t)],generation:r.generation},r.done.push(o);r.done.length>r.undoDepth;)r.done.shift(),r.done[0].ranges||r.done.shift()}r.done.push(n),r.generation=++r.maxGeneration,r.lastModTime=r.lastSelTime=s,r.lastOp=r.lastSelOp=i,r.lastOrigin=r.lastSelOrigin=t.origin,a||ge(e,"historyAdded")}function Br(e,t,n,i){var r=e.history,o=i&&i.origin;n==r.lastSelOp||o&&r.lastSelOrigin==o&&(r.lastModTime==r.lastSelTime&&r.lastOrigin==o||function(e,t,n,i){var r=t.charAt(0);return"*"==r||"+"==r&&n.ranges.length==i.ranges.length&&n.somethingSelected()==i.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}(e,o,K(r.done),t))?r.done[r.done.length-1]=t:Fr(t,r.done),r.lastSelTime=+new Date,r.lastSelOrigin=o,r.lastSelOp=n,i&&!1!==i.clearRedo&&Dr(r.undone)}function Fr(e,t){var n=K(t);n&&n.ranges&&n.equals(e)||t.push(e)}function Ur(e,t,n,i){var r=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,i),function(n){n.markedSpans&&((r||(r=t["spans_"+e.id]={}))[o]=n.markedSpans),++o})}function zr(e){if(!e)return null;for(var t,n=0;n-1&&(K(s)[d]=c[d],delete c[d])}}}return i}function jr(e,t,n,i){if(i){var r=e.anchor;if(n){var o=tt(t,r)<0;o!=tt(n,r)<0?(r=t,t=n):o!=tt(t,n)<0&&(t=n)}return new yr(r,t)}return new yr(n||t,t)}function Vr(e,t,n,i,r){null==r&&(r=e.cm&&(e.cm.display.shift||e.extend)),Kr(e,new Cr([jr(e.sel.primary(),t,n,r)],0),i)}function Gr(e,t,n){for(var i=[],r=e.cm&&(e.cm.display.shift||e.extend),o=0;o=t.ch:s.to>t.ch))){if(r&&(ge(l,"beforeCursorEnter"),l.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!l.atomic)continue;if(n){var d=l.find(i<0?1:-1),h=void 0;if((i<0?u:c)&&(d=no(e,d,-i,d&&d.line==t.line?o:null)),d&&d.line==t.line&&(h=tt(d,n))&&(i<0?h<0:h>0))return eo(e,d,t,i,r)}var f=l.find(i<0?-1:1);return(i<0?c:u)&&(f=no(e,f,i,f.line==t.line?o:null)),f?eo(e,f,t,i,r):null}}return t}function to(e,t,n,i,r){var o=i||1,a=eo(e,t,n,o,r)||!r&&eo(e,t,n,o,!0)||eo(e,t,n,-o,r)||!r&&eo(e,t,n,-o,!0);return a||(e.cantEdit=!0,et(e.first,0))}function no(e,t,n,i){return n<0&&0==t.ch?t.line>e.first?st(e,et(t.line-1)):null:n>0&&t.ch==(i||Xe(e,t.line)).text.length?t.line0)){var u=[l,1],d=tt(c.from,s.from),h=tt(c.to,s.to);(d<0||!a.inclusiveLeft&&!d)&&u.push({from:c.from,to:s.from}),(h>0||!a.inclusiveRight&&!h)&&u.push({from:s.to,to:c.to}),r.splice.apply(r,u),l+=u.length-3}}return r}(e,t.from,t.to);if(i)for(var r=i.length-1;r>=0;--r)ao(e,{from:i[r].from,to:i[r].to,text:r?[""]:t.text,origin:t.origin});else ao(e,t)}}function ao(e,t){if(1!=t.text.length||""!=t.text[0]||0!=tt(t.from,t.to)){var n=wr(e,t);Nr(e,t,n,e.cm?e.cm.curOp.id:NaN),co(e,t,n,Et(e,t));var i=[];Lr(e,function(e,n){n||-1!=z(i,e.history)||(po(e.history,t),i.push(e.history)),co(e,t,null,Et(e,t))})}}function so(e,t,n){var i=e.cm&&e.cm.state.suppressEdits;if(!i||n){for(var r,o=e.history,a=e.sel,s="undo"==t?o.done:o.undone,l="undo"==t?o.undone:o.done,c=0;c=0;--f){var p=h(f);if(p)return p.v}}}}function lo(e,t){if(0!=t&&(e.first+=t,e.sel=new Cr(Z(e.sel.ranges,function(e){return new yr(et(e.anchor.line+t,e.anchor.ch),et(e.head.line+t,e.head.ch))}),e.sel.primIndex),e.cm)){ci(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,i=n.viewFrom;ie.lastLine())){if(t.from.lineo&&(t={from:t.from,to:et(o,Xe(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=Ye(e,t.from,t.to),n||(n=wr(e,t)),e.cm?function(e,t,n){var i=e.doc,r=e.display,o=t.from,a=t.to,s=!1,l=o.line;e.options.lineWrapping||(l=Ze(Ft(Xe(i,o.line))),i.iter(l,a.line+1,function(e){if(e==r.maxLine)return s=!0,!0}));i.sel.contains(t.from,t.to)>-1&&ve(e);Tr(i,t,n,oi(e)),e.options.lineWrapping||(i.iter(l,o.line+t.text.length,function(e){var t=Vt(e);t>r.maxLineLength&&(r.maxLine=e,r.maxLineLength=t,r.maxLineChanged=!0,s=!1)}),s&&(e.curOp.updateMaxLine=!0));(function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontiern;i--){var r=Xe(e,i).stateAfter;if(r&&(!(r instanceof ct)||i+r.lookAhead1||!(this.children[0]instanceof mo))){var s=[];this.collapse(s),this.children=[new mo(s)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t50){for(var a=r.lines.length%25+25,s=a;s10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var i=0;i0||0==a&&!1!==o.clearWhenEmpty)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=L("span",[o.replacedWith],"CodeMirror-widget"),i.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true"),i.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(Bt(e,t.line,t,n,o)||t.line!=n.line&&Bt(e,n.line,t,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");_t=!0}o.addToHistory&&Nr(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var s,l=t.line,c=e.cm;if(e.iter(l,n.line+1,function(e){c&&o.collapsed&&!c.options.lineWrapping&&Ft(e)==c.display.maxLine&&(s=!0),o.collapsed&&l!=t.line&&Ke(e,0),function(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}(e,new bt(o,l==t.line?t.ch:null,l==n.line?n.ch:null)),++l}),o.collapsed&&e.iter(t.line,n.line+1,function(t){Wt(e,t)&&Ke(t,0)}),o.clearOnEnter&&he(o,"beforeCursorEnter",function(){return o.clear()}),o.readOnly&&(It=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++Ao,o.atomic=!0),c){if(s&&(c.curOp.updateMaxLine=!0),o.collapsed)ci(c,t.line,n.line+1);else if(o.className||o.startStyle||o.endStyle||o.css||o.attributes||o.title)for(var u=t.line;u<=n.line;u++)ui(c,u,"text");o.atomic&&Qr(c.doc),ln(c,"markerAdded",c,o)}return o}Io.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Vi(e),Ce(this,"clear")){var n=this.find();n&&ln(this,"clear",n.from,n.to)}for(var i=null,r=null,o=0;oe.display.maxLineLength&&(e.display.maxLine=c,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=i&&e&&this.collapsed&&ci(e,i,r+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&Qr(e.doc)),e&&ln(e,"markerCleared",e,this,i,r),t&&Gi(e),this.parent&&this.parent.clear()}},Io.prototype.find=function(e,t){var n,i;null==e&&"bookmark"==this.type&&(e=1);for(var r=0;r=0;l--)oo(this,i[l]);s?qr(this,s):this.cm&&Ti(this.cm)}),undo:Ji(function(){so(this,"undo")}),redo:Ji(function(){so(this,"redo")}),undoSelection:Ji(function(){so(this,"undo",!0)}),redoSelection:Ji(function(){so(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,i=0;i=e.ch)&&t.push(r.marker.parent||r.marker)}return t},findMarks:function(e,t,n){e=st(this,e),t=st(this,t);var i=[],r=e.line;return this.iter(e.line,t.line+1,function(o){var a=o.markedSpans;if(a)for(var s=0;s=l.to||null==l.from&&r!=e.line||null!=l.from&&r==t.line&&l.from>=t.ch||n&&!n(l.marker)||i.push(l.marker.parent||l.marker)}++r}),i},getAllMarks:function(){var e=[];return this.iter(function(t){var n=t.markedSpans;if(n)for(var i=0;ie)return t=e,!0;e-=o,++n}),st(this,et(n,t))},indexFromPos:function(e){var t=(e=st(this,e)).ch;if(e.linet&&(t=e.from),null!=e.to&&e.to-1)return t.state.draggingText(e),void setTimeout(function(){return t.display.input.focus()},20);try{var d=e.dataTransfer.getData("Text");if(d){var h;if(t.state.draggingText&&!t.state.draggingText.copy&&(h=t.listSelections()),Zr(t.doc,Ir(n,n)),h)for(var f=0;f=0;t--)uo(e.doc,"",i[t].from,i[t].to,"+delete");Ti(e)})}function qo(e,t,n){var i=oe(e.text,t+n,n);return i<0||i>e.text.length?null:i}function Ko(e,t,n){var i=qo(e,t.ch,n);return null==i?null:new et(t.line,i,n<0?"after":"before")}function Zo(e,t,n,i,r){if(e){"rtl"==t.doc.direction&&(r=-r);var o=ue(n,t.doc.direction);if(o){var a,s=r<0?K(o):o[0],l=r<0==(1==s.level)?"after":"before";if(s.level>0||"rtl"==t.doc.direction){var c=On(t,n);a=r<0?n.text.length-1:0;var u=Pn(t,c,a).top;a=ae(function(e){return Pn(t,c,e).top==u},r<0==(1==s.level)?s.from:s.to-1,a),"before"==l&&(a=qo(n,a,1))}else a=r<0?s.to:s.from;return new et(i,a,l)}}return new et(i,r<0?n.text.length:0,r<0?"before":"after")}Uo.basic={Left:"goCharLeft",Right:"goCharRight",Up:"goLineUp",Down:"goLineDown",End:"goLineEnd",Home:"goLineStartSmart",PageUp:"goPageUp",PageDown:"goPageDown",Delete:"delCharAfter",Backspace:"delCharBefore","Shift-Backspace":"delCharBefore",Tab:"defaultTab","Shift-Tab":"indentAuto",Enter:"newlineAndIndent",Insert:"toggleOverwrite",Esc:"singleSelection"},Uo.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","Ctrl-Left":"goGroupLeft","Ctrl-Right":"goGroupRight","Alt-Left":"goLineStart","Alt-Right":"goLineEnd","Ctrl-Backspace":"delGroupBefore","Ctrl-Delete":"delGroupAfter","Ctrl-S":"save","Ctrl-F":"find","Ctrl-G":"findNext","Shift-Ctrl-G":"findPrev","Shift-Ctrl-F":"replace","Shift-Ctrl-R":"replaceAll","Ctrl-[":"indentLess","Ctrl-]":"indentMore","Ctrl-U":"undoSelection","Shift-Ctrl-U":"redoSelection","Alt-U":"redoSelection",fallthrough:"basic"},Uo.emacsy={"Ctrl-F":"goCharRight","Ctrl-B":"goCharLeft","Ctrl-P":"goLineUp","Ctrl-N":"goLineDown","Alt-F":"goWordRight","Alt-B":"goWordLeft","Ctrl-A":"goLineStart","Ctrl-E":"goLineEnd","Ctrl-V":"goPageDown","Shift-Ctrl-V":"goPageUp","Ctrl-D":"delCharAfter","Ctrl-H":"delCharBefore","Alt-D":"delWordAfter","Alt-Backspace":"delWordBefore","Ctrl-K":"killLine","Ctrl-T":"transposeChars","Ctrl-O":"openLine"},Uo.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","Alt-Backspace":"delGroupBefore","Ctrl-Alt-Backspace":"delGroupAfter","Alt-Delete":"delGroupAfter","Cmd-S":"save","Cmd-F":"find","Cmd-G":"findNext","Shift-Cmd-G":"findPrev","Cmd-Alt-F":"replace","Shift-Cmd-Alt-F":"replaceAll","Cmd-[":"indentLess","Cmd-]":"indentMore","Cmd-Backspace":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},Uo.default=C?Uo.macDefault:Uo.pcDefault;var $o={selectAll:io,singleSelection:function(e){return e.setSelection(e.getCursor("anchor"),e.getCursor("head"),j)},killLine:function(e){return Yo(e,function(t){if(t.empty()){var n=Xe(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line0)r=new et(r.line,r.ch+1),e.replaceRange(o.charAt(r.ch-1)+o.charAt(r.ch-2),et(r.line,r.ch-2),r,"+transpose");else if(r.line>e.doc.first){var a=Xe(e.doc,r.line-1).text;a&&(r=new et(r.line,1),e.replaceRange(o.charAt(0)+e.doc.lineSeparator()+a.charAt(a.length-1),et(r.line-1,a.length-1),r,"+transpose"))}n.push(new yr(r,r))}e.setSelections(n)})},newlineAndIndent:function(e){return Zi(e,function(){for(var t=e.listSelections(),n=t.length-1;n>=0;n--)e.replaceRange(e.doc.lineSeparator(),t[n].anchor,t[n].head,"+input");t=e.listSelections();for(var i=0;i-1&&(tt((r=c.ranges[r]).from(),t)<0||t.xRel>0)&&(tt(r.to(),t)>0||t.xRel<0)?function(e,t,n,i){var r=e.display,o=!1,c=$i(e,function(t){l&&(r.scroller.draggable=!1),e.state.draggingText=!1,pe(r.wrapper.ownerDocument,"mouseup",c),pe(r.wrapper.ownerDocument,"mousemove",u),pe(r.scroller,"dragstart",d),pe(r.scroller,"drop",c),o||(Ae(t),i.addNew||Vr(e.doc,n,null,null,i.extend),l||a&&9==s?setTimeout(function(){r.wrapper.ownerDocument.body.focus(),r.input.focus()},20):r.input.focus())}),u=function(e){o=o||Math.abs(t.clientX-e.clientX)+Math.abs(t.clientY-e.clientY)>=10},d=function(){return o=!0};l&&(r.scroller.draggable=!0);e.state.draggingText=c,c.copy=!i.moveOnDrag,r.scroller.dragDrop&&r.scroller.dragDrop();he(r.wrapper.ownerDocument,"mouseup",c),he(r.wrapper.ownerDocument,"mousemove",u),he(r.scroller,"dragstart",d),he(r.scroller,"drop",c),Ii(e),setTimeout(function(){return r.input.focus()},20)}(e,i,t,o):function(e,t,n,i){var r=e.display,o=e.doc;Ae(t);var a,s,l=o.sel,c=l.ranges;i.addNew&&!i.extend?(s=o.sel.contains(n),a=s>-1?c[s]:new yr(n,n)):(a=o.sel.primary(),s=o.sel.primIndex);if("rectangle"==i.unit)i.addNew||(a=new yr(n,n)),n=si(e,t,!0,!0),s=-1;else{var u=fa(e,n,i.unit);a=i.extend?jr(a,u.anchor,u.head,i.extend):u}i.addNew?-1==s?(s=c.length,Kr(o,Ar(e,c.concat([a]),s),{scroll:!1,origin:"*mouse"})):c.length>1&&c[s].empty()&&"char"==i.unit&&!i.extend?(Kr(o,Ar(e,c.slice(0,s).concat(c.slice(s+1)),0),{scroll:!1,origin:"*mouse"}),l=o.sel):Xr(o,s,a,V):(s=0,Kr(o,new Cr([a],0),V),l=o.sel);var d=n;function h(t){if(0!=tt(d,t))if(d=t,"rectangle"==i.unit){for(var r=[],c=e.options.tabSize,u=F(Xe(o,n.line).text,n.ch,c),h=F(Xe(o,t.line).text,t.ch,c),f=Math.min(u,h),p=Math.max(u,h),g=Math.min(n.line,t.line),m=Math.min(e.lastLine(),Math.max(n.line,t.line));g<=m;g++){var v=Xe(o,g).text,C=X(v,f,c);f==p?r.push(new yr(et(g,C),et(g,C))):v.length>C&&r.push(new yr(et(g,C),et(g,X(v,p,c))))}r.length||r.push(new yr(n,n)),Kr(o,Ar(e,l.ranges.slice(0,s).concat(r),s),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var y,A=a,I=fa(e,t,i.unit),_=A.anchor;tt(I.anchor,_)>0?(y=I.head,_=ot(A.from(),I.anchor)):(y=I.anchor,_=rt(A.to(),I.head));var b=l.ranges.slice(0);b[s]=function(e,t){var n=t.anchor,i=t.head,r=Xe(e.doc,n.line);if(0==tt(n,i)&&n.sticky==i.sticky)return t;var o=ue(r);if(!o)return t;var a=le(o,n.ch,n.sticky),s=o[a];if(s.from!=n.ch&&s.to!=n.ch)return t;var l,c=a+(s.from==n.ch==(1!=s.level)?0:1);if(0==c||c==o.length)return t;if(i.line!=n.line)l=(i.line-n.line)*("ltr"==e.doc.direction?1:-1)>0;else{var u=le(o,i.ch,i.sticky),d=u-a||(i.ch-n.ch)*(1==s.level?-1:1);l=u==c-1||u==c?d<0:d>0}var h=o[c+(l?-1:0)],f=l==(1==h.level),p=f?h.from:h.to,g=f?"after":"before";return n.ch==p&&n.sticky==g?t:new yr(new et(n.line,p,g),i)}(e,new yr(st(o,_),y)),Kr(o,Ar(e,b,s),V)}}var f=r.wrapper.getBoundingClientRect(),p=0;function g(t){e.state.selectingText=!1,p=1/0,t&&(Ae(t),r.input.focus()),pe(r.wrapper.ownerDocument,"mousemove",m),pe(r.wrapper.ownerDocument,"mouseup",v),o.history.lastSelOrigin=null}var m=$i(e,function(t){0!==t.buttons&&xe(t)?function t(n){var a=++p;var s=si(e,n,!0,"rectangle"==i.unit);if(!s)return;if(0!=tt(s,d)){e.curOp.focus=O(),h(s);var l=Ei(r,o);(s.line>=l.to||s.linef.bottom?20:0;c&&setTimeout($i(e,function(){p==a&&(r.scroller.scrollTop+=c,t(n))}),50)}}(t):g(t)}),v=$i(e,g);e.state.selectingText=v,he(r.wrapper.ownerDocument,"mousemove",m),he(r.wrapper.ownerDocument,"mouseup",v)}(e,i,t,o)}(t,i,o,e):we(e)==n.scroller&&Ae(e):2==r?(i&&Vr(t.doc,i),setTimeout(function(){return n.input.focus()},20)):3==r&&(b?t.display.input.onContextMenu(e):Ii(t)))}}function fa(e,t,n){if("char"==n)return new yr(t,t);if("word"==n)return e.findWordAt(t);if("line"==n)return new yr(et(t.line,0),st(e.doc,et(t.line+1,0)));var i=n(e,t);return new yr(i.from,i.to)}function pa(e,t,n,i){var r,o;if(t.touches)r=t.touches[0].clientX,o=t.touches[0].clientY;else try{r=t.clientX,o=t.clientY}catch(t){return!1}if(r>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;i&&Ae(t);var a=e.display,s=a.lineDiv.getBoundingClientRect();if(o>s.bottom||!Ce(e,n))return _e(t);o-=s.top-a.viewOffset;for(var l=0;l=r)return ge(e,n,e,$e(e.doc,o),e.display.gutterSpecs[l].className,t),_e(t)}}function ga(e,t){return pa(e,t,"gutterClick",!0)}function ma(e,t){_n(e.display,t)||function(e,t){if(!Ce(e,"gutterContextMenu"))return!1;return pa(e,t,"gutterContextMenu",!1)}(e,t)||me(e,t,"contextmenu")||b||e.display.input.onContextMenu(t)}function va(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),zn(e)}da.prototype.compare=function(e,t,n){return this.time+400>e&&0==tt(t,this.pos)&&n==this.button};var Ca={toString:function(){return"CodeMirror.Init"}},ya={},Aa={};function Ia(e,t,n){if(!t!=!(n&&n!=Ca)){var i=e.display.dragFunctions,r=t?he:pe;r(e.display.scroller,"dragstart",i.start),r(e.display.scroller,"dragenter",i.enter),r(e.display.scroller,"dragover",i.over),r(e.display.scroller,"dragleave",i.leave),r(e.display.scroller,"drop",i.drop)}}function _a(e){e.options.lineWrapping?(P(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(E(e.display.wrapper,"CodeMirror-wrap"),Gt(e)),ai(e),ci(e),zn(e),setTimeout(function(){return Ui(e)},100)}function ba(e,t){var i=this;if(!(this instanceof ba))return new ba(e,t);this.options=t=t?B(t):{},B(ya,t,!1);var r=t.value;"string"==typeof r?r=new So(r,t.mode,null,t.lineSeparator,t.direction):t.mode&&(r.modeOption=t.mode),this.doc=r;var o=new ba.inputStyles[t.inputStyle](this),c=this.display=new function(e,t,i,r){var o=this;this.input=i,o.scrollbarFiller=T("div",null,"CodeMirror-scrollbar-filler"),o.scrollbarFiller.setAttribute("cm-not-content","true"),o.gutterFiller=T("div",null,"CodeMirror-gutter-filler"),o.gutterFiller.setAttribute("cm-not-content","true"),o.lineDiv=L("div",null,"CodeMirror-code"),o.selectionDiv=T("div",null,null,"position: relative; z-index: 1"),o.cursorDiv=T("div",null,"CodeMirror-cursors"),o.measure=T("div",null,"CodeMirror-measure"),o.lineMeasure=T("div",null,"CodeMirror-measure"),o.lineSpace=L("div",[o.measure,o.lineMeasure,o.selectionDiv,o.cursorDiv,o.lineDiv],null,"position: relative; outline: none");var c=L("div",[o.lineSpace],"CodeMirror-lines");o.mover=T("div",[c],null,"position: relative"),o.sizer=T("div",[o.mover],"CodeMirror-sizer"),o.sizerWidth=null,o.heightForcer=T("div",null,null,"position: absolute; height: "+W+"px; width: 1px;"),o.gutters=T("div",null,"CodeMirror-gutters"),o.lineGutter=null,o.scroller=T("div",[o.sizer,o.heightForcer,o.gutters],"CodeMirror-scroll"),o.scroller.setAttribute("tabIndex","-1"),o.wrapper=T("div",[o.scrollbarFiller,o.gutterFiller,o.scroller],"CodeMirror"),a&&s<8&&(o.gutters.style.zIndex=-1,o.scroller.style.paddingRight=0),l||n&&v||(o.scroller.draggable=!0),e&&(e.appendChild?e.appendChild(o.wrapper):e(o.wrapper)),o.viewFrom=o.viewTo=t.first,o.reportedViewFrom=o.reportedViewTo=t.first,o.view=[],o.renderedView=null,o.externalMeasured=null,o.viewOffset=0,o.lastWrapHeight=o.lastWrapWidth=0,o.updateLineNumbers=null,o.nativeBarWidth=o.barHeight=o.barWidth=0,o.scrollbarsClipped=!1,o.lineNumWidth=o.lineNumInnerWidth=o.lineNumChars=null,o.alignWidgets=!1,o.cachedCharWidth=o.cachedTextHeight=o.cachedPaddingH=null,o.maxLine=null,o.maxLineLength=0,o.maxLineChanged=!1,o.wheelDX=o.wheelDY=o.wheelStartX=o.wheelStartY=null,o.shift=!1,o.selForContextMenu=null,o.activeTouch=null,o.gutterSpecs=ur(r.gutters,r.lineNumbers),dr(o),i.init(o)}(e,r,o,t);for(var u in c.wrapper.CodeMirror=this,va(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Hi(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new U,keySeq:null,specialChars:null},t.autofocus&&!v&&c.input.focus(),a&&s<11&&setTimeout(function(){return i.display.input.reset(!0)},20),function(e){var t=e.display;he(t.scroller,"mousedown",$i(e,ha)),he(t.scroller,"dblclick",a&&s<11?$i(e,function(t){if(!me(e,t)){var n=si(e,t);if(n&&!ga(e,t)&&!_n(e.display,t)){Ae(t);var i=e.findWordAt(n);Vr(e.doc,i.anchor,i.head)}}}):function(t){return me(e,t)||Ae(t)});he(t.scroller,"contextmenu",function(t){return ma(e,t)}),he(t.input.getField(),"contextmenu",function(n){t.scroller.contains(n.target)||ma(e,n)});var n,i={end:0};function r(){t.activeTouch&&(n=setTimeout(function(){return t.activeTouch=null},1e3),(i=t.activeTouch).end=+new Date)}function o(e,t){if(null==t.left)return!0;var n=t.left-e.left,i=t.top-e.top;return n*n+i*i>400}he(t.scroller,"touchstart",function(r){if(!me(e,r)&&!function(e){if(1!=e.touches.length)return!1;var t=e.touches[0];return t.radiusX<=1&&t.radiusY<=1}(r)&&!ga(e,r)){t.input.ensurePolled(),clearTimeout(n);var o=+new Date;t.activeTouch={start:o,moved:!1,prev:o-i.end<=300?i:null},1==r.touches.length&&(t.activeTouch.left=r.touches[0].pageX,t.activeTouch.top=r.touches[0].pageY)}}),he(t.scroller,"touchmove",function(){t.activeTouch&&(t.activeTouch.moved=!0)}),he(t.scroller,"touchend",function(n){var i=t.activeTouch;if(i&&!_n(t,n)&&null!=i.left&&!i.moved&&new Date-i.start<300){var a,s=e.coordsChar(t.activeTouch,"page");a=!i.prev||o(i,i.prev)?new yr(s,s):!i.prev.prev||o(i,i.prev.prev)?e.findWordAt(s):new yr(et(s.line,0),st(e.doc,et(s.line+1,0))),e.setSelection(a.anchor,a.head),e.focus(),Ae(n)}r()}),he(t.scroller,"touchcancel",r),he(t.scroller,"scroll",function(){t.scroller.clientHeight&&(Pi(e,t.scroller.scrollTop),Di(e,t.scroller.scrollLeft,!0),ge(e,"scroll",e))}),he(t.scroller,"mousewheel",function(t){return vr(e,t)}),he(t.scroller,"DOMMouseScroll",function(t){return vr(e,t)}),he(t.wrapper,"scroll",function(){return t.wrapper.scrollTop=t.wrapper.scrollLeft=0}),t.dragFunctions={enter:function(t){me(e,t)||be(t)},over:function(t){me(e,t)||(!function(e,t){var n=si(e,t);if(n){var i=document.createDocumentFragment();mi(e,n,i),e.display.dragCursor||(e.display.dragCursor=T("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),e.display.lineSpace.insertBefore(e.display.dragCursor,e.display.cursorDiv)),k(e.display.dragCursor,i)}}(e,t),be(t))},start:function(t){return function(e,t){if(a&&(!e.state.draggingText||+new Date-ko<100))be(t);else if(!me(e,t)&&!_n(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setDragImage&&!h)){var n=T("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",d&&(n.width=n.height=1,e.display.wrapper.appendChild(n),n._top=n.offsetTop),t.dataTransfer.setDragImage(n,0,0),d&&n.parentNode.removeChild(n)}}(e,t)},drop:$i(e,To),leave:function(t){me(e,t)||Lo(e)}};var l=t.input.getField();he(l,"keyup",function(t){return sa.call(e,t)}),he(l,"keydown",$i(e,aa)),he(l,"keypress",$i(e,la)),he(l,"focus",function(t){return _i(e,t)}),he(l,"blur",function(t){return bi(e,t)})}(this),Po(),Vi(this),this.curOp.forceUpdate=!0,Mr(this,r),t.autofocus&&!v||this.hasFocus()?setTimeout(N(_i,this),20):bi(this),Aa)Aa.hasOwnProperty(u)&&Aa[u](i,t[u],Ca);cr(this),t.finishInit&&t.finishInit(this);for(var f=0;f150)){if(!i)return;n="prev"}}else c=0,n="not";"prev"==n?c=t>o.first?F(Xe(o,t-1).text,null,a):0:"add"==n?c=l+e.options.indentUnit:"subtract"==n?c=l-e.options.indentUnit:"number"==typeof n&&(c=l+n),c=Math.max(0,c);var d="",h=0;if(e.options.indentWithTabs)for(var f=Math.floor(c/a);f;--f)h+=a,d+="\t";if(ha,l=Oe(t),c=null;if(s&&i.ranges.length>1)if(Ea&&Ea.text.join("\n")==t){if(i.ranges.length%Ea.text.length==0){c=[];for(var u=0;u=0;h--){var f=i.ranges[h],p=f.from(),g=f.to();f.empty()&&(n&&n>0?p=et(p.line,p.ch-n):e.state.overwrite&&!s?g=et(g.line,Math.min(Xe(o,g.line).text.length,g.ch+K(l).length)):s&&Ea&&Ea.lineWise&&Ea.text.join("\n")==t&&(p=g=et(p.line,0)));var m={from:p,to:g,text:c?c[h%c.length]:l,origin:r||(s?"paste":e.state.cutIncoming>a?"cut":"+input")};oo(e.doc,m),ln(e,"inputRead",e,m)}t&&!s&&La(e,t),Ti(e),e.curOp.updateInput<2&&(e.curOp.updateInput=d),e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=-1}function Ta(e,t){var n=e.clipboardData&&e.clipboardData.getData("Text");if(n)return e.preventDefault(),t.isReadOnly()||t.options.disableInput||Zi(t,function(){return ka(t,n,0,null,"paste")}),!0}function La(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var n=e.doc.sel,i=n.ranges.length-1;i>=0;i--){var r=n.ranges[i];if(!(r.head.ch>100||i&&n.ranges[i-1].head.line==r.head.line)){var o=e.getModeAt(r.head),a=!1;if(o.electricChars){for(var s=0;s-1){a=xa(e,r.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(Xe(e.doc,r.head.line).text.slice(0,r.head.ch))&&(a=xa(e,r.head.line,"smart"));a&&ln(e,"electricInput",e,r.head.line)}}}function Ma(e){for(var t=[],n=[],i=0;i=t.text.length?(n.ch=t.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var o=le(r,n.ch,n.sticky),a=r[o];if("ltr"==e.doc.direction&&a.level%2==0&&(i>0?a.to>n.ch:a.from=a.from&&h>=u.begin)){var f=d?"before":"after";return new et(n.line,h,f)}}var p=function(e,t,i){for(var o=function(e,t){return t?new et(n.line,l(e,1),"before"):new et(n.line,e,"after")};e>=0&&e0==(1!=a.level),c=s?i.begin:l(i.end,-1);if(a.from<=c&&c0?u.end:l(u.begin,-1);return null==m||i>0&&m==t.text.length||!(g=p(i>0?0:r.length-1,i,c(m)))?null:g}(e.cm,s,t,n):Ko(s,t,n))){if(i||(a=t.line+l)=e.first+e.size||(t=new et(a,t.ch,t.sticky),!(s=Xe(e,a))))return!1;t=Zo(r,e.cm,s,t.line,l)}else t=o;return!0}if("char"==i)c();else if("column"==i)c(!0);else if("word"==i||"group"==i)for(var u=null,d="group"==i,h=e.cm&&e.cm.getHelper(t,"wordChars"),f=!0;!(n<0)||c(!f);f=!1){var p=s.text.charAt(t.ch)||"\n",g=te(p,h)?"w":d&&"\n"==p?"n":!d||/\s/.test(p)?null:"p";if(!d||f||g||(g="s"),u&&u!=g){n<0&&(n=1,c(),t.sticky="after");break}if(g&&(u=g),n>0&&!c(!f))break}var m=to(e,t,o,a,!0);return nt(o,m)&&(m.hitSide=!0),m}function Da(e,t,n,i){var r,o,a=e.doc,s=t.left;if("page"==i){var l=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),c=Math.max(l-.5*ti(e.display),3);r=(n>0?t.bottom:t.top)+n*c}else"line"==i&&(r=n>0?t.bottom+3:t.top-3);for(;(o=Zn(e,s,r)).outside;){if(n<0?r<=0:r>=a.height){o.hitSide=!0;break}r+=5*n}return o}var Na=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new U,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function Ba(e,t){var n=Mn(e,t.line);if(!n||n.hidden)return null;var i=Xe(e.doc,t.line),r=Tn(n,i,t.line),o=ue(i,e.doc.direction),a="left";o&&(a=le(o,t.ch)%2?"right":"left");var s=Nn(r.map,t.ch,a);return s.offset="right"==s.collapse?s.end:s.start,s}function Fa(e,t){return t&&(e.bad=!0),e}function Ua(e,t,n){var i;if(t==e.display.lineDiv){if(!(i=e.display.lineDiv.childNodes[n]))return Fa(e.clipPos(et(e.display.viewTo-1)),!0);t=null,n=0}else for(i=t;;i=i.parentNode){if(!i||i==e.display.lineDiv)return null;if(i.parentNode&&i.parentNode==e.display.lineDiv)break}for(var r=0;r=t.display.viewTo||o.line=t.display.viewFrom&&Ba(t,r)||{node:l[0].measure.map[2],offset:0},u=o.linei.firstLine()&&(a=et(a.line-1,Xe(i.doc,a.line-1).length)),s.ch==Xe(i.doc,s.line).text.length&&s.liner.viewTo-1)return!1;a.line==r.viewFrom||0==(e=li(i,a.line))?(t=Ze(r.view[0].line),n=r.view[0].node):(t=Ze(r.view[e].line),n=r.view[e-1].node.nextSibling);var l,c,u=li(i,s.line);if(u==r.view.length-1?(l=r.viewTo-1,c=r.lineDiv.lastChild):(l=Ze(r.view[u+1].line)-1,c=r.view[u+1].node.previousSibling),!n)return!1;for(var d=i.doc.splitLines(function(e,t,n,i,r){var o="",a=!1,s=e.doc.lineSeparator(),l=!1;function c(){a&&(o+=s,l&&(o+=s),a=l=!1)}function u(e){e&&(c(),o+=e)}function d(t){if(1==t.nodeType){var n=t.getAttribute("cm-text");if(n)return void u(n);var o,h=t.getAttribute("cm-marker");if(h){var f=e.findMarks(et(i,0),et(r+1,0),(m=+h,function(e){return e.id==m}));return void(f.length&&(o=f[0].find(0))&&u(Ye(e.doc,o.from,o.to).join(s)))}if("false"==t.getAttribute("contenteditable"))return;var p=/^(pre|div|p|li|table|br)$/i.test(t.nodeName);if(!/^br$/i.test(t.nodeName)&&0==t.textContent.length)return;p&&c();for(var g=0;g1&&h.length>1;)if(K(d)==K(h))d.pop(),h.pop(),l--;else{if(d[0]!=h[0])break;d.shift(),h.shift(),t++}for(var f=0,p=0,g=d[0],m=h[0],v=Math.min(g.length,m.length);fa.ch&&C.charCodeAt(C.length-p-1)==y.charCodeAt(y.length-p-1);)f--,p++;d[d.length-1]=C.slice(0,C.length-p).replace(/^\u200b+/,""),d[0]=d[0].slice(f).replace(/\u200b+$/,"");var I=et(t,f),_=et(l,h.length?K(h).length-p:0);return d.length>1||d[0]||tt(I,_)?(uo(i.doc,d,I,_,"+input"),!0):void 0},Na.prototype.ensurePolled=function(){this.forceCompositionEnd()},Na.prototype.reset=function(){this.forceCompositionEnd()},Na.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},Na.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout(function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()},80))},Na.prototype.updateFromDOM=function(){var e=this;!this.cm.isReadOnly()&&this.pollContent()||Zi(this.cm,function(){return ci(e.cm)})},Na.prototype.setUneditable=function(e){e.contentEditable="false"},Na.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly()||$i(this.cm,ka)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},Na.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},Na.prototype.onContextMenu=function(){},Na.prototype.resetPosition=function(){},Na.prototype.needsContentAttribute=!0;var Wa=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new U,this.hasSelection=!1,this.composing=null};Wa.prototype.init=function(e){var t=this,n=this,i=this.cm;this.createField(e);var r=this.textarea;function o(e){if(!me(i,e)){if(i.somethingSelected())Sa({lineWise:!1,text:i.getSelections()});else{if(!i.options.lineWiseCopyCut)return;var t=Ma(i);Sa({lineWise:!0,text:t.text}),"cut"==e.type?i.setSelections(t.ranges,null,j):(n.prevInput="",r.value=t.text.join("\n"),D(r))}"cut"==e.type&&(i.state.cutIncoming=+new Date)}}e.wrapper.insertBefore(this.wrapper,e.wrapper.firstChild),g&&(r.style.width="0px"),he(r,"input",function(){a&&s>=9&&t.hasSelection&&(t.hasSelection=null),n.poll()}),he(r,"paste",function(e){me(i,e)||Ta(e,i)||(i.state.pasteIncoming=+new Date,n.fastPoll())}),he(r,"cut",o),he(r,"copy",o),he(e.scroller,"paste",function(t){if(!_n(e,t)&&!me(i,t)){if(!r.dispatchEvent)return i.state.pasteIncoming=+new Date,void n.focus();var o=new Event("paste");o.clipboardData=t.clipboardData,r.dispatchEvent(o)}}),he(e.lineSpace,"selectstart",function(t){_n(e,t)||Ae(t)}),he(r,"compositionstart",function(){var e=i.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:e,range:i.markText(e,i.getCursor("to"),{className:"CodeMirror-composing"})}}),he(r,"compositionend",function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)})},Wa.prototype.createField=function(e){this.wrapper=Pa(),this.textarea=this.wrapper.firstChild},Wa.prototype.screenReaderLabelChanged=function(e){e?this.textarea.setAttribute("aria-label",e):this.textarea.removeAttribute("aria-label")},Wa.prototype.prepareSelection=function(){var e=this.cm,t=e.display,n=e.doc,i=gi(e);if(e.options.moveInputWithCursor){var r=Yn(e,n.sel.primary().head,"div"),o=t.wrapper.getBoundingClientRect(),a=t.lineDiv.getBoundingClientRect();i.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,r.top+a.top-o.top)),i.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,r.left+a.left-o.left))}return i},Wa.prototype.showSelection=function(e){var t=this.cm.display;k(t.cursorDiv,e.cursors),k(t.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},Wa.prototype.reset=function(e){if(!this.contextMenuPending&&!this.composing){var t=this.cm;if(t.somethingSelected()){this.prevInput="";var n=t.getSelection();this.textarea.value=n,t.state.focused&&D(this.textarea),a&&s>=9&&(this.hasSelection=n)}else e||(this.prevInput=this.textarea.value="",a&&s>=9&&(this.hasSelection=null))}},Wa.prototype.getField=function(){return this.textarea},Wa.prototype.supportsTouch=function(){return!1},Wa.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!v||O()!=this.textarea))try{this.textarea.focus()}catch(e){}},Wa.prototype.blur=function(){this.textarea.blur()},Wa.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},Wa.prototype.receivedFocus=function(){this.slowPoll()},Wa.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,function(){e.poll(),e.cm.state.focused&&e.slowPoll()})},Wa.prototype.fastPoll=function(){var e=!1,t=this;t.pollingFast=!0,t.polling.set(20,function n(){t.poll()||e?(t.pollingFast=!1,t.slowPoll()):(e=!0,t.polling.set(60,n))})},Wa.prototype.poll=function(){var e=this,t=this.cm,n=this.textarea,i=this.prevInput;if(this.contextMenuPending||!t.state.focused||Pe(n)&&!i&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var r=n.value;if(r==i&&!t.somethingSelected())return!1;if(a&&s>=9&&this.hasSelection===r||C&&/[\uf700-\uf7ff]/.test(r))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var o=r.charCodeAt(0);if(8203!=o||i||(i="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var l=0,c=Math.min(i.length,r.length);l1e3||r.indexOf("\n")>-1?n.value=e.prevInput="":e.prevInput=r,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))}),!0},Wa.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},Wa.prototype.onKeyPress=function(){a&&s>=9&&(this.hasSelection=null),this.fastPoll()},Wa.prototype.onContextMenu=function(e){var t=this,n=t.cm,i=n.display,r=t.textarea;t.contextMenuPending&&t.contextMenuPending();var o=si(n,e),c=i.scroller.scrollTop;if(o&&!d){n.options.resetSelectionOnContextMenu&&-1==n.doc.sel.contains(o)&&$i(n,Kr)(n.doc,Ir(o),j);var u,h=r.style.cssText,f=t.wrapper.style.cssText,p=t.wrapper.offsetParent.getBoundingClientRect();if(t.wrapper.style.cssText="position: static",r.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-p.top-5)+"px; left: "+(e.clientX-p.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",l&&(u=window.scrollY),i.input.focus(),l&&window.scrollTo(null,u),i.input.reset(),n.somethingSelected()||(r.value=t.prevInput=" "),t.contextMenuPending=v,i.selForContextMenu=n.doc.sel,clearTimeout(i.detectingSelectAll),a&&s>=9&&m(),b){be(e);var g=function(){pe(window,"mouseup",g),setTimeout(v,20)};he(window,"mouseup",g)}else setTimeout(v,50)}function m(){if(null!=r.selectionStart){var e=n.somethingSelected(),o="​"+(e?r.value:"");r.value="⇚",r.value=o,t.prevInput=e?"":"​",r.selectionStart=1,r.selectionEnd=o.length,i.selForContextMenu=n.doc.sel}}function v(){if(t.contextMenuPending==v&&(t.contextMenuPending=!1,t.wrapper.style.cssText=f,r.style.cssText=h,a&&s<9&&i.scrollbars.setScrollTop(i.scroller.scrollTop=c),null!=r.selectionStart)){(!a||a&&s<9)&&m();var e=0,o=function(){i.selForContextMenu==n.doc.sel&&0==r.selectionStart&&r.selectionEnd>0&&"​"==t.prevInput?$i(n,io)(n):e++<10?i.detectingSelectAll=setTimeout(o,500):(i.selForContextMenu=null,i.input.reset())};i.detectingSelectAll=setTimeout(o,200)}}},Wa.prototype.readOnlyChanged=function(e){e||this.reset(),this.textarea.disabled="nocursor"==e},Wa.prototype.setUneditable=function(){},Wa.prototype.needsContentAttribute=!1,function(e){var t=e.optionHandlers;function n(n,i,r,o){e.defaults[n]=i,r&&(t[n]=o?function(e,t,n){n!=Ca&&r(e,t,n)}:r)}e.defineOption=n,e.Init=Ca,n("value","",function(e,t){return e.setValue(t)},!0),n("mode",null,function(e,t){e.doc.modeOption=t,Er(e)},!0),n("indentUnit",2,Er,!0),n("indentWithTabs",!1),n("smartIndent",!0),n("tabSize",4,function(e){Sr(e),zn(e),ci(e)},!0),n("lineSeparator",null,function(e,t){if(e.doc.lineSep=t,t){var n=[],i=e.doc.first;e.doc.iter(function(e){for(var r=0;;){var o=e.text.indexOf(t,r);if(-1==o)break;r=o+t.length,n.push(et(i,o))}i++});for(var r=n.length-1;r>=0;r--)uo(e.doc,t,n[r],et(n[r].line,n[r].ch+t.length))}}),n("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,function(e,t,n){e.state.specialChars=new RegExp(t.source+(t.test("\t")?"":"|\t"),"g"),n!=Ca&&e.refresh()}),n("specialCharPlaceholder",Qt,function(e){return e.refresh()},!0),n("electricChars",!0),n("inputStyle",v?"contenteditable":"textarea",function(){throw new Error("inputStyle can not (yet) be changed in a running editor")},!0),n("spellcheck",!1,function(e,t){return e.getInputField().spellcheck=t},!0),n("autocorrect",!1,function(e,t){return e.getInputField().autocorrect=t},!0),n("autocapitalize",!1,function(e,t){return e.getInputField().autocapitalize=t},!0),n("rtlMoveVisually",!A),n("wholeLineUpdateBefore",!0),n("theme","default",function(e){va(e),hr(e)},!0),n("keyMap","default",function(e,t,n){var i=Xo(t),r=n!=Ca&&Xo(n);r&&r.detach&&r.detach(e,i),i.attach&&i.attach(e,r||null)}),n("extraKeys",null),n("configureMouse",null),n("lineWrapping",!1,_a,!0),n("gutters",[],function(e,t){e.display.gutterSpecs=ur(t,e.options.lineNumbers),hr(e)},!0),n("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?ri(e.display)+"px":"0",e.refresh()},!0),n("coverGutterNextToScrollbar",!1,function(e){return Ui(e)},!0),n("scrollbarStyle","native",function(e){Hi(e),Ui(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0),n("lineNumbers",!1,function(e,t){e.display.gutterSpecs=ur(e.options.gutters,t),hr(e)},!0),n("firstLineNumber",1,hr,!0),n("lineNumberFormatter",function(e){return e},hr,!0),n("showCursorWhenSelecting",!1,pi,!0),n("resetSelectionOnContextMenu",!0),n("lineWiseCopyCut",!0),n("pasteLinesPerSelection",!0),n("selectionsMayTouch",!1),n("readOnly",!1,function(e,t){"nocursor"==t&&(bi(e),e.display.input.blur()),e.display.input.readOnlyChanged(t)}),n("screenReaderLabel",null,function(e,t){t=""===t?null:t,e.display.input.screenReaderLabelChanged(t)}),n("disableInput",!1,function(e,t){t||e.display.input.reset()},!0),n("dragDrop",!0,Ia),n("allowDropFileTypes",null),n("cursorBlinkRate",530),n("cursorScrollMargin",0),n("cursorHeight",1,pi,!0),n("singleCursorHeightPerLine",!0,pi,!0),n("workTime",100),n("workDelay",100),n("flattenSpans",!0,Sr,!0),n("addModeClass",!1,Sr,!0),n("pollInterval",100),n("undoDepth",200,function(e,t){return e.doc.history.undoDepth=t}),n("historyEventDelay",1250),n("viewportMargin",10,function(e){return e.refresh()},!0),n("maxHighlightLength",1e4,Sr,!0),n("moveInputWithCursor",!0,function(e,t){t||e.display.input.resetPosition()}),n("tabindex",null,function(e,t){return e.display.input.getField().tabIndex=t||""}),n("autofocus",null),n("direction","ltr",function(e,t){return e.doc.setDirection(t)},!0),n("phrases",null)}(ba),function(e){var t=e.optionHandlers,n=e.helpers={};e.prototype={constructor:e,focus:function(){window.focus(),this.display.input.focus()},setOption:function(e,n){var i=this.options,r=i[e];i[e]==n&&"mode"!=e||(i[e]=n,t.hasOwnProperty(e)&&$i(this,t[e])(this,n,r),ge(this,"optionChange",this,e))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Xo(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;nn&&(xa(this,r.head.line,e,!0),n=r.head.line,i==this.doc.sel.primIndex&&Ti(this));else{var o=r.from(),a=r.to(),s=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var l=s;l0&&Xr(this.doc,i,new yr(o,c[i].to()),j)}}}),getTokenAt:function(e,t){return Ct(this,e,t)},getLineTokens:function(e,t){return Ct(this,et(e),t,!0)},getTokenTypeAt:function(e){e=st(this.doc,e);var t,n=ht(this,Xe(this.doc,e.line)),i=0,r=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var a=i+r>>1;if((a?n[2*a-1]:0)>=o)r=a;else{if(!(n[2*a+1]o&&(e=o,r=!0),i=Xe(this.doc,e)}else i=e;return Vn(this,i,{top:0,left:0},t||"page",n||r).top+(r?this.doc.height-jt(i):0)},defaultTextHeight:function(){return ti(this.display)},defaultCharWidth:function(){return ni(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,i,r){var o,a,s,l=this.display,c=(e=Yn(this,st(this.doc,e))).bottom,u=e.left;if(t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),l.sizer.appendChild(t),"over"==i)c=e.top;else if("above"==i||"near"==i){var d=Math.max(l.wrapper.clientHeight,this.doc.height),h=Math.max(l.sizer.clientWidth,l.lineSpace.clientWidth);("above"==i||e.bottom+t.offsetHeight>d)&&e.top>t.offsetHeight?c=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=d&&(c=e.bottom),u+t.offsetWidth>h&&(u=h-t.offsetWidth)}t.style.top=c+"px",t.style.left=t.style.right="","right"==r?(u=l.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==r?u=0:"middle"==r&&(u=(l.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),n&&(o=this,a={left:u,top:c,right:u+t.offsetWidth,bottom:c+t.offsetHeight},null!=(s=Si(o,a)).scrollTop&&Pi(o,s.scrollTop),null!=s.scrollLeft&&Di(o,s.scrollLeft))},triggerOnKeyDown:Qi(aa),triggerOnKeyPress:Qi(la),triggerOnKeyUp:sa,triggerOnMouseDown:Qi(ha),execCommand:function(e){if($o.hasOwnProperty(e))return $o[e].call(null,this)},triggerElectric:Qi(function(e){La(this,e)}),findPosH:function(e,t,n,i){var r=1;t<0&&(r=-1,t=-t);for(var o=st(this.doc,e),a=0;a0&&a(t.charAt(n-1));)--n;for(;i.5)&&ai(this),ge(this,"refresh",this)}),swapDoc:Qi(function(e){var t=this.doc;return t.cm=null,this.state.selectingText&&this.state.selectingText(),Mr(this,e),zn(this),this.display.input.reset(),Li(this,e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,ln(this,"swapDoc",this,t),t}),phrase:function(e){var t=this.options.phrases;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},ye(e),e.registerHelper=function(t,i,r){n.hasOwnProperty(t)||(n[t]=e[t]={_global:[]}),n[t][i]=r},e.registerGlobalHelper=function(t,i,r,o){e.registerHelper(t,i,o),n[t]._global.push({pred:r,val:o})}}(ba);var Ha="iter insert remove copy getEditor constructor".split(" ");for(var ja in So.prototype)So.prototype.hasOwnProperty(ja)&&z(Ha,ja)<0&&(ba.prototype[ja]=function(e){return function(){return e.apply(this.doc,arguments)}}(So.prototype[ja]));return ye(So),ba.inputStyles={textarea:Wa,contenteditable:Na},ba.defineMode=function(e){ba.defaults.mode||"null"==e||(ba.defaults.mode=e),function(e,t){arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),Ne[e]=t}.apply(this,arguments)},ba.defineMIME=function(e,t){Be[e]=t},ba.defineMode("null",function(){return{token:function(e){return e.skipToEnd()}}}),ba.defineMIME("text/plain","null"),ba.defineExtension=function(e,t){ba.prototype[e]=t},ba.defineDocExtension=function(e,t){So.prototype[e]=t},ba.fromTextArea=function(e,t){if((t=t?B(t):{}).value=e.value,!t.tabindex&&e.tabIndex&&(t.tabindex=e.tabIndex),!t.placeholder&&e.placeholder&&(t.placeholder=e.placeholder),null==t.autofocus){var n=O();t.autofocus=n==e||null!=e.getAttribute("autofocus")&&n==document.body}function i(){e.value=s.getValue()}var r;if(e.form&&(he(e.form,"submit",i),!t.leaveSubmitMethodAlone)){var o=e.form;r=o.submit;try{var a=o.submit=function(){i(),o.submit=r,o.submit(),o.submit=a}}catch(e){}}t.finishInit=function(n){n.save=i,n.getTextArea=function(){return e},n.toTextArea=function(){n.toTextArea=isNaN,i(),e.parentNode.removeChild(n.getWrapperElement()),e.style.display="",e.form&&(pe(e.form,"submit",i),t.leaveSubmitMethodAlone||"function"!=typeof e.form.submit||(e.form.submit=r))}},e.style.display="none";var s=ba(function(t){return e.parentNode.insertBefore(t,e.nextSibling)},t);return s},function(e){e.off=pe,e.on=he,e.wheelEventPixels=mr,e.Doc=So,e.splitLines=Oe,e.countColumn=F,e.findColumn=X,e.isWordChar=ee,e.Pass=H,e.signal=ge,e.Line=Xt,e.changeEnd=_r,e.scrollbarModel=Wi,e.Pos=et,e.cmpPos=tt,e.modes=Ne,e.mimeModes=Be,e.resolveMode=Fe,e.getMode=Ue,e.modeExtensions=ze,e.extendMode=We,e.copyState=He,e.startState=Ve,e.innerMode=je,e.commands=$o,e.keyMap=Uo,e.keyName=Go,e.isModifierKey=jo,e.lookupKey=Ho,e.normalizeKeyMap=Wo,e.StringStream=Ge,e.SharedTextMarker=bo,e.TextMarker=Io,e.LineWidget=Co,e.e_preventDefault=Ae,e.e_stopPropagation=Ie,e.e_stop=be,e.addClass=P,e.contains=M,e.rmClass=E,e.keyNames=Do}(ba),ba.version="5.52.2",ba}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";var t,n,i=e.Pos;function r(e,t){for(var n=function(e){var t=e.flags;return null!=t?t:(e.ignoreCase?"i":"")+(e.global?"g":"")+(e.multiline?"m":"")}(e),i=n,r=0;re.length-n)break;(!i||a>i.index+i[0].length)&&(i=o),r=o.index+1}return i}function l(e,t,n){t=r(t,"g");for(var o=n.line,a=n.ch,l=e.firstLine();o>=l;o--,a=-1){var c=e.getLine(o),u=s(c,t,a<0?0:c.length-a);if(u)return{from:i(o,u.index),to:i(o,u.index+u[0].length),match:u}}}function c(e,t,n,i){if(e.length==t.length)return n;for(var r=0,o=n+Math.max(0,e.length-t.length);;){if(r==o)return r;var a=r+o>>1,s=i(e.slice(0,a)).length;if(s==n)return a;s>n?o=a:r=a+1}}function u(e,u,d,h){var f;this.atOccurrence=!1,this.doc=e,d=d?e.clipPos(d):i(0,0),this.pos={from:d,to:d},"object"==typeof h?f=h.caseFold:(f=h,h=null),"string"==typeof u?(null==f&&(f=!1),this.matches=function(r,o){return(r?function(e,r,o,a){if(!r.length)return null;var s=a?t:n,l=s(r).split(/\r|\n\r?/);e:for(var u=o.line,d=o.ch,h=e.firstLine()-1+l.length;u>=h;u--,d=-1){var f=e.getLine(u);d>-1&&(f=f.slice(0,d));var p=s(f);if(1==l.length){var g=p.lastIndexOf(l[0]);if(-1==g)continue e;return{from:i(u,c(f,p,g,s)),to:i(u,c(f,p,g+l[0].length,s))}}var m=l[l.length-1];if(p.slice(0,m.length)==m){var v=1;for(o=u-l.length+1;v=h;){for(var f=0;f=h;f++){var p=e.getLine(d--);a=null==a?p:p+"\n"+a}c*=2;var g=s(a,t,u);if(g){var m=a.slice(0,g.index).split("\n"),v=g[0].split("\n"),C=d+m.length,y=m[m.length-1].length;return{from:i(C,y),to:i(C+v.length-1,1==v.length?y+v[0].length:v[v.length-1].length),match:g}}}}:function(e,t,n){if(!o(t))return a(e,t,n);t=r(t,"gm");for(var s,l=1,c=n.line,u=e.lastLine();c<=u;){for(var d=0;du);d++){var h=e.getLine(c++);s=null==s?h:s+"\n"+h}l*=2,t.lastIndex=n.ch;var f=t.exec(s);if(f){var p=s.slice(0,f.index).split("\n"),g=f[0].split("\n"),m=n.line+p.length-1,v=p[p.length-1].length;return{from:i(m,v),to:i(m+g.length-1,1==g.length?v+g[0].length:g[g.length-1].length),match:f}}}})(e,u,n)})}String.prototype.normalize?(t=function(e){return e.normalize("NFD").toLowerCase()},n=function(e){return e.normalize("NFD")}):(t=function(e){return e.toLowerCase()},n=function(e){return e}),u.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(t){for(var n=this.matches(t,this.doc.clipPos(t?this.pos.from:this.pos.to));n&&0==e.cmpPos(n.from,n.to);)t?n.from.ch?n.from=i(n.from.line,n.from.ch-1):n=n.from.line==this.doc.firstLine()?null:this.matches(t,this.doc.clipPos(i(n.from.line-1))):n.to.ch0);)i.push({anchor:r.from(),head:r.to()});i.length&&this.setSelections(i,0)})}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror"),require("./matchesonscrollbar")):"function"==typeof define&&define.amd?define(["../../lib/codemirror","./matchesonscrollbar"],e):e(CodeMirror)}(function(e){"use strict";var t={style:"matchhighlight",minChars:2,delay:100,wordsOnly:!1,annotateScrollbar:!1,showToken:!1,trim:!0};function n(e){var t=e.state.matchHighlighter;(t.active||e.hasFocus())&&r(e,t)}function i(e){var t=e.state.matchHighlighter;t.active||(t.active=!0,r(e,t))}function r(e,t){clearTimeout(t.timeout),t.timeout=setTimeout(function(){s(e)},t.options.delay)}function o(e,t,n,i){var r=e.state.matchHighlighter;if(e.addOverlay(r.overlay=function(e,t,n){return{token:function(i){if(i.match(e)&&(!t||function(e,t){return!(e.start&&t.test(e.string.charAt(e.start-1))||e.pos!=e.string.length&&t.test(e.string.charAt(e.pos)))}(i,t)))return n;i.next(),i.skipTo(e.charAt(0))||i.skipToEnd()}}}(t,n,i)),r.options.annotateScrollbar&&e.showMatchesOnScrollbar){var o=n?new RegExp("\\b"+t.replace(/[\\\[.+*?(){|^$]/g,"\\$&")+"\\b"):t;r.matchesonscroll=e.showMatchesOnScrollbar(o,!1,{className:"CodeMirror-selection-highlight-scrollbar"})}}function a(e){var t=e.state.matchHighlighter;t.overlay&&(e.removeOverlay(t.overlay),t.overlay=null,t.matchesonscroll&&(t.matchesonscroll.clear(),t.matchesonscroll=null))}function s(e){e.operation(function(){var t=e.state.matchHighlighter;if(a(e),e.somethingSelected()||!t.options.showToken){var n=e.getCursor("from"),i=e.getCursor("to");if(n.line==i.line&&(!t.options.wordsOnly||function(e,t,n){if(null!==e.getRange(t,n).match(/^\w+$/)){if(t.ch>0){var i={line:t.line,ch:t.ch-1},r=e.getRange(i,t);if(null===r.match(/\W/))return!1}if(n.ch=t.options.minChars&&o(e,r,!1,t.options.style)}}else{for(var s=!0===t.options.showToken?/[\w$]/:t.options.showToken,l=e.getCursor(),c=e.getLine(l.line),u=l.ch,d=u;u&&s.test(c.charAt(u-1));)--u;for(;d=this.gap.to)break;r.to.line>=this.gap.from&&this.matches.splice(t--,1)}for(var n=this.cm.getSearchCursor(this.query,e.Pos(this.gap.from,0),{caseFold:this.caseFold,multiline:this.options.multiline}),i=this.options&&this.options.maxMatches||1e3;n.findNext();){var r;if((r={from:n.from(),to:n.to()}).from.line>=this.gap.to)break;if(this.matches.splice(t++,0,r),this.matches.length>i)break}this.gap=null}},t.prototype.onChange=function(t){var i=t.from.line,r=e.changeEnd(t).line,o=r-t.to.line;if(this.gap?(this.gap.from=Math.min(n(this.gap.from,i,o),t.from.line),this.gap.to=Math.max(n(this.gap.to,i,o),t.from.line)):this.gap={from:t.from.line,to:r+1},o)for(var a=0;a",triples:"",explode:"[]{}"},n=e.Pos;function i(e,n){return"pairs"==n&&"string"==typeof e?e:"object"==typeof e&&null!=e[n]?e[n]:t[n]}e.defineOption("autoCloseBrackets",!1,function(t,n,a){a&&a!=e.Init&&(t.removeKeyMap(r),t.state.closeBrackets=null),n&&(o(i(n,"pairs")),t.state.closeBrackets=n,t.addKeyMap(r))});var r={Backspace:function(t){var r=s(t);if(!r||t.getOption("disableInput"))return e.Pass;for(var o=i(r,"pairs"),a=t.listSelections(),c=0;c=0;c--){var d=a[c].head;t.replaceRange("",n(d.line,d.ch-1),n(d.line,d.ch+1),"+delete")}},Enter:function(t){var n=s(t),r=n&&i(n,"explode");if(!r||t.getOption("disableInput"))return e.Pass;for(var o=t.listSelections(),a=0;a1&&h.indexOf(r)>=0&&t.getRange(n(y.line,y.ch-2),y)==r+r){if(y.ch>2&&/\bstring/.test(t.getTokenTypeAt(n(y.line,y.ch-2))))return e.Pass;v="addFour"}else if(f){var I=0==y.ch?" ":t.getRange(n(y.line,y.ch-1),y);if(e.isWordChar(A)||I==r||e.isWordChar(I))return e.Pass;v="both"}else{if(!g||!(0===A.length||/\s/.test(A)||d.indexOf(A)>-1))return e.Pass;v="both"}else v=f&&c(t,y)?"both":h.indexOf(r)>=0&&t.getRange(y,n(y.line,y.ch+3))==r+r+r?"skipThree":"skip";if(u){if(u!=v)return e.Pass}else u=v}var _=l%2?a.charAt(l-1):r,b=l%2?r:a.charAt(l+1);t.operation(function(){if("skip"==u)t.execCommand("goCharRight");else if("skipThree"==u)for(var i=0;i<3;i++)t.execCommand("goCharRight");else if("surround"==u){for(var r=t.getSelections(),i=0;i0,{anchor:new n(o.anchor.line,o.anchor.ch+(a?-1:1)),head:new n(o.head.line,o.head.ch+(a?1:-1))});t.setSelections(r)}else"both"==u?(t.replaceSelection(_+b,null),t.triggerElectric(_+b),t.execCommand("goCharLeft")):"addFour"==u&&(t.replaceSelection(_+_+_+_,"before"),t.execCommand("goCharRight"));var o,a})}(r,t)}}function s(e){var t=e.state.closeBrackets;return!t||t.override?t:e.getModeAt(e.getCursor()).closeBrackets||t}function l(e,t){var i=e.getRange(n(t.line,t.ch-1),n(t.line,t.ch+1));return 2==i.length?i:null}function c(e,t){var i=e.getTokenAt(n(t.line,t.ch+1));return/\bstring/.test(i.type)&&i.start==t.ch&&(0==t.ch||!/\bstring/.test(e.getTokenTypeAt(t)))}o(t.pairs+"`")}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){var t=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),n=e.Pos,i={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<","<":">>",">":"<<"};function r(e){return e&&e.bracketRegex||/[(){}[\]]/}function o(e,t,o){var s=e.getLineHandle(t.line),l=t.ch-1,c=o&&o.afterCursor;null==c&&(c=/(^| )cm-fat-cursor($| )/.test(e.getWrapperElement().className));var u=r(o),d=!c&&l>=0&&u.test(s.text.charAt(l))&&i[s.text.charAt(l)]||u.test(s.text.charAt(l+1))&&i[s.text.charAt(++l)];if(!d)return null;var h=">"==d.charAt(1)?1:-1;if(o&&o.strict&&h>0!=(l==t.ch))return null;var f=e.getTokenTypeAt(n(t.line,l+1)),p=a(e,n(t.line,l+(h>0?1:0)),h,f||null,o);return null==p?null:{from:n(t.line,l),to:p&&p.pos,match:p&&p.ch==d.charAt(0),forward:h>0}}function a(e,t,o,a,s){for(var l=s&&s.maxScanLineLength||1e4,c=s&&s.maxScanLines||1e3,u=[],d=r(s),h=o>0?Math.min(t.line+c,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-c),f=t.line;f!=h;f+=o){var p=e.getLine(f);if(p){var g=o>0?0:p.length-1,m=o>0?p.length:-1;if(!(p.length>l))for(f==t.line&&(g=t.ch-(o<0?1:0));g!=m;g+=o){var v=p.charAt(g);if(d.test(v)&&(void 0===a||e.getTokenTypeAt(n(f,g+1))==a)){var C=i[v];if(C&&">"==C.charAt(1)==o>0)u.push(v);else{if(!u.length)return{pos:n(f,g),ch:v};u.pop()}}}}}return f-o!=(o>0?e.lastLine():e.firstLine())&&null}function s(e,i,r){for(var a=e.state.matchBrackets.maxHighlightLineLength||1e3,s=[],l=e.listSelections(),c=0;ci.right?1:0:t.clientYi.bottom?1:0,r.moveTo(r.pos+n*r.screen)}),e.on(this.node,"mousewheel",o),e.on(this.node,"DOMMouseScroll",o)}t.prototype.setPos=function(e,t){return e<0&&(e=0),e>this.total-this.screen&&(e=this.total-this.screen),!(!t&&e==this.pos)&&(this.pos=e,this.inner.style["horizontal"==this.orientation?"left":"top"]=e*(this.size/this.total)+"px",!0)},t.prototype.moveTo=function(e){this.setPos(e)&&this.scroll(e,this.orientation)};function n(e,n,i){this.addClass=e,this.horiz=new t(e,"horizontal",i),n(this.horiz.node),this.vert=new t(e,"vertical",i),n(this.vert.node),this.width=null}t.prototype.update=function(e,t,n){var i=this.screen!=t||this.total!=e||this.size!=n;i&&(this.screen=t,this.total=e,this.size=n);var r=this.screen*(this.size/this.total);r<10&&(this.size-=10-r,r=10),this.inner.style["horizontal"==this.orientation?"width":"height"]=r+"px",this.setPos(this.pos,i)},n.prototype.update=function(e){if(null==this.width){var t=window.getComputedStyle?window.getComputedStyle(this.horiz.node):this.horiz.node.currentStyle;t&&(this.width=parseInt(t.height))}var n=this.width||0,i=e.scrollWidth>e.clientWidth+1,r=e.scrollHeight>e.clientHeight+1;return this.vert.node.style.display=r?"block":"none",this.horiz.node.style.display=i?"block":"none",r&&(this.vert.update(e.scrollHeight,e.clientHeight,e.viewHeight-(i?n:0)),this.vert.node.style.bottom=i?n+"px":"0"),i&&(this.horiz.update(e.scrollWidth,e.clientWidth,e.viewWidth-(r?n:0)-e.barLeft),this.horiz.node.style.right=r?n+"px":"0",this.horiz.node.style.left=e.barLeft+"px"),{right:r?n:0,bottom:i?n:0}},n.prototype.setScrollTop=function(e){this.vert.setPos(e)},n.prototype.setScrollLeft=function(e){this.horiz.setPos(e)},n.prototype.clear=function(){var e=this.horiz.node.parentNode;e.removeChild(this.horiz.node),e.removeChild(this.vert.node)},e.scrollbarModel.simple=function(e,t){return new n("CodeMirror-simplescroll",e,t)},e.scrollbarModel.overlay=function(e,t){return new n("CodeMirror-overlayscroll",e,t)}}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";function t(e,t){function n(e){clearTimeout(i.doRedraw),i.doRedraw=setTimeout(function(){i.redraw()},e)}this.cm=e,this.options=t,this.buttonHeight=t.scrollButtonHeight||e.getOption("scrollButtonHeight"),this.annotations=[],this.doRedraw=this.doUpdate=null,this.div=e.getWrapperElement().appendChild(document.createElement("div")),this.div.style.cssText="position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none",this.computeScale();var i=this;e.on("refresh",this.resizeHandler=function(){clearTimeout(i.doUpdate),i.doUpdate=setTimeout(function(){i.computeScale()&&n(20)},100)}),e.on("markerAdded",this.resizeHandler),e.on("markerCleared",this.resizeHandler),!1!==t.listenForChanges&&e.on("changes",this.changeHandler=function(){n(250)})}e.defineExtension("annotateScrollbar",function(e){return"string"==typeof e&&(e={className:e}),new t(this,e)}),e.defineOption("scrollButtonHeight",0),t.prototype.computeScale=function(){var e=this.cm,t=(e.getWrapperElement().clientHeight-e.display.barHeight-2*this.buttonHeight)/e.getScrollerElement().scrollHeight;if(t!=this.hScale)return this.hScale=t,!0},t.prototype.update=function(e){this.annotations=e,this.redraw()},t.prototype.redraw=function(e){!1!==e&&this.computeScale();var t=this.cm,n=this.hScale,i=document.createDocumentFragment(),r=this.annotations,o=t.getOption("lineWrapping"),a=o&&1.5*t.defaultTextHeight(),s=null,l=null;function c(e,n){return s!=e.line&&(s=e.line,l=t.getLineHandle(s)),l.widgets&&l.widgets.length||o&&l.height>a?t.charCoords(e,"local")[n?"top":"bottom"]:t.heightAtLine(l,"local")+(n?0:l.height)}var u=t.lastLine();if(t.display.barWidth)for(var d,h=0;hu)){for(var p=d||c(f.from,!0)*n,g=c(f.to,!1)*n;hu)&&!((d=c(r[h+1].from,!0)*n)>g+.9);)g=c((f=r[++h]).to,!1)*n;if(g!=p){var m=Math.max(g-p,3),v=i.appendChild(document.createElement("div"));v.style.cssText="position: absolute; right: 0px; width: "+Math.max(t.display.barWidth-1,2)+"px; top: "+(p+this.buttonHeight)+"px; height: "+m+"px",v.className=this.options.className,f.id&&v.setAttribute("annotation-id",f.id)}}}this.div.textContent="",this.div.appendChild(i)},t.prototype.clear=function(){this.cm.off("refresh",this.resizeHandler),this.cm.off("markerAdded",this.resizeHandler),this.cm.off("markerCleared",this.resizeHandler),this.changeHandler&&this.cm.off("changes",this.changeHandler),this.div.parentNode.removeChild(this.div)}}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";var t="CodeMirror-activeline",n="CodeMirror-activeline-background",i="CodeMirror-activeline-gutter";function r(e){for(var r=0;r!?|\/]/;function d(e,t){var i,f=e.next();if(l[f]){var p=l[f](e,t);if(!1!==p)return p}if('"'==f||"'"==f)return t.tokenize=(i=f,function(e,t){for(var n,r=!1,o=!1;null!=(n=e.next());){if(n==i&&!r){o=!0;break}r=!r&&"\\"==n}return(o||!r&&!c)&&(t.tokenize=d),"string"}),t.tokenize(e,t);if(/[\[\]{}\(\),;\:\.]/.test(f))return n=f,"bracket";if(/\d/.test(f))return e.eatWhile(/[\w\.]/),"number";if("/"==f){if(e.eat("*"))return t.tokenize=h,h(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(u.test(f))return e.eatWhile(u),"operator";e.eatWhile(/[\w\$_]/);var g=e.current();return r.propertyIsEnumerable(g)?(a.propertyIsEnumerable(g)&&(n="newstatement"),"keyword"):o.propertyIsEnumerable(g)?"builtin":s.propertyIsEnumerable(g)?"atom":"word"}function h(e,t){for(var n,i=!1;n=e.next();){if("/"==n&&i){t.tokenize=d;break}i="*"==n}return"comment"}function f(e,t,n,i,r){this.indented=e,this.column=t,this.type=n,this.align=i,this.prev=r}function p(e,t,n){return e.context=new f(e.indented,t,n,null,e.context)}function g(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}return{startState:function(e){return{tokenize:null,context:new f((e||0)-i,0,"top",!1),indented:0,startOfLine:!0}},token:function(e,t){var i=t.context;if(e.sol()&&(null==i.align&&(i.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return null;n=null;var r=(t.tokenize||d)(e,t);if("comment"==r||"meta"==r)return r;if(null==i.align&&(i.align=!0),";"!=n&&":"!=n||"statement"!=i.type)if("{"==n)p(t,e.column(),"}");else if("["==n)p(t,e.column(),"]");else if("("==n)p(t,e.column(),")");else if("}"==n){for(;"statement"==i.type;)i=g(t);for("}"==i.type&&(i=g(t));"statement"==i.type;)i=g(t)}else n==i.type?g(t):("}"==i.type||"top"==i.type||"statement"==i.type&&"newstatement"==n)&&p(t,e.column(),"statement");else g(t);return t.startOfLine=!1,r},indent:function(e,t){if(e.tokenize!=d&&null!=e.tokenize)return 0;var n=t&&t.charAt(0),r=e.context,o=n==r.type;return"statement"==r.type?r.indented+("{"==n?0:i):r.align?r.column+(o?0:1):r.indented+(o?0:i)},electricChars:"{}"}}),function(){function e(e){for(var t={},n=e.split(" "),i=0;i!?|~^@]/,f=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function p(e,t,n){return i=e,r=n,t}function g(e,t){var n,i=e.next();if('"'==i||"'"==i)return t.tokenize=(n=i,function(e,t){var i,r=!1;if(s&&"@"==e.peek()&&e.match(f))return t.tokenize=g,p("jsonld-keyword","meta");for(;null!=(i=e.next())&&(i!=n||r);)r=!r&&"\\"==i;return r||(t.tokenize=g),p("string","string")}),t.tokenize(e,t);if("."==i&&e.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return p("number","number");if("."==i&&e.match(".."))return p("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(i))return p(i);if("="==i&&e.eat(">"))return p("=>","operator");if("0"==i&&e.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return p("number","number");if(/\d/.test(i))return e.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),p("number","number");if("/"==i)return e.eat("*")?(t.tokenize=m,m(e,t)):e.eat("/")?(e.skipToEnd(),p("comment","comment")):qe(e,t,1)?(function(e){for(var t,n=!1,i=!1;null!=(t=e.next());){if(!n){if("/"==t&&!i)return;"["==t?i=!0:i&&"]"==t&&(i=!1)}n=!n&&"\\"==t}}(e),e.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),p("regexp","string-2")):(e.eat("="),p("operator","operator",e.current()));if("`"==i)return t.tokenize=v,v(e,t);if("#"==i)return e.skipToEnd(),p("error","error");if("<"==i&&e.match("!--")||"-"==i&&e.match("->"))return e.skipToEnd(),p("comment","comment");if(h.test(i))return">"==i&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=i&&"="!=i||e.eat("="):/[<>*+\-]/.test(i)&&(e.eat(i),">"==i&&e.eat(i))),p("operator","operator",e.current());if(u.test(i)){e.eatWhile(u);var r=e.current();if("."!=t.lastType){if(d.propertyIsEnumerable(r)){var o=d[r];return p(o.type,o.style,r)}if("async"==r&&e.match(/^(\s|\/\*.*?\*\/)*[\[\(\w]/,!1))return p("async","keyword",r)}return p("variable","variable",r)}}function m(e,t){for(var n,i=!1;n=e.next();){if("/"==n&&i){t.tokenize=g;break}i="*"==n}return p("comment","comment")}function v(e,t){for(var n,i=!1;null!=(n=e.next());){if(!i&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=g;break}i=!i&&"\\"==n}return p("quasi","string-2",e.current())}var C="([{}])";function y(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(n<0)){if(c){var i=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,n));i&&(n=i.index)}for(var r=0,o=!1,a=n-1;a>=0;--a){var s=e.string.charAt(a),l=C.indexOf(s);if(l>=0&&l<3){if(!r){++a;break}if(0==--r){"("==s&&(o=!0);break}}else if(l>=3&&l<6)++r;else if(u.test(s))o=!0;else if(/["'\/`]/.test(s))for(;;--a){if(0==a)return;if(e.string.charAt(a-1)==s&&"\\"!=e.string.charAt(a-2)){a--;break}}else if(o&&!r){++a;break}}o&&!r&&(t.fatArrowAt=a)}}var A={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0};function I(e,t,n,i,r,o){this.indented=e,this.column=t,this.type=n,this.prev=r,this.info=o,null!=i&&(this.align=i)}function _(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var i=e.context;i;i=i.prev)for(n=i.vars;n;n=n.next)if(n.name==t)return!0}var b={state:null,column:null,marked:null,cc:null};function w(){for(var e=arguments.length-1;e>=0;e--)b.cc.push(arguments[e])}function x(){return w.apply(null,arguments),!0}function E(e,t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}function S(e){var t=b.state;if(b.marked="def",t.context)if("var"==t.lexical.info&&t.context&&t.context.block){var i=function e(t,n){if(n){if(n.block){var i=e(t,n.prev);return i?i==n.prev?n:new T(i,n.vars,!0):null}return E(t,n.vars)?n:new T(n.prev,new L(t,n.vars),!1)}return null}(e,t.context);if(null!=i)return void(t.context=i)}else if(!E(e,t.localVars))return void(t.localVars=new L(e,t.localVars));n.globalVars&&!E(e,t.globalVars)&&(t.globalVars=new L(e,t.globalVars))}function k(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function T(e,t,n){this.prev=e,this.vars=t,this.block=n}function L(e,t){this.name=e,this.next=t}var M=new L("this",new L("arguments",null));function O(){b.state.context=new T(b.state.context,b.state.localVars,!1),b.state.localVars=M}function P(){b.state.context=new T(b.state.context,b.state.localVars,!0),b.state.localVars=null}function R(){b.state.localVars=b.state.context.vars,b.state.context=b.state.context.prev}function D(e,t){var n=function(){var n=b.state,i=n.indented;if("stat"==n.lexical.type)i=n.lexical.indented;else for(var r=n.lexical;r&&")"==r.type&&r.align;r=r.prev)i=r.indented;n.lexical=new I(i,b.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function N(){var e=b.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function B(e){return function t(n){return n==e?x():";"==e||"}"==n||")"==n||"]"==n?w():x(t)}}function F(e,t){return"var"==e?x(D("vardef",t),ye,B(";"),N):"keyword a"==e?x(D("form"),H,F,N):"keyword b"==e?x(D("form"),F,N):"keyword d"==e?b.stream.match(/^\s*$/,!1)?x():x(D("stat"),V,B(";"),N):"debugger"==e?x(B(";")):"{"==e?x(D("}"),P,ae,N,R):";"==e?x():"if"==e?("else"==b.state.lexical.info&&b.state.cc[b.state.cc.length-1]==N&&b.state.cc.pop()(),x(D("form"),H,F,N,xe)):"function"==e?x(Te):"for"==e?x(D("form"),Ee,F,N):"class"==e||c&&"interface"==t?(b.marked="keyword",x(D("form","class"==e?e:t),Re,N)):"variable"==e?c&&"declare"==t?(b.marked="keyword",x(F)):c&&("module"==t||"enum"==t||"type"==t)&&b.stream.match(/^\s*\w/,!1)?(b.marked="keyword","enum"==t?x(Xe):"type"==t?x(Me,B("operator"),de,B(";")):x(D("form"),Ae,B("{"),D("}"),ae,N,N)):c&&"namespace"==t?(b.marked="keyword",x(D("form"),z,F,N)):c&&"abstract"==t?(b.marked="keyword",x(F)):x(D("stat"),J):"switch"==e?x(D("form"),H,B("{"),D("}","switch"),P,ae,N,N,R):"case"==e?x(z,B(":")):"default"==e?x(B(":")):"catch"==e?x(D("form"),O,U,F,N,R):"export"==e?x(D("stat"),Fe,N):"import"==e?x(D("stat"),ze,N):"async"==e?x(F):"@"==t?x(z,F):w(D("stat"),z,B(";"),N)}function U(e){if("("==e)return x(Oe,B(")"))}function z(e,t){return j(e,t,!1)}function W(e,t){return j(e,t,!0)}function H(e){return"("!=e?w():x(D(")"),V,B(")"),N)}function j(e,t,n){if(b.state.fatArrowAt==b.stream.start){var i=n?Z:K;if("("==e)return x(O,D(")"),re(Oe,")"),N,B("=>"),i,R);if("variable"==e)return w(O,Ae,B("=>"),i,R)}var r=n?X:G;return A.hasOwnProperty(e)?x(r):"function"==e?x(Te,r):"class"==e||c&&"interface"==t?(b.marked="keyword",x(D("form"),Pe,N)):"keyword c"==e||"async"==e?x(n?W:z):"("==e?x(D(")"),V,B(")"),N,r):"operator"==e||"spread"==e?x(n?W:z):"["==e?x(D("]"),Ge,N,r):"{"==e?oe(te,"}",null,r):"quasi"==e?w(Y,r):"new"==e?x(function(e){return function(t){return"."==t?x(e?Q:$):"variable"==t&&c?x(me,e?X:G):w(e?W:z)}}(n)):"import"==e?x(z):x()}function V(e){return e.match(/[;\}\)\],]/)?w():w(z)}function G(e,t){return","==e?x(V):X(e,t,!1)}function X(e,t,n){var i=0==n?G:X,r=0==n?z:W;return"=>"==e?x(O,n?Z:K,R):"operator"==e?/\+\+|--/.test(t)||c&&"!"==t?x(i):c&&"<"==t&&b.stream.match(/^([^>]|<.*?>)*>\s*\(/,!1)?x(D(">"),re(de,">"),N,i):"?"==t?x(z,B(":"),r):x(r):"quasi"==e?w(Y,i):";"!=e?"("==e?oe(W,")","call",i):"."==e?x(ee,i):"["==e?x(D("]"),V,B("]"),N,i):c&&"as"==t?(b.marked="keyword",x(de,i)):"regexp"==e?(b.state.lastType=b.marked="operator",b.stream.backUp(b.stream.pos-b.stream.start-1),x(r)):void 0:void 0}function Y(e,t){return"quasi"!=e?w():"${"!=t.slice(t.length-2)?x(Y):x(z,q)}function q(e){if("}"==e)return b.marked="string-2",b.state.tokenize=v,x(Y)}function K(e){return y(b.stream,b.state),w("{"==e?F:z)}function Z(e){return y(b.stream,b.state),w("{"==e?F:W)}function $(e,t){if("target"==t)return b.marked="keyword",x(G)}function Q(e,t){if("target"==t)return b.marked="keyword",x(X)}function J(e){return":"==e?x(N,F):w(G,B(";"),N)}function ee(e){if("variable"==e)return b.marked="property",x()}function te(e,t){if("async"==e)return b.marked="property",x(te);if("variable"==e||"keyword"==b.style){return b.marked="property","get"==t||"set"==t?x(ne):(c&&b.state.fatArrowAt==b.stream.start&&(n=b.stream.match(/^\s*:\s*/,!1))&&(b.state.fatArrowAt=b.stream.pos+n[0].length),x(ie));var n}else{if("number"==e||"string"==e)return b.marked=s?"property":b.style+" property",x(ie);if("jsonld-keyword"==e)return x(ie);if(c&&k(t))return b.marked="keyword",x(te);if("["==e)return x(z,se,B("]"),ie);if("spread"==e)return x(W,ie);if("*"==t)return b.marked="keyword",x(te);if(":"==e)return w(ie)}}function ne(e){return"variable"!=e?w(ie):(b.marked="property",x(Te))}function ie(e){return":"==e?x(W):"("==e?w(Te):void 0}function re(e,t,n){function i(r,o){if(n?n.indexOf(r)>-1:","==r){var a=b.state.lexical;return"call"==a.info&&(a.pos=(a.pos||0)+1),x(function(n,i){return n==t||i==t?w():w(e)},i)}return r==t||o==t?x():n&&n.indexOf(";")>-1?w(e):x(B(t))}return function(n,r){return n==t||r==t?x():w(e,i)}}function oe(e,t,n){for(var i=3;i"),de):void 0}function he(e){if("=>"==e)return x(de)}function fe(e,t){return"variable"==e||"keyword"==b.style?(b.marked="property",x(fe)):"?"==t||"number"==e||"string"==e?x(fe):":"==e?x(de):"["==e?x(B("variable"),le,B("]"),fe):"("==e?w(Le,fe):void 0}function pe(e,t){return"variable"==e&&b.stream.match(/^\s*[?:]/,!1)||"?"==t?x(pe):":"==e?x(de):"spread"==e?x(pe):w(de)}function ge(e,t){return"<"==t?x(D(">"),re(de,">"),N,ge):"|"==t||"."==e||"&"==t?x(de):"["==e?x(de,B("]"),ge):"extends"==t||"implements"==t?(b.marked="keyword",x(de)):"?"==t?x(de,B(":"),de):void 0}function me(e,t){if("<"==t)return x(D(">"),re(de,">"),N,ge)}function ve(){return w(de,Ce)}function Ce(e,t){if("="==t)return x(de)}function ye(e,t){return"enum"==t?(b.marked="keyword",x(Xe)):w(Ae,se,be,we)}function Ae(e,t){return c&&k(t)?(b.marked="keyword",x(Ae)):"variable"==e?(S(t),x()):"spread"==e?x(Ae):"["==e?oe(_e,"]"):"{"==e?oe(Ie,"}"):void 0}function Ie(e,t){return"variable"!=e||b.stream.match(/^\s*:/,!1)?("variable"==e&&(b.marked="property"),"spread"==e?x(Ae):"}"==e?w():"["==e?x(z,B("]"),B(":"),Ie):x(B(":"),Ae,be)):(S(t),x(be))}function _e(){return w(Ae,be)}function be(e,t){if("="==t)return x(W)}function we(e){if(","==e)return x(ye)}function xe(e,t){if("keyword b"==e&&"else"==t)return x(D("form","else"),F,N)}function Ee(e,t){return"await"==t?x(Ee):"("==e?x(D(")"),Se,N):void 0}function Se(e){return"var"==e?x(ye,ke):"variable"==e?x(ke):w(ke)}function ke(e,t){return")"==e?x():";"==e?x(ke):"in"==t||"of"==t?(b.marked="keyword",x(z,ke)):w(z,ke)}function Te(e,t){return"*"==t?(b.marked="keyword",x(Te)):"variable"==e?(S(t),x(Te)):"("==e?x(O,D(")"),re(Oe,")"),N,ce,F,R):c&&"<"==t?x(D(">"),re(ve,">"),N,Te):void 0}function Le(e,t){return"*"==t?(b.marked="keyword",x(Le)):"variable"==e?(S(t),x(Le)):"("==e?x(O,D(")"),re(Oe,")"),N,ce,R):c&&"<"==t?x(D(">"),re(ve,">"),N,Le):void 0}function Me(e,t){return"keyword"==e||"variable"==e?(b.marked="type",x(Me)):"<"==t?x(D(">"),re(ve,">"),N):void 0}function Oe(e,t){return"@"==t&&x(z,Oe),"spread"==e?x(Oe):c&&k(t)?(b.marked="keyword",x(Oe)):c&&"this"==e?x(se,be):w(Ae,se,be)}function Pe(e,t){return"variable"==e?Re(e,t):De(e,t)}function Re(e,t){if("variable"==e)return S(t),x(De)}function De(e,t){return"<"==t?x(D(">"),re(ve,">"),N,De):"extends"==t||"implements"==t||c&&","==e?("implements"==t&&(b.marked="keyword"),x(c?de:z,De)):"{"==e?x(D("}"),Ne,N):void 0}function Ne(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||c&&k(t))&&b.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(b.marked="keyword",x(Ne)):"variable"==e||"keyword"==b.style?(b.marked="property",x(c?Be:Te,Ne)):"number"==e||"string"==e?x(c?Be:Te,Ne):"["==e?x(z,se,B("]"),c?Be:Te,Ne):"*"==t?(b.marked="keyword",x(Ne)):c&&"("==e?w(Le,Ne):";"==e||","==e?x(Ne):"}"==e?x():"@"==t?x(z,Ne):void 0}function Be(e,t){if("?"==t)return x(Be);if(":"==e)return x(de,be);if("="==t)return x(W);var n=b.state.lexical.prev;return w(n&&"interface"==n.info?Le:Te)}function Fe(e,t){return"*"==t?(b.marked="keyword",x(Ve,B(";"))):"default"==t?(b.marked="keyword",x(z,B(";"))):"{"==e?x(re(Ue,"}"),Ve,B(";")):w(F)}function Ue(e,t){return"as"==t?(b.marked="keyword",x(B("variable"))):"variable"==e?w(W,Ue):void 0}function ze(e){return"string"==e?x():"("==e?w(z):w(We,He,Ve)}function We(e,t){return"{"==e?oe(We,"}"):("variable"==e&&S(t),"*"==t&&(b.marked="keyword"),x(je))}function He(e){if(","==e)return x(We,He)}function je(e,t){if("as"==t)return b.marked="keyword",x(We)}function Ve(e,t){if("from"==t)return b.marked="keyword",x(z)}function Ge(e){return"]"==e?x():w(re(W,"]"))}function Xe(){return w(D("form"),Ae,B("{"),D("}"),re(Ye,"}"),N,N)}function Ye(){return w(Ae,be)}function qe(e,t,n){return t.tokenize==g&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(n||0)))}return R.lex=!0,N.lex=!0,{startState:function(e){var t={tokenize:g,lastType:"sof",cc:[],lexical:new I((e||0)-o,0,"block",!1),localVars:n.localVars,context:n.localVars&&new T(null,null,!1),indented:e||0};return n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),y(e,t)),t.tokenize!=m&&e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==i?n:(t.lastType="operator"!=i||"++"!=r&&"--"!=r?i:"incdec",function(e,t,n,i,r){var o=e.cc;for(b.state=e,b.stream=r,b.marked=null,b.cc=o,b.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():l?z:F)(n,i)){for(;o.length&&o[o.length-1].lex;)o.pop()();return b.marked?b.marked:"variable"==n&&_(e,i)?"variable-2":t}}(t,n,i,r,e))},indent:function(t,i){if(t.tokenize==m)return e.Pass;if(t.tokenize!=g)return 0;var r,s=i&&i.charAt(0),l=t.lexical;if(!/^\s*else\b/.test(i))for(var c=t.cc.length-1;c>=0;--c){var u=t.cc[c];if(u==N)l=l.prev;else if(u!=xe)break}for(;("stat"==l.type||"form"==l.type)&&("}"==s||(r=t.cc[t.cc.length-1])&&(r==G||r==X)&&!/^[,\.=+\-*:?[\(]/.test(i));)l=l.prev;a&&")"==l.type&&"stat"==l.prev.type&&(l=l.prev);var d=l.type,f=s==d;return"vardef"==d?l.indented+("operator"==t.lastType||","==t.lastType?l.info.length+1:0):"form"==d&&"{"==s?l.indented:"form"==d?l.indented+o:"stat"==d?l.indented+(function(e,t){return"operator"==e.lastType||","==e.lastType||h.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}(t,i)?a||o:0):"switch"!=l.info||f||0==n.doubleIndentSwitch?l.align?l.column+(f?0:1):l.indented+(f?0:o):l.indented+(/^(?:case|default)\b/.test(i)?o:2*o)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:l?null:"/*",blockCommentEnd:l?null:"*/",blockCommentContinue:l?null:" * ",lineComment:l?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:l?"json":"javascript",jsonldMode:s,jsonMode:l,expressionAllowed:qe,skipExpression:function(e){var t=e.cc[e.cc.length-1];t!=z&&t!=W||e.cc.pop()}}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})}),function(e){"object"==typeof exports&&"object"==typeof module?e(require("../../lib/codemirror")):"function"==typeof define&&define.amd?define(["../../lib/codemirror"],e):e(CodeMirror)}(function(e){"use strict";function t(e,t,n,i,r,o){this.indented=e,this.column=t,this.type=n,this.info=i,this.align=r,this.prev=o}function n(e,n,i,r){var o=e.indented;return e.context&&"statement"==e.context.type&&"statement"!=i&&(o=e.context.indented),e.context=new t(o,n,i,r,null,e.context)}function i(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}function r(e,t,n){return"variable"==t.prevToken||"type"==t.prevToken||(!!/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(e.string.slice(0,n))||(!(!t.typeAtEndOfLine||e.column()!=e.indentation())||void 0))}function o(e){for(;;){if(!e||"top"==e.type)return!0;if("}"==e.type&&"namespace"!=e.prev.info)return!1;e=e.prev}}function a(e){for(var t={},n=e.split(" "),i=0;i!?|\/]/,T=l.isIdentifierChar||/[\w\$_\xa1-\uffff]/,L=l.isReservedIdentifier||!1;function M(e,t){var n,i=e.next();if(A[i]){var r=A[i](e,t);if(!1!==r)return r}if('"'==i||"'"==i)return t.tokenize=(n=i,function(e,t){for(var i,r=!1,o=!1;null!=(i=e.next());){if(i==n&&!r){o=!0;break}r=!r&&"\\"==i}return(o||!r&&!I)&&(t.tokenize=null),"string"}),t.tokenize(e,t);if(x.test(i))return c=i,null;if(E.test(i)){if(e.backUp(1),e.match(S))return"number";e.next()}if("/"==i){if(e.eat("*"))return t.tokenize=O,O(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(k.test(i)){for(;!e.match(/^\/[\/*]/,!1)&&e.eat(k););return"operator"}if(e.eatWhile(T),w)for(;e.match(w);)e.eatWhile(T);var o=e.current();return s(p,o)?(s(v,o)&&(c="newstatement"),s(C,o)&&(u=!0),"keyword"):s(g,o)?"type":s(m,o)||L&&L(o)?(s(v,o)&&(c="newstatement"),"builtin"):s(y,o)?"atom":"variable"}function O(e,t){for(var n,i=!1;n=e.next();){if("/"==n&&i){t.tokenize=null;break}i="*"==n}return"comment"}function P(e,t){l.typeFirstDefinitions&&e.eol()&&o(t.context)&&(t.typeAtEndOfLine=r(e,t,e.pos))}return{startState:function(e){return{tokenize:null,context:new t((e||0)-d,0,"top",null,!1),indented:0,startOfLine:!0,prevToken:null}},token:function(e,t){var a=t.context;if(e.sol()&&(null==a.align&&(a.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return P(e,t),null;c=u=null;var s=(t.tokenize||M)(e,t);if("comment"==s||"meta"==s)return s;if(null==a.align&&(a.align=!0),";"==c||":"==c||","==c&&e.match(/^\s*(?:\/\/.*)?$/,!1))for(;"statement"==t.context.type;)i(t);else if("{"==c)n(t,e.column(),"}");else if("["==c)n(t,e.column(),"]");else if("("==c)n(t,e.column(),")");else if("}"==c){for(;"statement"==a.type;)a=i(t);for("}"==a.type&&(a=i(t));"statement"==a.type;)a=i(t)}else c==a.type?i(t):_&&(("}"==a.type||"top"==a.type)&&";"!=c||"statement"==a.type&&"newstatement"==c)&&n(t,e.column(),"statement",e.current());if("variable"==s&&("def"==t.prevToken||l.typeFirstDefinitions&&r(e,t,e.start)&&o(t.context)&&e.match(/^\s*\(/,!1))&&(s="def"),A.token){var d=A.token(e,t,s);void 0!==d&&(s=d)}return"def"==s&&!1===l.styleDefs&&(s="variable"),t.startOfLine=!1,t.prevToken=u?"def":s||c,P(e,t),s},indent:function(t,n){if(t.tokenize!=M&&null!=t.tokenize||t.typeAtEndOfLine)return e.Pass;var i=t.context,r=n&&n.charAt(0),o=r==i.type;if("statement"==i.type&&"}"==r&&(i=i.prev),l.dontIndentStatements)for(;"statement"==i.type&&l.dontIndentStatements.test(i.info);)i=i.prev;if(A.indent){var a=A.indent(t,i,n,d);if("number"==typeof a)return a}var s=i.prev&&"switch"==i.prev.info;if(l.allmanIndentation&&/[{(]/.test(r)){for(;"top"!=i.type&&"}"!=i.type;)i=i.prev;return i.indented}return"statement"==i.type?i.indented+("{"==r?0:h):!i.align||f&&")"==i.type?")"!=i.type||o?i.indented+(o?0:d)+(o||!s||/^(?:case|default)\b/.test(n)?0:d):i.indented+h:i.column+(o?0:1)},electricInput:b?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:"//",fold:"brace"}});var l="auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran",c="alignas alignof and and_eq audit axiom bitand bitor catch class compl concept constexpr const_cast decltype delete dynamic_cast explicit export final friend import module mutable namespace new noexcept not not_eq operator or or_eq override private protected public reinterpret_cast requires static_assert static_cast template this thread_local throw try typeid typename using virtual xor xor_eq",u="bycopy byref in inout oneway out self super atomic nonatomic retain copy readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd @interface @implementation @end @protocol @encode @property @synthesize @dynamic @class @public @package @private @protected @required @optional @try @catch @finally @import @selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available",d="FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINEDNS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT",h=a("int long char short double float unsigned signed void bool"),f=a("SEL instancetype id Class Protocol BOOL");function p(e){return s(h,e)||/.+_t$/.test(e)}function g(e){return p(e)||s(f,e)}var m="case do else for if switch while struct enum union";function v(e,t){if(!t.startOfLine)return!1;for(var n,i=null;n=e.peek();){if("\\"==n&&e.match(/^.$/)){i=v;break}if("/"==n&&e.match(/^\/[\/\*]/,!1))break;e.next()}return t.tokenize=i,"meta"}function C(e,t){return"type"==t.prevToken&&"type"}function y(e){return!(!e||e.length<2)&&("_"==e[0]&&("_"==e[1]||e[1]!==e[1].toLowerCase()))}function A(e){return e.eatWhile(/[\w\.']/),"number"}function I(e,t){if(e.backUp(1),e.match(/(R|u8R|uR|UR|LR)/)){var n=e.match(/"([^\s\\()]{0,16})\(/);return!!n&&(t.cpp11RawStringDelim=n[1],t.tokenize=w,w(e,t))}return e.match(/(u8|u|U|L)/)?!!e.match(/["']/,!1)&&"string":(e.next(),!1)}function _(e){var t=/(\w+)::~?(\w+)$/.exec(e);return t&&t[1]==t[2]}function b(e,t){for(var n;null!=(n=e.next());)if('"'==n&&!e.eat('"')){t.tokenize=null;break}return"string"}function w(e,t){var n=t.cpp11RawStringDelim.replace(/[^\w\s]/g,"\\$&");return e.match(new RegExp(".*?\\)"+n+'"'))?t.tokenize=null:e.skipToEnd(),"string"}function x(t,n){"string"==typeof t&&(t=[t]);var i=[];function r(e){if(e)for(var t in e)e.hasOwnProperty(t)&&i.push(t)}r(n.keywords),r(n.types),r(n.builtin),r(n.atoms),i.length&&(n.helperType=t[0],e.registerHelper("hintWords",t[0],i));for(var o=0;o!?|\/#:@]/,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return!!e.match('""')&&(t.tokenize=E,t.tokenize(e,t))},"'":function(e){return e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},"=":function(e,n){var i=n.context;return!("}"!=i.type||!i.align||!e.eat(">"))&&(n.context=new t(i.indented,i.column,i.type,i.info,null,i.prev),"operator")},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=S(1),t.tokenize(e,t))}},modeProps:{closeBrackets:{pairs:'()[]{}""',triples:'"'}}}),x("text/x-kotlin",{name:"clike",keywords:a("package as typealias class interface this super val operator var fun for is in This throw return annotation break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix suspend actual expect setparam"),types:a("Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy LazyThreadSafetyMode LongArray Nothing ShortArray Unit"),intendSwitch:!1,indentStatements:!1,multiLineStrings:!0,number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,blockKeywords:a("catch class do else finally for if where try while enum"),defKeywords:a("class val var object interface fun"),atoms:a("true false null this"),hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},"*":function(e,t){return"."==t.prevToken?"variable":"operator"},'"':function(e,t){var n;return t.tokenize=(n=e.match('""'),function(e,t){for(var i,r=!1,o=!1;!e.eol();){if(!n&&!r&&e.match('"')){o=!0;break}if(n&&e.match('"""')){o=!0;break}i=e.next(),!r&&"$"==i&&e.match("{")&&e.skipTo("}"),r=!r&&"\\"==i&&!n}return!o&&n||(t.tokenize=null),"string"}),t.tokenize(e,t)},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=S(1),t.tokenize(e,t))},indent:function(e,t,n,i){var r=n&&n.charAt(0);return"}"!=e.prevToken&&")"!=e.prevToken||""!=n?"operator"==e.prevToken&&"}"!=n&&"}"!=e.context.type||"variable"==e.prevToken&&"."==r||("}"==e.prevToken||")"==e.prevToken)&&"."==r?2*i+t.indented:t.align&&"}"==t.type?t.indented+(e.context.type==(n||"").charAt(0)?0:i):void 0:e.indented}},modeProps:{closeBrackets:{triples:'"'}}}),x(["x-shader/x-vertex","x-shader/x-fragment"],{name:"clike",keywords:a("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:a("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:a("for while do if else struct"),builtin:a("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:a("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":v},modeProps:{fold:["brace","include"]}}),x("text/x-nesc",{name:"clike",keywords:a(l+" as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:p,blockKeywords:a(m),atoms:a("null true false"),hooks:{"#":v},modeProps:{fold:["brace","include"]}}),x("text/x-objectivec",{name:"clike",keywords:a(l+" "+u),types:g,builtin:a(d),blockKeywords:a(m+" @synthesize @try @catch @finally @autoreleasepool @synchronized"),defKeywords:a("struct enum union @interface @implementation @protocol @class"),dontIndentStatements:/^@.*$/,typeFirstDefinitions:!0,atoms:a("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:y,hooks:{"#":v,"*":C},modeProps:{fold:["brace","include"]}}),x("text/x-objectivec++",{name:"clike",keywords:a(l+" "+u+" "+c),types:g,builtin:a(d),blockKeywords:a(m+" @synthesize @try @catch @finally @autoreleasepool @synchronized class try catch"),defKeywords:a("struct enum union @interface @implementation @protocol @class class namespace"),dontIndentStatements:/^@.*$|^template$/,typeFirstDefinitions:!0,atoms:a("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:y,hooks:{"#":v,"*":C,u:I,U:I,L:I,R:I,0:A,1:A,2:A,3:A,4:A,5:A,6:A,7:A,8:A,9:A,token:function(e,t,n){if("variable"==n&&"("==e.peek()&&(";"==t.prevToken||null==t.prevToken||"}"==t.prevToken)&&_(e.current()))return"def"}},namespaceSeparator:"::",modeProps:{fold:["brace","include"]}}),x("text/x-squirrel",{name:"clike",keywords:a("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:p,blockKeywords:a("case catch class else for foreach if switch try while"),defKeywords:a("function local class"),typeFirstDefinitions:!0,atoms:a("true false null"),hooks:{"#":v},modeProps:{fold:["brace","include"]}});var k=null;x("text/x-ceylon",{name:"clike",keywords:a("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"),types:function(e){var t=e.charAt(0);return t===t.toUpperCase()&&t!==t.toLowerCase()},blockKeywords:a("case catch class dynamic else finally for function if interface module new object switch try while"),defKeywords:a("class dynamic function interface module object package value"),builtin:a("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"),isPunctuationChar:/[\[\]{}\(\),;\:\.`]/,isOperatorChar:/[+\-*&%=<>!?|^~:\/]/,numberStart:/[\d#$]/,number:/^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,multiLineStrings:!0,typeFirstDefinitions:!0,atoms:a("true false null larger smaller equal empty finished"),indentSwitch:!1,styleDefs:!1,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return t.tokenize=function e(t){return function(n,i){for(var r,o=!1,a=!1;!n.eol();){if(!o&&n.match('"')&&("single"==t||n.match('""'))){a=!0;break}if(!o&&n.match("``")){k=e(t),a=!0;break}r=n.next(),o="single"==t&&!o&&"\\"==r}return a&&(i.tokenize=null),"string"}}(e.match('""')?"triple":"single"),t.tokenize(e,t)},"`":function(e,t){return!(!k||!e.match("`"))&&(t.tokenize=k,k=null,t.tokenize(e,t))},"'":function(e){return e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},token:function(e,t,n){if(("variable"==n||"type"==n)&&"."==t.prevToken)return"variable-2"}},modeProps:{fold:["brace","import"],closeBrackets:{triples:'"'}}})}),function(){function e(e){"use strict";var t={omitExtraWLInCodeBlocks:{defaultValue:!1,describe:"Omit the default extra whiteline added to code blocks",type:"boolean"},noHeaderId:{defaultValue:!1,describe:"Turn on/off generated header id",type:"boolean"},prefixHeaderId:{defaultValue:!1,describe:"Add a prefix to the generated header ids. Passing a string will prefix that string to the header id. Setting to true will add a generic 'section-' prefix",type:"string"},rawPrefixHeaderId:{defaultValue:!1,describe:'Setting this option to true will prevent showdown from modifying the prefix. This might result in malformed IDs (if, for instance, the " char is used in the prefix)',type:"boolean"},ghCompatibleHeaderId:{defaultValue:!1,describe:"Generate header ids compatible with github style (spaces are replaced with dashes, a bunch of non alphanumeric chars are removed)",type:"boolean"},rawHeaderId:{defaultValue:!1,describe:"Remove only spaces, ' and \" from generated header ids (including prefixes), replacing them with dashes (-). WARNING: This might result in malformed ids",type:"boolean"},headerLevelStart:{defaultValue:!1,describe:"The header blocks level start",type:"integer"},parseImgDimensions:{defaultValue:!1,describe:"Turn on/off image dimension parsing",type:"boolean"},simplifiedAutoLink:{defaultValue:!1,describe:"Turn on/off GFM autolink style",type:"boolean"},excludeTrailingPunctuationFromURLs:{defaultValue:!1,describe:"Excludes trailing punctuation from links generated with autoLinking",type:"boolean"},literalMidWordUnderscores:{defaultValue:!1,describe:"Parse midword underscores as literal underscores",type:"boolean"},literalMidWordAsterisks:{defaultValue:!1,describe:"Parse midword asterisks as literal asterisks",type:"boolean"},strikethrough:{defaultValue:!1,describe:"Turn on/off strikethrough support",type:"boolean"},tables:{defaultValue:!1,describe:"Turn on/off tables support",type:"boolean"},tablesHeaderId:{defaultValue:!1,describe:"Add an id to table headers",type:"boolean"},ghCodeBlocks:{defaultValue:!0,describe:"Turn on/off GFM fenced code blocks support",type:"boolean"},tasklists:{defaultValue:!1,describe:"Turn on/off GFM tasklist support",type:"boolean"},smoothLivePreview:{defaultValue:!1,describe:"Prevents weird effects in live previews due to incomplete input",type:"boolean"},smartIndentationFix:{defaultValue:!1,description:"Tries to smartly fix indentation in es6 strings",type:"boolean"},disableForced4SpacesIndentedSublists:{defaultValue:!1,description:"Disables the requirement of indenting nested sublists by 4 spaces",type:"boolean"},simpleLineBreaks:{defaultValue:!1,description:"Parses simple line breaks as
    (GFM Style)",type:"boolean"},requireSpaceBeforeHeadingText:{defaultValue:!1,description:"Makes adding a space between `#` and the header text mandatory (GFM Style)",type:"boolean"},ghMentions:{defaultValue:!1,description:"Enables github @mentions",type:"boolean"},ghMentionsLink:{defaultValue:"https://github.com/{u}",description:"Changes the link generated by @mentions. Only applies if ghMentions option is enabled.",type:"string"},encodeEmails:{defaultValue:!0,description:"Encode e-mail addresses through the use of Character Entities, transforming ASCII e-mail addresses into its equivalent decimal entities",type:"boolean"},openLinksInNewWindow:{defaultValue:!1,description:"Open all links in new windows",type:"boolean"},backslashEscapesHTMLTags:{defaultValue:!1,description:"Support for HTML Tag escaping. ex:
    foo
    ",type:"boolean"},emoji:{defaultValue:!1,description:"Enable emoji support. Ex: `this is a :smile: emoji`",type:"boolean"},underline:{defaultValue:!1,description:"Enable support for underline. Syntax is double or triple underscores: `__underline word__`. With this option enabled, underscores no longer parses into `` and ``",type:"boolean"},completeHTMLDocument:{defaultValue:!1,description:"Outputs a complete html document, including ``, `` and `` tags",type:"boolean"},metadata:{defaultValue:!1,description:"Enable support for document metadata (defined at the top of the document between `«««` and `»»»` or between `---` and `---`).",type:"boolean"},splitAdjacentBlockquotes:{defaultValue:!1,description:"Split adjacent blockquote blocks",type:"boolean"}};if(!1===e)return JSON.parse(JSON.stringify(t));var n={};for(var i in t)t.hasOwnProperty(i)&&(n[i]=t[i].defaultValue);return n}function t(e,t){"use strict";var n=t?"Error in "+t+" extension->":"Error in unnamed extension",r={valid:!0,error:""};i.helper.isArray(e)||(e=[e]);for(var o=0;o-1,d=new RegExp(t+"|"+n,"g"+c.replace(/g/g,"")),h=new RegExp(t,c.replace(/g/g,"")),f=[];do{for(r=0;a=d.exec(e);)if(h.test(a[0]))r++||(s=(o=d.lastIndex)-a[0].length);else if(r&&!--r){l=a.index+a[0].length;var p={left:{start:s,end:o},match:{start:o,end:a.index},right:{start:a.index,end:l},wholeMatch:{start:s,end:l}};if(f.push(p),!u)return f}}while(r&&(d.lastIndex=o));return f};i.helper.matchRecursiveRegExp=function(e,t,n,i){"use strict";for(var r=c(e,t,n,i),o=[],a=0;a0){var d=[];0!==s[0].wholeMatch.start&&d.push(e.slice(0,s[0].wholeMatch.start));for(var h=0;h=0?r+(n||0):r},i.helper.splitAtIndex=function(e,t){"use strict";if(!i.helper.isString(e))throw"InvalidArgumentError: first parameter of showdown.helper.regexIndexOf function must be a string";return[e.substring(0,t),e.substring(t)]},i.helper.encodeEmailAddress=function(e){"use strict";var t=[function(e){return"&#"+e.charCodeAt(0)+";"},function(e){return"&#x"+e.charCodeAt(0).toString(16)+";"},function(e){return e}];return e.replace(/./g,function(e){if("@"===e)e=t[Math.floor(2*Math.random())](e);else{var n=Math.random();e=n>.9?t[2](e):n>.45?t[1](e):t[0](e)}return e})},"undefined"==typeof console&&(console={warn:function(e){"use strict";alert(e)},log:function(e){"use strict";alert(e)},error:function(e){"use strict";throw e}}),i.helper.regexes={asteriskDashAndColon:/([*_:~])/g},i.helper.emojis={"+1":"👍","-1":"👎",100:"💯",1234:"🔢","1st_place_medal":"🥇","2nd_place_medal":"🥈","3rd_place_medal":"🥉","8ball":"🎱",a:"🅰️",ab:"🆎",abc:"🔤",abcd:"🔡",accept:"🉑",aerial_tramway:"🚡",airplane:"✈️",alarm_clock:"⏰",alembic:"⚗️",alien:"👽",ambulance:"🚑",amphora:"🏺",anchor:"⚓️",angel:"👼",anger:"💢",angry:"😠",anguished:"😧",ant:"🐜",apple:"🍎",aquarius:"♒️",aries:"♈️",arrow_backward:"◀️",arrow_double_down:"⏬",arrow_double_up:"⏫",arrow_down:"⬇️",arrow_down_small:"🔽",arrow_forward:"▶️",arrow_heading_down:"⤵️",arrow_heading_up:"⤴️",arrow_left:"⬅️",arrow_lower_left:"↙️",arrow_lower_right:"↘️",arrow_right:"➡️",arrow_right_hook:"↪️",arrow_up:"⬆️",arrow_up_down:"↕️",arrow_up_small:"🔼",arrow_upper_left:"↖️",arrow_upper_right:"↗️",arrows_clockwise:"🔃",arrows_counterclockwise:"🔄",art:"🎨",articulated_lorry:"🚛",artificial_satellite:"🛰",astonished:"😲",athletic_shoe:"👟",atm:"🏧",atom_symbol:"⚛️",avocado:"🥑",b:"🅱️",baby:"👶",baby_bottle:"🍼",baby_chick:"🐤",baby_symbol:"🚼",back:"🔙",bacon:"🥓",badminton:"🏸",baggage_claim:"🛄",baguette_bread:"🥖",balance_scale:"⚖️",balloon:"🎈",ballot_box:"🗳",ballot_box_with_check:"☑️",bamboo:"🎍",banana:"🍌",bangbang:"‼️",bank:"🏦",bar_chart:"📊",barber:"💈",baseball:"⚾️",basketball:"🏀",basketball_man:"⛹️",basketball_woman:"⛹️‍♀️",bat:"🦇",bath:"🛀",bathtub:"🛁",battery:"🔋",beach_umbrella:"🏖",bear:"🐻",bed:"🛏",bee:"🐝",beer:"🍺",beers:"🍻",beetle:"🐞",beginner:"🔰",bell:"🔔",bellhop_bell:"🛎",bento:"🍱",biking_man:"🚴",bike:"🚲",biking_woman:"🚴‍♀️",bikini:"👙",biohazard:"☣️",bird:"🐦",birthday:"🎂",black_circle:"⚫️",black_flag:"🏴",black_heart:"🖤",black_joker:"🃏",black_large_square:"⬛️",black_medium_small_square:"◾️",black_medium_square:"◼️",black_nib:"✒️",black_small_square:"▪️",black_square_button:"🔲",blonde_man:"👱",blonde_woman:"👱‍♀️",blossom:"🌼",blowfish:"🐡",blue_book:"📘",blue_car:"🚙",blue_heart:"💙",blush:"😊",boar:"🐗",boat:"⛵️",bomb:"💣",book:"📖",bookmark:"🔖",bookmark_tabs:"📑",books:"📚",boom:"💥",boot:"👢",bouquet:"💐",bowing_man:"🙇",bow_and_arrow:"🏹",bowing_woman:"🙇‍♀️",bowling:"🎳",boxing_glove:"🥊",boy:"👦",bread:"🍞",bride_with_veil:"👰",bridge_at_night:"🌉",briefcase:"💼",broken_heart:"💔",bug:"🐛",building_construction:"🏗",bulb:"💡",bullettrain_front:"🚅",bullettrain_side:"🚄",burrito:"🌯",bus:"🚌",business_suit_levitating:"🕴",busstop:"🚏",bust_in_silhouette:"👤",busts_in_silhouette:"👥",butterfly:"🦋",cactus:"🌵",cake:"🍰",calendar:"📆",call_me_hand:"🤙",calling:"📲",camel:"🐫",camera:"📷",camera_flash:"📸",camping:"🏕",cancer:"♋️",candle:"🕯",candy:"🍬",canoe:"🛶",capital_abcd:"🔠",capricorn:"♑️",car:"🚗",card_file_box:"🗃",card_index:"📇",card_index_dividers:"🗂",carousel_horse:"🎠",carrot:"🥕",cat:"🐱",cat2:"🐈",cd:"💿",chains:"⛓",champagne:"🍾",chart:"💹",chart_with_downwards_trend:"📉",chart_with_upwards_trend:"📈",checkered_flag:"🏁",cheese:"🧀",cherries:"🍒",cherry_blossom:"🌸",chestnut:"🌰",chicken:"🐔",children_crossing:"🚸",chipmunk:"🐿",chocolate_bar:"🍫",christmas_tree:"🎄",church:"⛪️",cinema:"🎦",circus_tent:"🎪",city_sunrise:"🌇",city_sunset:"🌆",cityscape:"🏙",cl:"🆑",clamp:"🗜",clap:"👏",clapper:"🎬",classical_building:"🏛",clinking_glasses:"🥂",clipboard:"📋",clock1:"🕐",clock10:"🕙",clock1030:"🕥",clock11:"🕚",clock1130:"🕦",clock12:"🕛",clock1230:"🕧",clock130:"🕜",clock2:"🕑",clock230:"🕝",clock3:"🕒",clock330:"🕞",clock4:"🕓",clock430:"🕟",clock5:"🕔",clock530:"🕠",clock6:"🕕",clock630:"🕡",clock7:"🕖",clock730:"🕢",clock8:"🕗",clock830:"🕣",clock9:"🕘",clock930:"🕤",closed_book:"📕",closed_lock_with_key:"🔐",closed_umbrella:"🌂",cloud:"☁️",cloud_with_lightning:"🌩",cloud_with_lightning_and_rain:"⛈",cloud_with_rain:"🌧",cloud_with_snow:"🌨",clown_face:"🤡",clubs:"♣️",cocktail:"🍸",coffee:"☕️",coffin:"⚰️",cold_sweat:"😰",comet:"☄️",computer:"💻",computer_mouse:"🖱",confetti_ball:"🎊",confounded:"😖",confused:"😕",congratulations:"㊗️",construction:"🚧",construction_worker_man:"👷",construction_worker_woman:"👷‍♀️",control_knobs:"🎛",convenience_store:"🏪",cookie:"🍪",cool:"🆒",policeman:"👮",copyright:"©️",corn:"🌽",couch_and_lamp:"🛋",couple:"👫",couple_with_heart_woman_man:"💑",couple_with_heart_man_man:"👨‍❤️‍👨",couple_with_heart_woman_woman:"👩‍❤️‍👩",couplekiss_man_man:"👨‍❤️‍💋‍👨",couplekiss_man_woman:"💏",couplekiss_woman_woman:"👩‍❤️‍💋‍👩",cow:"🐮",cow2:"🐄",cowboy_hat_face:"🤠",crab:"🦀",crayon:"🖍",credit_card:"💳",crescent_moon:"🌙",cricket:"🏏",crocodile:"🐊",croissant:"🥐",crossed_fingers:"🤞",crossed_flags:"🎌",crossed_swords:"⚔️",crown:"👑",cry:"😢",crying_cat_face:"😿",crystal_ball:"🔮",cucumber:"🥒",cupid:"💘",curly_loop:"➰",currency_exchange:"💱",curry:"🍛",custard:"🍮",customs:"🛃",cyclone:"🌀",dagger:"🗡",dancer:"💃",dancing_women:"👯",dancing_men:"👯‍♂️",dango:"🍡",dark_sunglasses:"🕶",dart:"🎯",dash:"💨",date:"📅",deciduous_tree:"🌳",deer:"🦌",department_store:"🏬",derelict_house:"🏚",desert:"🏜",desert_island:"🏝",desktop_computer:"🖥",male_detective:"🕵️",diamond_shape_with_a_dot_inside:"💠",diamonds:"♦️",disappointed:"😞",disappointed_relieved:"😥",dizzy:"💫",dizzy_face:"😵",do_not_litter:"🚯",dog:"🐶",dog2:"🐕",dollar:"💵",dolls:"🎎",dolphin:"🐬",door:"🚪",doughnut:"🍩",dove:"🕊",dragon:"🐉",dragon_face:"🐲",dress:"👗",dromedary_camel:"🐪",drooling_face:"🤤",droplet:"💧",drum:"🥁",duck:"🦆",dvd:"📀","e-mail":"📧",eagle:"🦅",ear:"👂",ear_of_rice:"🌾",earth_africa:"🌍",earth_americas:"🌎",earth_asia:"🌏",egg:"🥚",eggplant:"🍆",eight_pointed_black_star:"✴️",eight_spoked_asterisk:"✳️",electric_plug:"🔌",elephant:"🐘",email:"✉️",end:"🔚",envelope_with_arrow:"📩",euro:"💶",european_castle:"🏰",european_post_office:"🏤",evergreen_tree:"🌲",exclamation:"❗️",expressionless:"😑",eye:"👁",eye_speech_bubble:"👁‍🗨",eyeglasses:"👓",eyes:"👀",face_with_head_bandage:"🤕",face_with_thermometer:"🤒",fist_oncoming:"👊",factory:"🏭",fallen_leaf:"🍂",family_man_woman_boy:"👪",family_man_boy:"👨‍👦",family_man_boy_boy:"👨‍👦‍👦",family_man_girl:"👨‍👧",family_man_girl_boy:"👨‍👧‍👦",family_man_girl_girl:"👨‍👧‍👧",family_man_man_boy:"👨‍👨‍👦",family_man_man_boy_boy:"👨‍👨‍👦‍👦",family_man_man_girl:"👨‍👨‍👧",family_man_man_girl_boy:"👨‍👨‍👧‍👦",family_man_man_girl_girl:"👨‍👨‍👧‍👧",family_man_woman_boy_boy:"👨‍👩‍👦‍👦",family_man_woman_girl:"👨‍👩‍👧",family_man_woman_girl_boy:"👨‍👩‍👧‍👦",family_man_woman_girl_girl:"👨‍👩‍👧‍👧",family_woman_boy:"👩‍👦",family_woman_boy_boy:"👩‍👦‍👦",family_woman_girl:"👩‍👧",family_woman_girl_boy:"👩‍👧‍👦",family_woman_girl_girl:"👩‍👧‍👧",family_woman_woman_boy:"👩‍👩‍👦",family_woman_woman_boy_boy:"👩‍👩‍👦‍👦",family_woman_woman_girl:"👩‍👩‍👧",family_woman_woman_girl_boy:"👩‍👩‍👧‍👦",family_woman_woman_girl_girl:"👩‍👩‍👧‍👧",fast_forward:"⏩",fax:"📠",fearful:"😨",feet:"🐾",female_detective:"🕵️‍♀️",ferris_wheel:"🎡",ferry:"⛴",field_hockey:"🏑",file_cabinet:"🗄",file_folder:"📁",film_projector:"📽",film_strip:"🎞",fire:"🔥",fire_engine:"🚒",fireworks:"🎆",first_quarter_moon:"🌓",first_quarter_moon_with_face:"🌛",fish:"🐟",fish_cake:"🍥",fishing_pole_and_fish:"🎣",fist_raised:"✊",fist_left:"🤛",fist_right:"🤜",flags:"🎏",flashlight:"🔦",fleur_de_lis:"⚜️",flight_arrival:"🛬",flight_departure:"🛫",floppy_disk:"💾",flower_playing_cards:"🎴",flushed:"😳",fog:"🌫",foggy:"🌁",football:"🏈",footprints:"👣",fork_and_knife:"🍴",fountain:"⛲️",fountain_pen:"🖋",four_leaf_clover:"🍀",fox_face:"🦊",framed_picture:"🖼",free:"🆓",fried_egg:"🍳",fried_shrimp:"🍤",fries:"🍟",frog:"🐸",frowning:"😦",frowning_face:"☹️",frowning_man:"🙍‍♂️",frowning_woman:"🙍",middle_finger:"🖕",fuelpump:"⛽️",full_moon:"🌕",full_moon_with_face:"🌝",funeral_urn:"⚱️",game_die:"🎲",gear:"⚙️",gem:"💎",gemini:"♊️",ghost:"👻",gift:"🎁",gift_heart:"💝",girl:"👧",globe_with_meridians:"🌐",goal_net:"🥅",goat:"🐐",golf:"⛳️",golfing_man:"🏌️",golfing_woman:"🏌️‍♀️",gorilla:"🦍",grapes:"🍇",green_apple:"🍏",green_book:"📗",green_heart:"💚",green_salad:"🥗",grey_exclamation:"❕",grey_question:"❔",grimacing:"😬",grin:"😁",grinning:"😀",guardsman:"💂",guardswoman:"💂‍♀️",guitar:"🎸",gun:"🔫",haircut_woman:"💇",haircut_man:"💇‍♂️",hamburger:"🍔",hammer:"🔨",hammer_and_pick:"⚒",hammer_and_wrench:"🛠",hamster:"🐹",hand:"✋",handbag:"👜",handshake:"🤝",hankey:"💩",hatched_chick:"🐥",hatching_chick:"🐣",headphones:"🎧",hear_no_evil:"🙉",heart:"❤️",heart_decoration:"💟",heart_eyes:"😍",heart_eyes_cat:"😻",heartbeat:"💓",heartpulse:"💗",hearts:"♥️",heavy_check_mark:"✔️",heavy_division_sign:"➗",heavy_dollar_sign:"💲",heavy_heart_exclamation:"❣️",heavy_minus_sign:"➖",heavy_multiplication_x:"✖️",heavy_plus_sign:"➕",helicopter:"🚁",herb:"🌿",hibiscus:"🌺",high_brightness:"🔆",high_heel:"👠",hocho:"🔪",hole:"🕳",honey_pot:"🍯",horse:"🐴",horse_racing:"🏇",hospital:"🏥",hot_pepper:"🌶",hotdog:"🌭",hotel:"🏨",hotsprings:"♨️",hourglass:"⌛️",hourglass_flowing_sand:"⏳",house:"🏠",house_with_garden:"🏡",houses:"🏘",hugs:"🤗",hushed:"😯",ice_cream:"🍨",ice_hockey:"🏒",ice_skate:"⛸",icecream:"🍦",id:"🆔",ideograph_advantage:"🉐",imp:"👿",inbox_tray:"📥",incoming_envelope:"📨",tipping_hand_woman:"💁",information_source:"ℹ️",innocent:"😇",interrobang:"⁉️",iphone:"📱",izakaya_lantern:"🏮",jack_o_lantern:"🎃",japan:"🗾",japanese_castle:"🏯",japanese_goblin:"👺",japanese_ogre:"👹",jeans:"👖",joy:"😂",joy_cat:"😹",joystick:"🕹",kaaba:"🕋",key:"🔑",keyboard:"⌨️",keycap_ten:"🔟",kick_scooter:"🛴",kimono:"👘",kiss:"💋",kissing:"😗",kissing_cat:"😽",kissing_closed_eyes:"😚",kissing_heart:"😘",kissing_smiling_eyes:"😙",kiwi_fruit:"🥝",koala:"🐨",koko:"🈁",label:"🏷",large_blue_circle:"🔵",large_blue_diamond:"🔷",large_orange_diamond:"🔶",last_quarter_moon:"🌗",last_quarter_moon_with_face:"🌜",latin_cross:"✝️",laughing:"😆",leaves:"🍃",ledger:"📒",left_luggage:"🛅",left_right_arrow:"↔️",leftwards_arrow_with_hook:"↩️",lemon:"🍋",leo:"♌️",leopard:"🐆",level_slider:"🎚",libra:"♎️",light_rail:"🚈",link:"🔗",lion:"🦁",lips:"👄",lipstick:"💄",lizard:"🦎",lock:"🔒",lock_with_ink_pen:"🔏",lollipop:"🍭",loop:"➿",loud_sound:"🔊",loudspeaker:"📢",love_hotel:"🏩",love_letter:"💌",low_brightness:"🔅",lying_face:"🤥",m:"Ⓜ️",mag:"🔍",mag_right:"🔎",mahjong:"🀄️",mailbox:"📫",mailbox_closed:"📪",mailbox_with_mail:"📬",mailbox_with_no_mail:"📭",man:"👨",man_artist:"👨‍🎨",man_astronaut:"👨‍🚀",man_cartwheeling:"🤸‍♂️",man_cook:"👨‍🍳",man_dancing:"🕺",man_facepalming:"🤦‍♂️",man_factory_worker:"👨‍🏭",man_farmer:"👨‍🌾",man_firefighter:"👨‍🚒",man_health_worker:"👨‍⚕️",man_in_tuxedo:"🤵",man_judge:"👨‍⚖️",man_juggling:"🤹‍♂️",man_mechanic:"👨‍🔧",man_office_worker:"👨‍💼",man_pilot:"👨‍✈️",man_playing_handball:"🤾‍♂️",man_playing_water_polo:"🤽‍♂️",man_scientist:"👨‍🔬",man_shrugging:"🤷‍♂️",man_singer:"👨‍🎤",man_student:"👨‍🎓",man_teacher:"👨‍🏫",man_technologist:"👨‍💻",man_with_gua_pi_mao:"👲",man_with_turban:"👳",tangerine:"🍊",mans_shoe:"👞",mantelpiece_clock:"🕰",maple_leaf:"🍁",martial_arts_uniform:"🥋",mask:"😷",massage_woman:"💆",massage_man:"💆‍♂️",meat_on_bone:"🍖",medal_military:"🎖",medal_sports:"🏅",mega:"📣",melon:"🍈",memo:"📝",men_wrestling:"🤼‍♂️",menorah:"🕎",mens:"🚹",metal:"🤘",metro:"🚇",microphone:"🎤",microscope:"🔬",milk_glass:"🥛",milky_way:"🌌",minibus:"🚐",minidisc:"💽",mobile_phone_off:"📴",money_mouth_face:"🤑",money_with_wings:"💸",moneybag:"💰",monkey:"🐒",monkey_face:"🐵",monorail:"🚝",moon:"🌔",mortar_board:"🎓",mosque:"🕌",motor_boat:"🛥",motor_scooter:"🛵",motorcycle:"🏍",motorway:"🛣",mount_fuji:"🗻",mountain:"⛰",mountain_biking_man:"🚵",mountain_biking_woman:"🚵‍♀️",mountain_cableway:"🚠",mountain_railway:"🚞",mountain_snow:"🏔",mouse:"🐭",mouse2:"🐁",movie_camera:"🎥",moyai:"🗿",mrs_claus:"🤶",muscle:"💪",mushroom:"🍄",musical_keyboard:"🎹",musical_note:"🎵",musical_score:"🎼",mute:"🔇",nail_care:"💅",name_badge:"📛",national_park:"🏞",nauseated_face:"🤢",necktie:"👔",negative_squared_cross_mark:"❎",nerd_face:"🤓",neutral_face:"😐",new:"🆕",new_moon:"🌑",new_moon_with_face:"🌚",newspaper:"📰",newspaper_roll:"🗞",next_track_button:"⏭",ng:"🆖",no_good_man:"🙅‍♂️",no_good_woman:"🙅",night_with_stars:"🌃",no_bell:"🔕",no_bicycles:"🚳",no_entry:"⛔️",no_entry_sign:"🚫",no_mobile_phones:"📵",no_mouth:"😶",no_pedestrians:"🚷",no_smoking:"🚭","non-potable_water":"🚱",nose:"👃",notebook:"📓",notebook_with_decorative_cover:"📔",notes:"🎶",nut_and_bolt:"🔩",o:"⭕️",o2:"🅾️",ocean:"🌊",octopus:"🐙",oden:"🍢",office:"🏢",oil_drum:"🛢",ok:"🆗",ok_hand:"👌",ok_man:"🙆‍♂️",ok_woman:"🙆",old_key:"🗝",older_man:"👴",older_woman:"👵",om:"🕉",on:"🔛",oncoming_automobile:"🚘",oncoming_bus:"🚍",oncoming_police_car:"🚔",oncoming_taxi:"🚖",open_file_folder:"📂",open_hands:"👐",open_mouth:"😮",open_umbrella:"☂️",ophiuchus:"⛎",orange_book:"📙",orthodox_cross:"☦️",outbox_tray:"📤",owl:"🦉",ox:"🐂",package:"📦",page_facing_up:"📄",page_with_curl:"📃",pager:"📟",paintbrush:"🖌",palm_tree:"🌴",pancakes:"🥞",panda_face:"🐼",paperclip:"📎",paperclips:"🖇",parasol_on_ground:"⛱",parking:"🅿️",part_alternation_mark:"〽️",partly_sunny:"⛅️",passenger_ship:"🛳",passport_control:"🛂",pause_button:"⏸",peace_symbol:"☮️",peach:"🍑",peanuts:"🥜",pear:"🍐",pen:"🖊",pencil2:"✏️",penguin:"🐧",pensive:"😔",performing_arts:"🎭",persevere:"😣",person_fencing:"🤺",pouting_woman:"🙎",phone:"☎️",pick:"⛏",pig:"🐷",pig2:"🐖",pig_nose:"🐽",pill:"💊",pineapple:"🍍",ping_pong:"🏓",pisces:"♓️",pizza:"🍕",place_of_worship:"🛐",plate_with_cutlery:"🍽",play_or_pause_button:"⏯",point_down:"👇",point_left:"👈",point_right:"👉",point_up:"☝️",point_up_2:"👆",police_car:"🚓",policewoman:"👮‍♀️",poodle:"🐩",popcorn:"🍿",post_office:"🏣",postal_horn:"📯",postbox:"📮",potable_water:"🚰",potato:"🥔",pouch:"👝",poultry_leg:"🍗",pound:"💷",rage:"😡",pouting_cat:"😾",pouting_man:"🙎‍♂️",pray:"🙏",prayer_beads:"📿",pregnant_woman:"🤰",previous_track_button:"⏮",prince:"🤴",princess:"👸",printer:"🖨",purple_heart:"💜",purse:"👛",pushpin:"📌",put_litter_in_its_place:"🚮",question:"❓",rabbit:"🐰",rabbit2:"🐇",racehorse:"🐎",racing_car:"🏎",radio:"📻",radio_button:"🔘",radioactive:"☢️",railway_car:"🚃",railway_track:"🛤",rainbow:"🌈",rainbow_flag:"🏳️‍🌈",raised_back_of_hand:"🤚",raised_hand_with_fingers_splayed:"🖐",raised_hands:"🙌",raising_hand_woman:"🙋",raising_hand_man:"🙋‍♂️",ram:"🐏",ramen:"🍜",rat:"🐀",record_button:"⏺",recycle:"♻️",red_circle:"🔴",registered:"®️",relaxed:"☺️",relieved:"😌",reminder_ribbon:"🎗",repeat:"🔁",repeat_one:"🔂",rescue_worker_helmet:"⛑",restroom:"🚻",revolving_hearts:"💞",rewind:"⏪",rhinoceros:"🦏",ribbon:"🎀",rice:"🍚",rice_ball:"🍙",rice_cracker:"🍘",rice_scene:"🎑",right_anger_bubble:"🗯",ring:"💍",robot:"🤖",rocket:"🚀",rofl:"🤣",roll_eyes:"🙄",roller_coaster:"🎢",rooster:"🐓",rose:"🌹",rosette:"🏵",rotating_light:"🚨",round_pushpin:"📍",rowing_man:"🚣",rowing_woman:"🚣‍♀️",rugby_football:"🏉",running_man:"🏃",running_shirt_with_sash:"🎽",running_woman:"🏃‍♀️",sa:"🈂️",sagittarius:"♐️",sake:"🍶",sandal:"👡",santa:"🎅",satellite:"📡",saxophone:"🎷",school:"🏫",school_satchel:"🎒",scissors:"✂️",scorpion:"🦂",scorpius:"♏️",scream:"😱",scream_cat:"🙀",scroll:"📜",seat:"💺",secret:"㊙️",see_no_evil:"🙈",seedling:"🌱",selfie:"🤳",shallow_pan_of_food:"🥘",shamrock:"☘️",shark:"🦈",shaved_ice:"🍧",sheep:"🐑",shell:"🐚",shield:"🛡",shinto_shrine:"⛩",ship:"🚢",shirt:"👕",shopping:"🛍",shopping_cart:"🛒",shower:"🚿",shrimp:"🦐",signal_strength:"📶",six_pointed_star:"🔯",ski:"🎿",skier:"⛷",skull:"💀",skull_and_crossbones:"☠️",sleeping:"😴",sleeping_bed:"🛌",sleepy:"😪",slightly_frowning_face:"🙁",slightly_smiling_face:"🙂",slot_machine:"🎰",small_airplane:"🛩",small_blue_diamond:"🔹",small_orange_diamond:"🔸",small_red_triangle:"🔺",small_red_triangle_down:"🔻",smile:"😄",smile_cat:"😸",smiley:"😃",smiley_cat:"😺",smiling_imp:"😈",smirk:"😏",smirk_cat:"😼",smoking:"🚬",snail:"🐌",snake:"🐍",sneezing_face:"🤧",snowboarder:"🏂",snowflake:"❄️",snowman:"⛄️",snowman_with_snow:"☃️",sob:"😭",soccer:"⚽️",soon:"🔜",sos:"🆘",sound:"🔉",space_invader:"👾",spades:"♠️",spaghetti:"🍝",sparkle:"❇️",sparkler:"🎇",sparkles:"✨",sparkling_heart:"💖",speak_no_evil:"🙊",speaker:"🔈",speaking_head:"🗣",speech_balloon:"💬",speedboat:"🚤",spider:"🕷",spider_web:"🕸",spiral_calendar:"🗓",spiral_notepad:"🗒",spoon:"🥄",squid:"🦑",stadium:"🏟",star:"⭐️",star2:"🌟",star_and_crescent:"☪️",star_of_david:"✡️",stars:"🌠",station:"🚉",statue_of_liberty:"🗽",steam_locomotive:"🚂",stew:"🍲",stop_button:"⏹",stop_sign:"🛑",stopwatch:"⏱",straight_ruler:"📏",strawberry:"🍓",stuck_out_tongue:"😛",stuck_out_tongue_closed_eyes:"😝",stuck_out_tongue_winking_eye:"😜",studio_microphone:"🎙",stuffed_flatbread:"🥙",sun_behind_large_cloud:"🌥",sun_behind_rain_cloud:"🌦",sun_behind_small_cloud:"🌤",sun_with_face:"🌞",sunflower:"🌻",sunglasses:"😎",sunny:"☀️",sunrise:"🌅",sunrise_over_mountains:"🌄",surfing_man:"🏄",surfing_woman:"🏄‍♀️",sushi:"🍣",suspension_railway:"🚟",sweat:"😓",sweat_drops:"💦",sweat_smile:"😅",sweet_potato:"🍠",swimming_man:"🏊",swimming_woman:"🏊‍♀️",symbols:"🔣",synagogue:"🕍",syringe:"💉",taco:"🌮",tada:"🎉",tanabata_tree:"🎋",taurus:"♉️",taxi:"🚕",tea:"🍵",telephone_receiver:"📞",telescope:"🔭",tennis:"🎾",tent:"⛺️",thermometer:"🌡",thinking:"🤔",thought_balloon:"💭",ticket:"🎫",tickets:"🎟",tiger:"🐯",tiger2:"🐅",timer_clock:"⏲",tipping_hand_man:"💁‍♂️",tired_face:"😫",tm:"™️",toilet:"🚽",tokyo_tower:"🗼",tomato:"🍅",tongue:"👅",top:"🔝",tophat:"🎩",tornado:"🌪",trackball:"🖲",tractor:"🚜",traffic_light:"🚥",train:"🚋",train2:"🚆",tram:"🚊",triangular_flag_on_post:"🚩",triangular_ruler:"📐",trident:"🔱",triumph:"😤",trolleybus:"🚎",trophy:"🏆",tropical_drink:"🍹",tropical_fish:"🐠",truck:"🚚",trumpet:"🎺",tulip:"🌷",tumbler_glass:"🥃",turkey:"🦃",turtle:"🐢",tv:"📺",twisted_rightwards_arrows:"🔀",two_hearts:"💕",two_men_holding_hands:"👬",two_women_holding_hands:"👭",u5272:"🈹",u5408:"🈴",u55b6:"🈺",u6307:"🈯️",u6708:"🈷️",u6709:"🈶",u6e80:"🈵",u7121:"🈚️",u7533:"🈸",u7981:"🈲",u7a7a:"🈳",umbrella:"☔️",unamused:"😒",underage:"🔞",unicorn:"🦄",unlock:"🔓",up:"🆙",upside_down_face:"🙃",v:"✌️",vertical_traffic_light:"🚦",vhs:"📼",vibration_mode:"📳",video_camera:"📹",video_game:"🎮",violin:"🎻",virgo:"♍️",volcano:"🌋",volleyball:"🏐",vs:"🆚",vulcan_salute:"🖖",walking_man:"🚶",walking_woman:"🚶‍♀️",waning_crescent_moon:"🌘",waning_gibbous_moon:"🌖",warning:"⚠️",wastebasket:"🗑",watch:"⌚️",water_buffalo:"🐃",watermelon:"🍉",wave:"👋",wavy_dash:"〰️",waxing_crescent_moon:"🌒",wc:"🚾",weary:"😩",wedding:"💒",weight_lifting_man:"🏋️",weight_lifting_woman:"🏋️‍♀️",whale:"🐳",whale2:"🐋",wheel_of_dharma:"☸️",wheelchair:"♿️",white_check_mark:"✅",white_circle:"⚪️",white_flag:"🏳️",white_flower:"💮",white_large_square:"⬜️",white_medium_small_square:"◽️",white_medium_square:"◻️",white_small_square:"▫️",white_square_button:"🔳",wilted_flower:"🥀",wind_chime:"🎐",wind_face:"🌬",wine_glass:"🍷",wink:"😉",wolf:"🐺",woman:"👩",woman_artist:"👩‍🎨",woman_astronaut:"👩‍🚀",woman_cartwheeling:"🤸‍♀️",woman_cook:"👩‍🍳",woman_facepalming:"🤦‍♀️",woman_factory_worker:"👩‍🏭",woman_farmer:"👩‍🌾",woman_firefighter:"👩‍🚒",woman_health_worker:"👩‍⚕️",woman_judge:"👩‍⚖️",woman_juggling:"🤹‍♀️",woman_mechanic:"👩‍🔧",woman_office_worker:"👩‍💼",woman_pilot:"👩‍✈️",woman_playing_handball:"🤾‍♀️",woman_playing_water_polo:"🤽‍♀️",woman_scientist:"👩‍🔬",woman_shrugging:"🤷‍♀️",woman_singer:"👩‍🎤",woman_student:"👩‍🎓",woman_teacher:"👩‍🏫",woman_technologist:"👩‍💻",woman_with_turban:"👳‍♀️",womans_clothes:"👚",womans_hat:"👒",women_wrestling:"🤼‍♀️",womens:"🚺",world_map:"🗺",worried:"😟",wrench:"🔧",writing_hand:"✍️",x:"❌",yellow_heart:"💛",yen:"💴",yin_yang:"☯️",yum:"😋",zap:"⚡️",zipper_mouth_face:"🤐",zzz:"💤",octocat:'',showdown:''},i.Converter=function(e){"use strict";function n(e,n){if(n=n||null,i.helper.isString(e)){if(n=e=i.helper.stdExtName(e),i.extensions[e])return console.warn("DEPRECATION WARNING: "+e+" is an old extension that uses a deprecated loading method.Please inform the developer that the extension should be updated!"),void function(e,n){"function"==typeof e&&(e=e(new i.Converter)),i.helper.isArray(e)||(e=[e]);var r=t(e,n);if(!r.valid)throw Error(r.error);for(var o=0;o? ?(['"].*['"])?\)$/m)>-1)a="";else if(!a){if(o||(o=r.toLowerCase().replace(/ ?\n/g," ")),a="#"+o,i.helper.isUndefined(n.gUrls[o]))return e;a=n.gUrls[o],i.helper.isUndefined(n.gTitles[o])||(c=n.gTitles[o])}var u='"+r+""};return e=(e=(e=(e=(e=n.converter._dispatch("anchors.before",e,t,n)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)] ?(?:\n *)?\[(.*?)]()()()()/g,r)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]?<([^>]*)>(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,r)).replace(/\[((?:\[[^\]]*]|[^\[\]])*)]()[ \t]*\([ \t]??(?:[ \t]*((["'])([^"]*?)\5))?[ \t]?\)/g,r)).replace(/\[([^\[\]]+)]()()()()()/g,r),t.ghMentions&&(e=e.replace(/(^|\s)(\\)?(@([a-z\d\-]+))(?=[.!?;,[\]()]|\s|$)/gim,function(e,n,r,o,a){if("\\"===r)return n+o;if(!i.helper.isString(t.ghMentionsLink))throw new Error("ghMentionsLink option must be a string");var s=t.ghMentionsLink.replace(/\{u}/g,a),l="";return t.openLinksInNewWindow&&(l=' target="¨E95Eblank"'),n+'"+o+""})),n.converter._dispatch("anchors.after",e,t,n)});var u=/([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+?\.[^'">\s]+?)()(\1)?(?=\s|$)(?!["<>])/gi,d=/([*~_]+|\b)(((https?|ftp|dict):\/\/|www\.)[^'">\s]+\.[^'">\s]+?)([.!?,()\[\]])?(\1)?(?=\s|$)(?!["<>])/gi,h=/()<(((https?|ftp|dict):\/\/|www\.)[^'">\s]+)()>()/gi,f=/(^|\s)(?:mailto:)?([A-Za-z0-9!#$%&'*+-/=?^_`{|}~.]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)(?=$|\s)/gim,p=/<()(?:mailto:)?([-.\w]+@[-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+)>/gi,g=function(e){"use strict";return function(t,n,r,o,a,s,l){var c=r=r.replace(i.helper.regexes.asteriskDashAndColon,i.helper.escapeCharactersCallback),u="",d="",h=n||"",f=l||"";return/^www\./i.test(r)&&(r=r.replace(/^www\./i,"http://www.")),e.excludeTrailingPunctuationFromURLs&&s&&(u=s),e.openLinksInNewWindow&&(d=' target="¨E95Eblank"'),h+'"+c+""+u+f}},m=function(e,t){"use strict";return function(n,r,o){var a="mailto:";return r=r||"",o=i.subParser("unescapeSpecialChars")(o,e,t),e.encodeEmails?(a=i.helper.encodeEmailAddress(a+o),o=i.helper.encodeEmailAddress(o)):a+=o,r+''+o+""}};i.subParser("autoLinks",function(e,t,n){"use strict";return e=(e=(e=n.converter._dispatch("autoLinks.before",e,t,n)).replace(h,g(t))).replace(p,m(t,n)),n.converter._dispatch("autoLinks.after",e,t,n)}),i.subParser("simplifiedAutoLinks",function(e,t,n){"use strict";return t.simplifiedAutoLink?(e=n.converter._dispatch("simplifiedAutoLinks.before",e,t,n),e=(e=t.excludeTrailingPunctuationFromURLs?e.replace(d,g(t)):e.replace(u,g(t))).replace(f,m(t,n)),e=n.converter._dispatch("simplifiedAutoLinks.after",e,t,n)):e}),i.subParser("blockGamut",function(e,t,n){"use strict";return e=n.converter._dispatch("blockGamut.before",e,t,n),e=i.subParser("blockQuotes")(e,t,n),e=i.subParser("headers")(e,t,n),e=i.subParser("horizontalRule")(e,t,n),e=i.subParser("lists")(e,t,n),e=i.subParser("codeBlocks")(e,t,n),e=i.subParser("tables")(e,t,n),e=i.subParser("hashHTMLBlocks")(e,t,n),e=i.subParser("paragraphs")(e,t,n),n.converter._dispatch("blockGamut.after",e,t,n)}),i.subParser("blockQuotes",function(e,t,n){"use strict";e=n.converter._dispatch("blockQuotes.before",e,t,n),e+="\n\n";var r=/(^ {0,3}>[ \t]?.+\n(.+\n)*\n*)+/gm;return t.splitAdjacentBlockquotes&&(r=/^ {0,3}>[\s\S]*?(?:\n\n)/gm),e=e.replace(r,function(e){return e=(e=(e=e.replace(/^[ \t]*>[ \t]?/gm,"")).replace(/¨0/g,"")).replace(/^[ \t]+$/gm,""),e=i.subParser("githubCodeBlocks")(e,t,n),e=(e=(e=i.subParser("blockGamut")(e,t,n)).replace(/(^|\n)/g,"$1 ")).replace(/(\s*
    [^\r]+?<\/pre>)/gm,function(e,t){var n=t;return(n=n.replace(/^  /gm,"¨0")).replace(/¨0/g,"")}),i.subParser("hashBlock")("
    \n"+e+"\n
    ",t,n)}),n.converter._dispatch("blockQuotes.after",e,t,n)}),i.subParser("codeBlocks",function(e,t,n){"use strict";return e=n.converter._dispatch("codeBlocks.before",e,t,n),e=(e=(e+="¨0").replace(/(?:\n\n|^)((?:(?:[ ]{4}|\t).*\n+)+)(\n*[ ]{0,3}[^ \t\n]|(?=¨0))/g,function(e,r,o){var a=r,s=o,l="\n";return a=i.subParser("outdent")(a,t,n),a=i.subParser("encodeCode")(a,t,n),a=(a=(a=i.subParser("detab")(a,t,n)).replace(/^\n+/g,"")).replace(/\n+$/g,""),t.omitExtraWLInCodeBlocks&&(l=""),a="
    "+a+l+"
    ",i.subParser("hashBlock")(a,t,n)+s})).replace(/¨0/,""),n.converter._dispatch("codeBlocks.after",e,t,n)}),i.subParser("codeSpans",function(e,t,n){"use strict";return void 0===(e=n.converter._dispatch("codeSpans.before",e,t,n))&&(e=""),e=e.replace(/(^|[^\\])(`+)([^\r]*?[^`])\2(?!`)/gm,function(e,r,o,a){var s=a;return s=(s=s.replace(/^([ \t]*)/g,"")).replace(/[ \t]*$/g,""),s=r+""+(s=i.subParser("encodeCode")(s,t,n))+"",i.subParser("hashHTMLSpans")(s,t,n)}),n.converter._dispatch("codeSpans.after",e,t,n)}),i.subParser("completeHTMLDocument",function(e,t,n){"use strict";if(!t.completeHTMLDocument)return e;e=n.converter._dispatch("completeHTMLDocument.before",e,t,n);var i="html",r="\n",o="",a='\n',s="",l="";for(var c in void 0!==n.metadata.parsed.doctype&&(r="\n","html"!==(i=n.metadata.parsed.doctype.toString().toLowerCase())&&"html5"!==i||(a='')),n.metadata.parsed)if(n.metadata.parsed.hasOwnProperty(c))switch(c.toLowerCase()){case"doctype":break;case"title":o=""+n.metadata.parsed.title+"\n";break;case"charset":a="html"===i||"html5"===i?'\n':'\n';break;case"language":case"lang":s=' lang="'+n.metadata.parsed[c]+'"',l+='\n';break;default:l+='\n'}return e=r+"\n\n"+o+a+l+"\n\n"+e.trim()+"\n\n",n.converter._dispatch("completeHTMLDocument.after",e,t,n)}),i.subParser("detab",function(e,t,n){"use strict";return e=(e=(e=(e=(e=(e=n.converter._dispatch("detab.before",e,t,n)).replace(/\t(?=\t)/g," ")).replace(/\t/g,"¨A¨B")).replace(/¨B(.+?)¨A/g,function(e,t){for(var n=t,i=4-n.length%4,r=0;r/g,">"),n.converter._dispatch("encodeAmpsAndAngles.after",e,t,n)}),i.subParser("encodeBackslashEscapes",function(e,t,n){"use strict";return e=(e=(e=n.converter._dispatch("encodeBackslashEscapes.before",e,t,n)).replace(/\\(\\)/g,i.helper.escapeCharactersCallback)).replace(/\\([`*_{}\[\]()>#+.!~=|-])/g,i.helper.escapeCharactersCallback),n.converter._dispatch("encodeBackslashEscapes.after",e,t,n)}),i.subParser("encodeCode",function(e,t,n){"use strict";return e=(e=n.converter._dispatch("encodeCode.before",e,t,n)).replace(/&/g,"&").replace(//g,">").replace(/([*_{}\[\]\\=~-])/g,i.helper.escapeCharactersCallback),n.converter._dispatch("encodeCode.after",e,t,n)}),i.subParser("escapeSpecialCharsWithinTagAttributes",function(e,t,n){"use strict";return e=(e=(e=n.converter._dispatch("escapeSpecialCharsWithinTagAttributes.before",e,t,n)).replace(/<\/?[a-z\d_:-]+(?:[\s]+[\s\S]+?)?>/gi,function(e){return e.replace(/(.)<\/?code>(?=.)/g,"$1`").replace(/([\\`*_~=|])/g,i.helper.escapeCharactersCallback)})).replace(/-]|-[^>])(?:[^-]|-[^-])*)--)>/gi,function(e){return e.replace(/([\\`*_~=|])/g,i.helper.escapeCharactersCallback)}),n.converter._dispatch("escapeSpecialCharsWithinTagAttributes.after",e,t,n)}),i.subParser("githubCodeBlocks",function(e,t,n){"use strict";return t.ghCodeBlocks?(e=n.converter._dispatch("githubCodeBlocks.before",e,t,n),e=(e=(e+="¨0").replace(/(?:^|\n)(```+|~~~+)([^\s`~]*)\n([\s\S]*?)\n\1/g,function(e,r,o,a){var s=t.omitExtraWLInCodeBlocks?"":"\n";return a=i.subParser("encodeCode")(a,t,n),a=(a=(a=i.subParser("detab")(a,t,n)).replace(/^\n+/g,"")).replace(/\n+$/g,""),a="
    "+a+s+"
    ",a=i.subParser("hashBlock")(a,t,n),"\n\n¨G"+(n.ghCodeBlocks.push({text:e,codeblock:a})-1)+"G\n\n"})).replace(/¨0/,""),n.converter._dispatch("githubCodeBlocks.after",e,t,n)):e}),i.subParser("hashBlock",function(e,t,n){"use strict";return e=(e=n.converter._dispatch("hashBlock.before",e,t,n)).replace(/(^\n+|\n+$)/g,""),e="\n\n¨K"+(n.gHtmlBlocks.push(e)-1)+"K\n\n",n.converter._dispatch("hashBlock.after",e,t,n)}),i.subParser("hashCodeTags",function(e,t,n){"use strict";return e=n.converter._dispatch("hashCodeTags.before",e,t,n),e=i.helper.replaceRecursiveRegExp(e,function(e,r,o,a){var s=o+i.subParser("encodeCode")(r,t,n)+a;return"¨C"+(n.gHtmlSpans.push(s)-1)+"C"},"]*>","","gim"),n.converter._dispatch("hashCodeTags.after",e,t,n)}),i.subParser("hashElement",function(e,t,n){"use strict";return function(e,t){var i=t;return i=(i=(i=i.replace(/\n\n/g,"\n")).replace(/^\n/,"")).replace(/\n+$/g,""),"\n\n¨K"+(n.gHtmlBlocks.push(i)-1)+"K\n\n"}}),i.subParser("hashHTMLBlocks",function(e,t,n){"use strict";e=n.converter._dispatch("hashHTMLBlocks.before",e,t,n);var r=["pre","div","h1","h2","h3","h4","h5","h6","blockquote","table","dl","ol","ul","script","noscript","form","fieldset","iframe","math","style","section","header","footer","nav","article","aside","address","audio","canvas","figure","hgroup","output","video","p"],o=function(e,t,i,r){var o=e;return-1!==i.search(/\bmarkdown\b/)&&(o=i+n.converter.makeHtml(t)+r),"\n\n¨K"+(n.gHtmlBlocks.push(o)-1)+"K\n\n"};t.backslashEscapesHTMLTags&&(e=e.replace(/\\<(\/?[^>]+?)>/g,function(e,t){return"<"+t+">"}));for(var a=0;a]*>)","im"),c="<"+r[a]+"\\b[^>]*>",u="";-1!==(s=i.helper.regexIndexOf(e,l));){var d=i.helper.splitAtIndex(e,s),h=i.helper.replaceRecursiveRegExp(d[1],o,c,u,"im");if(h===d[1])break;e=d[0].concat(h)}return e=e.replace(/(\n {0,3}(<(hr)\b([^<>])*?\/?>)[ \t]*(?=\n{2,}))/g,i.subParser("hashElement")(e,t,n)),e=(e=i.helper.replaceRecursiveRegExp(e,function(e){return"\n\n¨K"+(n.gHtmlBlocks.push(e)-1)+"K\n\n"},"^ {0,3}\x3c!--","--\x3e","gm")).replace(/(?:\n\n)( {0,3}(?:<([?%])[^\r]*?\2>)[ \t]*(?=\n{2,}))/g,i.subParser("hashElement")(e,t,n)),n.converter._dispatch("hashHTMLBlocks.after",e,t,n)}),i.subParser("hashHTMLSpans",function(e,t,n){"use strict";function i(e){return"¨C"+(n.gHtmlSpans.push(e)-1)+"C"}return e=(e=(e=(e=(e=n.converter._dispatch("hashHTMLSpans.before",e,t,n)).replace(/<[^>]+?\/>/gi,function(e){return i(e)})).replace(/<([^>]+?)>[\s\S]*?<\/\1>/g,function(e){return i(e)})).replace(/<([^>]+?)\s[^>]+?>[\s\S]*?<\/\1>/g,function(e){return i(e)})).replace(/<[^>]+?>/gi,function(e){return i(e)}),n.converter._dispatch("hashHTMLSpans.after",e,t,n)}),i.subParser("unhashHTMLSpans",function(e,t,n){"use strict";e=n.converter._dispatch("unhashHTMLSpans.before",e,t,n);for(var i=0;i]*>\\s*]*>","^ {0,3}\\s*
    ","gim"),n.converter._dispatch("hashPreCodeTags.after",e,t,n)}),i.subParser("headers",function(e,t,n){"use strict";function r(e){var r,o;if(t.customizedHeaderId){var a=e.match(/\{([^{]+?)}\s*$/);a&&a[1]&&(e=a[1])}return r=e,o=i.helper.isString(t.prefixHeaderId)?t.prefixHeaderId:!0===t.prefixHeaderId?"section-":"",t.rawPrefixHeaderId||(r=o+r),r=t.ghCompatibleHeaderId?r.replace(/ /g,"-").replace(/&/g,"").replace(/¨T/g,"").replace(/¨D/g,"").replace(/[&+$,\/:;=?@"#{}|^¨~\[\]`\\*)(%.!'<>]/g,"").toLowerCase():t.rawHeaderId?r.replace(/ /g,"-").replace(/&/g,"&").replace(/¨T/g,"¨").replace(/¨D/g,"$").replace(/["']/g,"-").toLowerCase():r.replace(/[^\w]/g,"").toLowerCase(),t.rawPrefixHeaderId&&(r=o+r),n.hashLinkCounts[r]?r=r+"-"+n.hashLinkCounts[r]++:n.hashLinkCounts[r]=1,r}e=n.converter._dispatch("headers.before",e,t,n);var o=isNaN(parseInt(t.headerLevelStart))?1:parseInt(t.headerLevelStart),a=t.smoothLivePreview?/^(.+)[ \t]*\n={2,}[ \t]*\n+/gm:/^(.+)[ \t]*\n=+[ \t]*\n+/gm,s=t.smoothLivePreview?/^(.+)[ \t]*\n-{2,}[ \t]*\n+/gm:/^(.+)[ \t]*\n-+[ \t]*\n+/gm;e=(e=e.replace(a,function(e,a){var s=i.subParser("spanGamut")(a,t,n),l=t.noHeaderId?"":' id="'+r(a)+'"',c=""+s+"";return i.subParser("hashBlock")(c,t,n)})).replace(s,function(e,a){var s=i.subParser("spanGamut")(a,t,n),l=t.noHeaderId?"":' id="'+r(a)+'"',c=o+1,u=""+s+"";return i.subParser("hashBlock")(u,t,n)});var l=t.requireSpaceBeforeHeadingText?/^(#{1,6})[ \t]+(.+?)[ \t]*#*\n+/gm:/^(#{1,6})[ \t]*(.+?)[ \t]*#*\n+/gm;return e=e.replace(l,function(e,a,s){var l=s;t.customizedHeaderId&&(l=s.replace(/\s?\{([^{]+?)}\s*$/,""));var c=i.subParser("spanGamut")(l,t,n),u=t.noHeaderId?"":' id="'+r(s)+'"',d=o-1+a.length,h=""+c+"";return i.subParser("hashBlock")(h,t,n)}),n.converter._dispatch("headers.after",e,t,n)}),i.subParser("horizontalRule",function(e,t,n){"use strict";e=n.converter._dispatch("horizontalRule.before",e,t,n);var r=i.subParser("hashBlock")("
    ",t,n);return e=(e=(e=e.replace(/^ {0,2}( ?-){3,}[ \t]*$/gm,r)).replace(/^ {0,2}( ?\*){3,}[ \t]*$/gm,r)).replace(/^ {0,2}( ?_){3,}[ \t]*$/gm,r),n.converter._dispatch("horizontalRule.after",e,t,n)}),i.subParser("images",function(e,t,n){"use strict";function r(e,t,r,o,a,s,l,c){var u=n.gUrls,d=n.gTitles,h=n.gDimensions;if(r=r.toLowerCase(),c||(c=""),e.search(/\(? ?(['"].*['"])?\)$/m)>-1)o="";else if(""===o||null===o){if(""!==r&&null!==r||(r=t.toLowerCase().replace(/ ?\n/g," ")),o="#"+r,i.helper.isUndefined(u[r]))return e;o=u[r],i.helper.isUndefined(d[r])||(c=d[r]),i.helper.isUndefined(h[r])||(a=h[r].width,s=h[r].height)}t=t.replace(/"/g,""").replace(i.helper.regexes.asteriskDashAndColon,i.helper.escapeCharactersCallback);var f=''+t+'"}return e=(e=(e=(e=(e=(e=n.converter._dispatch("images.before",e,t,n)).replace(/!\[([^\]]*?)] ?(?:\n *)?\[([\s\S]*?)]()()()()()/g,r)).replace(/!\[([^\]]*?)][ \t]*()\([ \t]??(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,function(e,t,n,i,o,a,s,l){return r(e,t,n,i=i.replace(/\s/g,""),o,a,0,l)})).replace(/!\[([^\]]*?)][ \t]*()\([ \t]?<([^>]*)>(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(?:(["'])([^"]*?)\6))?[ \t]?\)/g,r)).replace(/!\[([^\]]*?)][ \t]*()\([ \t]??(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*(?:(["'])([^"]*?)\6)?[ \t]?\)/g,r)).replace(/!\[([^\[\]]+)]()()()()()/g,r),n.converter._dispatch("images.after",e,t,n)}),i.subParser("italicsAndBold",function(e,t,n){"use strict";function i(e,t,n){return t+e+n}return e=n.converter._dispatch("italicsAndBold.before",e,t,n),e=t.literalMidWordUnderscores?(e=(e=e.replace(/\b___(\S[\s\S]*)___\b/g,function(e,t){return i(t,"","")})).replace(/\b__(\S[\s\S]*)__\b/g,function(e,t){return i(t,"","")})).replace(/\b_(\S[\s\S]*?)_\b/g,function(e,t){return i(t,"","")}):(e=(e=e.replace(/___(\S[\s\S]*?)___/g,function(e,t){return/\S$/.test(t)?i(t,"",""):e})).replace(/__(\S[\s\S]*?)__/g,function(e,t){return/\S$/.test(t)?i(t,"",""):e})).replace(/_([^\s_][\s\S]*?)_/g,function(e,t){return/\S$/.test(t)?i(t,"",""):e}),e=t.literalMidWordAsterisks?(e=(e=e.replace(/([^*]|^)\B\*\*\*(\S[\s\S]+?)\*\*\*\B(?!\*)/g,function(e,t,n){return i(n,t+"","")})).replace(/([^*]|^)\B\*\*(\S[\s\S]+?)\*\*\B(?!\*)/g,function(e,t,n){return i(n,t+"","")})).replace(/([^*]|^)\B\*(\S[\s\S]+?)\*\B(?!\*)/g,function(e,t,n){return i(n,t+"","")}):(e=(e=e.replace(/\*\*\*(\S[\s\S]*?)\*\*\*/g,function(e,t){return/\S$/.test(t)?i(t,"",""):e})).replace(/\*\*(\S[\s\S]*?)\*\*/g,function(e,t){return/\S$/.test(t)?i(t,"",""):e})).replace(/\*([^\s*][\s\S]*?)\*/g,function(e,t){return/\S$/.test(t)?i(t,"",""):e}),n.converter._dispatch("italicsAndBold.after",e,t,n)}),i.subParser("lists",function(e,t,n){"use strict";function r(e,r){n.gListLevel++,e=e.replace(/\n{2,}$/,"\n");var o=/(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0| {0,3}([*+-]|\d+[.])[ \t]+))/gm,a=/\n[ \t]*\n(?!¨0)/.test(e+="¨0");return t.disableForced4SpacesIndentedSublists&&(o=/(\n)?(^ {0,3})([*+-]|\d+[.])[ \t]+((\[(x|X| )?])?[ \t]*[^\r]+?(\n{1,2}))(?=\n*(¨0|\2([*+-]|\d+[.])[ \t]+))/gm),e=(e=e.replace(o,function(e,r,o,s,l,c,u){u=u&&""!==u.trim();var d=i.subParser("outdent")(l,t,n),h="";return c&&t.tasklists&&(h=' class="task-list-item" style="list-style-type: none;"',d=d.replace(/^[ \t]*\[(x|X| )?]/m,function(){var e='"})),d=d.replace(/^([-*+]|\d\.)[ \t]+[\S\n ]*/g,function(e){return"¨A"+e}),r||d.search(/\n{2,}/)>-1?(d=i.subParser("githubCodeBlocks")(d,t,n),d=i.subParser("blockGamut")(d,t,n)):(d=(d=i.subParser("lists")(d,t,n)).replace(/\n$/,""),d=(d=i.subParser("hashHTMLBlocks")(d,t,n)).replace(/\n\n+/g,"\n\n"),d=a?i.subParser("paragraphs")(d,t,n):i.subParser("spanGamut")(d,t,n)),""+(d=d.replace("¨A",""))+"\n"})).replace(/¨0/g,""),n.gListLevel--,r&&(e=e.replace(/\s+$/,"")),e}function o(e,t){if("ol"===t){var n=e.match(/^ *(\d+)\./);if(n&&"1"!==n[1])return' start="'+n[1]+'"'}return""}function a(e,n,i){var a=t.disableForced4SpacesIndentedSublists?/^ ?\d+\.[ \t]/gm:/^ {0,3}\d+\.[ \t]/gm,s=t.disableForced4SpacesIndentedSublists?/^ ?[*+-][ \t]/gm:/^ {0,3}[*+-][ \t]/gm,l="ul"===n?a:s,c="";if(-1!==e.search(l))!function t(u){var d=u.search(l),h=o(e,n);-1!==d?(c+="\n\n<"+n+h+">\n"+r(u.slice(0,d),!!i)+"\n",l="ul"==(n="ul"===n?"ol":"ul")?a:s,t(u.slice(d))):c+="\n\n<"+n+h+">\n"+r(u,!!i)+"\n"}(e);else{var u=o(e,n);c="\n\n<"+n+u+">\n"+r(e,!!i)+"\n"}return c}return e=n.converter._dispatch("lists.before",e,t,n),e+="¨0",e=(e=n.gListLevel?e.replace(/^(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,function(e,t,n){return a(t,n.search(/[*+-]/g)>-1?"ul":"ol",!0)}):e.replace(/(\n\n|^\n?)(( {0,3}([*+-]|\d+[.])[ \t]+)[^\r]+?(¨0|\n{2,}(?=\S)(?![ \t]*(?:[*+-]|\d+[.])[ \t]+)))/gm,function(e,t,n,i){return a(n,i.search(/[*+-]/g)>-1?"ul":"ol",!1)})).replace(/¨0/,""),n.converter._dispatch("lists.after",e,t,n)}),i.subParser("metadata",function(e,t,n){"use strict";function i(e){n.metadata.raw=e,(e=(e=e.replace(/&/g,"&").replace(/"/g,""")).replace(/\n {4}/g," ")).replace(/^([\S ]+): +([\s\S]+?)$/gm,function(e,t,i){return n.metadata.parsed[t]=i,""})}return t.metadata?(e=(e=(e=(e=n.converter._dispatch("metadata.before",e,t,n)).replace(/^\s*«««+(\S*?)\n([\s\S]+?)\n»»»+\n/,function(e,t,n){return i(n),"¨M"})).replace(/^\s*---+(\S*?)\n([\s\S]+?)\n---+\n/,function(e,t,r){return t&&(n.metadata.format=t),i(r),"¨M"})).replace(/¨M/g,""),e=n.converter._dispatch("metadata.after",e,t,n)):e}),i.subParser("outdent",function(e,t,n){"use strict";return e=(e=(e=n.converter._dispatch("outdent.before",e,t,n)).replace(/^(\t|[ ]{1,4})/gm,"¨0")).replace(/¨0/g,""),n.converter._dispatch("outdent.after",e,t,n)}),i.subParser("paragraphs",function(e,t,n){"use strict";for(var r=(e=(e=(e=n.converter._dispatch("paragraphs.before",e,t,n)).replace(/^\n+/g,"")).replace(/\n+$/g,"")).split(/\n{2,}/g),o=[],a=r.length,s=0;s=0?o.push(l):l.search(/\S/)>=0&&(l=(l=i.subParser("spanGamut")(l,t,n)).replace(/^([ \t]*)/g,"

    "),l+="

    ",o.push(l))}for(a=o.length,s=0;s]*>\s*]*>/.test(u)&&(d=!0)}o[s]=u}return e=(e=(e=o.join("\n")).replace(/^\n+/g,"")).replace(/\n+$/g,""),n.converter._dispatch("paragraphs.after",e,t,n)}),i.subParser("runExtension",function(e,t,n,i){"use strict";if(e.filter)t=e.filter(t,i.converter,n);else if(e.regex){var r=e.regex;r instanceof RegExp||(r=new RegExp(r,"g")),t=t.replace(r,e.replace)}return t}),i.subParser("spanGamut",function(e,t,n){"use strict";return e=n.converter._dispatch("spanGamut.before",e,t,n),e=i.subParser("codeSpans")(e,t,n),e=i.subParser("escapeSpecialCharsWithinTagAttributes")(e,t,n),e=i.subParser("encodeBackslashEscapes")(e,t,n),e=i.subParser("images")(e,t,n),e=i.subParser("anchors")(e,t,n),e=i.subParser("autoLinks")(e,t,n),e=i.subParser("simplifiedAutoLinks")(e,t,n),e=i.subParser("emoji")(e,t,n),e=i.subParser("underline")(e,t,n),e=i.subParser("italicsAndBold")(e,t,n),e=i.subParser("strikethrough")(e,t,n),e=i.subParser("ellipsis")(e,t,n),e=i.subParser("hashHTMLSpans")(e,t,n),e=i.subParser("encodeAmpsAndAngles")(e,t,n),t.simpleLineBreaks?/\n\n¨K/.test(e)||(e=e.replace(/\n+/g,"
    \n")):e=e.replace(/ +\n/g,"
    \n"),n.converter._dispatch("spanGamut.after",e,t,n)}),i.subParser("strikethrough",function(e,t,n){"use strict";return t.strikethrough&&(e=(e=n.converter._dispatch("strikethrough.before",e,t,n)).replace(/(?:~){2}([\s\S]+?)(?:~){2}/g,function(e,r){return function(e){return t.simplifiedAutoLink&&(e=i.subParser("simplifiedAutoLinks")(e,t,n)),""+e+""}(r)}),e=n.converter._dispatch("strikethrough.after",e,t,n)),e}),i.subParser("stripLinkDefinitions",function(e,t,n){"use strict";var r=function(e,r,o,a,s,l,c){return r=r.toLowerCase(),o.match(/^data:.+?\/.+?;base64,/)?n.gUrls[r]=o.replace(/\s/g,""):n.gUrls[r]=i.subParser("encodeAmpsAndAngles")(o,t,n),l?l+c:(c&&(n.gTitles[r]=c.replace(/"|'/g,""")),t.parseImgDimensions&&a&&s&&(n.gDimensions[r]={width:a,height:s}),"")};return(e=(e=(e+="¨0").replace(/^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n\n|(?=¨0)|(?=\n\[))/gm,r)).replace(/^ {0,3}\[(.+)]:[ \t]*\n?[ \t]*\s]+)>?(?: =([*\d]+[A-Za-z%]{0,4})x([*\d]+[A-Za-z%]{0,4}))?[ \t]*\n?[ \t]*(?:(\n*)["|'(](.+?)["|')][ \t]*)?(?:\n+|(?=¨0))/gm,r)).replace(/¨0/,"")}),i.subParser("tables",function(e,t,n){"use strict";function r(e){return/^:[ \t]*--*$/.test(e)?' style="text-align:left;"':/^--*[ \t]*:[ \t]*$/.test(e)?' style="text-align:right;"':/^:[ \t]*--*[ \t]*:$/.test(e)?' style="text-align:center;"':""}function o(e,r){var o="";return e=e.trim(),(t.tablesHeaderId||t.tableHeaderId)&&(o=' id="'+e.replace(/ /g,"_").toLowerCase()+'"'),""+(e=i.subParser("spanGamut")(e,t,n))+"\n"}function a(e,r){return""+i.subParser("spanGamut")(e,t,n)+"\n"}function s(e){var s,l=e.split("\n");for(s=0;s\n\n\n",r=0;r\n";for(var o=0;o\n"}return n+"\n\n"}(h,p)}return t.tables?(e=(e=(e=(e=n.converter._dispatch("tables.before",e,t,n)).replace(/\\(\|)/g,i.helper.escapeCharactersCallback)).replace(/^ {0,3}\|?.+\|.+\n {0,3}\|?[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*:?[ \t]*(?:[-=]){2,}[\s\S]+?(?:\n\n|¨0)/gm,s)).replace(/^ {0,3}\|.+\|[ \t]*\n {0,3}\|[ \t]*:?[ \t]*(?:[-=]){2,}[ \t]*:?[ \t]*\|[ \t]*\n( {0,3}\|.+\|[ \t]*\n)*(?:\n|¨0)/gm,s),n.converter._dispatch("tables.after",e,t,n)):e}),i.subParser("underline",function(e,t,n){"use strict";return t.underline?(e=n.converter._dispatch("underline.before",e,t,n),e=(e=t.literalMidWordUnderscores?e.replace(/\b_?__(\S[\s\S]*)___?\b/g,function(e,t){return""+t+""}):e.replace(/_?__(\S[\s\S]*?)___?/g,function(e,t){return/\S$/.test(t)?""+t+"":e})).replace(/(_)/g,i.helper.escapeCharactersCallback),e=n.converter._dispatch("underline.after",e,t,n)):e}),i.subParser("unescapeSpecialChars",function(e,t,n){"use strict";return e=(e=n.converter._dispatch("unescapeSpecialChars.before",e,t,n)).replace(/¨E(\d+)E/g,function(e,t){var n=parseInt(t);return String.fromCharCode(n)}),n.converter._dispatch("unescapeSpecialChars.after",e,t,n)}),"function"==typeof define&&define.amd?define(function(){"use strict";return i}):"undefined"!=typeof module&&module.exports?module.exports=i:this.showdown=i}.call(this),function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Clipboard=e()}}(function(){return function e(t,n,i){function r(a,s){if(!n[a]){if(!t[a]){var l="function"==typeof require&&require;if(!s&&l)return l(a,!0);if(o)return o(a,!0);var c=new Error("Cannot find module '"+a+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[a]={exports:{}};t[a][0].call(u.exports,function(e){return r(t[a][1][e]||e)},u,u.exports,e,t,n,i)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a0&&void 0!==arguments[0]?arguments[0]:{};this.action=e.action,this.container=e.container,this.emitter=e.emitter,this.target=e.target,this.text=e.text,this.trigger=e.trigger,this.selectedText=""}},{key:"initSelection",value:function(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function(){var e=this,t="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return e.removeFake()},this.fakeHandler=this.container.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[t?"right":"left"]="-9999px";var i=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=i+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,this.container.appendChild(this.fakeElem),this.selectedText=(0,n.default)(this.fakeElem),this.copyText()}},{key:"removeFake",value:function(){this.fakeHandler&&(this.container.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(this.container.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function(){this.selectedText=(0,n.default)(this.target),this.copyText()}},{key:"copyText",value:function(){var e=void 0;try{e=document.execCommand(this.action)}catch(t){e=!1}this.handleResult(e)}},{key:"handleResult",value:function(e){this.emitter.emit(e?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function(){this.trigger&&this.trigger.focus(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function(){this.removeFake()}},{key:"action",set:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=e,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(e){if(void 0!==e){if(!e||"object"!==(void 0===e?"undefined":i(e))||1!==e.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&e.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(e.hasAttribute("readonly")||e.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=e}},get:function(){return this._target}}]),e}();e.exports=o})},{select:5}],8:[function(e,t,n){!function(i,r){if(void 0!==n)r(t,e("./clipboard-action"),e("tiny-emitter"),e("good-listener"));else{var o={exports:{}};r(o,i.clipboardAction,i.tinyEmitter,i.goodListener),i.clipboard=o.exports}}(this,function(e,t,n,i){"use strict";function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var n="data-clipboard-"+e;if(t.hasAttribute(n))return t.getAttribute(n)}var a=r(t),s=r(n),l=r(i),c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=function(){function e(e,t){for(var n=0;n0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof e.action?e.action:this.defaultAction,this.target="function"==typeof e.target?e.target:this.defaultTarget,this.text="function"==typeof e.text?e.text:this.defaultText,this.container="object"===c(e.container)?e.container:document.body}},{key:"listenClick",value:function(e){var t=this;this.listener=(0,l.default)(e,"click",function(e){return t.onClick(e)})}},{key:"onClick",value:function(e){var t=e.delegateTarget||e.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new a.default({action:this.action(t),target:this.target(t),text:this.text(t),container:this.container,trigger:t,emitter:this})}},{key:"defaultAction",value:function(e){return o("action",e)}},{key:"defaultTarget",value:function(e){var t=o("target",e);if(t)return document.querySelector(t)}},{key:"defaultText",value:function(e){return o("text",e)}},{key:"destroy",value:function(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],t="string"==typeof e?[e]:e,n=!!document.queryCommandSupported;return t.forEach(function(e){n=n&&!!document.queryCommandSupported(e)}),n}}]),t}();e.exports=d})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)}),function(e){function t(i){if(n[i])return n[i].exports;var r=n[i]={exports:{},id:i,loaded:!1};return e[i].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){ShareDB=n(1)},function(e,t,n){t.Connection=n(2),t.Doc=n(4),t.Error=n(7),t.Query=n(14),t.types=n(9)},function(e,t,n){(function(t){function i(e){l.EventEmitter.call(this),this.collections={},this.nextQueryId=1,this.queries={},this.seq=1,this.id=null,this.agent=null,this.debug=!1,this.bindToSocket(e)}function r(e){return e.hasPending()}function o(e){return e.hasWritePending()}var a=n(4),s=n(14),l=n(5),c=n(7),u=n(9),d=n(15);e.exports=i,l.mixin(i),i.prototype.bindToSocket=function(e){this.socket&&(this.socket.close(),this.socket.onmessage=null,this.socket.onopen=null,this.socket.onerror=null,this.socket.onclose=null),this.socket=e,this.state=0===e.readyState||1===e.readyState?"connecting":"disconnected",this.canSend=!1;var n=this;e.onmessage=function(e){try{var i="string"==typeof e.data?JSON.parse(e.data):e.data}catch(t){return void console.warn("Failed to parse message",e)}n.debug&&console.log("RECV",JSON.stringify(i));var r={data:i};if(n.emit("receive",r),r.data)try{n.handleMessage(r.data)}catch(e){t.nextTick(function(){n.emit("error",e)})}},e.onopen=function(){n._setState("connecting")},e.onerror=function(e){n.emit("connection error",e)},e.onclose=function(e){"closed"===e||"Closed"===e?n._setState("closed",e):"stopped"===e||"Stopped by server"===e?n._setState("stopped",e):n._setState("disconnected",e)}},i.prototype.handleMessage=function(e){var t=null;switch(e.error&&((t=new Error(e.error.message)).code=e.error.code,t.data=e,delete e.error),e.a){case"init":return 1!==e.protocol?(t=new c(4019,"Invalid protocol version"),this.emit("error",t)):u.map[e.type]!==u.defaultType?(t=new c(4020,"Invalid default type"),this.emit("error",t)):"string"!=typeof e.id?(t=new c(4021,"Invalid client id"),this.emit("error",t)):(this.id=e.id,void this._setState("connected"));case"qf":return void((n=this.queries[e.id])&&n._handleFetch(t,e.data,e.extra));case"qs":return void((n=this.queries[e.id])&&n._handleSubscribe(t,e.data,e.extra));case"qu":return;case"q":var n;if(!(n=this.queries[e.id]))return;return t?n._handleError(t):(e.diff&&n._handleDiff(e.diff),void(e.hasOwnProperty("extra")&&n._handleExtra(e.extra)));case"bf":return this._handleBulkMessage(e,"_handleFetch");case"bs":return this._handleBulkMessage(e,"_handleSubscribe");case"bu":return this._handleBulkMessage(e,"_handleUnsubscribe");case"f":return void((i=this.getExisting(e.c,e.d))&&i._handleFetch(t,e.data));case"s":return void((i=this.getExisting(e.c,e.d))&&i._handleSubscribe(t,e.data));case"u":return void((i=this.getExisting(e.c,e.d))&&i._handleUnsubscribe(t));case"op":var i;return void((i=this.getExisting(e.c,e.d))&&i._handleOp(t,e));default:console.warn("Ignorning unrecognized message",e)}},i.prototype._handleBulkMessage=function(e,t){if(e.data)for(var n in e.data){(r=this.getExisting(e.c,n))&&r[t](e.error,e.data[n])}else if(Array.isArray(e.b))for(var i=0;i1)for(var n=1;nthis.version?this.fetch(t):t&&t()}if(this.version>e.v)return t&&t();this.version=e.v;var i=void 0===e.type?c.defaultType:e.type;this._setType(i),this.data=this.type&&this.type.deserialize?this.type.deserialize(e.data):e.data,this.emit("load"),t&&t()},i.prototype.whenNothingPending=function(e){return this.hasPending()?void this.once("nothing pending",e):void e()},i.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe.length||this.inflightUnsubscribe.length||this.pendingFetch.length)},i.prototype.hasWritePending=function(){return!(!this.inflightOp&&!this.pendingOps.length)},i.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),this.hasPending()||this.emit("nothing pending"))},i.prototype._emitResponseError=function(e,t){return t?(t(e),void this._emitNothingPending()):(this._emitNothingPending(),void this.emit("error",e))},i.prototype._handleFetch=function(e,t){var n=this.inflightFetch.shift();return e?this._emitResponseError(e,n):(this.ingestSnapshot(t,n),void this._emitNothingPending())},i.prototype._handleSubscribe=function(e,t){var n=this.inflightSubscribe.shift();return e?this._emitResponseError(e,n):(this.wantSubscribe&&(this.subscribed=!0),this.ingestSnapshot(t,n),void this._emitNothingPending())},i.prototype._handleUnsubscribe=function(e){var t=this.inflightUnsubscribe.shift();return e?this._emitResponseError(e,t):(t&&t(),void this._emitNothingPending())},i.prototype._handleOp=function(e,t){if(e)return this.inflightOp?(4002===e.code&&(e=null),this._rollback(e)):this.emit("error",e);if(this.inflightOp&&t.src===this.inflightOp.src&&t.seq===this.inflightOp.seq)this._opAcknowledged(t);else if(null==this.version||t.v>this.version)this.fetch();else if(!(t.v1){this.applyStack||(this.applyStack=[]);for(var i=this.applyStack.length,r=0;r0)this.applyStack.length=e;else{var t=this.applyStack[0];if(this.applyStack=null,t)if(-1!==(i=this.pendingOps.indexOf(t)))for(var n=this.pendingOps.splice(i),i=0;i0&&this._events[e].length>a&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(e,t){function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}if(!i(t))throw TypeError("listener must be a function");var r=!1;return n.listener=t,this.on(e,n),this},n.prototype.removeListener=function(e,t){var n,o,a,s;if(!i(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(a=(n=this._events[e]).length,o=-1,n===t||i(n.listener)&&n.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(r(n)){for(s=a;s-- >0;)if(n[s]===t||n[s].listener&&n[s].listener===t){o=s;break}if(o<0)return this;1===n.length?(n.length=0,delete this._events[e]):n.splice(o,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},n.prototype.removeAllListeners=function(e){var t,n;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(i(n=this._events[e]))this.removeListener(e,n);else if(n)for(;n.length;)this.removeListener(e,n[n.length-1]);return delete this._events[e],this},n.prototype.listeners=function(e){return this._events&&this._events[e]?i(this._events[e])?[this._events[e]]:this._events[e].slice():[]},n.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(i(t))return 1;if(t)return t.length}return 0},n.listenerCount=function(e,t){return e.listenerCount(t)}},function(e,t,n){function i(e,t){i.super.call(this,t),this.code=e}n(8)(i),e.exports=i},function(e,t){"use strict";function n(e){e&&i(this,"message",{configurable:!0,value:e,writable:!0});var t=this.constructor.name;t&&t!==this.name&&i(this,"name",{configurable:!0,value:t,writable:!0}),r(this,this.constructor)}var i=Object.defineProperty,r=Error.captureStackTrace;r||(r=function(e){var t=new Error;i(e,"stack",{configurable:!0,get:function(){var e=t.stack;return i(this,"stack",{value:e}),e},set:function(t){i(e,"stack",{configurable:!0,value:t,writable:!0})}})}),n.prototype=Object.create(Error.prototype,{constructor:{configurable:!0,value:n,writable:!0}});var o=function(){function e(e,t){return i(e,"name",{configurable:!0,value:t})}try{var t=function(){};if(e(t,"foo"),"foo"===t.name)return e}catch(e){}}();(e.exports=function(e,t){if(null==t||t===Error)t=n;else if("function"!=typeof t)throw new TypeError("super_ should be a function");var i;if("string"==typeof e)i=e,e=function(){t.apply(this,arguments)},o&&(o(e,i),i=null);else if("function"!=typeof e)throw new TypeError("constructor should be either a string or a function");e.super_=e.super=t;var r={constructor:{configurable:!0,value:e,writable:!0}};return null!=i&&(r.name={configurable:!0,value:i,writable:!0}),e.prototype=Object.create(t.prototype,r),e}).BaseError=n},function(e,t,n){t.defaultType=n(10).type,t.map={},t.register=function(e){e.name&&(t.map[e.name]=e),e.uri&&(t.map[e.uri]=e)},t.register(t.defaultType)},function(e,t,n){e.exports={type:n(11)}},function(e,t,n){function i(e){e.t="text0";var t={p:e.p.pop()};null!=e.si&&(t.i=e.si),null!=e.sd&&(t.d=e.sd),e.o=[t]}function r(e){e.p.push(e.o[0].p),null!=e.o[0].i&&(e.si=e.o[0].i),null!=e.o[0].d&&(e.sd=e.o[0].d),delete e.t,delete e.o}var o=function(e){return"[object Array]"==Object.prototype.toString.call(e)},a=function(e){return JSON.parse(JSON.stringify(e))},s={name:"json0",uri:"http://sharejs.org/types/JSONv0"},l={};s.registerSubtype=function(e){l[e.name]=e},s.create=function(e){return void 0===e?null:a(e)},s.invertComponent=function(e){var t={p:e.p};return e.t&&l[e.t]&&(t.t=e.t,t.o=l[e.t].invert(e.o)),void 0!==e.si&&(t.sd=e.si),void 0!==e.sd&&(t.si=e.sd),void 0!==e.oi&&(t.od=e.oi),void 0!==e.od&&(t.oi=e.od),void 0!==e.li&&(t.ld=e.li),void 0!==e.ld&&(t.li=e.ld),void 0!==e.na&&(t.na=-e.na),void 0!==e.lm&&(t.lm=e.p[e.p.length-1],t.p=e.p.slice(0,e.p.length-1).concat([e.lm])),t},s.invert=function(e){for(var t=e.slice().reverse(),n=[],i=0;i=i||o!==t.p[r])return null}return n},s.canOpAffectPath=function(e,t){return null!=s.commonLengthForOps({p:t},e)},s.transformComponent=function(e,t,n,o){t=a(t);var c=s.commonLengthForOps(n,t),u=s.commonLengthForOps(t,n),d=t.p.length,h=n.p.length;if((null!=t.na||t.t)&&d++,(null!=n.na||n.t)&&h++,null!=u&&h>d&&t.p[u]==n.p[u])if(void 0!==t.ld){(p=a(n)).p=p.p.slice(d),t.ld=s.apply(a(t.ld),[p])}else if(void 0!==t.od){(p=a(n)).p=p.p.slice(d),t.od=s.apply(a(t.od),[p])}if(null!=c){var f=d==h,p=n;if(null==t.si&&null==t.sd||null==n.si&&null==n.sd||(i(t),i(p=a(n))),p.t&&l[p.t]){if(t.t&&t.t===p.t){var g=l[t.t].transform(t.o,p.o,o);if(g.length>0)if(null!=t.si||null!=t.sd)for(var m=t.p,v=0;vA&&t.p[c]--,C>I?t.p[c]++:C===I&&A>I&&(t.p[c]++,C===y&&t.lm++),y>A?t.lm--:y===A&&y>C&&t.lm--,y>I?t.lm++:y===I&&(I>A&&y>C||IC?t.lm++:y===A&&t.lm--)}else if(void 0!==t.li&&void 0===t.ld&&f){C=n.p[c],y=n.lm;(m=t.p[c])>C&&t.p[c]--,m>y&&t.p[c]++}else{C=n.p[c],y=n.lm;(m=t.p[c])===C?t.p[c]=y:(m>C&&t.p[c]--,m>y?t.p[c]++:m===y&&C>y&&t.p[c]++)}else if(void 0!==n.oi&&void 0!==n.od){if(t.p[c]===n.p[c]){if(void 0===t.oi||!f)return e;if("right"===o)return e;t.od=n.oi}}else if(void 0!==n.oi){if(void 0!==t.oi&&t.p[c]===n.p[c]){if("left"!==o)return e;s.append(e,{p:t.p,od:n.oi})}}else if(void 0!==n.od&&t.p[c]==n.p[c]){if(!f)return e;if(void 0===t.oi)return e;delete t.od}}return s.append(e,t),e},n(12)(s,s.transformComponent,s.checkValidOp,s.append);var u=n(13);s.registerSubtype(u),e.exports=s},function(e,t){e.exports=function(e,t,n,i){var r=function(e,n,i,r){t(i,e,n,"left"),t(r,n,e,"right")},o=e.transformX=function(e,t){n(e),n(t);for(var a=[],s=0;s=n.p+n.d.length)s(e,{d:t.d,p:t.p-n.d.length});else if(t.p+t.d.length<=n.p)s(e,t);else{var a={d:"",p:t.p};t.pn.p+n.d.length&&(a.d+=t.d.slice(n.p+n.d.length-t.p));var c=Math.max(t.p,n.p),u=Math.min(t.p+t.d.length,n.p+n.d.length);if(t.d.slice(c-t.p,u-t.p)!==n.d.slice(c-n.p,u-n.p))throw new Error("Delete ops delete different text in the same region of the document");""!==a.d&&(a.p=l(a.p,n),s(e,a))}return e},u=function(e){return null!=e.i?{d:e.i,p:e.p}:{i:e.d,p:e.p}};i.invert=function(e){e=e.slice().reverse();for(var t=0;t0))throw Error("Object components must be deletes of size > 0");break;case"string":if(!(r.length>0))throw Error("Inserts cannot be empty");break;case"number":if(!(r>0))throw Error("Skip components must be >0");if("number"==typeof t)throw Error("Adjacent skip components should be combined")}t=r}if("number"==typeof t)throw Error("Op has a trailing skip")},r=function(e){return function(t){if(t&&0!==t.d)return 0===e.length?e.push(t):typeof t==typeof e[e.length-1]?"object"==typeof t?e[e.length-1].d+=t.d:e[e.length-1]+=t:e.push(t)}},o=function(e){var t=0,n=0;return[function(i,r){if(t===e.length)return-1===i?null:i;var o,a=e[t];return"number"==typeof a?-1===i||a-n<=i?(o=a-n,++t,n=0,o):(n+=i,i):"string"==typeof a?-1===i||"i"===r||a.length-n<=i?(o=a.slice(n),++t,n=0,o):(o=a.slice(n,n+i),n+=i,o):-1===i||"d"===r||a.d-n<=i?(o={d:a.d-n},++t,n=0,o):(n+=i,{d:i})},function(){return e[t]}]},a=function(e){return"number"==typeof e?e:e.length||e.d},s=function(e){return e.length>0&&"number"==typeof e[e.length-1]&&e.pop(),e};t.normalize=function(e){for(var t=[],n=r(t),i=0;ie.length)throw Error("The op is too long for this document");n.push(e.slice(0,o)),e=e.slice(o);break;case"string":n.push(o);break;case"object":e=e.slice(o.d)}}return n.join("")+e},t.transform=function(e,t,n){if("left"!=n&&"right"!=n)throw Error("side ("+n+") must be 'left' or 'right'");i(e),i(t);for(var l=[],c=r(l),u=o(e),d=u[0],h=u[1],f=0;f0;)c(g=d(p,"i")),"string"!=typeof g&&(p-=a(g));break;case"string":"left"===n&&"string"==typeof h()&&c(d(-1)),c(m.length);break;case"object":for(p=m.d;p>0;)switch(g=d(p,"i"),typeof g){case"number":p-=g;break;case"string":c(g);break;case"object":p-=g.d}}}for(;m=d(-1);)c(m);return s(l)},t.compose=function(e,t){i(e),i(t);for(var n=[],l=r(n),c=o(e)[0],u=0;u0;)l(h=c(d,"d")),"object"!=typeof h&&(d-=a(h));break;case"string":l(f);break;case"object":for(d=f.d;d>0;)switch(h=c(d,"d"),typeof h){case"number":l({d:h}),d-=h;break;case"string":d-=h.length;break;case"object":l(h)}}}for(;f=c(-1);)l(f);return s(n)};var l=function(e,t){for(var n=0,i=0;i127)throw new RangeError("scale7To14Bit takes a 7-bit integer.\nscale7To14Bit("+e+") is invalid.");return e<=64?e<<7:e/127*16383};t.dataBytesToUint14=function(e){var t=e.map(function(e){return 127&e});switch(e.length){case 1:return n(t[0]);case 2:return(t[0]<<7)+t[1]}throw new Error("midiDataToMpeValue takes one or two 8-bit integers.\nmidiDataToMpeValue("+e+") is invalid.")},t.int7ToUnsignedFloat=function(e){return e<=64?.5*e/64:.5+.5*(e-64)/63},t.int14ToUnsignedFloat=function(e){return e<=8192?.5*e/8192:.5+.5*(e-8192)/8191},t.int14ToSignedFloat=function(e){return e<=8192?e/8192-1:(e-8192)/8191}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=void 0;t.logger=function(e){return function(t){return function(i){return function(r){var o=i(r),a=n;return(n=t.getState().activeNotes)!==a&&console.log("active notes:",e(n)),o}}}}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.findActiveNoteIndexesByChannel=t.findActiveNoteIndex=t.convertPitchBendRange=t.createPitchBendConverter=t.addPitch=t.addHelmholtzPitch=t.addScientificPitch=t.normalize=void 0;var i=n(3),r=n(26),o=n(23),a=n(27);function s(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t1&&void 0!==arguments[1]?arguments[1]:{},n=Object.keys(t).reduce(function(n,i){return void 0!==e[i]&&(n[i]=t[i](e[i])),n},{});return Object.assign({},e,n)}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={0:"C",1:"C#",2:"D",3:"Eb",4:"E",5:"F",6:"F#",7:"G",8:"Ab",9:"A",10:"Bb",11:"B"},i=t.toPitchClassNumber=function(e){return Math.floor(e%12)},r=t.toOctaveNumber=function(e){return Math.floor(e/12)-1},o=t.toPitchClassName=function(e){return n[i(e)]},a=t.toHelmholtzCommas=function(e){var t=Math.max(-1*r(e)+2,0);return new Array(t).fill(",").join("")},s=t.toHelmholtzApostrophes=function(e){var t=Math.max(r(e)-3,0);return new Array(t).fill("'").join("")},l=t.toHelmholtzPitchName=function(e){return e>=48?o(e).toLowerCase():o(e)};t.toHelmholtzPitch=function(e){return""+l(e)+a(e)+s(e)},t.toScientificPitch=function(e){return""+o(e)+r(e)}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=n(3),r=a(n(29)),o=a(n(30));function a(e){return e&&e.__esModule?e:{default:e}}t.default=(0,i.combineReducers)({channelScopes:o.default,activeNotes:r.default})},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=s(n(21)),r=s(n(19)),o=s(n(20)),a=n(25);function s(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}function l(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t0&&void 0!==arguments[0]?arguments[0]:r.ACTIVE_NOTE,t=arguments[1],n=t.noteNumber,a=t.channel,s=t.channelScope,l=t.noteOnVelocity,c=t.noteOffVelocity,u=t.pitch,d=t.pitchBend,h=t.pressure,f=t.timbre;switch(t.type){case i.NOTE_ON:return Object.assign({},e,{noteNumber:n,channel:a,noteOnVelocity:l},u&&{pitch:u},s);case i.NOTE_OFF:return Object.assign({},e,{noteOffVelocity:c,noteState:o.OFF});case i.PITCH_BEND:return Object.assign({},e,{pitchBend:d});case i.CHANNEL_PRESSURE:return Object.assign({},e,{pressure:h});case i.TIMBRE:return Object.assign({},e,{timbre:f})}return e};t.default=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments[1];if(!i[t.type])return e;switch(t.type){case i.NOTE_ON:return[].concat(l(e),[c({},t)]);case i.NOTE_OFF:var n=(0,a.findActiveNoteIndex)(e,t);return n>=0?[].concat(l(e.slice(0,n)),[c(e[n],t)],l(e.slice(n+1))):e;case i.PITCH_BEND:case i.CHANNEL_PRESSURE:case i.TIMBRE:return(0,a.findActiveNoteIndexesByChannel)(e,t).forEach(function(n){e=[].concat(l(e.slice(0,n)),[c(e[n],t)],l(e.slice(n+1)))}),e;case i.NOTE_RELEASED:return e.length?e.filter(function(e){return e.noteState!==o.OFF}):e;case i.ALL_NOTES_OFF:return[]}return e}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=o(n(21)),r=o(n(19));function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t.default=e,t}var a=function(e,t){switch(t.type){case i.PITCH_BEND:return Object.assign({},e,{pitchBend:t.pitchBend});case i.CHANNEL_PRESSURE:return Object.assign({},e,{pressure:t.pressure});case i.TIMBRE:return Object.assign({},e,{timbre:t.timbre});case i.NOTE_ON:case i.NOTE_OFF:return r.CHANNEL_SCOPE}return e};t.default=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r.CHANNEL_SCOPES,t=arguments[1];if(!i[t.type])return e;var n,o,s,l=t.channel;return Object.assign({},e,(n={},o=l,s=a(e[l],t),o in n?Object.defineProperty(n,o,{value:s,enumerable:!0,configurable:!0,writable:!0}):n[o]=s,n))}}]),saveAs=saveAs||function(e){"use strict";if(!(void 0===e||"undefined"!=typeof navigator&&/MSIE [1-9]\./.test(navigator.userAgent))){var t=function(){return e.URL||e.webkitURL||e},n=e.document.createElementNS("http://www.w3.org/1999/xhtml","a"),i="download"in n,r=/constructor/i.test(e.HTMLElement)||e.safari,o=/CriOS\/[\d]+/.test(navigator.userAgent),a=function(t){(e.setImmediate||e.setTimeout)(function(){throw t},0)},s=function(e){setTimeout(function(){"string"==typeof e?t().revokeObjectURL(e):e.remove()},4e4)},l=function(e,t,n){for(var i=(t=[].concat(t)).length;i--;){var r=e["on"+t[i]];if("function"==typeof r)try{r.call(e,n||e)}catch(e){a(e)}}},c=function(e){return/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e},u=function(a,u,d){d||(a=c(a));var h,f=this,p="application/octet-stream"===a.type,g=function(){l(f,"writestart progress write writeend".split(" "))};if(f.readyState=f.INIT,i)return h=t().createObjectURL(a),void setTimeout(function(){var e,t;n.href=h,n.download=u,e=n,t=new MouseEvent("click"),e.dispatchEvent(t),g(),s(h),f.readyState=f.DONE});!function(){if((o||p&&r)&&e.FileReader){var n=new FileReader;return n.onloadend=function(){var t=o?n.result:n.result.replace(/^data:[^;]*;/,"data:attachment/file;");e.open(t,"_blank")||(e.location.href=t),t=void 0,f.readyState=f.DONE,g()},n.readAsDataURL(a),void(f.readyState=f.INIT)}h||(h=t().createObjectURL(a)),p?e.location.href=h:e.open(h,"_blank")||(e.location.href=h);f.readyState=f.DONE,g(),s(h)}()},d=u.prototype;return"undefined"!=typeof navigator&&navigator.msSaveOrOpenBlob?function(e,t,n){return t=t||e.name||"download",n||(e=c(e)),navigator.msSaveOrOpenBlob(e,t)}:(d.abort=function(){},d.readyState=d.INIT=0,d.WRITING=1,d.DONE=2,d.error=d.onwritestart=d.onprogress=d.onwrite=d.onabort=d.onerror=d.onwriteend=null,function(e,t,n){return new u(e,t||e.name||"download",n)})}}("undefined"!=typeof self&&self||"undefined"!=typeof window&&window||this.content);"undefined"!=typeof module&&module.exports?module.exports.saveAs=saveAs:"undefined"!=typeof define&&null!==define&&null!==define.amd&&define("FileSaver.js",function(){return saveAs});var LeaderLine=function(){"use strict";var e,t,n,i,r,o,a,s,l,c,u,d,h,f="leader-line",p=1,g=2,m=3,v=4,C={top:p,right:g,bottom:m,left:v},y=1,A=2,I=3,_=4,b=5,w={straight:y,arc:A,fluid:I,magnet:_,grid:b},x="behind",E=f+"-defs",S='',k={disc:{elmId:"leader-line-disc",noRotate:!0,bBox:{left:-5,top:-5,width:10,height:10,right:5,bottom:5},widthR:2.5,heightR:2.5,bCircle:5,sideLen:5,backLen:5,overhead:0,outlineBase:1,outlineMax:4},square:{elmId:"leader-line-square",noRotate:!0,bBox:{left:-5,top:-5,width:10,height:10,right:5,bottom:5},widthR:2.5,heightR:2.5,bCircle:5,sideLen:5,backLen:5,overhead:0,outlineBase:1,outlineMax:4},arrow1:{elmId:"leader-line-arrow1",bBox:{left:-8,top:-8,width:16,height:16,right:8,bottom:8},widthR:4,heightR:4,bCircle:8,sideLen:8,backLen:8,overhead:8,outlineBase:2,outlineMax:1.5},arrow2:{elmId:"leader-line-arrow2",bBox:{left:-7,top:-8,width:11,height:16,right:4,bottom:8},widthR:2.75,heightR:4,bCircle:8,sideLen:8,backLen:7,overhead:4,outlineBase:1,outlineMax:1.75},arrow3:{elmId:"leader-line-arrow3",bBox:{left:-4,top:-5,width:12,height:10,right:8,bottom:5},widthR:3,heightR:2.5,bCircle:8,sideLen:5,backLen:4,overhead:8,outlineBase:1,outlineMax:2.5},hand:{elmId:"leader-line-hand",bBox:{left:-3,top:-12,width:40,height:24,right:37,bottom:12},widthR:10,heightR:6,bCircle:37,sideLen:12,backLen:3,overhead:37},crosshair:{elmId:"leader-line-crosshair",noRotate:!0,bBox:{left:-96,top:-96,width:192,height:192,right:96,bottom:96},widthR:48,heightR:48,bCircle:96,sideLen:96,backLen:96,overhead:0}},T={behind:x,disc:"disc",square:"square",arrow1:"arrow1",arrow2:"arrow2",arrow3:"arrow3",hand:"hand",crosshair:"crosshair"},L={disc:"disc",square:"square",arrow1:"arrow1",arrow2:"arrow2",arrow3:"arrow3",hand:"hand",crosshair:"crosshair"},M=[p,g,m,v],O="auto",P={x:"left",y:"top",width:"width",height:"height"},R=80,D=4,N=5,B=120,F=8,U=3.75,z=10,W=30,H=.5522847,j=.25*Math.PI,V=/^\s*(\-?[\d\.]+)\s*(\%)?\s*$/,G="http://www.w3.org/2000/svg",X="-ms-scroll-limit"in document.documentElement.style&&"-ms-ime-align"in document.documentElement.style&&!window.navigator.msPointerEnabled,Y=!X&&!!document.uniqueID,q="MozAppearance"in document.documentElement.style,K=!(X||q||!window.chrome||!window.CSS),Z=!X&&!Y&&!q&&!K&&!window.chrome&&"WebkitAppearance"in document.documentElement.style,$=Y||X?.2:.1,Q={path:I,lineColor:"coral",lineSize:4,plugSE:[x,"arrow1"],plugSizeSE:[1,1],lineOutlineEnabled:!1,lineOutlineColor:"indianred",lineOutlineSize:.25,plugOutlineEnabledSE:[!1,!1],plugOutlineSizeSE:[1,1]},J=(u={}.toString,d={}.hasOwnProperty.toString,h=d.call(Object),function(e){var t,n;return e&&"[object Object]"===u.call(e)&&(!(t=Object.getPrototypeOf(e))||(n=t.hasOwnProperty("constructor")&&t.constructor)&&"function"==typeof n&&d.call(n)===h)}),ee=Number.isFinite||function(e){return"number"==typeof e&&window.isFinite(e)},te=function(){var e,t={ease:[.25,.1,.25,1],linear:[0,0,1,1],"ease-in":[.42,0,1,1],"ease-out":[0,0,.58,1],"ease-in-out":[.42,0,.58,1]},n=1e3/60/2,i=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){setTimeout(e,n)},r=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.msCancelAnimationFrame||function(e){clearTimeout(e)},o=Number.isFinite||function(e){return"number"==typeof e&&window.isFinite(e)},a=[],s=0;function l(){var t=Date.now(),o=!1;e&&(r.call(window,e),e=null),a.forEach(function(e){var i,r,a;if(e.framesStart){if((i=t-e.framesStart)>=e.duration&&e.count&&e.loopsLeft<=1)return a=e.frames[e.lastFrame=e.reverse?0:e.frames.length-1],e.frameCallback(a.value,!0,a.timeRatio,a.outputRatio),void(e.framesStart=null);if(i>e.duration){if(r=Math.floor(i/e.duration),e.count){if(r>=e.loopsLeft)return a=e.frames[e.lastFrame=e.reverse?0:e.frames.length-1],e.frameCallback(a.value,!0,a.timeRatio,a.outputRatio),void(e.framesStart=null);e.loopsLeft-=r}e.framesStart+=e.duration*r,i=t-e.framesStart}e.reverse&&(i=e.duration-i),a=e.frames[e.lastFrame=Math.round(i/n)],!1!==e.frameCallback(a.value,!1,a.timeRatio,a.outputRatio)?o=!0:e.framesStart=null}}),o&&(e=i.call(window,l))}function c(e,t){e.framesStart=Date.now(),null!=t&&(e.framesStart-=e.duration*(e.reverse?1-t:t)),e.loopsLeft=e.count,e.lastFrame=null,l()}return{add:function(e,i,r,o,l,u,d){var h,f,p,g,m,v,C,y,A,I,_,b,w,x=++s;function E(t,n){return{value:e(n),timeRatio:t,outputRatio:n}}if("string"==typeof l&&(l=t[l]),e=e||function(){},r=this._endIndex||this._string[this._currentIndex]<"0"||"9"=this._endIndex||this._string[this._currentIndex]<"0"||"9"=this._endIndex)return null;var e=null,t=this._string[this._currentIndex];if(this._currentIndex+=1,"0"===t)e=0;else{if("1"!==t)return null;e=1}return this._skipOptionalSpacesOrDelimiter(),e}};var r=function(e){if(!e||0===e.length)return[];var t=new n(e),i=[];if(t.initialCommandIsMoveTo())for(;t.hasMoreData();){var r=t.parseSegment();if(null===r)break;i.push(r)}return i},o=e.SVGPathElement.prototype.setAttribute,a=e.SVGPathElement.prototype.removeAttribute,s=e.Symbol?e.Symbol():"__cachedPathData",l=e.Symbol?e.Symbol():"__cachedNormalizedPathData",c=function(e,t,n,i,r,o,a,s,l,u){var d,h,f,p,g,m=function(e,t,n){return{x:e*Math.cos(n)-t*Math.sin(n),y:e*Math.sin(n)+t*Math.cos(n)}},v=(d=a,Math.PI*d/180),C=[];if(u)h=u[0],f=u[1],p=u[2],g=u[3];else{var y=m(e,t,-v);e=y.x,t=y.y;var A=m(n,i,-v),I=(e-(n=A.x))/2,_=(t-(i=A.y))/2,b=I*I/(r*r)+_*_/(o*o);1120*Math.PI/180){var L=f,M=n,O=i;f=l&&h=Math.abs(i)?0<=t?g:v:0<=i?m:p))})),L.position_path!==O.position_path||L.position_lineStrokeWidth!==O.position_lineStrokeWidth||[0,1].some(function(e){return L.position_plugOverheadSE[e]!==O.position_plugOverheadSE[e]||(o=P[e],a=O.position_socketXYSE[e],o.x!==a.x||o.y!==a.y||o.socketId!==a.socketId)||(n=t[e],i=O.position_socketGravitySE[e],(r=null==n?"auto":Array.isArray(n)?"array":"number")!=(null==i?"auto":Array.isArray(i)?"array":"number")||("array"===r?n[0]!==i[0]||n[1]!==i[1]:n!==i));var n,i,r,o,a})){switch(e.pathList.baseVal=i=[],e.pathList.animVal=null,L.position_path){case y:i.push([X(P[0]),X(P[1])]);break;case A:h="number"==typeof t[0]&&0D?(L.position_lineStrokeWidth-D)*N:0),e.socketId===p?((a=(e.y-i.y)/2)=t.x:t.dirId===o?e.y>=t.y:e.x<=t.x}function f(e,t){return t.dirId===n||t.dirId===o?e.x===t.x:e.y===t.y}function p(e){return e[0]?{contain:0,notContain:1}:{contain:1,notContain:0}}function g(e,t,n){return Math.abs(t[n]-e[n])}function m(e,t,i){return"x"===i?e.x=W?m(l[t.notContain],l[t.contain],c[t.contain]):l[t.contain].dirId)):(i=[{x:l[0].x,y:l[0].y},{x:l[1].x,y:l[1].y}],s.forEach(function(e,t){var n=0===t?1:0,r=g(i[t],i[n],c[t]);rz&&(l[o]-ez&&(l[o]-ei.outlineMax&&(t=i.outlineMax),t*=2*i.outlineBase,I=Ne(C,A.plugOutline_strokeWidthSE,e,t)||I,I=Ne(C,A.plugOutline_inStrokeWidthSE,e,A.plugOutline_colorTraSE[e]?t-$/(A.line_strokeWidth/Q.lineSize)/y.plugSizeSE[e]*2:t/2)||I)}),I)),(n.faces||de.line||de.plug||de.lineOutline||de.plugOutline)&&(de.faces=(w=(_=t).curStats,E=_.aplStats,S=_.events,T=!1,!w.line_altColor&&Ne(_,E,"line_color",b=w.line_color,S.apl_line_color)&&(_.lineFace.style.stroke=b,T=!0),Ne(_,E,"line_strokeWidth",b=w.line_strokeWidth,S.apl_line_strokeWidth)&&(_.lineShape.style.strokeWidth=b+"px",T=!0,(q||Y)&&(Me(_,_.lineShape),Y&&(Me(_,_.lineFace),Me(_,_.lineMaskCaps)))),Ne(_,E,"lineOutline_enabled",b=w.lineOutline_enabled,S.apl_lineOutline_enabled)&&(_.lineOutlineFace.style.display=b?"inline":"none",T=!0),w.lineOutline_enabled&&(Ne(_,E,"lineOutline_color",b=w.lineOutline_color,S.apl_lineOutline_color)&&(_.lineOutlineFace.style.stroke=b,T=!0),Ne(_,E,"lineOutline_strokeWidth",b=w.lineOutline_strokeWidth,S.apl_lineOutline_strokeWidth)&&(_.lineOutlineMaskShape.style.strokeWidth=b+"px",T=!0,Y&&(Me(_,_.lineOutlineMaskCaps),Me(_,_.lineOutlineFace))),Ne(_,E,"lineOutline_inStrokeWidth",b=w.lineOutline_inStrokeWidth,S.apl_lineOutline_inStrokeWidth)&&(_.lineMaskShape.style.strokeWidth=b+"px",T=!0,Y&&(Me(_,_.lineOutlineMaskCaps),Me(_,_.lineOutlineFace)))),Ne(_,E,"plug_enabled",b=w.plug_enabled,S.apl_plug_enabled)&&(_.plugsFace.style.display=b?"inline":"none",T=!0),w.plug_enabled&&[0,1].forEach(function(e){var t=w.plug_plugSE[e],n=t!==x?k[L[t]]:null,i=Re(e,n);Ne(_,E.plug_enabledSE,e,b=w.plug_enabledSE[e],S.apl_plug_enabledSE)&&(_.plugsFace.style[i.prop]=b?"url(#"+_.plugMarkerIdSE[e]+")":"none",T=!0),w.plug_enabledSE[e]&&(Ne(_,E.plug_plugSE,e,t,S.apl_plug_plugSE)&&(_.plugFaceSE[e].href.baseVal="#"+n.elmId,Pe(_,_.plugMarkerSE[e],i.orient,n.bBox,_.svg,_.plugMarkerShapeSE[e],_.plugsFace),T=!0,q&&Me(_,_.plugsFace)),Ne(_,E.plug_colorSE,e,b=w.plug_colorSE[e],S.apl_plug_colorSE)&&(_.plugFaceSE[e].style.fill=b,T=!0,(K||Z||Y)&&!w.line_colorTra&&Me(_,Y?_.lineMaskCaps:_.capsMaskLine)),["markerWidth","markerHeight"].forEach(function(t){var n="plug_"+t+"SE";Ne(_,E[n],e,b=w[n][e],S["apl_"+n])&&(_.plugMarkerSE[e][t].baseVal.value=b,T=!0)}),Ne(_,E.plugOutline_enabledSE,e,b=w.plugOutline_enabledSE[e],S.apl_plugOutline_enabledSE)&&(b?(_.plugFaceSE[e].style.mask="url(#"+_.plugMaskIdSE[e]+")",_.plugOutlineFaceSE[e].style.display="inline"):(_.plugFaceSE[e].style.mask="none",_.plugOutlineFaceSE[e].style.display="none"),T=!0),w.plugOutline_enabledSE[e]&&(Ne(_,E.plugOutline_plugSE,e,t,S.apl_plugOutline_plugSE)&&(_.plugOutlineFaceSE[e].href.baseVal=_.plugMaskShapeSE[e].href.baseVal=_.plugOutlineMaskShapeSE[e].href.baseVal="#"+n.elmId,[_.plugMaskSE[e],_.plugOutlineMaskSE[e]].forEach(function(e){e.x.baseVal.value=n.bBox.left,e.y.baseVal.value=n.bBox.top,e.width.baseVal.value=n.bBox.width,e.height.baseVal.value=n.bBox.height}),T=!0),Ne(_,E.plugOutline_colorSE,e,b=w.plugOutline_colorSE[e],S.apl_plugOutline_colorSE)&&(_.plugOutlineFaceSE[e].style.fill=b,T=!0,Y&&(Me(_,_.lineMaskCaps),Me(_,_.lineOutlineMaskCaps))),Ne(_,E.plugOutline_strokeWidthSE,e,b=w.plugOutline_strokeWidthSE[e],S.apl_plugOutline_strokeWidthSE)&&(_.plugOutlineMaskShapeSE[e].style.strokeWidth=b+"px",T=!0),Ne(_,E.plugOutline_inStrokeWidthSE,e,b=w.plugOutline_inStrokeWidthSE[e],S.apl_plugOutline_inStrokeWidthSE)&&(_.plugMaskShapeSE[e].style.strokeWidth=b+"px",T=!0)))}),T)),(n.position||de.line||de.plug)&&(de.position=Ue(t)),(n.path||de.position)&&(de.path=(R=(M=t).curStats,D=M.aplStats,N=M.pathList.animVal||M.pathList.baseVal,B=R.path_edge,F=!1,N&&(B.x1=B.x2=N[0][0].x,B.y1=B.y2=N[0][0].y,R.path_pathData=O=xe(N,function(e){e.xB.x2&&(B.x2=e.x),e.y>B.y2&&(B.y2=e.y)}),Se(O,D.path_pathData)&&(M.linePath.setPathData(O),D.path_pathData=O,F=!0,Y?(Me(M,M.plugsFace),Me(M,M.lineMaskCaps)):q&&Me(M,M.linePath),M.events.apl_path&&M.events.apl_path.forEach(function(e){e(M,O)}))),F)),de.viewBox=(H=(U=t).curStats,j=U.aplStats,V=H.path_edge,G=H.viewBox_bBox,X=j.viewBox_bBox,J=U.svg.viewBox.baseVal,ee=U.svg.style,te=!1,z=Math.max(H.line_strokeWidth/2,H.viewBox_plugBCircleSE[0]||0,H.viewBox_plugBCircleSE[1]||0),W={x1:V.x1-z,y1:V.y1-z,x2:V.x2+z,y2:V.y2+z},U.events.new_edge4viewBox&&U.events.new_edge4viewBox.forEach(function(e){e(U,W)}),G.x=H.lineMask_x=H.lineOutlineMask_x=H.maskBGRect_x=W.x1,G.y=H.lineMask_y=H.lineOutlineMask_y=H.maskBGRect_y=W.y1,G.width=W.x2-W.x1,G.height=W.y2-W.y1,["x","y","width","height"].forEach(function(e){var t;(t=G[e])!==X[e]&&(J[e]=X[e]=t,ee[P[e]]=t+("x"===e||"y"===e?U.bodyOffset[e]:0)+"px",te=!0)}),te),de.mask=(re=(ne=t).curStats,oe=ne.aplStats,ae=!1,re.plug_enabled?[0,1].forEach(function(e){re.capsMaskMarker_enabledSE[e]=re.plug_enabledSE[e]&&re.plug_colorTraSE[e]||re.plugOutline_enabledSE[e]&&re.plugOutline_colorTraSE[e]}):re.capsMaskMarker_enabledSE[0]=re.capsMaskMarker_enabledSE[1]=!1,re.capsMaskMarker_enabled=re.capsMaskMarker_enabledSE[0]||re.capsMaskMarker_enabledSE[1],re.lineMask_outlineMode=re.lineOutline_enabled,re.caps_enabled=re.capsMaskMarker_enabled||re.capsMaskAnchor_enabledSE[0]||re.capsMaskAnchor_enabledSE[1],re.lineMask_enabled=re.caps_enabled||re.lineMask_outlineMode,(re.lineMask_enabled&&!re.lineMask_outlineMode||re.lineOutline_enabled)&&["x","y"].forEach(function(e){var t="maskBGRect_"+e;Ne(ne,oe,t,ie=re[t])&&(ne.maskBGRect[e].baseVal.value=ie,ae=!0)}),Ne(ne,oe,"lineMask_enabled",ie=re.lineMask_enabled)&&(ne.lineFace.style.mask=ie?"url(#"+ne.lineMaskId+")":"none",ae=!0,Z&&Me(ne,ne.lineMask)),re.lineMask_enabled&&(Ne(ne,oe,"lineMask_outlineMode",ie=re.lineMask_outlineMode)&&(ie?(ne.lineMaskBG.style.display="none",ne.lineMaskShape.style.display="inline"):(ne.lineMaskBG.style.display="inline",ne.lineMaskShape.style.display="none"),ae=!0),["x","y"].forEach(function(e){var t="lineMask_"+e;Ne(ne,oe,t,ie=re[t])&&(ne.lineMask[e].baseVal.value=ie,ae=!0)}),Ne(ne,oe,"caps_enabled",ie=re.caps_enabled)&&(ne.lineMaskCaps.style.display=ne.lineOutlineMaskCaps.style.display=ie?"inline":"none",ae=!0,Z&&Me(ne,ne.capsMaskLine)),re.caps_enabled&&([0,1].forEach(function(e){var t;Ne(ne,oe.capsMaskAnchor_enabledSE,e,ie=re.capsMaskAnchor_enabledSE[e])&&(ne.capsMaskAnchorSE[e].style.display=ie?"inline":"none",ae=!0,Z&&Me(ne,ne.lineMask)),re.capsMaskAnchor_enabledSE[e]&&(Se(t=re.capsMaskAnchor_pathDataSE[e],oe.capsMaskAnchor_pathDataSE[e])&&(ne.capsMaskAnchorSE[e].setPathData(t),oe.capsMaskAnchor_pathDataSE[e]=t,ae=!0),Ne(ne,oe.capsMaskAnchor_strokeWidthSE,e,ie=re.capsMaskAnchor_strokeWidthSE[e])&&(ne.capsMaskAnchorSE[e].style.strokeWidth=ie+"px",ae=!0))}),Ne(ne,oe,"capsMaskMarker_enabled",ie=re.capsMaskMarker_enabled)&&(ne.capsMaskLine.style.display=ie?"inline":"none",ae=!0),re.capsMaskMarker_enabled&&[0,1].forEach(function(e){var t=re.capsMaskMarker_plugSE[e],n=t!==x?k[L[t]]:null,i=Re(e,n);Ne(ne,oe.capsMaskMarker_enabledSE,e,ie=re.capsMaskMarker_enabledSE[e])&&(ne.capsMaskLine.style[i.prop]=ie?"url(#"+ne.lineMaskMarkerIdSE[e]+")":"none",ae=!0),re.capsMaskMarker_enabledSE[e]&&(Ne(ne,oe.capsMaskMarker_plugSE,e,t)&&(ne.capsMaskMarkerShapeSE[e].href.baseVal="#"+n.elmId,Pe(ne,ne.capsMaskMarkerSE[e],i.orient,n.bBox,ne.svg,ne.capsMaskMarkerShapeSE[e],ne.capsMaskLine),ae=!0,q&&(Me(ne,ne.capsMaskLine),Me(ne,ne.lineFace))),["markerWidth","markerHeight"].forEach(function(t){var n="capsMaskMarker_"+t+"SE";Ne(ne,oe[n],e,ie=re[n][e])&&(ne.capsMaskMarkerSE[e][t].baseVal.value=ie,ae=!0)}))}))),re.lineOutline_enabled&&["x","y"].forEach(function(e){var t="lineOutlineMask_"+e;Ne(ne,oe,t,ie=re[t])&&(ne.lineOutlineMask[e].baseVal.value=ie,ae=!0)}),ae),n.effect&&(ce=(se=t).curStats,ue=se.aplStats,Object.keys(e).forEach(function(t){var n=e[t],i=t+"_enabled",r=t+"_options",o=ce[r];Ne(se,ue,i,le=ce[i])?(le&&(ue[r]=fe(o)),n[le?"init":"remove"](se)):le&&he(o,ue[r])&&(n.remove(se),ue[i]=!0,ue[r]=fe(o),n.init(se))})),(K||Z)&&de.line&&!de.path&&Me(t,t.lineShape),K&&de.plug&&!de.line&&Me(t,t.plugsFace),Oe(t)}function He(e,t){return{duration:ee(e.duration)&&0t.x2&&(t.x2=i.x2),i.y2>t.y2&&(t.y2=i.y2),["x","y"].forEach(function(n){var i,a="dropShadow_"+n;r[a]=i=t[n+"1"],Ne(e,o,a,i)&&(e.efc_dropShadow_elmFilter[n].baseVal.value=i)}))}}},Object.keys(e).forEach(function(t){var n=e[t],i=n.stats;i[t+"_enabled"]={iniValue:!1},i[t+"_options"]={hasProps:!0},n.anim&&(i[t+"_animOptions"]={},i[t+"_animId"]={})}),t={none:{defaultAnimOptions:{},init:function(e,n){var i=e.curStats;i.show_animId&&(te.remove(i.show_animId),i.show_animId=null),t.none.start(e,n)},start:function(e,n){t.none.stop(e,!0)},stop:function(e,t,n){var i=e.curStats;return n=null!=n?n:e.aplStats.show_on,i.show_inAnim=!1,t&&ze(e,n),n?1:0}},fade:{defaultAnimOptions:{duration:300,timing:"linear"},init:function(e,n){var i=e.curStats,r=e.aplStats;i.show_animId&&te.remove(i.show_animId),i.show_animId=te.add(function(e){return e},function(n,i){i?t.fade.stop(e,!0):(e.svg.style.opacity=n+"",Y&&(Me(e,e.svg),Oe(e)))},r.show_animOptions.duration,1,r.show_animOptions.timing,null,!1),t.fade.start(e,n)},start:function(e,t){var n,i=e.curStats;i.show_inAnim&&(n=te.stop(i.show_animId)),ze(e,1),i.show_inAnim=!0,te.start(i.show_animId,!e.aplStats.show_on,null!=t?t:n)},stop:function(e,t,n){var i,r=e.curStats;return n=null!=n?n:e.aplStats.show_on,i=r.show_inAnim?te.stop(r.show_animId):n?1:0,r.show_inAnim=!1,t&&(e.svg.style.opacity=n?"":"0",ze(e,n)),i}},draw:{defaultAnimOptions:{duration:500,timing:[.58,0,.42,1]},init:function(e,n){var i=e.curStats,r=e.aplStats,o=e.pathList.baseVal,a=Ee(o),s=a.segsLen,l=a.lenAll;i.show_animId&&te.remove(i.show_animId),i.show_animId=te.add(function(e){var t,n,i,r,a=-1;if(0===e)n=[[o[0][0],o[0][0]]];else if(1===e)n=o;else{for(t=l*e,n=[];t>=s[++a];)n.push(o[a]),t-=s[a];t&&(2===(i=o[a]).length?n.push([i[0],Ae(i[0],i[1],t/s[a])]):(r=_e(i[0],i[1],i[2],i[3],we(i[0],i[1],i[2],i[3],t)),n.push([i[0],r.fromP1,r.fromP2,r])))}return n},function(n,i){i?t.draw.stop(e,!0):(e.pathList.animVal=n,We(e,{path:!0}))},r.show_animOptions.duration,1,r.show_animOptions.timing,null,!1),t.draw.start(e,n)},start:function(e,n){var i,r=e.curStats;r.show_inAnim&&(i=te.stop(r.show_animId)),ze(e,1),r.show_inAnim=!0,ke(e,"apl_position",t.draw.update),te.start(r.show_animId,!e.aplStats.show_on,null!=n?n:i)},stop:function(e,t,n){var i,r=e.curStats;return n=null!=n?n:e.aplStats.show_on,i=r.show_inAnim?te.stop(r.show_animId):n?1:0,r.show_inAnim=!1,t&&(e.pathList.animVal=n?null:[[e.pathList.baseVal[0][0],e.pathList.baseVal[0][0]]],We(e,{path:!0}),ze(e,n)),i},update:function(e){Te(e,"apl_position",t.draw.update),e.curStats.show_inAnim?t.draw.init(e,t.draw.stop(e)):e.aplStats.show_animOptions={}}}},function(){function t(e){return function(t){var n={};n[e]=t,this.setOptions(n)}}[["start","anchorSE",0],["end","anchorSE",1],["color","lineColor"],["size","lineSize"],["startSocketGravity","socketGravitySE",0],["endSocketGravity","socketGravitySE",1],["startPlugColor","plugColorSE",0],["endPlugColor","plugColorSE",1],["startPlugSize","plugSizeSE",0],["endPlugSize","plugSizeSE",1],["outline","lineOutlineEnabled"],["outlineColor","lineOutlineColor"],["outlineSize","lineOutlineSize"],["startPlugOutline","plugOutlineEnabledSE",0],["endPlugOutline","plugOutlineEnabledSE",1],["startPlugOutlineColor","plugOutlineColorSE",0],["endPlugOutlineColor","plugOutlineColorSE",1],["startPlugOutlineSize","plugOutlineSizeSE",0],["endPlugOutlineSize","plugOutlineSizeSE",1]].forEach(function(e){var n=e[0],i=e[1],r=e[2];Object.defineProperty(Ye.prototype,n,{get:function(){var e=null!=r?le[this._id].options[i][r]:i?le[this._id].options[i]:le[this._id].options[n];return null==e?O:fe(e)},set:t(n),enumerable:!0})}),[["path",w],["startSocket",C,"socketSE",0],["endSocket",C,"socketSE",1],["startPlug",T,"plugSE",0],["endPlug",T,"plugSE",1]].forEach(function(e){var n=e[0],i=e[1],r=e[2],o=e[3];Object.defineProperty(Ye.prototype,n,{get:function(){var e,t=null!=o?le[this._id].options[r][o]:r?le[this._id].options[r]:le[this._id].options[n];return t?Object.keys(i).some(function(n){return i[n]===t&&(e=n,!0)})?e:new Error("It's broken"):O},set:t(n),enumerable:!0})}),Object.keys(e).forEach(function(n){var i=e[n];Object.defineProperty(Ye.prototype,n,{get:function(){var e,t,r=le[this._id].options[n];return J(r)?(e=r,t=i.optionsConf.reduce(function(t,n){var i,r=n[0],o=n[1],a=n[2],s=n[3],l=n[4],c=null!=l?e[s][l]:s?e[s]:e[o];return t[o]="id"===r?c?Object.keys(a).some(function(e){return a[e]===c&&(i=e,!0)})?i:new Error("It's broken"):O:null==c?O:fe(c),t},{}),i.anim&&(t.animation=fe(e.animation)),t):r},set:t(n),enumerable:!0})}),["startLabel","endLabel","middleLabel"].forEach(function(e,n){Object.defineProperty(Ye.prototype,e,{get:function(){var e=le[this._id],t=e.options;return t.labelSEM[n]&&!e.optionIsAttach.labelSEM[n]?ue[t.labelSEM[n]._id].text:t.labelSEM[n]||""},set:t(e),enumerable:!0})})}(),Ye.prototype.setOptions=function(e){return Xe(le[this._id],e),this},Ye.prototype.position=function(){return We(le[this._id],{position:!0}),this},Ye.prototype.remove=function(){var t=le[this._id],n=t.curStats;Object.keys(e).forEach(function(e){var t=e+"_animId";n[t]&&te.remove(n[t])}),n.show_animId&&te.remove(n.show_animId),t.attachments.slice().forEach(function(e){Ge(t,e)}),t.baseWindow&&t.svg&&t.baseWindow.document.body.removeChild(t.svg),delete le[this._id]},Ye.prototype.show=function(e,t){return je(le[this._id],!0,e,t),this},Ye.prototype.hide=function(e,t){return je(le[this._id],!1,e,t),this},o=function(e){e&&ue[e._id]&&(e.boundTargets.slice().forEach(function(t){Ge(t.props,e,!0)}),e.conf.remove&&e.conf.remove(e),delete ue[e._id])},i=function(){function e(e,t){var n,i={conf:e,curStats:{},aplStats:{},boundTargets:[]},r={};e.argOptions.every(function(e){return!(!t.length||("string"==typeof e.type?typeof t[0]!==e.type:"function"!=typeof e.type||!e.type(t[0]))||(r[e.optionName]=t.shift(),0))}),n=t.length&&J(t[0])?fe(t[0]):{},Object.keys(r).forEach(function(e){n[e]=r[e]}),e.stats&&(De(i.curStats,e.stats),De(i.aplStats,e.stats)),Object.defineProperty(this,"_id",{value:++de}),Object.defineProperty(this,"isRemoved",{get:function(){return!ue[this._id]}}),i._id=this._id,e.init&&!e.init(i,n)||(ue[this._id]=i)}return e.prototype.remove=function(){var e=this,t=ue[e._id];t&&(t.boundTargets.slice().forEach(function(e){t.conf.removeOption(t,e)}),Le(function(){var t=ue[e._id];t&&(console.error("LeaderLineAttachment was not removed by removeOption"),o(t))}))},e}(),window.LeaderLineAttachment=i,r=function(e,t){return e instanceof i&&(!(e.isRemoved||t&&ue[e._id].conf.type!==t)||null)},n={pointAnchor:{type:"anchor",argOptions:[{optionName:"element",type:ge}],init:function(e,t){return e.element=n.pointAnchor.checkElement(t.element),e.x=n.pointAnchor.parsePercent(t.x,!0)||[.5,!0],e.y=n.pointAnchor.parsePercent(t.y,!0)||[.5,!0],!0},removeOption:function(e,t){var r=t.props,o={},a=e.element,s=r.options.anchorSE["start"===t.optionName?1:0];a===s&&(a=s===document.body?new i(n.pointAnchor,[a]):document.body),o[t.optionName]=a,Xe(r,o)},getBBoxNest:function(e,t){var n=Ce(e.element,t.baseWindow),i=n.width,r=n.height;return n.width=n.height=0,n.left=n.right=n.left+e.x[0]*(e.x[1]?i:1),n.top=n.bottom=n.top+e.y[0]*(e.y[1]?r:1),n},parsePercent:function(e,t){var n,i,r=!1;return ee(e)?i=e:"string"==typeof e&&(n=V.exec(e))&&n[2]&&(r=0!=(i=parseFloat(n[1])/100)),null!=i&&(t||0<=i)?[i,r]:null},checkElement:function(e){if(null==e)e=document.body;else if(!ge(e))throw new Error("`element` must be Element");return e}},areaAnchor:{type:"anchor",argOptions:[{optionName:"element",type:ge},{optionName:"shape",type:"string"}],stats:{color:{},strokeWidth:{},elementWidth:{},elementHeight:{},elementLeft:{},elementTop:{},pathListRel:{},bBoxRel:{},pathData:{},viewBoxBBox:{hasProps:!0},dashLen:{},dashGap:{}},init:function(e,t){var i,r,o,a=[];return e.element=n.pointAnchor.checkElement(t.element),"string"==typeof t.color&&(e.color=t.color.trim()),"string"==typeof t.fillColor&&(e.fill=t.fillColor.trim()),ee(t.size)&&0<=t.size&&(e.size=t.size),t.dash&&(e.dash=!0,ee(t.dash.len)&&0i.right&&(i.right=n),oi.bottom&&(i.bottom=o)):i={left:n,right:n,top:o,bottom:o},r?R.pathListRel.push([r,{x:n,y:o}]):R.pathListRel=[],r={x:n,y:o}}),R.pathListRel.push([]),o=R.strokeWidth/2,a=[{x:i.left-o,y:i.top-o},{x:i.right+o,y:i.bottom+o}],R.bBoxRel={left:a[0].x,top:a[0].y,right:a[1].x,bottom:a[1].y,width:a[1].x-a[0].x,height:a[1].y-a[0].y}}B.pathListRel=B.bBoxRel=!0}return(B.pathListRel||B.elementLeft||B.elementTop)&&(R.pathData=xe(R.pathListRel,function(e){e.x+=t.left,e.y+=t.top})),Ne(e,D,"strokeWidth",n=R.strokeWidth)&&(e.path.style.strokeWidth=n+"px"),Se(n=R.pathData,D.pathData)&&(e.path.setPathData(n),D.pathData=n,B.pathData=!0),e.dash&&(!B.pathData&&(!B.strokeWidth||e.dashLen&&e.dashGap)||(R.dashLen=e.dashLen||2*R.strokeWidth,R.dashGap=e.dashGap||R.strokeWidth),B.dash=Ne(e,D,"dashLen",R.dashLen)||B.dash,B.dash=Ne(e,D,"dashGap",R.dashGap)||B.dash,B.dash&&(e.path.style.strokeDasharray=D.dashLen+","+D.dashGap)),T=R.viewBoxBBox,L=D.viewBoxBBox,M=e.svg.viewBox.baseVal,O=e.svg.style,T.x=R.bBoxRel.left+t.left,T.y=R.bBoxRel.top+t.top,T.width=R.bBoxRel.width,T.height=R.bBoxRel.height,["x","y","width","height"].forEach(function(t){(n=T[t])!==L[t]&&(M[t]=L[t]=n,O[P[t]]=n+("x"===t||"y"===t?e.bodyOffset[t]:0)+"px")}),B.strokeWidth||B.pathListRel||B.bBoxRel}},mouseHoverAnchor:{type:"anchor",argOptions:[{optionName:"element",type:ge},{optionName:"showEffectName",type:"string"}],style:{backgroundImage:"url('data:image/svg+xml;charset=utf-8;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjI0IiBoZWlnaHQ9IjI0Ij48cG9seWdvbiBwb2ludHM9IjI0LDAgMCw4IDgsMTEgMCwxOSA1LDI0IDEzLDE2IDE2LDI0IiBmaWxsPSJjb3JhbCIvPjwvc3ZnPg==')",backgroundSize:"",backgroundRepeat:"no-repeat",backgroundColor:"#f8f881",cursor:"default"},hoverStyle:{backgroundImage:"none",backgroundColor:"#fadf8f"},padding:{top:1,right:15,bottom:1,left:2},minHeight:15,backgroundPosition:{right:2,top:2},backgroundSize:{width:12,height:12},dirKeys:[["top","Top"],["right","Right"],["bottom","Bottom"],["left","Left"]],init:function(e,i){var r,o,a,s,l,c,u,d,h,f,p,g=n.mouseHoverAnchor,m={};if(e.element=n.pointAnchor.checkElement(i.element),!((f=(d=e.element).ownerDocument)&&(h=f.defaultView)&&h.HTMLElement&&d instanceof h.HTMLElement))throw new Error("`element` must be HTML element");return g.style.backgroundSize=g.backgroundSize.width+"px "+g.backgroundSize.height+"px",["style","hoverStyle"].forEach(function(t){var n=g[t];e[t]=Object.keys(n).reduce(function(e,t){return e[t]=n[t],e},{})}),"inline"===(r=e.element.ownerDocument.defaultView.getComputedStyle(e.element,"")).display?e.style.display="inline-block":"none"===r.display&&(e.style.display="block"),n.mouseHoverAnchor.dirKeys.forEach(function(t){var n=t[0],i="padding"+t[1];parseFloat(r[i])e.x2&&(e.x2=i.x2),i.y2>e.y2&&(e.y2=i.y2)},newText:function(e,t,n,i,r){var o,a,s,c,u,d;return(o=t.createElementNS(G,"text")).textContent=e,[o.x,o.y].forEach(function(e){var t=n.createSVGLength();t.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX,0),e.baseVal.initialize(t)}),"boolean"!=typeof l&&(l="paintOrder"in o.style),r&&!l?(s=t.createElementNS(G,"defs"),o.id=i,s.appendChild(o),(u=(a=t.createElementNS(G,"g")).appendChild(t.createElementNS(G,"use"))).href.baseVal="#"+i,(c=a.appendChild(t.createElementNS(G,"use"))).href.baseVal="#"+i,(d=u.style).strokeLinejoin="round",{elmPosition:o,styleText:o.style,styleFill:c.style,styleStroke:d,styleShow:a.style,elmsAppend:[s,a]}):(d=o.style,r&&(d.strokeLinejoin="round",d.paintOrder="stroke"),{elmPosition:o,styleText:d,styleFill:d,styleStroke:r?d:null,styleShow:d,elmsAppend:[o]})},getMidPoint:function(e,t){var n,i,r,o=Ee(e),a=o.segsLen,s=o.lenAll,l=-1;if((n=s/2+(t||0))<=0)return 2===(i=e[0]).length?Ae(i[0],i[1],0):_e(i[0],i[1],i[2],i[3],0);if(s<=n)return 2===(i=e[e.length-1]).length?Ae(i[0],i[1],1):_e(i[0],i[1],i[2],i[3],1);for(r=[];n>a[++l];)r.push(e[l]),n-=a[l];return 2===(i=e[l]).length?Ae(i[0],i[1],n/a[l]):_e(i[0],i[1],i[2],i[3],we(i[0],i[1],i[2],i[3],n))},initSvg:function(e,t){var i,r,o=n.captionLabel.newText(e.text,t.baseWindow.document,t.svg,f+"-captionLabel-"+e._id,e.outlineColor);["elmPosition","styleFill","styleShow","elmsAppend"].forEach(function(t){e[t]=o[t]}),e.isShown=!1,e.styleShow.visibility="hidden",n.captionLabel.textStyleProps.forEach(function(t){null!=e[t]&&(o.styleText[t]=e[t])}),o.elmsAppend.forEach(function(e){t.svg.appendChild(e)}),i=o.elmPosition.getBBox(),e.width=i.width,e.height=i.height,e.outlineColor&&(r=10<(r=i.height/9)?10:r<2?2:r,o.styleStroke.strokeWidth=r+"px",o.styleStroke.stroke=e.outlineColor),e.strokeWidth=r||0,De(e.aplStats,n.captionLabel.stats),e.updateColor(t),e.refSocketXY?e.updateSocketXY(t):e.updatePath(t),Z&&We(t,{}),e.updateShow(t)},bind:function(e,t){var i=t.props;return e.color||ke(i,"cur_line_color",e.updateColor),(e.refSocketXY="startLabel"===t.optionName||"endLabel"===t.optionName)?(e.socketIndex="startLabel"===t.optionName?0:1,ke(i,"apl_position",e.updateSocketXY),e.offset||(ke(i,"cur_attach_plugSideLenSE",e.updateSocketXY),ke(i,"cur_line_strokeWidth",e.updateSocketXY))):ke(i,"apl_path",e.updatePath),ke(i,"svgShow",e.updateShow),Z&&ke(i,"new_edge4viewBox",e.adjustEdge),n.captionLabel.initSvg(e,i),!0},unbind:function(e,t){var i=t.props;e.elmsAppend&&(e.elmsAppend.forEach(function(e){i.svg.removeChild(e)}),e.elmPosition=e.styleFill=e.styleShow=e.elmsAppend=null),De(e.curStats,n.captionLabel.stats),De(e.aplStats,n.captionLabel.stats),e.color||Te(i,"cur_line_color",e.updateColor),e.refSocketXY?(Te(i,"apl_position",e.updateSocketXY),e.offset||(Te(i,"cur_attach_plugSideLenSE",e.updateSocketXY),Te(i,"cur_line_strokeWidth",e.updateSocketXY))):Te(i,"apl_path",e.updatePath),Te(i,"svgShow",e.updateShow),Z&&(Te(i,"new_edge4viewBox",e.adjustEdge),We(i,{}))},removeOption:function(e,t){var n=t.props,i={};i[t.optionName]="",Xe(n,i)},remove:function(e){e.boundTargets.length&&(console.error("LeaderLineAttachment was not unbound by remove"),e.boundTargets.forEach(function(t){n.captionLabel.unbind(e,t)}))}},pathLabel:{type:"label",argOptions:[{optionName:"text",type:"string"}],stats:{color:{},startOffset:{},pathData:{}},init:function(e,t){return"string"==typeof t.text&&(e.text=t.text.trim()),!!e.text&&("string"==typeof t.color&&(e.color=t.color.trim()),e.outlineColor="string"==typeof t.outlineColor?t.outlineColor.trim():"#fff",ee(t.lineOffset)&&(e.lineOffset=t.lineOffset),n.captionLabel.textStyleProps.forEach(function(n){null!=t[n]&&(e[n]=t[n])}),e.updateColor=function(t){n.captionLabel.updateColor(e,t)},e.updatePath=function(t){var i,r=e.curStats,o=e.aplStats,a=t.curStats,s=t.pathList.animVal||t.pathList.baseVal;s&&(r.pathData=i=n.pathLabel.getOffsetPathData(s,a.line_strokeWidth/2+e.strokeWidth/2+e.height/4,1.25*e.height),Se(i,o.pathData)&&(e.elmPath.setPathData(i),o.pathData=i,e.bBox=e.elmPosition.getBBox(),e.updateStartOffset(t)))},e.updateStartOffset=function(t){var n,i,r,o,a=e.curStats,s=e.aplStats,l=t.curStats;a.pathData&&(2!==e.semIndex||e.lineOffset)&&(n=a.pathData.reduce(function(e,t){var n,i=t.values;switch(t.type){case"M":o={x:i[0],y:i[1]};break;case"L":n={x:i[0],y:i[1]},o&&(e+=ye(o,n)),o=n;break;case"C":n={x:i[4],y:i[5]},o&&(e+=be(o,{x:i[0],y:i[1]},{x:i[2],y:i[3]},n)),o=n}return e},0),r=0===e.semIndex?0:1===e.semIndex?n:n/2,2!==e.semIndex&&(i=Math.max(l.attach_plugBackLenSE[e.semIndex]||0,l.line_strokeWidth/2)+e.strokeWidth/2+e.height/4,r=(r+=0===e.semIndex?i:-i)<0?0:nt?((r=i.points)[1]=Ie(r[0],r[1],-t),i.len=ye(r[0],r[1])):(i.points=null,i.len=0),e.len>t+n?((r=e.points)[0]=Ie(r[1],r[0],-(t+n)),e.len=ye(r[0],r[1])):(e.points=null,e.len=0)),i=e):i=null}),a.reduce(function(e,t){var n=t.points;return n&&(r&&s(n[0],r)||e.push({type:"M",values:[n[0].x,n[0].y]}),"line"===t.type?e.push({type:"L",values:[n[1].x,n[1].y]}):(n.shift(),n.forEach(function(t){e.push({type:"L",values:[t.x,t.y]})})),r=n[n.length-1]),e},[])},newText:function(e,t,n,i){var r,o,a,s,c,u,d,h,f,p;return(s=(a=t.createElementNS(G,"defs")).appendChild(t.createElementNS(G,"path"))).id=r=n+"-path",(u=(c=t.createElementNS(G,"text")).appendChild(t.createElementNS(G,"textPath"))).href.baseVal="#"+r,u.startOffset.baseVal.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PX,0),u.textContent=e,"boolean"!=typeof l&&(l="paintOrder"in c.style),i&&!l?(c.id=o=n+"-text",a.appendChild(c),(f=(d=t.createElementNS(G,"g")).appendChild(t.createElementNS(G,"use"))).href.baseVal="#"+o,(h=d.appendChild(t.createElementNS(G,"use"))).href.baseVal="#"+o,(p=f.style).strokeLinejoin="round",{elmPosition:c,elmPath:s,elmOffset:u,styleText:c.style,styleFill:h.style,styleStroke:p,styleShow:d.style,elmsAppend:[a,d]}):(p=c.style,i&&(p.strokeLinejoin="round",p.paintOrder="stroke"),{elmPosition:c,elmPath:s,elmOffset:u,styleText:p,styleFill:p,styleStroke:i?p:null,styleShow:p,elmsAppend:[a,c]})},initSvg:function(e,t){var i,r,o=n.pathLabel.newText(e.text,t.baseWindow.document,f+"-pathLabel-"+e._id,e.outlineColor);["elmPosition","elmPath","elmOffset","styleFill","styleShow","elmsAppend"].forEach(function(t){e[t]=o[t]}),e.isShown=!1,e.styleShow.visibility="hidden",n.captionLabel.textStyleProps.forEach(function(t){null!=e[t]&&(o.styleText[t]=e[t])}),o.elmsAppend.forEach(function(e){t.svg.appendChild(e)}),o.elmPath.setPathData([{type:"M",values:[0,100]},{type:"h",values:[100]}]),i=o.elmPosition.getBBox(),o.styleText.textAnchor=["start","end","middle"][e.semIndex],2!==e.semIndex||e.lineOffset||o.elmOffset.startOffset.baseVal.newValueSpecifiedUnits(SVGLength.SVG_LENGTHTYPE_PERCENTAGE,50),e.height=i.height,e.outlineColor&&(r=10<(r=i.height/9)?10:r<2?2:r,o.styleStroke.strokeWidth=r+"px",o.styleStroke.stroke=e.outlineColor),e.strokeWidth=r||0,De(e.aplStats,n.pathLabel.stats),e.updateColor(t),e.updatePath(t),e.updateStartOffset(t),Z&&We(t,{}),e.updateShow(t)},bind:function(e,t){var i=t.props;return e.color||ke(i,"cur_line_color",e.updateColor),ke(i,"cur_line_strokeWidth",e.updatePath),ke(i,"apl_path",e.updatePath),e.semIndex="startLabel"===t.optionName?0:"endLabel"===t.optionName?1:2,(2!==e.semIndex||e.lineOffset)&&ke(i,"cur_attach_plugBackLenSE",e.updateStartOffset),ke(i,"svgShow",e.updateShow),Z&&ke(i,"new_edge4viewBox",e.adjustEdge),n.pathLabel.initSvg(e,i),!0},unbind:function(e,t){var i=t.props;e.elmsAppend&&(e.elmsAppend.forEach(function(e){i.svg.removeChild(e)}),e.elmPosition=e.elmPath=e.elmOffset=e.styleFill=e.styleShow=e.elmsAppend=null),De(e.curStats,n.pathLabel.stats),De(e.aplStats,n.pathLabel.stats),e.color||Te(i,"cur_line_color",e.updateColor),Te(i,"cur_line_strokeWidth",e.updatePath),Te(i,"apl_path",e.updatePath),(2!==e.semIndex||e.lineOffset)&&Te(i,"cur_attach_plugBackLenSE",e.updateStartOffset),Te(i,"svgShow",e.updateShow),Z&&(Te(i,"new_edge4viewBox",e.adjustEdge),We(i,{}))},removeOption:function(e,t){var n=t.props,i={};i[t.optionName]="",Xe(n,i)},remove:function(e){e.boundTargets.length&&(console.error("LeaderLineAttachment was not unbound by remove"),e.boundTargets.forEach(function(t){n.pathLabel.unbind(e,t)}))}}},Object.keys(n).forEach(function(e){Ye[e]=function(){return new i(n[e],Array.prototype.slice.call(arguments))}}),Ye.positionByWindowResize=!0,window.addEventListener("resize",ie.add(function(){Ye.positionByWindowResize&&Object.keys(le).forEach(function(e){We(le[e],{position:!0})})}),!1),Ye}(),PlainOverlay=function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=3)}([function(e,t){e.exports=".plainoverlay,.plainoverlay:not(.plainoverlay-hide) .plainoverlay-builtin-face_01{-webkit-tap-highlight-color:rgba(0,0,0,0);transform:translateZ(0);box-shadow:0 0 1px rgba(0,0,0,0)}.plainoverlay{position:absolute;left:0;top:0;overflow:hidden;background-color:rgba(136,136,136,0.6);cursor:wait;z-index:9000;-webkit-transition-property:opacity;-moz-transition-property:opacity;-o-transition-property:opacity;transition-property:opacity;-webkit-transition-duration:200ms;-moz-transition-duration:200ms;-o-transition-duration:200ms;transition-duration:200ms;-webkit-transition-timing-function:linear;-moz-transition-timing-function:linear;-o-transition-timing-function:linear;transition-timing-function:linear;opacity:0}.plainoverlay.plainoverlay-show{opacity:1}.plainoverlay.plainoverlay-force{-webkit-transition-property:none;-moz-transition-property:none;-o-transition-property:none;transition-property:none}.plainoverlay.plainoverlay-hide{display:none}.plainoverlay.plainoverlay-doc{position:fixed;left:-200px;top:-200px;overflow:visible;padding:200px;width:100vw;height:100vh}.plainoverlay-body{width:100%;height:100%;display:-webkit-flex;display:flex;-webkit-justify-content:center;justify-content:center;-webkit-align-items:center;align-items:center}.plainoverlay.plainoverlay-doc .plainoverlay-body{width:100vw;height:100vh}.plainoverlay-builtin-face{width:90%;height:90%;max-width:320px;max-height:320px}#plainoverlay-builtin-face-defs{width:0;height:0;position:fixed;left:-100px;top:-100px}#plainoverlay-builtin-face_01 circle,#plainoverlay-builtin-face_01 path{fill:none;stroke-width:40px}#plainoverlay-builtin-face_01 circle{stroke:#fff;opacity:0.25}#plainoverlay-builtin-face_01 path{stroke-linecap:round}.plainoverlay:not(.plainoverlay-hide) .plainoverlay-builtin-face_01{-webkit-animation-name:plainoverlay-builtin-face_01-spin;-moz-animation-name:plainoverlay-builtin-face_01-spin;-ms-animation-name:plainoverlay-builtin-face_01-spin;-o-animation-name:plainoverlay-builtin-face_01-spin;animation-name:plainoverlay-builtin-face_01-spin;-webkit-animation-duration:1s;-moz-animation-duration:1s;-ms-animation-duration:1s;-o-animation-duration:1s;animation-duration:1s;-webkit-animation-timing-function:linear;-moz-animation-timing-function:linear;-ms-animation-timing-function:linear;-o-animation-timing-function:linear;animation-timing-function:linear;-webkit-animation-iteration-count:infinite;-moz-animation-iteration-count:infinite;-ms-animation-iteration-count:infinite;-o-animation-iteration-count:infinite;animation-iteration-count:infinite}@-moz-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-o-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@-ms-keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}@keyframes plainoverlay-builtin-face_01-spin{from{-webkit-transform:rotate(0deg);-moz-transform:rotate(0deg);-ms-transform:rotate(0deg);-o-transform:rotate(0deg);transform:rotate(0deg)}to{-webkit-transform:rotate(360deg);-moz-transform:rotate(360deg);-ms-transform:rotate(360deg);-o-transform:rotate(360deg);transform:rotate(360deg)}}"},function(e,t){e.exports=''},function(e,t){e.exports=''},function(e,t,n){"use strict";function i(e){return e.substr(0,1).toUpperCase()+e.substr(1)}n.r(t);var r=["webkit","moz","ms","o"],o=r.reduce(function(e,t){return e.push(t),e.push(i(t)),e},[]),a=r.map(function(e){return"-"+e+"-"}),s=function(){var e=void 0;return function(){return e=e||document.createElement("div").style}}(),l=function(){var e=new RegExp("^(?:"+r.join("|")+")(.)","i"),t=/[A-Z]/;return function(n){return"float"===(n=(n+"").replace(/\s/g,"").replace(/-([\da-z])/gi,function(e,t){return t.toUpperCase()}).replace(e,function(e,n){return t.test(n)?n.toLowerCase():e})).toLowerCase()?"cssFloat":n}}(),c=function(){var e=new RegExp("^(?:"+a.join("|")+")","i");return function(t){return(null!=t?t+"":"").replace(/\s/g,"").replace(e,"")}}(),u=function(e,t){var n=s();return e=e.replace(/[A-Z]/g,function(e){return"-"+e.toLowerCase()}),n.setProperty(e,t),null!=n[e]&&n.getPropertyValue(e)===t},d={},h={};function f(e){if((e=l(e))&&null==d[e]){var t=s();if(null!=t[e])d[e]=e;else{var n=i(e);o.some(function(i){var r=i+n;return null!=t[r]&&(d[e]=r,!0)})||(d[e]=!1)}}return d[e]||void 0}var p={getName:f,getValue:function(e,t){var n=void 0;return(e=f(e))?(h[e]=h[e]||{},(Array.isArray(t)?t:[t]).some(function(t){return t=c(t),null!=h[e][t]?!1!==h[e][t]&&(n=h[e][t],!0):u(e,t)?(n=h[e][t]=t,!0):!!a.some(function(i){var r=i+t;return!!u(e,r)&&(n=h[e][t]=r,!0)})||(h[e][t]=!1,!1)}),"string"==typeof n?n:void 0):n}},g=500,m=[],v=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||function(e){return setTimeout(e,1e3/60)},C=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame||window.msCancelAnimationFrame||function(e){return clearTimeout(e)},y=Date.now(),A=void 0;function I(){var e=void 0,t=void 0;A&&(C.call(window,A),A=null),m.forEach(function(t){var n;(n=t.event)&&(t.event=null,t.listener(n),e=!0)}),e?(y=Date.now(),t=!0):Date.now()-y-1&&(m.splice(t,1),!m.length&&A&&(C.call(window,A),A=null))}};function w(e){return(e+"").trim()}function x(e,t){t.setAttribute("class",e.join(" "))}function E(e){return!E.ignoreNative&&e.classList||(t=(e.getAttribute("class")||"").trim().split(/\s+/).filter(function(e){return!!e}),n={length:t.length,item:function(e){return t[e]},contains:function(e){return-1!==t.indexOf(w(e))},add:function(){return function(e,t,n){n.filter(function(t){return!(!(t=w(t))||-1!==e.indexOf(t)||(e.push(t),0))}).length&&x(e,t)}(t,e,Array.prototype.slice.call(arguments)),E.methodChain?n:void 0},remove:function(){return function(e,t,n){n.filter(function(t){var n=void 0;return!(!(t=w(t))||-1===(n=e.indexOf(t))||(e.splice(n,1),0))}).length&&x(e,t)}(t,e,Array.prototype.slice.call(arguments)),E.methodChain?n:void 0},toggle:function(n,i){return function(e,t,n,i){var r=e.indexOf(n=w(n));return-1!==r?!!i||(e.splice(r,1),x(e,t),!1):!1!==i&&(e.push(n),x(e,t),!0)}(t,e,n,i)},replace:function(i,r){return function(e,t,n,i){var r=void 0;(n=w(n))&&(i=w(i))&&n!==i&&-1!==(r=e.indexOf(n))&&(e.splice(r,1),-1===e.indexOf(i)&&e.push(i),x(e,t))}(t,e,i,r),E.methodChain?n:void 0}});var t,n}E.methodChain=!0;var S=E,k=function(){function e(e,t){for(var n=0;n0?e.timer=setTimeout(function(){j(e)},t):j(e)}}function G(e){clearTimeout(e.timer),e.state!==T&&(e.state=T,z(e,D))}function X(e,t){var n=e.options;function i(n){var i="number"==typeof t[n]?(e.window.getComputedStyle(e.element,"")[p.getName("transition-"+n)]||"").split(",")[t[n]]:t[n];return"string"==typeof i?i.trim():null}"string"==typeof t.pseudoElement&&(n.pseudoElement=t.pseudoElement);var r=i("property");"string"==typeof r&&"all"!==r&&"none"!==r&&(n.property=r),["duration","delay"].forEach(function(t){var r=i(t);if("string"==typeof r){var o=void 0,a=void 0;/^[0.]+$/.test(r)?(n[t]="0s",e[t]=0):(o=/^(.+?)(m)?s$/.exec(r))&&B(a=parseFloat(o[1]))&&("duration"!==t||a>=0)&&(n[t]=""+a+(o[2]||"")+"s",e[t]=a*(o[2]?1:1e3))}}),["procToOn","procToOff"].forEach(function(e){"function"==typeof t[e]?n[e]=t[e]:t.hasOwnProperty(e)&&null==t[e]&&(n[e]=void 0)})}var Y=function(){function e(t,n,i){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var r={ins:this,options:{pseudoElement:"",property:""},duration:0,delay:0,isOn:!!i};if(Object.defineProperty(this,"_id",{value:++U}),r._id=this._id,F[this._id]=r,!t.nodeType||t.nodeType!==Node.ELEMENT_NODE)throw new Error("This `element` is not accepted.");r.element=t,n||(n={}),r.window=t.ownerDocument.defaultView||n.window||window,n.hasOwnProperty("property")||(n.property=0),n.hasOwnProperty("duration")||(n.duration=0),n.hasOwnProperty("delay")||(n.delay=0),X(r,n),H(r)}return k(e,[{key:"remove",value:function(){var e=F[this._id];clearTimeout(e.timer),delete F[this._id]}},{key:"setOptions",value:function(e){return e&&X(F[this._id],e),this}},{key:"on",value:function(e,t){return arguments.length<2&&"boolean"!=typeof e&&(t=e,e=!1),this.setOptions(t),function(e,t,n){e.isOn&&e.state===T||e.isOn&&e.state!==T&&!t||(e.options.procToOn&&(n.unshift(!!t),e.options.procToOn.apply(e.ins,n)),t||!e.isOn&&e.state===L||-e.delay>e.duration?(G(e),e.isOn=!0,H(e)):(W(e),G(e),e.state=L,e.isOn=!0,e.runTime=Date.now(),e.startTime=0,z(e,O),e.delay>0?e.timer=setTimeout(function(){V(e)},e.delay):(e.delay<0&&(e.currentPosition=Math.min(e.currentPosition-e.delay,e.duration)),V(e))))}(F[this._id],e,Array.prototype.slice.call(arguments,2)),this}},{key:"off",value:function(e,t){return arguments.length<2&&"boolean"!=typeof e&&(t=e,e=!1),this.setOptions(t),function(e,t,n){!e.isOn&&e.state===T||!e.isOn&&e.state!==T&&!t||(e.options.procToOff&&(n.unshift(!!t),e.options.procToOff.apply(e.ins,n)),t||e.isOn&&e.state===L||-e.delay>e.duration?(G(e),e.isOn=!1,H(e)):(W(e),G(e),e.state=L,e.isOn=!1,e.runTime=Date.now(),e.startTime=0,z(e,O),e.delay>0?e.timer=setTimeout(function(){V(e)},e.delay):(e.delay<0&&(e.currentPosition=Math.max(e.currentPosition+e.delay,0)),V(e))))}(F[this._id],e,Array.prototype.slice.call(arguments,2)),this}},{key:"state",get:function(){return F[this._id].state}},{key:"element",get:function(){return F[this._id].element}},{key:"isReversing",get:function(){return F[this._id].isReversing}},{key:"pseudoElement",get:function(){return F[this._id].options.pseudoElement},set:function(e){X(F[this._id],{pseudoElement:e})}},{key:"property",get:function(){return F[this._id].options.property},set:function(e){X(F[this._id],{property:e})}},{key:"duration",get:function(){return F[this._id].options.duration},set:function(e){X(F[this._id],{duration:e})}},{key:"delay",get:function(){return F[this._id].options.delay},set:function(e){X(F[this._id],{delay:e})}},{key:"procToOn",get:function(){return F[this._id].options.procToOn},set:function(e){X(F[this._id],{procToOn:e})}},{key:"procToOff",get:function(){return F[this._id].options.procToOff},set:function(e){X(F[this._id],{procToOff:e})}}],[{key:"STATE_STOPPED",get:function(){return T}},{key:"STATE_DELAYING",get:function(){return L}},{key:"STATE_PLAYING",get:function(){return M}}]),e}(),q=n(0),K=n.n(q),Z=n(1),$=n.n(Z),Q=n(2),J=n.n(Q),ee=function(){function e(e,t){for(var n=0;n0)return!1}return!0}(e.elmOverlayBody,t):!t.containsNode||ye&&t.isCollapsed?function(e,t,n){var i=t.ownerDocument.createRange(),r=e.rangeCount;i.selectNodeContents(t);for(var o=0;o=0&&a.compareBoundaryPoints(Range.END_TO_START,i)<=0)return!0}return!1}(t,e.elmTargetBody):t.containsNode(e.elmTargetBody,!0))){try{t.removeAllRanges()}catch(e){}if(e.document.body.focus(),t.rangeCount>0)try{t.removeAllRanges()}catch(e){}return!0}return!1}function Pe(e){var t=e.elmTarget,n=e.elmTargetBody,i=n.getBoundingClientRect(),r=Te(e),o=-r.width,a=-r.height;if(we(t,{overflow:"hidden"},e.savedStyleTarget),o+=(r=Te(e)).width,a+=r.height,o||a){var s=e.window.getComputedStyle(n,""),l=void 0,c=void 0;if(ve||me){var u=s.writingMode||s["writing-mode"],d=s.direction;o&&(l=function(e,t){var n="rl-tb"===u||"tb-rl"===u||"bt-rl"===u||"rl-bt"===u;return ve&&n||me&&(n||"rtl"===d&&("horizontal-tb"===u||"vertical-rl"===u)||"ltr"===d&&"vertical-rl"===u)}()?"marginLeft":"marginRight"),a&&(c=function(e,t){var n="bt-rl"===u||"bt-lr"===u||"lr-bt"===u||"rl-bt"===u;return ve&&n||me&&(n||"rtl"===d&&("vertical-lr"===u||"vertical-rl"===u))}()?"marginTop":"marginBottom")}else o&&(l="marginRight"),a&&(c="marginBottom");var h={};return o&&(h[l]=parseFloat(s[l])+o+"px"),a&&(h[c]=parseFloat(s[c])+a+"px"),we(n,h,e.savedStyleTargetBody),function(e,t,n){var i=e.elmTargetBody,r=i.getBoundingClientRect();if(!(Math.abs(r.width-t)0?c.width+"px":0,height:c.height>0?c.height+"px":0},e.savedStyleTargetBody);var u={};r=i.getBoundingClientRect(),Math.abs(r.width-t)>=ge&&(u.width=c.width-(r.width-t)+"px"),r.height!==n&&(u.height=c.height-(r.height-n)+"px"),we(i,u,e.savedStyleTargetBody)}}(e,i.width,i.height),Le(e,t),!0}return xe(t,e.savedStyleTarget,["overflow"]),!1}function Re(e,t){var n=e.elmTargetBody,i=e.window.getComputedStyle(n,""),r=e.elmOverlay,o=e.window.getComputedStyle(r,""),a=Ee(r,e.window),s=["Top","Right","Bottom","Left"].reduce(function(e,t){return e[t.toLowerCase()]=parseFloat(i["border"+t+"Width"]),e},{}),l=a.left-parseFloat(o.left),c=a.top-parseFloat(o.top),u={left:t.left-l+s.left+"px",top:t.top-c+s.top+"px",width:t.width-s.left-s.right+"px",height:t.height-s.top-s.bottom+"px"},d=/^([\d.]+)(px|%)$/;[{prop:"TopLeft",hBorder:"left",vBorder:"top"},{prop:"TopRight",hBorder:"right",vBorder:"top"},{prop:"BottomRight",hBorder:"right",vBorder:"bottom"},{prop:"BottomLeft",hBorder:"left",vBorder:"bottom"}].forEach(function(e){var n=p.getName("border"+e.prop+"Radius"),r=i[n].split(" "),o=r[0],a=r[1]||r[0],l=d.exec(o);o=l?"px"===l[2]?+l[1]:l[1]*t.width/100:0,a=(l=d.exec(a))?"px"===l[2]?+l[1]:l[1]*t.height/100:0,o-=s[e.hBorder],a-=s[e.vBorder],o>0&&a>0&&(u[n]=o+"px "+a+"px")}),we(r,u),e.targetBodyBBox=t}function De(e){var t=e.elmTargetBody,n=e.elmOverlay,i=[e.elmTarget];return e.isDoc?(i.push(t),Array.prototype.slice.call(t.childNodes).forEach(function(e){e.nodeType!==Node.ELEMENT_NODE||e===n||S(e).contains(ie)||e.id===ce||(i.push(e),Array.prototype.push.apply(i,e.querySelectorAll("*")))})):Array.prototype.push.apply(i,t.querySelectorAll("*")),i}function Ne(e){if(e.filterElements=null,!1!==e.options.blur){var t=p.getName("filter"),n=p.getValue("filter","blur("+e.options.blur+"px)");if(n){var i=e.isDoc?Array.prototype.slice.call(e.elmTargetBody.childNodes).filter(function(t){return t.nodeType===Node.ELEMENT_NODE&&t!==e.elmOverlay&&!S(t).contains(ie)&&t.id!==ce}).map(function(e){return{element:e,savedStyle:{}}}):[{element:e.elmTargetBody,savedStyle:{}}];i.forEach(function(e){var i={};i[t]=n,we(e.element,i,e.savedStyle)}),e.filterElements=i}}e.state=he,e.options.onShow&&e.options.onShow.call(e.ins)}function Be(e){if(S(e.elmOverlay).add(ae),xe(e.elmTarget,e.savedStyleTarget),xe(e.elmTargetBody,e.savedStyleTargetBody),e.savedStyleTarget={},e.savedStyleTargetBody={},function(e){e.savedElementsAccKeys.forEach(function(e){try{!1===e.tabIndex?e.element.removeAttribute("tabindex"):null!=e.tabIndex&&(e.element.tabIndex=e.tabIndex)}catch(e){}try{e.accessKey&&(e.element.accessKey=e.accessKey)}catch(e){}})}(e),e.savedElementsAccKeys=[],e.isDoc&&e.activeElement){var t=e.state;e.state=ue,e.elmTargetBody.removeEventListener("focus",e.focusListener,!0),e.activeElement.focus(),e.state=t}e.activeElement=null,e.timerRestoreAndFinish&&(clearTimeout(e.timerRestoreAndFinish),e.timerRestoreAndFinish=null),e.timerRestoreAndFinish=setTimeout(function(){e.timerRestoreAndFinish=null,e.state=ue,e.elmTargetBody.addEventListener("focus",e.focusListener,!0),Le(e),e.savedElementsScroll=null,e.options.onHide&&e.options.onHide.call(e.ins)},0)}function Fe(e,t){var n=e.options;if(t.hasOwnProperty("face")&&(null==t.face?void 0:t.face)!==n.face){for(var i=e.elmOverlayBody;i.firstChild;)i.removeChild(i.firstChild);if(!1===t.face)n.face=!1;else if(t.face&&t.face.nodeType===Node.ELEMENT_NODE)n.face=t.face,i.appendChild(t.face);else if(null==t.face){var r=e.document;if(!r.getElementById(ce)){var o=(new e.window.DOMParser).parseFromString($.a,"image/svg+xml");r.body.appendChild(o.documentElement)}n.face=void 0,i.innerHTML=J.a}}Ie(t.duration)&&t.duration!==n.duration&&(n.duration=t.duration,e.elmOverlay.style[p.getName("transitionDuration")]=t.duration===pe?"":t.duration+"ms",e.transition.duration=t.duration+"ms"),(Ie(t.blur)||!1===t.blur)&&(n.blur=t.blur),Ae(t.style)&&we(e.elmOverlay,t.style),["onShow","onHide","onBeforeShow","onBeforeHide","onPosition"].forEach(function(e){"function"==typeof t[e]?n[e]=t[e]:t.hasOwnProperty(e)&&null==t[e]&&(n[e]=void 0)})}function Ue(e,t,n,i){var r=void 0,o=void 0;if(t){if(-1===De(e).indexOf(t))return o;r="html"===t.nodeName.toLowerCase()}else t=e.elmTarget,r=e.isDoc;var a=null!=i&&e.savedElementsScroll&&(e.savedElementsScroll.find?e.savedElementsScroll.find(function(e){return e.element===t}):function(n){var i=void 0;return e.savedElementsScroll.some(function(e){return e.element===t&&(i=e,!0)}),i}());return o=(n?Se:ke)(t,r,e.window,i),a&&(a[n?"left":"top"]=o),o}var ze=function(){function e(t,n){function i(e){var t=void 0;if(e)if(e.nodeType){if(e.nodeType===Node.DOCUMENT_NODE)t=e.documentElement;else if(e.nodeType===Node.ELEMENT_NODE){var n=e.nodeName.toLowerCase();t="body"===n?e.ownerDocument.documentElement:"iframe"===n||"frame"===n?e.contentDocument.documentElement:e}if(!t)throw new Error("This element is not accepted.")}else e===e.window&&(t=e.document.documentElement);else t=document.documentElement;return t}!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e);var r={ins:this,options:{face:!1,duration:pe,blur:!1},state:ue,savedStyleTarget:{},savedStyleTargetBody:{},blockingDisabled:!1};if(Object.defineProperty(this,"_id",{value:++be}),r._id=this._id,_e[this._id]=r,1===arguments.length){if(!(r.elmTarget=i(t))){if(!Ae(t))throw new Error("Invalid argument.");r.elmTarget=document.documentElement,n=t}}else if(!(r.elmTarget=i(t)))throw new Error("This target is not accepted.");if(n){if(!Ae(n))throw new Error("Invalid options.")}else n={};r.isDoc="html"===r.elmTarget.nodeName.toLowerCase();var o=r.document=r.elmTarget.ownerDocument;r.window=o.defaultView;var a=r.elmTargetBody=r.isDoc?o.body:r.elmTarget;if(!o.getElementById(ne)){var s=o.getElementsByTagName("head")[0]||o.documentElement,l=s.insertBefore(o.createElement("style"),s.firstChild);l.type="text/css",l.id=ne,l.textContent=K.a,(ve||me)&&function(e){setTimeout(function(){var t=e.parentNode,n=e.nextSibling;t.insertBefore(t.removeChild(e),n)},0)}(l)}var c=r.elmOverlay=o.createElement("div"),u=S(c);u.add(ie,ae),r.isDoc&&u.add(re),r.transition=new Y(c,{procToOn:function(e){var t=S(c);t.toggle(se,!!e),t.add(oe)},procToOff:function(e){var t=S(c);t.toggle(se,!!e),t.remove(oe)},property:"opacity",duration:pe+"ms"}),c.addEventListener("timedTransitionEnd",function(e){e.target===c&&"opacity"===e.propertyName&&(r.state===de?Ne(r):r.state===fe&&Be(r))},!0),(r.isDoc?r.window:a).addEventListener("scroll",function(e){var t=e.target;r.state!==ue&&!r.blockingDisabled&&Le(r,!r.isDoc||t!==r.window&&t!==r.document&&t!==r.elmTargetBody?t:r.elmTarget)&&(e.preventDefault(),e.stopImmediatePropagation())},!0),r.focusListener=function(e){r.state!==ue&&!r.blockingDisabled&&Me(r,e.target)&&(e.preventDefault(),e.stopImmediatePropagation())},a.addEventListener("focus",r.focusListener,!0),function(e){["keyup","mouseup"].forEach(function(t){r.window.addEventListener(t,e,!0)})}(function(e){r.state!==ue&&!r.blockingDisabled&&Oe(r)&&(e.preventDefault(),e.stopImmediatePropagation())}),r.resizing=!1,r.window.addEventListener("resize",b.add(function(){if(!r.resizing){if(r.resizing=!0,r.state!==ue){if(r.isDoc)r.savedElementsScroll.length&&r.savedElementsScroll[0].isDoc&&(r.disabledDocBars&&(xe(r.elmTarget,r.savedStyleTarget,["overflow"]),xe(a,r.savedStyleTargetBody,["marginLeft","marginRight","marginTop","marginBottom","width","height"])),r.disabledDocBars=Pe(r));else{var e=Ee(a,r.window),t=r.targetBodyBBox;e.left===t.left&&e.top===t.top&&e.width===t.width&&e.height===t.height||Re(r,e)}r.options.onPosition&&r.options.onPosition.call(r.ins)}r.resizing=!1}}),!0),c.addEventListener("touchmove",function(e){r.state!==ue&&(e.preventDefault(),e.stopImmediatePropagation())},!0),(r.elmOverlayBody=c.appendChild(o.createElement("div"))).className=le,o.body.appendChild(c),n.hasOwnProperty("face")||(n.face=null),Fe(r,n)}return ee(e,[{key:"setOptions",value:function(e){return Ae(e)&&Fe(_e[this._id],e),this}},{key:"show",value:function(e,t){return arguments.length<2&&"boolean"!=typeof e&&(t=e,e=!1),this.setOptions(t),function(e,t){if(!(e.state===he||e.state===de&&!t||e.state!==de&&e.options.onBeforeShow&&!1===e.options.onBeforeShow.call(e.ins))){if(e.state===ue){var n=e.elmOverlay,i=S(n);e.document.body.appendChild(n);var r=De(e);if(i.remove(ae),!e.isDoc){var o=e.elmTargetBody;"inline"===e.window.getComputedStyle(o,"").display&&we(o,{display:"inline-block"},e.savedStyleTargetBody),Re(e,Ee(o,e.window))}e.savedElementsScroll=function(t,n){var i=[];return t.forEach(function(t,r){var o=n&&0===r;(function(t,n){var i=e.window.getComputedStyle(t,""),r=t.nodeName.toLowerCase();return"scroll"===i.overflow||"auto"===i.overflow||"scroll"===i.overflowX||"auto"===i.overflowX||"scroll"===i.overflowY||"auto"===i.overflowY||n&&("visible"===i.overflow||"visible"===i.overflowX||"visible"===i.overflowY)||!n&&("textarea"===r||"select"===r)})(t,o)&&i.push({element:t,isDoc:o,left:Se(t,o,e.window),top:ke(t,o,e.window)})}),i}(r,e.isDoc),e.disabledDocBars=!1,e.isDoc&&e.savedElementsScroll.length&&e.savedElementsScroll[0].isDoc&&(e.disabledDocBars=Pe(e)),e.savedElementsAccKeys=function(e,t){var n=[];return e.forEach(function(e,i){if(!t||0!==i){var r={},o=e.tabIndex;-1!==o&&(r.element=e,r.tabIndex=!!e.hasAttribute("tabindex")&&o,e.tabIndex=-1);var a=e.accessKey;a&&(r.element=e,r.accessKey=a,e.accessKey=""),r.element&&n.push(r)}}),n}(r,e.isDoc),e.activeElement=e.document.activeElement,e.activeElement&&Me(e,e.activeElement),Oe(e),n.offsetWidth,e.options.onPosition&&e.options.onPosition.call(e.ins)}e.transition.on(t),e.state=de,t&&Ne(e)}}(_e[this._id],e),this}},{key:"hide",value:function(e){return function(e,t){if(!(e.state===ue||e.state===fe&&!t||e.state!==fe&&e.options.onBeforeHide&&!1===e.options.onBeforeHide.call(e.ins))){e.filterElements&&(e.filterElements.forEach(function(e){xe(e.element,e.savedStyle)}),e.filterElements=null);var n=e.document.activeElement;n&&n!==n.ownerDocument.body&&e.elmOverlay.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_CONTAINED_BY&&(n.blur?n.blur():n.ownerDocument.body.focus()),e.transition.off(t),e.state=fe,t&&Be(e)}}(_e[this._id],e),this}},{key:"scrollLeft",value:function(e,t){return Ue(_e[this._id],t,!0,e)}},{key:"scrollTop",value:function(e,t){return Ue(_e[this._id],t,!1,e)}},{key:"position",value:function(){var e=_e[this._id];return e.state!==ue&&(e.isDoc||Re(e,Ee(e.elmTargetBody,e.window)),e.options.onPosition&&e.options.onPosition.call(e.ins)),this}},{key:"state",get:function(){return _e[this._id].state}},{key:"style",get:function(){return _e[this._id].elmOverlay.style}},{key:"blockingDisabled",get:function(){return _e[this._id].blockingDisabled},set:function(e){"boolean"==typeof e&&(_e[this._id].blockingDisabled=e)}},{key:"face",get:function(){return _e[this._id].options.face},set:function(e){Fe(_e[this._id],{face:e})}},{key:"duration",get:function(){return _e[this._id].options.duration},set:function(e){Fe(_e[this._id],{duration:e})}},{key:"blur",get:function(){return _e[this._id].options.blur},set:function(e){Fe(_e[this._id],{blur:e})}},{key:"onShow",get:function(){return _e[this._id].options.onShow},set:function(e){Fe(_e[this._id],{onShow:e})}},{key:"onHide",get:function(){return _e[this._id].options.onHide},set:function(e){Fe(_e[this._id],{onHide:e})}},{key:"onBeforeShow",get:function(){return _e[this._id].options.onBeforeShow},set:function(e){Fe(_e[this._id],{onBeforeShow:e})}},{key:"onBeforeHide",get:function(){return _e[this._id].options.onBeforeHide},set:function(e){Fe(_e[this._id],{onBeforeHide:e})}},{key:"onPosition",get:function(){return _e[this._id].options.onPosition},set:function(e){Fe(_e[this._id],{onPosition:e})}}],[{key:"show",value:function(t,n){return new e(t,n).show()}},{key:"STATE_HIDDEN",get:function(){return ue}},{key:"STATE_SHOWING",get:function(){return de}},{key:"STATE_SHOWN",get:function(){return he}},{key:"STATE_HIDING",get:function(){return fe}}]),e}();t.default=ze}]).default,ResizeThrottler=new function(){var e=[],t=null,n=function(){null===t&&(t=setTimeout(function(){t=null,e.forEach(function(e){e()})},125))},i=function(t){e.push(t)};this.initialize=function(e){window.addEventListener("resize",n,!1),e.forEach(function(e){i(e),e()})},this.add=function(e){i(e)}};window.onload=function(){"use strict";document.body.style.overflow="hidden";!function(e){var t={0:[0,0,0],10:[75,0,159],20:[104,0,251],30:[131,0,255],40:[155,18,157],50:[175,37,0],60:[191,59,0],70:[206,88,0],80:[223,132,0],90:[240,188,0],100:[255,252,0]},n=[],r=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"],o=[],a=function(e){return 69+12*Math.log2(e/440)},s=function(e,t){return Math.min(Math.abs(Math.round(64*(1-(e-t)))),127)},l=function(e,t){return Math.round(8192+49152*Math.log2(e/(n=t,440*Math.pow(2,(n-69)/12))));var n},c=function(e,t){return Math.random()*(t-e)+e},u=function(){return!!navigator.requestMIDIAccess},d=function(e){return 0==(e&e-1)},h=function(e){return parseInt(e,10)},f=function(e){var t=e.getBoundingClientRect(),n=document.body,i=document.documentElement,r=window.pageYOffset||i.scrollTop||n.scrollTop,o=window.pageXOffset||i.scrollLeft||n.scrollLeft,a=i.clientTop||n.clientTop||0,s=i.clientLeft||n.clientLeft||0,l=t.top+r-a,c=t.left+o-s;return{top:Math.round(l),left:Math.round(c),width:t.width,height:t.height}},p=function(e,t,n,i){var r=0,o=0,a=0,s=t,l=0,c=Math.min,u=0;for(i&&(u=-(t-1),c=Math.max,s=0),r=n-1;r>=0;r-=1)for(o=0;o0||e[a+1]>0){s=c(s,l);break}return s},g=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.onreadystatechange=function(){4==n.readyState&&200==n.status&&t(n.responseText)},n.send()},m=function(e,t){e&&(e.mozImageSmoothingEnabled=t,e.oImageSmoothingEnabled=t,e.msImageSmoothingEnabled=t,e.imageSmoothingEnabled=t)},v=function(e,t){var n=(+e).toFixed(t+1);return+n.slice(0,n.length-1)},C=function(e){return 440*Math.pow(2,(e-69)/12)},y=function(){var e=document.querySelector(":focus");e&&e.blur()},A=function(e,t){return function(){var n,i=document.createElement("canvas"),r=i.getContext("2d");i.width=e.naturalWidth,i.height=e.naturalHeight,r.drawImage(e,0,0,i.width,i.height),n=r.getImageData(0,0,i.width,i.height),t(n)}};!function(){var e,i,a,s,l,c,u,d=0;for(d=0;d<256;d+=1)o.push((a=void 0,s=void 0,l=100*d/255,c=10*Math.floor(l/10),u=(l-c)/10,a=l<100?[t[c+10][0]-t[c+10][0],t[c+10][1]-t[c+10][1],t[c+10][2]-t[c+10][2]]:[0,0,0],"rgb("+(s=[t[c][0]+u*a[0],t[c][1]+u*a[1],t[c][2]+u*a[2]])[0]+", "+s[1]+","+s[2]+")"));for(d=0;d<127;d+=1)i=r[(e=d)%12],i+=(e/12|0)-1,n[d]=i}();var I=document.getElementById("fs_utter_fail"),_=document.getElementById("fail"),b=document.getElementById("fs_notification"),w=function(e,t){e instanceof Element?(_.innerHTML="",_.appendChild(e),""!==b.innerHTML&&b.classList.add("fs-text-align-right")):_.innerHTML=e,t&&(document.body.innerHTML="",I.innerHTML=''+e,document.body.appendChild(I))},x=function(e,t){var n=document.createElement("div");n.innerHTML=e,void 0===t&&(t=1500),""!==_.innerHTML&&n.classList.add("fs-text-align-right"),b.appendChild(n),window.setTimeout(function(e){return function(){e.classList.add("fs-opacity-transition"),e.classList.add("fs-transparent"),window.setTimeout(function(e){return function(){e.parentElement.removeChild(e)}}(e),2e3)}}(n),t)};I.innerHTML="";var E=function(){var t;return e.session_name?e.session_name:(t=window.location.pathname.split("/"))[t.length-1]};if(window.performance=window.performance||{},performance.now=performance.now||performance.mozNow||performance.msNow||performance.oNow||performance.webkitNow||function(){return(new Date).getTime()},window.AudioContext=window.AudioContext||window.webkitAudioContext||!1,window.requestAnimationFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame,window.cancelAnimationFrame=window.cancelAnimationFrame||window.mozCancelAnimationFrame||window.webkitCancelAnimationFrame,window.AudioContext)if(window.cancelAnimationFrame)if(window.indexedDB||(window.indexedDB=window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB,window.indexedDB?window.indexedDB={open:function(){return null}}:x("The IndexedDB API is not available, imported data will not be saved.",1e4)),window.localStorage)if(window.FileReader)if(window.Blob)if(window.File)if("undefined"!=typeof Worker){var S=document.createElement("canvas"),k={preserveDrawingBuffer:!0,antialias:!0,depth:!1};if(S.getContext("webgl2",k)||S.getContext("experimental-webgl2",k)){var T,L,M,O,P,R,D,N,B,F,U,z,W,H,j,V,G,X,Y,q='
    WebMIDI API is not enabled/supported by this browser, please use a compatible browser.
    ',K=new showdown.Converter,Z=1,$="https://www.fsynth.com/documentation/",Q=localStorage.getItem("fs-user-name"),J=localStorage.getItem(E()),ee=Uint8Array,te=document.getElementById("fs_red_curtain"),ne=document.getElementById("fs_user_name"),ie=document.getElementById("fs_username_input"),re=document.getElementById("fs_time_infos"),oe=document.getElementById("fs_hz_infos"),ae=document.getElementById("fs_xy_infos"),se=document.getElementById("fs_osc_infos"),le=document.getElementById("fs_polyphony_infos"),ce=document.getElementById("fs_fas_stream_load"),ue=document.getElementById("fs_fas_stream_latency"),de=(document.getElementById("fs_synth_output"),document.getElementById("fs_haxis_infos")),he=document.getElementById("fs_vaxis_infos"),fe=document.getElementById("canvas_container"),pe=document.createElement("canvas"),ge=document.getElementById("fs_record_canvas"),me=ge.getContext("2d"),ve=0,Ce=!1,ye=[function(e,t){return dt[e][t]+gt[e][t]+ft[e][t]},function(e,t){return dt[e][t]},function(e,t){return gt[e][t]},function(e,t){return ft[e][t]}],Ae=1,Ie={default:function(e,t){return t},additive:function(e,t){return e+t},substractive:function(e,t){return e-t},multiply:function(e,t){return e*t},f:null},_e=document.getElementById("fs_helper_canvas"),be=_e.getContext("2d"),we=window.innerWidth<500?320:window.innerWidth<800?640:window.innerWidth<1280?800:1224,xe=window.innerHeight<=640?200:439,Ee=we-1,Se=4*xe,ke=(new Uint8Array(we*xe*4),xe),Te={enabled:!0,pframe:[],index:0,program:null,texture:null},Le=[{name:"main",container:document.getElementById("fs_code"),marks:[],editor:null,index:0,default_value:document.getElementById("fragment-shader").text,sharedb:{doc:null,rdy:!1},collaborative:!0,outline:{element:function(){var e=WUI_Dialog.getDetachedDialog(rr);return e?e.document.getElementById("fs_main_outline"):document.getElementById("fs_main_outline")},data:[]},detached_windows:[],line_widgets:[]},{name:"library",container:document.getElementById("fs_library_code"),marks:[],editor:null,index:1,default_value:localStorage.getItem("fs-user-library")?localStorage.getItem("fs-user-library"):"// my library",collaborative:!1,outline:{element:function(){var e=WUI_Dialog.getDetachedDialog(rr);return e?e.document.getElementById("fs_library_outline"):document.getElementById("fs_library_outline")},data:[]},detached_windows:[],line_widgets:[]},{name:"example",container:document.getElementById("fs_example_code"),marks:null,editor:null,index:2,default_value:"",collaborative:!1,outline:null,detached_windows:[],line_widgets:[]}],Me=Le[0],Oe=localStorage.getItem("fs-editor-font-size"),Pe=localStorage.getItem("fs-editor-theme"),Re={showToken:/\w/,annotateScrollbar:!0},De={value:"",theme:null===Pe?"seti":Pe,matchBrackets:!0,lineNumbers:!0,gutters:["CodeMirror-linenumbers","fs-mark"],styleActiveLine:!0,scrollbarStyle:"native",mode:"text/x-glsl",extraKeys:{F11:function(e){var t=!e.getOption("fullScreen");e.setOption("fullScreen",t);var n=document.getElementById("fs_middle_panel"),i=document.getElementById("fs_explorer"),r=document.getElementById("fs_top_panel"),o=0;if(t){Me.editor.setOption("lineNumbers",!1),n.style.display="none",r.style.display="none",i.style.display="none";var a=document.getElementsByClassName("fs-mark");for(o=0;o=Rt.length||e<0?null:Rt[e]}(e);return t?t.freq:null},Nt=function(){var e,t=0,n=0;for(t=0;t1?e.getChannelData(1).buffer:null,i={settings:JSON.parse(JSON.stringify(Ht)),left:t,right:n,sample_rate:Mt},r=[t];Ht.height<=0&&(i.settings.height=xe),Ht.minfreq<=0&&(i.settings.minfreq=Rt[Rt.length-1].freq),Ht.maxfreq<=0&&(i.settings.maxfreq=Rt[0].freq),n&&r.push(n),x("conversion in progress...",2e3),Wt.postMessage(i,r)},Vt=function(e){var t=new FileReader;t.onload=function(e){var t,n;t=e.target.result,n=jt,Lt.decodeAudioData(t,function(e){n(e)},function(e){x("An error occured while decoding the audio data "+e.err)})},t.onerror=function(t){var n=t.target.error;switch(n.code){case n.NOT_FOUND_ERR:x("File '"+e.name+" not found.");break;case n.NOT_READABLE_ERR:x("File '"+e.name+" not readable.");break;case n.ABORT_ERR:x("File '"+e.name+" operation was aborted.");break;case n.SECURITY_ERR:x("File '"+e.name+" is in a locked state.");break;case n.ENCODING_ERR:x("File '"+e.name+" encoding took too long.");break;default:x("File '"+e.name+" cannot be loaded.")}},t.onprogress=function(t){var n=0;t.lengthComputable&&(n=Math.round(100*t.loaded/t.total),x("loading '"+e.name+"' "+n+"%."))},t.readAsArrayBuffer(e)};Wt.addEventListener("message",function(e){if(e.data===Object(e.data)){var t={width:e.data.width,height:e.data.height,data:{buffer:e.data.pbuffer}};Ft(t,{flip:!1}),x("Audio file converted to "+t.width+"x"+t.height+"px image.")}else"string"==typeof e.data?x(e.data,1e4):x("Audio file conversion in progress : "+e.data+"%")},!1);var Gt=document.getElementById("fs_import_dropzone"),Xt=function(e){return function(t){if(void 0===t)return n=Xt(e),i=WUI_Dialog.getDetachedDialog(dr),(r=i?i.document.createElement("input"):document.createElement("input")).type="file",r.multiple=!0,r.addEventListener("change",n,!1),void r.click();var n,i,r,o,a=t.target,s=a.files,l=0;if(0!==s.length){for(l=0;l0)for(n=4*e.shift,t.copyWithin(n,0,Se-n),i=0;i0){for(rt&&(V.bindBuffer(V.PIXEL_PACK_BUFFER,ot),V.bufferData(V.PIXEL_PACK_BUFFER,at,V.STATIC_READ)),s=0;s0)for(a=ft[f],ft[mt+f]=t.midi_out,l=0;l0||gt[l][s+1]>0||dt[l][s]>0||dt[l][s+1]>0;A.push(I)}se.textContent=A.join(" ")}if(function(){var e,t,n=0,i=0,r=0,o=1;if(Ce){if(t=new Uint8ClampedArray(Se),G===V.FLOAT&&(o=255),0===Ae||1===Ae||2===Ae)for(n=0;nwe&&(ve=0)}}(),Os.enabled&&Os.out){var _=[];for(s=0;sCompilation errors
    \n',s=0;s"+n[s].line+": "+n[s].msg+"\n",i.appendChild(r);Je&&w(i),V.deleteShader(a),a=!1}return a},In=function(e){$t!==e&&(V.useProgram(e),$t=e)},_n=function(e,t){var n=Y;return gn[e]||(void 0!==t&&(n=t),gn[e]=V.getUniformLocation(n,e)),gn[e]},bn=function(e,t,n,i,r,o){var a=_n(i,n);"bool"===t||"int"===t||"uint"===t?e.uniform1iv(a,new Int32Array(r)):"float"===t?e.uniform1fv(a,new Float32Array(r)):"bvec"===t||"ivec"===t||"uvec"===t?2===o?e.uniform2iv(a,new Int32Array(r)):3===o?e.uniform3iv(a,new Int32Array(r)):4===o&&e.uniform4iv(a,new Int32Array(r)):"vec"===t&&(2===o?e.uniform2fv(a,new Float32Array(r)):3===o?e.uniform3fv(a,new Float32Array(r)):4===o&&r.length>0&&e.uniform4fv(a,new Float32Array(r)))},wn=function(){var e,t,n,i,r,o,a="",s=Le[2],l=Me===s?"":Le[1].editor.getValue(),c=Me===s?s.editor.getValue():Le[0].editor.getValue(),u=l+"\n"+c,d=0;for(rt?(a+="#version 300 es\nprecision mediump float;layout(location = 0) out vec4 synthOutput;layout(location = 1) out vec4 fragColor;",u=(u=u.replace(/gl_FragColor/g,"fragColor")).replace(/texture2D/g,"texture"),e="#version 300 es\n"+document.getElementById("vertex-shader-2").text):(a+="precision mediump float;",u=(u=(u=u.replace(/texture/g,"texture2D")).replace(/fragColor/g,"gl_FragColor")).replace(/synthOutput.*;/g,""),e=document.getElementById("vertex-shader").text),d=0;d1?"["+r.count+"]":"")+";";if(a+="\n"+u,o=yn(An(V.VERTEX_SHADER,e),An(V.FRAGMENT_SHADER,a))){for(i in Me.index<2&&(Cn(1,l),Cn(0,c)),V.deleteProgram(Y),Y=o,gn={},w(""),Ri(),In(Y),V.uniform2f(V.getUniformLocation(Y,"resolution"),pe.width,pe.height),bn(V,"vec",Y,"keyboard",Fe.data,Fe.data_components),Os.inputs)r=Os.inputs[i],bn(V,r.type,Y,i,r.data,r.comps);rt&&V.bindBuffer(V.ARRAY_BUFFER,X),t=V.getAttribLocation(Y,"position"),V.enableVertexAttribArray(t),V.vertexAttribPointer(t,2,V.FLOAT,!1,0,0),je&&(je=!1,0===Z&&Gi(!1))}else je=!0},xn=function(){clearTimeout(mn),mn=setTimeout(wn,nt)},En=function(e,t){return function(){Lr("fs-workspace-item",e.index)(),e.editor.setCursor({line:t.start.line-1,ch:t.start.column});var n=0;for(n=0;n'+i.type_name+" "+i.name);r.innerHTML=''+t.returnType.name+" "+t.name+" ("+n.join(", ")+")",r.title="line: "+t.position.start.line,l.appendChild(r),r.addEventListener("click",En(s,t.position))}else"declarator"===t.type?((r=document.createElement("div")).className="fs-outline-item fs-outline-declarator",r.innerHTML=''+t.returnType+" "+t.name,r.title="line: "+t.position.start.line,l.appendChild(r),r.addEventListener("click",En(s,t.position))):"preprocessor"===t.type&&((r=document.createElement("div")).className="fs-outline-item fs-outline-preprocessor",r.innerHTML=t.name+" = "+t.value,r.title="line: "+t.position.start.line,l.appendChild(r),r.addEventListener("click",En(s,t.position)));var u=null;for(o=0;oni?(ui(e,t,n,i,r,o,a,s,l),void(Jn=performance.now())):void 0;for(ii&&(s=c(0,s),o=c(0,o),a=c(0,a),l=c(0,l)),e.globalAlpha=l,u=t.naturalWidth*o/2,d=t.naturalHeight*a/2,ei&&(i=$n),ti&&(r=Qn),C=Qn-r,p=(v=$n-i)/(m=Math.abs(v)>Math.abs(C)?Math.abs(v):Math.abs(C)),g=C/m,$n=i,Qn=r,y=1;y<=m;y+=1)i+=p,r+=g,h=Math.round(i-u),f=Math.round(r-d),e.save(),e.globalCompositeOperation=1===n?"destination-out":oi,e.translate(i,r),e.rotate(s),e.translate(h-i,f-r),e.scale(o,a),e.drawImage(t,0,0),e.restore()}(e.canvas_ctx,ri,e.mouse_btn-2,t,n,ai,si,ci,li),mi(e))},Ci=null,yi=0,Ai=0,Ii=null,_i=null,bi=function(e,t,n){return function(i){n(i,e,t,this)}},wi=function(e){var t,n,i,r,o,a=document.createElement("div"),s=document.createElement("div"),l="fs_channel_settings_playrate"+yi,c="fs_channel_settings_videostart"+yi,u="fs_channel_settings_videoend"+yi,f=vt[e],p="200px",g="",m='',v='';a.id="fs_channel_settings_dialog"+yi,f.dialog_id=yi,rt||d(f.image.width)&&d(f.image.height)&&1!==f.type&&3!==f.type&&5!==f.type&&6!==f.type||(m="",v=""),1!==f.type&&2!==f.type&&3!==f.type&&4!==f.type&&5!==f.type&&6!==f.type&&404!==f.type||(g="display: none"),a.style.fontSize="13px",s.innerHTML='
    Filter:
     
    Wrap S:
     
    Wrap T:
     
     
    ',a.appendChild(s),document.body.appendChild(a),t=document.getElementById("fs_channel_filter"+e),n=document.getElementById("fs_channel_wrap_s"+e),i=document.getElementById("fs_channel_wrap_t"+e),r=document.getElementById("fs_channel_vflip"+e),3===f.type&&(p="340px",s.innerHTML+=' 
    ',WUI_RangeSlider.create(l,{width:120,height:8,min:0,max:1e4,bar:!1,midi:!0,step:.001,scroll_step:.01,default_value:f.playrate,value:f.playrate,decimals:3,title:"Playback rate",title_min_width:140,value_min_width:88,on_change:bi(f,e,function(e,t){t.video_elem.playbackRate=parseFloat(e),t.playrate=parseFloat(e)})}),WUI_RangeSlider.create(c,{width:120,height:8,min:0,max:1,bar:!1,midi:!0,step:1e-4,scroll_step:.001,default_value:f.videostart,value:f.videostart,decimals:4,title:"Video start",title_min_width:140,value_min_width:88,on_change:bi(f,e,function(e,t){var n=parseFloat(e);t.videostart!==n&&(t.videostart=n,t.video_elem.currentTime=t.video_elem.duration*n)})}),WUI_RangeSlider.create(u,{width:120,height:8,min:0,max:1,bar:!1,midi:!0,step:1e-4,scroll_step:.001,default_value:f.videoend,value:f.videoend,decimals:4,title:"Video end",title_min_width:140,value_min_width:88,on_change:bi(f,e,function(e,t){t.videoend=parseFloat(e)})})),V.bindTexture(V.TEXTURE_2D,f.texture),V.getTexParameter(V.TEXTURE_2D,V.TEXTURE_MAG_FILTER)===V.NEAREST?t.value="nearest":V.getTexParameter(V.TEXTURE_2D,V.TEXTURE_MIN_FILTER)===V.LINEAR_MIPMAP_NEAREST?t.value="mipmap":V.getTexParameter(V.TEXTURE_2D,V.TEXTURE_MAG_FILTER)===V.LINEAR&&(t.value="linear"),(o=V.getTexParameter(V.TEXTURE_2D,V.TEXTURE_WRAP_S))===V.CLAMP_TO_EDGE?n.value="clamp":o===V.REPEAT?n.value="repeat":o===V.MIRRORED_REPEAT&&(n.value="mirror"),(o=V.getTexParameter(V.TEXTURE_2D,V.TEXTURE_WRAP_T))===V.CLAMP_TO_EDGE?i.value="clamp":o===V.REPEAT?i.value="repeat":o===V.MIRRORED_REPEAT&&(i.value="mirror"),f.db_obj.settings.flip?r.checked=!0:r.checked=!1,r.addEventListener("change",bi(f,e,function(e,t,n,i){var r;t.db_obj.settings.flip=i.checked,t.db_obj.settings.flip?un(t.texture,t.image,function(e){t.texture=e,Tt(h(n),t.db_obj)}):(r=an(t.image,t.texture),t.texture=r,Tt(h(n),t.db_obj))})),t.addEventListener("change",bi(f,e,function(e,t,n,i){sn(t.texture,i.value),t.db_obj.settings.f=i.value,Tt(h(n),t.db_obj)})),n.addEventListener("change",bi(f,e,function(e,t,n,i){ln(t.texture,i.value),t.db_obj.settings.wrap.s=i.value,Tt(h(n),t.db_obj)})),i.addEventListener("change",bi(f,e,function(e,t,n,i){cn(t.texture,i.value),t.db_obj.settings.wrap.t=i.value,Tt(h(n),t.db_obj)})),WUI_Dialog.create(a.id,{title:"iInput"+e+" settings",width:"250px",height:p,halign:"center",valign:"center",open:!1,minimized:!1,modal:!1,status_bar:!1,closable:!0,draggable:!0,minimizable:!0,resizable:!1,detachable:!1,min_width:200,min_height:250,header_btn:[{title:"Help",on_click:function(){window.open($+"import/")},class_name:"fs-help-icon"}]}),yi+=1},xi=function(e,t){var n=new Worker("dist/worker/image_processor.min.js");n.onmessage=function(e){n.terminate(),t(e.data)},n.postMessage({img_width:e.width,img_height:e.height,buffer:e.data.buffer},[e.data.buffer])},Ei=function(e){return function(t){t.preventDefault(),WUI_Dialog.open("fs_channel_settings_dialog"+e)}},Si=function(e){e.preventDefault();var t=h(e.target.dataset.inputId),n=vt[t],i=n.elem,r=[{icon:"fs-cross-45-icon",tooltip:"Delete",on_click:function(){Ct.removeChild(i),Li(t),gi(t)}}];404!==n.type&&r.unshift({icon:"fs-gear-icon",tooltip:"Settings",on_click:function(){var e;e=vt[t],WUI_Dialog.open("fs_channel_settings_dialog"+e.dialog_id)}}),0===n.type&&r.push({icon:"fs-xyf-icon",tooltip:"View image",on_click:function(){window.open(i.src).document.write("")}}),2===n.type&&r.push({icon:"fs-brush-icon",tooltip:"Open draw tools & allow to draw",on_click:Ti}),3===n.type&&r.push({icon:"fs-reset-icon",tooltip:"Rewind",on_click:function(){NaN===n.video_elem.duration?n.video_elem.currentTime=0:n.video_elem.currentTime=n.video_elem.duration*n.videostart}}),4===n.type&&(r.push({icon:"fs-reset-icon",tooltip:"Rewind",on_click:function(){n.globalTime=0,Go(n)}}),r.push({icon:"fs-code-icon",tooltip:"Pjs code editor",on_click:ki})),Ii=e,WUI_CircularMenu.create({element:i,rx:32,ry:32,item_width:32,item_height:32},r)},ki=function(e){var t,n;e?e.preventDefault():e=Ii,t=h(e.target.dataset.inputId),n=vt[t],$o(n),WUI_Dialog.open("fs_pjs")},Ti=function(e){var t,n=null;e?e.preventDefault():e=Ii,t=h(e.target.dataset.inputId);var i,r=(n=vt[t]).elem,o=0;for(o=0;o=1&&o<=Le[1].editor.lineCount()&&Me!==Le[2]?r=Le[1]:Me!==Le[2]?(o-=Le[1].editor.lineCount(),r=Me):(o-=1,r=Me),a.push({target:r.name,line:o,msg:n[2]}),(Qe||r.editor.getOption("fullScreen"))&&r.line_widgets.push(r.editor.addLineWidget(o-1,t,{coverGutter:!1,noHScroll:!0}));return a},Ni=function(e){M&&document.getElementsByTagName("head")[0].removeChild(M),(M=document.createElement("link")).onload=function(){var t=0;for(t=0;t","","","Fragment - "+Me.name,"",'','','','