repo_id
stringlengths 6
101
| size
int64 367
5.14M
| file_path
stringlengths 2
269
| content
stringlengths 367
5.14M
|
---|---|---|---|
2881099/FreeSql.AdminLTE
| 196,532 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/inputmask/inputmask.js
|
/*!
* dist/inputmask
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2021 Robin Herbots
* Licensed under the MIT license
* Version: 5.0.7
*/
!function(e, t) {
if ("object" == typeof exports && "object" == typeof module) module.exports = t(); else if ("function" == typeof define && define.amd) define([], t); else {
var i = t();
for (var a in i) ("object" == typeof exports ? exports : e)[a] = i[a];
}
}(self, (function() {
return function() {
"use strict";
var e = {
8741: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var i = !("undefined" == typeof window || !window.document || !window.document.createElement);
t.default = i;
},
3976: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var a, n = (a = i(5581)) && a.__esModule ? a : {
default: a
};
var r = {
_maxTestPos: 500,
placeholder: "_",
optionalmarker: [ "[", "]" ],
quantifiermarker: [ "{", "}" ],
groupmarker: [ "(", ")" ],
alternatormarker: "|",
escapeChar: "\\",
mask: null,
regex: null,
oncomplete: function() {},
onincomplete: function() {},
oncleared: function() {},
repeat: 0,
greedy: !1,
autoUnmask: !1,
removeMaskOnSubmit: !1,
clearMaskOnLostFocus: !0,
insertMode: !0,
insertModeVisual: !0,
clearIncomplete: !1,
alias: null,
onKeyDown: function() {},
onBeforeMask: null,
onBeforePaste: function(e, t) {
return "function" == typeof t.onBeforeMask ? t.onBeforeMask.call(this, e, t) : e;
},
onBeforeWrite: null,
onUnMask: null,
showMaskOnFocus: !0,
showMaskOnHover: !0,
onKeyValidation: function() {},
skipOptionalPartCharacter: " ",
numericInput: !1,
rightAlign: !1,
undoOnEscape: !0,
radixPoint: "",
_radixDance: !1,
groupSeparator: "",
keepStatic: null,
positionCaretOnTab: !0,
tabThrough: !1,
supportsInputType: [ "text", "tel", "url", "password", "search" ],
ignorables: [ n.default.BACKSPACE, n.default.TAB, n.default["PAUSE/BREAK"], n.default.ESCAPE, n.default.PAGE_UP, n.default.PAGE_DOWN, n.default.END, n.default.HOME, n.default.LEFT, n.default.UP, n.default.RIGHT, n.default.DOWN, n.default.INSERT, n.default.DELETE, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 229 ],
isComplete: null,
preValidation: null,
postValidation: null,
staticDefinitionSymbol: void 0,
jitMasking: !1,
nullable: !0,
inputEventOnly: !1,
noValuePatching: !1,
positionCaretOnClick: "lvp",
casing: null,
inputmode: "text",
importDataAttributes: !0,
shiftPositions: !0,
usePrototypeDefinitions: !0,
validationEventTimeOut: 3e3,
substitutes: {}
};
t.default = r;
},
7392: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
t.default = {
9: {
validator: "[0-9\uff10-\uff19]",
definitionSymbol: "*"
},
a: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
definitionSymbol: "*"
},
"*": {
validator: "[0-9\uff10-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"
}
};
},
253: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = function(e, t, i) {
if (void 0 === i) return e.__data ? e.__data[t] : null;
e.__data = e.__data || {}, e.__data[t] = i;
};
},
3776: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.Event = void 0, t.off = function(e, t) {
var i, a;
function n(e, t, n) {
if (e in i == !0) if (a.removeEventListener ? a.removeEventListener(e, n, !1) : a.detachEvent && a.detachEvent("on" + e, n),
"global" === t) for (var r in i[e]) i[e][r].splice(i[e][r].indexOf(n), 1); else i[e][t].splice(i[e][t].indexOf(n), 1);
}
function r(e, a) {
var n, r, o = [];
if (e.length > 0) if (void 0 === t) for (n = 0, r = i[e][a].length; n < r; n++) o.push({
ev: e,
namespace: a && a.length > 0 ? a : "global",
handler: i[e][a][n]
}); else o.push({
ev: e,
namespace: a && a.length > 0 ? a : "global",
handler: t
}); else if (a.length > 0) for (var l in i) for (var s in i[l]) if (s === a) if (void 0 === t) for (n = 0,
r = i[l][s].length; n < r; n++) o.push({
ev: l,
namespace: s,
handler: i[l][s][n]
}); else o.push({
ev: l,
namespace: s,
handler: t
});
return o;
}
if (u(this[0]) && e) {
i = this[0].eventRegistry, a = this[0];
for (var o = e.split(" "), l = 0; l < o.length; l++) for (var s = o[l].split("."), c = r(s[0], s[1]), f = 0, d = c.length; f < d; f++) n(c[f].ev, c[f].namespace, c[f].handler);
}
return this;
}, t.on = function(e, t) {
function i(e, i) {
n.addEventListener ? n.addEventListener(e, t, !1) : n.attachEvent && n.attachEvent("on" + e, t),
a[e] = a[e] || {}, a[e][i] = a[e][i] || [], a[e][i].push(t);
}
if (u(this[0])) for (var a = this[0].eventRegistry, n = this[0], r = e.split(" "), o = 0; o < r.length; o++) {
var l = r[o].split("."), s = l[0], c = l[1] || "global";
i(s, c);
}
return this;
}, t.trigger = function(e) {
if (u(this[0])) for (var t = this[0].eventRegistry, i = this[0], a = "string" == typeof e ? e.split(" ") : [ e.type ], r = 0; r < a.length; r++) {
var l = a[r].split("."), s = l[0], c = l[1] || "global";
if (void 0 !== document && "global" === c) {
var f, d, p = {
bubbles: !0,
cancelable: !0,
detail: arguments[1]
};
if (document.createEvent) {
try {
if ("input" === s) p.inputType = "insertText", f = new InputEvent(s, p); else f = new CustomEvent(s, p);
} catch (e) {
(f = document.createEvent("CustomEvent")).initCustomEvent(s, p.bubbles, p.cancelable, p.detail);
}
e.type && (0, n.default)(f, e), i.dispatchEvent(f);
} else (f = document.createEventObject()).eventType = s, f.detail = arguments[1],
e.type && (0, n.default)(f, e), i.fireEvent("on" + f.eventType, f);
} else if (void 0 !== t[s]) if (arguments[0] = arguments[0].type ? arguments[0] : o.default.Event(arguments[0]),
arguments[0].detail = arguments.slice(1), "global" === c) for (var h in t[s]) for (d = 0; d < t[s][h].length; d++) t[s][h][d].apply(i, arguments); else for (d = 0; d < t[s][c].length; d++) t[s][c][d].apply(i, arguments);
}
return this;
};
var a, n = s(i(600)), r = s(i(9380)), o = s(i(4963)), l = s(i(8741));
function s(e) {
return e && e.__esModule ? e : {
default: e
};
}
function u(e) {
return e instanceof Element;
}
t.Event = a, "function" == typeof r.default.CustomEvent ? t.Event = a = r.default.CustomEvent : l.default && (t.Event = a = function(e, t) {
t = t || {
bubbles: !1,
cancelable: !1,
detail: void 0
};
var i = document.createEvent("CustomEvent");
return i.initCustomEvent(e, t.bubbles, t.cancelable, t.detail), i;
}, a.prototype = r.default.Event.prototype);
},
600: function(e, t) {
function i(e) {
return i = "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;
}, i(e);
}
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = function e() {
var t, a, n, r, o, l, s = arguments[0] || {}, u = 1, c = arguments.length, f = !1;
"boolean" == typeof s && (f = s, s = arguments[u] || {}, u++);
"object" !== i(s) && "function" != typeof s && (s = {});
for (;u < c; u++) if (null != (t = arguments[u])) for (a in t) n = s[a], r = t[a],
s !== r && (f && r && ("[object Object]" === Object.prototype.toString.call(r) || (o = Array.isArray(r))) ? (o ? (o = !1,
l = n && Array.isArray(n) ? n : []) : l = n && "[object Object]" === Object.prototype.toString.call(n) ? n : {},
s[a] = e(f, l, r)) : void 0 !== r && (s[a] = r));
return s;
};
},
4963: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var a = l(i(600)), n = l(i(9380)), r = l(i(253)), o = i(3776);
function l(e) {
return e && e.__esModule ? e : {
default: e
};
}
var s = n.default.document;
function u(e) {
return e instanceof u ? e : this instanceof u ? void (null != e && e !== n.default && (this[0] = e.nodeName ? e : void 0 !== e[0] && e[0].nodeName ? e[0] : s.querySelector(e),
void 0 !== this[0] && null !== this[0] && (this[0].eventRegistry = this[0].eventRegistry || {}))) : new u(e);
}
u.prototype = {
on: o.on,
off: o.off,
trigger: o.trigger
}, u.extend = a.default, u.data = r.default, u.Event = o.Event;
var c = u;
t.default = c;
},
9845: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.ua = t.mobile = t.iphone = t.iemobile = t.ie = void 0;
var a, n = (a = i(9380)) && a.__esModule ? a : {
default: a
};
var r = n.default.navigator && n.default.navigator.userAgent || "", o = r.indexOf("MSIE ") > 0 || r.indexOf("Trident/") > 0, l = "ontouchstart" in n.default, s = /iemobile/i.test(r), u = /iphone/i.test(r) && !s;
t.iphone = u, t.iemobile = s, t.mobile = l, t.ie = o, t.ua = r;
},
7184: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = function(e) {
return e.replace(i, "\\$1");
};
var i = new RegExp("(\\" + [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ].join("|\\") + ")", "gim");
},
6030: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.EventHandlers = void 0;
var a, n = i(8711), r = (a = i(5581)) && a.__esModule ? a : {
default: a
}, o = i(9845), l = i(7215), s = i(7760), u = i(4713);
function c(e, t) {
var i = "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"];
if (!i) {
if (Array.isArray(e) || (i = function(e, t) {
if (!e) return;
if ("string" == typeof e) return f(e, t);
var i = Object.prototype.toString.call(e).slice(8, -1);
"Object" === i && e.constructor && (i = e.constructor.name);
if ("Map" === i || "Set" === i) return Array.from(e);
if ("Arguments" === i || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)) return f(e, t);
}(e)) || t && e && "number" == typeof e.length) {
i && (e = i);
var a = 0, n = function() {};
return {
s: n,
n: function() {
return a >= e.length ? {
done: !0
} : {
done: !1,
value: e[a++]
};
},
e: function(e) {
throw e;
},
f: n
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var r, o = !0, l = !1;
return {
s: function() {
i = i.call(e);
},
n: function() {
var e = i.next();
return o = e.done, e;
},
e: function(e) {
l = !0, r = e;
},
f: function() {
try {
o || null == i.return || i.return();
} finally {
if (l) throw r;
}
}
};
}
function f(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var i = 0, a = new Array(t); i < t; i++) a[i] = e[i];
return a;
}
var d = {
keydownEvent: function(e) {
var t = this.inputmask, i = t.opts, a = t.dependencyLib, c = t.maskset, f = this, d = a(f), p = e.keyCode, h = n.caret.call(t, f), v = i.onKeyDown.call(this, e, n.getBuffer.call(t), h, i);
if (void 0 !== v) return v;
if (p === r.default.BACKSPACE || p === r.default.DELETE || o.iphone && p === r.default.BACKSPACE_SAFARI || e.ctrlKey && p === r.default.X && !("oncut" in f)) e.preventDefault(),
l.handleRemove.call(t, f, p, h), (0, s.writeBuffer)(f, n.getBuffer.call(t, !0), c.p, e, f.inputmask._valueGet() !== n.getBuffer.call(t).join("")); else if (p === r.default.END || p === r.default.PAGE_DOWN) {
e.preventDefault();
var m = n.seekNext.call(t, n.getLastValidPosition.call(t));
n.caret.call(t, f, e.shiftKey ? h.begin : m, m, !0);
} else p === r.default.HOME && !e.shiftKey || p === r.default.PAGE_UP ? (e.preventDefault(),
n.caret.call(t, f, 0, e.shiftKey ? h.begin : 0, !0)) : i.undoOnEscape && p === r.default.ESCAPE && !0 !== e.altKey ? ((0,
s.checkVal)(f, !0, !1, t.undoValue.split("")), d.trigger("click")) : p !== r.default.INSERT || e.shiftKey || e.ctrlKey || void 0 !== t.userOptions.insertMode ? !0 === i.tabThrough && p === r.default.TAB ? !0 === e.shiftKey ? (h.end = n.seekPrevious.call(t, h.end, !0),
!0 === u.getTest.call(t, h.end - 1).match.static && h.end--, h.begin = n.seekPrevious.call(t, h.end, !0),
h.begin >= 0 && h.end > 0 && (e.preventDefault(), n.caret.call(t, f, h.begin, h.end))) : (h.begin = n.seekNext.call(t, h.begin, !0),
h.end = n.seekNext.call(t, h.begin, !0), h.end < c.maskLength && h.end--, h.begin <= c.maskLength && (e.preventDefault(),
n.caret.call(t, f, h.begin, h.end))) : e.shiftKey || i.insertModeVisual && !1 === i.insertMode && (p === r.default.RIGHT ? setTimeout((function() {
var e = n.caret.call(t, f);
n.caret.call(t, f, e.begin);
}), 0) : p === r.default.LEFT && setTimeout((function() {
var e = n.translatePosition.call(t, f.inputmask.caretPos.begin);
n.translatePosition.call(t, f.inputmask.caretPos.end);
t.isRTL ? n.caret.call(t, f, e + (e === c.maskLength ? 0 : 1)) : n.caret.call(t, f, e - (0 === e ? 0 : 1));
}), 0)) : l.isSelection.call(t, h) ? i.insertMode = !i.insertMode : (i.insertMode = !i.insertMode,
n.caret.call(t, f, h.begin, h.begin));
t.ignorable = i.ignorables.includes(p);
},
keypressEvent: function(e, t, i, a, o) {
var u = this.inputmask || this, c = u.opts, f = u.dependencyLib, d = u.maskset, p = u.el, h = f(p), v = e.keyCode;
if (!(!0 === t || e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || u.ignorable)) return v === r.default.ENTER && u.undoValue !== u._valueGet(!0) && (u.undoValue = u._valueGet(!0),
setTimeout((function() {
h.trigger("change");
}), 0)), u.skipInputEvent = !0, !0;
if (v) {
44 !== v && 46 !== v || 3 !== e.location || "" === c.radixPoint || (v = c.radixPoint.charCodeAt(0));
var m, g = t ? {
begin: o,
end: o
} : n.caret.call(u, p), k = String.fromCharCode(v);
k = c.substitutes[k] || k, d.writeOutBuffer = !0;
var y = l.isValid.call(u, g, k, a, void 0, void 0, void 0, t);
if (!1 !== y && (n.resetMaskSet.call(u, !0), m = void 0 !== y.caret ? y.caret : n.seekNext.call(u, y.pos.begin ? y.pos.begin : y.pos),
d.p = m), m = c.numericInput && void 0 === y.caret ? n.seekPrevious.call(u, m) : m,
!1 !== i && (setTimeout((function() {
c.onKeyValidation.call(p, v, y);
}), 0), d.writeOutBuffer && !1 !== y)) {
var b = n.getBuffer.call(u);
(0, s.writeBuffer)(p, b, m, e, !0 !== t);
}
if (e.preventDefault(), t) return !1 !== y && (y.forwardPosition = m), y;
}
},
keyupEvent: function(e) {
var t = this.inputmask;
!t.isComposing || e.keyCode !== r.default.KEY_229 && e.keyCode !== r.default.ENTER || t.$el.trigger("input");
},
pasteEvent: function(e) {
var t, i = this.inputmask, a = i.opts, r = i._valueGet(!0), o = n.caret.call(i, this);
i.isRTL && (t = o.end, o.end = n.translatePosition.call(i, o.begin), o.begin = n.translatePosition.call(i, t));
var l = r.substr(0, o.begin), u = r.substr(o.end, r.length);
if (l == (i.isRTL ? n.getBufferTemplate.call(i).slice().reverse() : n.getBufferTemplate.call(i)).slice(0, o.begin).join("") && (l = ""),
u == (i.isRTL ? n.getBufferTemplate.call(i).slice().reverse() : n.getBufferTemplate.call(i)).slice(o.end).join("") && (u = ""),
window.clipboardData && window.clipboardData.getData) r = l + window.clipboardData.getData("Text") + u; else {
if (!e.clipboardData || !e.clipboardData.getData) return !0;
r = l + e.clipboardData.getData("text/plain") + u;
}
var f = r;
if (i.isRTL) {
f = f.split("");
var d, p = c(n.getBufferTemplate.call(i));
try {
for (p.s(); !(d = p.n()).done; ) {
var h = d.value;
f[0] === h && f.shift();
}
} catch (e) {
p.e(e);
} finally {
p.f();
}
f = f.join("");
}
if ("function" == typeof a.onBeforePaste) {
if (!1 === (f = a.onBeforePaste.call(i, f, a))) return !1;
f || (f = r);
}
(0, s.checkVal)(this, !0, !1, f.toString().split(""), e), e.preventDefault();
},
inputFallBackEvent: function(e) {
var t = this.inputmask, i = t.opts, a = t.dependencyLib;
var l = this, c = l.inputmask._valueGet(!0), f = (t.isRTL ? n.getBuffer.call(t).slice().reverse() : n.getBuffer.call(t)).join(""), p = n.caret.call(t, l, void 0, void 0, !0);
if (f !== c) {
c = function(e, i, a) {
if (o.iemobile) {
var r = i.replace(n.getBuffer.call(t).join(""), "");
if (1 === r.length) {
var l = i.split("");
l.splice(a.begin, 0, r), i = l.join("");
}
}
return i;
}(0, c, p);
var h = function(e, a, r) {
for (var o, l, s, c = e.substr(0, r.begin).split(""), f = e.substr(r.begin).split(""), d = a.substr(0, r.begin).split(""), p = a.substr(r.begin).split(""), h = c.length >= d.length ? c.length : d.length, v = f.length >= p.length ? f.length : p.length, m = "", g = [], k = "~"; c.length < h; ) c.push(k);
for (;d.length < h; ) d.push(k);
for (;f.length < v; ) f.unshift(k);
for (;p.length < v; ) p.unshift(k);
var y = c.concat(f), b = d.concat(p);
for (l = 0, o = y.length; l < o; l++) switch (s = u.getPlaceholder.call(t, n.translatePosition.call(t, l)),
m) {
case "insertText":
b[l - 1] === y[l] && r.begin == y.length - 1 && g.push(y[l]), l = o;
break;
case "insertReplacementText":
case "deleteContentBackward":
y[l] === k ? r.end++ : l = o;
break;
default:
y[l] !== b[l] && (y[l + 1] !== k && y[l + 1] !== s && void 0 !== y[l + 1] || (b[l] !== s || b[l + 1] !== k) && b[l] !== k ? b[l + 1] === k && b[l] === y[l + 1] ? (m = "insertText",
g.push(y[l]), r.begin--, r.end--) : y[l] !== s && y[l] !== k && (y[l + 1] === k || b[l] !== y[l] && b[l + 1] === y[l + 1]) ? (m = "insertReplacementText",
g.push(y[l]), r.begin--) : y[l] === k ? (m = "deleteContentBackward", (n.isMask.call(t, n.translatePosition.call(t, l), !0) || b[l] === i.radixPoint) && r.end++) : l = o : (m = "insertText",
g.push(y[l]), r.begin--, r.end--));
}
return {
action: m,
data: g,
caret: r
};
}(c, f, p);
switch ((l.inputmask.shadowRoot || l.ownerDocument).activeElement !== l && l.focus(),
(0, s.writeBuffer)(l, n.getBuffer.call(t)), n.caret.call(t, l, p.begin, p.end, !0),
h.action) {
case "insertText":
case "insertReplacementText":
h.data.forEach((function(e, i) {
var n = new a.Event("keypress");
n.keyCode = e.charCodeAt(0), t.ignorable = !1, d.keypressEvent.call(l, n);
})), setTimeout((function() {
t.$el.trigger("keyup");
}), 0);
break;
case "deleteContentBackward":
var v = new a.Event("keydown");
v.keyCode = r.default.BACKSPACE, d.keydownEvent.call(l, v);
break;
default:
(0, s.applyInputValue)(l, c);
}
e.preventDefault();
}
},
compositionendEvent: function(e) {
var t = this.inputmask;
t.isComposing = !1, t.$el.trigger("input");
},
setValueEvent: function(e) {
var t = this.inputmask, i = this, a = e && e.detail ? e.detail[0] : arguments[1];
void 0 === a && (a = i.inputmask._valueGet(!0)), (0, s.applyInputValue)(i, a), (e.detail && void 0 !== e.detail[1] || void 0 !== arguments[2]) && n.caret.call(t, i, e.detail ? e.detail[1] : arguments[2]);
},
focusEvent: function(e) {
var t = this.inputmask, i = t.opts, a = this, r = a.inputmask._valueGet();
i.showMaskOnFocus && r !== n.getBuffer.call(t).join("") && (0, s.writeBuffer)(a, n.getBuffer.call(t), n.seekNext.call(t, n.getLastValidPosition.call(t))),
!0 !== i.positionCaretOnTab || !1 !== t.mouseEnter || l.isComplete.call(t, n.getBuffer.call(t)) && -1 !== n.getLastValidPosition.call(t) || d.clickEvent.apply(a, [ e, !0 ]),
t.undoValue = t._valueGet(!0);
},
invalidEvent: function(e) {
this.inputmask.validationEvent = !0;
},
mouseleaveEvent: function() {
var e = this.inputmask, t = e.opts, i = this;
e.mouseEnter = !1, t.clearMaskOnLostFocus && (i.inputmask.shadowRoot || i.ownerDocument).activeElement !== i && (0,
s.HandleNativePlaceholder)(i, e.originalPlaceholder);
},
clickEvent: function(e, t) {
var i = this.inputmask, a = this;
if ((a.inputmask.shadowRoot || a.ownerDocument).activeElement === a) {
var r = n.determineNewCaretPosition.call(i, n.caret.call(i, a), t);
void 0 !== r && n.caret.call(i, a, r);
}
},
cutEvent: function(e) {
var t = this.inputmask, i = t.maskset, a = this, o = n.caret.call(t, a), u = t.isRTL ? n.getBuffer.call(t).slice(o.end, o.begin) : n.getBuffer.call(t).slice(o.begin, o.end), c = t.isRTL ? u.reverse().join("") : u.join("");
window.navigator.clipboard ? window.navigator.clipboard.writeText(c) : window.clipboardData && window.clipboardData.getData && window.clipboardData.setData("Text", c),
l.handleRemove.call(t, a, r.default.DELETE, o), (0, s.writeBuffer)(a, n.getBuffer.call(t), i.p, e, t.undoValue !== t._valueGet(!0));
},
blurEvent: function(e) {
var t = this.inputmask, i = t.opts, a = (0, t.dependencyLib)(this), r = this;
if (r.inputmask) {
(0, s.HandleNativePlaceholder)(r, t.originalPlaceholder);
var o = r.inputmask._valueGet(), u = n.getBuffer.call(t).slice();
"" !== o && (i.clearMaskOnLostFocus && (-1 === n.getLastValidPosition.call(t) && o === n.getBufferTemplate.call(t).join("") ? u = [] : s.clearOptionalTail.call(t, u)),
!1 === l.isComplete.call(t, u) && (setTimeout((function() {
a.trigger("incomplete");
}), 0), i.clearIncomplete && (n.resetMaskSet.call(t), u = i.clearMaskOnLostFocus ? [] : n.getBufferTemplate.call(t).slice())),
(0, s.writeBuffer)(r, u, void 0, e)), t.undoValue !== t._valueGet(!0) && (t.undoValue = t._valueGet(!0),
a.trigger("change"));
}
},
mouseenterEvent: function() {
var e = this.inputmask, t = e.opts, i = this;
if (e.mouseEnter = !0, (i.inputmask.shadowRoot || i.ownerDocument).activeElement !== i) {
var a = (e.isRTL ? n.getBufferTemplate.call(e).slice().reverse() : n.getBufferTemplate.call(e)).join("");
e.placeholder !== a && i.placeholder !== e.originalPlaceholder && (e.originalPlaceholder = i.placeholder),
t.showMaskOnHover && (0, s.HandleNativePlaceholder)(i, a);
}
},
submitEvent: function() {
var e = this.inputmask, t = e.opts;
e.undoValue !== e._valueGet(!0) && e.$el.trigger("change"), -1 === n.getLastValidPosition.call(e) && e._valueGet && e._valueGet() === n.getBufferTemplate.call(e).join("") && e._valueSet(""),
t.clearIncomplete && !1 === l.isComplete.call(e, n.getBuffer.call(e)) && e._valueSet(""),
t.removeMaskOnSubmit && (e._valueSet(e.unmaskedvalue(), !0), setTimeout((function() {
(0, s.writeBuffer)(e.el, n.getBuffer.call(e));
}), 0));
},
resetEvent: function() {
var e = this.inputmask;
e.refreshValue = !0, setTimeout((function() {
(0, s.applyInputValue)(e.el, e._valueGet(!0));
}), 0);
}
};
t.EventHandlers = d;
},
9716: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.EventRuler = void 0;
var a = l(i(2394)), n = l(i(5581)), r = i(8711), o = i(7760);
function l(e) {
return e && e.__esModule ? e : {
default: e
};
}
var s = {
on: function(e, t, i) {
var l = e.inputmask.dependencyLib, s = function(t) {
t.originalEvent && (t = t.originalEvent || t, arguments[0] = t);
var s, u = this, c = u.inputmask, f = c ? c.opts : void 0;
if (void 0 === c && "FORM" !== this.nodeName) {
var d = l.data(u, "_inputmask_opts");
l(u).off(), d && new a.default(d).mask(u);
} else {
if ([ "submit", "reset", "setvalue" ].includes(t.type) || "FORM" === this.nodeName || !(u.disabled || u.readOnly && !("keydown" === t.type && t.ctrlKey && 67 === t.keyCode || !1 === f.tabThrough && t.keyCode === n.default.TAB))) {
switch (t.type) {
case "input":
if (!0 === c.skipInputEvent || t.inputType && "insertCompositionText" === t.inputType) return c.skipInputEvent = !1,
t.preventDefault();
break;
case "keydown":
c.skipKeyPressEvent = !1, c.skipInputEvent = c.isComposing = t.keyCode === n.default.KEY_229;
break;
case "keyup":
case "compositionend":
c.isComposing && (c.skipInputEvent = !1);
break;
case "keypress":
if (!0 === c.skipKeyPressEvent) return t.preventDefault();
c.skipKeyPressEvent = !0;
break;
case "click":
case "focus":
return c.validationEvent ? (c.validationEvent = !1, e.blur(), (0, o.HandleNativePlaceholder)(e, (c.isRTL ? r.getBufferTemplate.call(c).slice().reverse() : r.getBufferTemplate.call(c)).join("")),
setTimeout((function() {
e.focus();
}), f.validationEventTimeOut), !1) : (s = arguments, setTimeout((function() {
e.inputmask && i.apply(u, s);
}), 0), !1);
}
var p = i.apply(u, arguments);
return !1 === p && (t.preventDefault(), t.stopPropagation()), p;
}
t.preventDefault();
}
};
[ "submit", "reset" ].includes(t) ? (s = s.bind(e), null !== e.form && l(e.form).on(t, s)) : l(e).on(t, s),
e.inputmask.events[t] = e.inputmask.events[t] || [], e.inputmask.events[t].push(s);
},
off: function(e, t) {
if (e.inputmask && e.inputmask.events) {
var i = e.inputmask.dependencyLib, a = e.inputmask.events;
for (var n in t && ((a = [])[t] = e.inputmask.events[t]), a) {
for (var r = a[n]; r.length > 0; ) {
var o = r.pop();
[ "submit", "reset" ].includes(n) ? null !== e.form && i(e.form).off(n, o) : i(e).off(n, o);
}
delete e.inputmask.events[n];
}
}
}
};
t.EventRuler = s;
},
219: function(e, t, i) {
var a = d(i(2394)), n = d(i(5581)), r = d(i(7184)), o = i(8711), l = i(4713);
function s(e) {
return s = "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;
}, s(e);
}
function u(e, t) {
return function(e) {
if (Array.isArray(e)) return e;
}(e) || function(e, t) {
var i = null == e ? null : "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"];
if (null == i) return;
var a, n, r = [], o = !0, l = !1;
try {
for (i = i.call(e); !(o = (a = i.next()).done) && (r.push(a.value), !t || r.length !== t); o = !0) ;
} catch (e) {
l = !0, n = e;
} finally {
try {
o || null == i.return || i.return();
} finally {
if (l) throw n;
}
}
return r;
}(e, t) || function(e, t) {
if (!e) return;
if ("string" == typeof e) return c(e, t);
var i = Object.prototype.toString.call(e).slice(8, -1);
"Object" === i && e.constructor && (i = e.constructor.name);
if ("Map" === i || "Set" === i) return Array.from(e);
if ("Arguments" === i || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)) return c(e, t);
}(e, t) || function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}();
}
function c(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var i = 0, a = new Array(t); i < t; i++) a[i] = e[i];
return a;
}
function f(e, t) {
for (var i = 0; i < t.length; i++) {
var a = t[i];
a.enumerable = a.enumerable || !1, a.configurable = !0, "value" in a && (a.writable = !0),
Object.defineProperty(e, a.key, a);
}
}
function d(e) {
return e && e.__esModule ? e : {
default: e
};
}
var p = a.default.dependencyLib, h = function() {
function e(t, i, a) {
!function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, e), this.mask = t, this.format = i, this.opts = a, this._date = new Date(1, 0, 1),
this.initDateObject(t, this.opts);
}
var t, i, a;
return t = e, (i = [ {
key: "date",
get: function() {
return void 0 === this._date && (this._date = new Date(1, 0, 1), this.initDateObject(void 0, this.opts)),
this._date;
}
}, {
key: "initDateObject",
value: function(e, t) {
var i;
for (P(t).lastIndex = 0; i = P(t).exec(this.format); ) {
var a = new RegExp("\\d+$").exec(i[0]), n = a ? i[0][0] + "x" : i[0], r = void 0;
if (void 0 !== e) {
if (a) {
var o = P(t).lastIndex, l = O(i.index, t);
P(t).lastIndex = o, r = e.slice(0, e.indexOf(l.nextMatch[0]));
} else r = e.slice(0, n.length);
e = e.slice(r.length);
}
Object.prototype.hasOwnProperty.call(g, n) && this.setValue(this, r, n, g[n][2], g[n][1]);
}
}
}, {
key: "setValue",
value: function(e, t, i, a, n) {
if (void 0 !== t && (e[a] = "ampm" === a ? t : t.replace(/[^0-9]/g, "0"), e["raw" + a] = t.replace(/\s/g, "_")),
void 0 !== n) {
var r = e[a];
("day" === a && 29 === parseInt(r) || "month" === a && 2 === parseInt(r)) && (29 !== parseInt(e.day) || 2 !== parseInt(e.month) || "" !== e.year && void 0 !== e.year || e._date.setFullYear(2012, 1, 29)),
"day" === a && (m = !0, 0 === parseInt(r) && (r = 1)), "month" === a && (m = !0),
"year" === a && (m = !0, r.length < 4 && (r = _(r, 4, !0))), "" === r || isNaN(r) || n.call(e._date, r),
"ampm" === a && n.call(e._date, r);
}
}
}, {
key: "reset",
value: function() {
this._date = new Date(1, 0, 1);
}
}, {
key: "reInit",
value: function() {
this._date = void 0, this.date;
}
} ]) && f(t.prototype, i), a && f(t, a), Object.defineProperty(t, "prototype", {
writable: !1
}), e;
}(), v = (new Date).getFullYear(), m = !1, g = {
d: [ "[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate ],
dd: [ "0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function() {
return _(Date.prototype.getDate.call(this), 2);
} ],
ddd: [ "" ],
dddd: [ "" ],
m: [ "[1-9]|1[012]", function(e) {
var t = e ? parseInt(e) : 0;
return t > 0 && t--, Date.prototype.setMonth.call(this, t);
}, "month", function() {
return Date.prototype.getMonth.call(this) + 1;
} ],
mm: [ "0[1-9]|1[012]", function(e) {
var t = e ? parseInt(e) : 0;
return t > 0 && t--, Date.prototype.setMonth.call(this, t);
}, "month", function() {
return _(Date.prototype.getMonth.call(this) + 1, 2);
} ],
mmm: [ "" ],
mmmm: [ "" ],
yy: [ "[0-9]{2}", Date.prototype.setFullYear, "year", function() {
return _(Date.prototype.getFullYear.call(this), 2);
} ],
yyyy: [ "[0-9]{4}", Date.prototype.setFullYear, "year", function() {
return _(Date.prototype.getFullYear.call(this), 4);
} ],
h: [ "[1-9]|1[0-2]", Date.prototype.setHours, "hours", Date.prototype.getHours ],
hh: [ "0[1-9]|1[0-2]", Date.prototype.setHours, "hours", function() {
return _(Date.prototype.getHours.call(this), 2);
} ],
hx: [ function(e) {
return "[0-9]{".concat(e, "}");
}, Date.prototype.setHours, "hours", function(e) {
return Date.prototype.getHours;
} ],
H: [ "1?[0-9]|2[0-3]", Date.prototype.setHours, "hours", Date.prototype.getHours ],
HH: [ "0[0-9]|1[0-9]|2[0-3]", Date.prototype.setHours, "hours", function() {
return _(Date.prototype.getHours.call(this), 2);
} ],
Hx: [ function(e) {
return "[0-9]{".concat(e, "}");
}, Date.prototype.setHours, "hours", function(e) {
return function() {
return _(Date.prototype.getHours.call(this), e);
};
} ],
M: [ "[1-5]?[0-9]", Date.prototype.setMinutes, "minutes", Date.prototype.getMinutes ],
MM: [ "0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setMinutes, "minutes", function() {
return _(Date.prototype.getMinutes.call(this), 2);
} ],
s: [ "[1-5]?[0-9]", Date.prototype.setSeconds, "seconds", Date.prototype.getSeconds ],
ss: [ "0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setSeconds, "seconds", function() {
return _(Date.prototype.getSeconds.call(this), 2);
} ],
l: [ "[0-9]{3}", Date.prototype.setMilliseconds, "milliseconds", function() {
return _(Date.prototype.getMilliseconds.call(this), 3);
} ],
L: [ "[0-9]{2}", Date.prototype.setMilliseconds, "milliseconds", function() {
return _(Date.prototype.getMilliseconds.call(this), 2);
} ],
t: [ "[ap]", y, "ampm", b, 1 ],
tt: [ "[ap]m", y, "ampm", b, 2 ],
T: [ "[AP]", y, "ampm", b, 1 ],
TT: [ "[AP]M", y, "ampm", b, 2 ],
Z: [ ".*", void 0, "Z", function() {
var e = this.toString().match(/\((.+)\)/)[1];
e.includes(" ") && (e = (e = e.replace("-", " ").toUpperCase()).split(" ").map((function(e) {
return u(e, 1)[0];
})).join(""));
return e;
} ],
o: [ "" ],
S: [ "" ]
}, k = {
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
function y(e) {
var t = this.getHours();
e.toLowerCase().includes("p") ? this.setHours(t + 12) : e.toLowerCase().includes("a") && t >= 12 && this.setHours(t - 12);
}
function b() {
var e = this.getHours();
return (e = e || 12) >= 12 ? "PM" : "AM";
}
function x(e) {
var t = new RegExp("\\d+$").exec(e[0]);
if (t && void 0 !== t[0]) {
var i = g[e[0][0] + "x"].slice("");
return i[0] = i[0](t[0]), i[3] = i[3](t[0]), i;
}
if (g[e[0]]) return g[e[0]];
}
function P(e) {
if (!e.tokenizer) {
var t = [], i = [];
for (var a in g) if (/\.*x$/.test(a)) {
var n = a[0] + "\\d+";
-1 === i.indexOf(n) && i.push(n);
} else -1 === t.indexOf(a[0]) && t.push(a[0]);
e.tokenizer = "(" + (i.length > 0 ? i.join("|") + "|" : "") + t.join("+|") + ")+?|.",
e.tokenizer = new RegExp(e.tokenizer, "g");
}
return e.tokenizer;
}
function E(e, t, i) {
if (!m) return !0;
if (void 0 === e.rawday || !isFinite(e.rawday) && new Date(e.date.getFullYear(), isFinite(e.rawmonth) ? e.month : e.date.getMonth() + 1, 0).getDate() >= e.day || "29" == e.day && (!isFinite(e.rawyear) || void 0 === e.rawyear || "" === e.rawyear) || new Date(e.date.getFullYear(), isFinite(e.rawmonth) ? e.month : e.date.getMonth() + 1, 0).getDate() >= e.day) return t;
if ("29" == e.day) {
var a = O(t.pos, i);
if ("yyyy" === a.targetMatch[0] && t.pos - a.targetMatchIndex == 2) return t.remove = t.pos + 1,
t;
} else if ("02" == e.month && "30" == e.day && void 0 !== t.c) return e.day = "03",
e.date.setDate(3), e.date.setMonth(1), t.insert = [ {
pos: t.pos,
c: "0"
}, {
pos: t.pos + 1,
c: t.c
} ], t.caret = o.seekNext.call(this, t.pos + 1), t;
return !1;
}
function S(e, t, i, a) {
var n, o, l = "";
for (P(i).lastIndex = 0; n = P(i).exec(e); ) {
if (void 0 === t) if (o = x(n)) l += "(" + o[0] + ")"; else switch (n[0]) {
case "[":
l += "(";
break;
case "]":
l += ")?";
break;
default:
l += (0, r.default)(n[0]);
} else if (o = x(n)) if (!0 !== a && o[3]) l += o[3].call(t.date); else o[2] ? l += t["raw" + o[2]] : l += n[0]; else l += n[0];
}
return l;
}
function _(e, t, i) {
for (e = String(e), t = t || 2; e.length < t; ) e = i ? e + "0" : "0" + e;
return e;
}
function w(e, t, i) {
return "string" == typeof e ? new h(e, t, i) : e && "object" === s(e) && Object.prototype.hasOwnProperty.call(e, "date") ? e : void 0;
}
function M(e, t) {
return S(t.inputFormat, {
date: e
}, t);
}
function O(e, t) {
var i, a, n = 0, r = 0;
for (P(t).lastIndex = 0; a = P(t).exec(t.inputFormat); ) {
var o = new RegExp("\\d+$").exec(a[0]);
if ((n += r = o ? parseInt(o[0]) : a[0].length) >= e + 1) {
i = a, a = P(t).exec(t.inputFormat);
break;
}
}
return {
targetMatchIndex: n - r,
nextMatch: a,
targetMatch: i
};
}
a.default.extendAliases({
datetime: {
mask: function(e) {
return e.numericInput = !1, g.S = e.i18n.ordinalSuffix.join("|"), e.inputFormat = k[e.inputFormat] || e.inputFormat,
e.displayFormat = k[e.displayFormat] || e.displayFormat || e.inputFormat, e.outputFormat = k[e.outputFormat] || e.outputFormat || e.inputFormat,
e.placeholder = "" !== e.placeholder ? e.placeholder : e.inputFormat.replace(/[[\]]/, ""),
e.regex = S(e.inputFormat, void 0, e), e.min = w(e.min, e.inputFormat, e), e.max = w(e.max, e.inputFormat, e),
null;
},
placeholder: "",
inputFormat: "isoDateTime",
displayFormat: null,
outputFormat: null,
min: null,
max: null,
skipOptionalPartCharacter: "",
i18n: {
dayNames: [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ],
monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
ordinalSuffix: [ "st", "nd", "rd", "th" ]
},
preValidation: function(e, t, i, a, n, r, o, l) {
if (l) return !0;
if (isNaN(i) && e[t] !== i) {
var s = O(t, n);
if (s.nextMatch && s.nextMatch[0] === i && s.targetMatch[0].length > 1) {
var u = g[s.targetMatch[0]][0];
if (new RegExp(u).test("0" + e[t - 1])) return e[t] = e[t - 1], e[t - 1] = "0",
{
fuzzy: !0,
buffer: e,
refreshFromBuffer: {
start: t - 1,
end: t + 1
},
pos: t + 1
};
}
}
return !0;
},
postValidation: function(e, t, i, a, n, r, o, s) {
var u, c;
if (o) return !0;
if (!1 === a && (((u = O(t + 1, n)).targetMatch && u.targetMatchIndex === t && u.targetMatch[0].length > 1 && void 0 !== g[u.targetMatch[0]] || (u = O(t + 2, n)).targetMatch && u.targetMatchIndex === t + 1 && u.targetMatch[0].length > 1 && void 0 !== g[u.targetMatch[0]]) && (c = g[u.targetMatch[0]][0]),
void 0 !== c && (void 0 !== r.validPositions[t + 1] && new RegExp(c).test(i + "0") ? (e[t] = i,
e[t + 1] = "0", a = {
pos: t + 2,
caret: t
}) : new RegExp(c).test("0" + i) && (e[t] = "0", e[t + 1] = i, a = {
pos: t + 2
})), !1 === a)) return a;
if (a.fuzzy && (e = a.buffer, t = a.pos), (u = O(t, n)).targetMatch && u.targetMatch[0] && void 0 !== g[u.targetMatch[0]]) {
var f = g[u.targetMatch[0]];
c = f[0];
var d = e.slice(u.targetMatchIndex, u.targetMatchIndex + u.targetMatch[0].length);
if (!1 === new RegExp(c).test(d.join("")) && 2 === u.targetMatch[0].length && r.validPositions[u.targetMatchIndex] && r.validPositions[u.targetMatchIndex + 1] && (r.validPositions[u.targetMatchIndex + 1].input = "0"),
"year" == f[2]) for (var p = l.getMaskTemplate.call(this, !1, 1, void 0, !0), h = t + 1; h < e.length; h++) e[h] = p[h],
delete r.validPositions[h];
}
var m = a, k = w(e.join(""), n.inputFormat, n);
return m && k.date.getTime() == k.date.getTime() && (n.prefillYear && (m = function(e, t, i) {
if (e.year !== e.rawyear) {
var a = v.toString(), n = e.rawyear.replace(/[^0-9]/g, ""), r = a.slice(0, n.length), o = a.slice(n.length);
if (2 === n.length && n === r) {
var l = new Date(v, e.month - 1, e.day);
e.day == l.getDate() && (!i.max || i.max.date.getTime() >= l.getTime()) && (e.date.setFullYear(v),
e.year = a, t.insert = [ {
pos: t.pos + 1,
c: o[0]
}, {
pos: t.pos + 2,
c: o[1]
} ]);
}
}
return t;
}(k, m, n)), m = function(e, t, i, a, n) {
if (!t) return t;
if (t && i.min && i.min.date.getTime() == i.min.date.getTime()) {
var r;
for (e.reset(), P(i).lastIndex = 0; r = P(i).exec(i.inputFormat); ) {
var o;
if ((o = x(r)) && o[3]) {
for (var l = o[1], s = e[o[2]], u = i.min[o[2]], c = i.max ? i.max[o[2]] : u, f = [], d = !1, p = 0; p < u.length; p++) void 0 !== a.validPositions[p + r.index] || d ? (f[p] = s[p],
d = d || s[p] > u[p]) : (f[p] = u[p], "year" === o[2] && s.length - 1 == p && u != c && (f = (parseInt(f.join("")) + 1).toString().split("")),
"ampm" === o[2] && u != c && i.min.date.getTime() > e.date.getTime() && (f[p] = c[p]));
l.call(e._date, f.join(""));
}
}
t = i.min.date.getTime() <= e.date.getTime(), e.reInit();
}
return t && i.max && i.max.date.getTime() == i.max.date.getTime() && (t = i.max.date.getTime() >= e.date.getTime()),
t;
}(k, m = E.call(this, k, m, n), n, r)), void 0 !== t && m && a.pos !== t ? {
buffer: S(n.inputFormat, k, n).split(""),
refreshFromBuffer: {
start: t,
end: a.pos
},
pos: a.caret || a.pos
} : m;
},
onKeyDown: function(e, t, i, a) {
e.ctrlKey && e.keyCode === n.default.RIGHT && (this.inputmask._valueSet(M(new Date, a)),
p(this).trigger("setvalue"));
},
onUnMask: function(e, t, i) {
return t ? S(i.outputFormat, w(e, i.inputFormat, i), i, !0) : t;
},
casing: function(e, t, i, a) {
return 0 == t.nativeDef.indexOf("[ap]") ? e.toLowerCase() : 0 == t.nativeDef.indexOf("[AP]") ? e.toUpperCase() : e;
},
onBeforeMask: function(e, t) {
return "[object Date]" === Object.prototype.toString.call(e) && (e = M(e, t)), e;
},
insertMode: !1,
shiftPositions: !1,
keepStatic: !1,
inputmode: "numeric",
prefillYear: !0
}
});
},
3851: function(e, t, i) {
var a, n = (a = i(2394)) && a.__esModule ? a : {
default: a
}, r = i(8711), o = i(4713);
n.default.extendDefinitions({
A: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
casing: "upper"
},
"&": {
validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
casing: "upper"
},
"#": {
validator: "[0-9A-Fa-f]",
casing: "upper"
}
});
var l = new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");
function s(e, t, i, a, n) {
return i - 1 > -1 && "." !== t.buffer[i - 1] ? (e = t.buffer[i - 1] + e, e = i - 2 > -1 && "." !== t.buffer[i - 2] ? t.buffer[i - 2] + e : "0" + e) : e = "00" + e,
l.test(e);
}
n.default.extendAliases({
cssunit: {
regex: "[+-]?[0-9]+\\.?([0-9]+)?(px|em|rem|ex|%|in|cm|mm|pt|pc)"
},
url: {
regex: "(https?|ftp)://.*",
autoUnmask: !1,
keepStatic: !1,
tabThrough: !0
},
ip: {
mask: "i{1,3}.j{1,3}.k{1,3}.l{1,3}",
definitions: {
i: {
validator: s
},
j: {
validator: s
},
k: {
validator: s
},
l: {
validator: s
}
},
onUnMask: function(e, t, i) {
return e;
},
inputmode: "decimal",
substitutes: {
",": "."
}
},
email: {
mask: function(e) {
var t = "*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]", i = t;
if (e.separator) for (var a = 0; a < e.quantifier; a++) i += "[".concat(e.separator).concat(t, "]");
return i;
},
greedy: !1,
casing: "lower",
separator: null,
quantifier: 5,
skipOptionalPartCharacter: "",
onBeforePaste: function(e, t) {
return (e = e.toLowerCase()).replace("mailto:", "");
},
definitions: {
"*": {
validator: "[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5!#$%&'*+/=?^_`{|}~-]"
},
"-": {
validator: "[0-9A-Za-z-]"
}
},
onUnMask: function(e, t, i) {
return e;
},
inputmode: "email"
},
mac: {
mask: "##:##:##:##:##:##"
},
vin: {
mask: "V{13}9{4}",
definitions: {
V: {
validator: "[A-HJ-NPR-Za-hj-npr-z\\d]",
casing: "upper"
}
},
clearIncomplete: !0,
autoUnmask: !0
},
ssn: {
mask: "999-99-9999",
postValidation: function(e, t, i, a, n, l, s) {
var u = o.getMaskTemplate.call(this, !0, r.getLastValidPosition.call(this), !0, !0);
return /^(?!219-09-9999|078-05-1120)(?!666|000|9.{2}).{3}-(?!00).{2}-(?!0{4}).{4}$/.test(u.join(""));
}
}
});
},
207: function(e, t, i) {
var a = l(i(2394)), n = l(i(5581)), r = l(i(7184)), o = i(8711);
function l(e) {
return e && e.__esModule ? e : {
default: e
};
}
var s = a.default.dependencyLib;
function u(e, t) {
for (var i = "", n = 0; n < e.length; n++) a.default.prototype.definitions[e.charAt(n)] || t.definitions[e.charAt(n)] || t.optionalmarker[0] === e.charAt(n) || t.optionalmarker[1] === e.charAt(n) || t.quantifiermarker[0] === e.charAt(n) || t.quantifiermarker[1] === e.charAt(n) || t.groupmarker[0] === e.charAt(n) || t.groupmarker[1] === e.charAt(n) || t.alternatormarker === e.charAt(n) ? i += "\\" + e.charAt(n) : i += e.charAt(n);
return i;
}
function c(e, t, i, a) {
if (e.length > 0 && t > 0 && (!i.digitsOptional || a)) {
var n = e.indexOf(i.radixPoint), r = !1;
i.negationSymbol.back === e[e.length - 1] && (r = !0, e.length--), -1 === n && (e.push(i.radixPoint),
n = e.length - 1);
for (var o = 1; o <= t; o++) isFinite(e[n + o]) || (e[n + o] = "0");
}
return r && e.push(i.negationSymbol.back), e;
}
function f(e, t) {
var i = 0;
if ("+" === e) {
for (i in t.validPositions) ;
i = o.seekNext.call(this, parseInt(i));
}
for (var a in t.tests) if ((a = parseInt(a)) >= i) for (var n = 0, r = t.tests[a].length; n < r; n++) if ((void 0 === t.validPositions[a] || "-" === e) && t.tests[a][n].match.def === e) return a + (void 0 !== t.validPositions[a] && "-" !== e ? 1 : 0);
return i;
}
function d(e, t) {
var i = -1;
for (var a in t.validPositions) {
var n = t.validPositions[a];
if (n && n.match.def === e) {
i = parseInt(a);
break;
}
}
return i;
}
function p(e, t, i, a, n) {
var r = t.buffer ? t.buffer.indexOf(n.radixPoint) : -1, o = (-1 !== r || a && n.jitMasking) && new RegExp(n.definitions[9].validator).test(e);
return n._radixDance && -1 !== r && o && null == t.validPositions[r] ? {
insert: {
pos: r === i ? r + 1 : r,
c: n.radixPoint
},
pos: i
} : o;
}
a.default.extendAliases({
numeric: {
mask: function(e) {
e.repeat = 0, e.groupSeparator === e.radixPoint && e.digits && "0" !== e.digits && ("." === e.radixPoint ? e.groupSeparator = "," : "," === e.radixPoint ? e.groupSeparator = "." : e.groupSeparator = ""),
" " === e.groupSeparator && (e.skipOptionalPartCharacter = void 0), e.placeholder.length > 1 && (e.placeholder = e.placeholder.charAt(0)),
"radixFocus" === e.positionCaretOnClick && "" === e.placeholder && (e.positionCaretOnClick = "lvp");
var t = "0", i = e.radixPoint;
!0 === e.numericInput && void 0 === e.__financeInput ? (t = "1", e.positionCaretOnClick = "radixFocus" === e.positionCaretOnClick ? "lvp" : e.positionCaretOnClick,
e.digitsOptional = !1, isNaN(e.digits) && (e.digits = 2), e._radixDance = !1, i = "," === e.radixPoint ? "?" : "!",
"" !== e.radixPoint && void 0 === e.definitions[i] && (e.definitions[i] = {}, e.definitions[i].validator = "[" + e.radixPoint + "]",
e.definitions[i].placeholder = e.radixPoint, e.definitions[i].static = !0, e.definitions[i].generated = !0)) : (e.__financeInput = !1,
e.numericInput = !0);
var a, n = "[+]";
if (n += u(e.prefix, e), "" !== e.groupSeparator ? (void 0 === e.definitions[e.groupSeparator] && (e.definitions[e.groupSeparator] = {},
e.definitions[e.groupSeparator].validator = "[" + e.groupSeparator + "]", e.definitions[e.groupSeparator].placeholder = e.groupSeparator,
e.definitions[e.groupSeparator].static = !0, e.definitions[e.groupSeparator].generated = !0),
n += e._mask(e)) : n += "9{+}", void 0 !== e.digits && 0 !== e.digits) {
var o = e.digits.toString().split(",");
isFinite(o[0]) && o[1] && isFinite(o[1]) ? n += i + t + "{" + e.digits + "}" : (isNaN(e.digits) || parseInt(e.digits) > 0) && (e.digitsOptional || e.jitMasking ? (a = n + i + t + "{0," + e.digits + "}",
e.keepStatic = !0) : n += i + t + "{" + e.digits + "}");
} else e.inputmode = "numeric";
return n += u(e.suffix, e), n += "[-]", a && (n = [ a + u(e.suffix, e) + "[-]", n ]),
e.greedy = !1, function(e) {
void 0 === e.parseMinMaxOptions && (null !== e.min && (e.min = e.min.toString().replace(new RegExp((0,
r.default)(e.groupSeparator), "g"), ""), "," === e.radixPoint && (e.min = e.min.replace(e.radixPoint, ".")),
e.min = isFinite(e.min) ? parseFloat(e.min) : NaN, isNaN(e.min) && (e.min = Number.MIN_VALUE)),
null !== e.max && (e.max = e.max.toString().replace(new RegExp((0, r.default)(e.groupSeparator), "g"), ""),
"," === e.radixPoint && (e.max = e.max.replace(e.radixPoint, ".")), e.max = isFinite(e.max) ? parseFloat(e.max) : NaN,
isNaN(e.max) && (e.max = Number.MAX_VALUE)), e.parseMinMaxOptions = "done");
}(e), "" !== e.radixPoint && (e.substitutes["." == e.radixPoint ? "," : "."] = e.radixPoint),
n;
},
_mask: function(e) {
return "(" + e.groupSeparator + "999){+|1}";
},
digits: "*",
digitsOptional: !0,
enforceDigitsOnBlur: !1,
radixPoint: ".",
positionCaretOnClick: "radixFocus",
_radixDance: !0,
groupSeparator: "",
allowMinus: !0,
negationSymbol: {
front: "-",
back: ""
},
prefix: "",
suffix: "",
min: null,
max: null,
SetMaxOnOverflow: !1,
step: 1,
inputType: "text",
unmaskAsNumber: !1,
roundingFN: Math.round,
inputmode: "decimal",
shortcuts: {
k: "1000",
m: "1000000"
},
placeholder: "0",
greedy: !1,
rightAlign: !0,
insertMode: !0,
autoUnmask: !1,
skipOptionalPartCharacter: "",
usePrototypeDefinitions: !1,
stripLeadingZeroes: !0,
definitions: {
0: {
validator: p
},
1: {
validator: p,
definitionSymbol: "9"
},
9: {
validator: "[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]",
definitionSymbol: "*"
},
"+": {
validator: function(e, t, i, a, n) {
return n.allowMinus && ("-" === e || e === n.negationSymbol.front);
}
},
"-": {
validator: function(e, t, i, a, n) {
return n.allowMinus && e === n.negationSymbol.back;
}
}
},
preValidation: function(e, t, i, a, n, r, o, l) {
if (!1 !== n.__financeInput && i === n.radixPoint) return !1;
var s = e.indexOf(n.radixPoint), u = t;
if (t = function(e, t, i, a, n) {
return n._radixDance && n.numericInput && t !== n.negationSymbol.back && e <= i && (i > 0 || t == n.radixPoint) && (void 0 === a.validPositions[e - 1] || a.validPositions[e - 1].input !== n.negationSymbol.back) && (e -= 1),
e;
}(t, i, s, r, n), "-" === i || i === n.negationSymbol.front) {
if (!0 !== n.allowMinus) return !1;
var c = !1, p = d("+", r), h = d("-", r);
return -1 !== p && (c = [ p, h ]), !1 !== c ? {
remove: c,
caret: u - n.negationSymbol.back.length
} : {
insert: [ {
pos: f.call(this, "+", r),
c: n.negationSymbol.front,
fromIsValid: !0
}, {
pos: f.call(this, "-", r),
c: n.negationSymbol.back,
fromIsValid: void 0
} ],
caret: u + n.negationSymbol.back.length
};
}
if (i === n.groupSeparator) return {
caret: u
};
if (l) return !0;
if (-1 !== s && !0 === n._radixDance && !1 === a && i === n.radixPoint && void 0 !== n.digits && (isNaN(n.digits) || parseInt(n.digits) > 0) && s !== t) return {
caret: n._radixDance && t === s - 1 ? s + 1 : s
};
if (!1 === n.__financeInput) if (a) {
if (n.digitsOptional) return {
rewritePosition: o.end
};
if (!n.digitsOptional) {
if (o.begin > s && o.end <= s) return i === n.radixPoint ? {
insert: {
pos: s + 1,
c: "0",
fromIsValid: !0
},
rewritePosition: s
} : {
rewritePosition: s + 1
};
if (o.begin < s) return {
rewritePosition: o.begin - 1
};
}
} else if (!n.showMaskOnHover && !n.showMaskOnFocus && !n.digitsOptional && n.digits > 0 && "" === this.__valueGet.call(this.el)) return {
rewritePosition: s
};
return {
rewritePosition: t
};
},
postValidation: function(e, t, i, a, n, r, o) {
if (!1 === a) return a;
if (o) return !0;
if (null !== n.min || null !== n.max) {
var l = n.onUnMask(e.slice().reverse().join(""), void 0, s.extend({}, n, {
unmaskAsNumber: !0
}));
if (null !== n.min && l < n.min && (l.toString().length > n.min.toString().length || l < 0)) return !1;
if (null !== n.max && l > n.max) return !!n.SetMaxOnOverflow && {
refreshFromBuffer: !0,
buffer: c(n.max.toString().replace(".", n.radixPoint).split(""), n.digits, n).reverse()
};
}
return a;
},
onUnMask: function(e, t, i) {
if ("" === t && !0 === i.nullable) return t;
var a = e.replace(i.prefix, "");
return a = (a = a.replace(i.suffix, "")).replace(new RegExp((0, r.default)(i.groupSeparator), "g"), ""),
"" !== i.placeholder.charAt(0) && (a = a.replace(new RegExp(i.placeholder.charAt(0), "g"), "0")),
i.unmaskAsNumber ? ("" !== i.radixPoint && -1 !== a.indexOf(i.radixPoint) && (a = a.replace(r.default.call(this, i.radixPoint), ".")),
a = (a = a.replace(new RegExp("^" + (0, r.default)(i.negationSymbol.front)), "-")).replace(new RegExp((0,
r.default)(i.negationSymbol.back) + "$"), ""), Number(a)) : a;
},
isComplete: function(e, t) {
var i = (t.numericInput ? e.slice().reverse() : e).join("");
return i = (i = (i = (i = (i = i.replace(new RegExp("^" + (0, r.default)(t.negationSymbol.front)), "-")).replace(new RegExp((0,
r.default)(t.negationSymbol.back) + "$"), "")).replace(t.prefix, "")).replace(t.suffix, "")).replace(new RegExp((0,
r.default)(t.groupSeparator) + "([0-9]{3})", "g"), "$1"), "," === t.radixPoint && (i = i.replace((0,
r.default)(t.radixPoint), ".")), isFinite(i);
},
onBeforeMask: function(e, t) {
var i = t.radixPoint || ",";
isFinite(t.digits) && (t.digits = parseInt(t.digits)), "number" != typeof e && "number" !== t.inputType || "" === i || (e = e.toString().replace(".", i));
var a = "-" === e.charAt(0) || e.charAt(0) === t.negationSymbol.front, n = e.split(i), o = n[0].replace(/[^\-0-9]/g, ""), l = n.length > 1 ? n[1].replace(/[^0-9]/g, "") : "", s = n.length > 1;
e = o + ("" !== l ? i + l : l);
var u = 0;
if ("" !== i && (u = t.digitsOptional ? t.digits < l.length ? t.digits : l.length : t.digits,
"" !== l || !t.digitsOptional)) {
var f = Math.pow(10, u || 1);
e = e.replace((0, r.default)(i), "."), isNaN(parseFloat(e)) || (e = (t.roundingFN(parseFloat(e) * f) / f).toFixed(u)),
e = e.toString().replace(".", i);
}
if (0 === t.digits && -1 !== e.indexOf(i) && (e = e.substring(0, e.indexOf(i))),
null !== t.min || null !== t.max) {
var d = e.toString().replace(i, ".");
null !== t.min && d < t.min ? e = t.min.toString().replace(".", i) : null !== t.max && d > t.max && (e = t.max.toString().replace(".", i));
}
return a && "-" !== e.charAt(0) && (e = "-" + e), c(e.toString().split(""), u, t, s).join("");
},
onBeforeWrite: function(e, t, i, a) {
function n(e, t) {
if (!1 !== a.__financeInput || t) {
var i = e.indexOf(a.radixPoint);
-1 !== i && e.splice(i, 1);
}
if ("" !== a.groupSeparator) for (;-1 !== (i = e.indexOf(a.groupSeparator)); ) e.splice(i, 1);
return e;
}
var o, l;
if (a.stripLeadingZeroes && (l = function(e, t) {
var i = new RegExp("(^" + ("" !== t.negationSymbol.front ? (0, r.default)(t.negationSymbol.front) + "?" : "") + (0,
r.default)(t.prefix) + ")(.*)(" + (0, r.default)(t.suffix) + ("" != t.negationSymbol.back ? (0,
r.default)(t.negationSymbol.back) + "?" : "") + "$)").exec(e.slice().reverse().join("")), a = i ? i[2] : "", n = !1;
return a && (a = a.split(t.radixPoint.charAt(0))[0], n = new RegExp("^[0" + t.groupSeparator + "]*").exec(a)),
!(!n || !(n[0].length > 1 || n[0].length > 0 && n[0].length < a.length)) && n;
}(t, a))) for (var u = t.join("").lastIndexOf(l[0].split("").reverse().join("")) - (l[0] == l.input ? 0 : 1), f = l[0] == l.input ? 1 : 0, d = l[0].length - f; d > 0; d--) delete this.maskset.validPositions[u + d],
delete t[u + d];
if (e) switch (e.type) {
case "blur":
case "checkval":
if (null !== a.min) {
var p = a.onUnMask(t.slice().reverse().join(""), void 0, s.extend({}, a, {
unmaskAsNumber: !0
}));
if (null !== a.min && p < a.min) return {
refreshFromBuffer: !0,
buffer: c(a.min.toString().replace(".", a.radixPoint).split(""), a.digits, a).reverse()
};
}
if (t[t.length - 1] === a.negationSymbol.front) {
var h = new RegExp("(^" + ("" != a.negationSymbol.front ? (0, r.default)(a.negationSymbol.front) + "?" : "") + (0,
r.default)(a.prefix) + ")(.*)(" + (0, r.default)(a.suffix) + ("" != a.negationSymbol.back ? (0,
r.default)(a.negationSymbol.back) + "?" : "") + "$)").exec(n(t.slice(), !0).reverse().join(""));
0 == (h ? h[2] : "") && (o = {
refreshFromBuffer: !0,
buffer: [ 0 ]
});
} else if ("" !== a.radixPoint) {
t.indexOf(a.radixPoint) === a.suffix.length && (o && o.buffer ? o.buffer.splice(0, 1 + a.suffix.length) : (t.splice(0, 1 + a.suffix.length),
o = {
refreshFromBuffer: !0,
buffer: n(t)
}));
}
if (a.enforceDigitsOnBlur) {
var v = (o = o || {}) && o.buffer || t.slice().reverse();
o.refreshFromBuffer = !0, o.buffer = c(v, a.digits, a, !0).reverse();
}
}
return o;
},
onKeyDown: function(e, t, i, a) {
var r, o, l = s(this), u = String.fromCharCode(e.keyCode).toLowerCase();
if ((o = a.shortcuts && a.shortcuts[u]) && o.length > 1) return this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) * parseInt(o)),
l.trigger("setvalue"), !1;
if (e.ctrlKey) switch (e.keyCode) {
case n.default.UP:
return this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) + parseInt(a.step)),
l.trigger("setvalue"), !1;
case n.default.DOWN:
return this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) - parseInt(a.step)),
l.trigger("setvalue"), !1;
}
if (!e.shiftKey && (e.keyCode === n.default.DELETE || e.keyCode === n.default.BACKSPACE || e.keyCode === n.default.BACKSPACE_SAFARI) && i.begin !== t.length) {
if (t[e.keyCode === n.default.DELETE ? i.begin - 1 : i.end] === a.negationSymbol.front) return r = t.slice().reverse(),
"" !== a.negationSymbol.front && r.shift(), "" !== a.negationSymbol.back && r.pop(),
l.trigger("setvalue", [ r.join(""), i.begin ]), !1;
if (!0 === a._radixDance) {
var f = t.indexOf(a.radixPoint);
if (a.digitsOptional) {
if (0 === f) return (r = t.slice().reverse()).pop(), l.trigger("setvalue", [ r.join(""), i.begin >= r.length ? r.length : i.begin ]),
!1;
} else if (-1 !== f && (i.begin < f || i.end < f || e.keyCode === n.default.DELETE && i.begin === f)) return i.begin !== i.end || e.keyCode !== n.default.BACKSPACE && e.keyCode !== n.default.BACKSPACE_SAFARI || i.begin++,
(r = t.slice().reverse()).splice(r.length - i.begin, i.begin - i.end + 1), r = c(r, a.digits, a).join(""),
l.trigger("setvalue", [ r, i.begin >= r.length ? f + 1 : i.begin ]), !1;
}
}
}
},
currency: {
prefix: "",
groupSeparator: ",",
alias: "numeric",
digits: 2,
digitsOptional: !1
},
decimal: {
alias: "numeric"
},
integer: {
alias: "numeric",
inputmode: "numeric",
digits: 0
},
percentage: {
alias: "numeric",
min: 0,
max: 100,
suffix: " %",
digits: 0,
allowMinus: !1
},
indianns: {
alias: "numeric",
_mask: function(e) {
return "(" + e.groupSeparator + "99){*|1}(" + e.groupSeparator + "999){1|1}";
},
groupSeparator: ",",
radixPoint: ".",
placeholder: "0",
digits: 2,
digitsOptional: !1
}
});
},
9380: function(e, t, i) {
var a;
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var n = ((a = i(8741)) && a.__esModule ? a : {
default: a
}).default ? window : {};
t.default = n;
},
7760: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.HandleNativePlaceholder = function(e, t) {
var i = e ? e.inputmask : this;
if (s.ie) {
if (e.inputmask._valueGet() !== t && (e.placeholder !== t || "" === e.placeholder)) {
var a = o.getBuffer.call(i).slice(), n = e.inputmask._valueGet();
if (n !== t) {
var r = o.getLastValidPosition.call(i);
-1 === r && n === o.getBufferTemplate.call(i).join("") ? a = [] : -1 !== r && f.call(i, a),
p(e, a);
}
}
} else e.placeholder !== t && (e.placeholder = t, "" === e.placeholder && e.removeAttribute("placeholder"));
}, t.applyInputValue = c, t.checkVal = d, t.clearOptionalTail = f, t.unmaskedvalue = function(e) {
var t = e ? e.inputmask : this, i = t.opts, a = t.maskset;
if (e) {
if (void 0 === e.inputmask) return e.value;
e.inputmask && e.inputmask.refreshValue && c(e, e.inputmask._valueGet(!0));
}
var n = [], r = a.validPositions;
for (var l in r) r[l] && r[l].match && (1 != r[l].match.static || Array.isArray(a.metadata) && !0 !== r[l].generatedInput) && n.push(r[l].input);
var s = 0 === n.length ? "" : (t.isRTL ? n.reverse() : n).join("");
if ("function" == typeof i.onUnMask) {
var u = (t.isRTL ? o.getBuffer.call(t).slice().reverse() : o.getBuffer.call(t)).join("");
s = i.onUnMask.call(t, u, s, i);
}
return s;
}, t.writeBuffer = p;
var a, n = (a = i(5581)) && a.__esModule ? a : {
default: a
}, r = i(4713), o = i(8711), l = i(7215), s = i(9845), u = i(6030);
function c(e, t) {
var i = e ? e.inputmask : this, a = i.opts;
e.inputmask.refreshValue = !1, "function" == typeof a.onBeforeMask && (t = a.onBeforeMask.call(i, t, a) || t),
d(e, !0, !1, t = t.toString().split("")), i.undoValue = i._valueGet(!0), (a.clearMaskOnLostFocus || a.clearIncomplete) && e.inputmask._valueGet() === o.getBufferTemplate.call(i).join("") && -1 === o.getLastValidPosition.call(i) && e.inputmask._valueSet("");
}
function f(e) {
e.length = 0;
for (var t, i = r.getMaskTemplate.call(this, !0, 0, !0, void 0, !0); void 0 !== (t = i.shift()); ) e.push(t);
return e;
}
function d(e, t, i, a, n) {
var s = e ? e.inputmask : this, c = s.maskset, f = s.opts, d = s.dependencyLib, h = a.slice(), v = "", m = -1, g = void 0, k = f.skipOptionalPartCharacter;
f.skipOptionalPartCharacter = "", o.resetMaskSet.call(s), c.tests = {}, m = f.radixPoint ? o.determineNewCaretPosition.call(s, {
begin: 0,
end: 0
}, !1, !1 === f.__financeInput ? "radixFocus" : void 0).begin : 0, c.p = m, s.caretPos = {
begin: m
};
var y = [], b = s.caretPos;
if (h.forEach((function(e, t) {
if (void 0 !== e) {
var a = new d.Event("_checkval");
a.keyCode = e.toString().charCodeAt(0), v += e;
var n = o.getLastValidPosition.call(s, void 0, !0);
!function(e, t) {
for (var i = r.getMaskTemplate.call(s, !0, 0).slice(e, o.seekNext.call(s, e, !1, !1)).join("").replace(/'/g, ""), a = i.indexOf(t); a > 0 && " " === i[a - 1]; ) a--;
var n = 0 === a && !o.isMask.call(s, e) && (r.getTest.call(s, e).match.nativeDef === t.charAt(0) || !0 === r.getTest.call(s, e).match.static && r.getTest.call(s, e).match.nativeDef === "'" + t.charAt(0) || " " === r.getTest.call(s, e).match.nativeDef && (r.getTest.call(s, e + 1).match.nativeDef === t.charAt(0) || !0 === r.getTest.call(s, e + 1).match.static && r.getTest.call(s, e + 1).match.nativeDef === "'" + t.charAt(0)));
if (!n && a > 0 && !o.isMask.call(s, e, !1, !0)) {
var l = o.seekNext.call(s, e);
s.caretPos.begin < l && (s.caretPos = {
begin: l
});
}
return n;
}(m, v) ? (g = u.EventHandlers.keypressEvent.call(s, a, !0, !1, i, s.caretPos.begin)) && (m = s.caretPos.begin + 1,
v = "") : g = u.EventHandlers.keypressEvent.call(s, a, !0, !1, i, n + 1), g ? (void 0 !== g.pos && c.validPositions[g.pos] && !0 === c.validPositions[g.pos].match.static && void 0 === c.validPositions[g.pos].alternation && (y.push(g.pos),
s.isRTL || (g.forwardPosition = g.pos + 1)), p.call(s, void 0, o.getBuffer.call(s), g.forwardPosition, a, !1),
s.caretPos = {
begin: g.forwardPosition,
end: g.forwardPosition
}, b = s.caretPos) : void 0 === c.validPositions[t] && h[t] === r.getPlaceholder.call(s, t) && o.isMask.call(s, t, !0) ? s.caretPos.begin++ : s.caretPos = b;
}
})), y.length > 0) {
var x, P, E = o.seekNext.call(s, -1, void 0, !1);
if (!l.isComplete.call(s, o.getBuffer.call(s)) && y.length <= E || l.isComplete.call(s, o.getBuffer.call(s)) && y.length > 0 && y.length !== E && 0 === y[0]) for (var S = E; void 0 !== (x = y.shift()); ) {
var _ = new d.Event("_checkval");
if ((P = c.validPositions[x]).generatedInput = !0, _.keyCode = P.input.charCodeAt(0),
(g = u.EventHandlers.keypressEvent.call(s, _, !0, !1, i, S)) && void 0 !== g.pos && g.pos !== x && c.validPositions[g.pos] && !0 === c.validPositions[g.pos].match.static) y.push(g.pos); else if (!g) break;
S++;
}
}
t && p.call(s, e, o.getBuffer.call(s), g ? g.forwardPosition : s.caretPos.begin, n || new d.Event("checkval"), n && ("input" === n.type && s.undoValue !== o.getBuffer.call(s).join("") || "paste" === n.type)),
f.skipOptionalPartCharacter = k;
}
function p(e, t, i, a, r) {
var s = e ? e.inputmask : this, u = s.opts, c = s.dependencyLib;
if (a && "function" == typeof u.onBeforeWrite) {
var f = u.onBeforeWrite.call(s, a, t, i, u);
if (f) {
if (f.refreshFromBuffer) {
var d = f.refreshFromBuffer;
l.refreshFromBuffer.call(s, !0 === d ? d : d.start, d.end, f.buffer || t), t = o.getBuffer.call(s, !0);
}
void 0 !== i && (i = void 0 !== f.caret ? f.caret : i);
}
}
if (void 0 !== e && (e.inputmask._valueSet(t.join("")), void 0 === i || void 0 !== a && "blur" === a.type || o.caret.call(s, e, i, void 0, void 0, void 0 !== a && "keydown" === a.type && (a.keyCode === n.default.DELETE || a.keyCode === n.default.BACKSPACE)),
!0 === r)) {
var p = c(e), h = e.inputmask._valueGet();
e.inputmask.skipInputEvent = !0, p.trigger("input"), setTimeout((function() {
h === o.getBufferTemplate.call(s).join("") ? p.trigger("cleared") : !0 === l.isComplete.call(s, t) && p.trigger("complete");
}), 0);
}
}
},
2394: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0, i(7149), i(3194);
var a = i(157), n = m(i(4963)), r = m(i(9380)), o = i(2391), l = i(4713), s = i(8711), u = i(7215), c = i(7760), f = i(9716), d = m(i(7392)), p = m(i(3976)), h = m(i(8741));
function v(e) {
return v = "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;
}, v(e);
}
function m(e) {
return e && e.__esModule ? e : {
default: e
};
}
var g = r.default.document, k = "_inputmask_opts";
function y(e, t, i) {
if (h.default) {
if (!(this instanceof y)) return new y(e, t, i);
this.dependencyLib = n.default, this.el = void 0, this.events = {}, this.maskset = void 0,
!0 !== i && ("[object Object]" === Object.prototype.toString.call(e) ? t = e : (t = t || {},
e && (t.alias = e)), this.opts = n.default.extend(!0, {}, this.defaults, t), this.noMasksCache = t && void 0 !== t.definitions,
this.userOptions = t || {}, b(this.opts.alias, t, this.opts)), this.refreshValue = !1,
this.undoValue = void 0, this.$el = void 0, this.skipKeyPressEvent = !1, this.skipInputEvent = !1,
this.validationEvent = !1, this.ignorable = !1, this.maxLength, this.mouseEnter = !1,
this.originalPlaceholder = void 0, this.isComposing = !1;
}
}
function b(e, t, i) {
var a = y.prototype.aliases[e];
return a ? (a.alias && b(a.alias, void 0, i), n.default.extend(!0, i, a), n.default.extend(!0, i, t),
!0) : (null === i.mask && (i.mask = e), !1);
}
y.prototype = {
dataAttribute: "data-inputmask",
defaults: p.default,
definitions: d.default,
aliases: {},
masksCache: {},
get isRTL() {
return this.opts.isRTL || this.opts.numericInput;
},
mask: function(e) {
var t = this;
return "string" == typeof e && (e = g.getElementById(e) || g.querySelectorAll(e)),
(e = e.nodeName ? [ e ] : Array.isArray(e) ? e : Array.from(e)).forEach((function(e, i) {
var l = n.default.extend(!0, {}, t.opts);
if (function(e, t, i, a) {
function o(t, n) {
var o = "" === a ? t : a + "-" + t;
null !== (n = void 0 !== n ? n : e.getAttribute(o)) && ("string" == typeof n && (0 === t.indexOf("on") ? n = r.default[n] : "false" === n ? n = !1 : "true" === n && (n = !0)),
i[t] = n);
}
if (!0 === t.importDataAttributes) {
var l, s, u, c, f = e.getAttribute(a);
if (f && "" !== f && (f = f.replace(/'/g, '"'), s = JSON.parse("{" + f + "}")),
s) for (c in u = void 0, s) if ("alias" === c.toLowerCase()) {
u = s[c];
break;
}
for (l in o("alias", u), i.alias && b(i.alias, i, t), t) {
if (s) for (c in u = void 0, s) if (c.toLowerCase() === l.toLowerCase()) {
u = s[c];
break;
}
o(l, u);
}
}
n.default.extend(!0, t, i), ("rtl" === e.dir || t.rightAlign) && (e.style.textAlign = "right");
("rtl" === e.dir || t.numericInput) && (e.dir = "ltr", e.removeAttribute("dir"),
t.isRTL = !0);
return Object.keys(i).length;
}(e, l, n.default.extend(!0, {}, t.userOptions), t.dataAttribute)) {
var s = (0, o.generateMaskSet)(l, t.noMasksCache);
void 0 !== s && (void 0 !== e.inputmask && (e.inputmask.opts.autoUnmask = !0, e.inputmask.remove()),
e.inputmask = new y(void 0, void 0, !0), e.inputmask.opts = l, e.inputmask.noMasksCache = t.noMasksCache,
e.inputmask.userOptions = n.default.extend(!0, {}, t.userOptions), e.inputmask.el = e,
e.inputmask.$el = (0, n.default)(e), e.inputmask.maskset = s, n.default.data(e, k, t.userOptions),
a.mask.call(e.inputmask));
}
})), e && e[0] && e[0].inputmask || this;
},
option: function(e, t) {
return "string" == typeof e ? this.opts[e] : "object" === v(e) ? (n.default.extend(this.userOptions, e),
this.el && !0 !== t && this.mask(this.el), this) : void 0;
},
unmaskedvalue: function(e) {
if (this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
void 0 === this.el || void 0 !== e) {
var t = ("function" == typeof this.opts.onBeforeMask && this.opts.onBeforeMask.call(this, e, this.opts) || e).split("");
c.checkVal.call(this, void 0, !1, !1, t), "function" == typeof this.opts.onBeforeWrite && this.opts.onBeforeWrite.call(this, void 0, s.getBuffer.call(this), 0, this.opts);
}
return c.unmaskedvalue.call(this, this.el);
},
remove: function() {
if (this.el) {
n.default.data(this.el, k, null);
var e = this.opts.autoUnmask ? (0, c.unmaskedvalue)(this.el) : this._valueGet(this.opts.autoUnmask);
e !== s.getBufferTemplate.call(this).join("") ? this._valueSet(e, this.opts.autoUnmask) : this._valueSet(""),
f.EventRuler.off(this.el), Object.getOwnPropertyDescriptor && Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.el), "value") && this.__valueGet && Object.defineProperty(this.el, "value", {
get: this.__valueGet,
set: this.__valueSet,
configurable: !0
}) : g.__lookupGetter__ && this.el.__lookupGetter__("value") && this.__valueGet && (this.el.__defineGetter__("value", this.__valueGet),
this.el.__defineSetter__("value", this.__valueSet)), this.el.inputmask = void 0;
}
return this.el;
},
getemptymask: function() {
return this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
s.getBufferTemplate.call(this).join("");
},
hasMaskedValue: function() {
return !this.opts.autoUnmask;
},
isComplete: function() {
return this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
u.isComplete.call(this, s.getBuffer.call(this));
},
getmetadata: function() {
if (this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
Array.isArray(this.maskset.metadata)) {
var e = l.getMaskTemplate.call(this, !0, 0, !1).join("");
return this.maskset.metadata.forEach((function(t) {
return t.mask !== e || (e = t, !1);
})), e;
}
return this.maskset.metadata;
},
isValid: function(e) {
if (this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
e) {
var t = ("function" == typeof this.opts.onBeforeMask && this.opts.onBeforeMask.call(this, e, this.opts) || e).split("");
c.checkVal.call(this, void 0, !0, !1, t);
} else e = this.isRTL ? s.getBuffer.call(this).slice().reverse().join("") : s.getBuffer.call(this).join("");
for (var i = s.getBuffer.call(this), a = s.determineLastRequiredPosition.call(this), n = i.length - 1; n > a && !s.isMask.call(this, n); n--) ;
return i.splice(a, n + 1 - a), u.isComplete.call(this, i) && e === (this.isRTL ? s.getBuffer.call(this).slice().reverse().join("") : s.getBuffer.call(this).join(""));
},
format: function(e, t) {
this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache);
var i = ("function" == typeof this.opts.onBeforeMask && this.opts.onBeforeMask.call(this, e, this.opts) || e).split("");
c.checkVal.call(this, void 0, !0, !1, i);
var a = this.isRTL ? s.getBuffer.call(this).slice().reverse().join("") : s.getBuffer.call(this).join("");
return t ? {
value: a,
metadata: this.getmetadata()
} : a;
},
setValue: function(e) {
this.el && (0, n.default)(this.el).trigger("setvalue", [ e ]);
},
analyseMask: o.analyseMask
}, y.extendDefaults = function(e) {
n.default.extend(!0, y.prototype.defaults, e);
}, y.extendDefinitions = function(e) {
n.default.extend(!0, y.prototype.definitions, e);
}, y.extendAliases = function(e) {
n.default.extend(!0, y.prototype.aliases, e);
}, y.format = function(e, t, i) {
return y(t).format(e, i);
}, y.unmask = function(e, t) {
return y(t).unmaskedvalue(e);
}, y.isValid = function(e, t) {
return y(t).isValid(e);
}, y.remove = function(e) {
"string" == typeof e && (e = g.getElementById(e) || g.querySelectorAll(e)), (e = e.nodeName ? [ e ] : e).forEach((function(e) {
e.inputmask && e.inputmask.remove();
}));
}, y.setValue = function(e, t) {
"string" == typeof e && (e = g.getElementById(e) || g.querySelectorAll(e)), (e = e.nodeName ? [ e ] : e).forEach((function(e) {
e.inputmask ? e.inputmask.setValue(t) : (0, n.default)(e).trigger("setvalue", [ t ]);
}));
}, y.dependencyLib = n.default, r.default.Inputmask = y;
var x = y;
t.default = x;
},
5296: function(e, t, i) {
function a(e) {
return a = "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;
}, a(e);
}
var n = h(i(9380)), r = h(i(2394)), o = h(i(8741));
function l(e, t) {
for (var i = 0; i < t.length; i++) {
var a = t[i];
a.enumerable = a.enumerable || !1, a.configurable = !0, "value" in a && (a.writable = !0),
Object.defineProperty(e, a.key, a);
}
}
function s(e, t) {
if (t && ("object" === a(t) || "function" == typeof t)) return t;
if (void 0 !== t) throw new TypeError("Derived constructors may only return object or undefined");
return function(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e;
}(e);
}
function u(e) {
var t = "function" == typeof Map ? new Map : void 0;
return u = function(e) {
if (null === e || (i = e, -1 === Function.toString.call(i).indexOf("[native code]"))) return e;
var i;
if ("function" != typeof e) throw new TypeError("Super expression must either be null or a function");
if (void 0 !== t) {
if (t.has(e)) return t.get(e);
t.set(e, a);
}
function a() {
return c(e, arguments, p(this).constructor);
}
return a.prototype = Object.create(e.prototype, {
constructor: {
value: a,
enumerable: !1,
writable: !0,
configurable: !0
}
}), d(a, e);
}, u(e);
}
function c(e, t, i) {
return c = f() ? Reflect.construct : function(e, t, i) {
var a = [ null ];
a.push.apply(a, t);
var n = new (Function.bind.apply(e, a));
return i && d(n, i.prototype), n;
}, c.apply(null, arguments);
}
function f() {
if ("undefined" == typeof Reflect || !Reflect.construct) return !1;
if (Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], (function() {}))),
!0;
} catch (e) {
return !1;
}
}
function d(e, t) {
return d = Object.setPrototypeOf || function(e, t) {
return e.__proto__ = t, e;
}, d(e, t);
}
function p(e) {
return p = Object.setPrototypeOf ? Object.getPrototypeOf : function(e) {
return e.__proto__ || Object.getPrototypeOf(e);
}, p(e);
}
function h(e) {
return e && e.__esModule ? e : {
default: e
};
}
var v = n.default.document;
if (o.default && v && v.head && v.head.attachShadow && n.default.customElements && void 0 === n.default.customElements.get("input-mask")) {
var m = function(e) {
!function(e, t) {
if ("function" != typeof t && null !== t) throw new TypeError("Super expression must either be null or a function");
Object.defineProperty(e, "prototype", {
value: Object.create(t && t.prototype, {
constructor: {
value: e,
writable: !0,
configurable: !0
}
}),
writable: !1
}), t && d(e, t);
}(c, e);
var t, i, a, n, o, u = (t = c, i = f(), function() {
var e, a = p(t);
if (i) {
var n = p(this).constructor;
e = Reflect.construct(a, arguments, n);
} else e = a.apply(this, arguments);
return s(this, e);
});
function c() {
var e;
!function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, c);
var t = (e = u.call(this)).getAttributeNames(), i = e.attachShadow({
mode: "closed"
}), a = v.createElement("input");
for (var n in a.type = "text", i.appendChild(a), t) Object.prototype.hasOwnProperty.call(t, n) && a.setAttribute(t[n], e.getAttribute(t[n]));
var o = new r.default;
return o.dataAttribute = "", o.mask(a), a.inputmask.shadowRoot = i, e;
}
return a = c, n && l(a.prototype, n), o && l(a, o), Object.defineProperty(a, "prototype", {
writable: !1
}), a;
}(u(HTMLElement));
n.default.customElements.define("input-mask", m);
}
},
2391: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.analyseMask = function(e, t, i) {
var a, o, l, s, u, c, f = /(?:[?*+]|\{[0-9+*]+(?:,[0-9+*]*)?(?:\|[0-9+*]*)?\})|[^.?*+^${[]()|\\]+|./g, d = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, p = !1, h = new n.default, v = [], m = [], g = !1;
function k(e, a, n) {
n = void 0 !== n ? n : e.matches.length;
var o = e.matches[n - 1];
if (t) 0 === a.indexOf("[") || p && /\\d|\\s|\\w/i.test(a) || "." === a ? e.matches.splice(n++, 0, {
fn: new RegExp(a, i.casing ? "i" : ""),
static: !1,
optionality: !1,
newBlockMarker: void 0 === o ? "master" : o.def !== a,
casing: null,
def: a,
placeholder: void 0,
nativeDef: a
}) : (p && (a = a[a.length - 1]), a.split("").forEach((function(t, a) {
o = e.matches[n - 1], e.matches.splice(n++, 0, {
fn: /[a-z]/i.test(i.staticDefinitionSymbol || t) ? new RegExp("[" + (i.staticDefinitionSymbol || t) + "]", i.casing ? "i" : "") : null,
static: !0,
optionality: !1,
newBlockMarker: void 0 === o ? "master" : o.def !== t && !0 !== o.static,
casing: null,
def: i.staticDefinitionSymbol || t,
placeholder: void 0 !== i.staticDefinitionSymbol ? t : void 0,
nativeDef: (p ? "'" : "") + t
});
}))), p = !1; else {
var l = i.definitions && i.definitions[a] || i.usePrototypeDefinitions && r.default.prototype.definitions[a];
l && !p ? e.matches.splice(n++, 0, {
fn: l.validator ? "string" == typeof l.validator ? new RegExp(l.validator, i.casing ? "i" : "") : new function() {
this.test = l.validator;
} : new RegExp("."),
static: l.static || !1,
optionality: l.optional || !1,
newBlockMarker: void 0 === o || l.optional ? "master" : o.def !== (l.definitionSymbol || a),
casing: l.casing,
def: l.definitionSymbol || a,
placeholder: l.placeholder,
nativeDef: a,
generated: l.generated
}) : (e.matches.splice(n++, 0, {
fn: /[a-z]/i.test(i.staticDefinitionSymbol || a) ? new RegExp("[" + (i.staticDefinitionSymbol || a) + "]", i.casing ? "i" : "") : null,
static: !0,
optionality: !1,
newBlockMarker: void 0 === o ? "master" : o.def !== a && !0 !== o.static,
casing: null,
def: i.staticDefinitionSymbol || a,
placeholder: void 0 !== i.staticDefinitionSymbol ? a : void 0,
nativeDef: (p ? "'" : "") + a
}), p = !1);
}
}
function y() {
if (v.length > 0) {
if (k(s = v[v.length - 1], o), s.isAlternator) {
u = v.pop();
for (var e = 0; e < u.matches.length; e++) u.matches[e].isGroup && (u.matches[e].isGroup = !1);
v.length > 0 ? (s = v[v.length - 1]).matches.push(u) : h.matches.push(u);
}
} else k(h, o);
}
function b(e) {
var t = new n.default(!0);
return t.openGroup = !1, t.matches = e, t;
}
function x() {
if ((l = v.pop()).openGroup = !1, void 0 !== l) if (v.length > 0) {
if ((s = v[v.length - 1]).matches.push(l), s.isAlternator) {
for (var e = (u = v.pop()).matches[0].matches ? u.matches[0].matches.length : 1, t = 0; t < u.matches.length; t++) u.matches[t].isGroup = !1,
u.matches[t].alternatorGroup = !1, null === i.keepStatic && e < (u.matches[t].matches ? u.matches[t].matches.length : 1) && (i.keepStatic = !0),
e = u.matches[t].matches ? u.matches[t].matches.length : 1;
v.length > 0 ? (s = v[v.length - 1]).matches.push(u) : h.matches.push(u);
}
} else h.matches.push(l); else y();
}
function P(e) {
var t = e.pop();
return t.isQuantifier && (t = b([ e.pop(), t ])), t;
}
t && (i.optionalmarker[0] = void 0, i.optionalmarker[1] = void 0);
for (;a = t ? d.exec(e) : f.exec(e); ) {
if (o = a[0], t) {
switch (o.charAt(0)) {
case "?":
o = "{0,1}";
break;
case "+":
case "*":
o = "{" + o + "}";
break;
case "|":
if (0 === v.length) {
var E = b(h.matches);
E.openGroup = !0, v.push(E), h.matches = [], g = !0;
}
}
if ("\\d" === o) o = "[0-9]";
}
if (p) y(); else switch (o.charAt(0)) {
case "$":
case "^":
t || y();
break;
case i.escapeChar:
p = !0, t && y();
break;
case i.optionalmarker[1]:
case i.groupmarker[1]:
x();
break;
case i.optionalmarker[0]:
v.push(new n.default(!1, !0));
break;
case i.groupmarker[0]:
v.push(new n.default(!0));
break;
case i.quantifiermarker[0]:
var S = new n.default(!1, !1, !0), _ = (o = o.replace(/[{}?]/g, "")).split("|"), w = _[0].split(","), M = isNaN(w[0]) ? w[0] : parseInt(w[0]), O = 1 === w.length ? M : isNaN(w[1]) ? w[1] : parseInt(w[1]), T = isNaN(_[1]) ? _[1] : parseInt(_[1]);
"*" !== M && "+" !== M || (M = "*" === O ? 0 : 1), S.quantifier = {
min: M,
max: O,
jit: T
};
var C = v.length > 0 ? v[v.length - 1].matches : h.matches;
if ((a = C.pop()).isAlternator) {
C.push(a), C = a.matches;
var A = new n.default(!0), D = C.pop();
C.push(A), C = A.matches, a = D;
}
a.isGroup || (a = b([ a ])), C.push(a), C.push(S);
break;
case i.alternatormarker:
if (v.length > 0) {
var j = (s = v[v.length - 1]).matches[s.matches.length - 1];
c = s.openGroup && (void 0 === j.matches || !1 === j.isGroup && !1 === j.isAlternator) ? v.pop() : P(s.matches);
} else c = P(h.matches);
if (c.isAlternator) v.push(c); else if (c.alternatorGroup ? (u = v.pop(), c.alternatorGroup = !1) : u = new n.default(!1, !1, !1, !0),
u.matches.push(c), v.push(u), c.openGroup) {
c.openGroup = !1;
var B = new n.default(!0);
B.alternatorGroup = !0, v.push(B);
}
break;
default:
y();
}
}
g && x();
for (;v.length > 0; ) l = v.pop(), h.matches.push(l);
h.matches.length > 0 && (!function e(a) {
a && a.matches && a.matches.forEach((function(n, r) {
var o = a.matches[r + 1];
(void 0 === o || void 0 === o.matches || !1 === o.isQuantifier) && n && n.isGroup && (n.isGroup = !1,
t || (k(n, i.groupmarker[0], 0), !0 !== n.openGroup && k(n, i.groupmarker[1]))),
e(n);
}));
}(h), m.push(h));
(i.numericInput || i.isRTL) && function e(t) {
for (var a in t.matches = t.matches.reverse(), t.matches) if (Object.prototype.hasOwnProperty.call(t.matches, a)) {
var n = parseInt(a);
if (t.matches[a].isQuantifier && t.matches[n + 1] && t.matches[n + 1].isGroup) {
var r = t.matches[a];
t.matches.splice(a, 1), t.matches.splice(n + 1, 0, r);
}
void 0 !== t.matches[a].matches ? t.matches[a] = e(t.matches[a]) : t.matches[a] = ((o = t.matches[a]) === i.optionalmarker[0] ? o = i.optionalmarker[1] : o === i.optionalmarker[1] ? o = i.optionalmarker[0] : o === i.groupmarker[0] ? o = i.groupmarker[1] : o === i.groupmarker[1] && (o = i.groupmarker[0]),
o);
}
var o;
return t;
}(m[0]);
return m;
}, t.generateMaskSet = function(e, t) {
var i;
function n(e, i, n) {
var o, l, s = !1;
if (null !== e && "" !== e || ((s = null !== n.regex) ? e = (e = n.regex).replace(/^(\^)(.*)(\$)$/, "$2") : (s = !0,
e = ".*")), 1 === e.length && !1 === n.greedy && 0 !== n.repeat && (n.placeholder = ""),
n.repeat > 0 || "*" === n.repeat || "+" === n.repeat) {
var u = "*" === n.repeat ? 0 : "+" === n.repeat ? 1 : n.repeat;
e = n.groupmarker[0] + e + n.groupmarker[1] + n.quantifiermarker[0] + u + "," + n.repeat + n.quantifiermarker[1];
}
return l = s ? "regex_" + n.regex : n.numericInput ? e.split("").reverse().join("") : e,
null !== n.keepStatic && (l = "ks_" + n.keepStatic + l), void 0 === r.default.prototype.masksCache[l] || !0 === t ? (o = {
mask: e,
maskToken: r.default.prototype.analyseMask(e, s, n),
validPositions: {},
_buffer: void 0,
buffer: void 0,
tests: {},
excludes: {},
metadata: i,
maskLength: void 0,
jitOffset: {}
}, !0 !== t && (r.default.prototype.masksCache[l] = o, o = a.default.extend(!0, {}, r.default.prototype.masksCache[l]))) : o = a.default.extend(!0, {}, r.default.prototype.masksCache[l]),
o;
}
"function" == typeof e.mask && (e.mask = e.mask(e));
if (Array.isArray(e.mask)) {
if (e.mask.length > 1) {
null === e.keepStatic && (e.keepStatic = !0);
var o = e.groupmarker[0];
return (e.isRTL ? e.mask.reverse() : e.mask).forEach((function(t) {
o.length > 1 && (o += e.alternatormarker), void 0 !== t.mask && "function" != typeof t.mask ? o += t.mask : o += t;
})), n(o += e.groupmarker[1], e.mask, e);
}
e.mask = e.mask.pop();
}
i = e.mask && void 0 !== e.mask.mask && "function" != typeof e.mask.mask ? n(e.mask.mask, e.mask, e) : n(e.mask, e.mask, e);
null === e.keepStatic && (e.keepStatic = !1);
return i;
};
var a = o(i(4963)), n = o(i(9695)), r = o(i(2394));
function o(e) {
return e && e.__esModule ? e : {
default: e
};
}
},
157: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.mask = function() {
var e = this, t = this.opts, i = this.el, a = this.dependencyLib;
l.EventRuler.off(i);
var f = function(t, i) {
"textarea" !== t.tagName.toLowerCase() && i.ignorables.push(n.default.ENTER);
var s = t.getAttribute("type"), u = "input" === t.tagName.toLowerCase() && i.supportsInputType.includes(s) || t.isContentEditable || "textarea" === t.tagName.toLowerCase();
if (!u) if ("input" === t.tagName.toLowerCase()) {
var c = document.createElement("input");
c.setAttribute("type", s), u = "text" === c.type, c = null;
} else u = "partial";
return !1 !== u ? function(t) {
var n, s;
function u() {
return this.inputmask ? this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : -1 !== r.getLastValidPosition.call(e) || !0 !== i.nullable ? (this.inputmask.shadowRoot || this.ownerDocument).activeElement === this && i.clearMaskOnLostFocus ? (e.isRTL ? o.clearOptionalTail.call(e, r.getBuffer.call(e).slice()).reverse() : o.clearOptionalTail.call(e, r.getBuffer.call(e).slice())).join("") : n.call(this) : "" : n.call(this);
}
function c(e) {
s.call(this, e), this.inputmask && (0, o.applyInputValue)(this, e);
}
if (!t.inputmask.__valueGet) {
if (!0 !== i.noValuePatching) {
if (Object.getOwnPropertyDescriptor) {
var f = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t), "value") : void 0;
f && f.get && f.set ? (n = f.get, s = f.set, Object.defineProperty(t, "value", {
get: u,
set: c,
configurable: !0
})) : "input" !== t.tagName.toLowerCase() && (n = function() {
return this.textContent;
}, s = function(e) {
this.textContent = e;
}, Object.defineProperty(t, "value", {
get: u,
set: c,
configurable: !0
}));
} else document.__lookupGetter__ && t.__lookupGetter__("value") && (n = t.__lookupGetter__("value"),
s = t.__lookupSetter__("value"), t.__defineGetter__("value", u), t.__defineSetter__("value", c));
t.inputmask.__valueGet = n, t.inputmask.__valueSet = s;
}
t.inputmask._valueGet = function(t) {
return e.isRTL && !0 !== t ? n.call(this.el).split("").reverse().join("") : n.call(this.el);
}, t.inputmask._valueSet = function(t, i) {
s.call(this.el, null == t ? "" : !0 !== i && e.isRTL ? t.split("").reverse().join("") : t);
}, void 0 === n && (n = function() {
return this.value;
}, s = function(e) {
this.value = e;
}, function(t) {
if (a.valHooks && (void 0 === a.valHooks[t] || !0 !== a.valHooks[t].inputmaskpatch)) {
var n = a.valHooks[t] && a.valHooks[t].get ? a.valHooks[t].get : function(e) {
return e.value;
}, l = a.valHooks[t] && a.valHooks[t].set ? a.valHooks[t].set : function(e, t) {
return e.value = t, e;
};
a.valHooks[t] = {
get: function(t) {
if (t.inputmask) {
if (t.inputmask.opts.autoUnmask) return t.inputmask.unmaskedvalue();
var a = n(t);
return -1 !== r.getLastValidPosition.call(e, void 0, void 0, t.inputmask.maskset.validPositions) || !0 !== i.nullable ? a : "";
}
return n(t);
},
set: function(e, t) {
var i = l(e, t);
return e.inputmask && (0, o.applyInputValue)(e, t), i;
},
inputmaskpatch: !0
};
}
}(t.type), function(t) {
l.EventRuler.on(t, "mouseenter", (function() {
var t = this.inputmask._valueGet(!0);
t !== (e.isRTL ? r.getBuffer.call(e).reverse() : r.getBuffer.call(e)).join("") && (0,
o.applyInputValue)(this, t);
}));
}(t));
}
}(t) : t.inputmask = void 0, u;
}(i, t);
if (!1 !== f) {
e.originalPlaceholder = i.placeholder, e.maxLength = void 0 !== i ? i.maxLength : void 0,
-1 === e.maxLength && (e.maxLength = void 0), "inputMode" in i && null === i.getAttribute("inputmode") && (i.inputMode = t.inputmode,
i.setAttribute("inputmode", t.inputmode)), !0 === f && (t.showMaskOnFocus = t.showMaskOnFocus && -1 === [ "cc-number", "cc-exp" ].indexOf(i.autocomplete),
s.iphone && (t.insertModeVisual = !1), l.EventRuler.on(i, "submit", c.EventHandlers.submitEvent),
l.EventRuler.on(i, "reset", c.EventHandlers.resetEvent), l.EventRuler.on(i, "blur", c.EventHandlers.blurEvent),
l.EventRuler.on(i, "focus", c.EventHandlers.focusEvent), l.EventRuler.on(i, "invalid", c.EventHandlers.invalidEvent),
l.EventRuler.on(i, "click", c.EventHandlers.clickEvent), l.EventRuler.on(i, "mouseleave", c.EventHandlers.mouseleaveEvent),
l.EventRuler.on(i, "mouseenter", c.EventHandlers.mouseenterEvent), l.EventRuler.on(i, "paste", c.EventHandlers.pasteEvent),
l.EventRuler.on(i, "cut", c.EventHandlers.cutEvent), l.EventRuler.on(i, "complete", t.oncomplete),
l.EventRuler.on(i, "incomplete", t.onincomplete), l.EventRuler.on(i, "cleared", t.oncleared),
!0 !== t.inputEventOnly && (l.EventRuler.on(i, "keydown", c.EventHandlers.keydownEvent),
l.EventRuler.on(i, "keypress", c.EventHandlers.keypressEvent), l.EventRuler.on(i, "keyup", c.EventHandlers.keyupEvent)),
(s.mobile || t.inputEventOnly) && i.removeAttribute("maxLength"), l.EventRuler.on(i, "input", c.EventHandlers.inputFallBackEvent),
l.EventRuler.on(i, "compositionend", c.EventHandlers.compositionendEvent)), l.EventRuler.on(i, "setvalue", c.EventHandlers.setValueEvent),
r.getBufferTemplate.call(e).join(""), e.undoValue = e._valueGet(!0);
var d = (i.inputmask.shadowRoot || i.ownerDocument).activeElement;
if ("" !== i.inputmask._valueGet(!0) || !1 === t.clearMaskOnLostFocus || d === i) {
(0, o.applyInputValue)(i, i.inputmask._valueGet(!0), t);
var p = r.getBuffer.call(e).slice();
!1 === u.isComplete.call(e, p) && t.clearIncomplete && r.resetMaskSet.call(e), t.clearMaskOnLostFocus && d !== i && (-1 === r.getLastValidPosition.call(e) ? p = [] : o.clearOptionalTail.call(e, p)),
(!1 === t.clearMaskOnLostFocus || t.showMaskOnFocus && d === i || "" !== i.inputmask._valueGet(!0)) && (0,
o.writeBuffer)(i, p), d === i && r.caret.call(e, i, r.seekNext.call(e, r.getLastValidPosition.call(e)));
}
}
};
var a, n = (a = i(5581)) && a.__esModule ? a : {
default: a
}, r = i(8711), o = i(7760), l = i(9716), s = i(9845), u = i(7215), c = i(6030);
},
9695: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = function(e, t, i, a) {
this.matches = [], this.openGroup = e || !1, this.alternatorGroup = !1, this.isGroup = e || !1,
this.isOptional = t || !1, this.isQuantifier = i || !1, this.isAlternator = a || !1,
this.quantifier = {
min: 1,
max: 1
};
};
},
3194: function() {
Array.prototype.includes || Object.defineProperty(Array.prototype, "includes", {
value: function(e, t) {
if (null == this) throw new TypeError('"this" is null or not defined');
var i = Object(this), a = i.length >>> 0;
if (0 === a) return !1;
for (var n = 0 | t, r = Math.max(n >= 0 ? n : a - Math.abs(n), 0); r < a; ) {
if (i[r] === e) return !0;
r++;
}
return !1;
}
});
},
7149: function() {
function e(t) {
return e = "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;
}, e(t);
}
"function" != typeof Object.getPrototypeOf && (Object.getPrototypeOf = "object" === e("test".__proto__) ? function(e) {
return e.__proto__;
} : function(e) {
return e.constructor.prototype;
});
},
8711: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.caret = function(e, t, i, a, n) {
var r, o = this, l = this.opts;
if (void 0 === t) return "selectionStart" in e && "selectionEnd" in e ? (t = e.selectionStart,
i = e.selectionEnd) : window.getSelection ? (r = window.getSelection().getRangeAt(0)).commonAncestorContainer.parentNode !== e && r.commonAncestorContainer !== e || (t = r.startOffset,
i = r.endOffset) : document.selection && document.selection.createRange && (r = document.selection.createRange(),
t = 0 - r.duplicate().moveStart("character", -e.inputmask._valueGet().length), i = t + r.text.length),
{
begin: a ? t : u.call(o, t),
end: a ? i : u.call(o, i)
};
if (Array.isArray(t) && (i = o.isRTL ? t[0] : t[1], t = o.isRTL ? t[1] : t[0]),
void 0 !== t.begin && (i = o.isRTL ? t.begin : t.end, t = o.isRTL ? t.end : t.begin),
"number" == typeof t) {
t = a ? t : u.call(o, t), i = "number" == typeof (i = a ? i : u.call(o, i)) ? i : t;
var s = parseInt(((e.ownerDocument.defaultView || window).getComputedStyle ? (e.ownerDocument.defaultView || window).getComputedStyle(e, null) : e.currentStyle).fontSize) * i;
if (e.scrollLeft = s > e.scrollWidth ? s : 0, e.inputmask.caretPos = {
begin: t,
end: i
}, l.insertModeVisual && !1 === l.insertMode && t === i && (n || i++), e === (e.inputmask.shadowRoot || e.ownerDocument).activeElement) if ("setSelectionRange" in e) e.setSelectionRange(t, i); else if (window.getSelection) {
if (r = document.createRange(), void 0 === e.firstChild || null === e.firstChild) {
var c = document.createTextNode("");
e.appendChild(c);
}
r.setStart(e.firstChild, t < e.inputmask._valueGet().length ? t : e.inputmask._valueGet().length),
r.setEnd(e.firstChild, i < e.inputmask._valueGet().length ? i : e.inputmask._valueGet().length),
r.collapse(!0);
var f = window.getSelection();
f.removeAllRanges(), f.addRange(r);
} else e.createTextRange && ((r = e.createTextRange()).collapse(!0), r.moveEnd("character", i),
r.moveStart("character", t), r.select());
}
}, t.determineLastRequiredPosition = function(e) {
var t, i, r = this, l = this.maskset, s = this.dependencyLib, u = a.getMaskTemplate.call(r, !0, o.call(r), !0, !0), c = u.length, f = o.call(r), d = {}, p = l.validPositions[f], h = void 0 !== p ? p.locator.slice() : void 0;
for (t = f + 1; t < u.length; t++) i = a.getTestTemplate.call(r, t, h, t - 1), h = i.locator.slice(),
d[t] = s.extend(!0, {}, i);
var v = p && void 0 !== p.alternation ? p.locator[p.alternation] : void 0;
for (t = c - 1; t > f && (((i = d[t]).match.optionality || i.match.optionalQuantifier && i.match.newBlockMarker || v && (v !== d[t].locator[p.alternation] && 1 != i.match.static || !0 === i.match.static && i.locator[p.alternation] && n.checkAlternationMatch.call(r, i.locator[p.alternation].toString().split(","), v.toString().split(",")) && "" !== a.getTests.call(r, t)[0].def)) && u[t] === a.getPlaceholder.call(r, t, i.match)); t--) c--;
return e ? {
l: c,
def: d[c] ? d[c].match : void 0
} : c;
}, t.determineNewCaretPosition = function(e, t, i) {
var n = this, u = this.maskset, c = this.opts;
t && (n.isRTL ? e.end = e.begin : e.begin = e.end);
if (e.begin === e.end) {
switch (i = i || c.positionCaretOnClick) {
case "none":
break;
case "select":
e = {
begin: 0,
end: r.call(n).length
};
break;
case "ignore":
e.end = e.begin = s.call(n, o.call(n));
break;
case "radixFocus":
if (function(e) {
if ("" !== c.radixPoint && 0 !== c.digits) {
var t = u.validPositions;
if (void 0 === t[e] || t[e].input === a.getPlaceholder.call(n, e)) {
if (e < s.call(n, -1)) return !0;
var i = r.call(n).indexOf(c.radixPoint);
if (-1 !== i) {
for (var o in t) if (t[o] && i < o && t[o].input !== a.getPlaceholder.call(n, o)) return !1;
return !0;
}
}
}
return !1;
}(e.begin)) {
var f = r.call(n).join("").indexOf(c.radixPoint);
e.end = e.begin = c.numericInput ? s.call(n, f) : f;
break;
}
default:
var d = e.begin, p = o.call(n, d, !0), h = s.call(n, -1 !== p || l.call(n, 0) ? p : -1);
if (d <= h) e.end = e.begin = l.call(n, d, !1, !0) ? d : s.call(n, d); else {
var v = u.validPositions[p], m = a.getTestTemplate.call(n, h, v ? v.match.locator : void 0, v), g = a.getPlaceholder.call(n, h, m.match);
if ("" !== g && r.call(n)[h] !== g && !0 !== m.match.optionalQuantifier && !0 !== m.match.newBlockMarker || !l.call(n, h, c.keepStatic, !0) && m.match.def === g) {
var k = s.call(n, h);
(d >= k || d === h) && (h = k);
}
e.end = e.begin = h;
}
}
return e;
}
}, t.getBuffer = r, t.getBufferTemplate = function() {
var e = this.maskset;
void 0 === e._buffer && (e._buffer = a.getMaskTemplate.call(this, !1, 1), void 0 === e.buffer && (e.buffer = e._buffer.slice()));
return e._buffer;
}, t.getLastValidPosition = o, t.isMask = l, t.resetMaskSet = function(e) {
var t = this.maskset;
t.buffer = void 0, !0 !== e && (t.validPositions = {}, t.p = 0);
}, t.seekNext = s, t.seekPrevious = function(e, t) {
var i = this, n = e - 1;
if (e <= 0) return 0;
for (;n > 0 && (!0 === t && (!0 !== a.getTest.call(i, n).match.newBlockMarker || !l.call(i, n, void 0, !0)) || !0 !== t && !l.call(i, n, void 0, !0)); ) n--;
return n;
}, t.translatePosition = u;
var a = i(4713), n = i(7215);
function r(e) {
var t = this.maskset;
return void 0 !== t.buffer && !0 !== e || (t.buffer = a.getMaskTemplate.call(this, !0, o.call(this), !0),
void 0 === t._buffer && (t._buffer = t.buffer.slice())), t.buffer;
}
function o(e, t, i) {
var a = this.maskset, n = -1, r = -1, o = i || a.validPositions;
for (var l in void 0 === e && (e = -1), o) {
var s = parseInt(l);
o[s] && (t || !0 !== o[s].generatedInput) && (s <= e && (n = s), s >= e && (r = s));
}
return -1 === n || n == e ? r : -1 == r || e - n < r - e ? n : r;
}
function l(e, t, i) {
var n = this, r = this.maskset, o = a.getTestTemplate.call(n, e).match;
if ("" === o.def && (o = a.getTest.call(n, e).match), !0 !== o.static) return o.fn;
if (!0 === i && void 0 !== r.validPositions[e] && !0 !== r.validPositions[e].generatedInput) return !0;
if (!0 !== t && e > -1) {
if (i) {
var l = a.getTests.call(n, e);
return l.length > 1 + ("" === l[l.length - 1].match.def ? 1 : 0);
}
var s = a.determineTestTemplate.call(n, e, a.getTests.call(n, e)), u = a.getPlaceholder.call(n, e, s.match);
return s.match.def !== u;
}
return !1;
}
function s(e, t, i) {
var n = this;
void 0 === i && (i = !0);
for (var r = e + 1; "" !== a.getTest.call(n, r).match.def && (!0 === t && (!0 !== a.getTest.call(n, r).match.newBlockMarker || !l.call(n, r, void 0, !0)) || !0 !== t && !l.call(n, r, void 0, i)); ) r++;
return r;
}
function u(e) {
var t = this.opts, i = this.el;
return !this.isRTL || "number" != typeof e || t.greedy && "" === t.placeholder || !i || (e = Math.abs(this._valueGet().length - e)),
e;
}
},
4713: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.determineTestTemplate = u, t.getDecisionTaker = o, t.getMaskTemplate = function(e, t, i, a, n) {
var r = this, o = this.opts, c = this.maskset, f = o.greedy;
n && o.greedy && (o.greedy = !1, r.maskset.tests = {});
t = t || 0;
var p, h, v, m, g = [], k = 0;
do {
if (!0 === e && c.validPositions[k]) v = n && c.validPositions[k].match.optionality && void 0 === c.validPositions[k + 1] && (!0 === c.validPositions[k].generatedInput || c.validPositions[k].input == o.skipOptionalPartCharacter && k > 0) ? u.call(r, k, d.call(r, k, p, k - 1)) : c.validPositions[k],
h = v.match, p = v.locator.slice(), g.push(!0 === i ? v.input : !1 === i ? h.nativeDef : l.call(r, k, h)); else {
v = s.call(r, k, p, k - 1), h = v.match, p = v.locator.slice();
var y = !0 !== a && (!1 !== o.jitMasking ? o.jitMasking : h.jit);
(m = (m && h.static && h.def !== o.groupSeparator && null === h.fn || c.validPositions[k - 1] && h.static && h.def !== o.groupSeparator && null === h.fn) && c.tests[k] && 1 === c.tests[k].length) || !1 === y || void 0 === y || "number" == typeof y && isFinite(y) && y > k ? g.push(!1 === i ? h.nativeDef : l.call(r, k, h)) : m = !1;
}
k++;
} while (!0 !== h.static || "" !== h.def || t > k);
"" === g[g.length - 1] && g.pop();
!1 === i && void 0 !== c.maskLength || (c.maskLength = k - 1);
return o.greedy = f, g;
}, t.getPlaceholder = l, t.getTest = c, t.getTestTemplate = s, t.getTests = d, t.isSubsetOf = f;
var a, n = (a = i(2394)) && a.__esModule ? a : {
default: a
};
function r(e, t) {
var i = (null != e.alternation ? e.mloc[o(e)] : e.locator).join("");
if ("" !== i) for (;i.length < t; ) i += "0";
return i;
}
function o(e) {
var t = e.locator[e.alternation];
return "string" == typeof t && t.length > 0 && (t = t.split(",")[0]), void 0 !== t ? t.toString() : "";
}
function l(e, t, i) {
var a = this.opts, n = this.maskset;
if (void 0 !== (t = t || c.call(this, e).match).placeholder || !0 === i) return "function" == typeof t.placeholder ? t.placeholder(a) : t.placeholder;
if (!0 === t.static) {
if (e > -1 && void 0 === n.validPositions[e]) {
var r, o = d.call(this, e), l = [];
if (o.length > 1 + ("" === o[o.length - 1].match.def ? 1 : 0)) for (var s = 0; s < o.length; s++) if ("" !== o[s].match.def && !0 !== o[s].match.optionality && !0 !== o[s].match.optionalQuantifier && (!0 === o[s].match.static || void 0 === r || !1 !== o[s].match.fn.test(r.match.def, n, e, !0, a)) && (l.push(o[s]),
!0 === o[s].match.static && (r = o[s]), l.length > 1 && /[0-9a-bA-Z]/.test(l[0].match.def))) return a.placeholder.charAt(e % a.placeholder.length);
}
return t.def;
}
return a.placeholder.charAt(e % a.placeholder.length);
}
function s(e, t, i) {
return this.maskset.validPositions[e] || u.call(this, e, d.call(this, e, t ? t.slice() : t, i));
}
function u(e, t) {
var i = this.opts, a = function(e, t) {
var i = 0, a = !1;
t.forEach((function(e) {
e.match.optionality && (0 !== i && i !== e.match.optionality && (a = !0), (0 === i || i > e.match.optionality) && (i = e.match.optionality));
})), i && (0 == e || 1 == t.length ? i = 0 : a || (i = 0));
return i;
}(e, t);
e = e > 0 ? e - 1 : 0;
var n, o, l, s = r(c.call(this, e));
i.greedy && t.length > 1 && "" === t[t.length - 1].match.def && t.pop();
for (var u = 0; u < t.length; u++) {
var f = t[u];
n = r(f, s.length);
var d = Math.abs(n - s);
(void 0 === o || "" !== n && d < o || l && !i.greedy && l.match.optionality && l.match.optionality - a > 0 && "master" === l.match.newBlockMarker && (!f.match.optionality || f.match.optionality - a < 1 || !f.match.newBlockMarker) || l && !i.greedy && l.match.optionalQuantifier && !f.match.optionalQuantifier) && (o = d,
l = f);
}
return l;
}
function c(e, t) {
var i = this.maskset;
return i.validPositions[e] ? i.validPositions[e] : (t || d.call(this, e))[0];
}
function f(e, t, i) {
function a(e) {
for (var t, i = [], a = -1, n = 0, r = e.length; n < r; n++) if ("-" === e.charAt(n)) for (t = e.charCodeAt(n + 1); ++a < t; ) i.push(String.fromCharCode(a)); else a = e.charCodeAt(n),
i.push(e.charAt(n));
return i.join("");
}
return e.match.def === t.match.nativeDef || !(!(i.regex || e.match.fn instanceof RegExp && t.match.fn instanceof RegExp) || !0 === e.match.static || !0 === t.match.static) && -1 !== a(t.match.fn.toString().replace(/[[\]/]/g, "")).indexOf(a(e.match.fn.toString().replace(/[[\]/]/g, "")));
}
function d(e, t, i) {
var a, r, o = this, l = this.dependencyLib, s = this.maskset, c = this.opts, d = this.el, p = s.maskToken, h = t ? i : 0, v = t ? t.slice() : [ 0 ], m = [], g = !1, k = t ? t.join("") : "";
function y(t, i, r, o) {
function l(r, o, u) {
function p(e, t) {
var i = 0 === t.matches.indexOf(e);
return i || t.matches.every((function(a, n) {
return !0 === a.isQuantifier ? i = p(e, t.matches[n - 1]) : Object.prototype.hasOwnProperty.call(a, "matches") && (i = p(e, a)),
!i;
})), i;
}
function v(e, t, i) {
var a, n;
if ((s.tests[e] || s.validPositions[e]) && (s.tests[e] || [ s.validPositions[e] ]).every((function(e, r) {
if (e.mloc[t]) return a = e, !1;
var o = void 0 !== i ? i : e.alternation, l = void 0 !== e.locator[o] ? e.locator[o].toString().indexOf(t) : -1;
return (void 0 === n || l < n) && -1 !== l && (a = e, n = l), !0;
})), a) {
var r = a.locator[a.alternation];
return (a.mloc[t] || a.mloc[r] || a.locator).slice((void 0 !== i ? i : a.alternation) + 1);
}
return void 0 !== i ? v(e, t) : void 0;
}
function b(e, t) {
var i = e.alternation, a = void 0 === t || i === t.alternation && -1 === e.locator[i].toString().indexOf(t.locator[i]);
if (!a && i > t.alternation) for (var n = t.alternation; n < i; n++) if (e.locator[n] !== t.locator[n]) {
i = n, a = !0;
break;
}
if (a) {
e.mloc = e.mloc || {};
var r = e.locator[i];
if (void 0 !== r) {
if ("string" == typeof r && (r = r.split(",")[0]), void 0 === e.mloc[r] && (e.mloc[r] = e.locator.slice()),
void 0 !== t) {
for (var o in t.mloc) "string" == typeof o && (o = o.split(",")[0]), void 0 === e.mloc[o] && (e.mloc[o] = t.mloc[o]);
e.locator[i] = Object.keys(e.mloc).join(",");
}
return !0;
}
e.alternation = void 0;
}
return !1;
}
function x(e, t) {
if (e.locator.length !== t.locator.length) return !1;
for (var i = e.alternation + 1; i < e.locator.length; i++) if (e.locator[i] !== t.locator[i]) return !1;
return !0;
}
if (h > e + c._maxTestPos) throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + s.mask;
if (h === e && void 0 === r.matches) {
if (m.push({
match: r,
locator: o.reverse(),
cd: k,
mloc: {}
}), !r.optionality || void 0 !== u || !(c.definitions && c.definitions[r.nativeDef] && c.definitions[r.nativeDef].optional || n.default.prototype.definitions[r.nativeDef] && n.default.prototype.definitions[r.nativeDef].optional)) return !0;
g = !0, h = e;
} else if (void 0 !== r.matches) {
if (r.isGroup && u !== r) {
if (r = l(t.matches[t.matches.indexOf(r) + 1], o, u)) return !0;
} else if (r.isOptional) {
var P = r, E = m.length;
if (r = y(r, i, o, u)) {
if (m.forEach((function(e, t) {
t >= E && (e.match.optionality = e.match.optionality ? e.match.optionality + 1 : 1);
})), a = m[m.length - 1].match, void 0 !== u || !p(a, P)) return !0;
g = !0, h = e;
}
} else if (r.isAlternator) {
var S, _ = r, w = [], M = m.slice(), O = o.length, T = !1, C = i.length > 0 ? i.shift() : -1;
if (-1 === C || "string" == typeof C) {
var A, D = h, j = i.slice(), B = [];
if ("string" == typeof C) B = C.split(","); else for (A = 0; A < _.matches.length; A++) B.push(A.toString());
if (void 0 !== s.excludes[e]) {
for (var R = B.slice(), L = 0, I = s.excludes[e].length; L < I; L++) {
var F = s.excludes[e][L].toString().split(":");
o.length == F[1] && B.splice(B.indexOf(F[0]), 1);
}
0 === B.length && (delete s.excludes[e], B = R);
}
(!0 === c.keepStatic || isFinite(parseInt(c.keepStatic)) && D >= c.keepStatic) && (B = B.slice(0, 1));
for (var N = 0; N < B.length; N++) {
A = parseInt(B[N]), m = [], i = "string" == typeof C && v(h, A, O) || j.slice();
var V = _.matches[A];
if (V && l(V, [ A ].concat(o), u)) r = !0; else if (0 === N && (T = !0), V && V.matches && V.matches.length > _.matches[0].matches.length) break;
S = m.slice(), h = D, m = [];
for (var G = 0; G < S.length; G++) {
var H = S[G], K = !1;
H.match.jit = H.match.jit || T, H.alternation = H.alternation || O, b(H);
for (var U = 0; U < w.length; U++) {
var $ = w[U];
if ("string" != typeof C || void 0 !== H.alternation && B.includes(H.locator[H.alternation].toString())) {
if (H.match.nativeDef === $.match.nativeDef) {
K = !0, b($, H);
break;
}
if (f(H, $, c)) {
b(H, $) && (K = !0, w.splice(w.indexOf($), 0, H));
break;
}
if (f($, H, c)) {
b($, H);
break;
}
if (Z = $, !0 === (Q = H).match.static && !0 !== Z.match.static && Z.match.fn.test(Q.match.def, s, e, !1, c, !1)) {
x(H, $) || void 0 !== d.inputmask.userOptions.keepStatic ? b(H, $) && (K = !0, w.splice(w.indexOf($), 0, H)) : c.keepStatic = !0;
break;
}
}
}
K || w.push(H);
}
}
m = M.concat(w), h = e, g = m.length > 0, r = w.length > 0, i = j.slice();
} else r = l(_.matches[C] || t.matches[C], [ C ].concat(o), u);
if (r) return !0;
} else if (r.isQuantifier && u !== t.matches[t.matches.indexOf(r) - 1]) for (var q = r, z = i.length > 0 ? i.shift() : 0; z < (isNaN(q.quantifier.max) ? z + 1 : q.quantifier.max) && h <= e; z++) {
var W = t.matches[t.matches.indexOf(q) - 1];
if (r = l(W, [ z ].concat(o), W)) {
if ((a = m[m.length - 1].match).optionalQuantifier = z >= q.quantifier.min, a.jit = (z + 1) * (W.matches.indexOf(a) + 1) > q.quantifier.jit,
a.optionalQuantifier && p(a, W)) {
g = !0, h = e;
break;
}
return a.jit && (s.jitOffset[e] = W.matches.length - W.matches.indexOf(a)), !0;
}
} else if (r = y(r, i, o, u)) return !0;
} else h++;
var Q, Z;
}
for (var u = i.length > 0 ? i.shift() : 0; u < t.matches.length; u++) if (!0 !== t.matches[u].isQuantifier) {
var p = l(t.matches[u], [ u ].concat(r), o);
if (p && h === e) return p;
if (h > e) break;
}
}
if (e > -1) {
if (void 0 === t) {
for (var b, x = e - 1; void 0 === (b = s.validPositions[x] || s.tests[x]) && x > -1; ) x--;
void 0 !== b && x > -1 && (v = function(e, t) {
var i, a = [];
return Array.isArray(t) || (t = [ t ]), t.length > 0 && (void 0 === t[0].alternation || !0 === c.keepStatic ? 0 === (a = u.call(o, e, t.slice()).locator.slice()).length && (a = t[0].locator.slice()) : t.forEach((function(e) {
"" !== e.def && (0 === a.length ? (i = e.alternation, a = e.locator.slice()) : e.locator[i] && -1 === a[i].toString().indexOf(e.locator[i]) && (a[i] += "," + e.locator[i]));
}))), a;
}(x, b), k = v.join(""), h = x);
}
if (s.tests[e] && s.tests[e][0].cd === k) return s.tests[e];
for (var P = v.shift(); P < p.length; P++) {
if (y(p[P], v, [ P ]) && h === e || h > e) break;
}
}
return (0 === m.length || g) && m.push({
match: {
fn: null,
static: !0,
optionality: !1,
casing: null,
def: "",
placeholder: ""
},
locator: [],
mloc: {},
cd: k
}), void 0 !== t && s.tests[e] ? r = l.extend(!0, [], m) : (s.tests[e] = l.extend(!0, [], m),
r = s.tests[e]), m.forEach((function(e) {
e.match.optionality = !1;
})), r;
}
},
7215: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.alternate = s, t.checkAlternationMatch = function(e, t, i) {
for (var a, n = this.opts.greedy ? t : t.slice(0, 1), r = !1, o = void 0 !== i ? i.split(",") : [], l = 0; l < o.length; l++) -1 !== (a = e.indexOf(o[l])) && e.splice(a, 1);
for (var s = 0; s < e.length; s++) if (n.includes(e[s])) {
r = !0;
break;
}
return r;
}, t.handleRemove = function(e, t, i, a, l) {
var u = this, c = this.maskset, f = this.opts;
if ((f.numericInput || u.isRTL) && (t === r.default.BACKSPACE ? t = r.default.DELETE : t === r.default.DELETE && (t = r.default.BACKSPACE),
u.isRTL)) {
var d = i.end;
i.end = i.begin, i.begin = d;
}
var p, h = o.getLastValidPosition.call(u, void 0, !0);
i.end >= o.getBuffer.call(u).length && h >= i.end && (i.end = h + 1);
t === r.default.BACKSPACE ? i.end - i.begin < 1 && (i.begin = o.seekPrevious.call(u, i.begin)) : t === r.default.DELETE && i.begin === i.end && (i.end = o.isMask.call(u, i.end, !0, !0) ? i.end + 1 : o.seekNext.call(u, i.end) + 1);
if (!1 !== (p = m.call(u, i))) {
if (!0 !== a && !1 !== f.keepStatic || null !== f.regex && -1 !== n.getTest.call(u, i.begin).match.def.indexOf("|")) {
var v = s.call(u, !0);
if (v) {
var g = void 0 !== v.caret ? v.caret : v.pos ? o.seekNext.call(u, v.pos.begin ? v.pos.begin : v.pos) : o.getLastValidPosition.call(u, -1, !0);
(t !== r.default.DELETE || i.begin > g) && i.begin;
}
}
!0 !== a && (c.p = t === r.default.DELETE ? i.begin + p : i.begin, c.p = o.determineNewCaretPosition.call(u, {
begin: c.p,
end: c.p
}, !1, !1 === f.insertMode && t === r.default.BACKSPACE ? "none" : void 0).begin);
}
}, t.isComplete = c, t.isSelection = f, t.isValid = d, t.refreshFromBuffer = h,
t.revalidateMask = m;
var a, n = i(4713), r = (a = i(5581)) && a.__esModule ? a : {
default: a
}, o = i(8711), l = i(6030);
function s(e, t, i, a, r, l) {
var u, c, f, p, h, v, m, g, k, y, b, x = this, P = this.dependencyLib, E = this.opts, S = x.maskset, _ = P.extend(!0, {}, S.validPositions), w = P.extend(!0, {}, S.tests), M = !1, O = !1, T = void 0 !== r ? r : o.getLastValidPosition.call(x);
if (l && (y = l.begin, b = l.end, l.begin > l.end && (y = l.end, b = l.begin)),
-1 === T && void 0 === r) u = 0, c = (p = n.getTest.call(x, u)).alternation; else for (;T >= 0; T--) if ((f = S.validPositions[T]) && void 0 !== f.alternation) {
if (p && p.locator[f.alternation] !== f.locator[f.alternation]) break;
u = T, c = S.validPositions[u].alternation, p = f;
}
if (void 0 !== c) {
m = parseInt(u), S.excludes[m] = S.excludes[m] || [], !0 !== e && S.excludes[m].push((0,
n.getDecisionTaker)(p) + ":" + p.alternation);
var C = [], A = -1;
for (h = m; h < o.getLastValidPosition.call(x, void 0, !0) + 1; h++) -1 === A && e <= h && void 0 !== t && (C.push(t),
A = C.length - 1), (v = S.validPositions[h]) && !0 !== v.generatedInput && (void 0 === l || h < y || h >= b) && C.push(v.input),
delete S.validPositions[h];
for (-1 === A && void 0 !== t && (C.push(t), A = C.length - 1); void 0 !== S.excludes[m] && S.excludes[m].length < 10; ) {
for (S.tests = {}, o.resetMaskSet.call(x, !0), M = !0, h = 0; h < C.length && (g = M.caret || o.getLastValidPosition.call(x, void 0, !0) + 1,
k = C[h], M = d.call(x, g, k, !1, a, !0)); h++) h === A && (O = M), 1 == e && M && (O = {
caretPos: h
});
if (M) break;
if (o.resetMaskSet.call(x), p = n.getTest.call(x, m), S.validPositions = P.extend(!0, {}, _),
S.tests = P.extend(!0, {}, w), !S.excludes[m]) {
O = s.call(x, e, t, i, a, m - 1, l);
break;
}
var D = (0, n.getDecisionTaker)(p);
if (-1 !== S.excludes[m].indexOf(D + ":" + p.alternation)) {
O = s.call(x, e, t, i, a, m - 1, l);
break;
}
for (S.excludes[m].push(D + ":" + p.alternation), h = m; h < o.getLastValidPosition.call(x, void 0, !0) + 1; h++) delete S.validPositions[h];
}
}
return O && !1 === E.keepStatic || delete S.excludes[m], O;
}
function u(e, t, i) {
var a = this.opts, n = this.maskset;
switch (a.casing || t.casing) {
case "upper":
e = e.toUpperCase();
break;
case "lower":
e = e.toLowerCase();
break;
case "title":
var o = n.validPositions[i - 1];
e = 0 === i || o && o.input === String.fromCharCode(r.default.SPACE) ? e.toUpperCase() : e.toLowerCase();
break;
default:
if ("function" == typeof a.casing) {
var l = Array.prototype.slice.call(arguments);
l.push(n.validPositions), e = a.casing.apply(this, l);
}
}
return e;
}
function c(e) {
var t = this, i = this.opts, a = this.maskset;
if ("function" == typeof i.isComplete) return i.isComplete(e, i);
if ("*" !== i.repeat) {
var r = !1, l = o.determineLastRequiredPosition.call(t, !0), s = o.seekPrevious.call(t, l.l);
if (void 0 === l.def || l.def.newBlockMarker || l.def.optionality || l.def.optionalQuantifier) {
r = !0;
for (var u = 0; u <= s; u++) {
var c = n.getTestTemplate.call(t, u).match;
if (!0 !== c.static && void 0 === a.validPositions[u] && !0 !== c.optionality && !0 !== c.optionalQuantifier || !0 === c.static && e[u] !== n.getPlaceholder.call(t, u, c)) {
r = !1;
break;
}
}
}
return r;
}
}
function f(e) {
var t = this.opts.insertMode ? 0 : 1;
return this.isRTL ? e.begin - e.end > t : e.end - e.begin > t;
}
function d(e, t, i, a, r, l, p) {
var g = this, k = this.dependencyLib, y = this.opts, b = g.maskset;
i = !0 === i;
var x = e;
function P(e) {
if (void 0 !== e) {
if (void 0 !== e.remove && (Array.isArray(e.remove) || (e.remove = [ e.remove ]),
e.remove.sort((function(e, t) {
return t.pos - e.pos;
})).forEach((function(e) {
m.call(g, {
begin: e,
end: e + 1
});
})), e.remove = void 0), void 0 !== e.insert && (Array.isArray(e.insert) || (e.insert = [ e.insert ]),
e.insert.sort((function(e, t) {
return e.pos - t.pos;
})).forEach((function(e) {
"" !== e.c && d.call(g, e.pos, e.c, void 0 === e.strict || e.strict, void 0 !== e.fromIsValid ? e.fromIsValid : a);
})), e.insert = void 0), e.refreshFromBuffer && e.buffer) {
var t = e.refreshFromBuffer;
h.call(g, !0 === t ? t : t.start, t.end, e.buffer), e.refreshFromBuffer = void 0;
}
void 0 !== e.rewritePosition && (x = e.rewritePosition, e = !0);
}
return e;
}
function E(t, i, r) {
var l = !1;
return n.getTests.call(g, t).every((function(s, c) {
var d = s.match;
if (o.getBuffer.call(g, !0), !1 !== (l = (!d.jit || void 0 !== b.validPositions[o.seekPrevious.call(g, t)]) && (null != d.fn ? d.fn.test(i, b, t, r, y, f.call(g, e)) : (i === d.def || i === y.skipOptionalPartCharacter) && "" !== d.def && {
c: n.getPlaceholder.call(g, t, d, !0) || d.def,
pos: t
}))) {
var p = void 0 !== l.c ? l.c : i, h = t;
return p = p === y.skipOptionalPartCharacter && !0 === d.static ? n.getPlaceholder.call(g, t, d, !0) || d.def : p,
!0 !== (l = P(l)) && void 0 !== l.pos && l.pos !== t && (h = l.pos), !0 !== l && void 0 === l.pos && void 0 === l.c ? !1 : (!1 === m.call(g, e, k.extend({}, s, {
input: u.call(g, p, d, h)
}), a, h) && (l = !1), !1);
}
return !0;
})), l;
}
void 0 !== e.begin && (x = g.isRTL ? e.end : e.begin);
var S = !0, _ = k.extend(!0, {}, b.validPositions);
if (!1 === y.keepStatic && void 0 !== b.excludes[x] && !0 !== r && !0 !== a) for (var w = x; w < (g.isRTL ? e.begin : e.end); w++) void 0 !== b.excludes[w] && (b.excludes[w] = void 0,
delete b.tests[w]);
if ("function" == typeof y.preValidation && !0 !== a && !0 !== l && (S = P(S = y.preValidation.call(g, o.getBuffer.call(g), x, t, f.call(g, e), y, b, e, i || r))),
!0 === S) {
if (S = E(x, t, i), (!i || !0 === a) && !1 === S && !0 !== l) {
var M = b.validPositions[x];
if (!M || !0 !== M.match.static || M.match.def !== t && t !== y.skipOptionalPartCharacter) {
if (y.insertMode || void 0 === b.validPositions[o.seekNext.call(g, x)] || e.end > x) {
var O = !1;
if (b.jitOffset[x] && void 0 === b.validPositions[o.seekNext.call(g, x)] && !1 !== (S = d.call(g, x + b.jitOffset[x], t, !0, !0)) && (!0 !== r && (S.caret = x),
O = !0), e.end > x && (b.validPositions[x] = void 0), !O && !o.isMask.call(g, x, y.keepStatic && 0 === x)) for (var T = x + 1, C = o.seekNext.call(g, x, !1, 0 !== x); T <= C; T++) if (!1 !== (S = E(T, t, i))) {
S = v.call(g, x, void 0 !== S.pos ? S.pos : T) || S, x = T;
break;
}
}
} else S = {
caret: o.seekNext.call(g, x)
};
}
!1 !== S || !y.keepStatic || !c.call(g, o.getBuffer.call(g)) && 0 !== x || i || !0 === r ? f.call(g, e) && b.tests[x] && b.tests[x].length > 1 && y.keepStatic && !i && !0 !== r && (S = s.call(g, !0)) : S = s.call(g, x, t, i, a, void 0, e),
!0 === S && (S = {
pos: x
});
}
if ("function" == typeof y.postValidation && !0 !== a && !0 !== l) {
var A = y.postValidation.call(g, o.getBuffer.call(g, !0), void 0 !== e.begin ? g.isRTL ? e.end : e.begin : e, t, S, y, b, i, p);
void 0 !== A && (S = !0 === A ? S : A);
}
S && void 0 === S.pos && (S.pos = x), !1 === S || !0 === l ? (o.resetMaskSet.call(g, !0),
b.validPositions = k.extend(!0, {}, _)) : v.call(g, void 0, x, !0);
var D = P(S);
void 0 !== g.maxLength && (o.getBuffer.call(g).length > g.maxLength && !a && (o.resetMaskSet.call(g, !0),
b.validPositions = k.extend(!0, {}, _), D = !1));
return D;
}
function p(e, t, i) {
for (var a = this.maskset, r = !1, o = n.getTests.call(this, e), l = 0; l < o.length; l++) {
if (o[l].match && (o[l].match.nativeDef === t.match[i.shiftPositions ? "def" : "nativeDef"] && (!i.shiftPositions || !t.match.static) || o[l].match.nativeDef === t.match.nativeDef || i.regex && !o[l].match.static && o[l].match.fn.test(t.input))) {
r = !0;
break;
}
if (o[l].match && o[l].match.def === t.match.nativeDef) {
r = void 0;
break;
}
}
return !1 === r && void 0 !== a.jitOffset[e] && (r = p.call(this, e + a.jitOffset[e], t, i)),
r;
}
function h(e, t, i) {
var a, n, r = this, s = this.maskset, u = this.opts, c = this.dependencyLib, f = u.skipOptionalPartCharacter, d = r.isRTL ? i.slice().reverse() : i;
if (u.skipOptionalPartCharacter = "", !0 === e) o.resetMaskSet.call(r), s.tests = {},
e = 0, t = i.length, n = o.determineNewCaretPosition.call(r, {
begin: 0,
end: 0
}, !1).begin; else {
for (a = e; a < t; a++) delete s.validPositions[a];
n = e;
}
var p = new c.Event("keypress");
for (a = e; a < t; a++) {
p.keyCode = d[a].toString().charCodeAt(0), r.ignorable = !1;
var h = l.EventHandlers.keypressEvent.call(r, p, !0, !1, !1, n);
!1 !== h && void 0 !== h && (n = h.forwardPosition);
}
u.skipOptionalPartCharacter = f;
}
function v(e, t, i) {
var a = this, r = this.maskset, l = this.dependencyLib;
if (void 0 === e) for (e = t - 1; e > 0 && !r.validPositions[e]; e--) ;
for (var s = e; s < t; s++) {
if (void 0 === r.validPositions[s] && !o.isMask.call(a, s, !1)) if (0 == s ? n.getTest.call(a, s) : r.validPositions[s - 1]) {
var u = n.getTests.call(a, s).slice();
"" === u[u.length - 1].match.def && u.pop();
var c, f = n.determineTestTemplate.call(a, s, u);
if (f && (!0 !== f.match.jit || "master" === f.match.newBlockMarker && (c = r.validPositions[s + 1]) && !0 === c.match.optionalQuantifier) && ((f = l.extend({}, f, {
input: n.getPlaceholder.call(a, s, f.match, !0) || f.match.def
})).generatedInput = !0, m.call(a, s, f, !0), !0 !== i)) {
var p = r.validPositions[t].input;
return r.validPositions[t] = void 0, d.call(a, t, p, !0, !0);
}
}
}
}
function m(e, t, i, a) {
var r = this, l = this.maskset, s = this.opts, u = this.dependencyLib;
function c(e, t, i) {
var a = t[e];
if (void 0 !== a && !0 === a.match.static && !0 !== a.match.optionality && (void 0 === t[0] || void 0 === t[0].alternation)) {
var n = i.begin <= e - 1 ? t[e - 1] && !0 === t[e - 1].match.static && t[e - 1] : t[e - 1], r = i.end > e + 1 ? t[e + 1] && !0 === t[e + 1].match.static && t[e + 1] : t[e + 1];
return n && r;
}
return !1;
}
var f = 0, h = void 0 !== e.begin ? e.begin : e, v = void 0 !== e.end ? e.end : e, m = !0;
if (e.begin > e.end && (h = e.end, v = e.begin), a = void 0 !== a ? a : h, h !== v || s.insertMode && void 0 !== l.validPositions[a] && void 0 === i || void 0 === t || t.match.optionalQuantifier || t.match.optionality) {
var g, k = u.extend(!0, {}, l.validPositions), y = o.getLastValidPosition.call(r, void 0, !0);
for (l.p = h, g = y; g >= h; g--) delete l.validPositions[g], void 0 === t && delete l.tests[g + 1];
var b, x, P = a, E = P;
for (t && (l.validPositions[a] = u.extend(!0, {}, t), E++, P++), g = t ? v : v - 1; g <= y; g++) {
if (void 0 !== (b = k[g]) && !0 !== b.generatedInput && (g >= v || g >= h && c(g, k, {
begin: h,
end: v
}))) {
for (;"" !== n.getTest.call(r, E).match.def; ) {
if (!1 !== (x = p.call(r, E, b, s)) || "+" === b.match.def) {
"+" === b.match.def && o.getBuffer.call(r, !0);
var S = d.call(r, E, b.input, "+" !== b.match.def, !0);
if (m = !1 !== S, P = (S.pos || E) + 1, !m && x) break;
} else m = !1;
if (m) {
void 0 === t && b.match.static && g === e.begin && f++;
break;
}
if (!m && o.getBuffer.call(r), E > l.maskLength) break;
E++;
}
"" == n.getTest.call(r, E).match.def && (m = !1), E = P;
}
if (!m) break;
}
if (!m) return l.validPositions = u.extend(!0, {}, k), o.resetMaskSet.call(r, !0),
!1;
} else t && n.getTest.call(r, a).match.cd === t.match.cd && (l.validPositions[a] = u.extend(!0, {}, t));
return o.resetMaskSet.call(r, !0), f;
}
},
5581: function(e) {
e.exports = JSON.parse('{"BACKSPACE":8,"BACKSPACE_SAFARI":127,"DELETE":46,"DOWN":40,"END":35,"ENTER":13,"ESCAPE":27,"HOME":36,"INSERT":45,"LEFT":37,"PAGE_DOWN":34,"PAGE_UP":33,"RIGHT":39,"SPACE":32,"TAB":9,"UP":38,"X":88,"Z":90,"CONTROL":17,"PAUSE/BREAK":19,"WINDOWS_LEFT":91,"WINDOWS_RIGHT":92,"KEY_229":229}');
}
}, t = {};
function i(a) {
var n = t[a];
if (void 0 !== n) return n.exports;
var r = t[a] = {
exports: {}
};
return e[a](r, r.exports, i), r.exports;
}
var a = {};
return function() {
var e, t = a;
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0, i(3851), i(219), i(207), i(5296);
var n = ((e = i(2394)) && e.__esModule ? e : {
default: e
}).default;
t.default = n;
}(), a;
}();
}));
|
294coder/Efficient-MIF
| 5,365 |
utils/sharpening_index/imresize.py
|
"""
Python Code on GitHub: https://codeload.github.com/fatheral/matlab_imresize/zip/master
MIT License
Copyright (c) 2020 Alex
"""
from __future__ import print_function
import numpy as np
from math import ceil, floor
def deriveSizeFromScale(img_shape, scale):
output_shape = []
for k in range(2):
output_shape.append(int(ceil(scale[k] * img_shape[k])))
return output_shape
def deriveScaleFromSize(img_shape_in, img_shape_out):
scale = []
for k in range(2):
scale.append(1.0 * img_shape_out[k] / img_shape_in[k])
return scale
def triangle(x):
x = np.array(x).astype(np.float64)
lessthanzero = np.logical_and((x>=-1),x<0)
greaterthanzero = np.logical_and((x<=1),x>=0)
f = np.multiply((x+1),lessthanzero) + np.multiply((1-x),greaterthanzero)
return f
def cubic(x):
x = np.array(x).astype(np.float64)
absx = np.absolute(x)
absx2 = np.multiply(absx, absx)
absx3 = np.multiply(absx2, absx)
f = np.multiply(1.5*absx3 - 2.5*absx2 + 1, absx <= 1) + np.multiply(-0.5*absx3 + 2.5*absx2 - 4*absx + 2, (1 < absx) & (absx <= 2))
return f
def contributions(in_length, out_length, scale, kernel, k_width):
if scale < 1:
h = lambda x: scale * kernel(scale * x)
kernel_width = 1.0 * k_width / scale
else:
h = kernel
kernel_width = k_width
x = np.arange(1, out_length+1).astype(np.float64)
u = x / scale + 0.5 * (1 - 1 / scale)
left = np.floor(u - kernel_width / 2)
P = int(ceil(kernel_width)) + 2
ind = np.expand_dims(left, axis=1) + np.arange(P) - 1 # -1 because indexing from 0
indices = ind.astype(np.int32)
weights = h(np.expand_dims(u, axis=1) - indices - 1) # -1 because indexing from 0
weights = np.divide(weights, np.expand_dims(np.sum(weights, axis=1), axis=1))
aux = np.concatenate((np.arange(in_length), np.arange(in_length - 1, -1, step=-1))).astype(np.int32)
indices = aux[np.mod(indices, aux.size)]
ind2store = np.nonzero(np.any(weights, axis=0))
weights = weights[:, ind2store]
indices = indices[:, ind2store]
return weights, indices
def imresizemex(inimg, weights, indices, dim):
in_shape = inimg.shape
w_shape = weights.shape
out_shape = list(in_shape)
out_shape[dim] = w_shape[0]
outimg = np.zeros(out_shape)
if dim == 0:
for i_img in range(in_shape[1]):
for i_w in range(w_shape[0]):
w = weights[i_w, :]
ind = indices[i_w, :]
im_slice = inimg[ind, i_img].astype(np.float64)
outimg[i_w, i_img] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
elif dim == 1:
for i_img in range(in_shape[0]):
for i_w in range(w_shape[0]):
w = weights[i_w, :]
ind = indices[i_w, :]
im_slice = inimg[i_img, ind].astype(np.float64)
outimg[i_img, i_w] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
if inimg.dtype == np.uint8:
outimg = np.clip(outimg, 0, 255)
return np.around(outimg).astype(np.uint8)
else:
return outimg
def imresizevec(inimg, weights, indices, dim):
wshape = weights.shape
if dim == 0:
weights = weights.reshape((wshape[0], wshape[2], 1, 1))
outimg = np.sum(weights*((inimg[indices].squeeze(axis=1)).astype(np.float64)), axis=1)
elif dim == 1:
weights = weights.reshape((1, wshape[0], wshape[2], 1))
outimg = np.sum(weights*((inimg[:, indices].squeeze(axis=2)).astype(np.float64)), axis=2)
if inimg.dtype == np.uint8:
outimg = np.clip(outimg, 0, 255)
return np.around(outimg).astype(np.uint8)
else:
return outimg
def resizeAlongDim(A, dim, weights, indices, mode="vec"):
if mode == "org":
out = imresizemex(A, weights, indices, dim)
else:
out = imresizevec(A, weights, indices, dim)
return out
def imresize(I, scalar_scale=None, method='bicubic', output_shape=None, mode="vec"):
if method == 'bicubic':
kernel = cubic
elif method == 'bilinear':
kernel = triangle
else:
print ('Error: Unidentified method supplied')
kernel_width = 4.0
# Fill scale and output_size
if scalar_scale is not None:
scalar_scale = float(scalar_scale)
scale = [scalar_scale, scalar_scale]
output_size = deriveSizeFromScale(I.shape, scale)
elif output_shape is not None:
scale = deriveScaleFromSize(I.shape, output_shape)
output_size = list(output_shape)
else:
print ('Error: scalar_scale OR output_shape should be defined!')
return
scale_np = np.array(scale)
order = np.argsort(scale_np)
weights = []
indices = []
for k in range(2):
w, ind = contributions(I.shape[k], output_size[k], scale[k], kernel, kernel_width)
weights.append(w)
indices.append(ind)
B = np.copy(I)
flag2D = False
if B.ndim == 2:
B = np.expand_dims(B, axis=2)
flag2D = True
for k in range(2):
dim = order[k]
B = resizeAlongDim(B, dim, weights[dim], indices[dim], mode)
if flag2D:
B = np.squeeze(B, axis=2)
return B
def convertDouble2Byte(I):
B = np.clip(I, 0.0, 1.0)
B = 255*B
return np.around(B).astype(np.uint8)
|
294coder/Efficient-MIF
| 10,282 |
utils/sharpening_index/hqnr2.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
#
import sys
sys.path.append('./')
import numpy as np
from scipy import ndimage
import cv2
from .HQNR import HQNR
from .my_D_s import D_s as my_Ds
from .imresize import imresize
def mtf_resize(img, satellite='QuickBird', scale=4):
# satellite GNyq
scale = int(scale)
if satellite == 'QuickBird':
GNyq = [0.34, 0.32, 0.30, 0.22] # Band Order: B,G,R,NIR
GNyqPan = 0.15
elif satellite == 'IKONOS':
GNyq = [0.26, 0.28, 0.29, 0.28] # Band Order: B,G,R,NIR
GNyqPan = 0.17
elif satellite == 'WV3':
GNyq = [0.325, 0.355, 0.360, 0.350, 0.365, 0.360, 0.335, 0.315] # Band Order: B,G,R,NIR
GNyqPan = 0.14
else:
raise NotImplementedError('satellite: QuickBird or IKONOS or WV3')
# lowpass
img_ = img.squeeze()
img_ = img_.astype(np.float64)
if img_.ndim == 2: # Pan
H, W = img_.shape
lowpass = GNyq2win(GNyqPan, scale, N=41)
elif img_.ndim == 3: # MS
H, W, _ = img.shape
lowpass = [GNyq2win(gnyq, scale, N=41) for gnyq in GNyq]
lowpass = np.stack(lowpass, axis=-1)
img_ = ndimage.filters.correlate(img_, lowpass, mode='nearest')
# downsampling
output_size = (H // scale, W // scale)
img_ = cv2.resize(img_, dsize=output_size, interpolation=cv2.INTER_NEAREST)
return img_
def gaussian2d(N, std):
t = np.arange(-(N - 1) // 2, (N + 2) // 2)
t1, t2 = np.meshgrid(t, t)
std = np.double(std)
w = np.exp(-0.5 * (t1 / std) ** 2) * np.exp(-0.5 * (t2 / std) ** 2)
return w
def kaiser2d(N, beta):
t = np.arange(-(N - 1) // 2, (N + 2) // 2) / np.double(N - 1)
t1, t2 = np.meshgrid(t, t)
t12 = np.sqrt(t1 * t1 + t2 * t2)
w1 = np.kaiser(N, beta)
w = np.interp(t12, t, w1)
w[t12 > t[-1]] = 0
w[t12 < t[0]] = 0
return w
def fir_filter_wind(Hd, w):
"""
compute fir (finite impulse response) filter with window method
Hd: desired freqeuncy response (2D)
w: window (2D)
"""
hd = np.rot90(np.fft.fftshift(np.rot90(Hd, 2)), 2)
h = np.fft.fftshift(np.fft.ifft2(hd))
h = np.rot90(h, 2)
h = h * w
h = h / np.sum(h)
return h
def GNyq2win(GNyq, scale=4, N=41):
"""Generate a 2D convolutional window from a given GNyq
GNyq: Nyquist frequency
scale: spatial size of PAN / spatial size of MS
"""
# fir filter with window method
fcut = 1 / scale
alpha = np.sqrt(((N - 1) * (fcut / 2)) ** 2 / (-2 * np.log(GNyq)))
H = gaussian2d(N, alpha)
Hd = H / np.max(H)
w = kaiser2d(N, 0.5)
h = fir_filter_wind(Hd, w)
return np.real(h)
def _qindex(img1, img2, block_size=8):
"""Q-index for 2D (one-band) image, shape (H, W); uint or float [0, 1]"""
assert block_size > 1, 'block_size shold be greater than 1!'
img1_ = img1.astype(np.float64)
img2_ = img2.astype(np.float64)
window = np.ones((block_size, block_size)) / (block_size ** 2)
# window_size = block_size**2
# filter, valid
pad_topleft = int(np.floor(block_size / 2))
pad_bottomright = block_size - 1 - pad_topleft
mu1 = cv2.filter2D(img1_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright]
mu2 = cv2.filter2D(img2_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright]
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = cv2.filter2D(img1_ ** 2, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu1_sq
sigma2_sq = cv2.filter2D(img2_ ** 2, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu2_sq
# print(mu1_mu2.shape)
# print(sigma2_sq.shape)
sigma12 = cv2.filter2D(img1_ * img2_, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu1_mu2
# all = 1, include the case of simga == mu == 0
qindex_map = np.ones(sigma12.shape)
# sigma == 0 and mu != 0
idx = ((sigma1_sq + sigma2_sq) == 0) * ((mu1_sq + mu2_sq) != 0)
qindex_map[idx] = 2 * mu1_mu2[idx] / (mu1_sq + mu2_sq)[idx]
# sigma !=0 and mu == 0
idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) == 0)
qindex_map[idx] = 2 * sigma12[idx] / (sigma1_sq + sigma2_sq)[idx]
# sigma != 0 and mu != 0
idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) != 0)
qindex_map[idx] = ((2 * mu1_mu2[idx]) * (2 * sigma12[idx])) / (
(mu1_sq + mu2_sq)[idx] * (sigma1_sq + sigma2_sq)[idx])
return np.mean(qindex_map), qindex_map
def qindex(img1, img2, block_size=8):
"""Q-index for 2D (H, W) or 3D (H, W, C) image; uint or float [0, 1]"""
if not img1.shape == img2.shape:
raise ValueError('Input images must have the same dimensions.')
if img1.ndim == 2:
return _qindex(img1, img2, block_size)
elif img1.ndim == 3:
qindexs = [_qindex(img1[..., i], img2[..., i], block_size) for i in range(img1.shape[2])]
return np.array(qindexs).mean()
else:
raise ValueError('Wrong input image dimensions.')
def D_lambda(img_fake, img_lm, block_size=32, p=1):
"""Spectral distortion
img_fake, generated HRMS
img_lm, LRMS"""
assert img_fake.ndim == img_lm.ndim == 3, 'Images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert C_f == C_r, 'Fake and lm should have the same number of bands!'
# D_lambda
Q_fake = []
Q_lm = []
for i in range(C_f):
for j in range(i + 1, C_f):
# for fake
band1 = img_fake[..., i]
band2 = img_fake[..., j]
Q_fake.append(_qindex(band1, band2, block_size=block_size))
# for real
band1 = img_lm[..., i]
band2 = img_lm[..., j]
Q_lm.append(_qindex(band1, band2, block_size=block_size))
Q_fake = np.array(Q_fake)
Q_lm = np.array(Q_lm)
D_lambda_index = (np.abs(Q_fake - Q_lm) ** p).mean()
return D_lambda_index ** (1 / p)
def D_s(img_fake, img_lm, pan, satellite='QuickBird', scale=4, block_size=32, q=1):
"""Spatial distortion
img_fake, generated HRMS
img_lm, LRMS
pan, HRPan"""
# fake and lm
assert img_fake.ndim == img_lm.ndim == 3, 'MS images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert H_f // H_r == W_f // W_r == scale, 'Spatial resolution should be compatible with scale'
assert C_f == C_r, 'Fake and lm should have the same number of bands!'
# fake and pan
assert pan.ndim == 3, 'Panchromatic image must be 3D!'
H_p, W_p, C_p = pan.shape
assert C_p == 1, 'size of 3rd dim of Panchromatic image must be 1'
assert H_f == H_p and W_f == W_p, "Pan's and fake's spatial resolution should be the same"
# get LRPan, 2D
pan_lr = mtf_resize(pan, satellite=satellite, scale=scale)
# print(pan_lr.shape)
# D_s
Q_hr = []
Q_lr = []
for i in range(C_f):
# for HR fake
band1 = img_fake[..., i]
band2 = pan[..., 0] # the input PAN is 3D with size=1 along 3rd dim
# print(band1.shape)
# print(band2.shape)
Q_hr.append(_qindex(band1, band2, block_size=block_size))
band1 = img_lm[..., i]
band2 = pan_lr # this is 2D
# print(band1.shape)
# print(band2.shape)
Q_lr.append(_qindex(band1, band2, block_size=block_size))
Q_hr = np.array(Q_hr)
Q_lr = np.array(Q_lr)
D_s_index = (np.abs(Q_hr - Q_lr) ** q).mean()
return D_s_index ** (1 / q)
def qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1):
"""QNR - No reference IQA"""
if pan.ndim == 2:
pan = pan[:, :, None]
D_lambda_idx = D_lambda(ps_ms, msexp, S, p)
D_s_idx = D_s(ps_ms, ms, pan, 'WV3', ratio, S, q)
QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta
return QNR_idx, D_lambda_idx, D_s_idx
def my_qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1):
"""QNR - No reference IQA"""
# D_lambda_idx = D_lambda(img_fake, img_lm, block_size, p)
# D_s_idx = D_s(img_fake, img_lm, pan, satellite, scale, block_size, q)
D_lambda_idx = D_lambda(ps_ms, msexp, S, p)
D_s_idx = my_Ds(ps_ms, msexp, ms, pan, ratio, S, q)
QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta
return QNR_idx, D_lambda_idx, D_s_idx
def indexes_evaluation_FS(I_F, I_MS_LR, I_PAN, L, th_values, I_MS, sensor, ratio, Qblocks_size, flagQNR):
if th_values == 1:
I_F[I_F > 2 ** L] = 2 ** L
I_F[I_F < 0] = 0
assert flagQNR == False, 'flagQNR should be False'
if flagQNR:
QNR_index, D_lambda, D_S = my_qnr(I_F, I_MS_LR, I_MS, I_PAN, ratio, Qblocks_size)
else:
QNR_index, D_lambda, D_S, HQNR_map = HQNR(I_F, I_MS_LR, I_MS, I_PAN, Qblocks_size, sensor, ratio)
return QNR_index, D_lambda, D_S, HQNR_map
if __name__ == '__main__':
import scipy.io as sio
ratio = 4
index = 16
I_F = sio.loadmat(r'E:\HSI_PAN_result\pan_other_methods\WV3_Full\FusionNet\results\output_mulExm_' + f'{index}.mat')['sr'].astype(np.float32)
I_MS = sio.loadmat(r'E:\HSI_PAN_result\pan_other_methods\WV3_Full\EXP\results\output_mulExm_' + f'{index}.mat')['sr']
I_MS_LR = imresize(I_MS, 1/ratio) # I_F[...,[4,2,0]]
I_PAN = sio.loadmat(r'E:\HSI_PAN_result\pan_other_methods\WV3_Full\PAN\results\output_mulExm_' + f'{index}.mat')['sr']
L = 11
th_values = 0
sensor = 'wv3'.upper()
tag_ab = 'sensor-based'
Qblocks_size = 32
if th_values:
I_F[I_F > 2**L] = 2**L
I_F[I_F < 0] = 0
QNR_index, D_lambda, D_S, HQNR_map = indexes_evaluation_FS(I_F, I_MS_LR, I_PAN, L, th_values, I_MS, sensor, ratio, Qblocks_size, False)
print(QNR_index)
import matplotlib as mpl
import matplotlib.pyplot as plt
cmap = mpl.colormaps['jet'].resampled(256)
sup = 1
HQNR_map = imresize(HQNR_map, 512//16)
HQNR_map = HQNR_map - HQNR_map.min()
HQNR_map = HQNR_map / HQNR_map.max()
HQNR_map = HQNR_map / sup
# color mapping
HQNR_map = cmap(HQNR_map)
# HQNR_map = HQNR_map.astype(np.uint8)
plt.imshow(HQNR_map)
# plt.colorbar()
plt.show()
|
281677160/openwrt-package
| 21,058 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_dynamic_resolver.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include "ngx_event_timer_module.h"
#include "ngx_event_resolver.h"
#include "ngx_dynamic_resolver.h"
#include "ngx_toolkit_misc.h"
static ngx_int_t ngx_dynamic_resolver_process_init(ngx_cycle_t *cycle);
static void *ngx_dynamic_resolver_create_conf(ngx_cycle_t *cycle);
static char *ngx_dynamic_resolver_init_conf(ngx_cycle_t *cycle, void *conf);
#define MAX_DOMAIN_LEN 128
#define MAX_ADDRS 8
typedef struct ngx_dynamic_resolver_ctx_s ngx_dynamic_resolver_ctx_t;
typedef struct ngx_dynamic_resolver_domain_s ngx_dynamic_resolver_domain_t;
struct ngx_dynamic_resolver_ctx_s {
ngx_dynamic_resolver_handler_pt h;
void *data;
ngx_dynamic_resolver_ctx_t *next;
};
typedef struct {
struct sockaddr sockaddr;
socklen_t socklen;
u_short priority;
u_short weight;
} ngx_dynamic_resolver_addr_t;
struct ngx_dynamic_resolver_domain_s {
ngx_str_t domain;
u_char domain_cstr[MAX_DOMAIN_LEN];
ngx_uint_t naddrs;
ngx_dynamic_resolver_addr_t addrs[MAX_ADDRS];
ngx_dynamic_resolver_ctx_t *ctx;
ngx_dynamic_resolver_domain_t *next;
};
typedef struct {
ngx_msec_t refresh_interval;
size_t domain_buckets;
ngx_dynamic_resolver_domain_t **resolver_hash;
ngx_dynamic_resolver_ctx_t *free_ctx;
ngx_dynamic_resolver_domain_t *free_domain;
ngx_uint_t nalloc_ctx;
ngx_uint_t nfree_ctx;
ngx_uint_t nalloc_domain;
ngx_uint_t nfree_domain;
} ngx_dynamic_resolver_conf_t;
static ngx_str_t dynamic_resolver_name = ngx_string("dynamic_resolver");
static ngx_command_t ngx_dynamic_resolver_commands[] = {
{ ngx_string("dynamic_refresh_interval"),
NGX_EVENT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
0,
offsetof(ngx_dynamic_resolver_conf_t, refresh_interval),
NULL },
{ ngx_string("dynamic_domain_buckets"),
NGX_EVENT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
0,
offsetof(ngx_dynamic_resolver_conf_t, domain_buckets),
NULL },
ngx_null_command
};
ngx_event_module_t ngx_dynamic_resolver_module_ctx = {
&dynamic_resolver_name,
ngx_dynamic_resolver_create_conf, /* create configuration */
ngx_dynamic_resolver_init_conf, /* init configuration */
{ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
};
/* this module use ngx_cycle->log */
ngx_module_t ngx_dynamic_resolver_module = {
NGX_MODULE_V1,
&ngx_dynamic_resolver_module_ctx, /* module context */
ngx_dynamic_resolver_commands, /* module directives */
NGX_EVENT_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
ngx_dynamic_resolver_process_init, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_dynamic_resolver_create_conf(ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *conf;
conf = ngx_pcalloc(cycle->pool, sizeof(ngx_dynamic_resolver_conf_t));
if (conf == NULL) {
return NULL;
}
conf->refresh_interval = NGX_CONF_UNSET_MSEC;
conf->domain_buckets = NGX_CONF_UNSET_UINT;
return conf;
}
static char *
ngx_dynamic_resolver_init_conf(ngx_cycle_t *cycle, void *conf)
{
ngx_dynamic_resolver_conf_t *drcf = conf;
ngx_conf_init_msec_value(drcf->refresh_interval, 5000);
ngx_conf_init_uint_value(drcf->domain_buckets, 101);
if (drcf->refresh_interval > 0 && drcf->domain_buckets > 0) {
drcf->resolver_hash = ngx_pcalloc(cycle->pool,
sizeof(ngx_dynamic_resolver_domain_t *) * drcf->domain_buckets);
}
return NGX_CONF_OK;
}
/* reuse for ngx_dynamic_resolver_ctx_t */
static ngx_dynamic_resolver_ctx_t *
ngx_dynamic_resolver_get_ctx(ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_ctx_t *ctx;
drcf = ngx_event_get_conf(cycle->conf_ctx, ngx_dynamic_resolver_module);
ctx = drcf->free_ctx;
if (ctx == NULL) {
ctx = ngx_pcalloc(cycle->pool, sizeof(ngx_dynamic_resolver_ctx_t));
if (ctx == NULL) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0, "dynamic resolver, "
"alloc memory dynamic resolver ctx failed");
return NULL;
}
++drcf->nalloc_ctx;
} else {
drcf->free_ctx = drcf->free_ctx->next;
ngx_memzero(ctx, sizeof(ngx_dynamic_resolver_ctx_t));
--drcf->nfree_ctx;
}
return ctx;
}
static void
ngx_dynamic_resolver_put_ctx(ngx_dynamic_resolver_ctx_t *ctx,
ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *drcf;
drcf = ngx_event_get_conf(cycle->conf_ctx, ngx_dynamic_resolver_module);
ctx->next = drcf->free_ctx;
drcf->free_ctx = ctx;
++drcf->nfree_ctx;
}
/* reuse for ngx_dynamic_resolver_domain_t */
static ngx_dynamic_resolver_domain_t *
ngx_dynamic_resolver_get_domain(ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_domain_t *domain;
drcf = ngx_event_get_conf(cycle->conf_ctx, ngx_dynamic_resolver_module);
domain = drcf->free_domain;
if (domain == NULL) {
domain = ngx_pcalloc(cycle->pool,
sizeof(ngx_dynamic_resolver_domain_t));
if (domain == NULL) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0, "dynamic resolver, "
"alloc memory dynamic resolver domain failed");
return NULL;
}
++drcf->nalloc_domain;
} else {
drcf->free_domain = drcf->free_domain->next;
ngx_memzero(domain, sizeof(ngx_dynamic_resolver_domain_t));
--drcf->nfree_domain;
}
return domain;
}
static void
ngx_dynamic_resolver_put_domain(ngx_dynamic_resolver_domain_t *domain,
ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *drcf;
drcf = ngx_event_get_conf(cycle->conf_ctx, ngx_dynamic_resolver_module);
domain->next = drcf->free_domain;
drcf->free_domain = domain;
++drcf->nfree_domain;
}
static void
ngx_dynamic_resolver_on_result(void *data, ngx_resolver_addr_t *addrs,
ngx_uint_t naddrs)
{
ngx_dynamic_resolver_domain_t *domain;
ngx_dynamic_resolver_ctx_t *ctx;
ngx_uint_t i, n;
domain = data;
if (domain == NULL) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "dynamic resolver, "
"%V has been deleted", &domain->domain);
return;
}
if (naddrs == 0) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "dynamic resolver, "
"domain '%V' resolver failed", &domain->domain);
while (domain->ctx) {
ctx = domain->ctx;
domain->ctx = ctx->next;
ctx->h(ctx->data, NULL, 0);
ngx_dynamic_resolver_put_ctx(ctx, (ngx_cycle_t *) ngx_cycle);
}
return;
}
domain->naddrs = ngx_min(naddrs, MAX_ADDRS);
for (i = 0; i < domain->naddrs; ++i) {
ngx_memcpy(&domain->addrs[i].sockaddr, addrs[i].sockaddr,
addrs[i].socklen);
domain->addrs[i].socklen = addrs[i].socklen;
domain->addrs[i].priority = addrs[i].priority;
domain->addrs[i].weight = addrs[i].weight;
n = ngx_random() % domain->naddrs;
while (domain->ctx) {
ngx_log_debug1(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver, resolver '%V' successd",
&domain->domain);
ctx = domain->ctx;
domain->ctx = ctx->next;
ctx->h(ctx->data, &domain->addrs[n].sockaddr,
domain->addrs[n].socklen);
ngx_dynamic_resolver_put_ctx(ctx, (ngx_cycle_t *) ngx_cycle);
++n;
n %= domain->naddrs;
}
}
}
static void
ngx_dynamic_resolver_on_timer(void *data)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_domain_t *domain;
ngx_uint_t i;
if (ngx_exiting) {
return;
}
drcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_dynamic_resolver_module);
for (i = 0; i < drcf->domain_buckets; ++i) {
domain = drcf->resolver_hash[i];
while (domain) {
ngx_log_debug1(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver, on timer start resolver %V",
&domain->domain);
ngx_event_resolver_start_resolver(&domain->domain,
ngx_dynamic_resolver_on_result, domain);
domain = domain->next;
}
}
ngx_event_timer_add_timer(drcf->refresh_interval,
ngx_dynamic_resolver_on_timer, NULL);
}
static ngx_int_t
ngx_dynamic_resolver_process_init(ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *drcf;
drcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_dynamic_resolver_module);
if (drcf->refresh_interval == 0) {
return NGX_OK;
}
ngx_event_timer_add_timer(0, ngx_dynamic_resolver_on_timer, NULL);
return NGX_OK;
}
void
ngx_dynamic_resolver_add_domain(ngx_str_t *domain, ngx_cycle_t *cycle)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_domain_t *d;
ngx_uint_t idx;
struct sockaddr sa;
socklen_t len;
u_char temp[MAX_DOMAIN_LEN];
if (domain == NULL || domain->len == 0) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0,
"dynamic resolver add, domain is NULL");
return;
}
len = ngx_sock_pton(&sa, domain->data, domain->len);
/* addr is IP address */
if (len) {
ngx_log_error(NGX_LOG_DEBUG_CORE, cycle->log, 0,
"dynamic resolver add, domain is ipv4/ipv6/unix address");
return;
}
drcf = ngx_event_get_conf(cycle->conf_ctx, ngx_dynamic_resolver_module);
if (drcf->refresh_interval == 0) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0, "dynamic resolver add, "
"dynamic resolver closed when add domain");
return;
}
if (domain->len > MAX_DOMAIN_LEN) {
ngx_log_error(NGX_LOG_ERR, cycle->log, 0, "dynamic resolver add, "
"domain length(%z) is too long", domain->len);
return;
}
ngx_memzero(temp, MAX_DOMAIN_LEN);
idx = ngx_hash_strlow(temp, domain->data, domain->len);
idx %= drcf->domain_buckets;
ngx_log_debug2(NGX_LOG_DEBUG_CORE, cycle->log, 0, "dynamic resolver add, "
"prepare add %V in %d slot", domain, idx);
for (d = drcf->resolver_hash[idx]; d; d = d->next) {
if (d->domain.len == domain->len &&
ngx_memcmp(d->domain.data, temp, domain->len) == 0)
{
ngx_log_debug1(NGX_LOG_DEBUG_CORE, cycle->log, 0,
"dynamic resolver add, %V is in dynamic resolv hash table",
domain);
return;
}
}
d = ngx_dynamic_resolver_get_domain(cycle);
if (d == NULL) {
return;
}
/* add domain in dynamic resolver */
d->next = drcf->resolver_hash[idx];
drcf->resolver_hash[idx] = d;
ngx_memcpy(d->domain_cstr, temp, MAX_DOMAIN_LEN);
d->domain.data = d->domain_cstr;
d->domain.len = domain->len;
}
void
ngx_dynamic_resolver_del_domain(ngx_str_t *domain)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_domain_t **pd, *d;
ngx_dynamic_resolver_ctx_t *ctx;
ngx_uint_t idx;
struct sockaddr sa;
socklen_t len;
u_char temp[MAX_DOMAIN_LEN];
if (domain == NULL || domain->len == 0) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"dynamic resolver del, domain is NULL");
return;
}
len = ngx_sock_pton(&sa, domain->data, domain->len);
/* addr is IP address */
if (len) {
ngx_log_debug0(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver del, domain is ipv4/ipv6/unix address");
return;
}
drcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_dynamic_resolver_module);
if (drcf->refresh_interval == 0) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "dynamic resolver del, "
"dynamic resolver closed when del domain");
return;
}
if (domain->len > MAX_DOMAIN_LEN) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "dynamic resolver del, "
"domain length(%z) is too long", domain->len);
return;
}
ngx_memzero(temp, MAX_DOMAIN_LEN);
idx = ngx_hash_strlow(temp, domain->data, domain->len);
idx %= drcf->domain_buckets;
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "dynamic resolver del, "
"prepare del %V in %d slot", domain, idx);
for (pd = &drcf->resolver_hash[idx]; *pd; pd = &(*pd)->next) {
if ((*pd)->domain.len == domain->len &&
ngx_memcmp((*pd)->domain.data, temp, domain->len) == 0)
{
d= *pd;
*pd = (*pd)->next;
while (d->ctx) {
ctx = d->ctx;
d->ctx = ctx->next;
ctx->h(ctx->data, NULL, 0);
ngx_dynamic_resolver_put_ctx(ctx, (ngx_cycle_t *) ngx_cycle);
}
ngx_dynamic_resolver_put_domain(d, (ngx_cycle_t *) ngx_cycle);
return;
}
}
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "dynamic resolver del, "
"%V is not in dynamic resolv hash table", domain);
}
void
ngx_dynamic_resolver_start_resolver(ngx_str_t *domain,
ngx_dynamic_resolver_handler_pt h, void *data)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_domain_t *d;
ngx_dynamic_resolver_ctx_t *ctx;
ngx_uint_t idx, n;
struct sockaddr sa;
socklen_t len;
u_char temp[MAX_DOMAIN_LEN];
if (domain == NULL || domain->len == 0) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"dynamic resolver async, domain is NULL");
return;
}
len = ngx_sock_pton(&sa, domain->data, domain->len);
/* addr is ipv4/ipv6/unix address */
if (len) {
ngx_log_debug0(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver async, domain is ipv4/ipv6/unix address");
h(data, &sa, len);
return;
}
drcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_dynamic_resolver_module);
if (drcf->refresh_interval == 0) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "dynamic resolver async, "
"dynamic resolver closed when start resolver");
goto failed;
}
if (domain->len > MAX_DOMAIN_LEN) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "dynamic resolver async, "
"domain length(%z) is too long", domain->len);
goto failed;
}
ngx_memzero(temp, MAX_DOMAIN_LEN);
idx = ngx_hash_strlow(temp, domain->data, domain->len);
idx %= drcf->domain_buckets;
d = drcf->resolver_hash[idx];
while (d) {
if (d->domain.len == domain->len &&
ngx_memcmp(d->domain.data, temp, domain->len) == 0)
{
break;
}
d = d->next;
}
if (d == NULL) { /* not found */
d = ngx_dynamic_resolver_get_domain((ngx_cycle_t *) ngx_cycle);
if (d == NULL) {
goto failed;
}
/* add domain in dynamic resolver */
d->next = drcf->resolver_hash[idx];
drcf->resolver_hash[idx] = d;
ngx_memcpy(d->domain_cstr, temp, MAX_DOMAIN_LEN);
d->domain.data = d->domain_cstr;
d->domain.len = domain->len;
}
/* domain is not resolved */
if (d->naddrs == 0) {
/* add call back in resolver list */
ctx = ngx_dynamic_resolver_get_ctx((ngx_cycle_t *) ngx_cycle);
if (ctx == NULL) {
goto failed;
}
ngx_log_debug1(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver async, domain '%V' is not resolved",
&d->domain);
ctx->h = h;
ctx->data = data;
ctx->next = d->ctx;
d->ctx = ctx;
ngx_event_resolver_start_resolver(&d->domain,
ngx_dynamic_resolver_on_result, d);
return;
}
ngx_log_debug1(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver async, domain '%V' is resolved, call directly",
&d->domain);
/* call callback */
n = ngx_random() % d->naddrs;
h(data, &d->addrs[n].sockaddr, d->addrs[n].socklen);
return;
failed:
h(data, NULL, 0);
}
socklen_t
ngx_dynamic_resolver_gethostbyname(ngx_str_t *domain, struct sockaddr *sa)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_dynamic_resolver_domain_t *d;
ngx_uint_t idx, n;
socklen_t len;
u_char temp[MAX_DOMAIN_LEN];
if (domain == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"dynamic resolver sync, domain is NULL");
return 0;
}
len = ngx_sock_pton(sa, domain->data, domain->len);
/* addr is ipv4/ipv6/unix address */
if (len) {
ngx_log_debug0(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0,
"dynamic resolver sync, domain is ipv4/ipv6/unix address");
return len;
}
drcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_dynamic_resolver_module);
if (drcf->refresh_interval == 0) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "dynamic resolver sync, "
"dynamic resolver closed when start resolver");
return 0;
}
if (domain->len > MAX_DOMAIN_LEN) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "dynamic resolver sync, "
"domain length(%z) is too long", domain->len);
return 0;
}
ngx_memzero(temp, MAX_DOMAIN_LEN);
idx = ngx_hash_strlow(temp, domain->data, domain->len);
idx %= drcf->domain_buckets;
d = drcf->resolver_hash[idx];
while (d) {
if (d->domain.len == domain->len &&
ngx_memcmp(d->domain.data, temp, domain->len) == 0)
{
if (d->naddrs == 0) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"dynamic resolver sync, domain '%V' is not resolved",
&d->domain);
return 0;
}
n = ngx_random() % d->naddrs;
ngx_memcpy(sa, &d->addrs[n].sockaddr, d->addrs[n].socklen);
return d->addrs[n].socklen;
}
d = d->next;
}
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0, "dynamic resolver sync, "
"domain '%V' is not in dynamic resolver table", domain);
return 0;
}
ngx_chain_t *
ngx_dynamic_resolver_state(ngx_http_request_t *r)
{
ngx_dynamic_resolver_conf_t *drcf;
ngx_chain_t *cl;
ngx_buf_t *b;
size_t len;
drcf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_dynamic_resolver_module);
len = sizeof("##########dynamic resolver state##########\n") - 1
+ sizeof("ngx_dynamic_resolver alloc ctx: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_dynamic_resolver free ctx: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_dynamic_resolver alloc domain: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_dynamic_resolver free domain: \n") - 1 + NGX_OFF_T_LEN;
cl = ngx_alloc_chain_link(r->pool);
if (cl == NULL) {
return NULL;
}
cl->next = NULL;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL) {
return NULL;
}
cl->buf = b;
b->last = ngx_snprintf(b->last, len,
"##########dynamic resolver state##########\n"
"ngx_dynamic_resolver alloc ctx: %ui\n"
"ngx_dynamic_resolver free ctx: %ui\n"
"ngx_dynamic_resolver alloc domain: %ui\n"
"ngx_dynamic_resolver free domain: %ui\n",
drcf->nalloc_ctx, drcf->nfree_ctx,
drcf->nalloc_domain, drcf->nfree_domain);
return cl;
}
|
2881099/FreeSql.AdminLTE
| 192,624 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/inputmask/jquery.inputmask.js
|
/*!
* dist/jquery.inputmask
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2021 Robin Herbots
* Licensed under the MIT license
* Version: 5.0.7
*/
!function(e, t) {
if ("object" == typeof exports && "object" == typeof module) module.exports = t(require("jquery")); else if ("function" == typeof define && define.amd) define([ "jquery" ], t); else {
var i = "object" == typeof exports ? t(require("jquery")) : t(e.jQuery);
for (var a in i) ("object" == typeof exports ? exports : e)[a] = i[a];
}
}(self, (function(e) {
return function() {
"use strict";
var t = {
3046: function(e, t, i) {
var a;
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0, i(3851), i(219), i(207), i(5296);
var n = ((a = i(2394)) && a.__esModule ? a : {
default: a
}).default;
t.default = n;
},
8741: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var i = !("undefined" == typeof window || !window.document || !window.document.createElement);
t.default = i;
},
3976: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var a, n = (a = i(5581)) && a.__esModule ? a : {
default: a
};
var r = {
_maxTestPos: 500,
placeholder: "_",
optionalmarker: [ "[", "]" ],
quantifiermarker: [ "{", "}" ],
groupmarker: [ "(", ")" ],
alternatormarker: "|",
escapeChar: "\\",
mask: null,
regex: null,
oncomplete: function() {},
onincomplete: function() {},
oncleared: function() {},
repeat: 0,
greedy: !1,
autoUnmask: !1,
removeMaskOnSubmit: !1,
clearMaskOnLostFocus: !0,
insertMode: !0,
insertModeVisual: !0,
clearIncomplete: !1,
alias: null,
onKeyDown: function() {},
onBeforeMask: null,
onBeforePaste: function(e, t) {
return "function" == typeof t.onBeforeMask ? t.onBeforeMask.call(this, e, t) : e;
},
onBeforeWrite: null,
onUnMask: null,
showMaskOnFocus: !0,
showMaskOnHover: !0,
onKeyValidation: function() {},
skipOptionalPartCharacter: " ",
numericInput: !1,
rightAlign: !1,
undoOnEscape: !0,
radixPoint: "",
_radixDance: !1,
groupSeparator: "",
keepStatic: null,
positionCaretOnTab: !0,
tabThrough: !1,
supportsInputType: [ "text", "tel", "url", "password", "search" ],
ignorables: [ n.default.BACKSPACE, n.default.TAB, n.default["PAUSE/BREAK"], n.default.ESCAPE, n.default.PAGE_UP, n.default.PAGE_DOWN, n.default.END, n.default.HOME, n.default.LEFT, n.default.UP, n.default.RIGHT, n.default.DOWN, n.default.INSERT, n.default.DELETE, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 229 ],
isComplete: null,
preValidation: null,
postValidation: null,
staticDefinitionSymbol: void 0,
jitMasking: !1,
nullable: !0,
inputEventOnly: !1,
noValuePatching: !1,
positionCaretOnClick: "lvp",
casing: null,
inputmode: "text",
importDataAttributes: !0,
shiftPositions: !0,
usePrototypeDefinitions: !0,
validationEventTimeOut: 3e3,
substitutes: {}
};
t.default = r;
},
7392: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
t.default = {
9: {
validator: "[0-9\uff10-\uff19]",
definitionSymbol: "*"
},
a: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
definitionSymbol: "*"
},
"*": {
validator: "[0-9\uff10-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"
}
};
},
3287: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var a, n = (a = i(2047)) && a.__esModule ? a : {
default: a
};
if (void 0 === n.default) throw "jQuery not loaded!";
var r = n.default;
t.default = r;
},
9845: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.ua = t.mobile = t.iphone = t.iemobile = t.ie = void 0;
var a, n = (a = i(9380)) && a.__esModule ? a : {
default: a
};
var r = n.default.navigator && n.default.navigator.userAgent || "", o = r.indexOf("MSIE ") > 0 || r.indexOf("Trident/") > 0, s = "ontouchstart" in n.default, l = /iemobile/i.test(r), u = /iphone/i.test(r) && !l;
t.iphone = u, t.iemobile = l, t.mobile = s, t.ie = o, t.ua = r;
},
7184: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = function(e) {
return e.replace(i, "\\$1");
};
var i = new RegExp("(\\" + [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ].join("|\\") + ")", "gim");
},
6030: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.EventHandlers = void 0;
var a, n = i(8711), r = (a = i(5581)) && a.__esModule ? a : {
default: a
}, o = i(9845), s = i(7215), l = i(7760), u = i(4713);
function c(e, t) {
var i = "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"];
if (!i) {
if (Array.isArray(e) || (i = function(e, t) {
if (!e) return;
if ("string" == typeof e) return f(e, t);
var i = Object.prototype.toString.call(e).slice(8, -1);
"Object" === i && e.constructor && (i = e.constructor.name);
if ("Map" === i || "Set" === i) return Array.from(e);
if ("Arguments" === i || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)) return f(e, t);
}(e)) || t && e && "number" == typeof e.length) {
i && (e = i);
var a = 0, n = function() {};
return {
s: n,
n: function() {
return a >= e.length ? {
done: !0
} : {
done: !1,
value: e[a++]
};
},
e: function(e) {
throw e;
},
f: n
};
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
var r, o = !0, s = !1;
return {
s: function() {
i = i.call(e);
},
n: function() {
var e = i.next();
return o = e.done, e;
},
e: function(e) {
s = !0, r = e;
},
f: function() {
try {
o || null == i.return || i.return();
} finally {
if (s) throw r;
}
}
};
}
function f(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var i = 0, a = new Array(t); i < t; i++) a[i] = e[i];
return a;
}
var d = {
keydownEvent: function(e) {
var t = this.inputmask, i = t.opts, a = t.dependencyLib, c = t.maskset, f = this, d = a(f), p = e.keyCode, h = n.caret.call(t, f), m = i.onKeyDown.call(this, e, n.getBuffer.call(t), h, i);
if (void 0 !== m) return m;
if (p === r.default.BACKSPACE || p === r.default.DELETE || o.iphone && p === r.default.BACKSPACE_SAFARI || e.ctrlKey && p === r.default.X && !("oncut" in f)) e.preventDefault(),
s.handleRemove.call(t, f, p, h), (0, l.writeBuffer)(f, n.getBuffer.call(t, !0), c.p, e, f.inputmask._valueGet() !== n.getBuffer.call(t).join("")); else if (p === r.default.END || p === r.default.PAGE_DOWN) {
e.preventDefault();
var v = n.seekNext.call(t, n.getLastValidPosition.call(t));
n.caret.call(t, f, e.shiftKey ? h.begin : v, v, !0);
} else p === r.default.HOME && !e.shiftKey || p === r.default.PAGE_UP ? (e.preventDefault(),
n.caret.call(t, f, 0, e.shiftKey ? h.begin : 0, !0)) : i.undoOnEscape && p === r.default.ESCAPE && !0 !== e.altKey ? ((0,
l.checkVal)(f, !0, !1, t.undoValue.split("")), d.trigger("click")) : p !== r.default.INSERT || e.shiftKey || e.ctrlKey || void 0 !== t.userOptions.insertMode ? !0 === i.tabThrough && p === r.default.TAB ? !0 === e.shiftKey ? (h.end = n.seekPrevious.call(t, h.end, !0),
!0 === u.getTest.call(t, h.end - 1).match.static && h.end--, h.begin = n.seekPrevious.call(t, h.end, !0),
h.begin >= 0 && h.end > 0 && (e.preventDefault(), n.caret.call(t, f, h.begin, h.end))) : (h.begin = n.seekNext.call(t, h.begin, !0),
h.end = n.seekNext.call(t, h.begin, !0), h.end < c.maskLength && h.end--, h.begin <= c.maskLength && (e.preventDefault(),
n.caret.call(t, f, h.begin, h.end))) : e.shiftKey || i.insertModeVisual && !1 === i.insertMode && (p === r.default.RIGHT ? setTimeout((function() {
var e = n.caret.call(t, f);
n.caret.call(t, f, e.begin);
}), 0) : p === r.default.LEFT && setTimeout((function() {
var e = n.translatePosition.call(t, f.inputmask.caretPos.begin);
n.translatePosition.call(t, f.inputmask.caretPos.end);
t.isRTL ? n.caret.call(t, f, e + (e === c.maskLength ? 0 : 1)) : n.caret.call(t, f, e - (0 === e ? 0 : 1));
}), 0)) : s.isSelection.call(t, h) ? i.insertMode = !i.insertMode : (i.insertMode = !i.insertMode,
n.caret.call(t, f, h.begin, h.begin));
t.ignorable = i.ignorables.includes(p);
},
keypressEvent: function(e, t, i, a, o) {
var u = this.inputmask || this, c = u.opts, f = u.dependencyLib, d = u.maskset, p = u.el, h = f(p), m = e.keyCode;
if (!(!0 === t || e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || u.ignorable)) return m === r.default.ENTER && u.undoValue !== u._valueGet(!0) && (u.undoValue = u._valueGet(!0),
setTimeout((function() {
h.trigger("change");
}), 0)), u.skipInputEvent = !0, !0;
if (m) {
44 !== m && 46 !== m || 3 !== e.location || "" === c.radixPoint || (m = c.radixPoint.charCodeAt(0));
var v, g = t ? {
begin: o,
end: o
} : n.caret.call(u, p), k = String.fromCharCode(m);
k = c.substitutes[k] || k, d.writeOutBuffer = !0;
var y = s.isValid.call(u, g, k, a, void 0, void 0, void 0, t);
if (!1 !== y && (n.resetMaskSet.call(u, !0), v = void 0 !== y.caret ? y.caret : n.seekNext.call(u, y.pos.begin ? y.pos.begin : y.pos),
d.p = v), v = c.numericInput && void 0 === y.caret ? n.seekPrevious.call(u, v) : v,
!1 !== i && (setTimeout((function() {
c.onKeyValidation.call(p, m, y);
}), 0), d.writeOutBuffer && !1 !== y)) {
var b = n.getBuffer.call(u);
(0, l.writeBuffer)(p, b, v, e, !0 !== t);
}
if (e.preventDefault(), t) return !1 !== y && (y.forwardPosition = v), y;
}
},
keyupEvent: function(e) {
var t = this.inputmask;
!t.isComposing || e.keyCode !== r.default.KEY_229 && e.keyCode !== r.default.ENTER || t.$el.trigger("input");
},
pasteEvent: function(e) {
var t, i = this.inputmask, a = i.opts, r = i._valueGet(!0), o = n.caret.call(i, this);
i.isRTL && (t = o.end, o.end = n.translatePosition.call(i, o.begin), o.begin = n.translatePosition.call(i, t));
var s = r.substr(0, o.begin), u = r.substr(o.end, r.length);
if (s == (i.isRTL ? n.getBufferTemplate.call(i).slice().reverse() : n.getBufferTemplate.call(i)).slice(0, o.begin).join("") && (s = ""),
u == (i.isRTL ? n.getBufferTemplate.call(i).slice().reverse() : n.getBufferTemplate.call(i)).slice(o.end).join("") && (u = ""),
window.clipboardData && window.clipboardData.getData) r = s + window.clipboardData.getData("Text") + u; else {
if (!e.clipboardData || !e.clipboardData.getData) return !0;
r = s + e.clipboardData.getData("text/plain") + u;
}
var f = r;
if (i.isRTL) {
f = f.split("");
var d, p = c(n.getBufferTemplate.call(i));
try {
for (p.s(); !(d = p.n()).done; ) {
var h = d.value;
f[0] === h && f.shift();
}
} catch (e) {
p.e(e);
} finally {
p.f();
}
f = f.join("");
}
if ("function" == typeof a.onBeforePaste) {
if (!1 === (f = a.onBeforePaste.call(i, f, a))) return !1;
f || (f = r);
}
(0, l.checkVal)(this, !0, !1, f.toString().split(""), e), e.preventDefault();
},
inputFallBackEvent: function(e) {
var t = this.inputmask, i = t.opts, a = t.dependencyLib;
var s = this, c = s.inputmask._valueGet(!0), f = (t.isRTL ? n.getBuffer.call(t).slice().reverse() : n.getBuffer.call(t)).join(""), p = n.caret.call(t, s, void 0, void 0, !0);
if (f !== c) {
c = function(e, i, a) {
if (o.iemobile) {
var r = i.replace(n.getBuffer.call(t).join(""), "");
if (1 === r.length) {
var s = i.split("");
s.splice(a.begin, 0, r), i = s.join("");
}
}
return i;
}(0, c, p);
var h = function(e, a, r) {
for (var o, s, l, c = e.substr(0, r.begin).split(""), f = e.substr(r.begin).split(""), d = a.substr(0, r.begin).split(""), p = a.substr(r.begin).split(""), h = c.length >= d.length ? c.length : d.length, m = f.length >= p.length ? f.length : p.length, v = "", g = [], k = "~"; c.length < h; ) c.push(k);
for (;d.length < h; ) d.push(k);
for (;f.length < m; ) f.unshift(k);
for (;p.length < m; ) p.unshift(k);
var y = c.concat(f), b = d.concat(p);
for (s = 0, o = y.length; s < o; s++) switch (l = u.getPlaceholder.call(t, n.translatePosition.call(t, s)),
v) {
case "insertText":
b[s - 1] === y[s] && r.begin == y.length - 1 && g.push(y[s]), s = o;
break;
case "insertReplacementText":
case "deleteContentBackward":
y[s] === k ? r.end++ : s = o;
break;
default:
y[s] !== b[s] && (y[s + 1] !== k && y[s + 1] !== l && void 0 !== y[s + 1] || (b[s] !== l || b[s + 1] !== k) && b[s] !== k ? b[s + 1] === k && b[s] === y[s + 1] ? (v = "insertText",
g.push(y[s]), r.begin--, r.end--) : y[s] !== l && y[s] !== k && (y[s + 1] === k || b[s] !== y[s] && b[s + 1] === y[s + 1]) ? (v = "insertReplacementText",
g.push(y[s]), r.begin--) : y[s] === k ? (v = "deleteContentBackward", (n.isMask.call(t, n.translatePosition.call(t, s), !0) || b[s] === i.radixPoint) && r.end++) : s = o : (v = "insertText",
g.push(y[s]), r.begin--, r.end--));
}
return {
action: v,
data: g,
caret: r
};
}(c, f, p);
switch ((s.inputmask.shadowRoot || s.ownerDocument).activeElement !== s && s.focus(),
(0, l.writeBuffer)(s, n.getBuffer.call(t)), n.caret.call(t, s, p.begin, p.end, !0),
h.action) {
case "insertText":
case "insertReplacementText":
h.data.forEach((function(e, i) {
var n = new a.Event("keypress");
n.keyCode = e.charCodeAt(0), t.ignorable = !1, d.keypressEvent.call(s, n);
})), setTimeout((function() {
t.$el.trigger("keyup");
}), 0);
break;
case "deleteContentBackward":
var m = new a.Event("keydown");
m.keyCode = r.default.BACKSPACE, d.keydownEvent.call(s, m);
break;
default:
(0, l.applyInputValue)(s, c);
}
e.preventDefault();
}
},
compositionendEvent: function(e) {
var t = this.inputmask;
t.isComposing = !1, t.$el.trigger("input");
},
setValueEvent: function(e) {
var t = this.inputmask, i = this, a = e && e.detail ? e.detail[0] : arguments[1];
void 0 === a && (a = i.inputmask._valueGet(!0)), (0, l.applyInputValue)(i, a), (e.detail && void 0 !== e.detail[1] || void 0 !== arguments[2]) && n.caret.call(t, i, e.detail ? e.detail[1] : arguments[2]);
},
focusEvent: function(e) {
var t = this.inputmask, i = t.opts, a = this, r = a.inputmask._valueGet();
i.showMaskOnFocus && r !== n.getBuffer.call(t).join("") && (0, l.writeBuffer)(a, n.getBuffer.call(t), n.seekNext.call(t, n.getLastValidPosition.call(t))),
!0 !== i.positionCaretOnTab || !1 !== t.mouseEnter || s.isComplete.call(t, n.getBuffer.call(t)) && -1 !== n.getLastValidPosition.call(t) || d.clickEvent.apply(a, [ e, !0 ]),
t.undoValue = t._valueGet(!0);
},
invalidEvent: function(e) {
this.inputmask.validationEvent = !0;
},
mouseleaveEvent: function() {
var e = this.inputmask, t = e.opts, i = this;
e.mouseEnter = !1, t.clearMaskOnLostFocus && (i.inputmask.shadowRoot || i.ownerDocument).activeElement !== i && (0,
l.HandleNativePlaceholder)(i, e.originalPlaceholder);
},
clickEvent: function(e, t) {
var i = this.inputmask, a = this;
if ((a.inputmask.shadowRoot || a.ownerDocument).activeElement === a) {
var r = n.determineNewCaretPosition.call(i, n.caret.call(i, a), t);
void 0 !== r && n.caret.call(i, a, r);
}
},
cutEvent: function(e) {
var t = this.inputmask, i = t.maskset, a = this, o = n.caret.call(t, a), u = t.isRTL ? n.getBuffer.call(t).slice(o.end, o.begin) : n.getBuffer.call(t).slice(o.begin, o.end), c = t.isRTL ? u.reverse().join("") : u.join("");
window.navigator.clipboard ? window.navigator.clipboard.writeText(c) : window.clipboardData && window.clipboardData.getData && window.clipboardData.setData("Text", c),
s.handleRemove.call(t, a, r.default.DELETE, o), (0, l.writeBuffer)(a, n.getBuffer.call(t), i.p, e, t.undoValue !== t._valueGet(!0));
},
blurEvent: function(e) {
var t = this.inputmask, i = t.opts, a = (0, t.dependencyLib)(this), r = this;
if (r.inputmask) {
(0, l.HandleNativePlaceholder)(r, t.originalPlaceholder);
var o = r.inputmask._valueGet(), u = n.getBuffer.call(t).slice();
"" !== o && (i.clearMaskOnLostFocus && (-1 === n.getLastValidPosition.call(t) && o === n.getBufferTemplate.call(t).join("") ? u = [] : l.clearOptionalTail.call(t, u)),
!1 === s.isComplete.call(t, u) && (setTimeout((function() {
a.trigger("incomplete");
}), 0), i.clearIncomplete && (n.resetMaskSet.call(t), u = i.clearMaskOnLostFocus ? [] : n.getBufferTemplate.call(t).slice())),
(0, l.writeBuffer)(r, u, void 0, e)), t.undoValue !== t._valueGet(!0) && (t.undoValue = t._valueGet(!0),
a.trigger("change"));
}
},
mouseenterEvent: function() {
var e = this.inputmask, t = e.opts, i = this;
if (e.mouseEnter = !0, (i.inputmask.shadowRoot || i.ownerDocument).activeElement !== i) {
var a = (e.isRTL ? n.getBufferTemplate.call(e).slice().reverse() : n.getBufferTemplate.call(e)).join("");
e.placeholder !== a && i.placeholder !== e.originalPlaceholder && (e.originalPlaceholder = i.placeholder),
t.showMaskOnHover && (0, l.HandleNativePlaceholder)(i, a);
}
},
submitEvent: function() {
var e = this.inputmask, t = e.opts;
e.undoValue !== e._valueGet(!0) && e.$el.trigger("change"), -1 === n.getLastValidPosition.call(e) && e._valueGet && e._valueGet() === n.getBufferTemplate.call(e).join("") && e._valueSet(""),
t.clearIncomplete && !1 === s.isComplete.call(e, n.getBuffer.call(e)) && e._valueSet(""),
t.removeMaskOnSubmit && (e._valueSet(e.unmaskedvalue(), !0), setTimeout((function() {
(0, l.writeBuffer)(e.el, n.getBuffer.call(e));
}), 0));
},
resetEvent: function() {
var e = this.inputmask;
e.refreshValue = !0, setTimeout((function() {
(0, l.applyInputValue)(e.el, e._valueGet(!0));
}), 0);
}
};
t.EventHandlers = d;
},
9716: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.EventRuler = void 0;
var a = s(i(2394)), n = s(i(5581)), r = i(8711), o = i(7760);
function s(e) {
return e && e.__esModule ? e : {
default: e
};
}
var l = {
on: function(e, t, i) {
var s = e.inputmask.dependencyLib, l = function(t) {
t.originalEvent && (t = t.originalEvent || t, arguments[0] = t);
var l, u = this, c = u.inputmask, f = c ? c.opts : void 0;
if (void 0 === c && "FORM" !== this.nodeName) {
var d = s.data(u, "_inputmask_opts");
s(u).off(), d && new a.default(d).mask(u);
} else {
if ([ "submit", "reset", "setvalue" ].includes(t.type) || "FORM" === this.nodeName || !(u.disabled || u.readOnly && !("keydown" === t.type && t.ctrlKey && 67 === t.keyCode || !1 === f.tabThrough && t.keyCode === n.default.TAB))) {
switch (t.type) {
case "input":
if (!0 === c.skipInputEvent || t.inputType && "insertCompositionText" === t.inputType) return c.skipInputEvent = !1,
t.preventDefault();
break;
case "keydown":
c.skipKeyPressEvent = !1, c.skipInputEvent = c.isComposing = t.keyCode === n.default.KEY_229;
break;
case "keyup":
case "compositionend":
c.isComposing && (c.skipInputEvent = !1);
break;
case "keypress":
if (!0 === c.skipKeyPressEvent) return t.preventDefault();
c.skipKeyPressEvent = !0;
break;
case "click":
case "focus":
return c.validationEvent ? (c.validationEvent = !1, e.blur(), (0, o.HandleNativePlaceholder)(e, (c.isRTL ? r.getBufferTemplate.call(c).slice().reverse() : r.getBufferTemplate.call(c)).join("")),
setTimeout((function() {
e.focus();
}), f.validationEventTimeOut), !1) : (l = arguments, setTimeout((function() {
e.inputmask && i.apply(u, l);
}), 0), !1);
}
var p = i.apply(u, arguments);
return !1 === p && (t.preventDefault(), t.stopPropagation()), p;
}
t.preventDefault();
}
};
[ "submit", "reset" ].includes(t) ? (l = l.bind(e), null !== e.form && s(e.form).on(t, l)) : s(e).on(t, l),
e.inputmask.events[t] = e.inputmask.events[t] || [], e.inputmask.events[t].push(l);
},
off: function(e, t) {
if (e.inputmask && e.inputmask.events) {
var i = e.inputmask.dependencyLib, a = e.inputmask.events;
for (var n in t && ((a = [])[t] = e.inputmask.events[t]), a) {
for (var r = a[n]; r.length > 0; ) {
var o = r.pop();
[ "submit", "reset" ].includes(n) ? null !== e.form && i(e.form).off(n, o) : i(e).off(n, o);
}
delete e.inputmask.events[n];
}
}
}
};
t.EventRuler = l;
},
219: function(e, t, i) {
var a = d(i(2394)), n = d(i(5581)), r = d(i(7184)), o = i(8711), s = i(4713);
function l(e) {
return l = "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;
}, l(e);
}
function u(e, t) {
return function(e) {
if (Array.isArray(e)) return e;
}(e) || function(e, t) {
var i = null == e ? null : "undefined" != typeof Symbol && e[Symbol.iterator] || e["@@iterator"];
if (null == i) return;
var a, n, r = [], o = !0, s = !1;
try {
for (i = i.call(e); !(o = (a = i.next()).done) && (r.push(a.value), !t || r.length !== t); o = !0) ;
} catch (e) {
s = !0, n = e;
} finally {
try {
o || null == i.return || i.return();
} finally {
if (s) throw n;
}
}
return r;
}(e, t) || function(e, t) {
if (!e) return;
if ("string" == typeof e) return c(e, t);
var i = Object.prototype.toString.call(e).slice(8, -1);
"Object" === i && e.constructor && (i = e.constructor.name);
if ("Map" === i || "Set" === i) return Array.from(e);
if ("Arguments" === i || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)) return c(e, t);
}(e, t) || function() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}();
}
function c(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var i = 0, a = new Array(t); i < t; i++) a[i] = e[i];
return a;
}
function f(e, t) {
for (var i = 0; i < t.length; i++) {
var a = t[i];
a.enumerable = a.enumerable || !1, a.configurable = !0, "value" in a && (a.writable = !0),
Object.defineProperty(e, a.key, a);
}
}
function d(e) {
return e && e.__esModule ? e : {
default: e
};
}
var p = a.default.dependencyLib, h = function() {
function e(t, i, a) {
!function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, e), this.mask = t, this.format = i, this.opts = a, this._date = new Date(1, 0, 1),
this.initDateObject(t, this.opts);
}
var t, i, a;
return t = e, (i = [ {
key: "date",
get: function() {
return void 0 === this._date && (this._date = new Date(1, 0, 1), this.initDateObject(void 0, this.opts)),
this._date;
}
}, {
key: "initDateObject",
value: function(e, t) {
var i;
for (P(t).lastIndex = 0; i = P(t).exec(this.format); ) {
var a = new RegExp("\\d+$").exec(i[0]), n = a ? i[0][0] + "x" : i[0], r = void 0;
if (void 0 !== e) {
if (a) {
var o = P(t).lastIndex, s = O(i.index, t);
P(t).lastIndex = o, r = e.slice(0, e.indexOf(s.nextMatch[0]));
} else r = e.slice(0, n.length);
e = e.slice(r.length);
}
Object.prototype.hasOwnProperty.call(g, n) && this.setValue(this, r, n, g[n][2], g[n][1]);
}
}
}, {
key: "setValue",
value: function(e, t, i, a, n) {
if (void 0 !== t && (e[a] = "ampm" === a ? t : t.replace(/[^0-9]/g, "0"), e["raw" + a] = t.replace(/\s/g, "_")),
void 0 !== n) {
var r = e[a];
("day" === a && 29 === parseInt(r) || "month" === a && 2 === parseInt(r)) && (29 !== parseInt(e.day) || 2 !== parseInt(e.month) || "" !== e.year && void 0 !== e.year || e._date.setFullYear(2012, 1, 29)),
"day" === a && (v = !0, 0 === parseInt(r) && (r = 1)), "month" === a && (v = !0),
"year" === a && (v = !0, r.length < 4 && (r = w(r, 4, !0))), "" === r || isNaN(r) || n.call(e._date, r),
"ampm" === a && n.call(e._date, r);
}
}
}, {
key: "reset",
value: function() {
this._date = new Date(1, 0, 1);
}
}, {
key: "reInit",
value: function() {
this._date = void 0, this.date;
}
} ]) && f(t.prototype, i), a && f(t, a), Object.defineProperty(t, "prototype", {
writable: !1
}), e;
}(), m = (new Date).getFullYear(), v = !1, g = {
d: [ "[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", Date.prototype.getDate ],
dd: [ "0[1-9]|[12][0-9]|3[01]", Date.prototype.setDate, "day", function() {
return w(Date.prototype.getDate.call(this), 2);
} ],
ddd: [ "" ],
dddd: [ "" ],
m: [ "[1-9]|1[012]", function(e) {
var t = e ? parseInt(e) : 0;
return t > 0 && t--, Date.prototype.setMonth.call(this, t);
}, "month", function() {
return Date.prototype.getMonth.call(this) + 1;
} ],
mm: [ "0[1-9]|1[012]", function(e) {
var t = e ? parseInt(e) : 0;
return t > 0 && t--, Date.prototype.setMonth.call(this, t);
}, "month", function() {
return w(Date.prototype.getMonth.call(this) + 1, 2);
} ],
mmm: [ "" ],
mmmm: [ "" ],
yy: [ "[0-9]{2}", Date.prototype.setFullYear, "year", function() {
return w(Date.prototype.getFullYear.call(this), 2);
} ],
yyyy: [ "[0-9]{4}", Date.prototype.setFullYear, "year", function() {
return w(Date.prototype.getFullYear.call(this), 4);
} ],
h: [ "[1-9]|1[0-2]", Date.prototype.setHours, "hours", Date.prototype.getHours ],
hh: [ "0[1-9]|1[0-2]", Date.prototype.setHours, "hours", function() {
return w(Date.prototype.getHours.call(this), 2);
} ],
hx: [ function(e) {
return "[0-9]{".concat(e, "}");
}, Date.prototype.setHours, "hours", function(e) {
return Date.prototype.getHours;
} ],
H: [ "1?[0-9]|2[0-3]", Date.prototype.setHours, "hours", Date.prototype.getHours ],
HH: [ "0[0-9]|1[0-9]|2[0-3]", Date.prototype.setHours, "hours", function() {
return w(Date.prototype.getHours.call(this), 2);
} ],
Hx: [ function(e) {
return "[0-9]{".concat(e, "}");
}, Date.prototype.setHours, "hours", function(e) {
return function() {
return w(Date.prototype.getHours.call(this), e);
};
} ],
M: [ "[1-5]?[0-9]", Date.prototype.setMinutes, "minutes", Date.prototype.getMinutes ],
MM: [ "0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setMinutes, "minutes", function() {
return w(Date.prototype.getMinutes.call(this), 2);
} ],
s: [ "[1-5]?[0-9]", Date.prototype.setSeconds, "seconds", Date.prototype.getSeconds ],
ss: [ "0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]", Date.prototype.setSeconds, "seconds", function() {
return w(Date.prototype.getSeconds.call(this), 2);
} ],
l: [ "[0-9]{3}", Date.prototype.setMilliseconds, "milliseconds", function() {
return w(Date.prototype.getMilliseconds.call(this), 3);
} ],
L: [ "[0-9]{2}", Date.prototype.setMilliseconds, "milliseconds", function() {
return w(Date.prototype.getMilliseconds.call(this), 2);
} ],
t: [ "[ap]", y, "ampm", b, 1 ],
tt: [ "[ap]m", y, "ampm", b, 2 ],
T: [ "[AP]", y, "ampm", b, 1 ],
TT: [ "[AP]M", y, "ampm", b, 2 ],
Z: [ ".*", void 0, "Z", function() {
var e = this.toString().match(/\((.+)\)/)[1];
e.includes(" ") && (e = (e = e.replace("-", " ").toUpperCase()).split(" ").map((function(e) {
return u(e, 1)[0];
})).join(""));
return e;
} ],
o: [ "" ],
S: [ "" ]
}, k = {
isoDate: "yyyy-mm-dd",
isoTime: "HH:MM:ss",
isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};
function y(e) {
var t = this.getHours();
e.toLowerCase().includes("p") ? this.setHours(t + 12) : e.toLowerCase().includes("a") && t >= 12 && this.setHours(t - 12);
}
function b() {
var e = this.getHours();
return (e = e || 12) >= 12 ? "PM" : "AM";
}
function x(e) {
var t = new RegExp("\\d+$").exec(e[0]);
if (t && void 0 !== t[0]) {
var i = g[e[0][0] + "x"].slice("");
return i[0] = i[0](t[0]), i[3] = i[3](t[0]), i;
}
if (g[e[0]]) return g[e[0]];
}
function P(e) {
if (!e.tokenizer) {
var t = [], i = [];
for (var a in g) if (/\.*x$/.test(a)) {
var n = a[0] + "\\d+";
-1 === i.indexOf(n) && i.push(n);
} else -1 === t.indexOf(a[0]) && t.push(a[0]);
e.tokenizer = "(" + (i.length > 0 ? i.join("|") + "|" : "") + t.join("+|") + ")+?|.",
e.tokenizer = new RegExp(e.tokenizer, "g");
}
return e.tokenizer;
}
function E(e, t, i) {
if (!v) return !0;
if (void 0 === e.rawday || !isFinite(e.rawday) && new Date(e.date.getFullYear(), isFinite(e.rawmonth) ? e.month : e.date.getMonth() + 1, 0).getDate() >= e.day || "29" == e.day && (!isFinite(e.rawyear) || void 0 === e.rawyear || "" === e.rawyear) || new Date(e.date.getFullYear(), isFinite(e.rawmonth) ? e.month : e.date.getMonth() + 1, 0).getDate() >= e.day) return t;
if ("29" == e.day) {
var a = O(t.pos, i);
if ("yyyy" === a.targetMatch[0] && t.pos - a.targetMatchIndex == 2) return t.remove = t.pos + 1,
t;
} else if ("02" == e.month && "30" == e.day && void 0 !== t.c) return e.day = "03",
e.date.setDate(3), e.date.setMonth(1), t.insert = [ {
pos: t.pos,
c: "0"
}, {
pos: t.pos + 1,
c: t.c
} ], t.caret = o.seekNext.call(this, t.pos + 1), t;
return !1;
}
function S(e, t, i, a) {
var n, o, s = "";
for (P(i).lastIndex = 0; n = P(i).exec(e); ) {
if (void 0 === t) if (o = x(n)) s += "(" + o[0] + ")"; else switch (n[0]) {
case "[":
s += "(";
break;
case "]":
s += ")?";
break;
default:
s += (0, r.default)(n[0]);
} else if (o = x(n)) if (!0 !== a && o[3]) s += o[3].call(t.date); else o[2] ? s += t["raw" + o[2]] : s += n[0]; else s += n[0];
}
return s;
}
function w(e, t, i) {
for (e = String(e), t = t || 2; e.length < t; ) e = i ? e + "0" : "0" + e;
return e;
}
function _(e, t, i) {
return "string" == typeof e ? new h(e, t, i) : e && "object" === l(e) && Object.prototype.hasOwnProperty.call(e, "date") ? e : void 0;
}
function M(e, t) {
return S(t.inputFormat, {
date: e
}, t);
}
function O(e, t) {
var i, a, n = 0, r = 0;
for (P(t).lastIndex = 0; a = P(t).exec(t.inputFormat); ) {
var o = new RegExp("\\d+$").exec(a[0]);
if ((n += r = o ? parseInt(o[0]) : a[0].length) >= e + 1) {
i = a, a = P(t).exec(t.inputFormat);
break;
}
}
return {
targetMatchIndex: n - r,
nextMatch: a,
targetMatch: i
};
}
a.default.extendAliases({
datetime: {
mask: function(e) {
return e.numericInput = !1, g.S = e.i18n.ordinalSuffix.join("|"), e.inputFormat = k[e.inputFormat] || e.inputFormat,
e.displayFormat = k[e.displayFormat] || e.displayFormat || e.inputFormat, e.outputFormat = k[e.outputFormat] || e.outputFormat || e.inputFormat,
e.placeholder = "" !== e.placeholder ? e.placeholder : e.inputFormat.replace(/[[\]]/, ""),
e.regex = S(e.inputFormat, void 0, e), e.min = _(e.min, e.inputFormat, e), e.max = _(e.max, e.inputFormat, e),
null;
},
placeholder: "",
inputFormat: "isoDateTime",
displayFormat: null,
outputFormat: null,
min: null,
max: null,
skipOptionalPartCharacter: "",
i18n: {
dayNames: [ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ],
monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
ordinalSuffix: [ "st", "nd", "rd", "th" ]
},
preValidation: function(e, t, i, a, n, r, o, s) {
if (s) return !0;
if (isNaN(i) && e[t] !== i) {
var l = O(t, n);
if (l.nextMatch && l.nextMatch[0] === i && l.targetMatch[0].length > 1) {
var u = g[l.targetMatch[0]][0];
if (new RegExp(u).test("0" + e[t - 1])) return e[t] = e[t - 1], e[t - 1] = "0",
{
fuzzy: !0,
buffer: e,
refreshFromBuffer: {
start: t - 1,
end: t + 1
},
pos: t + 1
};
}
}
return !0;
},
postValidation: function(e, t, i, a, n, r, o, l) {
var u, c;
if (o) return !0;
if (!1 === a && (((u = O(t + 1, n)).targetMatch && u.targetMatchIndex === t && u.targetMatch[0].length > 1 && void 0 !== g[u.targetMatch[0]] || (u = O(t + 2, n)).targetMatch && u.targetMatchIndex === t + 1 && u.targetMatch[0].length > 1 && void 0 !== g[u.targetMatch[0]]) && (c = g[u.targetMatch[0]][0]),
void 0 !== c && (void 0 !== r.validPositions[t + 1] && new RegExp(c).test(i + "0") ? (e[t] = i,
e[t + 1] = "0", a = {
pos: t + 2,
caret: t
}) : new RegExp(c).test("0" + i) && (e[t] = "0", e[t + 1] = i, a = {
pos: t + 2
})), !1 === a)) return a;
if (a.fuzzy && (e = a.buffer, t = a.pos), (u = O(t, n)).targetMatch && u.targetMatch[0] && void 0 !== g[u.targetMatch[0]]) {
var f = g[u.targetMatch[0]];
c = f[0];
var d = e.slice(u.targetMatchIndex, u.targetMatchIndex + u.targetMatch[0].length);
if (!1 === new RegExp(c).test(d.join("")) && 2 === u.targetMatch[0].length && r.validPositions[u.targetMatchIndex] && r.validPositions[u.targetMatchIndex + 1] && (r.validPositions[u.targetMatchIndex + 1].input = "0"),
"year" == f[2]) for (var p = s.getMaskTemplate.call(this, !1, 1, void 0, !0), h = t + 1; h < e.length; h++) e[h] = p[h],
delete r.validPositions[h];
}
var v = a, k = _(e.join(""), n.inputFormat, n);
return v && k.date.getTime() == k.date.getTime() && (n.prefillYear && (v = function(e, t, i) {
if (e.year !== e.rawyear) {
var a = m.toString(), n = e.rawyear.replace(/[^0-9]/g, ""), r = a.slice(0, n.length), o = a.slice(n.length);
if (2 === n.length && n === r) {
var s = new Date(m, e.month - 1, e.day);
e.day == s.getDate() && (!i.max || i.max.date.getTime() >= s.getTime()) && (e.date.setFullYear(m),
e.year = a, t.insert = [ {
pos: t.pos + 1,
c: o[0]
}, {
pos: t.pos + 2,
c: o[1]
} ]);
}
}
return t;
}(k, v, n)), v = function(e, t, i, a, n) {
if (!t) return t;
if (t && i.min && i.min.date.getTime() == i.min.date.getTime()) {
var r;
for (e.reset(), P(i).lastIndex = 0; r = P(i).exec(i.inputFormat); ) {
var o;
if ((o = x(r)) && o[3]) {
for (var s = o[1], l = e[o[2]], u = i.min[o[2]], c = i.max ? i.max[o[2]] : u, f = [], d = !1, p = 0; p < u.length; p++) void 0 !== a.validPositions[p + r.index] || d ? (f[p] = l[p],
d = d || l[p] > u[p]) : (f[p] = u[p], "year" === o[2] && l.length - 1 == p && u != c && (f = (parseInt(f.join("")) + 1).toString().split("")),
"ampm" === o[2] && u != c && i.min.date.getTime() > e.date.getTime() && (f[p] = c[p]));
s.call(e._date, f.join(""));
}
}
t = i.min.date.getTime() <= e.date.getTime(), e.reInit();
}
return t && i.max && i.max.date.getTime() == i.max.date.getTime() && (t = i.max.date.getTime() >= e.date.getTime()),
t;
}(k, v = E.call(this, k, v, n), n, r)), void 0 !== t && v && a.pos !== t ? {
buffer: S(n.inputFormat, k, n).split(""),
refreshFromBuffer: {
start: t,
end: a.pos
},
pos: a.caret || a.pos
} : v;
},
onKeyDown: function(e, t, i, a) {
e.ctrlKey && e.keyCode === n.default.RIGHT && (this.inputmask._valueSet(M(new Date, a)),
p(this).trigger("setvalue"));
},
onUnMask: function(e, t, i) {
return t ? S(i.outputFormat, _(e, i.inputFormat, i), i, !0) : t;
},
casing: function(e, t, i, a) {
return 0 == t.nativeDef.indexOf("[ap]") ? e.toLowerCase() : 0 == t.nativeDef.indexOf("[AP]") ? e.toUpperCase() : e;
},
onBeforeMask: function(e, t) {
return "[object Date]" === Object.prototype.toString.call(e) && (e = M(e, t)), e;
},
insertMode: !1,
shiftPositions: !1,
keepStatic: !1,
inputmode: "numeric",
prefillYear: !0
}
});
},
3851: function(e, t, i) {
var a, n = (a = i(2394)) && a.__esModule ? a : {
default: a
}, r = i(8711), o = i(4713);
n.default.extendDefinitions({
A: {
validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
casing: "upper"
},
"&": {
validator: "[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
casing: "upper"
},
"#": {
validator: "[0-9A-Fa-f]",
casing: "upper"
}
});
var s = new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");
function l(e, t, i, a, n) {
return i - 1 > -1 && "." !== t.buffer[i - 1] ? (e = t.buffer[i - 1] + e, e = i - 2 > -1 && "." !== t.buffer[i - 2] ? t.buffer[i - 2] + e : "0" + e) : e = "00" + e,
s.test(e);
}
n.default.extendAliases({
cssunit: {
regex: "[+-]?[0-9]+\\.?([0-9]+)?(px|em|rem|ex|%|in|cm|mm|pt|pc)"
},
url: {
regex: "(https?|ftp)://.*",
autoUnmask: !1,
keepStatic: !1,
tabThrough: !0
},
ip: {
mask: "i{1,3}.j{1,3}.k{1,3}.l{1,3}",
definitions: {
i: {
validator: l
},
j: {
validator: l
},
k: {
validator: l
},
l: {
validator: l
}
},
onUnMask: function(e, t, i) {
return e;
},
inputmode: "decimal",
substitutes: {
",": "."
}
},
email: {
mask: function(e) {
var t = "*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]", i = t;
if (e.separator) for (var a = 0; a < e.quantifier; a++) i += "[".concat(e.separator).concat(t, "]");
return i;
},
greedy: !1,
casing: "lower",
separator: null,
quantifier: 5,
skipOptionalPartCharacter: "",
onBeforePaste: function(e, t) {
return (e = e.toLowerCase()).replace("mailto:", "");
},
definitions: {
"*": {
validator: "[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5!#$%&'*+/=?^_`{|}~-]"
},
"-": {
validator: "[0-9A-Za-z-]"
}
},
onUnMask: function(e, t, i) {
return e;
},
inputmode: "email"
},
mac: {
mask: "##:##:##:##:##:##"
},
vin: {
mask: "V{13}9{4}",
definitions: {
V: {
validator: "[A-HJ-NPR-Za-hj-npr-z\\d]",
casing: "upper"
}
},
clearIncomplete: !0,
autoUnmask: !0
},
ssn: {
mask: "999-99-9999",
postValidation: function(e, t, i, a, n, s, l) {
var u = o.getMaskTemplate.call(this, !0, r.getLastValidPosition.call(this), !0, !0);
return /^(?!219-09-9999|078-05-1120)(?!666|000|9.{2}).{3}-(?!00).{2}-(?!0{4}).{4}$/.test(u.join(""));
}
}
});
},
207: function(e, t, i) {
var a = s(i(2394)), n = s(i(5581)), r = s(i(7184)), o = i(8711);
function s(e) {
return e && e.__esModule ? e : {
default: e
};
}
var l = a.default.dependencyLib;
function u(e, t) {
for (var i = "", n = 0; n < e.length; n++) a.default.prototype.definitions[e.charAt(n)] || t.definitions[e.charAt(n)] || t.optionalmarker[0] === e.charAt(n) || t.optionalmarker[1] === e.charAt(n) || t.quantifiermarker[0] === e.charAt(n) || t.quantifiermarker[1] === e.charAt(n) || t.groupmarker[0] === e.charAt(n) || t.groupmarker[1] === e.charAt(n) || t.alternatormarker === e.charAt(n) ? i += "\\" + e.charAt(n) : i += e.charAt(n);
return i;
}
function c(e, t, i, a) {
if (e.length > 0 && t > 0 && (!i.digitsOptional || a)) {
var n = e.indexOf(i.radixPoint), r = !1;
i.negationSymbol.back === e[e.length - 1] && (r = !0, e.length--), -1 === n && (e.push(i.radixPoint),
n = e.length - 1);
for (var o = 1; o <= t; o++) isFinite(e[n + o]) || (e[n + o] = "0");
}
return r && e.push(i.negationSymbol.back), e;
}
function f(e, t) {
var i = 0;
if ("+" === e) {
for (i in t.validPositions) ;
i = o.seekNext.call(this, parseInt(i));
}
for (var a in t.tests) if ((a = parseInt(a)) >= i) for (var n = 0, r = t.tests[a].length; n < r; n++) if ((void 0 === t.validPositions[a] || "-" === e) && t.tests[a][n].match.def === e) return a + (void 0 !== t.validPositions[a] && "-" !== e ? 1 : 0);
return i;
}
function d(e, t) {
var i = -1;
for (var a in t.validPositions) {
var n = t.validPositions[a];
if (n && n.match.def === e) {
i = parseInt(a);
break;
}
}
return i;
}
function p(e, t, i, a, n) {
var r = t.buffer ? t.buffer.indexOf(n.radixPoint) : -1, o = (-1 !== r || a && n.jitMasking) && new RegExp(n.definitions[9].validator).test(e);
return n._radixDance && -1 !== r && o && null == t.validPositions[r] ? {
insert: {
pos: r === i ? r + 1 : r,
c: n.radixPoint
},
pos: i
} : o;
}
a.default.extendAliases({
numeric: {
mask: function(e) {
e.repeat = 0, e.groupSeparator === e.radixPoint && e.digits && "0" !== e.digits && ("." === e.radixPoint ? e.groupSeparator = "," : "," === e.radixPoint ? e.groupSeparator = "." : e.groupSeparator = ""),
" " === e.groupSeparator && (e.skipOptionalPartCharacter = void 0), e.placeholder.length > 1 && (e.placeholder = e.placeholder.charAt(0)),
"radixFocus" === e.positionCaretOnClick && "" === e.placeholder && (e.positionCaretOnClick = "lvp");
var t = "0", i = e.radixPoint;
!0 === e.numericInput && void 0 === e.__financeInput ? (t = "1", e.positionCaretOnClick = "radixFocus" === e.positionCaretOnClick ? "lvp" : e.positionCaretOnClick,
e.digitsOptional = !1, isNaN(e.digits) && (e.digits = 2), e._radixDance = !1, i = "," === e.radixPoint ? "?" : "!",
"" !== e.radixPoint && void 0 === e.definitions[i] && (e.definitions[i] = {}, e.definitions[i].validator = "[" + e.radixPoint + "]",
e.definitions[i].placeholder = e.radixPoint, e.definitions[i].static = !0, e.definitions[i].generated = !0)) : (e.__financeInput = !1,
e.numericInput = !0);
var a, n = "[+]";
if (n += u(e.prefix, e), "" !== e.groupSeparator ? (void 0 === e.definitions[e.groupSeparator] && (e.definitions[e.groupSeparator] = {},
e.definitions[e.groupSeparator].validator = "[" + e.groupSeparator + "]", e.definitions[e.groupSeparator].placeholder = e.groupSeparator,
e.definitions[e.groupSeparator].static = !0, e.definitions[e.groupSeparator].generated = !0),
n += e._mask(e)) : n += "9{+}", void 0 !== e.digits && 0 !== e.digits) {
var o = e.digits.toString().split(",");
isFinite(o[0]) && o[1] && isFinite(o[1]) ? n += i + t + "{" + e.digits + "}" : (isNaN(e.digits) || parseInt(e.digits) > 0) && (e.digitsOptional || e.jitMasking ? (a = n + i + t + "{0," + e.digits + "}",
e.keepStatic = !0) : n += i + t + "{" + e.digits + "}");
} else e.inputmode = "numeric";
return n += u(e.suffix, e), n += "[-]", a && (n = [ a + u(e.suffix, e) + "[-]", n ]),
e.greedy = !1, function(e) {
void 0 === e.parseMinMaxOptions && (null !== e.min && (e.min = e.min.toString().replace(new RegExp((0,
r.default)(e.groupSeparator), "g"), ""), "," === e.radixPoint && (e.min = e.min.replace(e.radixPoint, ".")),
e.min = isFinite(e.min) ? parseFloat(e.min) : NaN, isNaN(e.min) && (e.min = Number.MIN_VALUE)),
null !== e.max && (e.max = e.max.toString().replace(new RegExp((0, r.default)(e.groupSeparator), "g"), ""),
"," === e.radixPoint && (e.max = e.max.replace(e.radixPoint, ".")), e.max = isFinite(e.max) ? parseFloat(e.max) : NaN,
isNaN(e.max) && (e.max = Number.MAX_VALUE)), e.parseMinMaxOptions = "done");
}(e), "" !== e.radixPoint && (e.substitutes["." == e.radixPoint ? "," : "."] = e.radixPoint),
n;
},
_mask: function(e) {
return "(" + e.groupSeparator + "999){+|1}";
},
digits: "*",
digitsOptional: !0,
enforceDigitsOnBlur: !1,
radixPoint: ".",
positionCaretOnClick: "radixFocus",
_radixDance: !0,
groupSeparator: "",
allowMinus: !0,
negationSymbol: {
front: "-",
back: ""
},
prefix: "",
suffix: "",
min: null,
max: null,
SetMaxOnOverflow: !1,
step: 1,
inputType: "text",
unmaskAsNumber: !1,
roundingFN: Math.round,
inputmode: "decimal",
shortcuts: {
k: "1000",
m: "1000000"
},
placeholder: "0",
greedy: !1,
rightAlign: !0,
insertMode: !0,
autoUnmask: !1,
skipOptionalPartCharacter: "",
usePrototypeDefinitions: !1,
stripLeadingZeroes: !0,
definitions: {
0: {
validator: p
},
1: {
validator: p,
definitionSymbol: "9"
},
9: {
validator: "[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]",
definitionSymbol: "*"
},
"+": {
validator: function(e, t, i, a, n) {
return n.allowMinus && ("-" === e || e === n.negationSymbol.front);
}
},
"-": {
validator: function(e, t, i, a, n) {
return n.allowMinus && e === n.negationSymbol.back;
}
}
},
preValidation: function(e, t, i, a, n, r, o, s) {
if (!1 !== n.__financeInput && i === n.radixPoint) return !1;
var l = e.indexOf(n.radixPoint), u = t;
if (t = function(e, t, i, a, n) {
return n._radixDance && n.numericInput && t !== n.negationSymbol.back && e <= i && (i > 0 || t == n.radixPoint) && (void 0 === a.validPositions[e - 1] || a.validPositions[e - 1].input !== n.negationSymbol.back) && (e -= 1),
e;
}(t, i, l, r, n), "-" === i || i === n.negationSymbol.front) {
if (!0 !== n.allowMinus) return !1;
var c = !1, p = d("+", r), h = d("-", r);
return -1 !== p && (c = [ p, h ]), !1 !== c ? {
remove: c,
caret: u - n.negationSymbol.back.length
} : {
insert: [ {
pos: f.call(this, "+", r),
c: n.negationSymbol.front,
fromIsValid: !0
}, {
pos: f.call(this, "-", r),
c: n.negationSymbol.back,
fromIsValid: void 0
} ],
caret: u + n.negationSymbol.back.length
};
}
if (i === n.groupSeparator) return {
caret: u
};
if (s) return !0;
if (-1 !== l && !0 === n._radixDance && !1 === a && i === n.radixPoint && void 0 !== n.digits && (isNaN(n.digits) || parseInt(n.digits) > 0) && l !== t) return {
caret: n._radixDance && t === l - 1 ? l + 1 : l
};
if (!1 === n.__financeInput) if (a) {
if (n.digitsOptional) return {
rewritePosition: o.end
};
if (!n.digitsOptional) {
if (o.begin > l && o.end <= l) return i === n.radixPoint ? {
insert: {
pos: l + 1,
c: "0",
fromIsValid: !0
},
rewritePosition: l
} : {
rewritePosition: l + 1
};
if (o.begin < l) return {
rewritePosition: o.begin - 1
};
}
} else if (!n.showMaskOnHover && !n.showMaskOnFocus && !n.digitsOptional && n.digits > 0 && "" === this.__valueGet.call(this.el)) return {
rewritePosition: l
};
return {
rewritePosition: t
};
},
postValidation: function(e, t, i, a, n, r, o) {
if (!1 === a) return a;
if (o) return !0;
if (null !== n.min || null !== n.max) {
var s = n.onUnMask(e.slice().reverse().join(""), void 0, l.extend({}, n, {
unmaskAsNumber: !0
}));
if (null !== n.min && s < n.min && (s.toString().length > n.min.toString().length || s < 0)) return !1;
if (null !== n.max && s > n.max) return !!n.SetMaxOnOverflow && {
refreshFromBuffer: !0,
buffer: c(n.max.toString().replace(".", n.radixPoint).split(""), n.digits, n).reverse()
};
}
return a;
},
onUnMask: function(e, t, i) {
if ("" === t && !0 === i.nullable) return t;
var a = e.replace(i.prefix, "");
return a = (a = a.replace(i.suffix, "")).replace(new RegExp((0, r.default)(i.groupSeparator), "g"), ""),
"" !== i.placeholder.charAt(0) && (a = a.replace(new RegExp(i.placeholder.charAt(0), "g"), "0")),
i.unmaskAsNumber ? ("" !== i.radixPoint && -1 !== a.indexOf(i.radixPoint) && (a = a.replace(r.default.call(this, i.radixPoint), ".")),
a = (a = a.replace(new RegExp("^" + (0, r.default)(i.negationSymbol.front)), "-")).replace(new RegExp((0,
r.default)(i.negationSymbol.back) + "$"), ""), Number(a)) : a;
},
isComplete: function(e, t) {
var i = (t.numericInput ? e.slice().reverse() : e).join("");
return i = (i = (i = (i = (i = i.replace(new RegExp("^" + (0, r.default)(t.negationSymbol.front)), "-")).replace(new RegExp((0,
r.default)(t.negationSymbol.back) + "$"), "")).replace(t.prefix, "")).replace(t.suffix, "")).replace(new RegExp((0,
r.default)(t.groupSeparator) + "([0-9]{3})", "g"), "$1"), "," === t.radixPoint && (i = i.replace((0,
r.default)(t.radixPoint), ".")), isFinite(i);
},
onBeforeMask: function(e, t) {
var i = t.radixPoint || ",";
isFinite(t.digits) && (t.digits = parseInt(t.digits)), "number" != typeof e && "number" !== t.inputType || "" === i || (e = e.toString().replace(".", i));
var a = "-" === e.charAt(0) || e.charAt(0) === t.negationSymbol.front, n = e.split(i), o = n[0].replace(/[^\-0-9]/g, ""), s = n.length > 1 ? n[1].replace(/[^0-9]/g, "") : "", l = n.length > 1;
e = o + ("" !== s ? i + s : s);
var u = 0;
if ("" !== i && (u = t.digitsOptional ? t.digits < s.length ? t.digits : s.length : t.digits,
"" !== s || !t.digitsOptional)) {
var f = Math.pow(10, u || 1);
e = e.replace((0, r.default)(i), "."), isNaN(parseFloat(e)) || (e = (t.roundingFN(parseFloat(e) * f) / f).toFixed(u)),
e = e.toString().replace(".", i);
}
if (0 === t.digits && -1 !== e.indexOf(i) && (e = e.substring(0, e.indexOf(i))),
null !== t.min || null !== t.max) {
var d = e.toString().replace(i, ".");
null !== t.min && d < t.min ? e = t.min.toString().replace(".", i) : null !== t.max && d > t.max && (e = t.max.toString().replace(".", i));
}
return a && "-" !== e.charAt(0) && (e = "-" + e), c(e.toString().split(""), u, t, l).join("");
},
onBeforeWrite: function(e, t, i, a) {
function n(e, t) {
if (!1 !== a.__financeInput || t) {
var i = e.indexOf(a.radixPoint);
-1 !== i && e.splice(i, 1);
}
if ("" !== a.groupSeparator) for (;-1 !== (i = e.indexOf(a.groupSeparator)); ) e.splice(i, 1);
return e;
}
var o, s;
if (a.stripLeadingZeroes && (s = function(e, t) {
var i = new RegExp("(^" + ("" !== t.negationSymbol.front ? (0, r.default)(t.negationSymbol.front) + "?" : "") + (0,
r.default)(t.prefix) + ")(.*)(" + (0, r.default)(t.suffix) + ("" != t.negationSymbol.back ? (0,
r.default)(t.negationSymbol.back) + "?" : "") + "$)").exec(e.slice().reverse().join("")), a = i ? i[2] : "", n = !1;
return a && (a = a.split(t.radixPoint.charAt(0))[0], n = new RegExp("^[0" + t.groupSeparator + "]*").exec(a)),
!(!n || !(n[0].length > 1 || n[0].length > 0 && n[0].length < a.length)) && n;
}(t, a))) for (var u = t.join("").lastIndexOf(s[0].split("").reverse().join("")) - (s[0] == s.input ? 0 : 1), f = s[0] == s.input ? 1 : 0, d = s[0].length - f; d > 0; d--) delete this.maskset.validPositions[u + d],
delete t[u + d];
if (e) switch (e.type) {
case "blur":
case "checkval":
if (null !== a.min) {
var p = a.onUnMask(t.slice().reverse().join(""), void 0, l.extend({}, a, {
unmaskAsNumber: !0
}));
if (null !== a.min && p < a.min) return {
refreshFromBuffer: !0,
buffer: c(a.min.toString().replace(".", a.radixPoint).split(""), a.digits, a).reverse()
};
}
if (t[t.length - 1] === a.negationSymbol.front) {
var h = new RegExp("(^" + ("" != a.negationSymbol.front ? (0, r.default)(a.negationSymbol.front) + "?" : "") + (0,
r.default)(a.prefix) + ")(.*)(" + (0, r.default)(a.suffix) + ("" != a.negationSymbol.back ? (0,
r.default)(a.negationSymbol.back) + "?" : "") + "$)").exec(n(t.slice(), !0).reverse().join(""));
0 == (h ? h[2] : "") && (o = {
refreshFromBuffer: !0,
buffer: [ 0 ]
});
} else if ("" !== a.radixPoint) {
t.indexOf(a.radixPoint) === a.suffix.length && (o && o.buffer ? o.buffer.splice(0, 1 + a.suffix.length) : (t.splice(0, 1 + a.suffix.length),
o = {
refreshFromBuffer: !0,
buffer: n(t)
}));
}
if (a.enforceDigitsOnBlur) {
var m = (o = o || {}) && o.buffer || t.slice().reverse();
o.refreshFromBuffer = !0, o.buffer = c(m, a.digits, a, !0).reverse();
}
}
return o;
},
onKeyDown: function(e, t, i, a) {
var r, o, s = l(this), u = String.fromCharCode(e.keyCode).toLowerCase();
if ((o = a.shortcuts && a.shortcuts[u]) && o.length > 1) return this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) * parseInt(o)),
s.trigger("setvalue"), !1;
if (e.ctrlKey) switch (e.keyCode) {
case n.default.UP:
return this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) + parseInt(a.step)),
s.trigger("setvalue"), !1;
case n.default.DOWN:
return this.inputmask.__valueSet.call(this, parseFloat(this.inputmask.unmaskedvalue()) - parseInt(a.step)),
s.trigger("setvalue"), !1;
}
if (!e.shiftKey && (e.keyCode === n.default.DELETE || e.keyCode === n.default.BACKSPACE || e.keyCode === n.default.BACKSPACE_SAFARI) && i.begin !== t.length) {
if (t[e.keyCode === n.default.DELETE ? i.begin - 1 : i.end] === a.negationSymbol.front) return r = t.slice().reverse(),
"" !== a.negationSymbol.front && r.shift(), "" !== a.negationSymbol.back && r.pop(),
s.trigger("setvalue", [ r.join(""), i.begin ]), !1;
if (!0 === a._radixDance) {
var f = t.indexOf(a.radixPoint);
if (a.digitsOptional) {
if (0 === f) return (r = t.slice().reverse()).pop(), s.trigger("setvalue", [ r.join(""), i.begin >= r.length ? r.length : i.begin ]),
!1;
} else if (-1 !== f && (i.begin < f || i.end < f || e.keyCode === n.default.DELETE && i.begin === f)) return i.begin !== i.end || e.keyCode !== n.default.BACKSPACE && e.keyCode !== n.default.BACKSPACE_SAFARI || i.begin++,
(r = t.slice().reverse()).splice(r.length - i.begin, i.begin - i.end + 1), r = c(r, a.digits, a).join(""),
s.trigger("setvalue", [ r, i.begin >= r.length ? f + 1 : i.begin ]), !1;
}
}
}
},
currency: {
prefix: "",
groupSeparator: ",",
alias: "numeric",
digits: 2,
digitsOptional: !1
},
decimal: {
alias: "numeric"
},
integer: {
alias: "numeric",
inputmode: "numeric",
digits: 0
},
percentage: {
alias: "numeric",
min: 0,
max: 100,
suffix: " %",
digits: 0,
allowMinus: !1
},
indianns: {
alias: "numeric",
_mask: function(e) {
return "(" + e.groupSeparator + "99){*|1}(" + e.groupSeparator + "999){1|1}";
},
groupSeparator: ",",
radixPoint: ".",
placeholder: "0",
digits: 2,
digitsOptional: !1
}
});
},
9380: function(e, t, i) {
var a;
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var n = ((a = i(8741)) && a.__esModule ? a : {
default: a
}).default ? window : {};
t.default = n;
},
7760: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.HandleNativePlaceholder = function(e, t) {
var i = e ? e.inputmask : this;
if (l.ie) {
if (e.inputmask._valueGet() !== t && (e.placeholder !== t || "" === e.placeholder)) {
var a = o.getBuffer.call(i).slice(), n = e.inputmask._valueGet();
if (n !== t) {
var r = o.getLastValidPosition.call(i);
-1 === r && n === o.getBufferTemplate.call(i).join("") ? a = [] : -1 !== r && f.call(i, a),
p(e, a);
}
}
} else e.placeholder !== t && (e.placeholder = t, "" === e.placeholder && e.removeAttribute("placeholder"));
}, t.applyInputValue = c, t.checkVal = d, t.clearOptionalTail = f, t.unmaskedvalue = function(e) {
var t = e ? e.inputmask : this, i = t.opts, a = t.maskset;
if (e) {
if (void 0 === e.inputmask) return e.value;
e.inputmask && e.inputmask.refreshValue && c(e, e.inputmask._valueGet(!0));
}
var n = [], r = a.validPositions;
for (var s in r) r[s] && r[s].match && (1 != r[s].match.static || Array.isArray(a.metadata) && !0 !== r[s].generatedInput) && n.push(r[s].input);
var l = 0 === n.length ? "" : (t.isRTL ? n.reverse() : n).join("");
if ("function" == typeof i.onUnMask) {
var u = (t.isRTL ? o.getBuffer.call(t).slice().reverse() : o.getBuffer.call(t)).join("");
l = i.onUnMask.call(t, u, l, i);
}
return l;
}, t.writeBuffer = p;
var a, n = (a = i(5581)) && a.__esModule ? a : {
default: a
}, r = i(4713), o = i(8711), s = i(7215), l = i(9845), u = i(6030);
function c(e, t) {
var i = e ? e.inputmask : this, a = i.opts;
e.inputmask.refreshValue = !1, "function" == typeof a.onBeforeMask && (t = a.onBeforeMask.call(i, t, a) || t),
d(e, !0, !1, t = t.toString().split("")), i.undoValue = i._valueGet(!0), (a.clearMaskOnLostFocus || a.clearIncomplete) && e.inputmask._valueGet() === o.getBufferTemplate.call(i).join("") && -1 === o.getLastValidPosition.call(i) && e.inputmask._valueSet("");
}
function f(e) {
e.length = 0;
for (var t, i = r.getMaskTemplate.call(this, !0, 0, !0, void 0, !0); void 0 !== (t = i.shift()); ) e.push(t);
return e;
}
function d(e, t, i, a, n) {
var l = e ? e.inputmask : this, c = l.maskset, f = l.opts, d = l.dependencyLib, h = a.slice(), m = "", v = -1, g = void 0, k = f.skipOptionalPartCharacter;
f.skipOptionalPartCharacter = "", o.resetMaskSet.call(l), c.tests = {}, v = f.radixPoint ? o.determineNewCaretPosition.call(l, {
begin: 0,
end: 0
}, !1, !1 === f.__financeInput ? "radixFocus" : void 0).begin : 0, c.p = v, l.caretPos = {
begin: v
};
var y = [], b = l.caretPos;
if (h.forEach((function(e, t) {
if (void 0 !== e) {
var a = new d.Event("_checkval");
a.keyCode = e.toString().charCodeAt(0), m += e;
var n = o.getLastValidPosition.call(l, void 0, !0);
!function(e, t) {
for (var i = r.getMaskTemplate.call(l, !0, 0).slice(e, o.seekNext.call(l, e, !1, !1)).join("").replace(/'/g, ""), a = i.indexOf(t); a > 0 && " " === i[a - 1]; ) a--;
var n = 0 === a && !o.isMask.call(l, e) && (r.getTest.call(l, e).match.nativeDef === t.charAt(0) || !0 === r.getTest.call(l, e).match.static && r.getTest.call(l, e).match.nativeDef === "'" + t.charAt(0) || " " === r.getTest.call(l, e).match.nativeDef && (r.getTest.call(l, e + 1).match.nativeDef === t.charAt(0) || !0 === r.getTest.call(l, e + 1).match.static && r.getTest.call(l, e + 1).match.nativeDef === "'" + t.charAt(0)));
if (!n && a > 0 && !o.isMask.call(l, e, !1, !0)) {
var s = o.seekNext.call(l, e);
l.caretPos.begin < s && (l.caretPos = {
begin: s
});
}
return n;
}(v, m) ? (g = u.EventHandlers.keypressEvent.call(l, a, !0, !1, i, l.caretPos.begin)) && (v = l.caretPos.begin + 1,
m = "") : g = u.EventHandlers.keypressEvent.call(l, a, !0, !1, i, n + 1), g ? (void 0 !== g.pos && c.validPositions[g.pos] && !0 === c.validPositions[g.pos].match.static && void 0 === c.validPositions[g.pos].alternation && (y.push(g.pos),
l.isRTL || (g.forwardPosition = g.pos + 1)), p.call(l, void 0, o.getBuffer.call(l), g.forwardPosition, a, !1),
l.caretPos = {
begin: g.forwardPosition,
end: g.forwardPosition
}, b = l.caretPos) : void 0 === c.validPositions[t] && h[t] === r.getPlaceholder.call(l, t) && o.isMask.call(l, t, !0) ? l.caretPos.begin++ : l.caretPos = b;
}
})), y.length > 0) {
var x, P, E = o.seekNext.call(l, -1, void 0, !1);
if (!s.isComplete.call(l, o.getBuffer.call(l)) && y.length <= E || s.isComplete.call(l, o.getBuffer.call(l)) && y.length > 0 && y.length !== E && 0 === y[0]) for (var S = E; void 0 !== (x = y.shift()); ) {
var w = new d.Event("_checkval");
if ((P = c.validPositions[x]).generatedInput = !0, w.keyCode = P.input.charCodeAt(0),
(g = u.EventHandlers.keypressEvent.call(l, w, !0, !1, i, S)) && void 0 !== g.pos && g.pos !== x && c.validPositions[g.pos] && !0 === c.validPositions[g.pos].match.static) y.push(g.pos); else if (!g) break;
S++;
}
}
t && p.call(l, e, o.getBuffer.call(l), g ? g.forwardPosition : l.caretPos.begin, n || new d.Event("checkval"), n && ("input" === n.type && l.undoValue !== o.getBuffer.call(l).join("") || "paste" === n.type)),
f.skipOptionalPartCharacter = k;
}
function p(e, t, i, a, r) {
var l = e ? e.inputmask : this, u = l.opts, c = l.dependencyLib;
if (a && "function" == typeof u.onBeforeWrite) {
var f = u.onBeforeWrite.call(l, a, t, i, u);
if (f) {
if (f.refreshFromBuffer) {
var d = f.refreshFromBuffer;
s.refreshFromBuffer.call(l, !0 === d ? d : d.start, d.end, f.buffer || t), t = o.getBuffer.call(l, !0);
}
void 0 !== i && (i = void 0 !== f.caret ? f.caret : i);
}
}
if (void 0 !== e && (e.inputmask._valueSet(t.join("")), void 0 === i || void 0 !== a && "blur" === a.type || o.caret.call(l, e, i, void 0, void 0, void 0 !== a && "keydown" === a.type && (a.keyCode === n.default.DELETE || a.keyCode === n.default.BACKSPACE)),
!0 === r)) {
var p = c(e), h = e.inputmask._valueGet();
e.inputmask.skipInputEvent = !0, p.trigger("input"), setTimeout((function() {
h === o.getBufferTemplate.call(l).join("") ? p.trigger("cleared") : !0 === s.isComplete.call(l, t) && p.trigger("complete");
}), 0);
}
}
},
2394: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0, i(7149), i(3194);
var a = i(157), n = v(i(3287)), r = v(i(9380)), o = i(2391), s = i(4713), l = i(8711), u = i(7215), c = i(7760), f = i(9716), d = v(i(7392)), p = v(i(3976)), h = v(i(8741));
function m(e) {
return m = "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;
}, m(e);
}
function v(e) {
return e && e.__esModule ? e : {
default: e
};
}
var g = r.default.document, k = "_inputmask_opts";
function y(e, t, i) {
if (h.default) {
if (!(this instanceof y)) return new y(e, t, i);
this.dependencyLib = n.default, this.el = void 0, this.events = {}, this.maskset = void 0,
!0 !== i && ("[object Object]" === Object.prototype.toString.call(e) ? t = e : (t = t || {},
e && (t.alias = e)), this.opts = n.default.extend(!0, {}, this.defaults, t), this.noMasksCache = t && void 0 !== t.definitions,
this.userOptions = t || {}, b(this.opts.alias, t, this.opts)), this.refreshValue = !1,
this.undoValue = void 0, this.$el = void 0, this.skipKeyPressEvent = !1, this.skipInputEvent = !1,
this.validationEvent = !1, this.ignorable = !1, this.maxLength, this.mouseEnter = !1,
this.originalPlaceholder = void 0, this.isComposing = !1;
}
}
function b(e, t, i) {
var a = y.prototype.aliases[e];
return a ? (a.alias && b(a.alias, void 0, i), n.default.extend(!0, i, a), n.default.extend(!0, i, t),
!0) : (null === i.mask && (i.mask = e), !1);
}
y.prototype = {
dataAttribute: "data-inputmask",
defaults: p.default,
definitions: d.default,
aliases: {},
masksCache: {},
get isRTL() {
return this.opts.isRTL || this.opts.numericInput;
},
mask: function(e) {
var t = this;
return "string" == typeof e && (e = g.getElementById(e) || g.querySelectorAll(e)),
(e = e.nodeName ? [ e ] : Array.isArray(e) ? e : Array.from(e)).forEach((function(e, i) {
var s = n.default.extend(!0, {}, t.opts);
if (function(e, t, i, a) {
function o(t, n) {
var o = "" === a ? t : a + "-" + t;
null !== (n = void 0 !== n ? n : e.getAttribute(o)) && ("string" == typeof n && (0 === t.indexOf("on") ? n = r.default[n] : "false" === n ? n = !1 : "true" === n && (n = !0)),
i[t] = n);
}
if (!0 === t.importDataAttributes) {
var s, l, u, c, f = e.getAttribute(a);
if (f && "" !== f && (f = f.replace(/'/g, '"'), l = JSON.parse("{" + f + "}")),
l) for (c in u = void 0, l) if ("alias" === c.toLowerCase()) {
u = l[c];
break;
}
for (s in o("alias", u), i.alias && b(i.alias, i, t), t) {
if (l) for (c in u = void 0, l) if (c.toLowerCase() === s.toLowerCase()) {
u = l[c];
break;
}
o(s, u);
}
}
n.default.extend(!0, t, i), ("rtl" === e.dir || t.rightAlign) && (e.style.textAlign = "right");
("rtl" === e.dir || t.numericInput) && (e.dir = "ltr", e.removeAttribute("dir"),
t.isRTL = !0);
return Object.keys(i).length;
}(e, s, n.default.extend(!0, {}, t.userOptions), t.dataAttribute)) {
var l = (0, o.generateMaskSet)(s, t.noMasksCache);
void 0 !== l && (void 0 !== e.inputmask && (e.inputmask.opts.autoUnmask = !0, e.inputmask.remove()),
e.inputmask = new y(void 0, void 0, !0), e.inputmask.opts = s, e.inputmask.noMasksCache = t.noMasksCache,
e.inputmask.userOptions = n.default.extend(!0, {}, t.userOptions), e.inputmask.el = e,
e.inputmask.$el = (0, n.default)(e), e.inputmask.maskset = l, n.default.data(e, k, t.userOptions),
a.mask.call(e.inputmask));
}
})), e && e[0] && e[0].inputmask || this;
},
option: function(e, t) {
return "string" == typeof e ? this.opts[e] : "object" === m(e) ? (n.default.extend(this.userOptions, e),
this.el && !0 !== t && this.mask(this.el), this) : void 0;
},
unmaskedvalue: function(e) {
if (this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
void 0 === this.el || void 0 !== e) {
var t = ("function" == typeof this.opts.onBeforeMask && this.opts.onBeforeMask.call(this, e, this.opts) || e).split("");
c.checkVal.call(this, void 0, !1, !1, t), "function" == typeof this.opts.onBeforeWrite && this.opts.onBeforeWrite.call(this, void 0, l.getBuffer.call(this), 0, this.opts);
}
return c.unmaskedvalue.call(this, this.el);
},
remove: function() {
if (this.el) {
n.default.data(this.el, k, null);
var e = this.opts.autoUnmask ? (0, c.unmaskedvalue)(this.el) : this._valueGet(this.opts.autoUnmask);
e !== l.getBufferTemplate.call(this).join("") ? this._valueSet(e, this.opts.autoUnmask) : this._valueSet(""),
f.EventRuler.off(this.el), Object.getOwnPropertyDescriptor && Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.el), "value") && this.__valueGet && Object.defineProperty(this.el, "value", {
get: this.__valueGet,
set: this.__valueSet,
configurable: !0
}) : g.__lookupGetter__ && this.el.__lookupGetter__("value") && this.__valueGet && (this.el.__defineGetter__("value", this.__valueGet),
this.el.__defineSetter__("value", this.__valueSet)), this.el.inputmask = void 0;
}
return this.el;
},
getemptymask: function() {
return this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
l.getBufferTemplate.call(this).join("");
},
hasMaskedValue: function() {
return !this.opts.autoUnmask;
},
isComplete: function() {
return this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
u.isComplete.call(this, l.getBuffer.call(this));
},
getmetadata: function() {
if (this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
Array.isArray(this.maskset.metadata)) {
var e = s.getMaskTemplate.call(this, !0, 0, !1).join("");
return this.maskset.metadata.forEach((function(t) {
return t.mask !== e || (e = t, !1);
})), e;
}
return this.maskset.metadata;
},
isValid: function(e) {
if (this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache),
e) {
var t = ("function" == typeof this.opts.onBeforeMask && this.opts.onBeforeMask.call(this, e, this.opts) || e).split("");
c.checkVal.call(this, void 0, !0, !1, t);
} else e = this.isRTL ? l.getBuffer.call(this).slice().reverse().join("") : l.getBuffer.call(this).join("");
for (var i = l.getBuffer.call(this), a = l.determineLastRequiredPosition.call(this), n = i.length - 1; n > a && !l.isMask.call(this, n); n--) ;
return i.splice(a, n + 1 - a), u.isComplete.call(this, i) && e === (this.isRTL ? l.getBuffer.call(this).slice().reverse().join("") : l.getBuffer.call(this).join(""));
},
format: function(e, t) {
this.maskset = this.maskset || (0, o.generateMaskSet)(this.opts, this.noMasksCache);
var i = ("function" == typeof this.opts.onBeforeMask && this.opts.onBeforeMask.call(this, e, this.opts) || e).split("");
c.checkVal.call(this, void 0, !0, !1, i);
var a = this.isRTL ? l.getBuffer.call(this).slice().reverse().join("") : l.getBuffer.call(this).join("");
return t ? {
value: a,
metadata: this.getmetadata()
} : a;
},
setValue: function(e) {
this.el && (0, n.default)(this.el).trigger("setvalue", [ e ]);
},
analyseMask: o.analyseMask
}, y.extendDefaults = function(e) {
n.default.extend(!0, y.prototype.defaults, e);
}, y.extendDefinitions = function(e) {
n.default.extend(!0, y.prototype.definitions, e);
}, y.extendAliases = function(e) {
n.default.extend(!0, y.prototype.aliases, e);
}, y.format = function(e, t, i) {
return y(t).format(e, i);
}, y.unmask = function(e, t) {
return y(t).unmaskedvalue(e);
}, y.isValid = function(e, t) {
return y(t).isValid(e);
}, y.remove = function(e) {
"string" == typeof e && (e = g.getElementById(e) || g.querySelectorAll(e)), (e = e.nodeName ? [ e ] : e).forEach((function(e) {
e.inputmask && e.inputmask.remove();
}));
}, y.setValue = function(e, t) {
"string" == typeof e && (e = g.getElementById(e) || g.querySelectorAll(e)), (e = e.nodeName ? [ e ] : e).forEach((function(e) {
e.inputmask ? e.inputmask.setValue(t) : (0, n.default)(e).trigger("setvalue", [ t ]);
}));
}, y.dependencyLib = n.default, r.default.Inputmask = y;
var x = y;
t.default = x;
},
5296: function(e, t, i) {
function a(e) {
return a = "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;
}, a(e);
}
var n = h(i(9380)), r = h(i(2394)), o = h(i(8741));
function s(e, t) {
for (var i = 0; i < t.length; i++) {
var a = t[i];
a.enumerable = a.enumerable || !1, a.configurable = !0, "value" in a && (a.writable = !0),
Object.defineProperty(e, a.key, a);
}
}
function l(e, t) {
if (t && ("object" === a(t) || "function" == typeof t)) return t;
if (void 0 !== t) throw new TypeError("Derived constructors may only return object or undefined");
return function(e) {
if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
return e;
}(e);
}
function u(e) {
var t = "function" == typeof Map ? new Map : void 0;
return u = function(e) {
if (null === e || (i = e, -1 === Function.toString.call(i).indexOf("[native code]"))) return e;
var i;
if ("function" != typeof e) throw new TypeError("Super expression must either be null or a function");
if (void 0 !== t) {
if (t.has(e)) return t.get(e);
t.set(e, a);
}
function a() {
return c(e, arguments, p(this).constructor);
}
return a.prototype = Object.create(e.prototype, {
constructor: {
value: a,
enumerable: !1,
writable: !0,
configurable: !0
}
}), d(a, e);
}, u(e);
}
function c(e, t, i) {
return c = f() ? Reflect.construct : function(e, t, i) {
var a = [ null ];
a.push.apply(a, t);
var n = new (Function.bind.apply(e, a));
return i && d(n, i.prototype), n;
}, c.apply(null, arguments);
}
function f() {
if ("undefined" == typeof Reflect || !Reflect.construct) return !1;
if (Reflect.construct.sham) return !1;
if ("function" == typeof Proxy) return !0;
try {
return Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], (function() {}))),
!0;
} catch (e) {
return !1;
}
}
function d(e, t) {
return d = Object.setPrototypeOf || function(e, t) {
return e.__proto__ = t, e;
}, d(e, t);
}
function p(e) {
return p = Object.setPrototypeOf ? Object.getPrototypeOf : function(e) {
return e.__proto__ || Object.getPrototypeOf(e);
}, p(e);
}
function h(e) {
return e && e.__esModule ? e : {
default: e
};
}
var m = n.default.document;
if (o.default && m && m.head && m.head.attachShadow && n.default.customElements && void 0 === n.default.customElements.get("input-mask")) {
var v = function(e) {
!function(e, t) {
if ("function" != typeof t && null !== t) throw new TypeError("Super expression must either be null or a function");
Object.defineProperty(e, "prototype", {
value: Object.create(t && t.prototype, {
constructor: {
value: e,
writable: !0,
configurable: !0
}
}),
writable: !1
}), t && d(e, t);
}(c, e);
var t, i, a, n, o, u = (t = c, i = f(), function() {
var e, a = p(t);
if (i) {
var n = p(this).constructor;
e = Reflect.construct(a, arguments, n);
} else e = a.apply(this, arguments);
return l(this, e);
});
function c() {
var e;
!function(e, t) {
if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function");
}(this, c);
var t = (e = u.call(this)).getAttributeNames(), i = e.attachShadow({
mode: "closed"
}), a = m.createElement("input");
for (var n in a.type = "text", i.appendChild(a), t) Object.prototype.hasOwnProperty.call(t, n) && a.setAttribute(t[n], e.getAttribute(t[n]));
var o = new r.default;
return o.dataAttribute = "", o.mask(a), a.inputmask.shadowRoot = i, e;
}
return a = c, n && s(a.prototype, n), o && s(a, o), Object.defineProperty(a, "prototype", {
writable: !1
}), a;
}(u(HTMLElement));
n.default.customElements.define("input-mask", v);
}
},
443: function(e, t, i) {
var a = o(i(2047)), n = o(i(2394));
function r(e) {
return r = "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;
}, r(e);
}
function o(e) {
return e && e.__esModule ? e : {
default: e
};
}
void 0 === a.default.fn.inputmask && (a.default.fn.inputmask = function(e, t) {
var i, o = this[0];
if (void 0 === t && (t = {}), "string" == typeof e) switch (e) {
case "unmaskedvalue":
return o && o.inputmask ? o.inputmask.unmaskedvalue() : (0, a.default)(o).val();
case "remove":
return this.each((function() {
this.inputmask && this.inputmask.remove();
}));
case "getemptymask":
return o && o.inputmask ? o.inputmask.getemptymask() : "";
case "hasMaskedValue":
return !(!o || !o.inputmask) && o.inputmask.hasMaskedValue();
case "isComplete":
return !o || !o.inputmask || o.inputmask.isComplete();
case "getmetadata":
return o && o.inputmask ? o.inputmask.getmetadata() : void 0;
case "setvalue":
n.default.setValue(o, t);
break;
case "option":
if ("string" != typeof t) return this.each((function() {
if (void 0 !== this.inputmask) return this.inputmask.option(t);
}));
if (o && void 0 !== o.inputmask) return o.inputmask.option(t);
break;
default:
return t.alias = e, i = new n.default(t), this.each((function() {
i.mask(this);
}));
} else {
if (Array.isArray(e)) return t.alias = e, i = new n.default(t), this.each((function() {
i.mask(this);
}));
if ("object" == r(e)) return i = new n.default(e), void 0 === e.mask && void 0 === e.alias ? this.each((function() {
if (void 0 !== this.inputmask) return this.inputmask.option(e);
i.mask(this);
})) : this.each((function() {
i.mask(this);
}));
if (void 0 === e) return this.each((function() {
(i = new n.default(t)).mask(this);
}));
}
});
},
2391: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.analyseMask = function(e, t, i) {
var a, o, s, l, u, c, f = /(?:[?*+]|\{[0-9+*]+(?:,[0-9+*]*)?(?:\|[0-9+*]*)?\})|[^.?*+^${[]()|\\]+|./g, d = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, p = !1, h = new n.default, m = [], v = [], g = !1;
function k(e, a, n) {
n = void 0 !== n ? n : e.matches.length;
var o = e.matches[n - 1];
if (t) 0 === a.indexOf("[") || p && /\\d|\\s|\\w/i.test(a) || "." === a ? e.matches.splice(n++, 0, {
fn: new RegExp(a, i.casing ? "i" : ""),
static: !1,
optionality: !1,
newBlockMarker: void 0 === o ? "master" : o.def !== a,
casing: null,
def: a,
placeholder: void 0,
nativeDef: a
}) : (p && (a = a[a.length - 1]), a.split("").forEach((function(t, a) {
o = e.matches[n - 1], e.matches.splice(n++, 0, {
fn: /[a-z]/i.test(i.staticDefinitionSymbol || t) ? new RegExp("[" + (i.staticDefinitionSymbol || t) + "]", i.casing ? "i" : "") : null,
static: !0,
optionality: !1,
newBlockMarker: void 0 === o ? "master" : o.def !== t && !0 !== o.static,
casing: null,
def: i.staticDefinitionSymbol || t,
placeholder: void 0 !== i.staticDefinitionSymbol ? t : void 0,
nativeDef: (p ? "'" : "") + t
});
}))), p = !1; else {
var s = i.definitions && i.definitions[a] || i.usePrototypeDefinitions && r.default.prototype.definitions[a];
s && !p ? e.matches.splice(n++, 0, {
fn: s.validator ? "string" == typeof s.validator ? new RegExp(s.validator, i.casing ? "i" : "") : new function() {
this.test = s.validator;
} : new RegExp("."),
static: s.static || !1,
optionality: s.optional || !1,
newBlockMarker: void 0 === o || s.optional ? "master" : o.def !== (s.definitionSymbol || a),
casing: s.casing,
def: s.definitionSymbol || a,
placeholder: s.placeholder,
nativeDef: a,
generated: s.generated
}) : (e.matches.splice(n++, 0, {
fn: /[a-z]/i.test(i.staticDefinitionSymbol || a) ? new RegExp("[" + (i.staticDefinitionSymbol || a) + "]", i.casing ? "i" : "") : null,
static: !0,
optionality: !1,
newBlockMarker: void 0 === o ? "master" : o.def !== a && !0 !== o.static,
casing: null,
def: i.staticDefinitionSymbol || a,
placeholder: void 0 !== i.staticDefinitionSymbol ? a : void 0,
nativeDef: (p ? "'" : "") + a
}), p = !1);
}
}
function y() {
if (m.length > 0) {
if (k(l = m[m.length - 1], o), l.isAlternator) {
u = m.pop();
for (var e = 0; e < u.matches.length; e++) u.matches[e].isGroup && (u.matches[e].isGroup = !1);
m.length > 0 ? (l = m[m.length - 1]).matches.push(u) : h.matches.push(u);
}
} else k(h, o);
}
function b(e) {
var t = new n.default(!0);
return t.openGroup = !1, t.matches = e, t;
}
function x() {
if ((s = m.pop()).openGroup = !1, void 0 !== s) if (m.length > 0) {
if ((l = m[m.length - 1]).matches.push(s), l.isAlternator) {
for (var e = (u = m.pop()).matches[0].matches ? u.matches[0].matches.length : 1, t = 0; t < u.matches.length; t++) u.matches[t].isGroup = !1,
u.matches[t].alternatorGroup = !1, null === i.keepStatic && e < (u.matches[t].matches ? u.matches[t].matches.length : 1) && (i.keepStatic = !0),
e = u.matches[t].matches ? u.matches[t].matches.length : 1;
m.length > 0 ? (l = m[m.length - 1]).matches.push(u) : h.matches.push(u);
}
} else h.matches.push(s); else y();
}
function P(e) {
var t = e.pop();
return t.isQuantifier && (t = b([ e.pop(), t ])), t;
}
t && (i.optionalmarker[0] = void 0, i.optionalmarker[1] = void 0);
for (;a = t ? d.exec(e) : f.exec(e); ) {
if (o = a[0], t) {
switch (o.charAt(0)) {
case "?":
o = "{0,1}";
break;
case "+":
case "*":
o = "{" + o + "}";
break;
case "|":
if (0 === m.length) {
var E = b(h.matches);
E.openGroup = !0, m.push(E), h.matches = [], g = !0;
}
}
if ("\\d" === o) o = "[0-9]";
}
if (p) y(); else switch (o.charAt(0)) {
case "$":
case "^":
t || y();
break;
case i.escapeChar:
p = !0, t && y();
break;
case i.optionalmarker[1]:
case i.groupmarker[1]:
x();
break;
case i.optionalmarker[0]:
m.push(new n.default(!1, !0));
break;
case i.groupmarker[0]:
m.push(new n.default(!0));
break;
case i.quantifiermarker[0]:
var S = new n.default(!1, !1, !0), w = (o = o.replace(/[{}?]/g, "")).split("|"), _ = w[0].split(","), M = isNaN(_[0]) ? _[0] : parseInt(_[0]), O = 1 === _.length ? M : isNaN(_[1]) ? _[1] : parseInt(_[1]), T = isNaN(w[1]) ? w[1] : parseInt(w[1]);
"*" !== M && "+" !== M || (M = "*" === O ? 0 : 1), S.quantifier = {
min: M,
max: O,
jit: T
};
var A = m.length > 0 ? m[m.length - 1].matches : h.matches;
if ((a = A.pop()).isAlternator) {
A.push(a), A = a.matches;
var C = new n.default(!0), D = A.pop();
A.push(C), A = C.matches, a = D;
}
a.isGroup || (a = b([ a ])), A.push(a), A.push(S);
break;
case i.alternatormarker:
if (m.length > 0) {
var j = (l = m[m.length - 1]).matches[l.matches.length - 1];
c = l.openGroup && (void 0 === j.matches || !1 === j.isGroup && !1 === j.isAlternator) ? m.pop() : P(l.matches);
} else c = P(h.matches);
if (c.isAlternator) m.push(c); else if (c.alternatorGroup ? (u = m.pop(), c.alternatorGroup = !1) : u = new n.default(!1, !1, !1, !0),
u.matches.push(c), m.push(u), c.openGroup) {
c.openGroup = !1;
var B = new n.default(!0);
B.alternatorGroup = !0, m.push(B);
}
break;
default:
y();
}
}
g && x();
for (;m.length > 0; ) s = m.pop(), h.matches.push(s);
h.matches.length > 0 && (!function e(a) {
a && a.matches && a.matches.forEach((function(n, r) {
var o = a.matches[r + 1];
(void 0 === o || void 0 === o.matches || !1 === o.isQuantifier) && n && n.isGroup && (n.isGroup = !1,
t || (k(n, i.groupmarker[0], 0), !0 !== n.openGroup && k(n, i.groupmarker[1]))),
e(n);
}));
}(h), v.push(h));
(i.numericInput || i.isRTL) && function e(t) {
for (var a in t.matches = t.matches.reverse(), t.matches) if (Object.prototype.hasOwnProperty.call(t.matches, a)) {
var n = parseInt(a);
if (t.matches[a].isQuantifier && t.matches[n + 1] && t.matches[n + 1].isGroup) {
var r = t.matches[a];
t.matches.splice(a, 1), t.matches.splice(n + 1, 0, r);
}
void 0 !== t.matches[a].matches ? t.matches[a] = e(t.matches[a]) : t.matches[a] = ((o = t.matches[a]) === i.optionalmarker[0] ? o = i.optionalmarker[1] : o === i.optionalmarker[1] ? o = i.optionalmarker[0] : o === i.groupmarker[0] ? o = i.groupmarker[1] : o === i.groupmarker[1] && (o = i.groupmarker[0]),
o);
}
var o;
return t;
}(v[0]);
return v;
}, t.generateMaskSet = function(e, t) {
var i;
function n(e, i, n) {
var o, s, l = !1;
if (null !== e && "" !== e || ((l = null !== n.regex) ? e = (e = n.regex).replace(/^(\^)(.*)(\$)$/, "$2") : (l = !0,
e = ".*")), 1 === e.length && !1 === n.greedy && 0 !== n.repeat && (n.placeholder = ""),
n.repeat > 0 || "*" === n.repeat || "+" === n.repeat) {
var u = "*" === n.repeat ? 0 : "+" === n.repeat ? 1 : n.repeat;
e = n.groupmarker[0] + e + n.groupmarker[1] + n.quantifiermarker[0] + u + "," + n.repeat + n.quantifiermarker[1];
}
return s = l ? "regex_" + n.regex : n.numericInput ? e.split("").reverse().join("") : e,
null !== n.keepStatic && (s = "ks_" + n.keepStatic + s), void 0 === r.default.prototype.masksCache[s] || !0 === t ? (o = {
mask: e,
maskToken: r.default.prototype.analyseMask(e, l, n),
validPositions: {},
_buffer: void 0,
buffer: void 0,
tests: {},
excludes: {},
metadata: i,
maskLength: void 0,
jitOffset: {}
}, !0 !== t && (r.default.prototype.masksCache[s] = o, o = a.default.extend(!0, {}, r.default.prototype.masksCache[s]))) : o = a.default.extend(!0, {}, r.default.prototype.masksCache[s]),
o;
}
"function" == typeof e.mask && (e.mask = e.mask(e));
if (Array.isArray(e.mask)) {
if (e.mask.length > 1) {
null === e.keepStatic && (e.keepStatic = !0);
var o = e.groupmarker[0];
return (e.isRTL ? e.mask.reverse() : e.mask).forEach((function(t) {
o.length > 1 && (o += e.alternatormarker), void 0 !== t.mask && "function" != typeof t.mask ? o += t.mask : o += t;
})), n(o += e.groupmarker[1], e.mask, e);
}
e.mask = e.mask.pop();
}
i = e.mask && void 0 !== e.mask.mask && "function" != typeof e.mask.mask ? n(e.mask.mask, e.mask, e) : n(e.mask, e.mask, e);
null === e.keepStatic && (e.keepStatic = !1);
return i;
};
var a = o(i(3287)), n = o(i(9695)), r = o(i(2394));
function o(e) {
return e && e.__esModule ? e : {
default: e
};
}
},
157: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.mask = function() {
var e = this, t = this.opts, i = this.el, a = this.dependencyLib;
s.EventRuler.off(i);
var f = function(t, i) {
"textarea" !== t.tagName.toLowerCase() && i.ignorables.push(n.default.ENTER);
var l = t.getAttribute("type"), u = "input" === t.tagName.toLowerCase() && i.supportsInputType.includes(l) || t.isContentEditable || "textarea" === t.tagName.toLowerCase();
if (!u) if ("input" === t.tagName.toLowerCase()) {
var c = document.createElement("input");
c.setAttribute("type", l), u = "text" === c.type, c = null;
} else u = "partial";
return !1 !== u ? function(t) {
var n, l;
function u() {
return this.inputmask ? this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : -1 !== r.getLastValidPosition.call(e) || !0 !== i.nullable ? (this.inputmask.shadowRoot || this.ownerDocument).activeElement === this && i.clearMaskOnLostFocus ? (e.isRTL ? o.clearOptionalTail.call(e, r.getBuffer.call(e).slice()).reverse() : o.clearOptionalTail.call(e, r.getBuffer.call(e).slice())).join("") : n.call(this) : "" : n.call(this);
}
function c(e) {
l.call(this, e), this.inputmask && (0, o.applyInputValue)(this, e);
}
if (!t.inputmask.__valueGet) {
if (!0 !== i.noValuePatching) {
if (Object.getOwnPropertyDescriptor) {
var f = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t), "value") : void 0;
f && f.get && f.set ? (n = f.get, l = f.set, Object.defineProperty(t, "value", {
get: u,
set: c,
configurable: !0
})) : "input" !== t.tagName.toLowerCase() && (n = function() {
return this.textContent;
}, l = function(e) {
this.textContent = e;
}, Object.defineProperty(t, "value", {
get: u,
set: c,
configurable: !0
}));
} else document.__lookupGetter__ && t.__lookupGetter__("value") && (n = t.__lookupGetter__("value"),
l = t.__lookupSetter__("value"), t.__defineGetter__("value", u), t.__defineSetter__("value", c));
t.inputmask.__valueGet = n, t.inputmask.__valueSet = l;
}
t.inputmask._valueGet = function(t) {
return e.isRTL && !0 !== t ? n.call(this.el).split("").reverse().join("") : n.call(this.el);
}, t.inputmask._valueSet = function(t, i) {
l.call(this.el, null == t ? "" : !0 !== i && e.isRTL ? t.split("").reverse().join("") : t);
}, void 0 === n && (n = function() {
return this.value;
}, l = function(e) {
this.value = e;
}, function(t) {
if (a.valHooks && (void 0 === a.valHooks[t] || !0 !== a.valHooks[t].inputmaskpatch)) {
var n = a.valHooks[t] && a.valHooks[t].get ? a.valHooks[t].get : function(e) {
return e.value;
}, s = a.valHooks[t] && a.valHooks[t].set ? a.valHooks[t].set : function(e, t) {
return e.value = t, e;
};
a.valHooks[t] = {
get: function(t) {
if (t.inputmask) {
if (t.inputmask.opts.autoUnmask) return t.inputmask.unmaskedvalue();
var a = n(t);
return -1 !== r.getLastValidPosition.call(e, void 0, void 0, t.inputmask.maskset.validPositions) || !0 !== i.nullable ? a : "";
}
return n(t);
},
set: function(e, t) {
var i = s(e, t);
return e.inputmask && (0, o.applyInputValue)(e, t), i;
},
inputmaskpatch: !0
};
}
}(t.type), function(t) {
s.EventRuler.on(t, "mouseenter", (function() {
var t = this.inputmask._valueGet(!0);
t !== (e.isRTL ? r.getBuffer.call(e).reverse() : r.getBuffer.call(e)).join("") && (0,
o.applyInputValue)(this, t);
}));
}(t));
}
}(t) : t.inputmask = void 0, u;
}(i, t);
if (!1 !== f) {
e.originalPlaceholder = i.placeholder, e.maxLength = void 0 !== i ? i.maxLength : void 0,
-1 === e.maxLength && (e.maxLength = void 0), "inputMode" in i && null === i.getAttribute("inputmode") && (i.inputMode = t.inputmode,
i.setAttribute("inputmode", t.inputmode)), !0 === f && (t.showMaskOnFocus = t.showMaskOnFocus && -1 === [ "cc-number", "cc-exp" ].indexOf(i.autocomplete),
l.iphone && (t.insertModeVisual = !1), s.EventRuler.on(i, "submit", c.EventHandlers.submitEvent),
s.EventRuler.on(i, "reset", c.EventHandlers.resetEvent), s.EventRuler.on(i, "blur", c.EventHandlers.blurEvent),
s.EventRuler.on(i, "focus", c.EventHandlers.focusEvent), s.EventRuler.on(i, "invalid", c.EventHandlers.invalidEvent),
s.EventRuler.on(i, "click", c.EventHandlers.clickEvent), s.EventRuler.on(i, "mouseleave", c.EventHandlers.mouseleaveEvent),
s.EventRuler.on(i, "mouseenter", c.EventHandlers.mouseenterEvent), s.EventRuler.on(i, "paste", c.EventHandlers.pasteEvent),
s.EventRuler.on(i, "cut", c.EventHandlers.cutEvent), s.EventRuler.on(i, "complete", t.oncomplete),
s.EventRuler.on(i, "incomplete", t.onincomplete), s.EventRuler.on(i, "cleared", t.oncleared),
!0 !== t.inputEventOnly && (s.EventRuler.on(i, "keydown", c.EventHandlers.keydownEvent),
s.EventRuler.on(i, "keypress", c.EventHandlers.keypressEvent), s.EventRuler.on(i, "keyup", c.EventHandlers.keyupEvent)),
(l.mobile || t.inputEventOnly) && i.removeAttribute("maxLength"), s.EventRuler.on(i, "input", c.EventHandlers.inputFallBackEvent),
s.EventRuler.on(i, "compositionend", c.EventHandlers.compositionendEvent)), s.EventRuler.on(i, "setvalue", c.EventHandlers.setValueEvent),
r.getBufferTemplate.call(e).join(""), e.undoValue = e._valueGet(!0);
var d = (i.inputmask.shadowRoot || i.ownerDocument).activeElement;
if ("" !== i.inputmask._valueGet(!0) || !1 === t.clearMaskOnLostFocus || d === i) {
(0, o.applyInputValue)(i, i.inputmask._valueGet(!0), t);
var p = r.getBuffer.call(e).slice();
!1 === u.isComplete.call(e, p) && t.clearIncomplete && r.resetMaskSet.call(e), t.clearMaskOnLostFocus && d !== i && (-1 === r.getLastValidPosition.call(e) ? p = [] : o.clearOptionalTail.call(e, p)),
(!1 === t.clearMaskOnLostFocus || t.showMaskOnFocus && d === i || "" !== i.inputmask._valueGet(!0)) && (0,
o.writeBuffer)(i, p), d === i && r.caret.call(e, i, r.seekNext.call(e, r.getLastValidPosition.call(e)));
}
}
};
var a, n = (a = i(5581)) && a.__esModule ? a : {
default: a
}, r = i(8711), o = i(7760), s = i(9716), l = i(9845), u = i(7215), c = i(6030);
},
9695: function(e, t) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = function(e, t, i, a) {
this.matches = [], this.openGroup = e || !1, this.alternatorGroup = !1, this.isGroup = e || !1,
this.isOptional = t || !1, this.isQuantifier = i || !1, this.isAlternator = a || !1,
this.quantifier = {
min: 1,
max: 1
};
};
},
3194: function() {
Array.prototype.includes || Object.defineProperty(Array.prototype, "includes", {
value: function(e, t) {
if (null == this) throw new TypeError('"this" is null or not defined');
var i = Object(this), a = i.length >>> 0;
if (0 === a) return !1;
for (var n = 0 | t, r = Math.max(n >= 0 ? n : a - Math.abs(n), 0); r < a; ) {
if (i[r] === e) return !0;
r++;
}
return !1;
}
});
},
7149: function() {
function e(t) {
return e = "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;
}, e(t);
}
"function" != typeof Object.getPrototypeOf && (Object.getPrototypeOf = "object" === e("test".__proto__) ? function(e) {
return e.__proto__;
} : function(e) {
return e.constructor.prototype;
});
},
8711: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.caret = function(e, t, i, a, n) {
var r, o = this, s = this.opts;
if (void 0 === t) return "selectionStart" in e && "selectionEnd" in e ? (t = e.selectionStart,
i = e.selectionEnd) : window.getSelection ? (r = window.getSelection().getRangeAt(0)).commonAncestorContainer.parentNode !== e && r.commonAncestorContainer !== e || (t = r.startOffset,
i = r.endOffset) : document.selection && document.selection.createRange && (r = document.selection.createRange(),
t = 0 - r.duplicate().moveStart("character", -e.inputmask._valueGet().length), i = t + r.text.length),
{
begin: a ? t : u.call(o, t),
end: a ? i : u.call(o, i)
};
if (Array.isArray(t) && (i = o.isRTL ? t[0] : t[1], t = o.isRTL ? t[1] : t[0]),
void 0 !== t.begin && (i = o.isRTL ? t.begin : t.end, t = o.isRTL ? t.end : t.begin),
"number" == typeof t) {
t = a ? t : u.call(o, t), i = "number" == typeof (i = a ? i : u.call(o, i)) ? i : t;
var l = parseInt(((e.ownerDocument.defaultView || window).getComputedStyle ? (e.ownerDocument.defaultView || window).getComputedStyle(e, null) : e.currentStyle).fontSize) * i;
if (e.scrollLeft = l > e.scrollWidth ? l : 0, e.inputmask.caretPos = {
begin: t,
end: i
}, s.insertModeVisual && !1 === s.insertMode && t === i && (n || i++), e === (e.inputmask.shadowRoot || e.ownerDocument).activeElement) if ("setSelectionRange" in e) e.setSelectionRange(t, i); else if (window.getSelection) {
if (r = document.createRange(), void 0 === e.firstChild || null === e.firstChild) {
var c = document.createTextNode("");
e.appendChild(c);
}
r.setStart(e.firstChild, t < e.inputmask._valueGet().length ? t : e.inputmask._valueGet().length),
r.setEnd(e.firstChild, i < e.inputmask._valueGet().length ? i : e.inputmask._valueGet().length),
r.collapse(!0);
var f = window.getSelection();
f.removeAllRanges(), f.addRange(r);
} else e.createTextRange && ((r = e.createTextRange()).collapse(!0), r.moveEnd("character", i),
r.moveStart("character", t), r.select());
}
}, t.determineLastRequiredPosition = function(e) {
var t, i, r = this, s = this.maskset, l = this.dependencyLib, u = a.getMaskTemplate.call(r, !0, o.call(r), !0, !0), c = u.length, f = o.call(r), d = {}, p = s.validPositions[f], h = void 0 !== p ? p.locator.slice() : void 0;
for (t = f + 1; t < u.length; t++) i = a.getTestTemplate.call(r, t, h, t - 1), h = i.locator.slice(),
d[t] = l.extend(!0, {}, i);
var m = p && void 0 !== p.alternation ? p.locator[p.alternation] : void 0;
for (t = c - 1; t > f && (((i = d[t]).match.optionality || i.match.optionalQuantifier && i.match.newBlockMarker || m && (m !== d[t].locator[p.alternation] && 1 != i.match.static || !0 === i.match.static && i.locator[p.alternation] && n.checkAlternationMatch.call(r, i.locator[p.alternation].toString().split(","), m.toString().split(",")) && "" !== a.getTests.call(r, t)[0].def)) && u[t] === a.getPlaceholder.call(r, t, i.match)); t--) c--;
return e ? {
l: c,
def: d[c] ? d[c].match : void 0
} : c;
}, t.determineNewCaretPosition = function(e, t, i) {
var n = this, u = this.maskset, c = this.opts;
t && (n.isRTL ? e.end = e.begin : e.begin = e.end);
if (e.begin === e.end) {
switch (i = i || c.positionCaretOnClick) {
case "none":
break;
case "select":
e = {
begin: 0,
end: r.call(n).length
};
break;
case "ignore":
e.end = e.begin = l.call(n, o.call(n));
break;
case "radixFocus":
if (function(e) {
if ("" !== c.radixPoint && 0 !== c.digits) {
var t = u.validPositions;
if (void 0 === t[e] || t[e].input === a.getPlaceholder.call(n, e)) {
if (e < l.call(n, -1)) return !0;
var i = r.call(n).indexOf(c.radixPoint);
if (-1 !== i) {
for (var o in t) if (t[o] && i < o && t[o].input !== a.getPlaceholder.call(n, o)) return !1;
return !0;
}
}
}
return !1;
}(e.begin)) {
var f = r.call(n).join("").indexOf(c.radixPoint);
e.end = e.begin = c.numericInput ? l.call(n, f) : f;
break;
}
default:
var d = e.begin, p = o.call(n, d, !0), h = l.call(n, -1 !== p || s.call(n, 0) ? p : -1);
if (d <= h) e.end = e.begin = s.call(n, d, !1, !0) ? d : l.call(n, d); else {
var m = u.validPositions[p], v = a.getTestTemplate.call(n, h, m ? m.match.locator : void 0, m), g = a.getPlaceholder.call(n, h, v.match);
if ("" !== g && r.call(n)[h] !== g && !0 !== v.match.optionalQuantifier && !0 !== v.match.newBlockMarker || !s.call(n, h, c.keepStatic, !0) && v.match.def === g) {
var k = l.call(n, h);
(d >= k || d === h) && (h = k);
}
e.end = e.begin = h;
}
}
return e;
}
}, t.getBuffer = r, t.getBufferTemplate = function() {
var e = this.maskset;
void 0 === e._buffer && (e._buffer = a.getMaskTemplate.call(this, !1, 1), void 0 === e.buffer && (e.buffer = e._buffer.slice()));
return e._buffer;
}, t.getLastValidPosition = o, t.isMask = s, t.resetMaskSet = function(e) {
var t = this.maskset;
t.buffer = void 0, !0 !== e && (t.validPositions = {}, t.p = 0);
}, t.seekNext = l, t.seekPrevious = function(e, t) {
var i = this, n = e - 1;
if (e <= 0) return 0;
for (;n > 0 && (!0 === t && (!0 !== a.getTest.call(i, n).match.newBlockMarker || !s.call(i, n, void 0, !0)) || !0 !== t && !s.call(i, n, void 0, !0)); ) n--;
return n;
}, t.translatePosition = u;
var a = i(4713), n = i(7215);
function r(e) {
var t = this.maskset;
return void 0 !== t.buffer && !0 !== e || (t.buffer = a.getMaskTemplate.call(this, !0, o.call(this), !0),
void 0 === t._buffer && (t._buffer = t.buffer.slice())), t.buffer;
}
function o(e, t, i) {
var a = this.maskset, n = -1, r = -1, o = i || a.validPositions;
for (var s in void 0 === e && (e = -1), o) {
var l = parseInt(s);
o[l] && (t || !0 !== o[l].generatedInput) && (l <= e && (n = l), l >= e && (r = l));
}
return -1 === n || n == e ? r : -1 == r || e - n < r - e ? n : r;
}
function s(e, t, i) {
var n = this, r = this.maskset, o = a.getTestTemplate.call(n, e).match;
if ("" === o.def && (o = a.getTest.call(n, e).match), !0 !== o.static) return o.fn;
if (!0 === i && void 0 !== r.validPositions[e] && !0 !== r.validPositions[e].generatedInput) return !0;
if (!0 !== t && e > -1) {
if (i) {
var s = a.getTests.call(n, e);
return s.length > 1 + ("" === s[s.length - 1].match.def ? 1 : 0);
}
var l = a.determineTestTemplate.call(n, e, a.getTests.call(n, e)), u = a.getPlaceholder.call(n, e, l.match);
return l.match.def !== u;
}
return !1;
}
function l(e, t, i) {
var n = this;
void 0 === i && (i = !0);
for (var r = e + 1; "" !== a.getTest.call(n, r).match.def && (!0 === t && (!0 !== a.getTest.call(n, r).match.newBlockMarker || !s.call(n, r, void 0, !0)) || !0 !== t && !s.call(n, r, void 0, i)); ) r++;
return r;
}
function u(e) {
var t = this.opts, i = this.el;
return !this.isRTL || "number" != typeof e || t.greedy && "" === t.placeholder || !i || (e = Math.abs(this._valueGet().length - e)),
e;
}
},
4713: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.determineTestTemplate = u, t.getDecisionTaker = o, t.getMaskTemplate = function(e, t, i, a, n) {
var r = this, o = this.opts, c = this.maskset, f = o.greedy;
n && o.greedy && (o.greedy = !1, r.maskset.tests = {});
t = t || 0;
var p, h, m, v, g = [], k = 0;
do {
if (!0 === e && c.validPositions[k]) m = n && c.validPositions[k].match.optionality && void 0 === c.validPositions[k + 1] && (!0 === c.validPositions[k].generatedInput || c.validPositions[k].input == o.skipOptionalPartCharacter && k > 0) ? u.call(r, k, d.call(r, k, p, k - 1)) : c.validPositions[k],
h = m.match, p = m.locator.slice(), g.push(!0 === i ? m.input : !1 === i ? h.nativeDef : s.call(r, k, h)); else {
m = l.call(r, k, p, k - 1), h = m.match, p = m.locator.slice();
var y = !0 !== a && (!1 !== o.jitMasking ? o.jitMasking : h.jit);
(v = (v && h.static && h.def !== o.groupSeparator && null === h.fn || c.validPositions[k - 1] && h.static && h.def !== o.groupSeparator && null === h.fn) && c.tests[k] && 1 === c.tests[k].length) || !1 === y || void 0 === y || "number" == typeof y && isFinite(y) && y > k ? g.push(!1 === i ? h.nativeDef : s.call(r, k, h)) : v = !1;
}
k++;
} while (!0 !== h.static || "" !== h.def || t > k);
"" === g[g.length - 1] && g.pop();
!1 === i && void 0 !== c.maskLength || (c.maskLength = k - 1);
return o.greedy = f, g;
}, t.getPlaceholder = s, t.getTest = c, t.getTestTemplate = l, t.getTests = d, t.isSubsetOf = f;
var a, n = (a = i(2394)) && a.__esModule ? a : {
default: a
};
function r(e, t) {
var i = (null != e.alternation ? e.mloc[o(e)] : e.locator).join("");
if ("" !== i) for (;i.length < t; ) i += "0";
return i;
}
function o(e) {
var t = e.locator[e.alternation];
return "string" == typeof t && t.length > 0 && (t = t.split(",")[0]), void 0 !== t ? t.toString() : "";
}
function s(e, t, i) {
var a = this.opts, n = this.maskset;
if (void 0 !== (t = t || c.call(this, e).match).placeholder || !0 === i) return "function" == typeof t.placeholder ? t.placeholder(a) : t.placeholder;
if (!0 === t.static) {
if (e > -1 && void 0 === n.validPositions[e]) {
var r, o = d.call(this, e), s = [];
if (o.length > 1 + ("" === o[o.length - 1].match.def ? 1 : 0)) for (var l = 0; l < o.length; l++) if ("" !== o[l].match.def && !0 !== o[l].match.optionality && !0 !== o[l].match.optionalQuantifier && (!0 === o[l].match.static || void 0 === r || !1 !== o[l].match.fn.test(r.match.def, n, e, !0, a)) && (s.push(o[l]),
!0 === o[l].match.static && (r = o[l]), s.length > 1 && /[0-9a-bA-Z]/.test(s[0].match.def))) return a.placeholder.charAt(e % a.placeholder.length);
}
return t.def;
}
return a.placeholder.charAt(e % a.placeholder.length);
}
function l(e, t, i) {
return this.maskset.validPositions[e] || u.call(this, e, d.call(this, e, t ? t.slice() : t, i));
}
function u(e, t) {
var i = this.opts, a = function(e, t) {
var i = 0, a = !1;
t.forEach((function(e) {
e.match.optionality && (0 !== i && i !== e.match.optionality && (a = !0), (0 === i || i > e.match.optionality) && (i = e.match.optionality));
})), i && (0 == e || 1 == t.length ? i = 0 : a || (i = 0));
return i;
}(e, t);
e = e > 0 ? e - 1 : 0;
var n, o, s, l = r(c.call(this, e));
i.greedy && t.length > 1 && "" === t[t.length - 1].match.def && t.pop();
for (var u = 0; u < t.length; u++) {
var f = t[u];
n = r(f, l.length);
var d = Math.abs(n - l);
(void 0 === o || "" !== n && d < o || s && !i.greedy && s.match.optionality && s.match.optionality - a > 0 && "master" === s.match.newBlockMarker && (!f.match.optionality || f.match.optionality - a < 1 || !f.match.newBlockMarker) || s && !i.greedy && s.match.optionalQuantifier && !f.match.optionalQuantifier) && (o = d,
s = f);
}
return s;
}
function c(e, t) {
var i = this.maskset;
return i.validPositions[e] ? i.validPositions[e] : (t || d.call(this, e))[0];
}
function f(e, t, i) {
function a(e) {
for (var t, i = [], a = -1, n = 0, r = e.length; n < r; n++) if ("-" === e.charAt(n)) for (t = e.charCodeAt(n + 1); ++a < t; ) i.push(String.fromCharCode(a)); else a = e.charCodeAt(n),
i.push(e.charAt(n));
return i.join("");
}
return e.match.def === t.match.nativeDef || !(!(i.regex || e.match.fn instanceof RegExp && t.match.fn instanceof RegExp) || !0 === e.match.static || !0 === t.match.static) && -1 !== a(t.match.fn.toString().replace(/[[\]/]/g, "")).indexOf(a(e.match.fn.toString().replace(/[[\]/]/g, "")));
}
function d(e, t, i) {
var a, r, o = this, s = this.dependencyLib, l = this.maskset, c = this.opts, d = this.el, p = l.maskToken, h = t ? i : 0, m = t ? t.slice() : [ 0 ], v = [], g = !1, k = t ? t.join("") : "";
function y(t, i, r, o) {
function s(r, o, u) {
function p(e, t) {
var i = 0 === t.matches.indexOf(e);
return i || t.matches.every((function(a, n) {
return !0 === a.isQuantifier ? i = p(e, t.matches[n - 1]) : Object.prototype.hasOwnProperty.call(a, "matches") && (i = p(e, a)),
!i;
})), i;
}
function m(e, t, i) {
var a, n;
if ((l.tests[e] || l.validPositions[e]) && (l.tests[e] || [ l.validPositions[e] ]).every((function(e, r) {
if (e.mloc[t]) return a = e, !1;
var o = void 0 !== i ? i : e.alternation, s = void 0 !== e.locator[o] ? e.locator[o].toString().indexOf(t) : -1;
return (void 0 === n || s < n) && -1 !== s && (a = e, n = s), !0;
})), a) {
var r = a.locator[a.alternation];
return (a.mloc[t] || a.mloc[r] || a.locator).slice((void 0 !== i ? i : a.alternation) + 1);
}
return void 0 !== i ? m(e, t) : void 0;
}
function b(e, t) {
var i = e.alternation, a = void 0 === t || i === t.alternation && -1 === e.locator[i].toString().indexOf(t.locator[i]);
if (!a && i > t.alternation) for (var n = t.alternation; n < i; n++) if (e.locator[n] !== t.locator[n]) {
i = n, a = !0;
break;
}
if (a) {
e.mloc = e.mloc || {};
var r = e.locator[i];
if (void 0 !== r) {
if ("string" == typeof r && (r = r.split(",")[0]), void 0 === e.mloc[r] && (e.mloc[r] = e.locator.slice()),
void 0 !== t) {
for (var o in t.mloc) "string" == typeof o && (o = o.split(",")[0]), void 0 === e.mloc[o] && (e.mloc[o] = t.mloc[o]);
e.locator[i] = Object.keys(e.mloc).join(",");
}
return !0;
}
e.alternation = void 0;
}
return !1;
}
function x(e, t) {
if (e.locator.length !== t.locator.length) return !1;
for (var i = e.alternation + 1; i < e.locator.length; i++) if (e.locator[i] !== t.locator[i]) return !1;
return !0;
}
if (h > e + c._maxTestPos) throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + l.mask;
if (h === e && void 0 === r.matches) {
if (v.push({
match: r,
locator: o.reverse(),
cd: k,
mloc: {}
}), !r.optionality || void 0 !== u || !(c.definitions && c.definitions[r.nativeDef] && c.definitions[r.nativeDef].optional || n.default.prototype.definitions[r.nativeDef] && n.default.prototype.definitions[r.nativeDef].optional)) return !0;
g = !0, h = e;
} else if (void 0 !== r.matches) {
if (r.isGroup && u !== r) {
if (r = s(t.matches[t.matches.indexOf(r) + 1], o, u)) return !0;
} else if (r.isOptional) {
var P = r, E = v.length;
if (r = y(r, i, o, u)) {
if (v.forEach((function(e, t) {
t >= E && (e.match.optionality = e.match.optionality ? e.match.optionality + 1 : 1);
})), a = v[v.length - 1].match, void 0 !== u || !p(a, P)) return !0;
g = !0, h = e;
}
} else if (r.isAlternator) {
var S, w = r, _ = [], M = v.slice(), O = o.length, T = !1, A = i.length > 0 ? i.shift() : -1;
if (-1 === A || "string" == typeof A) {
var C, D = h, j = i.slice(), B = [];
if ("string" == typeof A) B = A.split(","); else for (C = 0; C < w.matches.length; C++) B.push(C.toString());
if (void 0 !== l.excludes[e]) {
for (var R = B.slice(), L = 0, I = l.excludes[e].length; L < I; L++) {
var F = l.excludes[e][L].toString().split(":");
o.length == F[1] && B.splice(B.indexOf(F[0]), 1);
}
0 === B.length && (delete l.excludes[e], B = R);
}
(!0 === c.keepStatic || isFinite(parseInt(c.keepStatic)) && D >= c.keepStatic) && (B = B.slice(0, 1));
for (var N = 0; N < B.length; N++) {
C = parseInt(B[N]), v = [], i = "string" == typeof A && m(h, C, O) || j.slice();
var V = w.matches[C];
if (V && s(V, [ C ].concat(o), u)) r = !0; else if (0 === N && (T = !0), V && V.matches && V.matches.length > w.matches[0].matches.length) break;
S = v.slice(), h = D, v = [];
for (var G = 0; G < S.length; G++) {
var H = S[G], K = !1;
H.match.jit = H.match.jit || T, H.alternation = H.alternation || O, b(H);
for (var U = 0; U < _.length; U++) {
var $ = _[U];
if ("string" != typeof A || void 0 !== H.alternation && B.includes(H.locator[H.alternation].toString())) {
if (H.match.nativeDef === $.match.nativeDef) {
K = !0, b($, H);
break;
}
if (f(H, $, c)) {
b(H, $) && (K = !0, _.splice(_.indexOf($), 0, H));
break;
}
if (f($, H, c)) {
b($, H);
break;
}
if (Z = $, !0 === (W = H).match.static && !0 !== Z.match.static && Z.match.fn.test(W.match.def, l, e, !1, c, !1)) {
x(H, $) || void 0 !== d.inputmask.userOptions.keepStatic ? b(H, $) && (K = !0, _.splice(_.indexOf($), 0, H)) : c.keepStatic = !0;
break;
}
}
}
K || _.push(H);
}
}
v = M.concat(_), h = e, g = v.length > 0, r = _.length > 0, i = j.slice();
} else r = s(w.matches[A] || t.matches[A], [ A ].concat(o), u);
if (r) return !0;
} else if (r.isQuantifier && u !== t.matches[t.matches.indexOf(r) - 1]) for (var q = r, z = i.length > 0 ? i.shift() : 0; z < (isNaN(q.quantifier.max) ? z + 1 : q.quantifier.max) && h <= e; z++) {
var Q = t.matches[t.matches.indexOf(q) - 1];
if (r = s(Q, [ z ].concat(o), Q)) {
if ((a = v[v.length - 1].match).optionalQuantifier = z >= q.quantifier.min, a.jit = (z + 1) * (Q.matches.indexOf(a) + 1) > q.quantifier.jit,
a.optionalQuantifier && p(a, Q)) {
g = !0, h = e;
break;
}
return a.jit && (l.jitOffset[e] = Q.matches.length - Q.matches.indexOf(a)), !0;
}
} else if (r = y(r, i, o, u)) return !0;
} else h++;
var W, Z;
}
for (var u = i.length > 0 ? i.shift() : 0; u < t.matches.length; u++) if (!0 !== t.matches[u].isQuantifier) {
var p = s(t.matches[u], [ u ].concat(r), o);
if (p && h === e) return p;
if (h > e) break;
}
}
if (e > -1) {
if (void 0 === t) {
for (var b, x = e - 1; void 0 === (b = l.validPositions[x] || l.tests[x]) && x > -1; ) x--;
void 0 !== b && x > -1 && (m = function(e, t) {
var i, a = [];
return Array.isArray(t) || (t = [ t ]), t.length > 0 && (void 0 === t[0].alternation || !0 === c.keepStatic ? 0 === (a = u.call(o, e, t.slice()).locator.slice()).length && (a = t[0].locator.slice()) : t.forEach((function(e) {
"" !== e.def && (0 === a.length ? (i = e.alternation, a = e.locator.slice()) : e.locator[i] && -1 === a[i].toString().indexOf(e.locator[i]) && (a[i] += "," + e.locator[i]));
}))), a;
}(x, b), k = m.join(""), h = x);
}
if (l.tests[e] && l.tests[e][0].cd === k) return l.tests[e];
for (var P = m.shift(); P < p.length; P++) {
if (y(p[P], m, [ P ]) && h === e || h > e) break;
}
}
return (0 === v.length || g) && v.push({
match: {
fn: null,
static: !0,
optionality: !1,
casing: null,
def: "",
placeholder: ""
},
locator: [],
mloc: {},
cd: k
}), void 0 !== t && l.tests[e] ? r = s.extend(!0, [], v) : (l.tests[e] = s.extend(!0, [], v),
r = l.tests[e]), v.forEach((function(e) {
e.match.optionality = !1;
})), r;
}
},
7215: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.alternate = l, t.checkAlternationMatch = function(e, t, i) {
for (var a, n = this.opts.greedy ? t : t.slice(0, 1), r = !1, o = void 0 !== i ? i.split(",") : [], s = 0; s < o.length; s++) -1 !== (a = e.indexOf(o[s])) && e.splice(a, 1);
for (var l = 0; l < e.length; l++) if (n.includes(e[l])) {
r = !0;
break;
}
return r;
}, t.handleRemove = function(e, t, i, a, s) {
var u = this, c = this.maskset, f = this.opts;
if ((f.numericInput || u.isRTL) && (t === r.default.BACKSPACE ? t = r.default.DELETE : t === r.default.DELETE && (t = r.default.BACKSPACE),
u.isRTL)) {
var d = i.end;
i.end = i.begin, i.begin = d;
}
var p, h = o.getLastValidPosition.call(u, void 0, !0);
i.end >= o.getBuffer.call(u).length && h >= i.end && (i.end = h + 1);
t === r.default.BACKSPACE ? i.end - i.begin < 1 && (i.begin = o.seekPrevious.call(u, i.begin)) : t === r.default.DELETE && i.begin === i.end && (i.end = o.isMask.call(u, i.end, !0, !0) ? i.end + 1 : o.seekNext.call(u, i.end) + 1);
if (!1 !== (p = v.call(u, i))) {
if (!0 !== a && !1 !== f.keepStatic || null !== f.regex && -1 !== n.getTest.call(u, i.begin).match.def.indexOf("|")) {
var m = l.call(u, !0);
if (m) {
var g = void 0 !== m.caret ? m.caret : m.pos ? o.seekNext.call(u, m.pos.begin ? m.pos.begin : m.pos) : o.getLastValidPosition.call(u, -1, !0);
(t !== r.default.DELETE || i.begin > g) && i.begin;
}
}
!0 !== a && (c.p = t === r.default.DELETE ? i.begin + p : i.begin, c.p = o.determineNewCaretPosition.call(u, {
begin: c.p,
end: c.p
}, !1, !1 === f.insertMode && t === r.default.BACKSPACE ? "none" : void 0).begin);
}
}, t.isComplete = c, t.isSelection = f, t.isValid = d, t.refreshFromBuffer = h,
t.revalidateMask = v;
var a, n = i(4713), r = (a = i(5581)) && a.__esModule ? a : {
default: a
}, o = i(8711), s = i(6030);
function l(e, t, i, a, r, s) {
var u, c, f, p, h, m, v, g, k, y, b, x = this, P = this.dependencyLib, E = this.opts, S = x.maskset, w = P.extend(!0, {}, S.validPositions), _ = P.extend(!0, {}, S.tests), M = !1, O = !1, T = void 0 !== r ? r : o.getLastValidPosition.call(x);
if (s && (y = s.begin, b = s.end, s.begin > s.end && (y = s.end, b = s.begin)),
-1 === T && void 0 === r) u = 0, c = (p = n.getTest.call(x, u)).alternation; else for (;T >= 0; T--) if ((f = S.validPositions[T]) && void 0 !== f.alternation) {
if (p && p.locator[f.alternation] !== f.locator[f.alternation]) break;
u = T, c = S.validPositions[u].alternation, p = f;
}
if (void 0 !== c) {
v = parseInt(u), S.excludes[v] = S.excludes[v] || [], !0 !== e && S.excludes[v].push((0,
n.getDecisionTaker)(p) + ":" + p.alternation);
var A = [], C = -1;
for (h = v; h < o.getLastValidPosition.call(x, void 0, !0) + 1; h++) -1 === C && e <= h && void 0 !== t && (A.push(t),
C = A.length - 1), (m = S.validPositions[h]) && !0 !== m.generatedInput && (void 0 === s || h < y || h >= b) && A.push(m.input),
delete S.validPositions[h];
for (-1 === C && void 0 !== t && (A.push(t), C = A.length - 1); void 0 !== S.excludes[v] && S.excludes[v].length < 10; ) {
for (S.tests = {}, o.resetMaskSet.call(x, !0), M = !0, h = 0; h < A.length && (g = M.caret || o.getLastValidPosition.call(x, void 0, !0) + 1,
k = A[h], M = d.call(x, g, k, !1, a, !0)); h++) h === C && (O = M), 1 == e && M && (O = {
caretPos: h
});
if (M) break;
if (o.resetMaskSet.call(x), p = n.getTest.call(x, v), S.validPositions = P.extend(!0, {}, w),
S.tests = P.extend(!0, {}, _), !S.excludes[v]) {
O = l.call(x, e, t, i, a, v - 1, s);
break;
}
var D = (0, n.getDecisionTaker)(p);
if (-1 !== S.excludes[v].indexOf(D + ":" + p.alternation)) {
O = l.call(x, e, t, i, a, v - 1, s);
break;
}
for (S.excludes[v].push(D + ":" + p.alternation), h = v; h < o.getLastValidPosition.call(x, void 0, !0) + 1; h++) delete S.validPositions[h];
}
}
return O && !1 === E.keepStatic || delete S.excludes[v], O;
}
function u(e, t, i) {
var a = this.opts, n = this.maskset;
switch (a.casing || t.casing) {
case "upper":
e = e.toUpperCase();
break;
case "lower":
e = e.toLowerCase();
break;
case "title":
var o = n.validPositions[i - 1];
e = 0 === i || o && o.input === String.fromCharCode(r.default.SPACE) ? e.toUpperCase() : e.toLowerCase();
break;
default:
if ("function" == typeof a.casing) {
var s = Array.prototype.slice.call(arguments);
s.push(n.validPositions), e = a.casing.apply(this, s);
}
}
return e;
}
function c(e) {
var t = this, i = this.opts, a = this.maskset;
if ("function" == typeof i.isComplete) return i.isComplete(e, i);
if ("*" !== i.repeat) {
var r = !1, s = o.determineLastRequiredPosition.call(t, !0), l = o.seekPrevious.call(t, s.l);
if (void 0 === s.def || s.def.newBlockMarker || s.def.optionality || s.def.optionalQuantifier) {
r = !0;
for (var u = 0; u <= l; u++) {
var c = n.getTestTemplate.call(t, u).match;
if (!0 !== c.static && void 0 === a.validPositions[u] && !0 !== c.optionality && !0 !== c.optionalQuantifier || !0 === c.static && e[u] !== n.getPlaceholder.call(t, u, c)) {
r = !1;
break;
}
}
}
return r;
}
}
function f(e) {
var t = this.opts.insertMode ? 0 : 1;
return this.isRTL ? e.begin - e.end > t : e.end - e.begin > t;
}
function d(e, t, i, a, r, s, p) {
var g = this, k = this.dependencyLib, y = this.opts, b = g.maskset;
i = !0 === i;
var x = e;
function P(e) {
if (void 0 !== e) {
if (void 0 !== e.remove && (Array.isArray(e.remove) || (e.remove = [ e.remove ]),
e.remove.sort((function(e, t) {
return t.pos - e.pos;
})).forEach((function(e) {
v.call(g, {
begin: e,
end: e + 1
});
})), e.remove = void 0), void 0 !== e.insert && (Array.isArray(e.insert) || (e.insert = [ e.insert ]),
e.insert.sort((function(e, t) {
return e.pos - t.pos;
})).forEach((function(e) {
"" !== e.c && d.call(g, e.pos, e.c, void 0 === e.strict || e.strict, void 0 !== e.fromIsValid ? e.fromIsValid : a);
})), e.insert = void 0), e.refreshFromBuffer && e.buffer) {
var t = e.refreshFromBuffer;
h.call(g, !0 === t ? t : t.start, t.end, e.buffer), e.refreshFromBuffer = void 0;
}
void 0 !== e.rewritePosition && (x = e.rewritePosition, e = !0);
}
return e;
}
function E(t, i, r) {
var s = !1;
return n.getTests.call(g, t).every((function(l, c) {
var d = l.match;
if (o.getBuffer.call(g, !0), !1 !== (s = (!d.jit || void 0 !== b.validPositions[o.seekPrevious.call(g, t)]) && (null != d.fn ? d.fn.test(i, b, t, r, y, f.call(g, e)) : (i === d.def || i === y.skipOptionalPartCharacter) && "" !== d.def && {
c: n.getPlaceholder.call(g, t, d, !0) || d.def,
pos: t
}))) {
var p = void 0 !== s.c ? s.c : i, h = t;
return p = p === y.skipOptionalPartCharacter && !0 === d.static ? n.getPlaceholder.call(g, t, d, !0) || d.def : p,
!0 !== (s = P(s)) && void 0 !== s.pos && s.pos !== t && (h = s.pos), !0 !== s && void 0 === s.pos && void 0 === s.c ? !1 : (!1 === v.call(g, e, k.extend({}, l, {
input: u.call(g, p, d, h)
}), a, h) && (s = !1), !1);
}
return !0;
})), s;
}
void 0 !== e.begin && (x = g.isRTL ? e.end : e.begin);
var S = !0, w = k.extend(!0, {}, b.validPositions);
if (!1 === y.keepStatic && void 0 !== b.excludes[x] && !0 !== r && !0 !== a) for (var _ = x; _ < (g.isRTL ? e.begin : e.end); _++) void 0 !== b.excludes[_] && (b.excludes[_] = void 0,
delete b.tests[_]);
if ("function" == typeof y.preValidation && !0 !== a && !0 !== s && (S = P(S = y.preValidation.call(g, o.getBuffer.call(g), x, t, f.call(g, e), y, b, e, i || r))),
!0 === S) {
if (S = E(x, t, i), (!i || !0 === a) && !1 === S && !0 !== s) {
var M = b.validPositions[x];
if (!M || !0 !== M.match.static || M.match.def !== t && t !== y.skipOptionalPartCharacter) {
if (y.insertMode || void 0 === b.validPositions[o.seekNext.call(g, x)] || e.end > x) {
var O = !1;
if (b.jitOffset[x] && void 0 === b.validPositions[o.seekNext.call(g, x)] && !1 !== (S = d.call(g, x + b.jitOffset[x], t, !0, !0)) && (!0 !== r && (S.caret = x),
O = !0), e.end > x && (b.validPositions[x] = void 0), !O && !o.isMask.call(g, x, y.keepStatic && 0 === x)) for (var T = x + 1, A = o.seekNext.call(g, x, !1, 0 !== x); T <= A; T++) if (!1 !== (S = E(T, t, i))) {
S = m.call(g, x, void 0 !== S.pos ? S.pos : T) || S, x = T;
break;
}
}
} else S = {
caret: o.seekNext.call(g, x)
};
}
!1 !== S || !y.keepStatic || !c.call(g, o.getBuffer.call(g)) && 0 !== x || i || !0 === r ? f.call(g, e) && b.tests[x] && b.tests[x].length > 1 && y.keepStatic && !i && !0 !== r && (S = l.call(g, !0)) : S = l.call(g, x, t, i, a, void 0, e),
!0 === S && (S = {
pos: x
});
}
if ("function" == typeof y.postValidation && !0 !== a && !0 !== s) {
var C = y.postValidation.call(g, o.getBuffer.call(g, !0), void 0 !== e.begin ? g.isRTL ? e.end : e.begin : e, t, S, y, b, i, p);
void 0 !== C && (S = !0 === C ? S : C);
}
S && void 0 === S.pos && (S.pos = x), !1 === S || !0 === s ? (o.resetMaskSet.call(g, !0),
b.validPositions = k.extend(!0, {}, w)) : m.call(g, void 0, x, !0);
var D = P(S);
void 0 !== g.maxLength && (o.getBuffer.call(g).length > g.maxLength && !a && (o.resetMaskSet.call(g, !0),
b.validPositions = k.extend(!0, {}, w), D = !1));
return D;
}
function p(e, t, i) {
for (var a = this.maskset, r = !1, o = n.getTests.call(this, e), s = 0; s < o.length; s++) {
if (o[s].match && (o[s].match.nativeDef === t.match[i.shiftPositions ? "def" : "nativeDef"] && (!i.shiftPositions || !t.match.static) || o[s].match.nativeDef === t.match.nativeDef || i.regex && !o[s].match.static && o[s].match.fn.test(t.input))) {
r = !0;
break;
}
if (o[s].match && o[s].match.def === t.match.nativeDef) {
r = void 0;
break;
}
}
return !1 === r && void 0 !== a.jitOffset[e] && (r = p.call(this, e + a.jitOffset[e], t, i)),
r;
}
function h(e, t, i) {
var a, n, r = this, l = this.maskset, u = this.opts, c = this.dependencyLib, f = u.skipOptionalPartCharacter, d = r.isRTL ? i.slice().reverse() : i;
if (u.skipOptionalPartCharacter = "", !0 === e) o.resetMaskSet.call(r), l.tests = {},
e = 0, t = i.length, n = o.determineNewCaretPosition.call(r, {
begin: 0,
end: 0
}, !1).begin; else {
for (a = e; a < t; a++) delete l.validPositions[a];
n = e;
}
var p = new c.Event("keypress");
for (a = e; a < t; a++) {
p.keyCode = d[a].toString().charCodeAt(0), r.ignorable = !1;
var h = s.EventHandlers.keypressEvent.call(r, p, !0, !1, !1, n);
!1 !== h && void 0 !== h && (n = h.forwardPosition);
}
u.skipOptionalPartCharacter = f;
}
function m(e, t, i) {
var a = this, r = this.maskset, s = this.dependencyLib;
if (void 0 === e) for (e = t - 1; e > 0 && !r.validPositions[e]; e--) ;
for (var l = e; l < t; l++) {
if (void 0 === r.validPositions[l] && !o.isMask.call(a, l, !1)) if (0 == l ? n.getTest.call(a, l) : r.validPositions[l - 1]) {
var u = n.getTests.call(a, l).slice();
"" === u[u.length - 1].match.def && u.pop();
var c, f = n.determineTestTemplate.call(a, l, u);
if (f && (!0 !== f.match.jit || "master" === f.match.newBlockMarker && (c = r.validPositions[l + 1]) && !0 === c.match.optionalQuantifier) && ((f = s.extend({}, f, {
input: n.getPlaceholder.call(a, l, f.match, !0) || f.match.def
})).generatedInput = !0, v.call(a, l, f, !0), !0 !== i)) {
var p = r.validPositions[t].input;
return r.validPositions[t] = void 0, d.call(a, t, p, !0, !0);
}
}
}
}
function v(e, t, i, a) {
var r = this, s = this.maskset, l = this.opts, u = this.dependencyLib;
function c(e, t, i) {
var a = t[e];
if (void 0 !== a && !0 === a.match.static && !0 !== a.match.optionality && (void 0 === t[0] || void 0 === t[0].alternation)) {
var n = i.begin <= e - 1 ? t[e - 1] && !0 === t[e - 1].match.static && t[e - 1] : t[e - 1], r = i.end > e + 1 ? t[e + 1] && !0 === t[e + 1].match.static && t[e + 1] : t[e + 1];
return n && r;
}
return !1;
}
var f = 0, h = void 0 !== e.begin ? e.begin : e, m = void 0 !== e.end ? e.end : e, v = !0;
if (e.begin > e.end && (h = e.end, m = e.begin), a = void 0 !== a ? a : h, h !== m || l.insertMode && void 0 !== s.validPositions[a] && void 0 === i || void 0 === t || t.match.optionalQuantifier || t.match.optionality) {
var g, k = u.extend(!0, {}, s.validPositions), y = o.getLastValidPosition.call(r, void 0, !0);
for (s.p = h, g = y; g >= h; g--) delete s.validPositions[g], void 0 === t && delete s.tests[g + 1];
var b, x, P = a, E = P;
for (t && (s.validPositions[a] = u.extend(!0, {}, t), E++, P++), g = t ? m : m - 1; g <= y; g++) {
if (void 0 !== (b = k[g]) && !0 !== b.generatedInput && (g >= m || g >= h && c(g, k, {
begin: h,
end: m
}))) {
for (;"" !== n.getTest.call(r, E).match.def; ) {
if (!1 !== (x = p.call(r, E, b, l)) || "+" === b.match.def) {
"+" === b.match.def && o.getBuffer.call(r, !0);
var S = d.call(r, E, b.input, "+" !== b.match.def, !0);
if (v = !1 !== S, P = (S.pos || E) + 1, !v && x) break;
} else v = !1;
if (v) {
void 0 === t && b.match.static && g === e.begin && f++;
break;
}
if (!v && o.getBuffer.call(r), E > s.maskLength) break;
E++;
}
"" == n.getTest.call(r, E).match.def && (v = !1), E = P;
}
if (!v) break;
}
if (!v) return s.validPositions = u.extend(!0, {}, k), o.resetMaskSet.call(r, !0),
!1;
} else t && n.getTest.call(r, a).match.cd === t.match.cd && (s.validPositions[a] = u.extend(!0, {}, t));
return o.resetMaskSet.call(r, !0), f;
}
},
2047: function(t) {
t.exports = e;
},
5581: function(e) {
e.exports = JSON.parse('{"BACKSPACE":8,"BACKSPACE_SAFARI":127,"DELETE":46,"DOWN":40,"END":35,"ENTER":13,"ESCAPE":27,"HOME":36,"INSERT":45,"LEFT":37,"PAGE_DOWN":34,"PAGE_UP":33,"RIGHT":39,"SPACE":32,"TAB":9,"UP":38,"X":88,"Z":90,"CONTROL":17,"PAUSE/BREAK":19,"WINDOWS_LEFT":91,"WINDOWS_RIGHT":92,"KEY_229":229}');
}
}, i = {};
function a(e) {
var n = i[e];
if (void 0 !== n) return n.exports;
var r = i[e] = {
exports: {}
};
return t[e](r, r.exports, a), r.exports;
}
var n = {};
return function() {
var e = n;
Object.defineProperty(e, "__esModule", {
value: !0
}), e.default = void 0;
var t, i = (t = a(3046)) && t.__esModule ? t : {
default: t
};
a(443);
var r = i.default;
e.default = r;
}(), n;
}();
}));
|
294coder/Efficient-MIF
| 8,030 |
utils/sharpening_index/my_q2n.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
#
# 由于dat及其方差等数值舍入存在误差,最终结果有0.001左右的误差
import numpy as np
import torch
import math
def q2n(gt, x, q_blocks_size, q_shift):
'''
'''
if isinstance(gt, torch.Tensor):
gt = gt.cpu().numpy()
x = x.cpu().numpy()
N1, N2, N3 = gt.shape # 255 255 8
size2 = q_blocks_size # 32
stepx = math.ceil(N1 / q_shift) # 8
stepy = math.ceil(N2 / q_shift) # 8
if stepy <= 0:
stepy = 1
stepx = 1
est1 = (stepx - 1) * q_shift + q_blocks_size - N1 # 1
est2 = (stepy - 1) * q_shift + q_blocks_size - N2 # 1
# if np.sum(np.array([est1 != 0, est2 != 0])) > 0:
# refref = np.zeros(shape=[N1+1, N2+1])
# fusfus = refref.copy()
if sum([(est1!=0), (est2!=0)]) > 0:
for i in range(N3):
a1 = gt[..., 0]
ia1 = np.zeros(shape=[N1 + est1, N2 + est2])
ia1[:N1, : N2] = a1
ia1[:, N2:N2 + est2] = ia1[:, N2-1:-1:N2 - est2 + 1]
ia1[N1:N1 + est1, ...] = ia1[N1-1:-1:N1-est1+1, ...]
if i == 0:
refref = ia1[..., np.newaxis] # np.concatenate(refref, ia1, axis=3)
else:
refref = np.concatenate([refref, ia1[..., np.newaxis]], axis=-1)
if i < N3:
gt = gt[..., 1:]
gt = refref
for i in range(N3):
a2 = x[..., 0]
ia2 = np.zeros(shape=[N1 + est1, N2 + est2])
ia2[: N1, : N2] = a2
ia2[:, N2:N2 + est2] = ia2[:, N2 - 1:-1:N2 - est2 + 1]
ia2[N1:N1 + est1, ...] = ia2[N1 - 1:-1:N1 - est1 + 1, ...]
if i == 0:
fusfus = ia2[..., np.newaxis] # np.concatenate(refref, ia1, axis=3)
else:
fusfus = np.concatenate([fusfus, ia2[..., np.newaxis]], axis=-1)
if i < N3:
x = x[..., 1:]
x = fusfus
# Equivalent to uint16(gt) in matlab (Xiao Wu in UESTC)
x = np.round(x.clip(0)).astype(np.uint16)
gt = np.round(gt.clip(0)).astype(np.uint16)
N1, N2, N3 = gt.shape
if math.ceil(math.log2(N3)) - math.log2(N3) != 0:
Ndif = pow(2, math.ceil(math.log2(N3))) - N3
dif = np.zeros(shape=[N1, N2, Ndif], dtype=np.uint16)
gt = np.concatenate([gt, dif], axis=-1)
x = np.concatenate([x, dif], axis=-1)
_, _, N3 = gt.shape
valori = np.zeros(shape=[stepx, stepy, N3])
for j in range(stepx):
for i in range(stepy):
o = onions_quality(gt[j * q_shift:j * q_shift + q_blocks_size,
i * q_shift: i * q_shift + size2, :],
x[j * q_shift:j * q_shift + q_blocks_size,
i * q_shift: i * q_shift + size2, :],
q_blocks_size)
# 0.971379489438014 0.00553590637316723 0.00305237797490489 -0.0188289323262161 -0.00420556598390016 -0.0173947468044076 -0.0202144450367593 0.0102693855205061
valori[j, i, :] = o
q2n_idx_map = np.sqrt(np.sum(valori ** 2, axis=-1))
q2n_index = np.mean(q2n_idx_map)
return q2n_index, q2n_idx_map
def norm_blocco(x, eps=1e-8):
a = x.mean()
c = x.std()
if c == 0:
c = eps
return (x - a) / c + 1, a, c
def onions_quality(dat1, dat2, size1):
dat1 = np.float64(dat1)
dat2 = np.float64(dat2)
dat2 = np.concatenate([dat2[..., 0, np.newaxis], -dat2[..., 1:]], axis=-1)
_, _, N3 = dat1.shape
size2 = size1
# Block norm
'''
319.6474609375 37.05174450544686
357.970703125 61.54042371537683
518.708984375 111.53732768071865
608.23828125 154.26606056030568
593.412109375 163.97722215177643
554.8486328125 113.96758695803403
690.16015625 151.29524031046248
442.2314453125 94.12877724960003
mat
319.6475 37.0698
357.9707 61.5705
518.7090 111.5918
608.2383 154.3414
593.4121 164.0573
554.8486 114.0233
690.1602 151.3692
442.2314 94.1748
'''
for i in range(N3):
a1, s, t = norm_blocco(np.squeeze(dat1[..., i]))
# print(s,t)
dat1[..., i] = a1
if s == 0:
if i == 0:
dat2[..., i] = dat2[..., i] - s + 1
else:
dat2[..., i] = -(-dat2[..., i] - s + 1)
else:
if i == 0:
dat2[..., i] = ((dat2[..., i] - s) / t) + 1
else:
dat2[..., i] = -(((-dat2[..., i] - s) / t) + 1)
m1 = np.zeros(shape=[N3])
m2 = m1.copy()
mod_q1m = 0
mod_q2m = 0
mod_q1 = np.zeros(shape=[size1, size2])
mod_q2 = np.zeros(shape=[size1, size2])
for i in range(N3):
m1[..., i] = np.mean(np.squeeze(dat1[..., i]))
m2[..., i] = np.mean(np.squeeze(dat2[..., i]))
mod_q1m += m1[..., i] ** 2
mod_q2m += m2[..., i] ** 2
mod_q1 += np.squeeze(dat1[..., i]) ** 2
mod_q2 += np.squeeze(dat2[..., i]) ** 2
mod_q1m = np.sqrt(mod_q1m)
mod_q2m = np.sqrt(mod_q2m)
mod_q1 = np.sqrt(mod_q1)
mod_q2 = np.sqrt(mod_q2)
termine2 = mod_q1m * mod_q2m # 7.97
termine4 = mod_q1m ** 2 + mod_q2m ** 2 #
int1 = (size1 * size2) / (size1 * size2 - 1) * np.mean(mod_q1 ** 2)
int2 = (size1 * size2) / (size1 * size2 - 1) * np.mean(mod_q2 ** 2)
termine3 = int1 + int2 - (size1 * size2) / ((size1 * size2 - 1)) * (mod_q1m ** 2 + mod_q2m ** 2) # 17.8988 ** 2
mean_bias = 2 * termine2 / termine4 # 1
if termine3 == 0:
q = np.zeros(shape=[1, N3])
q[:, :, N3 - 1] = mean_bias
else:
cbm = 2 / termine3
# 32 32 8
qu = onion_mult2D(dat1, dat2)
qm = onion_mult(m1.reshape(-1), m2.reshape(-1))
qv = np.zeros(shape=[N3])
for i in range(N3):
qv[i] = (size1 * size2) / ((size1 * size2) - 1) * np.mean(np.squeeze(qu[:, :, i]))
q = qv - (size1 * size2) / ((size1 * size2) - 1) * qm
q = q * mean_bias * cbm
return q
def onion_mult2D(onion1, onion2):
_, _, N3 = onion1.shape
if N3 > 1:
L = N3 // 2
a = onion1[..., : L]
b = onion1[..., L:]
b = np.concatenate([b[..., 0, np.newaxis], -b[..., 1:]], axis=-1)
c = onion2[..., : L]
d = onion2[..., L:]
d = np.concatenate([d[..., 0, np.newaxis], -d[..., 1:]], axis=-1)
if N3 == 2:
ris = np.concatenate([a * c - d * b, a * d + c * b], axis=-1)
else:
ris1 = onion_mult2D(a, c)
ris2 = onion_mult2D(d, np.concatenate([b[..., 0, np.newaxis], -b[..., 1:]], axis=-1))
ris3 = onion_mult2D(np.concatenate([a[..., 0, np.newaxis], -a[..., 1:]], axis=-1), d)
ris4 = onion_mult2D(c, b)
aux1 = ris1 - ris2
aux2 = ris3 + ris4
ris = np.concatenate([aux1, aux2], axis=-1)
else:
ris = onion1 * onion2
return ris
def onion_mult(onion1, onion2):
# _, N = onion1.shape
N = len(onion1)
if N > 1:
L = N // 2
a = onion1[:L]
b = onion1[L:]
# b[1:] = -b[1:]
b = np.append(np.array(b[0]), -b[1:])
c = onion2[:L]
d = onion2[L:]
# d[1:] = -d[1:]
d = np.append(np.array(d[0]), -d[1:])
if N == 2:
ris = np.append(a * c - d * b, a * d + c * b)
else:
ris1 = onion_mult(a, c)
# b[1:] = -b[1:]
ris2 = onion_mult(d, np.append(np.array(b[0]), -b[1:]))
# a[1:] = -a[1:]
ris3 = onion_mult(np.append(np.array(a[0]), -a[1:]), d)
ris4 = onion_mult(c, b)
aux1 = ris1 - ris2
aux2 = ris3 + ris4
ris = np.append(aux1, aux2)
else:
ris = np.array(onion1).reshape(-1) * np.array(onion2).reshape(-1)
return ris
|
294coder/Efficient-MIF
| 2,531 |
utils/sharpening_index/genMTF.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
Generate a bank of filters shaped on the MTF of the sensor. Each filter
corresponds to a band acquired by the sensor.
Interface:
h = genMTF(ratio, sensor, nbands)
Inputs:
ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
sensor: String for type of sensor (e.g. 'WV2','IKONOS');
nbands: Number of spectral bands.
Outputs:
h: Gaussian filter mimicking the MTF of the MS sensor.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
import numpy as np
from .tools import fir_filter_wind, gaussian2d, kaiser2d
def genMTF(ratio, sensor, nbands):
N = 41
if sensor=='QB':
GNyq = np.asarray([0.34, 0.32, 0.30, 0.22],dtype='float32') # Band Order: B,G,R,NIR
elif sensor=='IKONOS':
GNyq = np.asarray([0.26,0.28,0.29,0.28],dtype='float32') # Band Order: B,G,R,NIR
elif sensor=='GeoEye1' or sensor=='WV4':
GNyq = np.asarray([0.23,0.23,0.23,0.23],dtype='float32') # Band Order: B,G,R,NIR
elif sensor=='WV2':
GNyq = [0.35*np.ones(nbands),0.27]
elif sensor=='WV3':
GNyq = np.asarray([0.325,0.355,0.360,0.350,0.365,0.360,0.335,0.315],dtype='float32')
else:
GNyq = 0.3 * np.ones(nbands)
"""MTF"""
h = np.zeros((N, N, nbands))
fcut = 1/ratio
h = np.zeros((N,N,nbands))
for ii in range(nbands):
alpha = np.sqrt(((N-1)*(fcut/2))**2/(-2*np.log(GNyq[ii])))
H=gaussian2d(N,alpha)
Hd=H/np.max(H)
w=kaiser2d(N,0.5)
h[:,:,ii] = np.real(fir_filter_wind(Hd,w))
return h
|
2881099/FreeSql.AdminLTE
| 101,588 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/inputmask/inputmask.min.js
|
/*!
* dist/inputmask.min
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2021 Robin Herbots
* Licensed under the MIT license
* Version: 5.0.7
*/
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var a in i)("object"==typeof exports?exports:e)[a]=i[a]}}(self,(function(){return function(){"use strict";var e={8741:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var i=!("undefined"==typeof window||!window.document||!window.document.createElement);t.default=i},3976:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a,n=(a=i(5581))&&a.__esModule?a:{default:a};var r={_maxTestPos:500,placeholder:"_",optionalmarker:["[","]"],quantifiermarker:["{","}"],groupmarker:["(",")"],alternatormarker:"|",escapeChar:"\\",mask:null,regex:null,oncomplete:function(){},onincomplete:function(){},oncleared:function(){},repeat:0,greedy:!1,autoUnmask:!1,removeMaskOnSubmit:!1,clearMaskOnLostFocus:!0,insertMode:!0,insertModeVisual:!0,clearIncomplete:!1,alias:null,onKeyDown:function(){},onBeforeMask:null,onBeforePaste:function(e,t){return"function"==typeof t.onBeforeMask?t.onBeforeMask.call(this,e,t):e},onBeforeWrite:null,onUnMask:null,showMaskOnFocus:!0,showMaskOnHover:!0,onKeyValidation:function(){},skipOptionalPartCharacter:" ",numericInput:!1,rightAlign:!1,undoOnEscape:!0,radixPoint:"",_radixDance:!1,groupSeparator:"",keepStatic:null,positionCaretOnTab:!0,tabThrough:!1,supportsInputType:["text","tel","url","password","search"],ignorables:[n.default.BACKSPACE,n.default.TAB,n.default["PAUSE/BREAK"],n.default.ESCAPE,n.default.PAGE_UP,n.default.PAGE_DOWN,n.default.END,n.default.HOME,n.default.LEFT,n.default.UP,n.default.RIGHT,n.default.DOWN,n.default.INSERT,n.default.DELETE,93,112,113,114,115,116,117,118,119,120,121,122,123,0,229],isComplete:null,preValidation:null,postValidation:null,staticDefinitionSymbol:void 0,jitMasking:!1,nullable:!0,inputEventOnly:!1,noValuePatching:!1,positionCaretOnClick:"lvp",casing:null,inputmode:"text",importDataAttributes:!0,shiftPositions:!0,usePrototypeDefinitions:!0,validationEventTimeOut:3e3,substitutes:{}};t.default=r},7392:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;t.default={9:{validator:"[0-9\uff10-\uff19]",definitionSymbol:"*"},a:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",definitionSymbol:"*"},"*":{validator:"[0-9\uff10-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"}}},253:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i){if(void 0===i)return e.__data?e.__data[t]:null;e.__data=e.__data||{},e.__data[t]=i}},3776:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.Event=void 0,t.off=function(e,t){var i,a;function n(e,t,n){if(e in i==!0)if(a.removeEventListener?a.removeEventListener(e,n,!1):a.detachEvent&&a.detachEvent("on"+e,n),"global"===t)for(var r in i[e])i[e][r].splice(i[e][r].indexOf(n),1);else i[e][t].splice(i[e][t].indexOf(n),1)}function r(e,a){var n,r,o=[];if(e.length>0)if(void 0===t)for(n=0,r=i[e][a].length;n<r;n++)o.push({ev:e,namespace:a&&a.length>0?a:"global",handler:i[e][a][n]});else o.push({ev:e,namespace:a&&a.length>0?a:"global",handler:t});else if(a.length>0)for(var l in i)for(var s in i[l])if(s===a)if(void 0===t)for(n=0,r=i[l][s].length;n<r;n++)o.push({ev:l,namespace:s,handler:i[l][s][n]});else o.push({ev:l,namespace:s,handler:t});return o}if(u(this[0])&&e){i=this[0].eventRegistry,a=this[0];for(var o=e.split(" "),l=0;l<o.length;l++)for(var s=o[l].split("."),c=r(s[0],s[1]),f=0,d=c.length;f<d;f++)n(c[f].ev,c[f].namespace,c[f].handler)}return this},t.on=function(e,t){function i(e,i){n.addEventListener?n.addEventListener(e,t,!1):n.attachEvent&&n.attachEvent("on"+e,t),a[e]=a[e]||{},a[e][i]=a[e][i]||[],a[e][i].push(t)}if(u(this[0]))for(var a=this[0].eventRegistry,n=this[0],r=e.split(" "),o=0;o<r.length;o++){var l=r[o].split("."),s=l[0],c=l[1]||"global";i(s,c)}return this},t.trigger=function(e){if(u(this[0]))for(var t=this[0].eventRegistry,i=this[0],a="string"==typeof e?e.split(" "):[e.type],r=0;r<a.length;r++){var l=a[r].split("."),s=l[0],c=l[1]||"global";if(void 0!==document&&"global"===c){var f,d,p={bubbles:!0,cancelable:!0,detail:arguments[1]};if(document.createEvent){try{if("input"===s)p.inputType="insertText",f=new InputEvent(s,p);else f=new CustomEvent(s,p)}catch(e){(f=document.createEvent("CustomEvent")).initCustomEvent(s,p.bubbles,p.cancelable,p.detail)}e.type&&(0,n.default)(f,e),i.dispatchEvent(f)}else(f=document.createEventObject()).eventType=s,f.detail=arguments[1],e.type&&(0,n.default)(f,e),i.fireEvent("on"+f.eventType,f)}else if(void 0!==t[s])if(arguments[0]=arguments[0].type?arguments[0]:o.default.Event(arguments[0]),arguments[0].detail=arguments.slice(1),"global"===c)for(var h in t[s])for(d=0;d<t[s][h].length;d++)t[s][h][d].apply(i,arguments);else for(d=0;d<t[s][c].length;d++)t[s][c][d].apply(i,arguments)}return this};var a,n=s(i(600)),r=s(i(9380)),o=s(i(4963)),l=s(i(8741));function s(e){return e&&e.__esModule?e:{default:e}}function u(e){return e instanceof Element}t.Event=a,"function"==typeof r.default.CustomEvent?t.Event=a=r.default.CustomEvent:l.default&&(t.Event=a=function(e,t){t=t||{bubbles:!1,cancelable:!1,detail:void 0};var i=document.createEvent("CustomEvent");return i.initCustomEvent(e,t.bubbles,t.cancelable,t.detail),i},a.prototype=r.default.Event.prototype)},600:function(e,t){function i(e){return i="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},i(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function e(){var t,a,n,r,o,l,s=arguments[0]||{},u=1,c=arguments.length,f=!1;"boolean"==typeof s&&(f=s,s=arguments[u]||{},u++);"object"!==i(s)&&"function"!=typeof s&&(s={});for(;u<c;u++)if(null!=(t=arguments[u]))for(a in t)n=s[a],r=t[a],s!==r&&(f&&r&&("[object Object]"===Object.prototype.toString.call(r)||(o=Array.isArray(r)))?(o?(o=!1,l=n&&Array.isArray(n)?n:[]):l=n&&"[object Object]"===Object.prototype.toString.call(n)?n:{},s[a]=e(f,l,r)):void 0!==r&&(s[a]=r));return s}},4963:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var a=l(i(600)),n=l(i(9380)),r=l(i(253)),o=i(3776);function l(e){return e&&e.__esModule?e:{default:e}}var s=n.default.document;function u(e){return e instanceof u?e:this instanceof u?void(null!=e&&e!==n.default&&(this[0]=e.nodeName?e:void 0!==e[0]&&e[0].nodeName?e[0]:s.querySelector(e),void 0!==this[0]&&null!==this[0]&&(this[0].eventRegistry=this[0].eventRegistry||{}))):new u(e)}u.prototype={on:o.on,off:o.off,trigger:o.trigger},u.extend=a.default,u.data=r.default,u.Event=o.Event;var c=u;t.default=c},9845:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.ua=t.mobile=t.iphone=t.iemobile=t.ie=void 0;var a,n=(a=i(9380))&&a.__esModule?a:{default:a};var r=n.default.navigator&&n.default.navigator.userAgent||"",o=r.indexOf("MSIE ")>0||r.indexOf("Trident/")>0,l="ontouchstart"in n.default,s=/iemobile/i.test(r),u=/iphone/i.test(r)&&!s;t.iphone=u,t.iemobile=s,t.mobile=l,t.ie=o,t.ua=r},7184:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e.replace(i,"\\$1")};var i=new RegExp("(\\"+["/",".","*","+","?","|","(",")","[","]","{","}","\\","$","^"].join("|\\")+")","gim")},6030:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.EventHandlers=void 0;var a,n=i(8711),r=(a=i(5581))&&a.__esModule?a:{default:a},o=i(9845),l=i(7215),s=i(7760),u=i(4713);function c(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!i){if(Array.isArray(e)||(i=function(e,t){if(!e)return;if("string"==typeof e)return f(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return f(e,t)}(e))||t&&e&&"number"==typeof e.length){i&&(e=i);var a=0,n=function(){};return{s:n,n:function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}},e:function(e){throw e},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var r,o=!0,l=!1;return{s:function(){i=i.call(e)},n:function(){var e=i.next();return o=e.done,e},e:function(e){l=!0,r=e},f:function(){try{o||null==i.return||i.return()}finally{if(l)throw r}}}}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,a=new Array(t);i<t;i++)a[i]=e[i];return a}var d={keydownEvent:function(e){var t=this.inputmask,i=t.opts,a=t.dependencyLib,c=t.maskset,f=this,d=a(f),p=e.keyCode,h=n.caret.call(t,f),v=i.onKeyDown.call(this,e,n.getBuffer.call(t),h,i);if(void 0!==v)return v;if(p===r.default.BACKSPACE||p===r.default.DELETE||o.iphone&&p===r.default.BACKSPACE_SAFARI||e.ctrlKey&&p===r.default.X&&!("oncut"in f))e.preventDefault(),l.handleRemove.call(t,f,p,h),(0,s.writeBuffer)(f,n.getBuffer.call(t,!0),c.p,e,f.inputmask._valueGet()!==n.getBuffer.call(t).join(""));else if(p===r.default.END||p===r.default.PAGE_DOWN){e.preventDefault();var m=n.seekNext.call(t,n.getLastValidPosition.call(t));n.caret.call(t,f,e.shiftKey?h.begin:m,m,!0)}else p===r.default.HOME&&!e.shiftKey||p===r.default.PAGE_UP?(e.preventDefault(),n.caret.call(t,f,0,e.shiftKey?h.begin:0,!0)):i.undoOnEscape&&p===r.default.ESCAPE&&!0!==e.altKey?((0,s.checkVal)(f,!0,!1,t.undoValue.split("")),d.trigger("click")):p!==r.default.INSERT||e.shiftKey||e.ctrlKey||void 0!==t.userOptions.insertMode?!0===i.tabThrough&&p===r.default.TAB?!0===e.shiftKey?(h.end=n.seekPrevious.call(t,h.end,!0),!0===u.getTest.call(t,h.end-1).match.static&&h.end--,h.begin=n.seekPrevious.call(t,h.end,!0),h.begin>=0&&h.end>0&&(e.preventDefault(),n.caret.call(t,f,h.begin,h.end))):(h.begin=n.seekNext.call(t,h.begin,!0),h.end=n.seekNext.call(t,h.begin,!0),h.end<c.maskLength&&h.end--,h.begin<=c.maskLength&&(e.preventDefault(),n.caret.call(t,f,h.begin,h.end))):e.shiftKey||i.insertModeVisual&&!1===i.insertMode&&(p===r.default.RIGHT?setTimeout((function(){var e=n.caret.call(t,f);n.caret.call(t,f,e.begin)}),0):p===r.default.LEFT&&setTimeout((function(){var e=n.translatePosition.call(t,f.inputmask.caretPos.begin);n.translatePosition.call(t,f.inputmask.caretPos.end);t.isRTL?n.caret.call(t,f,e+(e===c.maskLength?0:1)):n.caret.call(t,f,e-(0===e?0:1))}),0)):l.isSelection.call(t,h)?i.insertMode=!i.insertMode:(i.insertMode=!i.insertMode,n.caret.call(t,f,h.begin,h.begin));t.ignorable=i.ignorables.includes(p)},keypressEvent:function(e,t,i,a,o){var u=this.inputmask||this,c=u.opts,f=u.dependencyLib,d=u.maskset,p=u.el,h=f(p),v=e.keyCode;if(!(!0===t||e.ctrlKey&&e.altKey)&&(e.ctrlKey||e.metaKey||u.ignorable))return v===r.default.ENTER&&u.undoValue!==u._valueGet(!0)&&(u.undoValue=u._valueGet(!0),setTimeout((function(){h.trigger("change")}),0)),u.skipInputEvent=!0,!0;if(v){44!==v&&46!==v||3!==e.location||""===c.radixPoint||(v=c.radixPoint.charCodeAt(0));var m,g=t?{begin:o,end:o}:n.caret.call(u,p),k=String.fromCharCode(v);k=c.substitutes[k]||k,d.writeOutBuffer=!0;var y=l.isValid.call(u,g,k,a,void 0,void 0,void 0,t);if(!1!==y&&(n.resetMaskSet.call(u,!0),m=void 0!==y.caret?y.caret:n.seekNext.call(u,y.pos.begin?y.pos.begin:y.pos),d.p=m),m=c.numericInput&&void 0===y.caret?n.seekPrevious.call(u,m):m,!1!==i&&(setTimeout((function(){c.onKeyValidation.call(p,v,y)}),0),d.writeOutBuffer&&!1!==y)){var b=n.getBuffer.call(u);(0,s.writeBuffer)(p,b,m,e,!0!==t)}if(e.preventDefault(),t)return!1!==y&&(y.forwardPosition=m),y}},keyupEvent:function(e){var t=this.inputmask;!t.isComposing||e.keyCode!==r.default.KEY_229&&e.keyCode!==r.default.ENTER||t.$el.trigger("input")},pasteEvent:function(e){var t,i=this.inputmask,a=i.opts,r=i._valueGet(!0),o=n.caret.call(i,this);i.isRTL&&(t=o.end,o.end=n.translatePosition.call(i,o.begin),o.begin=n.translatePosition.call(i,t));var l=r.substr(0,o.begin),u=r.substr(o.end,r.length);if(l==(i.isRTL?n.getBufferTemplate.call(i).slice().reverse():n.getBufferTemplate.call(i)).slice(0,o.begin).join("")&&(l=""),u==(i.isRTL?n.getBufferTemplate.call(i).slice().reverse():n.getBufferTemplate.call(i)).slice(o.end).join("")&&(u=""),window.clipboardData&&window.clipboardData.getData)r=l+window.clipboardData.getData("Text")+u;else{if(!e.clipboardData||!e.clipboardData.getData)return!0;r=l+e.clipboardData.getData("text/plain")+u}var f=r;if(i.isRTL){f=f.split("");var d,p=c(n.getBufferTemplate.call(i));try{for(p.s();!(d=p.n()).done;){var h=d.value;f[0]===h&&f.shift()}}catch(e){p.e(e)}finally{p.f()}f=f.join("")}if("function"==typeof a.onBeforePaste){if(!1===(f=a.onBeforePaste.call(i,f,a)))return!1;f||(f=r)}(0,s.checkVal)(this,!0,!1,f.toString().split(""),e),e.preventDefault()},inputFallBackEvent:function(e){var t=this.inputmask,i=t.opts,a=t.dependencyLib;var l=this,c=l.inputmask._valueGet(!0),f=(t.isRTL?n.getBuffer.call(t).slice().reverse():n.getBuffer.call(t)).join(""),p=n.caret.call(t,l,void 0,void 0,!0);if(f!==c){c=function(e,i,a){if(o.iemobile){var r=i.replace(n.getBuffer.call(t).join(""),"");if(1===r.length){var l=i.split("");l.splice(a.begin,0,r),i=l.join("")}}return i}(0,c,p);var h=function(e,a,r){for(var o,l,s,c=e.substr(0,r.begin).split(""),f=e.substr(r.begin).split(""),d=a.substr(0,r.begin).split(""),p=a.substr(r.begin).split(""),h=c.length>=d.length?c.length:d.length,v=f.length>=p.length?f.length:p.length,m="",g=[],k="~";c.length<h;)c.push(k);for(;d.length<h;)d.push(k);for(;f.length<v;)f.unshift(k);for(;p.length<v;)p.unshift(k);var y=c.concat(f),b=d.concat(p);for(l=0,o=y.length;l<o;l++)switch(s=u.getPlaceholder.call(t,n.translatePosition.call(t,l)),m){case"insertText":b[l-1]===y[l]&&r.begin==y.length-1&&g.push(y[l]),l=o;break;case"insertReplacementText":case"deleteContentBackward":y[l]===k?r.end++:l=o;break;default:y[l]!==b[l]&&(y[l+1]!==k&&y[l+1]!==s&&void 0!==y[l+1]||(b[l]!==s||b[l+1]!==k)&&b[l]!==k?b[l+1]===k&&b[l]===y[l+1]?(m="insertText",g.push(y[l]),r.begin--,r.end--):y[l]!==s&&y[l]!==k&&(y[l+1]===k||b[l]!==y[l]&&b[l+1]===y[l+1])?(m="insertReplacementText",g.push(y[l]),r.begin--):y[l]===k?(m="deleteContentBackward",(n.isMask.call(t,n.translatePosition.call(t,l),!0)||b[l]===i.radixPoint)&&r.end++):l=o:(m="insertText",g.push(y[l]),r.begin--,r.end--))}return{action:m,data:g,caret:r}}(c,f,p);switch((l.inputmask.shadowRoot||l.ownerDocument).activeElement!==l&&l.focus(),(0,s.writeBuffer)(l,n.getBuffer.call(t)),n.caret.call(t,l,p.begin,p.end,!0),h.action){case"insertText":case"insertReplacementText":h.data.forEach((function(e,i){var n=new a.Event("keypress");n.keyCode=e.charCodeAt(0),t.ignorable=!1,d.keypressEvent.call(l,n)})),setTimeout((function(){t.$el.trigger("keyup")}),0);break;case"deleteContentBackward":var v=new a.Event("keydown");v.keyCode=r.default.BACKSPACE,d.keydownEvent.call(l,v);break;default:(0,s.applyInputValue)(l,c)}e.preventDefault()}},compositionendEvent:function(e){var t=this.inputmask;t.isComposing=!1,t.$el.trigger("input")},setValueEvent:function(e){var t=this.inputmask,i=this,a=e&&e.detail?e.detail[0]:arguments[1];void 0===a&&(a=i.inputmask._valueGet(!0)),(0,s.applyInputValue)(i,a),(e.detail&&void 0!==e.detail[1]||void 0!==arguments[2])&&n.caret.call(t,i,e.detail?e.detail[1]:arguments[2])},focusEvent:function(e){var t=this.inputmask,i=t.opts,a=this,r=a.inputmask._valueGet();i.showMaskOnFocus&&r!==n.getBuffer.call(t).join("")&&(0,s.writeBuffer)(a,n.getBuffer.call(t),n.seekNext.call(t,n.getLastValidPosition.call(t))),!0!==i.positionCaretOnTab||!1!==t.mouseEnter||l.isComplete.call(t,n.getBuffer.call(t))&&-1!==n.getLastValidPosition.call(t)||d.clickEvent.apply(a,[e,!0]),t.undoValue=t._valueGet(!0)},invalidEvent:function(e){this.inputmask.validationEvent=!0},mouseleaveEvent:function(){var e=this.inputmask,t=e.opts,i=this;e.mouseEnter=!1,t.clearMaskOnLostFocus&&(i.inputmask.shadowRoot||i.ownerDocument).activeElement!==i&&(0,s.HandleNativePlaceholder)(i,e.originalPlaceholder)},clickEvent:function(e,t){var i=this.inputmask,a=this;if((a.inputmask.shadowRoot||a.ownerDocument).activeElement===a){var r=n.determineNewCaretPosition.call(i,n.caret.call(i,a),t);void 0!==r&&n.caret.call(i,a,r)}},cutEvent:function(e){var t=this.inputmask,i=t.maskset,a=this,o=n.caret.call(t,a),u=t.isRTL?n.getBuffer.call(t).slice(o.end,o.begin):n.getBuffer.call(t).slice(o.begin,o.end),c=t.isRTL?u.reverse().join(""):u.join("");window.navigator.clipboard?window.navigator.clipboard.writeText(c):window.clipboardData&&window.clipboardData.getData&&window.clipboardData.setData("Text",c),l.handleRemove.call(t,a,r.default.DELETE,o),(0,s.writeBuffer)(a,n.getBuffer.call(t),i.p,e,t.undoValue!==t._valueGet(!0))},blurEvent:function(e){var t=this.inputmask,i=t.opts,a=(0,t.dependencyLib)(this),r=this;if(r.inputmask){(0,s.HandleNativePlaceholder)(r,t.originalPlaceholder);var o=r.inputmask._valueGet(),u=n.getBuffer.call(t).slice();""!==o&&(i.clearMaskOnLostFocus&&(-1===n.getLastValidPosition.call(t)&&o===n.getBufferTemplate.call(t).join("")?u=[]:s.clearOptionalTail.call(t,u)),!1===l.isComplete.call(t,u)&&(setTimeout((function(){a.trigger("incomplete")}),0),i.clearIncomplete&&(n.resetMaskSet.call(t),u=i.clearMaskOnLostFocus?[]:n.getBufferTemplate.call(t).slice())),(0,s.writeBuffer)(r,u,void 0,e)),t.undoValue!==t._valueGet(!0)&&(t.undoValue=t._valueGet(!0),a.trigger("change"))}},mouseenterEvent:function(){var e=this.inputmask,t=e.opts,i=this;if(e.mouseEnter=!0,(i.inputmask.shadowRoot||i.ownerDocument).activeElement!==i){var a=(e.isRTL?n.getBufferTemplate.call(e).slice().reverse():n.getBufferTemplate.call(e)).join("");e.placeholder!==a&&i.placeholder!==e.originalPlaceholder&&(e.originalPlaceholder=i.placeholder),t.showMaskOnHover&&(0,s.HandleNativePlaceholder)(i,a)}},submitEvent:function(){var e=this.inputmask,t=e.opts;e.undoValue!==e._valueGet(!0)&&e.$el.trigger("change"),-1===n.getLastValidPosition.call(e)&&e._valueGet&&e._valueGet()===n.getBufferTemplate.call(e).join("")&&e._valueSet(""),t.clearIncomplete&&!1===l.isComplete.call(e,n.getBuffer.call(e))&&e._valueSet(""),t.removeMaskOnSubmit&&(e._valueSet(e.unmaskedvalue(),!0),setTimeout((function(){(0,s.writeBuffer)(e.el,n.getBuffer.call(e))}),0))},resetEvent:function(){var e=this.inputmask;e.refreshValue=!0,setTimeout((function(){(0,s.applyInputValue)(e.el,e._valueGet(!0))}),0)}};t.EventHandlers=d},9716:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.EventRuler=void 0;var a=l(i(2394)),n=l(i(5581)),r=i(8711),o=i(7760);function l(e){return e&&e.__esModule?e:{default:e}}var s={on:function(e,t,i){var l=e.inputmask.dependencyLib,s=function(t){t.originalEvent&&(t=t.originalEvent||t,arguments[0]=t);var s,u=this,c=u.inputmask,f=c?c.opts:void 0;if(void 0===c&&"FORM"!==this.nodeName){var d=l.data(u,"_inputmask_opts");l(u).off(),d&&new a.default(d).mask(u)}else{if(["submit","reset","setvalue"].includes(t.type)||"FORM"===this.nodeName||!(u.disabled||u.readOnly&&!("keydown"===t.type&&t.ctrlKey&&67===t.keyCode||!1===f.tabThrough&&t.keyCode===n.default.TAB))){switch(t.type){case"input":if(!0===c.skipInputEvent||t.inputType&&"insertCompositionText"===t.inputType)return c.skipInputEvent=!1,t.preventDefault();break;case"keydown":c.skipKeyPressEvent=!1,c.skipInputEvent=c.isComposing=t.keyCode===n.default.KEY_229;break;case"keyup":case"compositionend":c.isComposing&&(c.skipInputEvent=!1);break;case"keypress":if(!0===c.skipKeyPressEvent)return t.preventDefault();c.skipKeyPressEvent=!0;break;case"click":case"focus":return c.validationEvent?(c.validationEvent=!1,e.blur(),(0,o.HandleNativePlaceholder)(e,(c.isRTL?r.getBufferTemplate.call(c).slice().reverse():r.getBufferTemplate.call(c)).join("")),setTimeout((function(){e.focus()}),f.validationEventTimeOut),!1):(s=arguments,setTimeout((function(){e.inputmask&&i.apply(u,s)}),0),!1)}var p=i.apply(u,arguments);return!1===p&&(t.preventDefault(),t.stopPropagation()),p}t.preventDefault()}};["submit","reset"].includes(t)?(s=s.bind(e),null!==e.form&&l(e.form).on(t,s)):l(e).on(t,s),e.inputmask.events[t]=e.inputmask.events[t]||[],e.inputmask.events[t].push(s)},off:function(e,t){if(e.inputmask&&e.inputmask.events){var i=e.inputmask.dependencyLib,a=e.inputmask.events;for(var n in t&&((a=[])[t]=e.inputmask.events[t]),a){for(var r=a[n];r.length>0;){var o=r.pop();["submit","reset"].includes(n)?null!==e.form&&i(e.form).off(n,o):i(e).off(n,o)}delete e.inputmask.events[n]}}}};t.EventRuler=s},219:function(e,t,i){var a=d(i(2394)),n=d(i(5581)),r=d(i(7184)),o=i(8711),l=i(4713);function s(e){return s="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},s(e)}function u(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var i=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null==i)return;var a,n,r=[],o=!0,l=!1;try{for(i=i.call(e);!(o=(a=i.next()).done)&&(r.push(a.value),!t||r.length!==t);o=!0);}catch(e){l=!0,n=e}finally{try{o||null==i.return||i.return()}finally{if(l)throw n}}return r}(e,t)||function(e,t){if(!e)return;if("string"==typeof e)return c(e,t);var i=Object.prototype.toString.call(e).slice(8,-1);"Object"===i&&e.constructor&&(i=e.constructor.name);if("Map"===i||"Set"===i)return Array.from(e);if("Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i))return c(e,t)}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function c(e,t){(null==t||t>e.length)&&(t=e.length);for(var i=0,a=new Array(t);i<t;i++)a[i]=e[i];return a}function f(e,t){for(var i=0;i<t.length;i++){var a=t[i];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}function d(e){return e&&e.__esModule?e:{default:e}}var p=a.default.dependencyLib,h=function(){function e(t,i,a){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.mask=t,this.format=i,this.opts=a,this._date=new Date(1,0,1),this.initDateObject(t,this.opts)}var t,i,a;return t=e,(i=[{key:"date",get:function(){return void 0===this._date&&(this._date=new Date(1,0,1),this.initDateObject(void 0,this.opts)),this._date}},{key:"initDateObject",value:function(e,t){var i;for(P(t).lastIndex=0;i=P(t).exec(this.format);){var a=new RegExp("\\d+$").exec(i[0]),n=a?i[0][0]+"x":i[0],r=void 0;if(void 0!==e){if(a){var o=P(t).lastIndex,l=O(i.index,t);P(t).lastIndex=o,r=e.slice(0,e.indexOf(l.nextMatch[0]))}else r=e.slice(0,n.length);e=e.slice(r.length)}Object.prototype.hasOwnProperty.call(g,n)&&this.setValue(this,r,n,g[n][2],g[n][1])}}},{key:"setValue",value:function(e,t,i,a,n){if(void 0!==t&&(e[a]="ampm"===a?t:t.replace(/[^0-9]/g,"0"),e["raw"+a]=t.replace(/\s/g,"_")),void 0!==n){var r=e[a];("day"===a&&29===parseInt(r)||"month"===a&&2===parseInt(r))&&(29!==parseInt(e.day)||2!==parseInt(e.month)||""!==e.year&&void 0!==e.year||e._date.setFullYear(2012,1,29)),"day"===a&&(m=!0,0===parseInt(r)&&(r=1)),"month"===a&&(m=!0),"year"===a&&(m=!0,r.length<4&&(r=_(r,4,!0))),""===r||isNaN(r)||n.call(e._date,r),"ampm"===a&&n.call(e._date,r)}}},{key:"reset",value:function(){this._date=new Date(1,0,1)}},{key:"reInit",value:function(){this._date=void 0,this.date}}])&&f(t.prototype,i),a&&f(t,a),Object.defineProperty(t,"prototype",{writable:!1}),e}(),v=(new Date).getFullYear(),m=!1,g={d:["[1-9]|[12][0-9]|3[01]",Date.prototype.setDate,"day",Date.prototype.getDate],dd:["0[1-9]|[12][0-9]|3[01]",Date.prototype.setDate,"day",function(){return _(Date.prototype.getDate.call(this),2)}],ddd:[""],dddd:[""],m:["[1-9]|1[012]",function(e){var t=e?parseInt(e):0;return t>0&&t--,Date.prototype.setMonth.call(this,t)},"month",function(){return Date.prototype.getMonth.call(this)+1}],mm:["0[1-9]|1[012]",function(e){var t=e?parseInt(e):0;return t>0&&t--,Date.prototype.setMonth.call(this,t)},"month",function(){return _(Date.prototype.getMonth.call(this)+1,2)}],mmm:[""],mmmm:[""],yy:["[0-9]{2}",Date.prototype.setFullYear,"year",function(){return _(Date.prototype.getFullYear.call(this),2)}],yyyy:["[0-9]{4}",Date.prototype.setFullYear,"year",function(){return _(Date.prototype.getFullYear.call(this),4)}],h:["[1-9]|1[0-2]",Date.prototype.setHours,"hours",Date.prototype.getHours],hh:["0[1-9]|1[0-2]",Date.prototype.setHours,"hours",function(){return _(Date.prototype.getHours.call(this),2)}],hx:[function(e){return"[0-9]{".concat(e,"}")},Date.prototype.setHours,"hours",function(e){return Date.prototype.getHours}],H:["1?[0-9]|2[0-3]",Date.prototype.setHours,"hours",Date.prototype.getHours],HH:["0[0-9]|1[0-9]|2[0-3]",Date.prototype.setHours,"hours",function(){return _(Date.prototype.getHours.call(this),2)}],Hx:[function(e){return"[0-9]{".concat(e,"}")},Date.prototype.setHours,"hours",function(e){return function(){return _(Date.prototype.getHours.call(this),e)}}],M:["[1-5]?[0-9]",Date.prototype.setMinutes,"minutes",Date.prototype.getMinutes],MM:["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]",Date.prototype.setMinutes,"minutes",function(){return _(Date.prototype.getMinutes.call(this),2)}],s:["[1-5]?[0-9]",Date.prototype.setSeconds,"seconds",Date.prototype.getSeconds],ss:["0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]",Date.prototype.setSeconds,"seconds",function(){return _(Date.prototype.getSeconds.call(this),2)}],l:["[0-9]{3}",Date.prototype.setMilliseconds,"milliseconds",function(){return _(Date.prototype.getMilliseconds.call(this),3)}],L:["[0-9]{2}",Date.prototype.setMilliseconds,"milliseconds",function(){return _(Date.prototype.getMilliseconds.call(this),2)}],t:["[ap]",y,"ampm",b,1],tt:["[ap]m",y,"ampm",b,2],T:["[AP]",y,"ampm",b,1],TT:["[AP]M",y,"ampm",b,2],Z:[".*",void 0,"Z",function(){var e=this.toString().match(/\((.+)\)/)[1];e.includes(" ")&&(e=(e=e.replace("-"," ").toUpperCase()).split(" ").map((function(e){return u(e,1)[0]})).join(""));return e}],o:[""],S:[""]},k={isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:ss",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"};function y(e){var t=this.getHours();e.toLowerCase().includes("p")?this.setHours(t+12):e.toLowerCase().includes("a")&&t>=12&&this.setHours(t-12)}function b(){var e=this.getHours();return(e=e||12)>=12?"PM":"AM"}function x(e){var t=new RegExp("\\d+$").exec(e[0]);if(t&&void 0!==t[0]){var i=g[e[0][0]+"x"].slice("");return i[0]=i[0](t[0]),i[3]=i[3](t[0]),i}if(g[e[0]])return g[e[0]]}function P(e){if(!e.tokenizer){var t=[],i=[];for(var a in g)if(/\.*x$/.test(a)){var n=a[0]+"\\d+";-1===i.indexOf(n)&&i.push(n)}else-1===t.indexOf(a[0])&&t.push(a[0]);e.tokenizer="("+(i.length>0?i.join("|")+"|":"")+t.join("+|")+")+?|.",e.tokenizer=new RegExp(e.tokenizer,"g")}return e.tokenizer}function E(e,t,i){if(!m)return!0;if(void 0===e.rawday||!isFinite(e.rawday)&&new Date(e.date.getFullYear(),isFinite(e.rawmonth)?e.month:e.date.getMonth()+1,0).getDate()>=e.day||"29"==e.day&&(!isFinite(e.rawyear)||void 0===e.rawyear||""===e.rawyear)||new Date(e.date.getFullYear(),isFinite(e.rawmonth)?e.month:e.date.getMonth()+1,0).getDate()>=e.day)return t;if("29"==e.day){var a=O(t.pos,i);if("yyyy"===a.targetMatch[0]&&t.pos-a.targetMatchIndex==2)return t.remove=t.pos+1,t}else if("02"==e.month&&"30"==e.day&&void 0!==t.c)return e.day="03",e.date.setDate(3),e.date.setMonth(1),t.insert=[{pos:t.pos,c:"0"},{pos:t.pos+1,c:t.c}],t.caret=o.seekNext.call(this,t.pos+1),t;return!1}function S(e,t,i,a){var n,o,l="";for(P(i).lastIndex=0;n=P(i).exec(e);){if(void 0===t)if(o=x(n))l+="("+o[0]+")";else switch(n[0]){case"[":l+="(";break;case"]":l+=")?";break;default:l+=(0,r.default)(n[0])}else if(o=x(n))if(!0!==a&&o[3])l+=o[3].call(t.date);else o[2]?l+=t["raw"+o[2]]:l+=n[0];else l+=n[0]}return l}function _(e,t,i){for(e=String(e),t=t||2;e.length<t;)e=i?e+"0":"0"+e;return e}function w(e,t,i){return"string"==typeof e?new h(e,t,i):e&&"object"===s(e)&&Object.prototype.hasOwnProperty.call(e,"date")?e:void 0}function M(e,t){return S(t.inputFormat,{date:e},t)}function O(e,t){var i,a,n=0,r=0;for(P(t).lastIndex=0;a=P(t).exec(t.inputFormat);){var o=new RegExp("\\d+$").exec(a[0]);if((n+=r=o?parseInt(o[0]):a[0].length)>=e+1){i=a,a=P(t).exec(t.inputFormat);break}}return{targetMatchIndex:n-r,nextMatch:a,targetMatch:i}}a.default.extendAliases({datetime:{mask:function(e){return e.numericInput=!1,g.S=e.i18n.ordinalSuffix.join("|"),e.inputFormat=k[e.inputFormat]||e.inputFormat,e.displayFormat=k[e.displayFormat]||e.displayFormat||e.inputFormat,e.outputFormat=k[e.outputFormat]||e.outputFormat||e.inputFormat,e.placeholder=""!==e.placeholder?e.placeholder:e.inputFormat.replace(/[[\]]/,""),e.regex=S(e.inputFormat,void 0,e),e.min=w(e.min,e.inputFormat,e),e.max=w(e.max,e.inputFormat,e),null},placeholder:"",inputFormat:"isoDateTime",displayFormat:null,outputFormat:null,min:null,max:null,skipOptionalPartCharacter:"",i18n:{dayNames:["Mon","Tue","Wed","Thu","Fri","Sat","Sun","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],ordinalSuffix:["st","nd","rd","th"]},preValidation:function(e,t,i,a,n,r,o,l){if(l)return!0;if(isNaN(i)&&e[t]!==i){var s=O(t,n);if(s.nextMatch&&s.nextMatch[0]===i&&s.targetMatch[0].length>1){var u=g[s.targetMatch[0]][0];if(new RegExp(u).test("0"+e[t-1]))return e[t]=e[t-1],e[t-1]="0",{fuzzy:!0,buffer:e,refreshFromBuffer:{start:t-1,end:t+1},pos:t+1}}}return!0},postValidation:function(e,t,i,a,n,r,o,s){var u,c;if(o)return!0;if(!1===a&&(((u=O(t+1,n)).targetMatch&&u.targetMatchIndex===t&&u.targetMatch[0].length>1&&void 0!==g[u.targetMatch[0]]||(u=O(t+2,n)).targetMatch&&u.targetMatchIndex===t+1&&u.targetMatch[0].length>1&&void 0!==g[u.targetMatch[0]])&&(c=g[u.targetMatch[0]][0]),void 0!==c&&(void 0!==r.validPositions[t+1]&&new RegExp(c).test(i+"0")?(e[t]=i,e[t+1]="0",a={pos:t+2,caret:t}):new RegExp(c).test("0"+i)&&(e[t]="0",e[t+1]=i,a={pos:t+2})),!1===a))return a;if(a.fuzzy&&(e=a.buffer,t=a.pos),(u=O(t,n)).targetMatch&&u.targetMatch[0]&&void 0!==g[u.targetMatch[0]]){var f=g[u.targetMatch[0]];c=f[0];var d=e.slice(u.targetMatchIndex,u.targetMatchIndex+u.targetMatch[0].length);if(!1===new RegExp(c).test(d.join(""))&&2===u.targetMatch[0].length&&r.validPositions[u.targetMatchIndex]&&r.validPositions[u.targetMatchIndex+1]&&(r.validPositions[u.targetMatchIndex+1].input="0"),"year"==f[2])for(var p=l.getMaskTemplate.call(this,!1,1,void 0,!0),h=t+1;h<e.length;h++)e[h]=p[h],delete r.validPositions[h]}var m=a,k=w(e.join(""),n.inputFormat,n);return m&&k.date.getTime()==k.date.getTime()&&(n.prefillYear&&(m=function(e,t,i){if(e.year!==e.rawyear){var a=v.toString(),n=e.rawyear.replace(/[^0-9]/g,""),r=a.slice(0,n.length),o=a.slice(n.length);if(2===n.length&&n===r){var l=new Date(v,e.month-1,e.day);e.day==l.getDate()&&(!i.max||i.max.date.getTime()>=l.getTime())&&(e.date.setFullYear(v),e.year=a,t.insert=[{pos:t.pos+1,c:o[0]},{pos:t.pos+2,c:o[1]}])}}return t}(k,m,n)),m=function(e,t,i,a,n){if(!t)return t;if(t&&i.min&&i.min.date.getTime()==i.min.date.getTime()){var r;for(e.reset(),P(i).lastIndex=0;r=P(i).exec(i.inputFormat);){var o;if((o=x(r))&&o[3]){for(var l=o[1],s=e[o[2]],u=i.min[o[2]],c=i.max?i.max[o[2]]:u,f=[],d=!1,p=0;p<u.length;p++)void 0!==a.validPositions[p+r.index]||d?(f[p]=s[p],d=d||s[p]>u[p]):(f[p]=u[p],"year"===o[2]&&s.length-1==p&&u!=c&&(f=(parseInt(f.join(""))+1).toString().split("")),"ampm"===o[2]&&u!=c&&i.min.date.getTime()>e.date.getTime()&&(f[p]=c[p]));l.call(e._date,f.join(""))}}t=i.min.date.getTime()<=e.date.getTime(),e.reInit()}return t&&i.max&&i.max.date.getTime()==i.max.date.getTime()&&(t=i.max.date.getTime()>=e.date.getTime()),t}(k,m=E.call(this,k,m,n),n,r)),void 0!==t&&m&&a.pos!==t?{buffer:S(n.inputFormat,k,n).split(""),refreshFromBuffer:{start:t,end:a.pos},pos:a.caret||a.pos}:m},onKeyDown:function(e,t,i,a){e.ctrlKey&&e.keyCode===n.default.RIGHT&&(this.inputmask._valueSet(M(new Date,a)),p(this).trigger("setvalue"))},onUnMask:function(e,t,i){return t?S(i.outputFormat,w(e,i.inputFormat,i),i,!0):t},casing:function(e,t,i,a){return 0==t.nativeDef.indexOf("[ap]")?e.toLowerCase():0==t.nativeDef.indexOf("[AP]")?e.toUpperCase():e},onBeforeMask:function(e,t){return"[object Date]"===Object.prototype.toString.call(e)&&(e=M(e,t)),e},insertMode:!1,shiftPositions:!1,keepStatic:!1,inputmode:"numeric",prefillYear:!0}})},3851:function(e,t,i){var a,n=(a=i(2394))&&a.__esModule?a:{default:a},r=i(8711),o=i(4713);n.default.extendDefinitions({A:{validator:"[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",casing:"upper"},"&":{validator:"[0-9A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",casing:"upper"},"#":{validator:"[0-9A-Fa-f]",casing:"upper"}});var l=new RegExp("25[0-5]|2[0-4][0-9]|[01][0-9][0-9]");function s(e,t,i,a,n){return i-1>-1&&"."!==t.buffer[i-1]?(e=t.buffer[i-1]+e,e=i-2>-1&&"."!==t.buffer[i-2]?t.buffer[i-2]+e:"0"+e):e="00"+e,l.test(e)}n.default.extendAliases({cssunit:{regex:"[+-]?[0-9]+\\.?([0-9]+)?(px|em|rem|ex|%|in|cm|mm|pt|pc)"},url:{regex:"(https?|ftp)://.*",autoUnmask:!1,keepStatic:!1,tabThrough:!0},ip:{mask:"i{1,3}.j{1,3}.k{1,3}.l{1,3}",definitions:{i:{validator:s},j:{validator:s},k:{validator:s},l:{validator:s}},onUnMask:function(e,t,i){return e},inputmode:"decimal",substitutes:{",":"."}},email:{mask:function(e){var t="*{1,64}[.*{1,64}][.*{1,64}][.*{1,63}]@-{1,63}.-{1,63}[.-{1,63}][.-{1,63}]",i=t;if(e.separator)for(var a=0;a<e.quantifier;a++)i+="[".concat(e.separator).concat(t,"]");return i},greedy:!1,casing:"lower",separator:null,quantifier:5,skipOptionalPartCharacter:"",onBeforePaste:function(e,t){return(e=e.toLowerCase()).replace("mailto:","")},definitions:{"*":{validator:"[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5!#$%&'*+/=?^_`{|}~-]"},"-":{validator:"[0-9A-Za-z-]"}},onUnMask:function(e,t,i){return e},inputmode:"email"},mac:{mask:"##:##:##:##:##:##"},vin:{mask:"V{13}9{4}",definitions:{V:{validator:"[A-HJ-NPR-Za-hj-npr-z\\d]",casing:"upper"}},clearIncomplete:!0,autoUnmask:!0},ssn:{mask:"999-99-9999",postValidation:function(e,t,i,a,n,l,s){var u=o.getMaskTemplate.call(this,!0,r.getLastValidPosition.call(this),!0,!0);return/^(?!219-09-9999|078-05-1120)(?!666|000|9.{2}).{3}-(?!00).{2}-(?!0{4}).{4}$/.test(u.join(""))}}})},207:function(e,t,i){var a=l(i(2394)),n=l(i(5581)),r=l(i(7184)),o=i(8711);function l(e){return e&&e.__esModule?e:{default:e}}var s=a.default.dependencyLib;function u(e,t){for(var i="",n=0;n<e.length;n++)a.default.prototype.definitions[e.charAt(n)]||t.definitions[e.charAt(n)]||t.optionalmarker[0]===e.charAt(n)||t.optionalmarker[1]===e.charAt(n)||t.quantifiermarker[0]===e.charAt(n)||t.quantifiermarker[1]===e.charAt(n)||t.groupmarker[0]===e.charAt(n)||t.groupmarker[1]===e.charAt(n)||t.alternatormarker===e.charAt(n)?i+="\\"+e.charAt(n):i+=e.charAt(n);return i}function c(e,t,i,a){if(e.length>0&&t>0&&(!i.digitsOptional||a)){var n=e.indexOf(i.radixPoint),r=!1;i.negationSymbol.back===e[e.length-1]&&(r=!0,e.length--),-1===n&&(e.push(i.radixPoint),n=e.length-1);for(var o=1;o<=t;o++)isFinite(e[n+o])||(e[n+o]="0")}return r&&e.push(i.negationSymbol.back),e}function f(e,t){var i=0;if("+"===e){for(i in t.validPositions);i=o.seekNext.call(this,parseInt(i))}for(var a in t.tests)if((a=parseInt(a))>=i)for(var n=0,r=t.tests[a].length;n<r;n++)if((void 0===t.validPositions[a]||"-"===e)&&t.tests[a][n].match.def===e)return a+(void 0!==t.validPositions[a]&&"-"!==e?1:0);return i}function d(e,t){var i=-1;for(var a in t.validPositions){var n=t.validPositions[a];if(n&&n.match.def===e){i=parseInt(a);break}}return i}function p(e,t,i,a,n){var r=t.buffer?t.buffer.indexOf(n.radixPoint):-1,o=(-1!==r||a&&n.jitMasking)&&new RegExp(n.definitions[9].validator).test(e);return n._radixDance&&-1!==r&&o&&null==t.validPositions[r]?{insert:{pos:r===i?r+1:r,c:n.radixPoint},pos:i}:o}a.default.extendAliases({numeric:{mask:function(e){e.repeat=0,e.groupSeparator===e.radixPoint&&e.digits&&"0"!==e.digits&&("."===e.radixPoint?e.groupSeparator=",":","===e.radixPoint?e.groupSeparator=".":e.groupSeparator="")," "===e.groupSeparator&&(e.skipOptionalPartCharacter=void 0),e.placeholder.length>1&&(e.placeholder=e.placeholder.charAt(0)),"radixFocus"===e.positionCaretOnClick&&""===e.placeholder&&(e.positionCaretOnClick="lvp");var t="0",i=e.radixPoint;!0===e.numericInput&&void 0===e.__financeInput?(t="1",e.positionCaretOnClick="radixFocus"===e.positionCaretOnClick?"lvp":e.positionCaretOnClick,e.digitsOptional=!1,isNaN(e.digits)&&(e.digits=2),e._radixDance=!1,i=","===e.radixPoint?"?":"!",""!==e.radixPoint&&void 0===e.definitions[i]&&(e.definitions[i]={},e.definitions[i].validator="["+e.radixPoint+"]",e.definitions[i].placeholder=e.radixPoint,e.definitions[i].static=!0,e.definitions[i].generated=!0)):(e.__financeInput=!1,e.numericInput=!0);var a,n="[+]";if(n+=u(e.prefix,e),""!==e.groupSeparator?(void 0===e.definitions[e.groupSeparator]&&(e.definitions[e.groupSeparator]={},e.definitions[e.groupSeparator].validator="["+e.groupSeparator+"]",e.definitions[e.groupSeparator].placeholder=e.groupSeparator,e.definitions[e.groupSeparator].static=!0,e.definitions[e.groupSeparator].generated=!0),n+=e._mask(e)):n+="9{+}",void 0!==e.digits&&0!==e.digits){var o=e.digits.toString().split(",");isFinite(o[0])&&o[1]&&isFinite(o[1])?n+=i+t+"{"+e.digits+"}":(isNaN(e.digits)||parseInt(e.digits)>0)&&(e.digitsOptional||e.jitMasking?(a=n+i+t+"{0,"+e.digits+"}",e.keepStatic=!0):n+=i+t+"{"+e.digits+"}")}else e.inputmode="numeric";return n+=u(e.suffix,e),n+="[-]",a&&(n=[a+u(e.suffix,e)+"[-]",n]),e.greedy=!1,function(e){void 0===e.parseMinMaxOptions&&(null!==e.min&&(e.min=e.min.toString().replace(new RegExp((0,r.default)(e.groupSeparator),"g"),""),","===e.radixPoint&&(e.min=e.min.replace(e.radixPoint,".")),e.min=isFinite(e.min)?parseFloat(e.min):NaN,isNaN(e.min)&&(e.min=Number.MIN_VALUE)),null!==e.max&&(e.max=e.max.toString().replace(new RegExp((0,r.default)(e.groupSeparator),"g"),""),","===e.radixPoint&&(e.max=e.max.replace(e.radixPoint,".")),e.max=isFinite(e.max)?parseFloat(e.max):NaN,isNaN(e.max)&&(e.max=Number.MAX_VALUE)),e.parseMinMaxOptions="done")}(e),""!==e.radixPoint&&(e.substitutes["."==e.radixPoint?",":"."]=e.radixPoint),n},_mask:function(e){return"("+e.groupSeparator+"999){+|1}"},digits:"*",digitsOptional:!0,enforceDigitsOnBlur:!1,radixPoint:".",positionCaretOnClick:"radixFocus",_radixDance:!0,groupSeparator:"",allowMinus:!0,negationSymbol:{front:"-",back:""},prefix:"",suffix:"",min:null,max:null,SetMaxOnOverflow:!1,step:1,inputType:"text",unmaskAsNumber:!1,roundingFN:Math.round,inputmode:"decimal",shortcuts:{k:"1000",m:"1000000"},placeholder:"0",greedy:!1,rightAlign:!0,insertMode:!0,autoUnmask:!1,skipOptionalPartCharacter:"",usePrototypeDefinitions:!1,stripLeadingZeroes:!0,definitions:{0:{validator:p},1:{validator:p,definitionSymbol:"9"},9:{validator:"[0-9\uff10-\uff19\u0660-\u0669\u06f0-\u06f9]",definitionSymbol:"*"},"+":{validator:function(e,t,i,a,n){return n.allowMinus&&("-"===e||e===n.negationSymbol.front)}},"-":{validator:function(e,t,i,a,n){return n.allowMinus&&e===n.negationSymbol.back}}},preValidation:function(e,t,i,a,n,r,o,l){if(!1!==n.__financeInput&&i===n.radixPoint)return!1;var s=e.indexOf(n.radixPoint),u=t;if(t=function(e,t,i,a,n){return n._radixDance&&n.numericInput&&t!==n.negationSymbol.back&&e<=i&&(i>0||t==n.radixPoint)&&(void 0===a.validPositions[e-1]||a.validPositions[e-1].input!==n.negationSymbol.back)&&(e-=1),e}(t,i,s,r,n),"-"===i||i===n.negationSymbol.front){if(!0!==n.allowMinus)return!1;var c=!1,p=d("+",r),h=d("-",r);return-1!==p&&(c=[p,h]),!1!==c?{remove:c,caret:u-n.negationSymbol.back.length}:{insert:[{pos:f.call(this,"+",r),c:n.negationSymbol.front,fromIsValid:!0},{pos:f.call(this,"-",r),c:n.negationSymbol.back,fromIsValid:void 0}],caret:u+n.negationSymbol.back.length}}if(i===n.groupSeparator)return{caret:u};if(l)return!0;if(-1!==s&&!0===n._radixDance&&!1===a&&i===n.radixPoint&&void 0!==n.digits&&(isNaN(n.digits)||parseInt(n.digits)>0)&&s!==t)return{caret:n._radixDance&&t===s-1?s+1:s};if(!1===n.__financeInput)if(a){if(n.digitsOptional)return{rewritePosition:o.end};if(!n.digitsOptional){if(o.begin>s&&o.end<=s)return i===n.radixPoint?{insert:{pos:s+1,c:"0",fromIsValid:!0},rewritePosition:s}:{rewritePosition:s+1};if(o.begin<s)return{rewritePosition:o.begin-1}}}else if(!n.showMaskOnHover&&!n.showMaskOnFocus&&!n.digitsOptional&&n.digits>0&&""===this.__valueGet.call(this.el))return{rewritePosition:s};return{rewritePosition:t}},postValidation:function(e,t,i,a,n,r,o){if(!1===a)return a;if(o)return!0;if(null!==n.min||null!==n.max){var l=n.onUnMask(e.slice().reverse().join(""),void 0,s.extend({},n,{unmaskAsNumber:!0}));if(null!==n.min&&l<n.min&&(l.toString().length>n.min.toString().length||l<0))return!1;if(null!==n.max&&l>n.max)return!!n.SetMaxOnOverflow&&{refreshFromBuffer:!0,buffer:c(n.max.toString().replace(".",n.radixPoint).split(""),n.digits,n).reverse()}}return a},onUnMask:function(e,t,i){if(""===t&&!0===i.nullable)return t;var a=e.replace(i.prefix,"");return a=(a=a.replace(i.suffix,"")).replace(new RegExp((0,r.default)(i.groupSeparator),"g"),""),""!==i.placeholder.charAt(0)&&(a=a.replace(new RegExp(i.placeholder.charAt(0),"g"),"0")),i.unmaskAsNumber?(""!==i.radixPoint&&-1!==a.indexOf(i.radixPoint)&&(a=a.replace(r.default.call(this,i.radixPoint),".")),a=(a=a.replace(new RegExp("^"+(0,r.default)(i.negationSymbol.front)),"-")).replace(new RegExp((0,r.default)(i.negationSymbol.back)+"$"),""),Number(a)):a},isComplete:function(e,t){var i=(t.numericInput?e.slice().reverse():e).join("");return i=(i=(i=(i=(i=i.replace(new RegExp("^"+(0,r.default)(t.negationSymbol.front)),"-")).replace(new RegExp((0,r.default)(t.negationSymbol.back)+"$"),"")).replace(t.prefix,"")).replace(t.suffix,"")).replace(new RegExp((0,r.default)(t.groupSeparator)+"([0-9]{3})","g"),"$1"),","===t.radixPoint&&(i=i.replace((0,r.default)(t.radixPoint),".")),isFinite(i)},onBeforeMask:function(e,t){var i=t.radixPoint||",";isFinite(t.digits)&&(t.digits=parseInt(t.digits)),"number"!=typeof e&&"number"!==t.inputType||""===i||(e=e.toString().replace(".",i));var a="-"===e.charAt(0)||e.charAt(0)===t.negationSymbol.front,n=e.split(i),o=n[0].replace(/[^\-0-9]/g,""),l=n.length>1?n[1].replace(/[^0-9]/g,""):"",s=n.length>1;e=o+(""!==l?i+l:l);var u=0;if(""!==i&&(u=t.digitsOptional?t.digits<l.length?t.digits:l.length:t.digits,""!==l||!t.digitsOptional)){var f=Math.pow(10,u||1);e=e.replace((0,r.default)(i),"."),isNaN(parseFloat(e))||(e=(t.roundingFN(parseFloat(e)*f)/f).toFixed(u)),e=e.toString().replace(".",i)}if(0===t.digits&&-1!==e.indexOf(i)&&(e=e.substring(0,e.indexOf(i))),null!==t.min||null!==t.max){var d=e.toString().replace(i,".");null!==t.min&&d<t.min?e=t.min.toString().replace(".",i):null!==t.max&&d>t.max&&(e=t.max.toString().replace(".",i))}return a&&"-"!==e.charAt(0)&&(e="-"+e),c(e.toString().split(""),u,t,s).join("")},onBeforeWrite:function(e,t,i,a){function n(e,t){if(!1!==a.__financeInput||t){var i=e.indexOf(a.radixPoint);-1!==i&&e.splice(i,1)}if(""!==a.groupSeparator)for(;-1!==(i=e.indexOf(a.groupSeparator));)e.splice(i,1);return e}var o,l;if(a.stripLeadingZeroes&&(l=function(e,t){var i=new RegExp("(^"+(""!==t.negationSymbol.front?(0,r.default)(t.negationSymbol.front)+"?":"")+(0,r.default)(t.prefix)+")(.*)("+(0,r.default)(t.suffix)+(""!=t.negationSymbol.back?(0,r.default)(t.negationSymbol.back)+"?":"")+"$)").exec(e.slice().reverse().join("")),a=i?i[2]:"",n=!1;return a&&(a=a.split(t.radixPoint.charAt(0))[0],n=new RegExp("^[0"+t.groupSeparator+"]*").exec(a)),!(!n||!(n[0].length>1||n[0].length>0&&n[0].length<a.length))&&n}(t,a)))for(var u=t.join("").lastIndexOf(l[0].split("").reverse().join(""))-(l[0]==l.input?0:1),f=l[0]==l.input?1:0,d=l[0].length-f;d>0;d--)delete this.maskset.validPositions[u+d],delete t[u+d];if(e)switch(e.type){case"blur":case"checkval":if(null!==a.min){var p=a.onUnMask(t.slice().reverse().join(""),void 0,s.extend({},a,{unmaskAsNumber:!0}));if(null!==a.min&&p<a.min)return{refreshFromBuffer:!0,buffer:c(a.min.toString().replace(".",a.radixPoint).split(""),a.digits,a).reverse()}}if(t[t.length-1]===a.negationSymbol.front){var h=new RegExp("(^"+(""!=a.negationSymbol.front?(0,r.default)(a.negationSymbol.front)+"?":"")+(0,r.default)(a.prefix)+")(.*)("+(0,r.default)(a.suffix)+(""!=a.negationSymbol.back?(0,r.default)(a.negationSymbol.back)+"?":"")+"$)").exec(n(t.slice(),!0).reverse().join(""));0==(h?h[2]:"")&&(o={refreshFromBuffer:!0,buffer:[0]})}else if(""!==a.radixPoint){t.indexOf(a.radixPoint)===a.suffix.length&&(o&&o.buffer?o.buffer.splice(0,1+a.suffix.length):(t.splice(0,1+a.suffix.length),o={refreshFromBuffer:!0,buffer:n(t)}))}if(a.enforceDigitsOnBlur){var v=(o=o||{})&&o.buffer||t.slice().reverse();o.refreshFromBuffer=!0,o.buffer=c(v,a.digits,a,!0).reverse()}}return o},onKeyDown:function(e,t,i,a){var r,o,l=s(this),u=String.fromCharCode(e.keyCode).toLowerCase();if((o=a.shortcuts&&a.shortcuts[u])&&o.length>1)return this.inputmask.__valueSet.call(this,parseFloat(this.inputmask.unmaskedvalue())*parseInt(o)),l.trigger("setvalue"),!1;if(e.ctrlKey)switch(e.keyCode){case n.default.UP:return this.inputmask.__valueSet.call(this,parseFloat(this.inputmask.unmaskedvalue())+parseInt(a.step)),l.trigger("setvalue"),!1;case n.default.DOWN:return this.inputmask.__valueSet.call(this,parseFloat(this.inputmask.unmaskedvalue())-parseInt(a.step)),l.trigger("setvalue"),!1}if(!e.shiftKey&&(e.keyCode===n.default.DELETE||e.keyCode===n.default.BACKSPACE||e.keyCode===n.default.BACKSPACE_SAFARI)&&i.begin!==t.length){if(t[e.keyCode===n.default.DELETE?i.begin-1:i.end]===a.negationSymbol.front)return r=t.slice().reverse(),""!==a.negationSymbol.front&&r.shift(),""!==a.negationSymbol.back&&r.pop(),l.trigger("setvalue",[r.join(""),i.begin]),!1;if(!0===a._radixDance){var f=t.indexOf(a.radixPoint);if(a.digitsOptional){if(0===f)return(r=t.slice().reverse()).pop(),l.trigger("setvalue",[r.join(""),i.begin>=r.length?r.length:i.begin]),!1}else if(-1!==f&&(i.begin<f||i.end<f||e.keyCode===n.default.DELETE&&i.begin===f))return i.begin!==i.end||e.keyCode!==n.default.BACKSPACE&&e.keyCode!==n.default.BACKSPACE_SAFARI||i.begin++,(r=t.slice().reverse()).splice(r.length-i.begin,i.begin-i.end+1),r=c(r,a.digits,a).join(""),l.trigger("setvalue",[r,i.begin>=r.length?f+1:i.begin]),!1}}}},currency:{prefix:"",groupSeparator:",",alias:"numeric",digits:2,digitsOptional:!1},decimal:{alias:"numeric"},integer:{alias:"numeric",inputmode:"numeric",digits:0},percentage:{alias:"numeric",min:0,max:100,suffix:" %",digits:0,allowMinus:!1},indianns:{alias:"numeric",_mask:function(e){return"("+e.groupSeparator+"99){*|1}("+e.groupSeparator+"999){1|1}"},groupSeparator:",",radixPoint:".",placeholder:"0",digits:2,digitsOptional:!1}})},9380:function(e,t,i){var a;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var n=((a=i(8741))&&a.__esModule?a:{default:a}).default?window:{};t.default=n},7760:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.HandleNativePlaceholder=function(e,t){var i=e?e.inputmask:this;if(s.ie){if(e.inputmask._valueGet()!==t&&(e.placeholder!==t||""===e.placeholder)){var a=o.getBuffer.call(i).slice(),n=e.inputmask._valueGet();if(n!==t){var r=o.getLastValidPosition.call(i);-1===r&&n===o.getBufferTemplate.call(i).join("")?a=[]:-1!==r&&f.call(i,a),p(e,a)}}}else e.placeholder!==t&&(e.placeholder=t,""===e.placeholder&&e.removeAttribute("placeholder"))},t.applyInputValue=c,t.checkVal=d,t.clearOptionalTail=f,t.unmaskedvalue=function(e){var t=e?e.inputmask:this,i=t.opts,a=t.maskset;if(e){if(void 0===e.inputmask)return e.value;e.inputmask&&e.inputmask.refreshValue&&c(e,e.inputmask._valueGet(!0))}var n=[],r=a.validPositions;for(var l in r)r[l]&&r[l].match&&(1!=r[l].match.static||Array.isArray(a.metadata)&&!0!==r[l].generatedInput)&&n.push(r[l].input);var s=0===n.length?"":(t.isRTL?n.reverse():n).join("");if("function"==typeof i.onUnMask){var u=(t.isRTL?o.getBuffer.call(t).slice().reverse():o.getBuffer.call(t)).join("");s=i.onUnMask.call(t,u,s,i)}return s},t.writeBuffer=p;var a,n=(a=i(5581))&&a.__esModule?a:{default:a},r=i(4713),o=i(8711),l=i(7215),s=i(9845),u=i(6030);function c(e,t){var i=e?e.inputmask:this,a=i.opts;e.inputmask.refreshValue=!1,"function"==typeof a.onBeforeMask&&(t=a.onBeforeMask.call(i,t,a)||t),d(e,!0,!1,t=t.toString().split("")),i.undoValue=i._valueGet(!0),(a.clearMaskOnLostFocus||a.clearIncomplete)&&e.inputmask._valueGet()===o.getBufferTemplate.call(i).join("")&&-1===o.getLastValidPosition.call(i)&&e.inputmask._valueSet("")}function f(e){e.length=0;for(var t,i=r.getMaskTemplate.call(this,!0,0,!0,void 0,!0);void 0!==(t=i.shift());)e.push(t);return e}function d(e,t,i,a,n){var s=e?e.inputmask:this,c=s.maskset,f=s.opts,d=s.dependencyLib,h=a.slice(),v="",m=-1,g=void 0,k=f.skipOptionalPartCharacter;f.skipOptionalPartCharacter="",o.resetMaskSet.call(s),c.tests={},m=f.radixPoint?o.determineNewCaretPosition.call(s,{begin:0,end:0},!1,!1===f.__financeInput?"radixFocus":void 0).begin:0,c.p=m,s.caretPos={begin:m};var y=[],b=s.caretPos;if(h.forEach((function(e,t){if(void 0!==e){var a=new d.Event("_checkval");a.keyCode=e.toString().charCodeAt(0),v+=e;var n=o.getLastValidPosition.call(s,void 0,!0);!function(e,t){for(var i=r.getMaskTemplate.call(s,!0,0).slice(e,o.seekNext.call(s,e,!1,!1)).join("").replace(/'/g,""),a=i.indexOf(t);a>0&&" "===i[a-1];)a--;var n=0===a&&!o.isMask.call(s,e)&&(r.getTest.call(s,e).match.nativeDef===t.charAt(0)||!0===r.getTest.call(s,e).match.static&&r.getTest.call(s,e).match.nativeDef==="'"+t.charAt(0)||" "===r.getTest.call(s,e).match.nativeDef&&(r.getTest.call(s,e+1).match.nativeDef===t.charAt(0)||!0===r.getTest.call(s,e+1).match.static&&r.getTest.call(s,e+1).match.nativeDef==="'"+t.charAt(0)));if(!n&&a>0&&!o.isMask.call(s,e,!1,!0)){var l=o.seekNext.call(s,e);s.caretPos.begin<l&&(s.caretPos={begin:l})}return n}(m,v)?(g=u.EventHandlers.keypressEvent.call(s,a,!0,!1,i,s.caretPos.begin))&&(m=s.caretPos.begin+1,v=""):g=u.EventHandlers.keypressEvent.call(s,a,!0,!1,i,n+1),g?(void 0!==g.pos&&c.validPositions[g.pos]&&!0===c.validPositions[g.pos].match.static&&void 0===c.validPositions[g.pos].alternation&&(y.push(g.pos),s.isRTL||(g.forwardPosition=g.pos+1)),p.call(s,void 0,o.getBuffer.call(s),g.forwardPosition,a,!1),s.caretPos={begin:g.forwardPosition,end:g.forwardPosition},b=s.caretPos):void 0===c.validPositions[t]&&h[t]===r.getPlaceholder.call(s,t)&&o.isMask.call(s,t,!0)?s.caretPos.begin++:s.caretPos=b}})),y.length>0){var x,P,E=o.seekNext.call(s,-1,void 0,!1);if(!l.isComplete.call(s,o.getBuffer.call(s))&&y.length<=E||l.isComplete.call(s,o.getBuffer.call(s))&&y.length>0&&y.length!==E&&0===y[0])for(var S=E;void 0!==(x=y.shift());){var _=new d.Event("_checkval");if((P=c.validPositions[x]).generatedInput=!0,_.keyCode=P.input.charCodeAt(0),(g=u.EventHandlers.keypressEvent.call(s,_,!0,!1,i,S))&&void 0!==g.pos&&g.pos!==x&&c.validPositions[g.pos]&&!0===c.validPositions[g.pos].match.static)y.push(g.pos);else if(!g)break;S++}}t&&p.call(s,e,o.getBuffer.call(s),g?g.forwardPosition:s.caretPos.begin,n||new d.Event("checkval"),n&&("input"===n.type&&s.undoValue!==o.getBuffer.call(s).join("")||"paste"===n.type)),f.skipOptionalPartCharacter=k}function p(e,t,i,a,r){var s=e?e.inputmask:this,u=s.opts,c=s.dependencyLib;if(a&&"function"==typeof u.onBeforeWrite){var f=u.onBeforeWrite.call(s,a,t,i,u);if(f){if(f.refreshFromBuffer){var d=f.refreshFromBuffer;l.refreshFromBuffer.call(s,!0===d?d:d.start,d.end,f.buffer||t),t=o.getBuffer.call(s,!0)}void 0!==i&&(i=void 0!==f.caret?f.caret:i)}}if(void 0!==e&&(e.inputmask._valueSet(t.join("")),void 0===i||void 0!==a&&"blur"===a.type||o.caret.call(s,e,i,void 0,void 0,void 0!==a&&"keydown"===a.type&&(a.keyCode===n.default.DELETE||a.keyCode===n.default.BACKSPACE)),!0===r)){var p=c(e),h=e.inputmask._valueGet();e.inputmask.skipInputEvent=!0,p.trigger("input"),setTimeout((function(){h===o.getBufferTemplate.call(s).join("")?p.trigger("cleared"):!0===l.isComplete.call(s,t)&&p.trigger("complete")}),0)}}},2394:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,i(7149),i(3194);var a=i(157),n=m(i(4963)),r=m(i(9380)),o=i(2391),l=i(4713),s=i(8711),u=i(7215),c=i(7760),f=i(9716),d=m(i(7392)),p=m(i(3976)),h=m(i(8741));function v(e){return v="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},v(e)}function m(e){return e&&e.__esModule?e:{default:e}}var g=r.default.document,k="_inputmask_opts";function y(e,t,i){if(h.default){if(!(this instanceof y))return new y(e,t,i);this.dependencyLib=n.default,this.el=void 0,this.events={},this.maskset=void 0,!0!==i&&("[object Object]"===Object.prototype.toString.call(e)?t=e:(t=t||{},e&&(t.alias=e)),this.opts=n.default.extend(!0,{},this.defaults,t),this.noMasksCache=t&&void 0!==t.definitions,this.userOptions=t||{},b(this.opts.alias,t,this.opts)),this.refreshValue=!1,this.undoValue=void 0,this.$el=void 0,this.skipKeyPressEvent=!1,this.skipInputEvent=!1,this.validationEvent=!1,this.ignorable=!1,this.maxLength,this.mouseEnter=!1,this.originalPlaceholder=void 0,this.isComposing=!1}}function b(e,t,i){var a=y.prototype.aliases[e];return a?(a.alias&&b(a.alias,void 0,i),n.default.extend(!0,i,a),n.default.extend(!0,i,t),!0):(null===i.mask&&(i.mask=e),!1)}y.prototype={dataAttribute:"data-inputmask",defaults:p.default,definitions:d.default,aliases:{},masksCache:{},get isRTL(){return this.opts.isRTL||this.opts.numericInput},mask:function(e){var t=this;return"string"==typeof e&&(e=g.getElementById(e)||g.querySelectorAll(e)),(e=e.nodeName?[e]:Array.isArray(e)?e:Array.from(e)).forEach((function(e,i){var l=n.default.extend(!0,{},t.opts);if(function(e,t,i,a){function o(t,n){var o=""===a?t:a+"-"+t;null!==(n=void 0!==n?n:e.getAttribute(o))&&("string"==typeof n&&(0===t.indexOf("on")?n=r.default[n]:"false"===n?n=!1:"true"===n&&(n=!0)),i[t]=n)}if(!0===t.importDataAttributes){var l,s,u,c,f=e.getAttribute(a);if(f&&""!==f&&(f=f.replace(/'/g,'"'),s=JSON.parse("{"+f+"}")),s)for(c in u=void 0,s)if("alias"===c.toLowerCase()){u=s[c];break}for(l in o("alias",u),i.alias&&b(i.alias,i,t),t){if(s)for(c in u=void 0,s)if(c.toLowerCase()===l.toLowerCase()){u=s[c];break}o(l,u)}}n.default.extend(!0,t,i),("rtl"===e.dir||t.rightAlign)&&(e.style.textAlign="right");("rtl"===e.dir||t.numericInput)&&(e.dir="ltr",e.removeAttribute("dir"),t.isRTL=!0);return Object.keys(i).length}(e,l,n.default.extend(!0,{},t.userOptions),t.dataAttribute)){var s=(0,o.generateMaskSet)(l,t.noMasksCache);void 0!==s&&(void 0!==e.inputmask&&(e.inputmask.opts.autoUnmask=!0,e.inputmask.remove()),e.inputmask=new y(void 0,void 0,!0),e.inputmask.opts=l,e.inputmask.noMasksCache=t.noMasksCache,e.inputmask.userOptions=n.default.extend(!0,{},t.userOptions),e.inputmask.el=e,e.inputmask.$el=(0,n.default)(e),e.inputmask.maskset=s,n.default.data(e,k,t.userOptions),a.mask.call(e.inputmask))}})),e&&e[0]&&e[0].inputmask||this},option:function(e,t){return"string"==typeof e?this.opts[e]:"object"===v(e)?(n.default.extend(this.userOptions,e),this.el&&!0!==t&&this.mask(this.el),this):void 0},unmaskedvalue:function(e){if(this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),void 0===this.el||void 0!==e){var t=("function"==typeof this.opts.onBeforeMask&&this.opts.onBeforeMask.call(this,e,this.opts)||e).split("");c.checkVal.call(this,void 0,!1,!1,t),"function"==typeof this.opts.onBeforeWrite&&this.opts.onBeforeWrite.call(this,void 0,s.getBuffer.call(this),0,this.opts)}return c.unmaskedvalue.call(this,this.el)},remove:function(){if(this.el){n.default.data(this.el,k,null);var e=this.opts.autoUnmask?(0,c.unmaskedvalue)(this.el):this._valueGet(this.opts.autoUnmask);e!==s.getBufferTemplate.call(this).join("")?this._valueSet(e,this.opts.autoUnmask):this._valueSet(""),f.EventRuler.off(this.el),Object.getOwnPropertyDescriptor&&Object.getPrototypeOf?Object.getOwnPropertyDescriptor(Object.getPrototypeOf(this.el),"value")&&this.__valueGet&&Object.defineProperty(this.el,"value",{get:this.__valueGet,set:this.__valueSet,configurable:!0}):g.__lookupGetter__&&this.el.__lookupGetter__("value")&&this.__valueGet&&(this.el.__defineGetter__("value",this.__valueGet),this.el.__defineSetter__("value",this.__valueSet)),this.el.inputmask=void 0}return this.el},getemptymask:function(){return this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),s.getBufferTemplate.call(this).join("")},hasMaskedValue:function(){return!this.opts.autoUnmask},isComplete:function(){return this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),u.isComplete.call(this,s.getBuffer.call(this))},getmetadata:function(){if(this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),Array.isArray(this.maskset.metadata)){var e=l.getMaskTemplate.call(this,!0,0,!1).join("");return this.maskset.metadata.forEach((function(t){return t.mask!==e||(e=t,!1)})),e}return this.maskset.metadata},isValid:function(e){if(this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache),e){var t=("function"==typeof this.opts.onBeforeMask&&this.opts.onBeforeMask.call(this,e,this.opts)||e).split("");c.checkVal.call(this,void 0,!0,!1,t)}else e=this.isRTL?s.getBuffer.call(this).slice().reverse().join(""):s.getBuffer.call(this).join("");for(var i=s.getBuffer.call(this),a=s.determineLastRequiredPosition.call(this),n=i.length-1;n>a&&!s.isMask.call(this,n);n--);return i.splice(a,n+1-a),u.isComplete.call(this,i)&&e===(this.isRTL?s.getBuffer.call(this).slice().reverse().join(""):s.getBuffer.call(this).join(""))},format:function(e,t){this.maskset=this.maskset||(0,o.generateMaskSet)(this.opts,this.noMasksCache);var i=("function"==typeof this.opts.onBeforeMask&&this.opts.onBeforeMask.call(this,e,this.opts)||e).split("");c.checkVal.call(this,void 0,!0,!1,i);var a=this.isRTL?s.getBuffer.call(this).slice().reverse().join(""):s.getBuffer.call(this).join("");return t?{value:a,metadata:this.getmetadata()}:a},setValue:function(e){this.el&&(0,n.default)(this.el).trigger("setvalue",[e])},analyseMask:o.analyseMask},y.extendDefaults=function(e){n.default.extend(!0,y.prototype.defaults,e)},y.extendDefinitions=function(e){n.default.extend(!0,y.prototype.definitions,e)},y.extendAliases=function(e){n.default.extend(!0,y.prototype.aliases,e)},y.format=function(e,t,i){return y(t).format(e,i)},y.unmask=function(e,t){return y(t).unmaskedvalue(e)},y.isValid=function(e,t){return y(t).isValid(e)},y.remove=function(e){"string"==typeof e&&(e=g.getElementById(e)||g.querySelectorAll(e)),(e=e.nodeName?[e]:e).forEach((function(e){e.inputmask&&e.inputmask.remove()}))},y.setValue=function(e,t){"string"==typeof e&&(e=g.getElementById(e)||g.querySelectorAll(e)),(e=e.nodeName?[e]:e).forEach((function(e){e.inputmask?e.inputmask.setValue(t):(0,n.default)(e).trigger("setvalue",[t])}))},y.dependencyLib=n.default,r.default.Inputmask=y;var x=y;t.default=x},5296:function(e,t,i){function a(e){return a="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},a(e)}var n=h(i(9380)),r=h(i(2394)),o=h(i(8741));function l(e,t){for(var i=0;i<t.length;i++){var a=t[i];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}function s(e,t){if(t&&("object"===a(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}function u(e){var t="function"==typeof Map?new Map:void 0;return u=function(e){if(null===e||(i=e,-1===Function.toString.call(i).indexOf("[native code]")))return e;var i;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,a)}function a(){return c(e,arguments,p(this).constructor)}return a.prototype=Object.create(e.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),d(a,e)},u(e)}function c(e,t,i){return c=f()?Reflect.construct:function(e,t,i){var a=[null];a.push.apply(a,t);var n=new(Function.bind.apply(e,a));return i&&d(n,i.prototype),n},c.apply(null,arguments)}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(e,t)}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}function h(e){return e&&e.__esModule?e:{default:e}}var v=n.default.document;if(o.default&&v&&v.head&&v.head.attachShadow&&n.default.customElements&&void 0===n.default.customElements.get("input-mask")){var m=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");Object.defineProperty(e,"prototype",{value:Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),writable:!1}),t&&d(e,t)}(c,e);var t,i,a,n,o,u=(t=c,i=f(),function(){var e,a=p(t);if(i){var n=p(this).constructor;e=Reflect.construct(a,arguments,n)}else e=a.apply(this,arguments);return s(this,e)});function c(){var e;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,c);var t=(e=u.call(this)).getAttributeNames(),i=e.attachShadow({mode:"closed"}),a=v.createElement("input");for(var n in a.type="text",i.appendChild(a),t)Object.prototype.hasOwnProperty.call(t,n)&&a.setAttribute(t[n],e.getAttribute(t[n]));var o=new r.default;return o.dataAttribute="",o.mask(a),a.inputmask.shadowRoot=i,e}return a=c,n&&l(a.prototype,n),o&&l(a,o),Object.defineProperty(a,"prototype",{writable:!1}),a}(u(HTMLElement));n.default.customElements.define("input-mask",m)}},2391:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.analyseMask=function(e,t,i){var a,o,l,s,u,c,f=/(?:[?*+]|\{[0-9+*]+(?:,[0-9+*]*)?(?:\|[0-9+*]*)?\})|[^.?*+^${[]()|\\]+|./g,d=/\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g,p=!1,h=new n.default,v=[],m=[],g=!1;function k(e,a,n){n=void 0!==n?n:e.matches.length;var o=e.matches[n-1];if(t)0===a.indexOf("[")||p&&/\\d|\\s|\\w/i.test(a)||"."===a?e.matches.splice(n++,0,{fn:new RegExp(a,i.casing?"i":""),static:!1,optionality:!1,newBlockMarker:void 0===o?"master":o.def!==a,casing:null,def:a,placeholder:void 0,nativeDef:a}):(p&&(a=a[a.length-1]),a.split("").forEach((function(t,a){o=e.matches[n-1],e.matches.splice(n++,0,{fn:/[a-z]/i.test(i.staticDefinitionSymbol||t)?new RegExp("["+(i.staticDefinitionSymbol||t)+"]",i.casing?"i":""):null,static:!0,optionality:!1,newBlockMarker:void 0===o?"master":o.def!==t&&!0!==o.static,casing:null,def:i.staticDefinitionSymbol||t,placeholder:void 0!==i.staticDefinitionSymbol?t:void 0,nativeDef:(p?"'":"")+t})}))),p=!1;else{var l=i.definitions&&i.definitions[a]||i.usePrototypeDefinitions&&r.default.prototype.definitions[a];l&&!p?e.matches.splice(n++,0,{fn:l.validator?"string"==typeof l.validator?new RegExp(l.validator,i.casing?"i":""):new function(){this.test=l.validator}:new RegExp("."),static:l.static||!1,optionality:l.optional||!1,newBlockMarker:void 0===o||l.optional?"master":o.def!==(l.definitionSymbol||a),casing:l.casing,def:l.definitionSymbol||a,placeholder:l.placeholder,nativeDef:a,generated:l.generated}):(e.matches.splice(n++,0,{fn:/[a-z]/i.test(i.staticDefinitionSymbol||a)?new RegExp("["+(i.staticDefinitionSymbol||a)+"]",i.casing?"i":""):null,static:!0,optionality:!1,newBlockMarker:void 0===o?"master":o.def!==a&&!0!==o.static,casing:null,def:i.staticDefinitionSymbol||a,placeholder:void 0!==i.staticDefinitionSymbol?a:void 0,nativeDef:(p?"'":"")+a}),p=!1)}}function y(){if(v.length>0){if(k(s=v[v.length-1],o),s.isAlternator){u=v.pop();for(var e=0;e<u.matches.length;e++)u.matches[e].isGroup&&(u.matches[e].isGroup=!1);v.length>0?(s=v[v.length-1]).matches.push(u):h.matches.push(u)}}else k(h,o)}function b(e){var t=new n.default(!0);return t.openGroup=!1,t.matches=e,t}function x(){if((l=v.pop()).openGroup=!1,void 0!==l)if(v.length>0){if((s=v[v.length-1]).matches.push(l),s.isAlternator){for(var e=(u=v.pop()).matches[0].matches?u.matches[0].matches.length:1,t=0;t<u.matches.length;t++)u.matches[t].isGroup=!1,u.matches[t].alternatorGroup=!1,null===i.keepStatic&&e<(u.matches[t].matches?u.matches[t].matches.length:1)&&(i.keepStatic=!0),e=u.matches[t].matches?u.matches[t].matches.length:1;v.length>0?(s=v[v.length-1]).matches.push(u):h.matches.push(u)}}else h.matches.push(l);else y()}function P(e){var t=e.pop();return t.isQuantifier&&(t=b([e.pop(),t])),t}t&&(i.optionalmarker[0]=void 0,i.optionalmarker[1]=void 0);for(;a=t?d.exec(e):f.exec(e);){if(o=a[0],t){switch(o.charAt(0)){case"?":o="{0,1}";break;case"+":case"*":o="{"+o+"}";break;case"|":if(0===v.length){var E=b(h.matches);E.openGroup=!0,v.push(E),h.matches=[],g=!0}}if("\\d"===o)o="[0-9]"}if(p)y();else switch(o.charAt(0)){case"$":case"^":t||y();break;case i.escapeChar:p=!0,t&&y();break;case i.optionalmarker[1]:case i.groupmarker[1]:x();break;case i.optionalmarker[0]:v.push(new n.default(!1,!0));break;case i.groupmarker[0]:v.push(new n.default(!0));break;case i.quantifiermarker[0]:var S=new n.default(!1,!1,!0),_=(o=o.replace(/[{}?]/g,"")).split("|"),w=_[0].split(","),M=isNaN(w[0])?w[0]:parseInt(w[0]),O=1===w.length?M:isNaN(w[1])?w[1]:parseInt(w[1]),T=isNaN(_[1])?_[1]:parseInt(_[1]);"*"!==M&&"+"!==M||(M="*"===O?0:1),S.quantifier={min:M,max:O,jit:T};var C=v.length>0?v[v.length-1].matches:h.matches;if((a=C.pop()).isAlternator){C.push(a),C=a.matches;var A=new n.default(!0),D=C.pop();C.push(A),C=A.matches,a=D}a.isGroup||(a=b([a])),C.push(a),C.push(S);break;case i.alternatormarker:if(v.length>0){var j=(s=v[v.length-1]).matches[s.matches.length-1];c=s.openGroup&&(void 0===j.matches||!1===j.isGroup&&!1===j.isAlternator)?v.pop():P(s.matches)}else c=P(h.matches);if(c.isAlternator)v.push(c);else if(c.alternatorGroup?(u=v.pop(),c.alternatorGroup=!1):u=new n.default(!1,!1,!1,!0),u.matches.push(c),v.push(u),c.openGroup){c.openGroup=!1;var B=new n.default(!0);B.alternatorGroup=!0,v.push(B)}break;default:y()}}g&&x();for(;v.length>0;)l=v.pop(),h.matches.push(l);h.matches.length>0&&(!function e(a){a&&a.matches&&a.matches.forEach((function(n,r){var o=a.matches[r+1];(void 0===o||void 0===o.matches||!1===o.isQuantifier)&&n&&n.isGroup&&(n.isGroup=!1,t||(k(n,i.groupmarker[0],0),!0!==n.openGroup&&k(n,i.groupmarker[1]))),e(n)}))}(h),m.push(h));(i.numericInput||i.isRTL)&&function e(t){for(var a in t.matches=t.matches.reverse(),t.matches)if(Object.prototype.hasOwnProperty.call(t.matches,a)){var n=parseInt(a);if(t.matches[a].isQuantifier&&t.matches[n+1]&&t.matches[n+1].isGroup){var r=t.matches[a];t.matches.splice(a,1),t.matches.splice(n+1,0,r)}void 0!==t.matches[a].matches?t.matches[a]=e(t.matches[a]):t.matches[a]=((o=t.matches[a])===i.optionalmarker[0]?o=i.optionalmarker[1]:o===i.optionalmarker[1]?o=i.optionalmarker[0]:o===i.groupmarker[0]?o=i.groupmarker[1]:o===i.groupmarker[1]&&(o=i.groupmarker[0]),o)}var o;return t}(m[0]);return m},t.generateMaskSet=function(e,t){var i;function n(e,i,n){var o,l,s=!1;if(null!==e&&""!==e||((s=null!==n.regex)?e=(e=n.regex).replace(/^(\^)(.*)(\$)$/,"$2"):(s=!0,e=".*")),1===e.length&&!1===n.greedy&&0!==n.repeat&&(n.placeholder=""),n.repeat>0||"*"===n.repeat||"+"===n.repeat){var u="*"===n.repeat?0:"+"===n.repeat?1:n.repeat;e=n.groupmarker[0]+e+n.groupmarker[1]+n.quantifiermarker[0]+u+","+n.repeat+n.quantifiermarker[1]}return l=s?"regex_"+n.regex:n.numericInput?e.split("").reverse().join(""):e,null!==n.keepStatic&&(l="ks_"+n.keepStatic+l),void 0===r.default.prototype.masksCache[l]||!0===t?(o={mask:e,maskToken:r.default.prototype.analyseMask(e,s,n),validPositions:{},_buffer:void 0,buffer:void 0,tests:{},excludes:{},metadata:i,maskLength:void 0,jitOffset:{}},!0!==t&&(r.default.prototype.masksCache[l]=o,o=a.default.extend(!0,{},r.default.prototype.masksCache[l]))):o=a.default.extend(!0,{},r.default.prototype.masksCache[l]),o}"function"==typeof e.mask&&(e.mask=e.mask(e));if(Array.isArray(e.mask)){if(e.mask.length>1){null===e.keepStatic&&(e.keepStatic=!0);var o=e.groupmarker[0];return(e.isRTL?e.mask.reverse():e.mask).forEach((function(t){o.length>1&&(o+=e.alternatormarker),void 0!==t.mask&&"function"!=typeof t.mask?o+=t.mask:o+=t})),n(o+=e.groupmarker[1],e.mask,e)}e.mask=e.mask.pop()}i=e.mask&&void 0!==e.mask.mask&&"function"!=typeof e.mask.mask?n(e.mask.mask,e.mask,e):n(e.mask,e.mask,e);null===e.keepStatic&&(e.keepStatic=!1);return i};var a=o(i(4963)),n=o(i(9695)),r=o(i(2394));function o(e){return e&&e.__esModule?e:{default:e}}},157:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.mask=function(){var e=this,t=this.opts,i=this.el,a=this.dependencyLib;l.EventRuler.off(i);var f=function(t,i){"textarea"!==t.tagName.toLowerCase()&&i.ignorables.push(n.default.ENTER);var s=t.getAttribute("type"),u="input"===t.tagName.toLowerCase()&&i.supportsInputType.includes(s)||t.isContentEditable||"textarea"===t.tagName.toLowerCase();if(!u)if("input"===t.tagName.toLowerCase()){var c=document.createElement("input");c.setAttribute("type",s),u="text"===c.type,c=null}else u="partial";return!1!==u?function(t){var n,s;function u(){return this.inputmask?this.inputmask.opts.autoUnmask?this.inputmask.unmaskedvalue():-1!==r.getLastValidPosition.call(e)||!0!==i.nullable?(this.inputmask.shadowRoot||this.ownerDocument).activeElement===this&&i.clearMaskOnLostFocus?(e.isRTL?o.clearOptionalTail.call(e,r.getBuffer.call(e).slice()).reverse():o.clearOptionalTail.call(e,r.getBuffer.call(e).slice())).join(""):n.call(this):"":n.call(this)}function c(e){s.call(this,e),this.inputmask&&(0,o.applyInputValue)(this,e)}if(!t.inputmask.__valueGet){if(!0!==i.noValuePatching){if(Object.getOwnPropertyDescriptor){var f=Object.getPrototypeOf?Object.getOwnPropertyDescriptor(Object.getPrototypeOf(t),"value"):void 0;f&&f.get&&f.set?(n=f.get,s=f.set,Object.defineProperty(t,"value",{get:u,set:c,configurable:!0})):"input"!==t.tagName.toLowerCase()&&(n=function(){return this.textContent},s=function(e){this.textContent=e},Object.defineProperty(t,"value",{get:u,set:c,configurable:!0}))}else document.__lookupGetter__&&t.__lookupGetter__("value")&&(n=t.__lookupGetter__("value"),s=t.__lookupSetter__("value"),t.__defineGetter__("value",u),t.__defineSetter__("value",c));t.inputmask.__valueGet=n,t.inputmask.__valueSet=s}t.inputmask._valueGet=function(t){return e.isRTL&&!0!==t?n.call(this.el).split("").reverse().join(""):n.call(this.el)},t.inputmask._valueSet=function(t,i){s.call(this.el,null==t?"":!0!==i&&e.isRTL?t.split("").reverse().join(""):t)},void 0===n&&(n=function(){return this.value},s=function(e){this.value=e},function(t){if(a.valHooks&&(void 0===a.valHooks[t]||!0!==a.valHooks[t].inputmaskpatch)){var n=a.valHooks[t]&&a.valHooks[t].get?a.valHooks[t].get:function(e){return e.value},l=a.valHooks[t]&&a.valHooks[t].set?a.valHooks[t].set:function(e,t){return e.value=t,e};a.valHooks[t]={get:function(t){if(t.inputmask){if(t.inputmask.opts.autoUnmask)return t.inputmask.unmaskedvalue();var a=n(t);return-1!==r.getLastValidPosition.call(e,void 0,void 0,t.inputmask.maskset.validPositions)||!0!==i.nullable?a:""}return n(t)},set:function(e,t){var i=l(e,t);return e.inputmask&&(0,o.applyInputValue)(e,t),i},inputmaskpatch:!0}}}(t.type),function(t){l.EventRuler.on(t,"mouseenter",(function(){var t=this.inputmask._valueGet(!0);t!==(e.isRTL?r.getBuffer.call(e).reverse():r.getBuffer.call(e)).join("")&&(0,o.applyInputValue)(this,t)}))}(t))}}(t):t.inputmask=void 0,u}(i,t);if(!1!==f){e.originalPlaceholder=i.placeholder,e.maxLength=void 0!==i?i.maxLength:void 0,-1===e.maxLength&&(e.maxLength=void 0),"inputMode"in i&&null===i.getAttribute("inputmode")&&(i.inputMode=t.inputmode,i.setAttribute("inputmode",t.inputmode)),!0===f&&(t.showMaskOnFocus=t.showMaskOnFocus&&-1===["cc-number","cc-exp"].indexOf(i.autocomplete),s.iphone&&(t.insertModeVisual=!1),l.EventRuler.on(i,"submit",c.EventHandlers.submitEvent),l.EventRuler.on(i,"reset",c.EventHandlers.resetEvent),l.EventRuler.on(i,"blur",c.EventHandlers.blurEvent),l.EventRuler.on(i,"focus",c.EventHandlers.focusEvent),l.EventRuler.on(i,"invalid",c.EventHandlers.invalidEvent),l.EventRuler.on(i,"click",c.EventHandlers.clickEvent),l.EventRuler.on(i,"mouseleave",c.EventHandlers.mouseleaveEvent),l.EventRuler.on(i,"mouseenter",c.EventHandlers.mouseenterEvent),l.EventRuler.on(i,"paste",c.EventHandlers.pasteEvent),l.EventRuler.on(i,"cut",c.EventHandlers.cutEvent),l.EventRuler.on(i,"complete",t.oncomplete),l.EventRuler.on(i,"incomplete",t.onincomplete),l.EventRuler.on(i,"cleared",t.oncleared),!0!==t.inputEventOnly&&(l.EventRuler.on(i,"keydown",c.EventHandlers.keydownEvent),l.EventRuler.on(i,"keypress",c.EventHandlers.keypressEvent),l.EventRuler.on(i,"keyup",c.EventHandlers.keyupEvent)),(s.mobile||t.inputEventOnly)&&i.removeAttribute("maxLength"),l.EventRuler.on(i,"input",c.EventHandlers.inputFallBackEvent),l.EventRuler.on(i,"compositionend",c.EventHandlers.compositionendEvent)),l.EventRuler.on(i,"setvalue",c.EventHandlers.setValueEvent),r.getBufferTemplate.call(e).join(""),e.undoValue=e._valueGet(!0);var d=(i.inputmask.shadowRoot||i.ownerDocument).activeElement;if(""!==i.inputmask._valueGet(!0)||!1===t.clearMaskOnLostFocus||d===i){(0,o.applyInputValue)(i,i.inputmask._valueGet(!0),t);var p=r.getBuffer.call(e).slice();!1===u.isComplete.call(e,p)&&t.clearIncomplete&&r.resetMaskSet.call(e),t.clearMaskOnLostFocus&&d!==i&&(-1===r.getLastValidPosition.call(e)?p=[]:o.clearOptionalTail.call(e,p)),(!1===t.clearMaskOnLostFocus||t.showMaskOnFocus&&d===i||""!==i.inputmask._valueGet(!0))&&(0,o.writeBuffer)(i,p),d===i&&r.caret.call(e,i,r.seekNext.call(e,r.getLastValidPosition.call(e)))}}};var a,n=(a=i(5581))&&a.__esModule?a:{default:a},r=i(8711),o=i(7760),l=i(9716),s=i(9845),u=i(7215),c=i(6030)},9695:function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i,a){this.matches=[],this.openGroup=e||!1,this.alternatorGroup=!1,this.isGroup=e||!1,this.isOptional=t||!1,this.isQuantifier=i||!1,this.isAlternator=a||!1,this.quantifier={min:1,max:1}}},3194:function(){Array.prototype.includes||Object.defineProperty(Array.prototype,"includes",{value:function(e,t){if(null==this)throw new TypeError('"this" is null or not defined');var i=Object(this),a=i.length>>>0;if(0===a)return!1;for(var n=0|t,r=Math.max(n>=0?n:a-Math.abs(n),0);r<a;){if(i[r]===e)return!0;r++}return!1}})},7149:function(){function e(t){return e="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},e(t)}"function"!=typeof Object.getPrototypeOf&&(Object.getPrototypeOf="object"===e("test".__proto__)?function(e){return e.__proto__}:function(e){return e.constructor.prototype})},8711:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.caret=function(e,t,i,a,n){var r,o=this,l=this.opts;if(void 0===t)return"selectionStart"in e&&"selectionEnd"in e?(t=e.selectionStart,i=e.selectionEnd):window.getSelection?(r=window.getSelection().getRangeAt(0)).commonAncestorContainer.parentNode!==e&&r.commonAncestorContainer!==e||(t=r.startOffset,i=r.endOffset):document.selection&&document.selection.createRange&&(r=document.selection.createRange(),t=0-r.duplicate().moveStart("character",-e.inputmask._valueGet().length),i=t+r.text.length),{begin:a?t:u.call(o,t),end:a?i:u.call(o,i)};if(Array.isArray(t)&&(i=o.isRTL?t[0]:t[1],t=o.isRTL?t[1]:t[0]),void 0!==t.begin&&(i=o.isRTL?t.begin:t.end,t=o.isRTL?t.end:t.begin),"number"==typeof t){t=a?t:u.call(o,t),i="number"==typeof(i=a?i:u.call(o,i))?i:t;var s=parseInt(((e.ownerDocument.defaultView||window).getComputedStyle?(e.ownerDocument.defaultView||window).getComputedStyle(e,null):e.currentStyle).fontSize)*i;if(e.scrollLeft=s>e.scrollWidth?s:0,e.inputmask.caretPos={begin:t,end:i},l.insertModeVisual&&!1===l.insertMode&&t===i&&(n||i++),e===(e.inputmask.shadowRoot||e.ownerDocument).activeElement)if("setSelectionRange"in e)e.setSelectionRange(t,i);else if(window.getSelection){if(r=document.createRange(),void 0===e.firstChild||null===e.firstChild){var c=document.createTextNode("");e.appendChild(c)}r.setStart(e.firstChild,t<e.inputmask._valueGet().length?t:e.inputmask._valueGet().length),r.setEnd(e.firstChild,i<e.inputmask._valueGet().length?i:e.inputmask._valueGet().length),r.collapse(!0);var f=window.getSelection();f.removeAllRanges(),f.addRange(r)}else e.createTextRange&&((r=e.createTextRange()).collapse(!0),r.moveEnd("character",i),r.moveStart("character",t),r.select())}},t.determineLastRequiredPosition=function(e){var t,i,r=this,l=this.maskset,s=this.dependencyLib,u=a.getMaskTemplate.call(r,!0,o.call(r),!0,!0),c=u.length,f=o.call(r),d={},p=l.validPositions[f],h=void 0!==p?p.locator.slice():void 0;for(t=f+1;t<u.length;t++)i=a.getTestTemplate.call(r,t,h,t-1),h=i.locator.slice(),d[t]=s.extend(!0,{},i);var v=p&&void 0!==p.alternation?p.locator[p.alternation]:void 0;for(t=c-1;t>f&&(((i=d[t]).match.optionality||i.match.optionalQuantifier&&i.match.newBlockMarker||v&&(v!==d[t].locator[p.alternation]&&1!=i.match.static||!0===i.match.static&&i.locator[p.alternation]&&n.checkAlternationMatch.call(r,i.locator[p.alternation].toString().split(","),v.toString().split(","))&&""!==a.getTests.call(r,t)[0].def))&&u[t]===a.getPlaceholder.call(r,t,i.match));t--)c--;return e?{l:c,def:d[c]?d[c].match:void 0}:c},t.determineNewCaretPosition=function(e,t,i){var n=this,u=this.maskset,c=this.opts;t&&(n.isRTL?e.end=e.begin:e.begin=e.end);if(e.begin===e.end){switch(i=i||c.positionCaretOnClick){case"none":break;case"select":e={begin:0,end:r.call(n).length};break;case"ignore":e.end=e.begin=s.call(n,o.call(n));break;case"radixFocus":if(function(e){if(""!==c.radixPoint&&0!==c.digits){var t=u.validPositions;if(void 0===t[e]||t[e].input===a.getPlaceholder.call(n,e)){if(e<s.call(n,-1))return!0;var i=r.call(n).indexOf(c.radixPoint);if(-1!==i){for(var o in t)if(t[o]&&i<o&&t[o].input!==a.getPlaceholder.call(n,o))return!1;return!0}}}return!1}(e.begin)){var f=r.call(n).join("").indexOf(c.radixPoint);e.end=e.begin=c.numericInput?s.call(n,f):f;break}default:var d=e.begin,p=o.call(n,d,!0),h=s.call(n,-1!==p||l.call(n,0)?p:-1);if(d<=h)e.end=e.begin=l.call(n,d,!1,!0)?d:s.call(n,d);else{var v=u.validPositions[p],m=a.getTestTemplate.call(n,h,v?v.match.locator:void 0,v),g=a.getPlaceholder.call(n,h,m.match);if(""!==g&&r.call(n)[h]!==g&&!0!==m.match.optionalQuantifier&&!0!==m.match.newBlockMarker||!l.call(n,h,c.keepStatic,!0)&&m.match.def===g){var k=s.call(n,h);(d>=k||d===h)&&(h=k)}e.end=e.begin=h}}return e}},t.getBuffer=r,t.getBufferTemplate=function(){var e=this.maskset;void 0===e._buffer&&(e._buffer=a.getMaskTemplate.call(this,!1,1),void 0===e.buffer&&(e.buffer=e._buffer.slice()));return e._buffer},t.getLastValidPosition=o,t.isMask=l,t.resetMaskSet=function(e){var t=this.maskset;t.buffer=void 0,!0!==e&&(t.validPositions={},t.p=0)},t.seekNext=s,t.seekPrevious=function(e,t){var i=this,n=e-1;if(e<=0)return 0;for(;n>0&&(!0===t&&(!0!==a.getTest.call(i,n).match.newBlockMarker||!l.call(i,n,void 0,!0))||!0!==t&&!l.call(i,n,void 0,!0));)n--;return n},t.translatePosition=u;var a=i(4713),n=i(7215);function r(e){var t=this.maskset;return void 0!==t.buffer&&!0!==e||(t.buffer=a.getMaskTemplate.call(this,!0,o.call(this),!0),void 0===t._buffer&&(t._buffer=t.buffer.slice())),t.buffer}function o(e,t,i){var a=this.maskset,n=-1,r=-1,o=i||a.validPositions;for(var l in void 0===e&&(e=-1),o){var s=parseInt(l);o[s]&&(t||!0!==o[s].generatedInput)&&(s<=e&&(n=s),s>=e&&(r=s))}return-1===n||n==e?r:-1==r||e-n<r-e?n:r}function l(e,t,i){var n=this,r=this.maskset,o=a.getTestTemplate.call(n,e).match;if(""===o.def&&(o=a.getTest.call(n,e).match),!0!==o.static)return o.fn;if(!0===i&&void 0!==r.validPositions[e]&&!0!==r.validPositions[e].generatedInput)return!0;if(!0!==t&&e>-1){if(i){var l=a.getTests.call(n,e);return l.length>1+(""===l[l.length-1].match.def?1:0)}var s=a.determineTestTemplate.call(n,e,a.getTests.call(n,e)),u=a.getPlaceholder.call(n,e,s.match);return s.match.def!==u}return!1}function s(e,t,i){var n=this;void 0===i&&(i=!0);for(var r=e+1;""!==a.getTest.call(n,r).match.def&&(!0===t&&(!0!==a.getTest.call(n,r).match.newBlockMarker||!l.call(n,r,void 0,!0))||!0!==t&&!l.call(n,r,void 0,i));)r++;return r}function u(e){var t=this.opts,i=this.el;return!this.isRTL||"number"!=typeof e||t.greedy&&""===t.placeholder||!i||(e=Math.abs(this._valueGet().length-e)),e}},4713:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.determineTestTemplate=u,t.getDecisionTaker=o,t.getMaskTemplate=function(e,t,i,a,n){var r=this,o=this.opts,c=this.maskset,f=o.greedy;n&&o.greedy&&(o.greedy=!1,r.maskset.tests={});t=t||0;var p,h,v,m,g=[],k=0;do{if(!0===e&&c.validPositions[k])v=n&&c.validPositions[k].match.optionality&&void 0===c.validPositions[k+1]&&(!0===c.validPositions[k].generatedInput||c.validPositions[k].input==o.skipOptionalPartCharacter&&k>0)?u.call(r,k,d.call(r,k,p,k-1)):c.validPositions[k],h=v.match,p=v.locator.slice(),g.push(!0===i?v.input:!1===i?h.nativeDef:l.call(r,k,h));else{v=s.call(r,k,p,k-1),h=v.match,p=v.locator.slice();var y=!0!==a&&(!1!==o.jitMasking?o.jitMasking:h.jit);(m=(m&&h.static&&h.def!==o.groupSeparator&&null===h.fn||c.validPositions[k-1]&&h.static&&h.def!==o.groupSeparator&&null===h.fn)&&c.tests[k]&&1===c.tests[k].length)||!1===y||void 0===y||"number"==typeof y&&isFinite(y)&&y>k?g.push(!1===i?h.nativeDef:l.call(r,k,h)):m=!1}k++}while(!0!==h.static||""!==h.def||t>k);""===g[g.length-1]&&g.pop();!1===i&&void 0!==c.maskLength||(c.maskLength=k-1);return o.greedy=f,g},t.getPlaceholder=l,t.getTest=c,t.getTestTemplate=s,t.getTests=d,t.isSubsetOf=f;var a,n=(a=i(2394))&&a.__esModule?a:{default:a};function r(e,t){var i=(null!=e.alternation?e.mloc[o(e)]:e.locator).join("");if(""!==i)for(;i.length<t;)i+="0";return i}function o(e){var t=e.locator[e.alternation];return"string"==typeof t&&t.length>0&&(t=t.split(",")[0]),void 0!==t?t.toString():""}function l(e,t,i){var a=this.opts,n=this.maskset;if(void 0!==(t=t||c.call(this,e).match).placeholder||!0===i)return"function"==typeof t.placeholder?t.placeholder(a):t.placeholder;if(!0===t.static){if(e>-1&&void 0===n.validPositions[e]){var r,o=d.call(this,e),l=[];if(o.length>1+(""===o[o.length-1].match.def?1:0))for(var s=0;s<o.length;s++)if(""!==o[s].match.def&&!0!==o[s].match.optionality&&!0!==o[s].match.optionalQuantifier&&(!0===o[s].match.static||void 0===r||!1!==o[s].match.fn.test(r.match.def,n,e,!0,a))&&(l.push(o[s]),!0===o[s].match.static&&(r=o[s]),l.length>1&&/[0-9a-bA-Z]/.test(l[0].match.def)))return a.placeholder.charAt(e%a.placeholder.length)}return t.def}return a.placeholder.charAt(e%a.placeholder.length)}function s(e,t,i){return this.maskset.validPositions[e]||u.call(this,e,d.call(this,e,t?t.slice():t,i))}function u(e,t){var i=this.opts,a=function(e,t){var i=0,a=!1;t.forEach((function(e){e.match.optionality&&(0!==i&&i!==e.match.optionality&&(a=!0),(0===i||i>e.match.optionality)&&(i=e.match.optionality))})),i&&(0==e||1==t.length?i=0:a||(i=0));return i}(e,t);e=e>0?e-1:0;var n,o,l,s=r(c.call(this,e));i.greedy&&t.length>1&&""===t[t.length-1].match.def&&t.pop();for(var u=0;u<t.length;u++){var f=t[u];n=r(f,s.length);var d=Math.abs(n-s);(void 0===o||""!==n&&d<o||l&&!i.greedy&&l.match.optionality&&l.match.optionality-a>0&&"master"===l.match.newBlockMarker&&(!f.match.optionality||f.match.optionality-a<1||!f.match.newBlockMarker)||l&&!i.greedy&&l.match.optionalQuantifier&&!f.match.optionalQuantifier)&&(o=d,l=f)}return l}function c(e,t){var i=this.maskset;return i.validPositions[e]?i.validPositions[e]:(t||d.call(this,e))[0]}function f(e,t,i){function a(e){for(var t,i=[],a=-1,n=0,r=e.length;n<r;n++)if("-"===e.charAt(n))for(t=e.charCodeAt(n+1);++a<t;)i.push(String.fromCharCode(a));else a=e.charCodeAt(n),i.push(e.charAt(n));return i.join("")}return e.match.def===t.match.nativeDef||!(!(i.regex||e.match.fn instanceof RegExp&&t.match.fn instanceof RegExp)||!0===e.match.static||!0===t.match.static)&&-1!==a(t.match.fn.toString().replace(/[[\]/]/g,"")).indexOf(a(e.match.fn.toString().replace(/[[\]/]/g,"")))}function d(e,t,i){var a,r,o=this,l=this.dependencyLib,s=this.maskset,c=this.opts,d=this.el,p=s.maskToken,h=t?i:0,v=t?t.slice():[0],m=[],g=!1,k=t?t.join(""):"";function y(t,i,r,o){function l(r,o,u){function p(e,t){var i=0===t.matches.indexOf(e);return i||t.matches.every((function(a,n){return!0===a.isQuantifier?i=p(e,t.matches[n-1]):Object.prototype.hasOwnProperty.call(a,"matches")&&(i=p(e,a)),!i})),i}function v(e,t,i){var a,n;if((s.tests[e]||s.validPositions[e])&&(s.tests[e]||[s.validPositions[e]]).every((function(e,r){if(e.mloc[t])return a=e,!1;var o=void 0!==i?i:e.alternation,l=void 0!==e.locator[o]?e.locator[o].toString().indexOf(t):-1;return(void 0===n||l<n)&&-1!==l&&(a=e,n=l),!0})),a){var r=a.locator[a.alternation];return(a.mloc[t]||a.mloc[r]||a.locator).slice((void 0!==i?i:a.alternation)+1)}return void 0!==i?v(e,t):void 0}function b(e,t){var i=e.alternation,a=void 0===t||i===t.alternation&&-1===e.locator[i].toString().indexOf(t.locator[i]);if(!a&&i>t.alternation)for(var n=t.alternation;n<i;n++)if(e.locator[n]!==t.locator[n]){i=n,a=!0;break}if(a){e.mloc=e.mloc||{};var r=e.locator[i];if(void 0!==r){if("string"==typeof r&&(r=r.split(",")[0]),void 0===e.mloc[r]&&(e.mloc[r]=e.locator.slice()),void 0!==t){for(var o in t.mloc)"string"==typeof o&&(o=o.split(",")[0]),void 0===e.mloc[o]&&(e.mloc[o]=t.mloc[o]);e.locator[i]=Object.keys(e.mloc).join(",")}return!0}e.alternation=void 0}return!1}function x(e,t){if(e.locator.length!==t.locator.length)return!1;for(var i=e.alternation+1;i<e.locator.length;i++)if(e.locator[i]!==t.locator[i])return!1;return!0}if(h>e+c._maxTestPos)throw"Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. "+s.mask;if(h===e&&void 0===r.matches){if(m.push({match:r,locator:o.reverse(),cd:k,mloc:{}}),!r.optionality||void 0!==u||!(c.definitions&&c.definitions[r.nativeDef]&&c.definitions[r.nativeDef].optional||n.default.prototype.definitions[r.nativeDef]&&n.default.prototype.definitions[r.nativeDef].optional))return!0;g=!0,h=e}else if(void 0!==r.matches){if(r.isGroup&&u!==r){if(r=l(t.matches[t.matches.indexOf(r)+1],o,u))return!0}else if(r.isOptional){var P=r,E=m.length;if(r=y(r,i,o,u)){if(m.forEach((function(e,t){t>=E&&(e.match.optionality=e.match.optionality?e.match.optionality+1:1)})),a=m[m.length-1].match,void 0!==u||!p(a,P))return!0;g=!0,h=e}}else if(r.isAlternator){var S,_=r,w=[],M=m.slice(),O=o.length,T=!1,C=i.length>0?i.shift():-1;if(-1===C||"string"==typeof C){var A,D=h,j=i.slice(),B=[];if("string"==typeof C)B=C.split(",");else for(A=0;A<_.matches.length;A++)B.push(A.toString());if(void 0!==s.excludes[e]){for(var R=B.slice(),L=0,I=s.excludes[e].length;L<I;L++){var F=s.excludes[e][L].toString().split(":");o.length==F[1]&&B.splice(B.indexOf(F[0]),1)}0===B.length&&(delete s.excludes[e],B=R)}(!0===c.keepStatic||isFinite(parseInt(c.keepStatic))&&D>=c.keepStatic)&&(B=B.slice(0,1));for(var N=0;N<B.length;N++){A=parseInt(B[N]),m=[],i="string"==typeof C&&v(h,A,O)||j.slice();var V=_.matches[A];if(V&&l(V,[A].concat(o),u))r=!0;else if(0===N&&(T=!0),V&&V.matches&&V.matches.length>_.matches[0].matches.length)break;S=m.slice(),h=D,m=[];for(var G=0;G<S.length;G++){var H=S[G],K=!1;H.match.jit=H.match.jit||T,H.alternation=H.alternation||O,b(H);for(var U=0;U<w.length;U++){var $=w[U];if("string"!=typeof C||void 0!==H.alternation&&B.includes(H.locator[H.alternation].toString())){if(H.match.nativeDef===$.match.nativeDef){K=!0,b($,H);break}if(f(H,$,c)){b(H,$)&&(K=!0,w.splice(w.indexOf($),0,H));break}if(f($,H,c)){b($,H);break}if(Z=$,!0===(Q=H).match.static&&!0!==Z.match.static&&Z.match.fn.test(Q.match.def,s,e,!1,c,!1)){x(H,$)||void 0!==d.inputmask.userOptions.keepStatic?b(H,$)&&(K=!0,w.splice(w.indexOf($),0,H)):c.keepStatic=!0;break}}}K||w.push(H)}}m=M.concat(w),h=e,g=m.length>0,r=w.length>0,i=j.slice()}else r=l(_.matches[C]||t.matches[C],[C].concat(o),u);if(r)return!0}else if(r.isQuantifier&&u!==t.matches[t.matches.indexOf(r)-1])for(var q=r,z=i.length>0?i.shift():0;z<(isNaN(q.quantifier.max)?z+1:q.quantifier.max)&&h<=e;z++){var W=t.matches[t.matches.indexOf(q)-1];if(r=l(W,[z].concat(o),W)){if((a=m[m.length-1].match).optionalQuantifier=z>=q.quantifier.min,a.jit=(z+1)*(W.matches.indexOf(a)+1)>q.quantifier.jit,a.optionalQuantifier&&p(a,W)){g=!0,h=e;break}return a.jit&&(s.jitOffset[e]=W.matches.length-W.matches.indexOf(a)),!0}}else if(r=y(r,i,o,u))return!0}else h++;var Q,Z}for(var u=i.length>0?i.shift():0;u<t.matches.length;u++)if(!0!==t.matches[u].isQuantifier){var p=l(t.matches[u],[u].concat(r),o);if(p&&h===e)return p;if(h>e)break}}if(e>-1){if(void 0===t){for(var b,x=e-1;void 0===(b=s.validPositions[x]||s.tests[x])&&x>-1;)x--;void 0!==b&&x>-1&&(v=function(e,t){var i,a=[];return Array.isArray(t)||(t=[t]),t.length>0&&(void 0===t[0].alternation||!0===c.keepStatic?0===(a=u.call(o,e,t.slice()).locator.slice()).length&&(a=t[0].locator.slice()):t.forEach((function(e){""!==e.def&&(0===a.length?(i=e.alternation,a=e.locator.slice()):e.locator[i]&&-1===a[i].toString().indexOf(e.locator[i])&&(a[i]+=","+e.locator[i]))}))),a}(x,b),k=v.join(""),h=x)}if(s.tests[e]&&s.tests[e][0].cd===k)return s.tests[e];for(var P=v.shift();P<p.length;P++){if(y(p[P],v,[P])&&h===e||h>e)break}}return(0===m.length||g)&&m.push({match:{fn:null,static:!0,optionality:!1,casing:null,def:"",placeholder:""},locator:[],mloc:{},cd:k}),void 0!==t&&s.tests[e]?r=l.extend(!0,[],m):(s.tests[e]=l.extend(!0,[],m),r=s.tests[e]),m.forEach((function(e){e.match.optionality=!1})),r}},7215:function(e,t,i){Object.defineProperty(t,"__esModule",{value:!0}),t.alternate=s,t.checkAlternationMatch=function(e,t,i){for(var a,n=this.opts.greedy?t:t.slice(0,1),r=!1,o=void 0!==i?i.split(","):[],l=0;l<o.length;l++)-1!==(a=e.indexOf(o[l]))&&e.splice(a,1);for(var s=0;s<e.length;s++)if(n.includes(e[s])){r=!0;break}return r},t.handleRemove=function(e,t,i,a,l){var u=this,c=this.maskset,f=this.opts;if((f.numericInput||u.isRTL)&&(t===r.default.BACKSPACE?t=r.default.DELETE:t===r.default.DELETE&&(t=r.default.BACKSPACE),u.isRTL)){var d=i.end;i.end=i.begin,i.begin=d}var p,h=o.getLastValidPosition.call(u,void 0,!0);i.end>=o.getBuffer.call(u).length&&h>=i.end&&(i.end=h+1);t===r.default.BACKSPACE?i.end-i.begin<1&&(i.begin=o.seekPrevious.call(u,i.begin)):t===r.default.DELETE&&i.begin===i.end&&(i.end=o.isMask.call(u,i.end,!0,!0)?i.end+1:o.seekNext.call(u,i.end)+1);if(!1!==(p=m.call(u,i))){if(!0!==a&&!1!==f.keepStatic||null!==f.regex&&-1!==n.getTest.call(u,i.begin).match.def.indexOf("|")){var v=s.call(u,!0);if(v){var g=void 0!==v.caret?v.caret:v.pos?o.seekNext.call(u,v.pos.begin?v.pos.begin:v.pos):o.getLastValidPosition.call(u,-1,!0);(t!==r.default.DELETE||i.begin>g)&&i.begin}}!0!==a&&(c.p=t===r.default.DELETE?i.begin+p:i.begin,c.p=o.determineNewCaretPosition.call(u,{begin:c.p,end:c.p},!1,!1===f.insertMode&&t===r.default.BACKSPACE?"none":void 0).begin)}},t.isComplete=c,t.isSelection=f,t.isValid=d,t.refreshFromBuffer=h,t.revalidateMask=m;var a,n=i(4713),r=(a=i(5581))&&a.__esModule?a:{default:a},o=i(8711),l=i(6030);function s(e,t,i,a,r,l){var u,c,f,p,h,v,m,g,k,y,b,x=this,P=this.dependencyLib,E=this.opts,S=x.maskset,_=P.extend(!0,{},S.validPositions),w=P.extend(!0,{},S.tests),M=!1,O=!1,T=void 0!==r?r:o.getLastValidPosition.call(x);if(l&&(y=l.begin,b=l.end,l.begin>l.end&&(y=l.end,b=l.begin)),-1===T&&void 0===r)u=0,c=(p=n.getTest.call(x,u)).alternation;else for(;T>=0;T--)if((f=S.validPositions[T])&&void 0!==f.alternation){if(p&&p.locator[f.alternation]!==f.locator[f.alternation])break;u=T,c=S.validPositions[u].alternation,p=f}if(void 0!==c){m=parseInt(u),S.excludes[m]=S.excludes[m]||[],!0!==e&&S.excludes[m].push((0,n.getDecisionTaker)(p)+":"+p.alternation);var C=[],A=-1;for(h=m;h<o.getLastValidPosition.call(x,void 0,!0)+1;h++)-1===A&&e<=h&&void 0!==t&&(C.push(t),A=C.length-1),(v=S.validPositions[h])&&!0!==v.generatedInput&&(void 0===l||h<y||h>=b)&&C.push(v.input),delete S.validPositions[h];for(-1===A&&void 0!==t&&(C.push(t),A=C.length-1);void 0!==S.excludes[m]&&S.excludes[m].length<10;){for(S.tests={},o.resetMaskSet.call(x,!0),M=!0,h=0;h<C.length&&(g=M.caret||o.getLastValidPosition.call(x,void 0,!0)+1,k=C[h],M=d.call(x,g,k,!1,a,!0));h++)h===A&&(O=M),1==e&&M&&(O={caretPos:h});if(M)break;if(o.resetMaskSet.call(x),p=n.getTest.call(x,m),S.validPositions=P.extend(!0,{},_),S.tests=P.extend(!0,{},w),!S.excludes[m]){O=s.call(x,e,t,i,a,m-1,l);break}var D=(0,n.getDecisionTaker)(p);if(-1!==S.excludes[m].indexOf(D+":"+p.alternation)){O=s.call(x,e,t,i,a,m-1,l);break}for(S.excludes[m].push(D+":"+p.alternation),h=m;h<o.getLastValidPosition.call(x,void 0,!0)+1;h++)delete S.validPositions[h]}}return O&&!1===E.keepStatic||delete S.excludes[m],O}function u(e,t,i){var a=this.opts,n=this.maskset;switch(a.casing||t.casing){case"upper":e=e.toUpperCase();break;case"lower":e=e.toLowerCase();break;case"title":var o=n.validPositions[i-1];e=0===i||o&&o.input===String.fromCharCode(r.default.SPACE)?e.toUpperCase():e.toLowerCase();break;default:if("function"==typeof a.casing){var l=Array.prototype.slice.call(arguments);l.push(n.validPositions),e=a.casing.apply(this,l)}}return e}function c(e){var t=this,i=this.opts,a=this.maskset;if("function"==typeof i.isComplete)return i.isComplete(e,i);if("*"!==i.repeat){var r=!1,l=o.determineLastRequiredPosition.call(t,!0),s=o.seekPrevious.call(t,l.l);if(void 0===l.def||l.def.newBlockMarker||l.def.optionality||l.def.optionalQuantifier){r=!0;for(var u=0;u<=s;u++){var c=n.getTestTemplate.call(t,u).match;if(!0!==c.static&&void 0===a.validPositions[u]&&!0!==c.optionality&&!0!==c.optionalQuantifier||!0===c.static&&e[u]!==n.getPlaceholder.call(t,u,c)){r=!1;break}}}return r}}function f(e){var t=this.opts.insertMode?0:1;return this.isRTL?e.begin-e.end>t:e.end-e.begin>t}function d(e,t,i,a,r,l,p){var g=this,k=this.dependencyLib,y=this.opts,b=g.maskset;i=!0===i;var x=e;function P(e){if(void 0!==e){if(void 0!==e.remove&&(Array.isArray(e.remove)||(e.remove=[e.remove]),e.remove.sort((function(e,t){return t.pos-e.pos})).forEach((function(e){m.call(g,{begin:e,end:e+1})})),e.remove=void 0),void 0!==e.insert&&(Array.isArray(e.insert)||(e.insert=[e.insert]),e.insert.sort((function(e,t){return e.pos-t.pos})).forEach((function(e){""!==e.c&&d.call(g,e.pos,e.c,void 0===e.strict||e.strict,void 0!==e.fromIsValid?e.fromIsValid:a)})),e.insert=void 0),e.refreshFromBuffer&&e.buffer){var t=e.refreshFromBuffer;h.call(g,!0===t?t:t.start,t.end,e.buffer),e.refreshFromBuffer=void 0}void 0!==e.rewritePosition&&(x=e.rewritePosition,e=!0)}return e}function E(t,i,r){var l=!1;return n.getTests.call(g,t).every((function(s,c){var d=s.match;if(o.getBuffer.call(g,!0),!1!==(l=(!d.jit||void 0!==b.validPositions[o.seekPrevious.call(g,t)])&&(null!=d.fn?d.fn.test(i,b,t,r,y,f.call(g,e)):(i===d.def||i===y.skipOptionalPartCharacter)&&""!==d.def&&{c:n.getPlaceholder.call(g,t,d,!0)||d.def,pos:t}))){var p=void 0!==l.c?l.c:i,h=t;return p=p===y.skipOptionalPartCharacter&&!0===d.static?n.getPlaceholder.call(g,t,d,!0)||d.def:p,!0!==(l=P(l))&&void 0!==l.pos&&l.pos!==t&&(h=l.pos),!0!==l&&void 0===l.pos&&void 0===l.c?!1:(!1===m.call(g,e,k.extend({},s,{input:u.call(g,p,d,h)}),a,h)&&(l=!1),!1)}return!0})),l}void 0!==e.begin&&(x=g.isRTL?e.end:e.begin);var S=!0,_=k.extend(!0,{},b.validPositions);if(!1===y.keepStatic&&void 0!==b.excludes[x]&&!0!==r&&!0!==a)for(var w=x;w<(g.isRTL?e.begin:e.end);w++)void 0!==b.excludes[w]&&(b.excludes[w]=void 0,delete b.tests[w]);if("function"==typeof y.preValidation&&!0!==a&&!0!==l&&(S=P(S=y.preValidation.call(g,o.getBuffer.call(g),x,t,f.call(g,e),y,b,e,i||r))),!0===S){if(S=E(x,t,i),(!i||!0===a)&&!1===S&&!0!==l){var M=b.validPositions[x];if(!M||!0!==M.match.static||M.match.def!==t&&t!==y.skipOptionalPartCharacter){if(y.insertMode||void 0===b.validPositions[o.seekNext.call(g,x)]||e.end>x){var O=!1;if(b.jitOffset[x]&&void 0===b.validPositions[o.seekNext.call(g,x)]&&!1!==(S=d.call(g,x+b.jitOffset[x],t,!0,!0))&&(!0!==r&&(S.caret=x),O=!0),e.end>x&&(b.validPositions[x]=void 0),!O&&!o.isMask.call(g,x,y.keepStatic&&0===x))for(var T=x+1,C=o.seekNext.call(g,x,!1,0!==x);T<=C;T++)if(!1!==(S=E(T,t,i))){S=v.call(g,x,void 0!==S.pos?S.pos:T)||S,x=T;break}}}else S={caret:o.seekNext.call(g,x)}}!1!==S||!y.keepStatic||!c.call(g,o.getBuffer.call(g))&&0!==x||i||!0===r?f.call(g,e)&&b.tests[x]&&b.tests[x].length>1&&y.keepStatic&&!i&&!0!==r&&(S=s.call(g,!0)):S=s.call(g,x,t,i,a,void 0,e),!0===S&&(S={pos:x})}if("function"==typeof y.postValidation&&!0!==a&&!0!==l){var A=y.postValidation.call(g,o.getBuffer.call(g,!0),void 0!==e.begin?g.isRTL?e.end:e.begin:e,t,S,y,b,i,p);void 0!==A&&(S=!0===A?S:A)}S&&void 0===S.pos&&(S.pos=x),!1===S||!0===l?(o.resetMaskSet.call(g,!0),b.validPositions=k.extend(!0,{},_)):v.call(g,void 0,x,!0);var D=P(S);void 0!==g.maxLength&&(o.getBuffer.call(g).length>g.maxLength&&!a&&(o.resetMaskSet.call(g,!0),b.validPositions=k.extend(!0,{},_),D=!1));return D}function p(e,t,i){for(var a=this.maskset,r=!1,o=n.getTests.call(this,e),l=0;l<o.length;l++){if(o[l].match&&(o[l].match.nativeDef===t.match[i.shiftPositions?"def":"nativeDef"]&&(!i.shiftPositions||!t.match.static)||o[l].match.nativeDef===t.match.nativeDef||i.regex&&!o[l].match.static&&o[l].match.fn.test(t.input))){r=!0;break}if(o[l].match&&o[l].match.def===t.match.nativeDef){r=void 0;break}}return!1===r&&void 0!==a.jitOffset[e]&&(r=p.call(this,e+a.jitOffset[e],t,i)),r}function h(e,t,i){var a,n,r=this,s=this.maskset,u=this.opts,c=this.dependencyLib,f=u.skipOptionalPartCharacter,d=r.isRTL?i.slice().reverse():i;if(u.skipOptionalPartCharacter="",!0===e)o.resetMaskSet.call(r),s.tests={},e=0,t=i.length,n=o.determineNewCaretPosition.call(r,{begin:0,end:0},!1).begin;else{for(a=e;a<t;a++)delete s.validPositions[a];n=e}var p=new c.Event("keypress");for(a=e;a<t;a++){p.keyCode=d[a].toString().charCodeAt(0),r.ignorable=!1;var h=l.EventHandlers.keypressEvent.call(r,p,!0,!1,!1,n);!1!==h&&void 0!==h&&(n=h.forwardPosition)}u.skipOptionalPartCharacter=f}function v(e,t,i){var a=this,r=this.maskset,l=this.dependencyLib;if(void 0===e)for(e=t-1;e>0&&!r.validPositions[e];e--);for(var s=e;s<t;s++){if(void 0===r.validPositions[s]&&!o.isMask.call(a,s,!1))if(0==s?n.getTest.call(a,s):r.validPositions[s-1]){var u=n.getTests.call(a,s).slice();""===u[u.length-1].match.def&&u.pop();var c,f=n.determineTestTemplate.call(a,s,u);if(f&&(!0!==f.match.jit||"master"===f.match.newBlockMarker&&(c=r.validPositions[s+1])&&!0===c.match.optionalQuantifier)&&((f=l.extend({},f,{input:n.getPlaceholder.call(a,s,f.match,!0)||f.match.def})).generatedInput=!0,m.call(a,s,f,!0),!0!==i)){var p=r.validPositions[t].input;return r.validPositions[t]=void 0,d.call(a,t,p,!0,!0)}}}}function m(e,t,i,a){var r=this,l=this.maskset,s=this.opts,u=this.dependencyLib;function c(e,t,i){var a=t[e];if(void 0!==a&&!0===a.match.static&&!0!==a.match.optionality&&(void 0===t[0]||void 0===t[0].alternation)){var n=i.begin<=e-1?t[e-1]&&!0===t[e-1].match.static&&t[e-1]:t[e-1],r=i.end>e+1?t[e+1]&&!0===t[e+1].match.static&&t[e+1]:t[e+1];return n&&r}return!1}var f=0,h=void 0!==e.begin?e.begin:e,v=void 0!==e.end?e.end:e,m=!0;if(e.begin>e.end&&(h=e.end,v=e.begin),a=void 0!==a?a:h,h!==v||s.insertMode&&void 0!==l.validPositions[a]&&void 0===i||void 0===t||t.match.optionalQuantifier||t.match.optionality){var g,k=u.extend(!0,{},l.validPositions),y=o.getLastValidPosition.call(r,void 0,!0);for(l.p=h,g=y;g>=h;g--)delete l.validPositions[g],void 0===t&&delete l.tests[g+1];var b,x,P=a,E=P;for(t&&(l.validPositions[a]=u.extend(!0,{},t),E++,P++),g=t?v:v-1;g<=y;g++){if(void 0!==(b=k[g])&&!0!==b.generatedInput&&(g>=v||g>=h&&c(g,k,{begin:h,end:v}))){for(;""!==n.getTest.call(r,E).match.def;){if(!1!==(x=p.call(r,E,b,s))||"+"===b.match.def){"+"===b.match.def&&o.getBuffer.call(r,!0);var S=d.call(r,E,b.input,"+"!==b.match.def,!0);if(m=!1!==S,P=(S.pos||E)+1,!m&&x)break}else m=!1;if(m){void 0===t&&b.match.static&&g===e.begin&&f++;break}if(!m&&o.getBuffer.call(r),E>l.maskLength)break;E++}""==n.getTest.call(r,E).match.def&&(m=!1),E=P}if(!m)break}if(!m)return l.validPositions=u.extend(!0,{},k),o.resetMaskSet.call(r,!0),!1}else t&&n.getTest.call(r,a).match.cd===t.match.cd&&(l.validPositions[a]=u.extend(!0,{},t));return o.resetMaskSet.call(r,!0),f}},5581:function(e){e.exports=JSON.parse('{"BACKSPACE":8,"BACKSPACE_SAFARI":127,"DELETE":46,"DOWN":40,"END":35,"ENTER":13,"ESCAPE":27,"HOME":36,"INSERT":45,"LEFT":37,"PAGE_DOWN":34,"PAGE_UP":33,"RIGHT":39,"SPACE":32,"TAB":9,"UP":38,"X":88,"Z":90,"CONTROL":17,"PAUSE/BREAK":19,"WINDOWS_LEFT":91,"WINDOWS_RIGHT":92,"KEY_229":229}')}},t={};function i(a){var n=t[a];if(void 0!==n)return n.exports;var r=t[a]={exports:{}};return e[a](r,r.exports,i),r.exports}var a={};return function(){var e,t=a;Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,i(3851),i(219),i(207),i(5296);var n=((e=i(2394))&&e.__esModule?e:{default:e}).default;t.default=n}(),a}()}));
|
294coder/Efficient-MIF
| 2,177 |
utils/sharpening_index/MTF_pan.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
MTF filters the image I_MS using a Gaussin filter matched with the Modulation Transfer Function (MTF) of the MultiSpectral (MS) sensor.
Interface:
I_Filtered = MTF(I_MS,sensor,ratio)
Inputs:
I_MS: MS image;
sensor: String for type of sensor (e.g. 'WV2', 'IKONOS');
ratio: Scale ratio between MS and PAN.
Outputs:
I_Filtered: Output filtered MS image.
Notes:
The bottleneck of this function is the function scipy.filters.correlate that gets the same results as in the MATLAB toolbox
but it is very slow with respect to fftconvolve that instead gets slightly different results
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
from scipy import ndimage
import numpy as np
from .genMTF_pan import genMTF_pan
def MTF_pan(I_MS, sensor, ratio):
h = genMTF_pan(ratio, sensor, I_MS.shape[2])
I_MS_LP = np.zeros((I_MS.shape))
for ii in range(I_MS.shape[2]):
I_MS_LP[:, :, ii] = ndimage.filters.correlate(I_MS[:, :, ii], h, mode='nearest')
### This can speed-up the processing, but with slightly different results with respect to the MATLAB toolbox
# hb = h[:,:,ii]
# I_MS_LP[:,:,ii] = signal.fftconvolve(I_MS[:,:,ii],hb[::-1],mode='same')
return np.double(I_MS_LP)
|
281677160/openwrt-package
| 8,920 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_toolkit_misc.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_toolkit_misc.h"
#include <ngx_md5.h>
typedef struct {
ngx_str_t scheme;
in_port_t port;
} ngx_scheme_port_t;
ngx_scheme_port_t ngx_sheme_port[] = {
{ ngx_string("http"), 80 },
{ ngx_string("https"), 443 },
{ ngx_string("rtmp"), 1935 },
{ ngx_null_string, 0 }
};
#define FILEBUFSIZE 8192
socklen_t
ngx_sock_pton_unix(struct sockaddr *sa, u_char *text, size_t len)
{
#if NGX_HAVE_UNIX_DOMAIN
u_char *path;
struct sockaddr_un *saun;
// skip 'unix:'
path = text + 5;
len -= 5;
if (len == 0) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"no path in the unix domain");
return 0;
}
++len; // sun_path need '\0' as end
if (len > sizeof(saun->sun_path)) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"too long path in the unix domain socket");
return 0;
}
saun = (struct sockaddr_un *) sa;
saun->sun_family = AF_UNIX;
(void) ngx_cpystrn((u_char *) saun->sun_path, path, len);
return sizeof(struct sockaddr_un);
#else
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"the unix domain sockets are not supported on this platform");
return 0;
#endif
}
socklen_t
ngx_sock_pton_inet6(struct sockaddr *sa, u_char *text, size_t len)
{
#if NGX_HAVE_INET6
struct in6_addr inaddr6;
struct sockaddr_in6 *sin6;
u_char *p, *last;
ngx_int_t port;
size_t alen, plen;
last = text + len;
p = ngx_strlchr(text, last, ']');
if (p == NULL || p == last - 1) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"not a ipv6 address format");
return 0;
}
++text;
alen = p - text;
/*
* prevent MSVC8 warning:
* potentially uninitialized local variable 'inaddr6' used
*/
ngx_memzero(&inaddr6, sizeof(struct in6_addr));
if (ngx_inet6_addr(text, alen, inaddr6.s6_addr) != NGX_OK) {
// not ipv6 address
return 0;
}
sa->sa_family = AF_INET6;
sin6 = (struct sockaddr_in6 *) sa;
ngx_memcpy(sin6->sin6_addr.s6_addr, inaddr6.s6_addr, 16);
++p;
if (*p == ':') { // has port
++p;
plen = last - p;
port = ngx_atoi(p, plen);
if (port < 0 || port > 65535) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"invalid port: %i", port);
return 0;
}
ngx_inet_set_port(sa, (in_port_t) port);
}
return sizeof(struct sockaddr_in6);
#else
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"the INET6 sockets are not supported on this platform");
return 0;
#endif
}
socklen_t
ngx_sock_pton_inet(struct sockaddr *sa, u_char *text, size_t len)
{
in_addr_t inaddr;
struct sockaddr_in *sin;
u_char *p, *last;
ngx_int_t port;
size_t alen, plen;
last = text + len;
p = ngx_strlchr(text, last, ':');
alen = len;
if (p != NULL) { // have port
alen = p - text;
}
inaddr = ngx_inet_addr(text, alen);
if (inaddr == INADDR_NONE) {
// not ipv4 address
return 0;
}
sa->sa_family = AF_INET;
sin = (struct sockaddr_in *) sa;
sin->sin_addr.s_addr = inaddr;
if (p != NULL) { // has port
++p;
plen = last - p;
port = ngx_atoi(p, plen);
if (port < 0 || port > 65535) {
ngx_log_error(NGX_LOG_INFO, ngx_cycle->log, 0,
"invalid port: %i", port);
return 0;
}
ngx_inet_set_port(sa, (in_port_t) port);
}
return sizeof(struct sockaddr_in);
}
ngx_int_t
ngx_parse_request_url(ngx_request_url_t *request_url, ngx_str_t *url)
{
u_char *last, *host_last;
u_char *scheme;
u_char *user, *host, *port;
u_char *path, *args, *fragment;
/* NULL url */
if (url->len == 0) {
return NGX_ERROR;
}
last = url->data + url->len;
scheme = url->data;
user = (u_char *) ngx_strnstr(scheme, "://", last - scheme);
if (user == NULL) {
return NGX_ERROR;
}
request_url->scheme.data = scheme;
request_url->scheme.len = user - scheme;
user += 3;
if (user >= last) {
return NGX_ERROR;
}
host_last = ngx_strlchr(user, last, '/');
if (host_last == NULL) {
host_last = last;
}
host = ngx_strlchr(user, host_last, '@');
if (host == NULL) { /* no user */
host = user;
} else {
if (user == host) { /* user is "" */
return NGX_ERROR;
}
request_url->user.data = user;
request_url->user.len = host - user;
++host;
if (host == host_last) { /* no host */
return NGX_ERROR;
}
}
port = ngx_strlchr(host, host_last, ':');
if (port == NULL) { /* no port */
request_url->host.data = host;
request_url->host.len = host_last - host;
request_url->host_with_port = request_url->host;
} else {
request_url->host.data = host;
request_url->host.len = port - host;
++port;
if (port == host_last) { /* port error */
return NGX_ERROR;
}
request_url->port.data = port;
request_url->port.len = host_last - port;
request_url->host_with_port.data = host;
request_url->host_with_port.len = host_last - host;
}
path = ++host_last;
if (path >= last) { /* no path */
goto done;
}
args = ngx_strlchr(path, last, '?');
if (args == NULL) { /* no args */
request_url->path.data = path;
request_url->path.len = last - path;
request_url->uri_with_args = request_url->path;
goto done;
} else {
request_url->path.data = path;
request_url->path.len = args - path;
++args;
if (args == last) { /* args error */
return NGX_ERROR;
}
}
fragment = ngx_strlchr(args, last, '#');
if (fragment == NULL) { /* no fragment */
request_url->args.data = args;
request_url->args.len = last - args;
} else {
request_url->args.data = args;
request_url->args.len = fragment - args;
++fragment;
if (fragment == last) { /* fragment error */
return NGX_ERROR;
}
request_url->fragment.data = fragment;
request_url->fragment.len = last - fragment;
}
request_url->uri_with_args.data = path;
request_url->uri_with_args.len = last - path;
done:
return NGX_OK;
}
in_port_t
ngx_request_port(ngx_str_t *scheme, ngx_str_t *port)
{
ngx_int_t p;
ngx_scheme_port_t *sp;
if (port->len) {
p = ngx_atoi(port->data, port->len);
if (p < 1 || p > 65535) { /* invalid port */
return 0;
}
return p;
}
for (sp = ngx_sheme_port; sp->port != 0; ++sp) {
if (sp->scheme.len == scheme->len
&& ngx_memcmp(sp->scheme.data, scheme->data, scheme->len) == 0)
{
return sp->port;
}
}
return 0;
}
ngx_int_t
ngx_md5_file(ngx_fd_t fd, u_char md5key[NGX_MD5KEY_LEN])
{
ngx_md5_t ctx;
u_char buf[FILEBUFSIZE];
u_char md5[16];
ssize_t n;
ngx_uint_t i;
u_char *p;
ngx_md5_init(&ctx);
for (;;) {
n = ngx_read_fd(fd, buf, FILEBUFSIZE);
if (n == 0) { /* read eof of file */
break;
}
if (n == NGX_FILE_ERROR) {
return NGX_ERROR;
}
ngx_md5_update(&ctx, buf, n);
}
ngx_md5_final(md5, &ctx);
p = md5key;
for (i = 0; i < 16; ++i) {
p = ngx_sprintf(p, "%02xi", md5[i]);
}
return NGX_OK;
}
ngx_int_t
ngx_copy_str(ngx_pool_t *pool, ngx_str_t *dst, ngx_str_t *src)
{
if (src->len == 0) {
return NGX_OK;
}
dst->len = src->len;
dst->data = ngx_palloc(pool, src->len);
if (dst->data == NULL) {
return NGX_ERROR;
}
ngx_memcpy(dst->data, src->data, src->len);
return NGX_OK;
}
socklen_t
ngx_sock_pton(struct sockaddr *sa, u_char *text, size_t len)
{
if (len >= 5 && ngx_strncasecmp(text, (u_char *) "unix:", 5) == 0) {
return ngx_sock_pton_unix(sa, text, len);
}
if (len && text[0] == '[') {
return ngx_sock_pton_inet6(sa, text, len);
}
return ngx_sock_pton_inet(sa, text, len);
}
|
294coder/Efficient-MIF
| 2,768 |
utils/sharpening_index/HQNR.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
Hybrid Quality with No Reference (HQNR) index.
Interface:
[HQNR_index,D_lambda,D_S] = HQNR(ps_ms,ms,msexp,pan,S,sensor,ratio)
Inputs:
ps_ms: Pansharpened image;
ms: Original MS image;
msexp: MS image resampled to panchromatic scale;
pan: Panchromatic image;
S: Block size;
sensor: String for type of sensor (e.g. 'WV2','IKONOS');
ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
Outputs:
HQNR_index: HQNR index;
D_lambda: Spectral distortion index;
D_S: Spatial distortion index.
Notes:
Results very close to the MATLAB toolbox's ones. In particular, the results of D_S are more accurate than the MATLAB toolbox's ones
because the Q-index is applied in a sliding window way. Instead, for computational reasons, the MATLAB toolbox uses a distinct block implementation
of the Q-index.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
import numpy as np
from .D_lambda_K import D_lambda_K
# from .D_s import D_s
from .my_D_s import D_s
def HQNR(ps_ms, ms, msexp, pan, S, sensor, ratio):
"""HQNR index and maps
Args:
ps_ms (ndarray): fusion
ms (ndarray): MS_LR
msexp (ndarray): MS
pan (ndarray): pan
S (int): block size
sensor (str): sensor type
ratio (int): fusion ratio
Returns:
[float, float, float, ndarray, ndarray, ndarray]: indices and maps
"""
D_lambda, D_l_map = D_lambda_K(ps_ms, msexp, ratio, sensor, S) # .copy()
D_S, D_S_map = D_s(ps_ms, msexp, ms, pan, ratio, S, 1)
HQNR_index = (1 - D_lambda) * (1 - D_S)
HQNR_map = (1 - D_l_map) * (1 - D_S_map.mean(-1))
return HQNR_index, D_lambda, D_S, HQNR_map
|
281677160/openwrt-package
| 3,312 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_toolkit_misc.h
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#ifndef _NGX_TOOLKIT_MISC_H_INCLUDED_
#define _NGX_TOOLKIT_MISC_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
/*
* scheme://[user@]host[:port]/path[?args][#fragment]
*/
typedef struct {
ngx_str_t scheme;
ngx_str_t user;
ngx_str_t host;
ngx_str_t port;
ngx_str_t path;
ngx_str_t args;
ngx_str_t fragment;
ngx_str_t host_with_port; /* host[:port] */
ngx_str_t uri_with_args; /* /path[?args][#fragment] */
} ngx_request_url_t;
#define NGX_MD5KEY_LEN 32
/*
* parse request url format as:
* scheme://[user@]host[:port]/path[?args][#fragment]
*
* return value:
* NGX_OK : parse success
* NGX_ERROR: request url format error
* paras:
* request_url: url parse result return to user,
* all paras in request url is segment point to url
* url : request url for parse
*/
ngx_int_t ngx_parse_request_url(ngx_request_url_t *request_url, ngx_str_t *url);
/*
* convert port to in_port_t according to scheme and port
*
* return value:
* If port is set to correct number range in [1, 65535], return port
* If port is set to non correct value, return 0
* If port is not set, return default value for scheme:
* 80 for http
* 443 for https
* 1935 for rtmp
* 0 for others now
* values:
* scheme : sheme string like http https or rtmp
* port : port for convert to in_port_t
*/
in_port_t ngx_request_port(ngx_str_t *scheme, ngx_str_t *port);
/*
* calculating file md5key as md5sum in shell
*
* return value:
* NGX_OK : calculating success
* NGX_ERROR: calculating error such as file is not exist
* paras:
* fd : file desc for calculating md5key
* md5key: md5key result
*/
ngx_int_t ngx_md5_file(ngx_fd_t fd, u_char md5key[NGX_MD5KEY_LEN]);
/*
* copy str
*
* return value:
* NGX_OK: copy successd
* NGX_ERROR: copy failed
* paras:
* pool: for alloc space for storing str
* dst: str copy to
* src: str copy from
*/
ngx_int_t ngx_copy_str(ngx_pool_t *pool, ngx_str_t *dst, ngx_str_t *src);
/*
* parse text to struct sockaddr
*
* return value:
* 0: if text is not ipv4/ipv6/unix address
* >0: socklen for sa
*
* paras:
* sa: struct sockadd parse to
* text: ipv4/ipv6/unix address for parsing, text could have port
* len: text's length
*/
socklen_t ngx_sock_pton(struct sockaddr *sa, u_char *text, size_t len);
#ifdef NGX_DEBUG
#define NGX_START_TIMING \
struct timeval __start, __end; \
ngx_gettimeofday(&__start);
#define NGX_STOP_TIMING(log, msg) \
ngx_gettimeofday(&__end); \
ngx_log_error(NGX_LOG_INFO, log, 0, msg " spend %ui us", \
(__end.tv_sec - __start.tv_sec) * 1000000 \
+ (__end.tv_usec - __start.tv_usec));
#else
#define NGX_START_TIMING
#define NGX_STOP_TIMING(log, msg)
#endif
#endif
|
2881099/FreeSql.AdminLTE
| 38,829 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/bootstrap-slider/bootstrap-slider.min.js
|
/*! =======================================================
VERSION 11.0.2
========================================================= */
"use strict";var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},windowIsDefined="object"===("undefined"==typeof window?"undefined":_typeof(window));!function(a){if("function"==typeof define&&define.amd)define(["jquery"],a);else if("object"===("undefined"==typeof module?"undefined":_typeof(module))&&module.exports){var b;try{b=require("jquery")}catch(c){b=null}module.exports=a(b)}else window&&(window.Slider=a(window.jQuery))}(function(a){var b="slider",c="bootstrapSlider";windowIsDefined&&!window.console&&(window.console={}),windowIsDefined&&!window.console.log&&(window.console.log=function(){}),windowIsDefined&&!window.console.warn&&(window.console.warn=function(){});var d;return function(a){function b(){}function c(a){function c(b){b.prototype.option||(b.prototype.option=function(b){a.isPlainObject(b)&&(this.options=a.extend(!0,this.options,b))})}function e(b,c){a.fn[b]=function(e){if("string"==typeof e){for(var g=d.call(arguments,1),h=0,i=this.length;i>h;h++){var j=this[h],k=a.data(j,b);if(k)if(a.isFunction(k[e])&&"_"!==e.charAt(0)){var l=k[e].apply(k,g);if(void 0!==l&&l!==k)return l}else f("no such method '"+e+"' for "+b+" instance");else f("cannot call methods on "+b+" prior to initialization; attempted to call '"+e+"'")}return this}var m=this.map(function(){var d=a.data(this,b);return d?(d.option(e),d._init()):(d=new c(this,e),a.data(this,b,d)),a(this)});return 1===m.length?m[0]:m}}if(a){var f="undefined"==typeof console?b:function(a){console.error(a)};return a.bridget=function(a,b){c(b),e(a,b)},a.bridget}}var d=Array.prototype.slice;c(a)}(a),function(a){function e(b,c){function d(a,b){var c="data-slider-"+b.replace(/_/g,"-"),d=a.getAttribute(c);try{return JSON.parse(d)}catch(e){return d}}this._state={value:null,enabled:null,offset:null,size:null,percentage:null,inDrag:!1,over:!1,tickIndex:null},this.ticksCallbackMap={},this.handleCallbackMap={},"string"==typeof b?this.element=document.querySelector(b):b instanceof HTMLElement&&(this.element=b),c=c?c:{};for(var e=Object.keys(this.defaultOptions),f=c.hasOwnProperty("min"),g=c.hasOwnProperty("max"),i=0;i<e.length;i++){var j=e[i],k=c[j];k="undefined"!=typeof k?k:d(this.element,j),k=null!==k?k:this.defaultOptions[j],this.options||(this.options={}),this.options[j]=k}if(this.ticksAreValid=Array.isArray(this.options.ticks)&&this.options.ticks.length>0,this.ticksAreValid||(this.options.lock_to_ticks=!1),"auto"===this.options.rtl){var l=window.getComputedStyle(this.element);null!=l?this.options.rtl="rtl"===l.direction:this.options.rtl="rtl"===this.element.style.direction}"vertical"!==this.options.orientation||"top"!==this.options.tooltip_position&&"bottom"!==this.options.tooltip_position?"horizontal"!==this.options.orientation||"left"!==this.options.tooltip_position&&"right"!==this.options.tooltip_position||(this.options.tooltip_position="top"):this.options.rtl?this.options.tooltip_position="left":this.options.tooltip_position="right";var m,n,o,p,q,r=this.element.style.width,s=!1,t=this.element.parentNode;if(this.sliderElem)s=!0;else{this.sliderElem=document.createElement("div"),this.sliderElem.className="slider";var u=document.createElement("div");u.className="slider-track",n=document.createElement("div"),n.className="slider-track-low",m=document.createElement("div"),m.className="slider-selection",o=document.createElement("div"),o.className="slider-track-high",p=document.createElement("div"),p.className="slider-handle min-slider-handle",p.setAttribute("role","slider"),p.setAttribute("aria-valuemin",this.options.min),p.setAttribute("aria-valuemax",this.options.max),q=document.createElement("div"),q.className="slider-handle max-slider-handle",q.setAttribute("role","slider"),q.setAttribute("aria-valuemin",this.options.min),q.setAttribute("aria-valuemax",this.options.max),u.appendChild(n),u.appendChild(m),u.appendChild(o),this.rangeHighlightElements=[];var v=this.options.rangeHighlights;if(Array.isArray(v)&&v.length>0)for(var w=0;w<v.length;w++){var x=document.createElement("div"),y=v[w]["class"]||"";x.className="slider-rangeHighlight slider-selection "+y,this.rangeHighlightElements.push(x),u.appendChild(x)}var z=Array.isArray(this.options.labelledby);if(z&&this.options.labelledby[0]&&p.setAttribute("aria-labelledby",this.options.labelledby[0]),z&&this.options.labelledby[1]&&q.setAttribute("aria-labelledby",this.options.labelledby[1]),!z&&this.options.labelledby&&(p.setAttribute("aria-labelledby",this.options.labelledby),q.setAttribute("aria-labelledby",this.options.labelledby)),this.ticks=[],Array.isArray(this.options.ticks)&&this.options.ticks.length>0){for(this.ticksContainer=document.createElement("div"),this.ticksContainer.className="slider-tick-container",i=0;i<this.options.ticks.length;i++){var A=document.createElement("div");if(A.className="slider-tick",this.options.ticks_tooltip){var B=this._addTickListener(),C=B.addMouseEnter(this,A,i),D=B.addMouseLeave(this,A);this.ticksCallbackMap[i]={mouseEnter:C,mouseLeave:D}}this.ticks.push(A),this.ticksContainer.appendChild(A)}m.className+=" tick-slider-selection"}if(this.tickLabels=[],Array.isArray(this.options.ticks_labels)&&this.options.ticks_labels.length>0)for(this.tickLabelContainer=document.createElement("div"),this.tickLabelContainer.className="slider-tick-label-container",i=0;i<this.options.ticks_labels.length;i++){var E=document.createElement("div"),F=0===this.options.ticks_positions.length,G=this.options.reversed&&F?this.options.ticks_labels.length-(i+1):i;E.className="slider-tick-label",E.innerHTML=this.options.ticks_labels[G],this.tickLabels.push(E),this.tickLabelContainer.appendChild(E)}var H=function(a){var b=document.createElement("div");b.className="arrow";var c=document.createElement("div");c.className="tooltip-inner",a.appendChild(b),a.appendChild(c)},I=document.createElement("div");I.className="tooltip tooltip-main",I.setAttribute("role","presentation"),H(I);var J=document.createElement("div");J.className="tooltip tooltip-min",J.setAttribute("role","presentation"),H(J);var K=document.createElement("div");K.className="tooltip tooltip-max",K.setAttribute("role","presentation"),H(K),this.sliderElem.appendChild(u),this.sliderElem.appendChild(I),this.sliderElem.appendChild(J),this.sliderElem.appendChild(K),this.tickLabelContainer&&this.sliderElem.appendChild(this.tickLabelContainer),this.ticksContainer&&this.sliderElem.appendChild(this.ticksContainer),this.sliderElem.appendChild(p),this.sliderElem.appendChild(q),t.insertBefore(this.sliderElem,this.element),this.element.style.display="none"}if(a&&(this.$element=a(this.element),this.$sliderElem=a(this.sliderElem)),this.eventToCallbackMap={},this.sliderElem.id=this.options.id,this.touchCapable="ontouchstart"in window||window.DocumentTouch&&document instanceof window.DocumentTouch,this.touchX=0,this.touchY=0,this.tooltip=this.sliderElem.querySelector(".tooltip-main"),this.tooltipInner=this.tooltip.querySelector(".tooltip-inner"),this.tooltip_min=this.sliderElem.querySelector(".tooltip-min"),this.tooltipInner_min=this.tooltip_min.querySelector(".tooltip-inner"),this.tooltip_max=this.sliderElem.querySelector(".tooltip-max"),this.tooltipInner_max=this.tooltip_max.querySelector(".tooltip-inner"),h[this.options.scale]&&(this.options.scale=h[this.options.scale]),s===!0&&(this._removeClass(this.sliderElem,"slider-horizontal"),this._removeClass(this.sliderElem,"slider-vertical"),this._removeClass(this.sliderElem,"slider-rtl"),this._removeClass(this.tooltip,"hide"),this._removeClass(this.tooltip_min,"hide"),this._removeClass(this.tooltip_max,"hide"),["left","right","top","width","height"].forEach(function(a){this._removeProperty(this.trackLow,a),this._removeProperty(this.trackSelection,a),this._removeProperty(this.trackHigh,a)},this),[this.handle1,this.handle2].forEach(function(a){this._removeProperty(a,"left"),this._removeProperty(a,"right"),this._removeProperty(a,"top")},this),[this.tooltip,this.tooltip_min,this.tooltip_max].forEach(function(a){this._removeProperty(a,"bs-tooltip-left"),this._removeProperty(a,"bs-tooltip-right"),this._removeProperty(a,"bs-tooltip-top"),this._removeClass(a,"bs-tooltip-right"),this._removeClass(a,"bs-tooltip-left"),this._removeClass(a,"bs-tooltip-top")},this)),"vertical"===this.options.orientation?(this._addClass(this.sliderElem,"slider-vertical"),this.stylePos="top",this.mousePos="pageY",this.sizePos="offsetHeight"):(this._addClass(this.sliderElem,"slider-horizontal"),this.sliderElem.style.width=r,this.options.orientation="horizontal",this.options.rtl?this.stylePos="right":this.stylePos="left",this.mousePos="clientX",this.sizePos="offsetWidth"),this.options.rtl&&this._addClass(this.sliderElem,"slider-rtl"),this._setTooltipPosition(),Array.isArray(this.options.ticks)&&this.options.ticks.length>0&&(g||(this.options.max=Math.max.apply(Math,this.options.ticks)),f||(this.options.min=Math.min.apply(Math,this.options.ticks))),Array.isArray(this.options.value)?(this.options.range=!0,this._state.value=this.options.value):this.options.range?this._state.value=[this.options.value,this.options.max]:this._state.value=this.options.value,this.trackLow=n||this.trackLow,this.trackSelection=m||this.trackSelection,this.trackHigh=o||this.trackHigh,"none"===this.options.selection?(this._addClass(this.trackLow,"hide"),this._addClass(this.trackSelection,"hide"),this._addClass(this.trackHigh,"hide")):("after"===this.options.selection||"before"===this.options.selection)&&(this._removeClass(this.trackLow,"hide"),this._removeClass(this.trackSelection,"hide"),this._removeClass(this.trackHigh,"hide")),this.handle1=p||this.handle1,this.handle2=q||this.handle2,s===!0)for(this._removeClass(this.handle1,"round triangle"),this._removeClass(this.handle2,"round triangle hide"),i=0;i<this.ticks.length;i++)this._removeClass(this.ticks[i],"round triangle hide");var L=["round","triangle","custom"],M=-1!==L.indexOf(this.options.handle);if(M)for(this._addClass(this.handle1,this.options.handle),this._addClass(this.handle2,this.options.handle),i=0;i<this.ticks.length;i++)this._addClass(this.ticks[i],this.options.handle);if(this._state.offset=this._offset(this.sliderElem),this._state.size=this.sliderElem[this.sizePos],this.setValue(this._state.value),this.handle1Keydown=this._keydown.bind(this,0),this.handle1.addEventListener("keydown",this.handle1Keydown,!1),this.handle2Keydown=this._keydown.bind(this,1),this.handle2.addEventListener("keydown",this.handle2Keydown,!1),this.mousedown=this._mousedown.bind(this),this.touchstart=this._touchstart.bind(this),this.touchmove=this._touchmove.bind(this),this.touchCapable&&(this.sliderElem.addEventListener("touchstart",this.touchstart,!1),this.sliderElem.addEventListener("touchmove",this.touchmove,!1)),this.sliderElem.addEventListener("mousedown",this.mousedown,!1),this.resize=this._resize.bind(this),window.addEventListener("resize",this.resize,!1),"hide"===this.options.tooltip)this._addClass(this.tooltip,"hide"),this._addClass(this.tooltip_min,"hide"),this._addClass(this.tooltip_max,"hide");else if("always"===this.options.tooltip)this._showTooltip(),this._alwaysShowTooltip=!0;else{if(this.showTooltip=this._showTooltip.bind(this),this.hideTooltip=this._hideTooltip.bind(this),this.options.ticks_tooltip){var N=this._addTickListener(),O=N.addMouseEnter(this,this.handle1),P=N.addMouseLeave(this,this.handle1);this.handleCallbackMap.handle1={mouseEnter:O,mouseLeave:P},O=N.addMouseEnter(this,this.handle2),P=N.addMouseLeave(this,this.handle2),this.handleCallbackMap.handle2={mouseEnter:O,mouseLeave:P}}else this.sliderElem.addEventListener("mouseenter",this.showTooltip,!1),this.sliderElem.addEventListener("mouseleave",this.hideTooltip,!1),this.touchCapable&&(this.sliderElem.addEventListener("touchstart",this.showTooltip,!1),this.sliderElem.addEventListener("touchmove",this.showTooltip,!1),this.sliderElem.addEventListener("touchend",this.hideTooltip,!1));this.handle1.addEventListener("focus",this.showTooltip,!1),this.handle1.addEventListener("blur",this.hideTooltip,!1),this.handle2.addEventListener("focus",this.showTooltip,!1),this.handle2.addEventListener("blur",this.hideTooltip,!1),this.touchCapable&&(this.handle1.addEventListener("touchstart",this.showTooltip,!1),this.handle1.addEventListener("touchmove",this.showTooltip,!1),this.handle1.addEventListener("touchend",this.hideTooltip,!1),this.handle2.addEventListener("touchstart",this.showTooltip,!1),this.handle2.addEventListener("touchmove",this.showTooltip,!1),this.handle2.addEventListener("touchend",this.hideTooltip,!1))}this.options.enabled?this.enable():this.disable()}var f=void 0,g={formatInvalidInputErrorMsg:function(a){return"Invalid input value '"+a+"' passed in"},callingContextNotSliderInstance:"Calling context element does not have instance of Slider bound to it. Check your code to make sure the JQuery object returned from the call to the slider() initializer is calling the method"},h={linear:{getValue:function(a,b){return a<b.min?b.min:a>b.max?b.max:a},toValue:function(a){var b=a/100*(this.options.max-this.options.min),c=!0;if(this.options.ticks_positions.length>0){for(var d,e,f,g=0,i=1;i<this.options.ticks_positions.length;i++)if(a<=this.options.ticks_positions[i]){d=this.options.ticks[i-1],f=this.options.ticks_positions[i-1],e=this.options.ticks[i],g=this.options.ticks_positions[i];break}var j=(a-f)/(g-f);b=d+j*(e-d),c=!1}var k=c?this.options.min:0,l=k+Math.round(b/this.options.step)*this.options.step;return h.linear.getValue(l,this.options)},toPercentage:function(a){if(this.options.max===this.options.min)return 0;if(this.options.ticks_positions.length>0){for(var b,c,d,e=0,f=0;f<this.options.ticks.length;f++)if(a<=this.options.ticks[f]){b=f>0?this.options.ticks[f-1]:0,d=f>0?this.options.ticks_positions[f-1]:0,c=this.options.ticks[f],e=this.options.ticks_positions[f];break}if(f>0){var g=(a-b)/(c-b);return d+g*(e-d)}}return 100*(a-this.options.min)/(this.options.max-this.options.min)}},logarithmic:{toValue:function(a){var b=1-this.options.min,c=Math.log(this.options.min+b),d=Math.log(this.options.max+b),e=Math.exp(c+(d-c)*a/100)-b;return Math.round(e)===d?d:(e=this.options.min+Math.round((e-this.options.min)/this.options.step)*this.options.step,h.linear.getValue(e,this.options))},toPercentage:function(a){if(this.options.max===this.options.min)return 0;var b=1-this.options.min,c=Math.log(this.options.max+b),d=Math.log(this.options.min+b),e=Math.log(a+b);return 100*(e-d)/(c-d)}}};d=function(a,b){return e.call(this,a,b),this},d.prototype={_init:function(){},constructor:d,defaultOptions:{id:"",min:0,max:10,step:1,precision:0,orientation:"horizontal",value:5,range:!1,selection:"before",tooltip:"show",tooltip_split:!1,lock_to_ticks:!1,handle:"round",reversed:!1,rtl:"auto",enabled:!0,formatter:function(a){return Array.isArray(a)?a[0]+" : "+a[1]:a},natural_arrow_keys:!1,ticks:[],ticks_positions:[],ticks_labels:[],ticks_snap_bounds:0,ticks_tooltip:!1,scale:"linear",focus:!1,tooltip_position:null,labelledby:null,rangeHighlights:[]},getElement:function(){return this.sliderElem},getValue:function(){return this.options.range?this._state.value:this._state.value[0]},setValue:function(a,b,c){a||(a=0);var d=this.getValue();this._state.value=this._validateInputValue(a);var e=this._applyPrecision.bind(this);this.options.range?(this._state.value[0]=e(this._state.value[0]),this._state.value[1]=e(this._state.value[1]),this.ticksAreValid&&this.options.lock_to_ticks&&(this._state.value[0]=this.options.ticks[this._getClosestTickIndex(this._state.value[0])],this._state.value[1]=this.options.ticks[this._getClosestTickIndex(this._state.value[1])]),this._state.value[0]=Math.max(this.options.min,Math.min(this.options.max,this._state.value[0])),this._state.value[1]=Math.max(this.options.min,Math.min(this.options.max,this._state.value[1]))):(this._state.value=e(this._state.value),this.ticksAreValid&&this.options.lock_to_ticks&&(this._state.value=this.options.ticks[this._getClosestTickIndex(this._state.value)]),this._state.value=[Math.max(this.options.min,Math.min(this.options.max,this._state.value))],this._addClass(this.handle2,"hide"),"after"===this.options.selection?this._state.value[1]=this.options.max:this._state.value[1]=this.options.min),this._setTickIndex(),this.options.max>this.options.min?this._state.percentage=[this._toPercentage(this._state.value[0]),this._toPercentage(this._state.value[1]),100*this.options.step/(this.options.max-this.options.min)]:this._state.percentage=[0,0,100],this._layout();var f=this.options.range?this._state.value:this._state.value[0];this._setDataVal(f),b===!0&&this._trigger("slide",f);var g=!1;return g=Array.isArray(f)?d[0]!==f[0]||d[1]!==f[1]:d!==f,g&&c===!0&&this._trigger("change",{oldValue:d,newValue:f}),this},destroy:function(){this._removeSliderEventHandlers(),this.sliderElem.parentNode.removeChild(this.sliderElem),this.element.style.display="",this._cleanUpEventCallbacksMap(),this.element.removeAttribute("data"),a&&(this._unbindJQueryEventHandlers(),f===b&&this.$element.removeData(f),this.$element.removeData(c))},disable:function(){return this._state.enabled=!1,this.handle1.removeAttribute("tabindex"),this.handle2.removeAttribute("tabindex"),this._addClass(this.sliderElem,"slider-disabled"),this._trigger("slideDisabled"),this},enable:function(){return this._state.enabled=!0,this.handle1.setAttribute("tabindex",0),this.handle2.setAttribute("tabindex",0),this._removeClass(this.sliderElem,"slider-disabled"),this._trigger("slideEnabled"),this},toggle:function(){return this._state.enabled?this.disable():this.enable(),this},isEnabled:function(){return this._state.enabled},on:function(a,b){return this._bindNonQueryEventHandler(a,b),this},off:function(b,c){a?(this.$element.off(b,c),this.$sliderElem.off(b,c)):this._unbindNonQueryEventHandler(b,c)},getAttribute:function(a){return a?this.options[a]:this.options},setAttribute:function(a,b){return this.options[a]=b,this},refresh:function(d){var g=this.getValue();return this._removeSliderEventHandlers(),e.call(this,this.element,this.options),d&&d.useCurrentValue===!0&&this.setValue(g),a&&(f===b?(a.data(this.element,b,this),a.data(this.element,c,this)):a.data(this.element,c,this)),this},relayout:function(){return this._resize(),this},_removeTooltipListener:function(a,b){this.handle1.removeEventListener(a,b,!1),this.handle2.removeEventListener(a,b,!1)},_removeSliderEventHandlers:function(){if(this.handle1.removeEventListener("keydown",this.handle1Keydown,!1),this.handle2.removeEventListener("keydown",this.handle2Keydown,!1),this.options.ticks_tooltip){for(var a=this.ticksContainer.getElementsByClassName("slider-tick"),b=0;b<a.length;b++)a[b].removeEventListener("mouseenter",this.ticksCallbackMap[b].mouseEnter,!1),a[b].removeEventListener("mouseleave",this.ticksCallbackMap[b].mouseLeave,!1);this.handleCallbackMap.handle1&&this.handleCallbackMap.handle2&&(this.handle1.removeEventListener("mouseenter",this.handleCallbackMap.handle1.mouseEnter,!1),this.handle2.removeEventListener("mouseenter",this.handleCallbackMap.handle2.mouseEnter,!1),this.handle1.removeEventListener("mouseleave",this.handleCallbackMap.handle1.mouseLeave,!1),this.handle2.removeEventListener("mouseleave",this.handleCallbackMap.handle2.mouseLeave,!1))}this.handleCallbackMap=null,this.ticksCallbackMap=null,this.showTooltip&&this._removeTooltipListener("focus",this.showTooltip),this.hideTooltip&&this._removeTooltipListener("blur",this.hideTooltip),this.showTooltip&&this.sliderElem.removeEventListener("mouseenter",this.showTooltip,!1),this.hideTooltip&&this.sliderElem.removeEventListener("mouseleave",this.hideTooltip,!1),this.sliderElem.removeEventListener("mousedown",this.mousedown,!1),this.touchCapable&&(this.showTooltip&&(this.handle1.removeEventListener("touchstart",this.showTooltip,!1),this.handle1.removeEventListener("touchmove",this.showTooltip,!1),this.handle2.removeEventListener("touchstart",this.showTooltip,!1),this.handle2.removeEventListener("touchmove",this.showTooltip,!1)),this.hideTooltip&&(this.handle1.removeEventListener("touchend",this.hideTooltip,!1),this.handle2.removeEventListener("touchend",this.hideTooltip,!1)),this.showTooltip&&(this.sliderElem.removeEventListener("touchstart",this.showTooltip,!1),this.sliderElem.removeEventListener("touchmove",this.showTooltip,!1)),this.hideTooltip&&this.sliderElem.removeEventListener("touchend",this.hideTooltip,!1),this.sliderElem.removeEventListener("touchstart",this.touchstart,!1),this.sliderElem.removeEventListener("touchmove",this.touchmove,!1)),window.removeEventListener("resize",this.resize,!1)},_bindNonQueryEventHandler:function(a,b){void 0===this.eventToCallbackMap[a]&&(this.eventToCallbackMap[a]=[]),this.eventToCallbackMap[a].push(b)},_unbindNonQueryEventHandler:function(a,b){var c=this.eventToCallbackMap[a];if(void 0!==c)for(var d=0;d<c.length;d++)if(c[d]===b){c.splice(d,1);break}},_cleanUpEventCallbacksMap:function(){for(var a=Object.keys(this.eventToCallbackMap),b=0;b<a.length;b++){var c=a[b];delete this.eventToCallbackMap[c]}},_showTooltip:function(){this.options.tooltip_split===!1?(this._addClass(this.tooltip,"show"),this.tooltip_min.style.display="none",this.tooltip_max.style.display="none"):(this._addClass(this.tooltip_min,"show"),this._addClass(this.tooltip_max,"show"),this.tooltip.style.display="none"),this._state.over=!0},_hideTooltip:function(){this._state.inDrag===!1&&this._alwaysShowTooltip!==!0&&(this._removeClass(this.tooltip,"show"),this._removeClass(this.tooltip_min,"show"),this._removeClass(this.tooltip_max,"show")),this._state.over=!1},_setToolTipOnMouseOver:function(a){function b(a,b){return b?[100-a.percentage[0],c.options.range?100-a.percentage[1]:a.percentage[1]]:[a.percentage[0],a.percentage[1]]}var c=this,d=this.options.formatter(a?a.value[0]:this._state.value[0]),e=a?b(a,this.options.reversed):b(this._state,this.options.reversed);this._setText(this.tooltipInner,d),this.tooltip.style[this.stylePos]=e[0]+"%"},_copyState:function(){return{value:[this._state.value[0],this._state.value[1]],enabled:this._state.enabled,offset:this._state.offset,size:this._state.size,percentage:[this._state.percentage[0],this._state.percentage[1],this._state.percentage[2]],inDrag:this._state.inDrag,over:this._state.over,dragged:this._state.dragged,keyCtrl:this._state.keyCtrl}},_addTickListener:function(){return{addMouseEnter:function(a,b,c){var d=function(){var d=a._copyState(),e=b===a.handle1?d.value[0]:d.value[1],f=void 0;void 0!==c?(e=a.options.ticks[c],f=a.options.ticks_positions.length>0&&a.options.ticks_positions[c]||a._toPercentage(a.options.ticks[c])):f=a._toPercentage(e),d.value[0]=e,d.percentage[0]=f,a._setToolTipOnMouseOver(d),a._showTooltip()};return b.addEventListener("mouseenter",d,!1),d},addMouseLeave:function(a,b){var c=function(){a._hideTooltip()};return b.addEventListener("mouseleave",c,!1),c}}},_layout:function(){var a,b;if(a=this.options.reversed?[100-this._state.percentage[0],this.options.range?100-this._state.percentage[1]:this._state.percentage[1]]:[this._state.percentage[0],this._state.percentage[1]],this.handle1.style[this.stylePos]=a[0]+"%",this.handle1.setAttribute("aria-valuenow",this._state.value[0]),b=this.options.formatter(this._state.value[0]),isNaN(b)?this.handle1.setAttribute("aria-valuetext",b):this.handle1.removeAttribute("aria-valuetext"),this.handle2.style[this.stylePos]=a[1]+"%",this.handle2.setAttribute("aria-valuenow",this._state.value[1]),b=this.options.formatter(this._state.value[1]),isNaN(b)?this.handle2.setAttribute("aria-valuetext",b):this.handle2.removeAttribute("aria-valuetext"),this.rangeHighlightElements.length>0&&Array.isArray(this.options.rangeHighlights)&&this.options.rangeHighlights.length>0)for(var c=0;c<this.options.rangeHighlights.length;c++){var d=this._toPercentage(this.options.rangeHighlights[c].start),e=this._toPercentage(this.options.rangeHighlights[c].end);if(this.options.reversed){var f=100-e;e=100-d,d=f}var g=this._createHighlightRange(d,e);g?"vertical"===this.options.orientation?(this.rangeHighlightElements[c].style.top=g.start+"%",this.rangeHighlightElements[c].style.height=g.size+"%"):(this.options.rtl?this.rangeHighlightElements[c].style.right=g.start+"%":this.rangeHighlightElements[c].style.left=g.start+"%",this.rangeHighlightElements[c].style.width=g.size+"%"):this.rangeHighlightElements[c].style.display="none"}if(Array.isArray(this.options.ticks)&&this.options.ticks.length>0){var h,i="vertical"===this.options.orientation?"height":"width";h="vertical"===this.options.orientation?"marginTop":this.options.rtl?"marginRight":"marginLeft";var j=this._state.size/(this.options.ticks.length-1);if(this.tickLabelContainer){var k=0;if(0===this.options.ticks_positions.length)"vertical"!==this.options.orientation&&(this.tickLabelContainer.style[h]=-j/2+"px"),k=this.tickLabelContainer.offsetHeight;else for(l=0;l<this.tickLabelContainer.childNodes.length;l++)this.tickLabelContainer.childNodes[l].offsetHeight>k&&(k=this.tickLabelContainer.childNodes[l].offsetHeight);"horizontal"===this.options.orientation&&(this.sliderElem.style.marginBottom=k+"px")}for(var l=0;l<this.options.ticks.length;l++){var m=this.options.ticks_positions[l]||this._toPercentage(this.options.ticks[l]);this.options.reversed&&(m=100-m),this.ticks[l].style[this.stylePos]=m+"%",this._removeClass(this.ticks[l],"in-selection"),this.options.range?m>=a[0]&&m<=a[1]&&this._addClass(this.ticks[l],"in-selection"):"after"===this.options.selection&&m>=a[0]?this._addClass(this.ticks[l],"in-selection"):"before"===this.options.selection&&m<=a[0]&&this._addClass(this.ticks[l],"in-selection"),this.tickLabels[l]&&(this.tickLabels[l].style[i]=j+"px","vertical"!==this.options.orientation&&void 0!==this.options.ticks_positions[l]?(this.tickLabels[l].style.position="absolute",this.tickLabels[l].style[this.stylePos]=m+"%",this.tickLabels[l].style[h]=-j/2+"px"):"vertical"===this.options.orientation&&(this.options.rtl?this.tickLabels[l].style.marginRight=this.sliderElem.offsetWidth+"px":this.tickLabels[l].style.marginLeft=this.sliderElem.offsetWidth+"px",this.tickLabelContainer.style[h]=this.sliderElem.offsetWidth/2*-1+"px"),this._removeClass(this.tickLabels[l],"label-in-selection label-is-selection"),this.options.range?m>=a[0]&&m<=a[1]&&(this._addClass(this.tickLabels[l],"label-in-selection"),(m===a[0]||a[1])&&this._addClass(this.tickLabels[l],"label-is-selection")):("after"===this.options.selection&&m>=a[0]?this._addClass(this.tickLabels[l],"label-in-selection"):"before"===this.options.selection&&m<=a[0]&&this._addClass(this.tickLabels[l],"label-in-selection"),m===a[0]&&this._addClass(this.tickLabels[l],"label-is-selection")))}}var n;if(this.options.range){n=this.options.formatter(this._state.value),this._setText(this.tooltipInner,n),this.tooltip.style[this.stylePos]=(a[1]+a[0])/2+"%";var o=this.options.formatter(this._state.value[0]);this._setText(this.tooltipInner_min,o);var p=this.options.formatter(this._state.value[1]);this._setText(this.tooltipInner_max,p),this.tooltip_min.style[this.stylePos]=a[0]+"%",this.tooltip_max.style[this.stylePos]=a[1]+"%"}else n=this.options.formatter(this._state.value[0]),this._setText(this.tooltipInner,n),this.tooltip.style[this.stylePos]=a[0]+"%";if("vertical"===this.options.orientation)this.trackLow.style.top="0",this.trackLow.style.height=Math.min(a[0],a[1])+"%",this.trackSelection.style.top=Math.min(a[0],a[1])+"%",this.trackSelection.style.height=Math.abs(a[0]-a[1])+"%",this.trackHigh.style.bottom="0",this.trackHigh.style.height=100-Math.min(a[0],a[1])-Math.abs(a[0]-a[1])+"%";else{"right"===this.stylePos?this.trackLow.style.right="0":this.trackLow.style.left="0",this.trackLow.style.width=Math.min(a[0],a[1])+"%","right"===this.stylePos?this.trackSelection.style.right=Math.min(a[0],a[1])+"%":this.trackSelection.style.left=Math.min(a[0],a[1])+"%",this.trackSelection.style.width=Math.abs(a[0]-a[1])+"%","right"===this.stylePos?this.trackHigh.style.left="0":this.trackHigh.style.right="0",this.trackHigh.style.width=100-Math.min(a[0],a[1])-Math.abs(a[0]-a[1])+"%";var q=this.tooltip_min.getBoundingClientRect(),r=this.tooltip_max.getBoundingClientRect();"bottom"===this.options.tooltip_position?q.right>r.left?(this._removeClass(this.tooltip_max,"bs-tooltip-bottom"),this._addClass(this.tooltip_max,"bs-tooltip-top"),this.tooltip_max.style.top="",this.tooltip_max.style.bottom="22px"):(this._removeClass(this.tooltip_max,"bs-tooltip-top"),this._addClass(this.tooltip_max,"bs-tooltip-bottom"),this.tooltip_max.style.top=this.tooltip_min.style.top,this.tooltip_max.style.bottom=""):q.right>r.left?(this._removeClass(this.tooltip_max,"bs-tooltip-top"),this._addClass(this.tooltip_max,"bs-tooltip-bottom"),this.tooltip_max.style.top="18px"):(this._removeClass(this.tooltip_max,"bs-tooltip-bottom"),this._addClass(this.tooltip_max,"bs-tooltip-top"),this.tooltip_max.style.top=this.tooltip_min.style.top)}},_createHighlightRange:function(a,b){return this._isHighlightRange(a,b)?a>b?{start:b,size:a-b}:{start:a,size:b-a}:null},_isHighlightRange:function(a,b){return a>=0&&100>=a&&b>=0&&100>=b?!0:!1},_resize:function(a){this._state.offset=this._offset(this.sliderElem),this._state.size=this.sliderElem[this.sizePos],this._layout()},_removeProperty:function(a,b){a.style.removeProperty?a.style.removeProperty(b):a.style.removeAttribute(b)},_mousedown:function(a){if(!this._state.enabled)return!1;a.preventDefault&&a.preventDefault(),this._state.offset=this._offset(this.sliderElem),this._state.size=this.sliderElem[this.sizePos];var b=this._getPercentage(a);if(this.options.range){var c=Math.abs(this._state.percentage[0]-b),d=Math.abs(this._state.percentage[1]-b);this._state.dragged=d>c?0:1,this._adjustPercentageForRangeSliders(b)}else this._state.dragged=0;this._state.percentage[this._state.dragged]=b,this.touchCapable&&(document.removeEventListener("touchmove",this.mousemove,!1),document.removeEventListener("touchend",this.mouseup,!1)),this.mousemove&&document.removeEventListener("mousemove",this.mousemove,!1),this.mouseup&&document.removeEventListener("mouseup",this.mouseup,!1),this.mousemove=this._mousemove.bind(this),this.mouseup=this._mouseup.bind(this),this.touchCapable&&(document.addEventListener("touchmove",this.mousemove,!1),document.addEventListener("touchend",this.mouseup,!1)),document.addEventListener("mousemove",this.mousemove,!1),document.addEventListener("mouseup",this.mouseup,!1),this._state.inDrag=!0;var e=this._calculateValue();return this._trigger("slideStart",e),this.setValue(e,!1,!0),a.returnValue=!1,this.options.focus&&this._triggerFocusOnHandle(this._state.dragged),!0},_touchstart:function(a){this._mousedown(a)},_triggerFocusOnHandle:function(a){0===a&&this.handle1.focus(),1===a&&this.handle2.focus()},_keydown:function(a,b){if(!this._state.enabled)return!1;var c;switch(b.keyCode){case 37:case 40:c=-1;break;case 39:case 38:c=1}if(c){if(this.options.natural_arrow_keys){var d="horizontal"===this.options.orientation,e="vertical"===this.options.orientation,f=this.options.rtl,g=this.options.reversed;d?f?g||(c=-c):g&&(c=-c):e&&(g||(c=-c))}var h;if(this.ticksAreValid&&this.options.lock_to_ticks){var i=void 0;i=this.options.ticks.indexOf(this._state.value[a]),-1===i&&(i=0,window.console.warn("(lock_to_ticks) _keydown: index should not be -1")),i+=c,i=Math.max(0,Math.min(this.options.ticks.length-1,i)),h=this.options.ticks[i]}else h=this._state.value[a]+c*this.options.step;var j=this._toPercentage(h);if(this._state.keyCtrl=a,this.options.range){this._adjustPercentageForRangeSliders(j);var k=this._state.keyCtrl?this._state.value[0]:h,l=this._state.keyCtrl?h:this._state.value[1];h=[Math.max(this.options.min,Math.min(this.options.max,k)),Math.max(this.options.min,Math.min(this.options.max,l))]}else h=Math.max(this.options.min,Math.min(this.options.max,h));return this._trigger("slideStart",h),this.setValue(h,!0,!0),this._trigger("slideStop",h),this._pauseEvent(b),delete this._state.keyCtrl,!1}},_pauseEvent:function(a){a.stopPropagation&&a.stopPropagation(),
a.preventDefault&&a.preventDefault(),a.cancelBubble=!0,a.returnValue=!1},_mousemove:function(a){if(!this._state.enabled)return!1;var b=this._getPercentage(a);this._adjustPercentageForRangeSliders(b),this._state.percentage[this._state.dragged]=b;var c=this._calculateValue(!0);return this.setValue(c,!0,!0),!1},_touchmove:function(a){void 0!==a.changedTouches&&a.preventDefault&&a.preventDefault()},_adjustPercentageForRangeSliders:function(a){if(this.options.range){var b=this._getNumDigitsAfterDecimalPlace(a);b=b?b-1:0;var c=this._applyToFixedAndParseFloat(a,b);0===this._state.dragged&&this._applyToFixedAndParseFloat(this._state.percentage[1],b)<c?(this._state.percentage[0]=this._state.percentage[1],this._state.dragged=1):1===this._state.dragged&&this._applyToFixedAndParseFloat(this._state.percentage[0],b)>c?(this._state.percentage[1]=this._state.percentage[0],this._state.dragged=0):0===this._state.keyCtrl&&this._toPercentage(this._state.value[1])<a?(this._state.percentage[0]=this._state.percentage[1],this._state.keyCtrl=1,this.handle2.focus()):1===this._state.keyCtrl&&this._toPercentage(this._state.value[0])>a&&(this._state.percentage[1]=this._state.percentage[0],this._state.keyCtrl=0,this.handle1.focus())}},_mouseup:function(a){if(!this._state.enabled)return!1;var b=this._getPercentage(a);this._adjustPercentageForRangeSliders(b),this._state.percentage[this._state.dragged]=b,this.touchCapable&&(document.removeEventListener("touchmove",this.mousemove,!1),document.removeEventListener("touchend",this.mouseup,!1)),document.removeEventListener("mousemove",this.mousemove,!1),document.removeEventListener("mouseup",this.mouseup,!1),this._state.inDrag=!1,this._state.over===!1&&this._hideTooltip();var c=this._calculateValue(!0);return this.setValue(c,!1,!0),this._trigger("slideStop",c),this._state.dragged=null,!1},_setValues:function(a,b){var c=0===a?0:100;this._state.percentage[a]!==c&&(b.data[a]=this._toValue(this._state.percentage[a]),b.data[a]=this._applyPrecision(b.data[a]))},_calculateValue:function(a){var b={};return this.options.range?(b.data=[this.options.min,this.options.max],this._setValues(0,b),this._setValues(1,b),a&&(b.data[0]=this._snapToClosestTick(b.data[0]),b.data[1]=this._snapToClosestTick(b.data[1]))):(b.data=this._toValue(this._state.percentage[0]),b.data=parseFloat(b.data),b.data=this._applyPrecision(b.data),a&&(b.data=this._snapToClosestTick(b.data))),b.data},_snapToClosestTick:function(a){for(var b=[a,1/0],c=0;c<this.options.ticks.length;c++){var d=Math.abs(this.options.ticks[c]-a);d<=b[1]&&(b=[this.options.ticks[c],d])}return b[1]<=this.options.ticks_snap_bounds?b[0]:a},_applyPrecision:function(a){var b=this.options.precision||this._getNumDigitsAfterDecimalPlace(this.options.step);return this._applyToFixedAndParseFloat(a,b)},_getNumDigitsAfterDecimalPlace:function(a){var b=(""+a).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return b?Math.max(0,(b[1]?b[1].length:0)-(b[2]?+b[2]:0)):0},_applyToFixedAndParseFloat:function(a,b){var c=a.toFixed(b);return parseFloat(c)},_getPercentage:function(a){!this.touchCapable||"touchstart"!==a.type&&"touchmove"!==a.type&&"touchend"!==a.type||(a=a.changedTouches[0]);var b=a[this.mousePos],c=this._state.offset[this.stylePos],d=b-c;"right"===this.stylePos&&(d=-d);var e=d/this._state.size*100;return e=Math.round(e/this._state.percentage[2])*this._state.percentage[2],this.options.reversed&&(e=100-e),Math.max(0,Math.min(100,e))},_validateInputValue:function(a){if(isNaN(+a)){if(Array.isArray(a))return this._validateArray(a),a;throw new Error(g.formatInvalidInputErrorMsg(a))}return+a},_validateArray:function(a){for(var b=0;b<a.length;b++){var c=a[b];if("number"!=typeof c)throw new Error(g.formatInvalidInputErrorMsg(c))}},_setDataVal:function(a){this.element.setAttribute("data-value",a),this.element.setAttribute("value",a),this.element.value=a},_trigger:function(b,c){c=c||0===c?c:void 0;var d=this.eventToCallbackMap[b];if(d&&d.length)for(var e=0;e<d.length;e++){var f=d[e];f(c)}a&&this._triggerJQueryEvent(b,c)},_triggerJQueryEvent:function(a,b){var c={type:a,value:b};this.$element.trigger(c),this.$sliderElem.trigger(c)},_unbindJQueryEventHandlers:function(){this.$element.off(),this.$sliderElem.off()},_setText:function(a,b){"undefined"!=typeof a.textContent?a.textContent=b:"undefined"!=typeof a.innerText&&(a.innerText=b)},_removeClass:function(a,b){for(var c=b.split(" "),d=a.className,e=0;e<c.length;e++){var f=c[e],g=new RegExp("(?:\\s|^)"+f+"(?:\\s|$)");d=d.replace(g," ")}a.className=d.trim()},_addClass:function(a,b){for(var c=b.split(" "),d=a.className,e=0;e<c.length;e++){var f=c[e],g=new RegExp("(?:\\s|^)"+f+"(?:\\s|$)"),h=g.test(d);h||(d+=" "+f)}a.className=d.trim()},_offsetLeft:function(a){return a.getBoundingClientRect().left},_offsetRight:function(a){return a.getBoundingClientRect().right},_offsetTop:function(a){for(var b=a.offsetTop;(a=a.offsetParent)&&!isNaN(a.offsetTop);)b+=a.offsetTop,"BODY"!==a.tagName&&(b-=a.scrollTop);return b},_offset:function(a){return{left:this._offsetLeft(a),right:this._offsetRight(a),top:this._offsetTop(a)}},_css:function(b,c,d){if(a)a.style(b,c,d);else{var e=c.replace(/^-ms-/,"ms-").replace(/-([\da-z])/gi,function(a,b){return b.toUpperCase()});b.style[e]=d}},_toValue:function(a){return this.options.scale.toValue.apply(this,[a])},_toPercentage:function(a){return this.options.scale.toPercentage.apply(this,[a])},_setTooltipPosition:function(){var a=[this.tooltip,this.tooltip_min,this.tooltip_max];if("vertical"===this.options.orientation){var b;b=this.options.tooltip_position?this.options.tooltip_position:this.options.rtl?"left":"right";var c="left"===b?"right":"left";a.forEach(function(a){this._addClass(a,"bs-tooltip-"+b),a.style[c]="100%"}.bind(this))}else"bottom"===this.options.tooltip_position?a.forEach(function(a){this._addClass(a,"bs-tooltip-bottom"),a.style.top="22px"}.bind(this)):a.forEach(function(a){this._addClass(a,"bs-tooltip-top"),a.style.top=-this.tooltip.outerHeight-14+"px"}.bind(this))},_getClosestTickIndex:function(a){for(var b=Math.abs(a-this.options.ticks[0]),c=0,d=0;d<this.options.ticks.length;++d){var e=Math.abs(a-this.options.ticks[d]);b>e&&(b=e,c=d)}return c},_setTickIndex:function(){this.ticksAreValid&&(this._state.tickIndex=[this.options.ticks.indexOf(this._state.value[0]),this.options.ticks.indexOf(this._state.value[1])])}},a&&a.fn&&(a.fn.slider?(windowIsDefined&&window.console.warn("bootstrap-slider.js - WARNING: $.fn.slider namespace is already bound. Use the $.fn.bootstrapSlider namespace instead."),f=c):(a.bridget(b,d),f=b),a.bridget(c,d),a(function(){a("input[data-provide=slider]")[f]()}))}(a),d});
|
281677160/openwrt-package
| 2,849 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_map.h
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#ifndef _NGX_MAP_H_INCLUDED_
#define _NGX_MAP_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
/*
* key: key for map node
*/
typedef ngx_rbtree_key_t (* ngx_map_hash_pt)(intptr_t key);
/*
* if key1 < key2, return -1
* if key1 = key2, return 0
* if key1 > key2, return 1
*/
typedef int (* ngx_cmp_pt)(intptr_t key1, intptr_t key2);
/* ngx_str_t */
ngx_rbtree_key_t ngx_map_hash_str(intptr_t key);
int ngx_cmp_str(intptr_t key1, intptr_t key2);
/* ngx_uint_t */
ngx_rbtree_key_t ngx_map_hash_uint(intptr_t key);
int ngx_cmp_uint(intptr_t key1, intptr_t key2);
/* ngx_int_t */
ngx_rbtree_key_t ngx_map_hash_int(intptr_t key);
int ngx_cmp_int(intptr_t key1, intptr_t key2);
typedef struct {
ngx_rbtree_t rbtree;
ngx_rbtree_node_t sentinel;
ngx_map_hash_pt hash;
ngx_cmp_pt cmp;
} ngx_map_t;
typedef struct {
ngx_rbtree_node_t rn;
intptr_t raw_key;
ngx_map_t *map;
} ngx_map_node_t;
/*
* return value:
* None
* paras:
* map : map for initial
* hash: hash func for calc key's hash
* cmp : cmp func for cmp two keys
*/
void ngx_map_init(ngx_map_t *map, ngx_map_hash_pt hash, ngx_cmp_pt cmp);
/*
* return value:
* if map is empty return 1, else return 0
*/
#define ngx_map_empty(map) (map->rbtree.root == map->rbtree.sentinel)
/*
* return value:
* the mininum key map node, if map is empty, return NULL
* paras:
* map: map for operate
*/
ngx_map_node_t *ngx_map_begin(ngx_map_t *map);
/*
* return value:
* the maximum key map node, if map is empty, return NULL
* paras:
* map: map for operate
*/
ngx_map_node_t *ngx_map_rbegin(ngx_map_t *map);
/*
* return value:
* the next bigger key map node, if none, return NULL
* paras:
* n : current node
*/
ngx_map_node_t *ngx_map_next(ngx_map_node_t *n);
/*
* return value:
* the next smaller key map node, if none, return NULL
* paras:
* n : current node
*/
ngx_map_node_t *ngx_map_prev(ngx_map_node_t *n);
/*
* return value:
* None
* paras:
* map : map for operate
* node : map node for inserting into map
* covered: 1 for covered if key is same, 0 do nothing if key is same
*/
void ngx_map_insert(ngx_map_t *map, ngx_map_node_t *node, ngx_flag_t covered);
/*
* return value:
* None
* paras:
* map: map for operate
* key: map node key for deleting from map
*/
void ngx_map_delete(ngx_map_t *map, intptr_t key);
/*
* return value:
* node in map searching by key, NULL for not found
* paras:
* map: map for operate
* key: node key for searching
*/
ngx_map_node_t *ngx_map_find(ngx_map_t *map, intptr_t key);
#endif
|
294coder/Efficient-MIF
| 8,807 |
utils/FS_index/indexes_evaluation_FS.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
#
import numpy as np
import torch
from scipy import signal, ndimage, misc
import cv2
from .HQNR import HQNR
from .my_D_s import D_s as my_Ds
def mtf_resize(img, satellite='QuickBird', scale=4):
# satellite GNyq
scale = int(scale)
if satellite == 'QuickBird':
GNyq = [0.34, 0.32, 0.30, 0.22] # Band Order: B,G,R,NIR
GNyqPan = 0.15
elif satellite == 'IKONOS':
GNyq = [0.26, 0.28, 0.29, 0.28] # Band Order: B,G,R,NIR
GNyqPan = 0.17
elif satellite == 'WV3':
GNyq = [0.325, 0.355, 0.360, 0.350, 0.365, 0.360, 0.335, 0.315] # Band Order: B,G,R,NIR
GNyqPan = 0.14
else:
raise NotImplementedError('satellite: QuickBird or IKONOS or WV3')
# lowpass
img_ = img.squeeze()
img_ = img_.astype(np.float64)
if img_.ndim == 2: # Pan
H, W = img_.shape
lowpass = GNyq2win(GNyqPan, scale, N=41)
elif img_.ndim == 3: # MS
H, W, _ = img.shape
lowpass = [GNyq2win(gnyq, scale, N=41) for gnyq in GNyq]
lowpass = np.stack(lowpass, axis=-1)
img_ = ndimage.filters.correlate(img_, lowpass, mode='nearest')
# downsampling
output_size = (H // scale, W // scale)
img_ = cv2.resize(img_, dsize=output_size, interpolation=cv2.INTER_NEAREST)
return img_
def gaussian2d(N, std):
t = np.arange(-(N - 1) // 2, (N + 2) // 2)
t1, t2 = np.meshgrid(t, t)
std = np.double(std)
w = np.exp(-0.5 * (t1 / std) ** 2) * np.exp(-0.5 * (t2 / std) ** 2)
return w
def kaiser2d(N, beta):
t = np.arange(-(N - 1) // 2, (N + 2) // 2) / np.double(N - 1)
t1, t2 = np.meshgrid(t, t)
t12 = np.sqrt(t1 * t1 + t2 * t2)
w1 = np.kaiser(N, beta)
w = np.interp(t12, t, w1)
w[t12 > t[-1]] = 0
w[t12 < t[0]] = 0
return w
def fir_filter_wind(Hd, w):
"""
compute fir (finite impulse response) filter with window method
Hd: desired freqeuncy response (2D)
w: window (2D)
"""
hd = np.rot90(np.fft.fftshift(np.rot90(Hd, 2)), 2)
h = np.fft.fftshift(np.fft.ifft2(hd))
h = np.rot90(h, 2)
h = h * w
h = h / np.sum(h)
return h
def GNyq2win(GNyq, scale=4, N=41):
"""Generate a 2D convolutional window from a given GNyq
GNyq: Nyquist frequency
scale: spatial size of PAN / spatial size of MS
"""
# fir filter with window method
fcut = 1 / scale
alpha = np.sqrt(((N - 1) * (fcut / 2)) ** 2 / (-2 * np.log(GNyq)))
H = gaussian2d(N, alpha)
Hd = H / np.max(H)
w = kaiser2d(N, 0.5)
h = fir_filter_wind(Hd, w)
return np.real(h)
def _qindex(img1, img2, block_size=8):
"""Q-index for 2D (one-band) image, shape (H, W); uint or float [0, 1]"""
assert block_size > 1, 'block_size shold be greater than 1!'
img1_ = img1.astype(np.float64)
img2_ = img2.astype(np.float64)
window = np.ones((block_size, block_size)) / (block_size ** 2)
# window_size = block_size**2
# filter, valid
pad_topleft = int(np.floor(block_size / 2))
pad_bottomright = block_size - 1 - pad_topleft
mu1 = cv2.filter2D(img1_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright]
mu2 = cv2.filter2D(img2_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright]
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = cv2.filter2D(img1_ ** 2, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu1_sq
sigma2_sq = cv2.filter2D(img2_ ** 2, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu2_sq
# print(mu1_mu2.shape)
# print(sigma2_sq.shape)
sigma12 = cv2.filter2D(img1_ * img2_, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu1_mu2
# all = 1, include the case of simga == mu == 0
qindex_map = np.ones(sigma12.shape)
# sigma == 0 and mu != 0
idx = ((sigma1_sq + sigma2_sq) == 0) * ((mu1_sq + mu2_sq) != 0)
qindex_map[idx] = 2 * mu1_mu2[idx] / (mu1_sq + mu2_sq)[idx]
# sigma !=0 and mu == 0
idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) == 0)
qindex_map[idx] = 2 * sigma12[idx] / (sigma1_sq + sigma2_sq)[idx]
# sigma != 0 and mu != 0
idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) != 0)
qindex_map[idx] = ((2 * mu1_mu2[idx]) * (2 * sigma12[idx])) / (
(mu1_sq + mu2_sq)[idx] * (sigma1_sq + sigma2_sq)[idx])
return np.mean(qindex_map)
def qindex(img1, img2, block_size=8):
"""Q-index for 2D (H, W) or 3D (H, W, C) image; uint or float [0, 1]"""
if not img1.shape == img2.shape:
raise ValueError('Input images must have the same dimensions.')
if img1.ndim == 2:
return _qindex(img1, img2, block_size)
elif img1.ndim == 3:
qindexs = [_qindex(img1[..., i], img2[..., i], block_size) for i in range(img1.shape[2])]
return np.array(qindexs).mean()
else:
raise ValueError('Wrong input image dimensions.')
def D_lambda(img_fake, img_lm, block_size=32, p=1):
"""Spectral distortion
img_fake, generated HRMS
img_lm, LRMS"""
assert img_fake.ndim == img_lm.ndim == 3, 'Images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert C_f == C_r, 'Fake and lm should have the same number of bands!'
# D_lambda
Q_fake = []
Q_lm = []
for i in range(C_f):
for j in range(i + 1, C_f):
# for fake
band1 = img_fake[..., i]
band2 = img_fake[..., j]
Q_fake.append(_qindex(band1, band2, block_size=block_size))
# for real
band1 = img_lm[..., i]
band2 = img_lm[..., j]
Q_lm.append(_qindex(band1, band2, block_size=block_size))
Q_fake = np.array(Q_fake)
Q_lm = np.array(Q_lm)
D_lambda_index = (np.abs(Q_fake - Q_lm) ** p).mean()
return D_lambda_index ** (1 / p)
def D_s(img_fake, img_lm, pan, satellite='QuickBird', scale=4, block_size=32, q=1):
"""Spatial distortion
img_fake, generated HRMS
img_lm, LRMS
pan, HRPan"""
# fake and lm
assert img_fake.ndim == img_lm.ndim == 3, 'MS images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert H_f // H_r == W_f // W_r == scale, 'Spatial resolution should be compatible with scale'
assert C_f == C_r, 'Fake and lm should have the same number of bands!'
# fake and pan
assert pan.ndim == 3, 'Panchromatic image must be 3D!'
H_p, W_p, C_p = pan.shape
assert C_p == 1, 'size of 3rd dim of Panchromatic image must be 1'
assert H_f == H_p and W_f == W_p, "Pan's and fake's spatial resolution should be the same"
# get LRPan, 2D
pan_lr = mtf_resize(pan, satellite=satellite, scale=scale)
# print(pan_lr.shape)
# D_s
Q_hr = []
Q_lr = []
for i in range(C_f):
# for HR fake
band1 = img_fake[..., i]
band2 = pan[..., 0] # the input PAN is 3D with size=1 along 3rd dim
# print(band1.shape)
# print(band2.shape)
Q_hr.append(_qindex(band1, band2, block_size=block_size))
band1 = img_lm[..., i]
band2 = pan_lr # this is 2D
# print(band1.shape)
# print(band2.shape)
Q_lr.append(_qindex(band1, band2, block_size=block_size))
Q_hr = np.array(Q_hr)
Q_lr = np.array(Q_lr)
D_s_index = (np.abs(Q_hr - Q_lr) ** q).mean()
return D_s_index ** (1 / q)
def qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1):
"""QNR - No reference IQA"""
if pan.ndim == 2:
pan = pan[:, :, None]
D_lambda_idx = D_lambda(ps_ms, msexp, S, p)
D_s_idx = D_s(ps_ms, ms, pan, 'WV3', ratio, S, q)
QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta
return QNR_idx, D_lambda_idx, D_s_idx
def my_qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1):
"""QNR - No reference IQA"""
# D_lambda_idx = D_lambda(img_fake, img_lm, block_size, p)
# D_s_idx = D_s(img_fake, img_lm, pan, satellite, scale, block_size, q)
D_lambda_idx = D_lambda(ps_ms, msexp, S, p)
D_s_idx = my_Ds(ps_ms, msexp, ms, pan, ratio, S, q)
QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta
return QNR_idx, D_lambda_idx, D_s_idx
def indexes_evaluation_FS(I_F, I_MS_LR, I_PAN, L, th_values, I_MS, sensor, ratio, Qblocks_size, flagQNR):
if th_values == 1:
I_F[I_F > 2 ** L] = 2 ** L
I_F[I_F < 0] = 0
if flagQNR:
QNR_index, D_lambda, D_S = my_qnr(I_F, I_MS_LR, I_MS, I_PAN, ratio, Qblocks_size)
else:
QNR_index, D_lambda, D_S = HQNR(I_F, I_MS_LR, I_MS, I_PAN, Qblocks_size, sensor, ratio)
return QNR_index, D_lambda, D_S
|
281677160/openwrt-package
| 1,683 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_dynamic_resolver.h
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#ifndef _NGX_DYNAMIC_RESOLVER_H_INCLUDED_
#define _NGX_DYNAMIC_RESOLVER_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
/*
* paras:
* data : user private data set in ngx_dynamic_resolver_start_resolver
* sa : sock address get
* socklen: sock address len, 0 for get none address
*/
typedef void (* ngx_dynamic_resolver_handler_pt)(void *data,
struct sockaddr *sa, socklen_t socklen);
/*
* add domain into dynamic resolver
*
* paras:
* domain: domain for DNS query
*/
void ngx_dynamic_resolver_add_domain(ngx_str_t *domain, ngx_cycle_t *cycle);
/*
* del domain from dynamic resolver
*
* paras:
* domain: domain for DNS query
*/
void ngx_dynamic_resolver_del_domain(ngx_str_t *domain);
/*
* get addr from dynamic resolver by domain if exist,
* otherwise, get from resolver configured into event resolver
* and add domain into dynamic resolver
*
* paras:
* domain: domain for DNS query
* h : callback handler
* data : data for callback
*/
void ngx_dynamic_resolver_start_resolver(ngx_str_t *domain,
ngx_dynamic_resolver_handler_pt h, void *data);
/*
* get addr from dynamic resolver by domain,
*
* return:
* 0 for failed
* socklen for successd
*
* paras:
* domain: domain for query
* sa : sockaddr for domain
*/
socklen_t ngx_dynamic_resolver_gethostbyname(ngx_str_t *domain,
struct sockaddr *sa);
/*
* paras:
* r: http request to query status of dynamic resolver
*/
ngx_chain_t *ngx_dynamic_resolver_state(ngx_http_request_t *r);
#endif
|
281677160/openwrt-package
| 13,803 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_http_trace_module.c
|
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
typedef struct {
ngx_flag_t trace;
} ngx_http_trace_main_conf_t;
typedef struct {
u_char traceid[32]; /* X-NTM-Traceid */
u_char cid[32]; /* X-NTM-Currentid */
u_char pid[32]; /* X-NTM-Parentid */
ngx_flag_t debug; /* X-NTM-Debug */
} ngx_http_trace_ctx_t;
static void *ngx_http_trace_create_main_conf(ngx_conf_t *cf);
static char *ngx_http_trace_init_main_conf(ngx_conf_t *cf, void *conf);
static char *ngx_http_trace(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_http_trace_add_variables(ngx_conf_t *cf);
static ngx_int_t ngx_http_trace_init(ngx_conf_t *cf);
static ngx_int_t ngx_http_trace_traceid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_http_trace_currentid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_http_trace_parentid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_http_trace_debug_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_http_trace_newid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_command_t ngx_http_trace_commands[] = {
{ ngx_string("http_trace"),
NGX_HTTP_MAIN_CONF|NGX_CONF_NOARGS,
ngx_http_trace,
0,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_http_trace_module_ctx = {
ngx_http_trace_add_variables, /* preconfiguration */
ngx_http_trace_init, /* postconfiguration */
ngx_http_trace_create_main_conf, /* create main configuration */
ngx_http_trace_init_main_conf, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_http_trace_module = {
NGX_MODULE_V1,
&ngx_http_trace_module_ctx, /* module context */
ngx_http_trace_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_http_variable_t ngx_http_trace_vars[] = {
{ ngx_string("ntm_traceid"), NULL,
ngx_http_trace_traceid_variable, 0, 0, 0 },
{ ngx_string("ntm_currentid"), NULL,
ngx_http_trace_currentid_variable, 0, 0, 0 },
{ ngx_string("ntm_parentid"), NULL,
ngx_http_trace_parentid_variable, 0, 0, 0 },
{ ngx_string("ntm_debug"), NULL,
ngx_http_trace_debug_variable, 0, 0, 0 },
{ ngx_string("ntm_newid"), NULL,
ngx_http_trace_newid_variable, 0, 0, 0 },
{ ngx_null_string, NULL, NULL, 0, 0, 0 }
};
static void
ngx_http_trace_genid(u_char *id) {
ngx_sprintf(id, "%08xD%08xD%08xD%08xD",
(uint32_t) ngx_random(), (uint32_t) ngx_random(),
(uint32_t) ngx_random(), (uint32_t) ngx_random());
}
static u_char *
ngx_http_trace_log_error(ngx_log_t *log, u_char *buf, size_t len)
{
u_char *p;
ngx_http_request_t *r;
ngx_http_log_ctx_t *ctx;
ngx_http_trace_ctx_t *tctx;
ngx_str_t traceid, currentid, parentid;
if (log->action) {
p = ngx_snprintf(buf, len, " while %s", log->action);
len -= p - buf;
buf = p;
}
ctx = log->data;
p = ngx_snprintf(buf, len, ", client: %V", &ctx->connection->addr_text);
len -= p - buf;
buf = p;
r = ctx->request;
if (r) {
p = r->log_handler(r, ctx->current_request, p, len);
len -= p - buf;
buf = p;
} else {
p = ngx_snprintf(p, len, ", server: %V",
&ctx->connection->listening->addr_text);
len -= p - buf;
buf = p;
}
tctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (tctx) {
traceid.data = tctx->traceid;
traceid.len = sizeof(tctx->traceid);
currentid.data = tctx->cid;
currentid.len = sizeof(tctx->cid);
parentid.data = tctx->pid;
parentid.len = sizeof(tctx->pid);
p = ngx_snprintf(p, len, ", [NGINX-TRACE] traceid: %V, currentid: %V, "
"parentid: %V [NGINX-TRACE-END]",
&traceid, ¤tid, &parentid);
}
return p;
}
// First request without X-NTM-Traceid X-NTM-Currentid or X-NTM-Parentid
// Need to gen these ids and set X-NTM headers in main request
static ngx_int_t
ngx_http_trace_first_request(ngx_http_request_t *r, ngx_http_trace_ctx_t *ctx)
{
ngx_table_elt_t *h;
ngx_http_trace_genid(ctx->traceid);
ngx_http_trace_genid(ctx->cid);
ngx_sprintf(ctx->pid, "00000000000000000000000000000000");
// Set X-NTM-Traceid
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key.data = (u_char *) "X-NTM-Traceid";
h->key.len = sizeof("X-NTM-Traceid") - 1;
h->value.data = ctx->traceid;
h->value.len = sizeof(ctx->traceid);
h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
if (h->lowcase_key == NULL) {
return NGX_ERROR;
}
h->hash = ngx_hash_strlow(h->lowcase_key, h->key.data, h->key.len);
// Set X-NTM-Currentid
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key.data = (u_char *) "X-NTM-Currentid";
h->key.len = sizeof("X-NTM-Currentid") - 1;
h->value.data = ctx->cid;
h->value.len = sizeof(ctx->cid);
h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
if (h->lowcase_key == NULL) {
return NGX_ERROR;
}
h->hash = ngx_hash_strlow(h->lowcase_key, h->key.data, h->key.len);
// Set X-NTM-Parentid
h = ngx_list_push(&r->headers_in.headers);
if (h == NULL) {
return NGX_ERROR;
}
h->key.data = (u_char *) "X-NTM-Parentid";
h->key.len = sizeof("X-NTM-Parentid") - 1;
h->value.data = ctx->pid;
h->value.len = sizeof(ctx->pid);
h->lowcase_key = ngx_pnalloc(r->pool, h->key.len);
if (h->lowcase_key == NULL) {
return NGX_ERROR;
}
h->hash = ngx_hash_strlow(h->lowcase_key, h->key.data, h->key.len);
return NGX_OK;
}
static ngx_int_t
ngx_http_trace_handler(ngx_http_request_t *r)
{
ngx_http_trace_main_conf_t *tmcf;
ngx_http_trace_ctx_t *ctx;
ngx_http_variable_value_t v;
ngx_str_t header;
if (r != r->main) { // subrequest
return NGX_DECLINED;
}
tmcf = ngx_http_get_module_main_conf(r, ngx_http_trace_module);
if (!tmcf->trace) {
return NGX_DECLINED;
}
ctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (ctx) { // ctx already create, enter twice
return NGX_DECLINED;
}
ctx = ngx_pcalloc(r->pool, sizeof(ngx_http_trace_ctx_t));
if (ctx == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
ngx_http_set_ctx(r, ctx, ngx_http_trace_module);
// traceid currentid parentid log into nginx error log
r->connection->log->handler = ngx_http_trace_log_error;
// Get X-NTM-Debug
header.data = (u_char *) "http_x_ntm_debug";
header.len = sizeof("http_x_ntm_debug") - 1;
ngx_http_variable_unknown_header(&v, &header, &r->headers_in.headers.part,
sizeof("http_") - 1);
if (!v.not_found && v.len == 1 && v.data[0] == '1') {
// Has header X-NTM-Debug: 1
ctx->debug = 1;
}
// Get X-NTM-Traceid
header.data = (u_char *) "http_x_ntm_traceid";
header.len = sizeof("http_x_ntm_traceid") - 1;
ngx_http_variable_unknown_header(&v, &header, &r->headers_in.headers.part,
sizeof("http_") - 1);
if (v.not_found) {
goto notfound;
}
ngx_memcpy(ctx->traceid, v.data, ngx_min(v.len, sizeof(ctx->traceid)));
// Get X-NTM-Currentid
header.data = (u_char *) "http_x_ntm_currentid";
header.len = sizeof("http_x_ntm_currentid") - 1;
ngx_http_variable_unknown_header(&v, &header, &r->headers_in.headers.part,
sizeof("http_") - 1);
if (v.not_found) {
goto notfound;
}
ngx_memcpy(ctx->cid, v.data, ngx_min(v.len, sizeof(ctx->cid)));
// Get X-NTM-Parentid
header.data = (u_char *) "http_x_ntm_parentid";
header.len = sizeof("http_x_ntm_parentid") - 1;
ngx_http_variable_unknown_header(&v, &header, &r->headers_in.headers.part,
sizeof("http_") - 1);
if (v.not_found) {
goto notfound;
}
ngx_memcpy(ctx->pid, v.data, ngx_min(v.len, sizeof(ctx->pid)));
return NGX_DECLINED;
notfound:
if (ngx_http_trace_first_request(r, ctx) != NGX_OK) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
return NGX_DECLINED;
}
static ngx_int_t
ngx_http_trace_traceid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_http_trace_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (ctx == NULL) {
v->not_found = 1;
return NGX_OK;
}
v->data = ctx->traceid;
v->len = sizeof(ctx->traceid);
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_http_trace_currentid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_http_trace_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (ctx == NULL) {
v->not_found = 1;
return NGX_OK;
}
v->data = ctx->cid;
v->len = sizeof(ctx->cid);
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_http_trace_parentid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_http_trace_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (ctx == NULL) {
v->not_found = 1;
return NGX_OK;
}
v->data = ctx->pid;
v->len = sizeof(ctx->pid);
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_http_trace_debug_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_http_trace_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (ctx == NULL) {
v->not_found = 1;
return NGX_OK;
}
if (ctx->debug) {
v->data = (u_char *) "1";
} else {
v->data = (u_char *) "0";
}
v->len = sizeof("1") - 1;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_http_trace_newid_variable(ngx_http_request_t *r,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_http_trace_ctx_t *ctx;
u_char *newid;
ctx = ngx_http_get_module_ctx(r, ngx_http_trace_module);
if (ctx == NULL) {
v->not_found = 1;
return NGX_OK;
}
newid = ngx_pcalloc(r->pool, sizeof(ctx->cid));
if (newid == NULL) {
return NGX_ERROR;
}
// fill newid
ngx_http_trace_genid(newid);
v->data = newid;
v->len = sizeof(ctx->cid);
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static void *
ngx_http_trace_create_main_conf(ngx_conf_t *cf)
{
ngx_http_trace_main_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_http_trace_main_conf_t));
if (conf == NULL) {
return NULL;
}
conf->trace = NGX_CONF_UNSET;
return conf;
}
static char *
ngx_http_trace_init_main_conf(ngx_conf_t *cf, void *conf)
{
ngx_http_trace_main_conf_t *tmcf;
tmcf = conf;
ngx_conf_init_value(tmcf->trace, 0);
return NGX_CONF_OK;
}
static char *
ngx_http_trace(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_trace_main_conf_t *tmcf;
tmcf = conf;
if (tmcf->trace != NGX_CONF_UNSET) {
return "is duplicate";
}
tmcf->trace = 1;
return NGX_CONF_OK;
}
static ngx_int_t
ngx_http_trace_add_variables(ngx_conf_t *cf)
{
ngx_http_variable_t *var, *v;
for (v = ngx_http_trace_vars; v->name.len; v++) {
var = ngx_http_add_variable(cf, &v->name, v->flags);
if (var == NULL) {
return NGX_ERROR;
}
var->get_handler = v->get_handler;
var->data = v->data;
}
return NGX_OK;
}
static ngx_int_t
ngx_http_trace_init(ngx_conf_t *cf)
{
ngx_http_handler_pt *h;
ngx_http_core_main_conf_t *cmcf;
cmcf = ngx_http_conf_get_module_main_conf(cf, ngx_http_core_module);
h = ngx_array_push(&cmcf->phases[NGX_HTTP_POST_READ_PHASE].handlers);
if (h == NULL) {
return NGX_ERROR;
}
*h = ngx_http_trace_handler;
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 21,150 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jqvmap/jquery.vmap.min.js
|
/*!
* JQVMap: jQuery Vector Map Library
* @author JQVMap <[email protected]>
* @version 1.5.1
* @link http://jqvmap.com
* @license https://github.com/manifestinteractive/jqvmap/blob/master/LICENSE
* @builddate 2016/06/02
*/
var VectorCanvas=function(a,b,c){if(this.mode=window.SVGAngle?"svg":"vml",this.params=c,"svg"===this.mode)this.createSvgNode=function(a){return document.createElementNS(this.svgns,a)};else{try{document.namespaces.rvml||document.namespaces.add("rvml","urn:schemas-microsoft-com:vml"),this.createVmlNode=function(a){return document.createElement("<rvml:"+a+' class="rvml">')}}catch(d){this.createVmlNode=function(a){return document.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}document.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)")}"svg"===this.mode?this.canvas=this.createSvgNode("svg"):(this.canvas=this.createVmlNode("group"),this.canvas.style.position="absolute"),this.setSize(a,b)};VectorCanvas.prototype={svgns:"http://www.w3.org/2000/svg",mode:"svg",width:0,height:0,canvas:null};var ColorScale=function(a,b,c,d){a&&this.setColors(a),b&&this.setNormalizeFunction(b),c&&this.setMin(c),c&&this.setMax(d)};ColorScale.prototype={colors:[]};var JQVMap=function(a){a=a||{};var b,c=this,d=JQVMap.maps[a.map];if(!d)throw new Error('Invalid "'+a.map+'" map parameter. Please make sure you have loaded this map file in your HTML.');this.selectedRegions=[],this.multiSelectRegion=a.multiSelectRegion,this.container=a.container,this.defaultWidth=d.width,this.defaultHeight=d.height,this.color=a.color,this.selectedColor=a.selectedColor,this.hoverColor=a.hoverColor,this.hoverColors=a.hoverColors,this.hoverOpacity=a.hoverOpacity,this.setBackgroundColor(a.backgroundColor),this.width=a.container.width(),this.height=a.container.height(),this.resize(),jQuery(window).resize(function(){var d=a.container.width(),e=a.container.height();if(d&&e){c.width=d,c.height=e,c.resize(),c.canvas.setSize(c.width,c.height),c.applyTransform();var f=jQuery.Event("resize.jqvmap");jQuery(a.container).trigger(f,[d,e]),b&&(jQuery(".jqvmap-pin").remove(),c.pinHandlers=!1,c.placePins(b.pins,b.mode))}}),this.canvas=new VectorCanvas(this.width,this.height,a),a.container.append(this.canvas.canvas),this.makeDraggable(),this.rootGroup=this.canvas.createGroup(!0),this.index=JQVMap.mapIndex,this.label=jQuery("<div/>").addClass("jqvmap-label").appendTo(jQuery("body")).hide(),a.enableZoom&&(jQuery("<div/>").addClass("jqvmap-zoomin").text("+").appendTo(a.container),jQuery("<div/>").addClass("jqvmap-zoomout").html("−").appendTo(a.container)),c.countries=[];for(var e in d.paths){var f=this.canvas.createPath({path:d.paths[e].path});f.setFill(this.color),f.id=c.getCountryId(e),c.countries[e]=f,"svg"===this.canvas.mode?f.setAttribute("class","jqvmap-region"):jQuery(f).addClass("jqvmap-region"),jQuery(this.rootGroup).append(f)}if(jQuery(a.container).delegate("svg"===this.canvas.mode?"path":"shape","mouseover mouseout",function(b){var e=b.target,f=b.target.id.split("_").pop(),g=jQuery.Event("labelShow.jqvmap"),h=jQuery.Event("regionMouseOver.jqvmap");f=f.toLowerCase(),"mouseover"===b.type?(jQuery(a.container).trigger(h,[f,d.paths[f].name]),h.isDefaultPrevented()||c.highlight(f,e),a.showTooltip&&(c.label.text(d.paths[f].name),jQuery(a.container).trigger(g,[c.label,f]),g.isDefaultPrevented()||(c.label.show(),c.labelWidth=c.label.width(),c.labelHeight=c.label.height()))):(c.unhighlight(f,e),c.label.hide(),jQuery(a.container).trigger("regionMouseOut.jqvmap",[f,d.paths[f].name]))}),jQuery(a.container).delegate("svg"===this.canvas.mode?"path":"shape","click",function(b){var e=b.target,f=b.target.id.split("_").pop(),g=jQuery.Event("regionClick.jqvmap");if(f=f.toLowerCase(),jQuery(a.container).trigger(g,[f,d.paths[f].name]),!a.multiSelectRegion&&!g.isDefaultPrevented())for(var h in d.paths)c.countries[h].currentFillColor=c.countries[h].getOriginalFill(),c.countries[h].setFill(c.countries[h].getOriginalFill());g.isDefaultPrevented()||(c.isSelected(f)?c.deselect(f,e):c.select(f,e))}),a.showTooltip&&a.container.mousemove(function(a){if(c.label.is(":visible")){var b=a.pageX-15-c.labelWidth,d=a.pageY-15-c.labelHeight;0>b&&(b=a.pageX+15),0>d&&(d=a.pageY+15),c.label.css({left:b,top:d})}}),this.setColors(a.colors),this.canvas.canvas.appendChild(this.rootGroup),this.applyTransform(),this.colorScale=new ColorScale(a.scaleColors,a.normalizeFunction,a.valueMin,a.valueMax),a.values&&(this.values=a.values,this.setValues(a.values)),a.selectedRegions)if(a.selectedRegions instanceof Array)for(var g in a.selectedRegions)this.select(a.selectedRegions[g].toLowerCase());else this.select(a.selectedRegions.toLowerCase());if(this.bindZoomButtons(),a.pins&&(b={pins:a.pins,mode:a.pinMode},this.pinHandlers=!1,this.placePins(a.pins,a.pinMode)),a.showLabels){this.pinHandlers=!1;var h={};for(e in c.countries)"function"!=typeof c.countries[e]&&(a.pins&&a.pins[e]||(h[e]=e.toUpperCase()));b={pins:h,mode:"content"},this.placePins(h,"content")}JQVMap.mapIndex++};JQVMap.prototype={transX:0,transY:0,scale:1,baseTransX:0,baseTransY:0,baseScale:1,width:0,height:0,countries:{},countriesColors:{},countriesData:{},zoomStep:1.4,zoomMaxStep:4,zoomCurStep:1},JQVMap.xlink="http://www.w3.org/1999/xlink",JQVMap.mapIndex=1,JQVMap.maps={},function(){var a={colors:1,values:1,backgroundColor:1,scaleColors:1,normalizeFunction:1,enableZoom:1,showTooltip:1,borderColor:1,borderWidth:1,borderOpacity:1,selectedRegions:1,multiSelectRegion:1},b={onLabelShow:"labelShow",onLoad:"load",onRegionOver:"regionMouseOver",onRegionOut:"regionMouseOut",onRegionClick:"regionClick",onRegionSelect:"regionSelect",onRegionDeselect:"regionDeselect",onResize:"resize"};jQuery.fn.vectorMap=function(c){var d={map:"world_en",backgroundColor:"#a5bfdd",color:"#f4f3f0",hoverColor:"#c9dfaf",hoverColors:{},selectedColor:"#c9dfaf",scaleColors:["#b6d6ff","#005ace"],normalizeFunction:"linear",enableZoom:!0,showTooltip:!0,borderColor:"#818181",borderWidth:1,borderOpacity:.25,selectedRegions:null,multiSelectRegion:!1},e=this.data("mapObject");if("addMap"===c)JQVMap.maps[arguments[1]]=arguments[2];else{if("set"!==c||!a[arguments[1]]){if("string"==typeof c&&"function"==typeof e[c])return e[c].apply(e,Array.prototype.slice.call(arguments,1));jQuery.extend(d,c),d.container=this,this.css({position:"relative",overflow:"hidden"}),e=new JQVMap(d),this.data("mapObject",e),this.unbind(".jqvmap");for(var f in b)d[f]&&this.bind(b[f]+".jqvmap",d[f]);var g=jQuery.Event("load.jqvmap");return jQuery(d.container).trigger(g,e),e}e["set"+arguments[1].charAt(0).toUpperCase()+arguments[1].substr(1)].apply(e,Array.prototype.slice.call(arguments,2))}}}(jQuery),ColorScale.arrayToRgb=function(a){for(var b,c="#",d=0;d<a.length;d++)b=a[d].toString(16),c+=1===b.length?"0"+b:b;return c},ColorScale.prototype.getColor=function(a){"function"==typeof this.normalize&&(a=this.normalize(a));for(var b,c=[],d=0,e=0;e<this.colors.length-1;e++)b=this.vectorLength(this.vectorSubtract(this.colors[e+1],this.colors[e])),c.push(b),d+=b;var f=(this.maxValue-this.minValue)/d;for(e=0;e<c.length;e++)c[e]*=f;for(e=0,a-=this.minValue;a-c[e]>=0;)a-=c[e],e++;var g;for(g=e===this.colors.length-1?this.vectorToNum(this.colors[e]).toString(16):this.vectorToNum(this.vectorAdd(this.colors[e],this.vectorMult(this.vectorSubtract(this.colors[e+1],this.colors[e]),a/c[e]))).toString(16);g.length<6;)g="0"+g;return"#"+g},ColorScale.rgbToArray=function(a){return a=a.substr(1),[parseInt(a.substr(0,2),16),parseInt(a.substr(2,2),16),parseInt(a.substr(4,2),16)]},ColorScale.prototype.setColors=function(a){for(var b=0;b<a.length;b++)a[b]=ColorScale.rgbToArray(a[b]);this.colors=a},ColorScale.prototype.setMax=function(a){this.clearMaxValue=a,"function"==typeof this.normalize?this.maxValue=this.normalize(a):this.maxValue=a},ColorScale.prototype.setMin=function(a){this.clearMinValue=a,"function"==typeof this.normalize?this.minValue=this.normalize(a):this.minValue=a},ColorScale.prototype.setNormalizeFunction=function(a){"polynomial"===a?this.normalize=function(a){return Math.pow(a,.2)}:"linear"===a?delete this.normalize:this.normalize=a,this.setMin(this.clearMinValue),this.setMax(this.clearMaxValue)},ColorScale.prototype.vectorAdd=function(a,b){for(var c=[],d=0;d<a.length;d++)c[d]=a[d]+b[d];return c},ColorScale.prototype.vectorLength=function(a){for(var b=0,c=0;c<a.length;c++)b+=a[c]*a[c];return Math.sqrt(b)},ColorScale.prototype.vectorMult=function(a,b){for(var c=[],d=0;d<a.length;d++)c[d]=a[d]*b;return c},ColorScale.prototype.vectorSubtract=function(a,b){for(var c=[],d=0;d<a.length;d++)c[d]=a[d]-b[d];return c},ColorScale.prototype.vectorToNum=function(a){for(var b=0,c=0;c<a.length;c++)b+=Math.round(a[c])*Math.pow(256,a.length-c-1);return b},JQVMap.prototype.applyTransform=function(){var a,b,c,d;this.defaultWidth*this.scale<=this.width?(a=(this.width-this.defaultWidth*this.scale)/(2*this.scale),c=(this.width-this.defaultWidth*this.scale)/(2*this.scale)):(a=0,c=(this.width-this.defaultWidth*this.scale)/this.scale),this.defaultHeight*this.scale<=this.height?(b=(this.height-this.defaultHeight*this.scale)/(2*this.scale),d=(this.height-this.defaultHeight*this.scale)/(2*this.scale)):(b=0,d=(this.height-this.defaultHeight*this.scale)/this.scale),this.transY>b?this.transY=b:this.transY<d&&(this.transY=d),this.transX>a?this.transX=a:this.transX<c&&(this.transX=c),this.canvas.applyTransformParams(this.scale,this.transX,this.transY)},JQVMap.prototype.bindZoomButtons=function(){var a=this;this.container.find(".jqvmap-zoomin").click(function(){a.zoomIn()}),this.container.find(".jqvmap-zoomout").click(function(){a.zoomOut()})},JQVMap.prototype.deselect=function(a,b){if(a=a.toLowerCase(),b=b||jQuery("#"+this.getCountryId(a))[0],this.isSelected(a))this.selectedRegions.splice(this.selectIndex(a),1),jQuery(this.container).trigger("regionDeselect.jqvmap",[a]),b.currentFillColor=b.getOriginalFill(),b.setFill(b.getOriginalFill());else for(var c in this.countries)this.selectedRegions.splice(this.selectedRegions.indexOf(c),1),this.countries[c].currentFillColor=this.color,this.countries[c].setFill(this.color)},JQVMap.prototype.getCountryId=function(a){return"jqvmap"+this.index+"_"+a},JQVMap.prototype.getPin=function(a){var b=jQuery("#"+this.getPinId(a));return b.html()},JQVMap.prototype.getPinId=function(a){return this.getCountryId(a)+"_pin"},JQVMap.prototype.getPins=function(){var a=this.container.find(".jqvmap-pin"),b={};return jQuery.each(a,function(a,c){c=jQuery(c);var d=c.attr("for").toLowerCase(),e=c.html();b[d]=e}),JSON.stringify(b)},JQVMap.prototype.highlight=function(a,b){b=b||jQuery("#"+this.getCountryId(a))[0],this.hoverOpacity?b.setOpacity(this.hoverOpacity):this.hoverColors&&a in this.hoverColors?(b.currentFillColor=b.getFill()+"",b.setFill(this.hoverColors[a])):this.hoverColor&&(b.currentFillColor=b.getFill()+"",b.setFill(this.hoverColor))},JQVMap.prototype.isSelected=function(a){return this.selectIndex(a)>=0},JQVMap.prototype.makeDraggable=function(){var a,b,c=!1,d=this;d.isMoving=!1,d.isMovingTimeout=!1;var e,f,g,h,i,j,k;this.container.mousemove(function(e){return c&&(d.transX-=(a-e.pageX)/d.scale,d.transY-=(b-e.pageY)/d.scale,d.applyTransform(),a=e.pageX,b=e.pageY,d.isMoving=!0,d.isMovingTimeout&&clearTimeout(d.isMovingTimeout),d.container.trigger("drag")),!1}).mousedown(function(d){return c=!0,a=d.pageX,b=d.pageY,!1}).mouseup(function(){return c=!1,clearTimeout(d.isMovingTimeout),d.isMovingTimeout=setTimeout(function(){d.isMoving=!1},100),!1}).mouseout(function(){return c&&d.isMoving?(clearTimeout(d.isMovingTimeout),d.isMovingTimeout=setTimeout(function(){c=!1,d.isMoving=!1},100),!1):void 0}),jQuery(this.container).bind("touchmove",function(a){var b,c,l,m,n=a.originalEvent.touches;if(1===n.length){if(1===e){if(j===n[0].pageX&&k===n[0].pageY)return;l=d.transX,m=d.transY,d.transX-=(j-n[0].pageX)/d.scale,d.transY-=(k-n[0].pageY)/d.scale,d.applyTransform(),(l!==d.transX||m!==d.transY)&&a.preventDefault(),d.isMoving=!0,d.isMovingTimeout&&clearTimeout(d.isMovingTimeout)}j=n[0].pageX,k=n[0].pageY}else 2===n.length&&(2===e?(c=Math.sqrt(Math.pow(n[0].pageX-n[1].pageX,2)+Math.pow(n[0].pageY-n[1].pageY,2))/h,d.setScale(i*c,f,g),a.preventDefault()):(b=jQuery(d.container).offset(),f=n[0].pageX>n[1].pageX?n[1].pageX+(n[0].pageX-n[1].pageX)/2:n[0].pageX+(n[1].pageX-n[0].pageX)/2,g=n[0].pageY>n[1].pageY?n[1].pageY+(n[0].pageY-n[1].pageY)/2:n[0].pageY+(n[1].pageY-n[0].pageY)/2,f-=b.left,g-=b.top,i=d.scale,h=Math.sqrt(Math.pow(n[0].pageX-n[1].pageX,2)+Math.pow(n[0].pageY-n[1].pageY,2))));e=n.length}),jQuery(this.container).bind("touchstart",function(){e=0}),jQuery(this.container).bind("touchend",function(){e=0})},JQVMap.prototype.placePins=function(a,b){var c=this;if((!b||"content"!==b&&"id"!==b)&&(b="content"),"content"===b?jQuery.each(a,function(a,b){if(0!==jQuery("#"+c.getCountryId(a)).length){var d=c.getPinId(a),e=jQuery("#"+d);e.length>0&&e.remove(),c.container.append('<div id="'+d+'" for="'+a+'" class="jqvmap-pin" style="position:absolute">'+b+"</div>")}}):jQuery.each(a,function(a,b){if(0!==jQuery("#"+c.getCountryId(a)).length){var d=c.getPinId(a),e=jQuery("#"+d);e.length>0&&e.remove(),c.container.append('<div id="'+d+'" for="'+a+'" class="jqvmap-pin" style="position:absolute"></div>'),e.append(jQuery("#"+b))}}),this.positionPins(),!this.pinHandlers){this.pinHandlers=!0;var d=function(){c.positionPins()};this.container.bind("zoomIn",d).bind("zoomOut",d).bind("drag",d)}},JQVMap.prototype.positionPins=function(){var a=this,b=this.container.find(".jqvmap-pin");jQuery.each(b,function(b,c){c=jQuery(c);var d=a.getCountryId(c.attr("for").toLowerCase()),e=jQuery("#"+d),f=e[0].getBBox(),g=a.scale,h=a.canvas.rootGroup.getBoundingClientRect(),i=a.container[0].getBoundingClientRect(),j={left:h.left-i.left,top:h.top-i.top},k=f.x*g+f.width*g/2,l=f.y*g+f.height*g/2;c.css({left:j.left+k-c.width()/2,top:j.top+l-c.height()/2})})},JQVMap.prototype.removePin=function(a){a=a.toLowerCase(),jQuery("#"+this.getPinId(a)).remove()},JQVMap.prototype.removePins=function(){this.container.find(".jqvmap-pin").remove()},JQVMap.prototype.reset=function(){for(var a in this.countries)this.countries[a].setFill(this.color);this.scale=this.baseScale,this.transX=this.baseTransX,this.transY=this.baseTransY,this.applyTransform()},JQVMap.prototype.resize=function(){var a=this.baseScale;this.width/this.height>this.defaultWidth/this.defaultHeight?(this.baseScale=this.height/this.defaultHeight,this.baseTransX=Math.abs(this.width-this.defaultWidth*this.baseScale)/(2*this.baseScale)):(this.baseScale=this.width/this.defaultWidth,this.baseTransY=Math.abs(this.height-this.defaultHeight*this.baseScale)/(2*this.baseScale)),this.scale*=this.baseScale/a,this.transX*=this.baseScale/a,this.transY*=this.baseScale/a},JQVMap.prototype.select=function(a,b){a=a.toLowerCase(),b=b||jQuery("#"+this.getCountryId(a))[0],this.isSelected(a)||(this.multiSelectRegion?this.selectedRegions.push(a):this.selectedRegions=[a],jQuery(this.container).trigger("regionSelect.jqvmap",[a]),this.selectedColor&&b&&(b.currentFillColor=this.selectedColor,b.setFill(this.selectedColor)))},JQVMap.prototype.selectIndex=function(a){a=a.toLowerCase();for(var b=0;b<this.selectedRegions.length;b++)if(a===this.selectedRegions[b])return b;return-1},JQVMap.prototype.setBackgroundColor=function(a){this.container.css("background-color",a)},JQVMap.prototype.setColors=function(a,b){if("string"==typeof a)this.countries[a].setFill(b),this.countries[a].setAttribute("original",b);else{var c=a;for(var d in c)this.countries[d]&&(this.countries[d].setFill(c[d]),this.countries[d].setAttribute("original",c[d]))}},JQVMap.prototype.setNormalizeFunction=function(a){this.colorScale.setNormalizeFunction(a),this.values&&this.setValues(this.values)},JQVMap.prototype.setScale=function(a){this.scale=a,this.applyTransform()},JQVMap.prototype.setScaleColors=function(a){this.colorScale.setColors(a),this.values&&this.setValues(this.values)},JQVMap.prototype.setValues=function(a){var b,c=0,d=Number.MAX_VALUE;for(var e in a)e=e.toLowerCase(),b=parseFloat(a[e]),isNaN(b)||(b>c&&(c=a[e]),d>b&&(d=b));d===c&&c++,this.colorScale.setMin(d),this.colorScale.setMax(c);var f={};for(e in a)e=e.toLowerCase(),b=parseFloat(a[e]),f[e]=isNaN(b)?this.color:this.colorScale.getColor(b);this.setColors(f),this.values=a},JQVMap.prototype.unhighlight=function(a,b){a=a.toLowerCase(),b=b||jQuery("#"+this.getCountryId(a))[0],b.setOpacity(1),b.currentFillColor&&b.setFill(b.currentFillColor)},JQVMap.prototype.zoomIn=function(){var a=this,b=(jQuery("#zoom").innerHeight()-12-30-6-7-6)/(this.zoomMaxStep-this.zoomCurStep);if(a.zoomCurStep<a.zoomMaxStep){a.transX-=(a.width/a.scale-a.width/(a.scale*a.zoomStep))/2,a.transY-=(a.height/a.scale-a.height/(a.scale*a.zoomStep))/2,a.setScale(a.scale*a.zoomStep),a.zoomCurStep++;var c=jQuery("#zoomSlider");c.css("top",parseInt(c.css("top"),10)-b),a.container.trigger("zoomIn")}},JQVMap.prototype.zoomOut=function(){var a=this,b=(jQuery("#zoom").innerHeight()-12-30-6-7-6)/(this.zoomMaxStep-this.zoomCurStep);if(a.zoomCurStep>1){a.transX+=(a.width/(a.scale/a.zoomStep)-a.width/a.scale)/2,a.transY+=(a.height/(a.scale/a.zoomStep)-a.height/a.scale)/2,a.setScale(a.scale/a.zoomStep),a.zoomCurStep--;var c=jQuery("#zoomSlider");c.css("top",parseInt(c.css("top"),10)+b),a.container.trigger("zoomOut")}},VectorCanvas.prototype.applyTransformParams=function(a,b,c){"svg"===this.mode?this.rootGroup.setAttribute("transform","scale("+a+") translate("+b+", "+c+")"):(this.rootGroup.coordorigin=this.width-b+","+(this.height-c),this.rootGroup.coordsize=this.width/a+","+this.height/a)},VectorCanvas.prototype.createGroup=function(a){var b;return"svg"===this.mode?b=this.createSvgNode("g"):(b=this.createVmlNode("group"),b.style.width=this.width+"px",b.style.height=this.height+"px",b.style.left="0px",b.style.top="0px",b.coordorigin="0 0",b.coordsize=this.width+" "+this.height),a&&(this.rootGroup=b),b},VectorCanvas.prototype.createPath=function(a){var b;if("svg"===this.mode)b=this.createSvgNode("path"),b.setAttribute("d",a.path),null!==this.params.borderColor&&b.setAttribute("stroke",this.params.borderColor),this.params.borderWidth>0&&(b.setAttribute("stroke-width",this.params.borderWidth),b.setAttribute("stroke-linecap","round"),b.setAttribute("stroke-linejoin","round")),this.params.borderOpacity>0&&b.setAttribute("stroke-opacity",this.params.borderOpacity),b.setFill=function(a){this.setAttribute("fill",a),null===this.getAttribute("original")&&this.setAttribute("original",a)},b.getFill=function(){return this.getAttribute("fill")},b.getOriginalFill=function(){return this.getAttribute("original")},b.setOpacity=function(a){this.setAttribute("fill-opacity",a)};else{b=this.createVmlNode("shape"),b.coordorigin="0 0",b.coordsize=this.width+" "+this.height,b.style.width=this.width+"px",b.style.height=this.height+"px",b.fillcolor=JQVMap.defaultFillColor,b.stroked=!1,b.path=VectorCanvas.pathSvgToVml(a.path);var c=this.createVmlNode("skew");c.on=!0,c.matrix="0.01,0,0,0.01,0,0",c.offset="0,0",b.appendChild(c);var d=this.createVmlNode("fill");b.appendChild(d),b.setFill=function(a){this.getElementsByTagName("fill")[0].color=a,null===this.getAttribute("original")&&this.setAttribute("original",a)},b.getFill=function(){return this.getElementsByTagName("fill")[0].color},b.getOriginalFill=function(){return this.getAttribute("original")},b.setOpacity=function(a){this.getElementsByTagName("fill")[0].opacity=parseInt(100*a,10)+"%"}}return b},VectorCanvas.prototype.pathSvgToVml=function(a){var b,c,d="",e=0,f=0;return a.replace(/([MmLlHhVvCcSs])((?:-?(?:\d+)?(?:\.\d+)?,?\s?)+)/g,function(a,g,h){h=h.replace(/(\d)-/g,"$1,-").replace(/\s+/g,",").split(","),h[0]||h.shift();for(var i=0,j=h.length;j>i;i++)h[i]=Math.round(100*h[i]);switch(g){case"m":e+=h[0],f+=h[1],d="t"+h.join(",");break;case"M":e=h[0],f=h[1],d="m"+h.join(",");break;case"l":e+=h[0],f+=h[1],d="r"+h.join(",");break;case"L":e=h[0],f=h[1],d="l"+h.join(",");break;case"h":e+=h[0],d="r"+h[0]+",0";break;case"H":e=h[0],d="l"+e+","+f;break;case"v":f+=h[0],d="r0,"+h[0];break;case"V":f=h[0],d="l"+e+","+f;break;case"c":b=e+h[h.length-4],c=f+h[h.length-3],e+=h[h.length-2],f+=h[h.length-1],d="v"+h.join(",");break;case"C":b=h[h.length-4],c=h[h.length-3],e=h[h.length-2],f=h[h.length-1],d="c"+h.join(",");break;case"s":h.unshift(f-c),h.unshift(e-b),b=e+h[h.length-4],c=f+h[h.length-3],e+=h[h.length-2],f+=h[h.length-1],d="v"+h.join(",");break;case"S":h.unshift(f+f-c),h.unshift(e+e-b),b=h[h.length-4],c=h[h.length-3],e=h[h.length-2],f=h[h.length-1],d="c"+h.join(",")}return d}).replace(/z/g,"")},VectorCanvas.prototype.setSize=function(a,b){if("svg"===this.mode)this.canvas.setAttribute("width",a),this.canvas.setAttribute("height",b);else if(this.canvas.style.width=a+"px",this.canvas.style.height=b+"px",this.canvas.coordsize=a+" "+b,this.canvas.coordorigin="0 0",this.rootGroup){for(var c=this.rootGroup.getElementsByTagName("shape"),d=0,e=c.length;e>d;d++)c[d].coordsize=a+" "+b,c[d].style.width=a+"px",c[d].style.height=b+"px";this.rootGroup.coordsize=a+" "+b,this.rootGroup.style.width=a+"px",this.rootGroup.style.height=b+"px"}this.width=a,this.height=b};
|
281677160/openwrt-package
| 7,268 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_event_resolver.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_event_resolver.h"
static void *ngx_event_resolver_create_conf(ngx_cycle_t *cycle);
static char *ngx_event_resolver_init_conf(ngx_cycle_t *cycle, void *conf);
static char *ngx_event_resolver(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
typedef struct ngx_event_resolver_ctx_s ngx_event_resolver_ctx_t;
struct ngx_event_resolver_ctx_s {
ngx_event_resolver_handler_pt handler;
void *data;
ngx_event_resolver_ctx_t *next;
};
typedef struct {
ngx_msec_t resolver_timeout;
ngx_resolver_t *resolver;
ngx_event_resolver_ctx_t *free_ctx;
ngx_uint_t nalloc;
ngx_uint_t nfree;
} ngx_event_resolver_conf_t;
static ngx_str_t event_resolver_name = ngx_string("event_resolver");
static ngx_command_t ngx_event_resolver_commands[] = {
{ ngx_string("resolver"),
NGX_EVENT_CONF|NGX_CONF_1MORE,
ngx_event_resolver,
0,
0,
NULL },
{ ngx_string("resolver_timeout"),
NGX_EVENT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
0,
offsetof(ngx_event_resolver_conf_t, resolver_timeout),
NULL },
ngx_null_command
};
ngx_event_module_t ngx_event_resolver_module_ctx = {
&event_resolver_name,
ngx_event_resolver_create_conf, /* create configuration */
ngx_event_resolver_init_conf, /* init configuration */
{ NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
};
/* this module use ngx_cycle->log */
ngx_module_t ngx_event_resolver_module = {
NGX_MODULE_V1,
&ngx_event_resolver_module_ctx, /* module context */
ngx_event_resolver_commands, /* module directives */
NGX_EVENT_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_event_resolver_create_conf(ngx_cycle_t *cycle)
{
ngx_event_resolver_conf_t *conf;
conf = ngx_pcalloc(cycle->pool, sizeof(ngx_event_resolver_conf_t));
if (conf == NULL) {
return NULL;
}
conf->resolver_timeout = NGX_CONF_UNSET_MSEC;
return conf;
}
static char *
ngx_event_resolver_init_conf(ngx_cycle_t *cycle, void *conf)
{
ngx_event_resolver_conf_t *ercf = conf;
ngx_conf_init_msec_value(ercf->resolver_timeout, 60000);
return NGX_CONF_OK;
}
static char *
ngx_event_resolver(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_event_resolver_conf_t *ercf = conf;
ngx_str_t *value;
if (ercf->resolver) {
return "is duplicate";
}
value = cf->args->elts;
ercf->resolver = ngx_resolver_create(cf, &value[1], cf->args->nelts - 1);
if (ercf->resolver == NULL) {
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static ngx_event_resolver_ctx_t *
ngx_event_resolver_get_ctx()
{
ngx_event_resolver_ctx_t *ctx;
ngx_event_resolver_conf_t *ercf;
ercf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_resolver_module);
ctx = ercf->free_ctx;
if (ctx == NULL) {
ctx = ngx_pcalloc(ngx_cycle->pool, sizeof(ngx_event_resolver_ctx_t));
++ercf->nalloc;
} else {
ercf->free_ctx = ctx->next;
ctx->next = NULL;
--ercf->nfree;
}
return ctx;
}
static void
ngx_event_resolver_put_ctx(ngx_event_resolver_ctx_t *ctx)
{
ngx_event_resolver_conf_t *ercf;
ercf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_resolver_module);
ctx->next = ercf->free_ctx;
ercf->free_ctx = ctx;
++ercf->nfree;
}
static void
ngx_event_resolver_handler(ngx_resolver_ctx_t *ctx)
{
ngx_event_resolver_ctx_t *erctx;
erctx = ctx->data;
if (ctx->state) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"event resolver, domain '%V' could not be resolved (%i: %s)",
&ctx->name, ctx->state, ngx_resolver_strerror(ctx->state));
erctx->handler(erctx->data, NULL, 0);
goto failed;
}
erctx->handler(erctx->data, ctx->addrs, ctx->naddrs);
failed:
ngx_resolve_name_done(ctx);
ngx_event_resolver_put_ctx(erctx);
}
void
ngx_event_resolver_start_resolver(ngx_str_t *domain,
ngx_event_resolver_handler_pt h, void *data)
{
ngx_event_resolver_conf_t *ercf;
ngx_event_resolver_ctx_t *erctx;
ngx_resolver_ctx_t *ctx, temp;
ercf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_resolver_module);
ngx_log_debug1(NGX_LOG_DEBUG_CORE, ngx_cycle->log, 0, "event resolver, "
"start resolv domain '%V'", domain);
if (ercf->resolver == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "event resolver, "
"resolver does not configured");
h(data, NULL, 0);
return;
}
temp.name = *domain;
erctx = ngx_event_resolver_get_ctx();
if (erctx == NULL) {
return;
}
erctx->handler = h;
erctx->data = data;
ctx = ngx_resolve_start(ercf->resolver, &temp);
if (ctx == NULL) {
goto failed;
}
if (ctx == NGX_NO_RESOLVER) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "event resolver, "
"no resolver defined to resolv %V", domain);
goto failed;
}
ctx->name = *domain;
ctx->handler = ngx_event_resolver_handler;
ctx->data = erctx;
ctx->timeout = ercf->resolver_timeout;
if (ngx_resolve_name(ctx) != NGX_OK) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "event resolver, "
"resolv %V failed", domain);
goto failed;
}
return;
failed:
h(data, NULL, 0);
if (ctx == NULL || ctx == NGX_NO_RESOLVER) {
ngx_resolve_name_done(ctx);
ngx_event_resolver_put_ctx(erctx);
}
}
ngx_chain_t *
ngx_event_resolver_state(ngx_http_request_t *r)
{
ngx_event_resolver_conf_t *ercf;
ngx_chain_t *cl;
ngx_buf_t *b;
size_t len;
ercf = ngx_event_get_conf(ngx_cycle->conf_ctx, ngx_event_resolver_module);
len = sizeof("##########event resolver state##########\n") - 1
+ sizeof("ngx_event_resolver alloc: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_event_resolver free: \n") - 1 + NGX_OFF_T_LEN;
cl = ngx_alloc_chain_link(r->pool);
if (cl == NULL) {
return NULL;
}
cl->next = NULL;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL) {
return NULL;
}
cl->buf = b;
b->last = ngx_snprintf(b->last, len,
"##########event resolver state##########\n"
"ngx_event_resolver alloc: %ui\nngx_event_resolver free: %ui\n",
ercf->nalloc, ercf->nfree);
return cl;
}
|
2881099/FreeSql.AdminLTE
| 34,341 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/jqvmap/jquery.vmap.js
|
/*!
* JQVMap: jQuery Vector Map Library
* @author JQVMap <[email protected]>
* @version 1.5.1
* @link http://jqvmap.com
* @license https://github.com/manifestinteractive/jqvmap/blob/master/LICENSE
* @builddate 2016/06/02
*/
var VectorCanvas = function (width, height, params) {
this.mode = window.SVGAngle ? 'svg' : 'vml';
this.params = params;
if (this.mode === 'svg') {
this.createSvgNode = function (nodeName) {
return document.createElementNS(this.svgns, nodeName);
};
} else {
try {
if (!document.namespaces.rvml) {
document.namespaces.add('rvml', 'urn:schemas-microsoft-com:vml');
}
this.createVmlNode = function (tagName) {
return document.createElement('<rvml:' + tagName + ' class="rvml">');
};
} catch (e) {
this.createVmlNode = function (tagName) {
return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
};
}
document.createStyleSheet().addRule('.rvml', 'behavior:url(#default#VML)');
}
if (this.mode === 'svg') {
this.canvas = this.createSvgNode('svg');
} else {
this.canvas = this.createVmlNode('group');
this.canvas.style.position = 'absolute';
}
this.setSize(width, height);
};
VectorCanvas.prototype = {
svgns: 'http://www.w3.org/2000/svg',
mode: 'svg',
width: 0,
height: 0,
canvas: null
};
var ColorScale = function (colors, normalizeFunction, minValue, maxValue) {
if (colors) {
this.setColors(colors);
}
if (normalizeFunction) {
this.setNormalizeFunction(normalizeFunction);
}
if (minValue) {
this.setMin(minValue);
}
if (minValue) {
this.setMax(maxValue);
}
};
ColorScale.prototype = {
colors: []
};
var JQVMap = function (params) {
params = params || {};
var map = this;
var mapData = JQVMap.maps[params.map];
var mapPins;
if( !mapData){
throw new Error('Invalid "' + params.map + '" map parameter. Please make sure you have loaded this map file in your HTML.');
}
this.selectedRegions = [];
this.multiSelectRegion = params.multiSelectRegion;
this.container = params.container;
this.defaultWidth = mapData.width;
this.defaultHeight = mapData.height;
this.color = params.color;
this.selectedColor = params.selectedColor;
this.hoverColor = params.hoverColor;
this.hoverColors = params.hoverColors;
this.hoverOpacity = params.hoverOpacity;
this.setBackgroundColor(params.backgroundColor);
this.width = params.container.width();
this.height = params.container.height();
this.resize();
jQuery(window).resize(function () {
var newWidth = params.container.width();
var newHeight = params.container.height();
if(newWidth && newHeight){
map.width = newWidth;
map.height = newHeight;
map.resize();
map.canvas.setSize(map.width, map.height);
map.applyTransform();
var resizeEvent = jQuery.Event('resize.jqvmap');
jQuery(params.container).trigger(resizeEvent, [newWidth, newHeight]);
if(mapPins){
jQuery('.jqvmap-pin').remove();
map.pinHandlers = false;
map.placePins(mapPins.pins, mapPins.mode);
}
}
});
this.canvas = new VectorCanvas(this.width, this.height, params);
params.container.append(this.canvas.canvas);
this.makeDraggable();
this.rootGroup = this.canvas.createGroup(true);
this.index = JQVMap.mapIndex;
this.label = jQuery('<div/>').addClass('jqvmap-label').appendTo(jQuery('body')).hide();
if (params.enableZoom) {
jQuery('<div/>').addClass('jqvmap-zoomin').text('+').appendTo(params.container);
jQuery('<div/>').addClass('jqvmap-zoomout').html('−').appendTo(params.container);
}
map.countries = [];
for (var key in mapData.paths) {
var path = this.canvas.createPath({
path: mapData.paths[key].path
});
path.setFill(this.color);
path.id = map.getCountryId(key);
map.countries[key] = path;
if (this.canvas.mode === 'svg') {
path.setAttribute('class', 'jqvmap-region');
} else {
jQuery(path).addClass('jqvmap-region');
}
jQuery(this.rootGroup).append(path);
}
jQuery(params.container).delegate(this.canvas.mode === 'svg' ? 'path' : 'shape', 'mouseover mouseout', function (e) {
var containerPath = e.target,
code = e.target.id.split('_').pop(),
labelShowEvent = jQuery.Event('labelShow.jqvmap'),
regionMouseOverEvent = jQuery.Event('regionMouseOver.jqvmap');
code = code.toLowerCase();
if (e.type === 'mouseover') {
jQuery(params.container).trigger(regionMouseOverEvent, [code, mapData.paths[code].name]);
if (!regionMouseOverEvent.isDefaultPrevented()) {
map.highlight(code, containerPath);
}
if (params.showTooltip) {
map.label.text(mapData.paths[code].name);
jQuery(params.container).trigger(labelShowEvent, [map.label, code]);
if (!labelShowEvent.isDefaultPrevented()) {
map.label.show();
map.labelWidth = map.label.width();
map.labelHeight = map.label.height();
}
}
} else {
map.unhighlight(code, containerPath);
map.label.hide();
jQuery(params.container).trigger('regionMouseOut.jqvmap', [code, mapData.paths[code].name]);
}
});
jQuery(params.container).delegate(this.canvas.mode === 'svg' ? 'path' : 'shape', 'click', function (regionClickEvent) {
var targetPath = regionClickEvent.target;
var code = regionClickEvent.target.id.split('_').pop();
var mapClickEvent = jQuery.Event('regionClick.jqvmap');
code = code.toLowerCase();
jQuery(params.container).trigger(mapClickEvent, [code, mapData.paths[code].name]);
if ( !params.multiSelectRegion && !mapClickEvent.isDefaultPrevented()) {
for (var keyPath in mapData.paths) {
map.countries[keyPath].currentFillColor = map.countries[keyPath].getOriginalFill();
map.countries[keyPath].setFill(map.countries[keyPath].getOriginalFill());
}
}
if ( !mapClickEvent.isDefaultPrevented()) {
if (map.isSelected(code)) {
map.deselect(code, targetPath);
} else {
map.select(code, targetPath);
}
}
});
if (params.showTooltip) {
params.container.mousemove(function (e) {
if (map.label.is(':visible')) {
var left = e.pageX - 15 - map.labelWidth;
var top = e.pageY - 15 - map.labelHeight;
if(left < 0) {
left = e.pageX + 15;
}
if(top < 0) {
top = e.pageY + 15;
}
map.label.css({
left: left,
top: top
});
}
});
}
this.setColors(params.colors);
this.canvas.canvas.appendChild(this.rootGroup);
this.applyTransform();
this.colorScale = new ColorScale(params.scaleColors, params.normalizeFunction, params.valueMin, params.valueMax);
if (params.values) {
this.values = params.values;
this.setValues(params.values);
}
if (params.selectedRegions) {
if (params.selectedRegions instanceof Array) {
for(var k in params.selectedRegions) {
this.select(params.selectedRegions[k].toLowerCase());
}
} else {
this.select(params.selectedRegions.toLowerCase());
}
}
this.bindZoomButtons();
if(params.pins) {
mapPins = {
pins: params.pins,
mode: params.pinMode
};
this.pinHandlers = false;
this.placePins(params.pins, params.pinMode);
}
if(params.showLabels){
this.pinHandlers = false;
var pins = {};
for (key in map.countries){
if (typeof map.countries[key] !== 'function') {
if( !params.pins || !params.pins[key] ){
pins[key] = key.toUpperCase();
}
}
}
mapPins = {
pins: pins,
mode: 'content'
};
this.placePins(pins, 'content');
}
JQVMap.mapIndex++;
};
JQVMap.prototype = {
transX: 0,
transY: 0,
scale: 1,
baseTransX: 0,
baseTransY: 0,
baseScale: 1,
width: 0,
height: 0,
countries: {},
countriesColors: {},
countriesData: {},
zoomStep: 1.4,
zoomMaxStep: 4,
zoomCurStep: 1
};
JQVMap.xlink = 'http://www.w3.org/1999/xlink';
JQVMap.mapIndex = 1;
JQVMap.maps = {};
(function(){
var apiParams = {
colors: 1,
values: 1,
backgroundColor: 1,
scaleColors: 1,
normalizeFunction: 1,
enableZoom: 1,
showTooltip: 1,
borderColor: 1,
borderWidth: 1,
borderOpacity: 1,
selectedRegions: 1,
multiSelectRegion: 1
};
var apiEvents = {
onLabelShow: 'labelShow',
onLoad: 'load',
onRegionOver: 'regionMouseOver',
onRegionOut: 'regionMouseOut',
onRegionClick: 'regionClick',
onRegionSelect: 'regionSelect',
onRegionDeselect: 'regionDeselect',
onResize: 'resize'
};
jQuery.fn.vectorMap = function (options) {
var defaultParams = {
map: 'world_en',
backgroundColor: '#a5bfdd',
color: '#f4f3f0',
hoverColor: '#c9dfaf',
hoverColors: {},
selectedColor: '#c9dfaf',
scaleColors: ['#b6d6ff', '#005ace'],
normalizeFunction: 'linear',
enableZoom: true,
showTooltip: true,
borderColor: '#818181',
borderWidth: 1,
borderOpacity: 0.25,
selectedRegions: null,
multiSelectRegion: false
}, map = this.data('mapObject');
if (options === 'addMap') {
JQVMap.maps[arguments[1]] = arguments[2];
} else if (options === 'set' && apiParams[arguments[1]]) {
map['set' + arguments[1].charAt(0).toUpperCase() + arguments[1].substr(1)].apply(map, Array.prototype.slice.call(arguments, 2));
} else if (typeof options === 'string' &&
typeof map[options] === 'function') {
return map[options].apply(map, Array.prototype.slice.call(arguments, 1));
} else {
jQuery.extend(defaultParams, options);
defaultParams.container = this;
this.css({ position: 'relative', overflow: 'hidden' });
map = new JQVMap(defaultParams);
this.data('mapObject', map);
this.unbind('.jqvmap');
for (var e in apiEvents) {
if (defaultParams[e]) {
this.bind(apiEvents[e] + '.jqvmap', defaultParams[e]);
}
}
var loadEvent = jQuery.Event('load.jqvmap');
jQuery(defaultParams.container).trigger(loadEvent, map);
return map;
}
};
})(jQuery);
ColorScale.arrayToRgb = function (ar) {
var rgb = '#';
var d;
for (var i = 0; i < ar.length; i++) {
d = ar[i].toString(16);
rgb += d.length === 1 ? '0' + d : d;
}
return rgb;
};
ColorScale.prototype.getColor = function (value) {
if (typeof this.normalize === 'function') {
value = this.normalize(value);
}
var lengthes = [];
var fullLength = 0;
var l;
for (var i = 0; i < this.colors.length - 1; i++) {
l = this.vectorLength(this.vectorSubtract(this.colors[i + 1], this.colors[i]));
lengthes.push(l);
fullLength += l;
}
var c = (this.maxValue - this.minValue) / fullLength;
for (i = 0; i < lengthes.length; i++) {
lengthes[i] *= c;
}
i = 0;
value -= this.minValue;
while (value - lengthes[i] >= 0) {
value -= lengthes[i];
i++;
}
var color;
if (i === this.colors.length - 1) {
color = this.vectorToNum(this.colors[i]).toString(16);
} else {
color = (this.vectorToNum(this.vectorAdd(this.colors[i], this.vectorMult(this.vectorSubtract(this.colors[i + 1], this.colors[i]), (value) / (lengthes[i]))))).toString(16);
}
while (color.length < 6) {
color = '0' + color;
}
return '#' + color;
};
ColorScale.rgbToArray = function (rgb) {
rgb = rgb.substr(1);
return [parseInt(rgb.substr(0, 2), 16), parseInt(rgb.substr(2, 2), 16), parseInt(rgb.substr(4, 2), 16)];
};
ColorScale.prototype.setColors = function (colors) {
for (var i = 0; i < colors.length; i++) {
colors[i] = ColorScale.rgbToArray(colors[i]);
}
this.colors = colors;
};
ColorScale.prototype.setMax = function (max) {
this.clearMaxValue = max;
if (typeof this.normalize === 'function') {
this.maxValue = this.normalize(max);
} else {
this.maxValue = max;
}
};
ColorScale.prototype.setMin = function (min) {
this.clearMinValue = min;
if (typeof this.normalize === 'function') {
this.minValue = this.normalize(min);
} else {
this.minValue = min;
}
};
ColorScale.prototype.setNormalizeFunction = function (f) {
if (f === 'polynomial') {
this.normalize = function (value) {
return Math.pow(value, 0.2);
};
} else if (f === 'linear') {
delete this.normalize;
} else {
this.normalize = f;
}
this.setMin(this.clearMinValue);
this.setMax(this.clearMaxValue);
};
ColorScale.prototype.vectorAdd = function (vector1, vector2) {
var vector = [];
for (var i = 0; i < vector1.length; i++) {
vector[i] = vector1[i] + vector2[i];
}
return vector;
};
ColorScale.prototype.vectorLength = function (vector) {
var result = 0;
for (var i = 0; i < vector.length; i++) {
result += vector[i] * vector[i];
}
return Math.sqrt(result);
};
ColorScale.prototype.vectorMult = function (vector, num) {
var result = [];
for (var i = 0; i < vector.length; i++) {
result[i] = vector[i] * num;
}
return result;
};
ColorScale.prototype.vectorSubtract = function (vector1, vector2) {
var vector = [];
for (var i = 0; i < vector1.length; i++) {
vector[i] = vector1[i] - vector2[i];
}
return vector;
};
ColorScale.prototype.vectorToNum = function (vector) {
var num = 0;
for (var i = 0; i < vector.length; i++) {
num += Math.round(vector[i]) * Math.pow(256, vector.length - i - 1);
}
return num;
};
JQVMap.prototype.applyTransform = function () {
var maxTransX, maxTransY, minTransX, minTransY;
if (this.defaultWidth * this.scale <= this.width) {
maxTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale);
minTransX = (this.width - this.defaultWidth * this.scale) / (2 * this.scale);
} else {
maxTransX = 0;
minTransX = (this.width - this.defaultWidth * this.scale) / this.scale;
}
if (this.defaultHeight * this.scale <= this.height) {
maxTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale);
minTransY = (this.height - this.defaultHeight * this.scale) / (2 * this.scale);
} else {
maxTransY = 0;
minTransY = (this.height - this.defaultHeight * this.scale) / this.scale;
}
if (this.transY > maxTransY) {
this.transY = maxTransY;
} else if (this.transY < minTransY) {
this.transY = minTransY;
}
if (this.transX > maxTransX) {
this.transX = maxTransX;
} else if (this.transX < minTransX) {
this.transX = minTransX;
}
this.canvas.applyTransformParams(this.scale, this.transX, this.transY);
};
JQVMap.prototype.bindZoomButtons = function () {
var map = this;
this.container.find('.jqvmap-zoomin').click(function(){
map.zoomIn();
});
this.container.find('.jqvmap-zoomout').click(function(){
map.zoomOut();
});
};
JQVMap.prototype.deselect = function (cc, path) {
cc = cc.toLowerCase();
path = path || jQuery('#' + this.getCountryId(cc))[0];
if (this.isSelected(cc)) {
this.selectedRegions.splice(this.selectIndex(cc), 1);
jQuery(this.container).trigger('regionDeselect.jqvmap', [cc]);
path.currentFillColor = path.getOriginalFill();
path.setFill(path.getOriginalFill());
} else {
for (var key in this.countries) {
this.selectedRegions.splice(this.selectedRegions.indexOf(key), 1);
this.countries[key].currentFillColor = this.color;
this.countries[key].setFill(this.color);
}
}
};
JQVMap.prototype.getCountryId = function (cc) {
return 'jqvmap' + this.index + '_' + cc;
};
JQVMap.prototype.getPin = function(cc){
var pinObj = jQuery('#' + this.getPinId(cc));
return pinObj.html();
};
JQVMap.prototype.getPinId = function (cc) {
return this.getCountryId(cc) + '_pin';
};
JQVMap.prototype.getPins = function(){
var pins = this.container.find('.jqvmap-pin');
var ret = {};
jQuery.each(pins, function(index, pinObj){
pinObj = jQuery(pinObj);
var cc = pinObj.attr('for').toLowerCase();
var pinContent = pinObj.html();
ret[cc] = pinContent;
});
return JSON.stringify(ret);
};
JQVMap.prototype.highlight = function (cc, path) {
path = path || jQuery('#' + this.getCountryId(cc))[0];
if (this.hoverOpacity) {
path.setOpacity(this.hoverOpacity);
} else if (this.hoverColors && (cc in this.hoverColors)) {
path.currentFillColor = path.getFill() + '';
path.setFill(this.hoverColors[cc]);
} else if (this.hoverColor) {
path.currentFillColor = path.getFill() + '';
path.setFill(this.hoverColor);
}
};
JQVMap.prototype.isSelected = function(cc) {
return this.selectIndex(cc) >= 0;
};
JQVMap.prototype.makeDraggable = function () {
var mouseDown = false;
var oldPageX, oldPageY;
var self = this;
self.isMoving = false;
self.isMovingTimeout = false;
var lastTouchCount;
var touchCenterX;
var touchCenterY;
var touchStartDistance;
var touchStartScale;
var touchX;
var touchY;
this.container.mousemove(function (e) {
if (mouseDown) {
self.transX -= (oldPageX - e.pageX) / self.scale;
self.transY -= (oldPageY - e.pageY) / self.scale;
self.applyTransform();
oldPageX = e.pageX;
oldPageY = e.pageY;
self.isMoving = true;
if (self.isMovingTimeout) {
clearTimeout(self.isMovingTimeout);
}
self.container.trigger('drag');
}
return false;
}).mousedown(function (e) {
mouseDown = true;
oldPageX = e.pageX;
oldPageY = e.pageY;
return false;
}).mouseup(function () {
mouseDown = false;
clearTimeout(self.isMovingTimeout);
self.isMovingTimeout = setTimeout(function () {
self.isMoving = false;
}, 100);
return false;
}).mouseout(function () {
if(mouseDown && self.isMoving){
clearTimeout(self.isMovingTimeout);
self.isMovingTimeout = setTimeout(function () {
mouseDown = false;
self.isMoving = false;
}, 100);
return false;
}
});
jQuery(this.container).bind('touchmove', function (e) {
var offset;
var scale;
var touches = e.originalEvent.touches;
var transformXOld;
var transformYOld;
if (touches.length === 1) {
if (lastTouchCount === 1) {
if(touchX === touches[0].pageX && touchY === touches[0].pageY){
return;
}
transformXOld = self.transX;
transformYOld = self.transY;
self.transX -= (touchX - touches[0].pageX) / self.scale;
self.transY -= (touchY - touches[0].pageY) / self.scale;
self.applyTransform();
if (transformXOld !== self.transX || transformYOld !== self.transY) {
e.preventDefault();
}
self.isMoving = true;
if (self.isMovingTimeout) {
clearTimeout(self.isMovingTimeout);
}
}
touchX = touches[0].pageX;
touchY = touches[0].pageY;
} else if (touches.length === 2) {
if (lastTouchCount === 2) {
scale = Math.sqrt(
Math.pow(touches[0].pageX - touches[1].pageX, 2) +
Math.pow(touches[0].pageY - touches[1].pageY, 2)
) / touchStartDistance;
self.setScale(
touchStartScale * scale,
touchCenterX,
touchCenterY
);
e.preventDefault();
} else {
offset = jQuery(self.container).offset();
if (touches[0].pageX > touches[1].pageX) {
touchCenterX = touches[1].pageX + (touches[0].pageX - touches[1].pageX) / 2;
} else {
touchCenterX = touches[0].pageX + (touches[1].pageX - touches[0].pageX) / 2;
}
if (touches[0].pageY > touches[1].pageY) {
touchCenterY = touches[1].pageY + (touches[0].pageY - touches[1].pageY) / 2;
} else {
touchCenterY = touches[0].pageY + (touches[1].pageY - touches[0].pageY) / 2;
}
touchCenterX -= offset.left;
touchCenterY -= offset.top;
touchStartScale = self.scale;
touchStartDistance = Math.sqrt(
Math.pow(touches[0].pageX - touches[1].pageX, 2) +
Math.pow(touches[0].pageY - touches[1].pageY, 2)
);
}
}
lastTouchCount = touches.length;
});
jQuery(this.container).bind('touchstart', function () {
lastTouchCount = 0;
});
jQuery(this.container).bind('touchend', function () {
lastTouchCount = 0;
});
};
JQVMap.prototype.placePins = function(pins, pinMode){
var map = this;
if(!pinMode || (pinMode !== 'content' && pinMode !== 'id')) {
pinMode = 'content';
}
if(pinMode === 'content') {//treat pin as content
jQuery.each(pins, function(index, pin){
if(jQuery('#' + map.getCountryId(index)).length === 0){
return;
}
var pinIndex = map.getPinId(index);
var $pin = jQuery('#' + pinIndex);
if($pin.length > 0){
$pin.remove();
}
map.container.append('<div id="' + pinIndex + '" for="' + index + '" class="jqvmap-pin" style="position:absolute">' + pin + '</div>');
});
} else { //treat pin as id of an html content
jQuery.each(pins, function(index, pin){
if(jQuery('#' + map.getCountryId(index)).length === 0){
return;
}
var pinIndex = map.getPinId(index);
var $pin = jQuery('#' + pinIndex);
if($pin.length > 0){
$pin.remove();
}
map.container.append('<div id="' + pinIndex + '" for="' + index + '" class="jqvmap-pin" style="position:absolute"></div>');
$pin.append(jQuery('#' + pin));
});
}
this.positionPins();
if(!this.pinHandlers){
this.pinHandlers = true;
var positionFix = function(){
map.positionPins();
};
this.container.bind('zoomIn', positionFix)
.bind('zoomOut', positionFix)
.bind('drag', positionFix);
}
};
JQVMap.prototype.positionPins = function(){
var map = this;
var pins = this.container.find('.jqvmap-pin');
jQuery.each(pins, function(index, pinObj){
pinObj = jQuery(pinObj);
var countryId = map.getCountryId(pinObj.attr('for').toLowerCase());
var countryObj = jQuery('#' + countryId);
var bbox = countryObj[0].getBBox();
var scale = map.scale;
var rootCoords = map.canvas.rootGroup.getBoundingClientRect();
var mapCoords = map.container[0].getBoundingClientRect();
var coords = {
left: rootCoords.left - mapCoords.left,
top: rootCoords.top - mapCoords.top
};
var middleX = (bbox.x * scale) + ((bbox.width * scale) / 2);
var middleY = (bbox.y * scale) + ((bbox.height * scale) / 2);
pinObj.css({
left: coords.left + middleX - (pinObj.width() / 2),
top: coords.top + middleY - (pinObj.height() / 2)
});
});
};
JQVMap.prototype.removePin = function(cc) {
cc = cc.toLowerCase();
jQuery('#' + this.getPinId(cc)).remove();
};
JQVMap.prototype.removePins = function(){
this.container.find('.jqvmap-pin').remove();
};
JQVMap.prototype.reset = function () {
for (var key in this.countries) {
this.countries[key].setFill(this.color);
}
this.scale = this.baseScale;
this.transX = this.baseTransX;
this.transY = this.baseTransY;
this.applyTransform();
this.zoomCurStep = 1;
};
JQVMap.prototype.resize = function () {
var curBaseScale = this.baseScale;
if (this.width / this.height > this.defaultWidth / this.defaultHeight) {
this.baseScale = this.height / this.defaultHeight;
this.baseTransX = Math.abs(this.width - this.defaultWidth * this.baseScale) / (2 * this.baseScale);
} else {
this.baseScale = this.width / this.defaultWidth;
this.baseTransY = Math.abs(this.height - this.defaultHeight * this.baseScale) / (2 * this.baseScale);
}
this.scale *= this.baseScale / curBaseScale;
this.transX *= this.baseScale / curBaseScale;
this.transY *= this.baseScale / curBaseScale;
};
JQVMap.prototype.select = function (cc, path) {
cc = cc.toLowerCase();
path = path || jQuery('#' + this.getCountryId(cc))[0];
if (!this.isSelected(cc)) {
if (this.multiSelectRegion) {
this.selectedRegions.push(cc);
} else {
this.selectedRegions = [cc];
}
jQuery(this.container).trigger('regionSelect.jqvmap', [cc]);
if (this.selectedColor && path) {
path.currentFillColor = this.selectedColor;
path.setFill(this.selectedColor);
}
}
};
JQVMap.prototype.selectIndex = function (cc) {
cc = cc.toLowerCase();
for (var i = 0; i < this.selectedRegions.length; i++) {
if (cc === this.selectedRegions[i]) {
return i;
}
}
return -1;
};
JQVMap.prototype.setBackgroundColor = function (backgroundColor) {
this.container.css('background-color', backgroundColor);
};
JQVMap.prototype.setColors = function (key, color) {
if (typeof key === 'string') {
this.countries[key].setFill(color);
this.countries[key].setAttribute('original', color);
} else {
var colors = key;
for (var code in colors) {
if (this.countries[code]) {
this.countries[code].setFill(colors[code]);
this.countries[code].setAttribute('original', colors[code]);
}
}
}
};
JQVMap.prototype.setNormalizeFunction = function (f) {
this.colorScale.setNormalizeFunction(f);
if (this.values) {
this.setValues(this.values);
}
};
JQVMap.prototype.setScale = function (scale) {
this.scale = scale;
this.applyTransform();
};
JQVMap.prototype.setScaleColors = function (colors) {
this.colorScale.setColors(colors);
if (this.values) {
this.setValues(this.values);
}
};
JQVMap.prototype.setValues = function (values) {
var max = 0,
min = Number.MAX_VALUE,
val;
for (var cc in values) {
cc = cc.toLowerCase();
val = parseFloat(values[cc]);
if (isNaN(val)) {
continue;
}
if (val > max) {
max = values[cc];
}
if (val < min) {
min = val;
}
}
if (min === max) {
max++;
}
this.colorScale.setMin(min);
this.colorScale.setMax(max);
var colors = {};
for (cc in values) {
cc = cc.toLowerCase();
val = parseFloat(values[cc]);
colors[cc] = isNaN(val) ? this.color : this.colorScale.getColor(val);
}
this.setColors(colors);
this.values = values;
};
JQVMap.prototype.unhighlight = function (cc, path) {
cc = cc.toLowerCase();
path = path || jQuery('#' + this.getCountryId(cc))[0];
path.setOpacity(1);
if (path.currentFillColor) {
path.setFill(path.currentFillColor);
}
};
JQVMap.prototype.zoomIn = function () {
var map = this;
var sliderDelta = (jQuery('#zoom').innerHeight() - 6 * 2 - 15 * 2 - 3 * 2 - 7 - 6) / (this.zoomMaxStep - this.zoomCurStep);
if (map.zoomCurStep < map.zoomMaxStep) {
map.transX -= (map.width / map.scale - map.width / (map.scale * map.zoomStep)) / 2;
map.transY -= (map.height / map.scale - map.height / (map.scale * map.zoomStep)) / 2;
map.setScale(map.scale * map.zoomStep);
map.zoomCurStep++;
var $slider = jQuery('#zoomSlider');
$slider.css('top', parseInt($slider.css('top'), 10) - sliderDelta);
map.container.trigger('zoomIn');
}
};
JQVMap.prototype.zoomOut = function () {
var map = this;
var sliderDelta = (jQuery('#zoom').innerHeight() - 6 * 2 - 15 * 2 - 3 * 2 - 7 - 6) / (this.zoomMaxStep - this.zoomCurStep);
if (map.zoomCurStep > 1) {
map.transX += (map.width / (map.scale / map.zoomStep) - map.width / map.scale) / 2;
map.transY += (map.height / (map.scale / map.zoomStep) - map.height / map.scale) / 2;
map.setScale(map.scale / map.zoomStep);
map.zoomCurStep--;
var $slider = jQuery('#zoomSlider');
$slider.css('top', parseInt($slider.css('top'), 10) + sliderDelta);
map.container.trigger('zoomOut');
}
};
VectorCanvas.prototype.applyTransformParams = function (scale, transX, transY) {
if (this.mode === 'svg') {
this.rootGroup.setAttribute('transform', 'scale(' + scale + ') translate(' + transX + ', ' + transY + ')');
} else {
this.rootGroup.coordorigin = (this.width - transX) + ',' + (this.height - transY);
this.rootGroup.coordsize = this.width / scale + ',' + this.height / scale;
}
};
VectorCanvas.prototype.createGroup = function (isRoot) {
var node;
if (this.mode === 'svg') {
node = this.createSvgNode('g');
} else {
node = this.createVmlNode('group');
node.style.width = this.width + 'px';
node.style.height = this.height + 'px';
node.style.left = '0px';
node.style.top = '0px';
node.coordorigin = '0 0';
node.coordsize = this.width + ' ' + this.height;
}
if (isRoot) {
this.rootGroup = node;
}
return node;
};
VectorCanvas.prototype.createPath = function (config) {
var node;
if (this.mode === 'svg') {
node = this.createSvgNode('path');
node.setAttribute('d', config.path);
if (this.params.borderColor !== null) {
node.setAttribute('stroke', this.params.borderColor);
}
if (this.params.borderWidth > 0) {
node.setAttribute('stroke-width', this.params.borderWidth);
node.setAttribute('stroke-linecap', 'round');
node.setAttribute('stroke-linejoin', 'round');
}
if (this.params.borderOpacity > 0) {
node.setAttribute('stroke-opacity', this.params.borderOpacity);
}
node.setFill = function (color) {
this.setAttribute('fill', color);
if (this.getAttribute('original') === null) {
this.setAttribute('original', color);
}
};
node.getFill = function () {
return this.getAttribute('fill');
};
node.getOriginalFill = function () {
return this.getAttribute('original');
};
node.setOpacity = function (opacity) {
this.setAttribute('fill-opacity', opacity);
};
} else {
node = this.createVmlNode('shape');
node.coordorigin = '0 0';
node.coordsize = this.width + ' ' + this.height;
node.style.width = this.width + 'px';
node.style.height = this.height + 'px';
node.fillcolor = JQVMap.defaultFillColor;
node.stroked = false;
node.path = VectorCanvas.pathSvgToVml(config.path);
var scale = this.createVmlNode('skew');
scale.on = true;
scale.matrix = '0.01,0,0,0.01,0,0';
scale.offset = '0,0';
node.appendChild(scale);
var fill = this.createVmlNode('fill');
node.appendChild(fill);
node.setFill = function (color) {
this.getElementsByTagName('fill')[0].color = color;
if (this.getAttribute('original') === null) {
this.setAttribute('original', color);
}
};
node.getFill = function () {
return this.getElementsByTagName('fill')[0].color;
};
node.getOriginalFill = function () {
return this.getAttribute('original');
};
node.setOpacity = function (opacity) {
this.getElementsByTagName('fill')[0].opacity = parseInt(opacity * 100, 10) + '%';
};
}
return node;
};
VectorCanvas.prototype.pathSvgToVml = function (path) {
var result = '';
var cx = 0, cy = 0, ctrlx, ctrly;
return path.replace(/([MmLlHhVvCcSs])((?:-?(?:\d+)?(?:\.\d+)?,?\s?)+)/g, function (segment, letter, coords) {
coords = coords.replace(/(\d)-/g, '$1,-').replace(/\s+/g, ',').split(',');
if (!coords[0]) {
coords.shift();
}
for (var i = 0, l = coords.length; i < l; i++) {
coords[i] = Math.round(100 * coords[i]);
}
switch (letter) {
case 'm':
cx += coords[0];
cy += coords[1];
result = 't' + coords.join(',');
break;
case 'M':
cx = coords[0];
cy = coords[1];
result = 'm' + coords.join(',');
break;
case 'l':
cx += coords[0];
cy += coords[1];
result = 'r' + coords.join(',');
break;
case 'L':
cx = coords[0];
cy = coords[1];
result = 'l' + coords.join(',');
break;
case 'h':
cx += coords[0];
result = 'r' + coords[0] + ',0';
break;
case 'H':
cx = coords[0];
result = 'l' + cx + ',' + cy;
break;
case 'v':
cy += coords[0];
result = 'r0,' + coords[0];
break;
case 'V':
cy = coords[0];
result = 'l' + cx + ',' + cy;
break;
case 'c':
ctrlx = cx + coords[coords.length - 4];
ctrly = cy + coords[coords.length - 3];
cx += coords[coords.length - 2];
cy += coords[coords.length - 1];
result = 'v' + coords.join(',');
break;
case 'C':
ctrlx = coords[coords.length - 4];
ctrly = coords[coords.length - 3];
cx = coords[coords.length - 2];
cy = coords[coords.length - 1];
result = 'c' + coords.join(',');
break;
case 's':
coords.unshift(cy - ctrly);
coords.unshift(cx - ctrlx);
ctrlx = cx + coords[coords.length - 4];
ctrly = cy + coords[coords.length - 3];
cx += coords[coords.length - 2];
cy += coords[coords.length - 1];
result = 'v' + coords.join(',');
break;
case 'S':
coords.unshift(cy + cy - ctrly);
coords.unshift(cx + cx - ctrlx);
ctrlx = coords[coords.length - 4];
ctrly = coords[coords.length - 3];
cx = coords[coords.length - 2];
cy = coords[coords.length - 1];
result = 'c' + coords.join(',');
break;
default:
break;
}
return result;
}).replace(/z/g, '');
};
VectorCanvas.prototype.setSize = function (width, height) {
if (this.mode === 'svg') {
this.canvas.setAttribute('width', width);
this.canvas.setAttribute('height', height);
} else {
this.canvas.style.width = width + 'px';
this.canvas.style.height = height + 'px';
this.canvas.coordsize = width + ' ' + height;
this.canvas.coordorigin = '0 0';
if (this.rootGroup) {
var paths = this.rootGroup.getElementsByTagName('shape');
for (var i = 0, l = paths.length; i < l; i++) {
paths[i].coordsize = width + ' ' + height;
paths[i].style.width = width + 'px';
paths[i].style.height = height + 'px';
}
this.rootGroup.coordsize = width + ' ' + height;
this.rootGroup.style.width = width + 'px';
this.rootGroup.style.height = height + 'px';
}
}
this.width = width;
this.height = height;
};
|
281677160/openwrt-package
| 25,668 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_dynamic_conf.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_dynamic_conf.h"
#include "ngx_toolkit_misc.h"
#include "ngx_event_timer_module.h"
static ngx_int_t ngx_dynamic_conf_process_init(ngx_cycle_t *cycle);
static void *ngx_dynamic_conf_module_create_conf(ngx_cycle_t *cycle);
static char *ngx_dynamic_conf_module_init_conf(ngx_cycle_t *cycle, void *conf);
static char *ngx_dynamic_conf(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static char *ngx_dynamic_log(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
#define NGX_CONF_BUFFER 4096
ngx_uint_t ngx_core_max_module;
static ngx_uint_t arg_number[] = {
NGX_CONF_NOARGS,
NGX_CONF_TAKE1,
NGX_CONF_TAKE2,
NGX_CONF_TAKE3,
NGX_CONF_TAKE4,
NGX_CONF_TAKE5,
NGX_CONF_TAKE6,
NGX_CONF_TAKE7
};
typedef struct {
void **module_conf; /* index is module index */
ngx_pool_t *pool; /* dynamic conf alloc pool */
} ngx_dynamic_conf_ctx_t;
typedef struct {
ngx_dynamic_conf_ctx_t *conf[2];
unsigned used; /* 0 and 1 for index of conf */
ngx_str_t file;
ngx_msec_t refresh;
ngx_log_t *log;
u_char md5key[NGX_MD5KEY_LEN + 1];
} ngx_dynamic_conf_conf_t;
static ngx_command_t ngx_dynamic_conf_commands[] = {
{ ngx_string("dynamic_conf"),
NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE2,
ngx_dynamic_conf,
0,
0,
NULL },
{ ngx_string("dynamic_log"),
NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_1MORE,
ngx_dynamic_log,
0,
0,
NULL },
ngx_null_command
};
ngx_core_module_t ngx_dynamic_conf_module_ctx = {
ngx_string("dynamic_conf"),
ngx_dynamic_conf_module_create_conf,
ngx_dynamic_conf_module_init_conf
};
ngx_module_t ngx_dynamic_conf_module = {
NGX_MODULE_V1,
&ngx_dynamic_conf_module_ctx, /* module context */
ngx_dynamic_conf_commands, /* module directives */
NGX_CORE_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
ngx_dynamic_conf_process_init, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_dynamic_conf_module_create_conf(ngx_cycle_t *cycle)
{
ngx_dynamic_conf_conf_t *conf;
conf = ngx_pcalloc(cycle->pool, sizeof(ngx_dynamic_conf_conf_t));
if (conf == NULL) {
return NULL;
}
conf->refresh = NGX_CONF_UNSET_MSEC;
return conf;
}
static char *
ngx_dynamic_conf_module_init_conf(ngx_cycle_t *cycle, void *conf)
{
ngx_dynamic_conf_conf_t *dccf;
dccf = conf;
ngx_conf_init_msec_value(dccf->refresh, 60000);
if (dccf->log == NULL) {
dccf->log = &cycle->new_log;
}
return NGX_CONF_OK;
}
static char *
ngx_dynamic_conf(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_dynamic_conf_conf_t *dccf;
ngx_str_t *value;
ngx_fd_t fd;
dccf = conf;
if (dccf->file.len) {
return "is duplicate";
}
value = cf->args->elts;
dccf->file = value[1];
if (ngx_conf_full_name(cf->cycle, &dccf->file, 0)) {
return NGX_CONF_ERROR;
}
/* test file, ngx_conf_full_name will fill '\0' at end of file name */
fd = ngx_open_file(dccf->file.data, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0);
if (fd == NGX_INVALID_FILE) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, ngx_errno, "dynamic conf "
ngx_open_file_n " \"%s\" failed", dccf->file.data);
return NGX_CONF_ERROR;
}
ngx_close_file(fd);
dccf->refresh = ngx_parse_time(&value[2], 0);
if (dccf->refresh == (ngx_msec_t) NGX_ERROR) {
return "invalid refresh";
}
dccf->used = 1;
return NGX_CONF_OK;
}
static char *
ngx_dynamic_log(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_dynamic_conf_conf_t *dccf = conf;
return ngx_log_set_log(cf, &dccf->log);
}
static ngx_int_t
ngx_dynamic_conf_handler(ngx_conf_t *cf, ngx_int_t last)
{
char *rv;
ngx_uint_t i, found;
ngx_str_t *name;
ngx_command_t *cmd;
void *conf;
name = cf->args->elts;
found = 0;
for (i = 0; cf->cycle->modules[i]; ++i) {
cmd = (ngx_command_t *) cf->cycle->modules[i]->spare_hook1;
if (cmd == NULL) {
continue;
}
for (/* void */; cmd->name.len; ++cmd) {
if (name->len != cmd->name.len) {
continue;
}
if (ngx_strcmp(name->data, cmd->name.data) != 0) {
continue;
}
found = 1;
if (cf->cycle->modules[i]->type != NGX_CONF_MODULE
&& cf->cycle->modules[i]->type != cf->module_type)
{
continue;
}
/* is the directive's location right ? */
if (!(cmd->type & cf->cmd_type)) {
continue;
}
if (!(cmd->type & NGX_CONF_BLOCK) && last != NGX_OK) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"directive \"%s\" is not terminated by \";\"",
name->data);
return NGX_ERROR;
}
if ((cmd->type & NGX_CONF_BLOCK) && last != NGX_CONF_BLOCK_START) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"directive \"%s\" has no opening \"{\"",
name->data);
return NGX_ERROR;
}
/* is the directive's argument count right ? */
if (!(cmd->type & NGX_CONF_ANY)) {
if (cmd->type & NGX_CONF_FLAG) {
if (cf->args->nelts != 2) {
goto invalid;
}
} else if (cmd->type & NGX_CONF_1MORE) {
if (cf->args->nelts < 2) {
goto invalid;
}
} else if (cmd->type & NGX_CONF_2MORE) {
if (cf->args->nelts < 3) {
goto invalid;
}
} else if (cf->args->nelts > NGX_CONF_MAX_ARGS) {
goto invalid;
} else if (!(cmd->type & arg_number[cf->args->nelts - 1])) {
goto invalid;
}
}
/* set up the directive's configuration context */
conf = ((void **) cf->ctx)[cf->cycle->modules[i]->ctx_index];
rv = cmd->set(cf, cmd, conf);
if (rv == NGX_CONF_OK) {
return NGX_OK;
}
if (rv == NGX_CONF_ERROR) {
return NGX_ERROR;
}
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"\"%s\" directive %s", name->data, rv);
return NGX_ERROR;
}
}
if (found) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"\"%s\" directive is not allowed here", name->data);
return NGX_ERROR;
}
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unknown directive \"%s\"", name->data);
return NGX_ERROR;
invalid:
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"invalid number of arguments in \"%s\" directive",
name->data);
return NGX_ERROR;
}
/* same as ngx_conf_read_token in ngx_conf_file.c */
static ngx_int_t
ngx_dynamic_conf_read_token(ngx_conf_t *cf)
{
u_char *start, ch, *src, *dst;
off_t file_size;
size_t len;
ssize_t n, size;
ngx_uint_t found, need_space, last_space, sharp_comment,
variable;
ngx_uint_t quoted, s_quoted, d_quoted, start_line;
ngx_str_t *word;
ngx_buf_t *b;
found = 0;
need_space = 0;
last_space = 1;
sharp_comment = 0;
variable = 0;
quoted = 0;
s_quoted = 0;
d_quoted = 0;
cf->args->nelts = 0;
b = cf->conf_file->buffer;
start = b->pos;
start_line = cf->conf_file->line;
file_size = ngx_file_size(&cf->conf_file->file.info);
for ( ;; ) {
if (b->pos >= b->last) {
if (cf->conf_file->file.offset >= file_size) {
if (cf->args->nelts > 0 || !last_space) {
if (cf->conf_file->file.fd == NGX_INVALID_FILE) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unexpected end of parameter, "
"expecting \";\"");
return NGX_ERROR;
}
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unexpected end of file, "
"expecting \";\" or \"}\"");
return NGX_ERROR;
}
return NGX_CONF_FILE_DONE;
}
len = b->pos - start;
if (len == NGX_CONF_BUFFER) {
cf->conf_file->line = start_line;
if (d_quoted) {
ch = '"';
} else if (s_quoted) {
ch = '\'';
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"too long parameter \"%*s...\" started",
10, start);
return NGX_ERROR;
}
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"too long parameter, probably "
"missing terminating \"%c\" character", ch);
return NGX_ERROR;
}
if (len) {
ngx_memmove(b->start, start, len);
}
size = (ssize_t) (file_size - cf->conf_file->file.offset);
if (size > b->end - (b->start + len)) {
size = b->end - (b->start + len);
}
n = ngx_read_file(&cf->conf_file->file, b->start + len, size,
cf->conf_file->file.offset);
if (n == NGX_ERROR) {
return NGX_ERROR;
}
if (n != size) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
ngx_read_file_n " returned "
"only %z bytes instead of %z",
n, size);
return NGX_ERROR;
}
b->pos = b->start + len;
b->last = b->pos + n;
start = b->start;
}
ch = *b->pos++;
if (ch == LF) {
cf->conf_file->line++;
if (sharp_comment) {
sharp_comment = 0;
}
}
if (sharp_comment) {
continue;
}
if (quoted) {
quoted = 0;
continue;
}
if (need_space) {
if (ch == ' ' || ch == '\t' || ch == CR || ch == LF) {
last_space = 1;
need_space = 0;
continue;
}
if (ch == ';') {
return NGX_OK;
}
if (ch == '{') {
return NGX_CONF_BLOCK_START;
}
if (ch == ')') {
last_space = 1;
need_space = 0;
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unexpected \"%c\"", ch);
return NGX_ERROR;
}
}
if (last_space) {
if (ch == ' ' || ch == '\t' || ch == CR || ch == LF) {
continue;
}
start = b->pos - 1;
start_line = cf->conf_file->line;
switch (ch) {
case ';':
case '{':
if (cf->args->nelts == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unexpected \"%c\"", ch);
return NGX_ERROR;
}
if (ch == '{') {
return NGX_CONF_BLOCK_START;
}
return NGX_OK;
case '}':
if (cf->args->nelts != 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unexpected \"}\"");
return NGX_ERROR;
}
return NGX_CONF_BLOCK_DONE;
case '#':
sharp_comment = 1;
continue;
case '\\':
quoted = 1;
last_space = 0;
continue;
case '"':
start++;
d_quoted = 1;
last_space = 0;
continue;
case '\'':
start++;
s_quoted = 1;
last_space = 0;
continue;
default:
last_space = 0;
}
} else {
if (ch == '{' && variable) {
continue;
}
variable = 0;
if (ch == '\\') {
quoted = 1;
continue;
}
if (ch == '$') {
variable = 1;
continue;
}
if (d_quoted) {
if (ch == '"') {
d_quoted = 0;
need_space = 1;
found = 1;
}
} else if (s_quoted) {
if (ch == '\'') {
s_quoted = 0;
need_space = 1;
found = 1;
}
} else if (ch == ' ' || ch == '\t' || ch == CR || ch == LF
|| ch == ';' || ch == '{')
{
last_space = 1;
found = 1;
}
if (found) {
word = ngx_array_push(cf->args);
if (word == NULL) {
return NGX_ERROR;
}
word->data = ngx_pnalloc(cf->pool, b->pos - 1 - start + 1);
if (word->data == NULL) {
return NGX_ERROR;
}
for (dst = word->data, src = start, len = 0;
src < b->pos - 1;
len++)
{
if (*src == '\\') {
switch (src[1]) {
case '"':
case '\'':
case '\\':
src++;
break;
case 't':
*dst++ = '\t';
src += 2;
continue;
case 'r':
*dst++ = '\r';
src += 2;
continue;
case 'n':
*dst++ = '\n';
src += 2;
continue;
}
}
*dst++ = *src++;
}
*dst = '\0';
word->len = len;
if (ch == ';') {
return NGX_OK;
}
if (ch == '{') {
return NGX_CONF_BLOCK_START;
}
found = 0;
}
}
}
}
ngx_int_t
ngx_dynamic_conf_parse(ngx_conf_t *cf, unsigned init)
{
ngx_int_t rc;
enum {
parse_init = 0,
parse_block
} type;
type = init ? parse_init : parse_block;
for (;;) {
rc = ngx_dynamic_conf_read_token(cf);
/*
* ngx_conf_read_token() may return
*
* NGX_ERROR there is error
* NGX_OK the token terminated by ";" was found
* NGX_CONF_BLOCK_START the token terminated by "{" was found
* NGX_CONF_BLOCK_DONE the "}" was found
* NGX_CONF_FILE_DONE the configuration file is done
*/
if (rc == NGX_ERROR) {
return NGX_ERROR;
}
if (rc == NGX_CONF_BLOCK_DONE) {
if (type != parse_block) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "unexpected \"}\"");
return NGX_ERROR;
}
return NGX_OK;
}
if (rc == NGX_CONF_FILE_DONE) {
if (type == parse_block) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unexpected end of file, expecting \"}\"");
return NGX_ERROR;
}
return NGX_OK;
}
rc = ngx_dynamic_conf_handler(cf, rc);
if (rc == NGX_ERROR) {
return NGX_ERROR;
}
}
}
static ngx_int_t
ngx_dynamic_conf_load_conf(ngx_fd_t fd, ngx_dynamic_conf_conf_t *dccf)
{
ngx_dynamic_conf_ctx_t *conf;
ngx_dynamic_core_module_t *module;
ngx_pool_t *pool;
ngx_conf_t cf;
ngx_buf_t buf;
ngx_conf_file_t conf_file;
u_char buffer[NGX_CONF_BUFFER];
ngx_uint_t i;
void *rv;
ngx_memzero(&cf, sizeof(ngx_conf_t));
pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, dccf->log);
if (pool == NULL) {
return NGX_ERROR;
}
pool->log = dccf->log;
conf = ngx_pcalloc(pool, sizeof(ngx_dynamic_conf_ctx_t));
if (conf == NULL) {
goto failed;
}
conf->pool = pool;
ngx_core_max_module = ngx_count_modules((ngx_cycle_t *) ngx_cycle,
NGX_CORE_MODULE);
conf->module_conf = ngx_pcalloc(pool, sizeof(void *) * ngx_core_max_module);
if (conf->module_conf == NULL) {
goto failed;
}
cf.args = ngx_array_create(pool, 10, sizeof(ngx_str_t));
if (cf.args == NULL) {
goto failed;
}
cf.temp_pool = ngx_create_pool(NGX_CYCLE_POOL_SIZE, dccf->log);
if (cf.temp_pool == NULL) {
goto failed;
}
cf.ctx = conf->module_conf;
cf.cycle = (ngx_cycle_t *) ngx_cycle;
cf.pool = pool;
cf.log = dccf->log;
cf.module_type = NGX_CORE_MODULE;
cf.cmd_type = NGX_MAIN_CONF;
cf.conf_file = &conf_file;
if (ngx_fd_info(fd, &cf.conf_file->file.info) == NGX_FILE_ERROR) {
ngx_log_error(NGX_LOG_EMERG, cf.log, ngx_errno,
ngx_fd_info_n " failed");
}
cf.conf_file->buffer = &buf;
buf.pos = buf.last = buf.start = buffer;
buf.end = buf.start + NGX_CONF_BUFFER;
buf.temporary = 1;
cf.conf_file->file.fd = fd;
cf.conf_file->file.name.len = dccf->file.len;
cf.conf_file->file.name.data = dccf->file.data;
cf.conf_file->file.offset = 0;
cf.conf_file->file.log = cf.log;
cf.conf_file->line = 1;
for (i = 0; ngx_cycle->modules[i]; ++i) {
if (ngx_cycle->modules[i]->type != NGX_CORE_MODULE) {
continue;
}
module = (ngx_dynamic_core_module_t *)
ngx_cycle->modules[i]->spare_hook0;
if (module == NULL) { /* dctx not configured */
continue;
}
if (module->create_conf) {
rv = module->create_conf(&cf);
if (rv == NULL) {
goto failed;
}
conf->module_conf[ngx_cycle->modules[i]->ctx_index] = rv;
}
}
if (ngx_dynamic_conf_parse(&cf, 1) != NGX_OK) {
goto failed;
}
for (i = 0; ngx_cycle->modules[i]; ++i) {
if (ngx_cycle->modules[i]->type != NGX_CORE_MODULE) {
continue;
}
module = (ngx_dynamic_core_module_t *) ngx_cycle->modules[i]->
spare_hook0;
if (module == NULL) {
continue;
}
if (module->init_conf) {
rv = conf->module_conf[ngx_cycle->modules[i]->ctx_index];
if (module->init_conf(&cf, rv) == NGX_CONF_ERROR) {
goto failed;
}
}
}
/* load conf ok, switch conf to new conf */
if (dccf->conf[dccf->used]) {
pool = dccf->conf[dccf->used]->pool;
dccf->conf[dccf->used] = NULL;
ngx_destroy_pool(pool);
}
dccf->used = dccf->used ? 0 : 1;
dccf->conf[dccf->used] = conf;
return NGX_OK;
failed:
if (cf.temp_pool) {
ngx_destroy_pool(cf.temp_pool);
}
ngx_destroy_pool(pool);
return NGX_ERROR;
}
static void
ngx_dynamic_conf_check_conf(void *data)
{
ngx_dynamic_conf_conf_t *dccf;
ngx_fd_t fd;
u_char md5key[NGX_MD5KEY_LEN];
NGX_START_TIMING
dccf = data;
if (ngx_exiting) { /* avoid nginx reload worker hungup */
return;
}
fd = ngx_open_file(dccf->file.data, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0);
if (fd == NGX_INVALID_FILE) {
ngx_log_error(NGX_LOG_ERR, dccf->log, ngx_errno,
ngx_open_file_n "\"%V\" failed", &dccf->file);
goto done;
}
/* check md5key for dynamic conf file */
if (ngx_md5_file(fd, md5key) == NGX_ERROR) {
ngx_log_error(NGX_LOG_ERR, dccf->log, 0, "md5 file \"%V\" failed",
&dccf->file);
goto done;
}
if (ngx_memcmp(dccf->md5key, md5key, NGX_MD5KEY_LEN) == 0) {
ngx_log_debug1(NGX_LOG_DEBUG_CORE, dccf->log, 0,
"\"%V\" md5key not change", &dccf->file);
goto done;
}
/* parse dynamic conf */
if (ngx_dynamic_conf_load_conf(fd, dccf) != NGX_OK) {
ngx_log_error(NGX_LOG_ERR, dccf->log, 0, "load file \"%V\" failed",
&dccf->file);
goto done;
}
ngx_memcpy(dccf->md5key, md5key, NGX_MD5KEY_LEN);
ngx_log_error(NGX_LOG_INFO, dccf->log, 0,
"dynamic conf load successd, md5key: \"%s\"", dccf->md5key);
done:
ngx_close_file(fd);
ngx_event_timer_add_timer(dccf->refresh, ngx_dynamic_conf_check_conf, dccf);
NGX_STOP_TIMING(dccf->log, "ngx_dynamic_conf_check_conf")
}
static ngx_int_t ngx_dynamic_conf_process_init(ngx_cycle_t *cycle)
{
ngx_dynamic_conf_conf_t *dccf;
ngx_fd_t fd;
u_char md5key[NGX_MD5KEY_LEN];
NGX_START_TIMING
dccf = (ngx_dynamic_conf_conf_t *) ngx_get_conf(cycle->conf_ctx,
ngx_dynamic_conf_module);
if (dccf->file.len == 0) { /* dynamic conf not configured */
return NGX_OK;
}
fd = ngx_open_file(dccf->file.data, NGX_FILE_RDONLY, NGX_FILE_OPEN, 0);
if (fd == NGX_INVALID_FILE) {
ngx_log_error(NGX_LOG_ERR, dccf->log, ngx_errno,
ngx_open_file_n "\"%V\" failed", &dccf->file);
return NGX_ERROR;
}
/* parse dynamic conf */
if (ngx_dynamic_conf_load_conf(fd, dccf) != NGX_OK) {
ngx_log_error(NGX_LOG_ERR, dccf->log, 0, "load file \"%V\" failed",
&dccf->file);
return NGX_ERROR;
}
/* calc md5key for dynamic conf file */
if (ngx_md5_file(fd, md5key) == NGX_ERROR) {
ngx_log_error(NGX_LOG_ERR, dccf->log, 0, "md5 file \"%V\" failed",
&dccf->file);
return NGX_ERROR;
}
ngx_close_file(fd);
ngx_memcpy(dccf->md5key, md5key, NGX_MD5KEY_LEN);
ngx_log_error(NGX_LOG_INFO, dccf->log, 0,
"dynamic conf load successd, md5key: \"%s\"", dccf->md5key);
/* add dynamic conf parse timer */
ngx_event_timer_add_timer(dccf->refresh, ngx_dynamic_conf_check_conf, dccf);
NGX_STOP_TIMING(dccf->log, "ngx_dynamic_conf_process_init")
return NGX_OK;
}
#if (NGX_PCRE)
ngx_dynamic_regex_t *
ngx_dynamic_regex_compile(ngx_conf_t *cf, ngx_regex_compile_t *rc)
{
ngx_dynamic_regex_t *re;
rc->pool = cf->pool;
if (ngx_regex_compile(rc) != NGX_OK) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V", &rc->err);
return NULL;
}
re = ngx_pcalloc(cf->pool, sizeof(ngx_regex_elt_t));
if (re == NULL) {
return NULL;
}
re->regex = rc->regex;
re->name = rc->pattern;
return re;
}
#endif
int
ngx_dynamic_cmp_dns_wildcards(const void *one, const void *two)
{
ngx_hash_key_t *first, *second;
first = (ngx_hash_key_t *) one;
second = (ngx_hash_key_t *) two;
return ngx_dns_strcmp(first->key.data, second->key.data);
}
void *
ngx_get_dconf(ngx_module_t *m)
{
ngx_dynamic_conf_conf_t *dccf;
dccf = (ngx_dynamic_conf_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_dynamic_conf_module);
if (dccf->conf[dccf->used] == 0) { /* dynamic conf not configured */
return NULL;
}
return dccf->conf[dccf->used]->module_conf[m->ctx_index];
}
|
281677160/openwrt-package
| 4,395 |
luci-app-nginx-pingos/modules/nginx-toolkit-module/ngx_poold.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_poold.h"
#include "ngx_map.h"
typedef struct ngx_poold_node_s ngx_poold_node_t;
static ngx_pool_t *ngx_poold_pool;
static ngx_map_t ngx_poold_map;
static ngx_poold_node_t *ngx_poold_free_node;
static ngx_uint_t ngx_poold_nalloc;
static ngx_uint_t ngx_poold_nfree;
struct ngx_poold_node_s {
ngx_map_node_t m; /* map node */
ngx_poold_node_t *next; /* free node */
ngx_pool_t *pool;
char *file; /* file create pool */
int line; /* line create pool */
};
static ngx_int_t
ngx_poold_init()
{
ngx_poold_pool = ngx_create_pool(4096, ngx_cycle->log);
if (ngx_poold_pool == NULL) {
return NGX_ERROR;
}
ngx_map_init(&ngx_poold_map, ngx_map_hash_uint, ngx_cmp_uint);
ngx_poold_free_node = NULL;
ngx_poold_nalloc = 0;
ngx_poold_nfree = 0;
return NGX_OK;
}
static ngx_poold_node_t *
ngx_poold_get_node()
{
ngx_poold_node_t *n;
n = ngx_poold_free_node;
if (n == NULL) {
n = ngx_pcalloc(ngx_poold_pool, sizeof(ngx_poold_node_t));
if (n == NULL) {
return NULL;
}
++ngx_poold_nalloc;
} else {
ngx_poold_free_node = n->next;
ngx_memzero(n, sizeof(ngx_poold_node_t));
--ngx_poold_nfree;
}
return n;
}
static void
ngx_poold_put_node(ngx_poold_node_t *node)
{
if (ngx_poold_pool == NULL) {
return;
}
if (node == NULL) {
return;
}
node->next = ngx_poold_free_node;
ngx_poold_free_node = node;
++ngx_poold_nfree;
}
ngx_pool_t *
ngx_create_pool_debug(size_t size, ngx_log_t *log, char *file, int line)
{
ngx_poold_node_t *node;
if (ngx_poold_pool == NULL) {
ngx_poold_init();
}
/* construct a poold node */
node = ngx_poold_get_node();
node->pool = ngx_create_pool(size, log);
node->file = file;
node->line = line;
/* record node in poold map */
node->m.raw_key = (intptr_t) node->pool;
ngx_map_insert(&ngx_poold_map, &node->m, 0);
return node->pool;
}
void
ngx_destroy_pool_debug(ngx_pool_t *pool, char *file, int line)
{
ngx_poold_node_t *node;
ngx_map_node_t *m;
/* get node by pool */
m = ngx_map_find(&ngx_poold_map, (intptr_t) pool);
if (m == NULL) {
ngx_log_error(NGX_LOG_EMERG, ngx_cycle->log, 0,
"destroy pool twice: %s:%d", file, line);
return;
}
ngx_map_delete(&ngx_poold_map, (intptr_t) pool);
node = (ngx_poold_node_t *) ((char *) m - offsetof(ngx_poold_node_t, m));
ngx_destroy_pool(pool);
/* put node in poold map */
ngx_poold_put_node(node);
}
ngx_chain_t *
ngx_poold_state(ngx_http_request_t *r, unsigned detail)
{
ngx_chain_t *cl;
ngx_buf_t *b;
ngx_map_node_t *node;
ngx_poold_node_t *pn;
size_t len, len1;
ngx_uint_t n;
len = sizeof("##########ngx debug pool##########\n") - 1
+ sizeof("ngx_poold nalloc node: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_poold nfree node: \n") - 1 + NGX_OFF_T_LEN;
len1 = 0;
/* node for create pool */
if (detail) {
n = ngx_poold_nalloc - ngx_poold_nfree;
/* " file:line\n" */
len1 = 4 + 256 + 1 + NGX_OFF_T_LEN + 1;
len += len1 * n;
}
cl = ngx_alloc_chain_link(r->pool);
if (cl == NULL) {
return NULL;
}
cl->next = NULL;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL) {
return NULL;
}
cl->buf = b;
b->last = ngx_snprintf(b->last, len,
"##########ngx debug pool##########\n"
"ngx_poold nalloc node: %ui\nngx_poold nfree node: %ui\n",
ngx_poold_nalloc, ngx_poold_nfree);
if (detail) {
for (node = ngx_map_begin(&ngx_poold_map); node;
node = ngx_map_next(node))
{
/* m is first element of ngx_poold_node_t */
pn = (ngx_poold_node_t *) node;
b->last = ngx_snprintf(b->last, len1, " %s:%d\n",
pn->file, pn->line);
}
}
return cl;
}
|
2881099/FreeSql.AdminLTE
| 66,264 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/daterangepicker/daterangepicker.js
|
/**
* @version: 3.1
* @author: Dan Grossman http://www.dangrossman.info/
* @copyright: Copyright (c) 2012-2019 Dan Grossman. All rights reserved.
* @license: Licensed under the MIT license. See http://www.opensource.org/licenses/mit-license.php
* @website: http://www.daterangepicker.com/
*/
// Following the UMD template https://github.com/umdjs/umd/blob/master/templates/returnExportsGlobal.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Make globaly available as well
define(['moment', 'jquery'], function (moment, jquery) {
if (!jquery.fn) jquery.fn = {}; // webpack server rendering
if (typeof moment !== 'function' && moment.hasOwnProperty('default')) moment = moment['default']
return factory(moment, jquery);
});
} else if (typeof module === 'object' && module.exports) {
// Node / Browserify
//isomorphic issue
var jQuery = (typeof window != 'undefined') ? window.jQuery : undefined;
if (!jQuery) {
jQuery = require('jquery');
if (!jQuery.fn) jQuery.fn = {};
}
var moment = (typeof window != 'undefined' && typeof window.moment != 'undefined') ? window.moment : require('moment');
module.exports = factory(moment, jQuery);
} else {
// Browser globals
root.daterangepicker = factory(root.moment, root.jQuery);
}
}(this, function(moment, $) {
var DateRangePicker = function(element, options, cb) {
//default settings for options
this.parentEl = 'body';
this.element = $(element);
this.startDate = moment().startOf('day');
this.endDate = moment().endOf('day');
this.minDate = false;
this.maxDate = false;
this.maxSpan = false;
this.autoApply = false;
this.singleDatePicker = false;
this.showDropdowns = false;
this.minYear = moment().subtract(100, 'year').format('YYYY');
this.maxYear = moment().add(100, 'year').format('YYYY');
this.showWeekNumbers = false;
this.showISOWeekNumbers = false;
this.showCustomRangeLabel = true;
this.timePicker = false;
this.timePicker24Hour = false;
this.timePickerIncrement = 1;
this.timePickerSeconds = false;
this.linkedCalendars = true;
this.autoUpdateInput = true;
this.alwaysShowCalendars = false;
this.ranges = {};
this.opens = 'right';
if (this.element.hasClass('pull-right'))
this.opens = 'left';
this.drops = 'down';
if (this.element.hasClass('dropup'))
this.drops = 'up';
this.buttonClasses = 'btn btn-sm';
this.applyButtonClasses = 'btn-primary';
this.cancelButtonClasses = 'btn-default';
this.locale = {
direction: 'ltr',
format: moment.localeData().longDateFormat('L'),
separator: ' - ',
applyLabel: 'Apply',
cancelLabel: 'Cancel',
weekLabel: 'W',
customRangeLabel: 'Custom Range',
daysOfWeek: moment.weekdaysMin(),
monthNames: moment.monthsShort(),
firstDay: moment.localeData().firstDayOfWeek()
};
this.callback = function() { };
//some state information
this.isShowing = false;
this.leftCalendar = {};
this.rightCalendar = {};
//custom options from user
if (typeof options !== 'object' || options === null)
options = {};
//allow setting options with data attributes
//data-api options will be overwritten with custom javascript options
options = $.extend(this.element.data(), options);
//html template for the picker UI
if (typeof options.template !== 'string' && !(options.template instanceof $))
options.template =
'<div class="daterangepicker">' +
'<div class="ranges"></div>' +
'<div class="drp-calendar left">' +
'<div class="calendar-table"></div>' +
'<div class="calendar-time"></div>' +
'</div>' +
'<div class="drp-calendar right">' +
'<div class="calendar-table"></div>' +
'<div class="calendar-time"></div>' +
'</div>' +
'<div class="drp-buttons">' +
'<span class="drp-selected"></span>' +
'<button class="cancelBtn" type="button"></button>' +
'<button class="applyBtn" disabled="disabled" type="button"></button> ' +
'</div>' +
'</div>';
this.parentEl = (options.parentEl && $(options.parentEl).length) ? $(options.parentEl) : $(this.parentEl);
this.container = $(options.template).appendTo(this.parentEl);
//
// handle all the possible options overriding defaults
//
if (typeof options.locale === 'object') {
if (typeof options.locale.direction === 'string')
this.locale.direction = options.locale.direction;
if (typeof options.locale.format === 'string')
this.locale.format = options.locale.format;
if (typeof options.locale.separator === 'string')
this.locale.separator = options.locale.separator;
if (typeof options.locale.daysOfWeek === 'object')
this.locale.daysOfWeek = options.locale.daysOfWeek.slice();
if (typeof options.locale.monthNames === 'object')
this.locale.monthNames = options.locale.monthNames.slice();
if (typeof options.locale.firstDay === 'number')
this.locale.firstDay = options.locale.firstDay;
if (typeof options.locale.applyLabel === 'string')
this.locale.applyLabel = options.locale.applyLabel;
if (typeof options.locale.cancelLabel === 'string')
this.locale.cancelLabel = options.locale.cancelLabel;
if (typeof options.locale.weekLabel === 'string')
this.locale.weekLabel = options.locale.weekLabel;
if (typeof options.locale.customRangeLabel === 'string'){
//Support unicode chars in the custom range name.
var elem = document.createElement('textarea');
elem.innerHTML = options.locale.customRangeLabel;
var rangeHtml = elem.value;
this.locale.customRangeLabel = rangeHtml;
}
}
this.container.addClass(this.locale.direction);
if (typeof options.startDate === 'string')
this.startDate = moment(options.startDate, this.locale.format);
if (typeof options.endDate === 'string')
this.endDate = moment(options.endDate, this.locale.format);
if (typeof options.minDate === 'string')
this.minDate = moment(options.minDate, this.locale.format);
if (typeof options.maxDate === 'string')
this.maxDate = moment(options.maxDate, this.locale.format);
if (typeof options.startDate === 'object')
this.startDate = moment(options.startDate);
if (typeof options.endDate === 'object')
this.endDate = moment(options.endDate);
if (typeof options.minDate === 'object')
this.minDate = moment(options.minDate);
if (typeof options.maxDate === 'object')
this.maxDate = moment(options.maxDate);
// sanity check for bad options
if (this.minDate && this.startDate.isBefore(this.minDate))
this.startDate = this.minDate.clone();
// sanity check for bad options
if (this.maxDate && this.endDate.isAfter(this.maxDate))
this.endDate = this.maxDate.clone();
if (typeof options.applyButtonClasses === 'string')
this.applyButtonClasses = options.applyButtonClasses;
if (typeof options.applyClass === 'string') //backwards compat
this.applyButtonClasses = options.applyClass;
if (typeof options.cancelButtonClasses === 'string')
this.cancelButtonClasses = options.cancelButtonClasses;
if (typeof options.cancelClass === 'string') //backwards compat
this.cancelButtonClasses = options.cancelClass;
if (typeof options.maxSpan === 'object')
this.maxSpan = options.maxSpan;
if (typeof options.dateLimit === 'object') //backwards compat
this.maxSpan = options.dateLimit;
if (typeof options.opens === 'string')
this.opens = options.opens;
if (typeof options.drops === 'string')
this.drops = options.drops;
if (typeof options.showWeekNumbers === 'boolean')
this.showWeekNumbers = options.showWeekNumbers;
if (typeof options.showISOWeekNumbers === 'boolean')
this.showISOWeekNumbers = options.showISOWeekNumbers;
if (typeof options.buttonClasses === 'string')
this.buttonClasses = options.buttonClasses;
if (typeof options.buttonClasses === 'object')
this.buttonClasses = options.buttonClasses.join(' ');
if (typeof options.showDropdowns === 'boolean')
this.showDropdowns = options.showDropdowns;
if (typeof options.minYear === 'number')
this.minYear = options.minYear;
if (typeof options.maxYear === 'number')
this.maxYear = options.maxYear;
if (typeof options.showCustomRangeLabel === 'boolean')
this.showCustomRangeLabel = options.showCustomRangeLabel;
if (typeof options.singleDatePicker === 'boolean') {
this.singleDatePicker = options.singleDatePicker;
if (this.singleDatePicker)
this.endDate = this.startDate.clone();
}
if (typeof options.timePicker === 'boolean')
this.timePicker = options.timePicker;
if (typeof options.timePickerSeconds === 'boolean')
this.timePickerSeconds = options.timePickerSeconds;
if (typeof options.timePickerIncrement === 'number')
this.timePickerIncrement = options.timePickerIncrement;
if (typeof options.timePicker24Hour === 'boolean')
this.timePicker24Hour = options.timePicker24Hour;
if (typeof options.autoApply === 'boolean')
this.autoApply = options.autoApply;
if (typeof options.autoUpdateInput === 'boolean')
this.autoUpdateInput = options.autoUpdateInput;
if (typeof options.linkedCalendars === 'boolean')
this.linkedCalendars = options.linkedCalendars;
if (typeof options.isInvalidDate === 'function')
this.isInvalidDate = options.isInvalidDate;
if (typeof options.isCustomDate === 'function')
this.isCustomDate = options.isCustomDate;
if (typeof options.alwaysShowCalendars === 'boolean')
this.alwaysShowCalendars = options.alwaysShowCalendars;
// update day names order to firstDay
if (this.locale.firstDay != 0) {
var iterator = this.locale.firstDay;
while (iterator > 0) {
this.locale.daysOfWeek.push(this.locale.daysOfWeek.shift());
iterator--;
}
}
var start, end, range;
//if no start/end dates set, check if an input element contains initial values
if (typeof options.startDate === 'undefined' && typeof options.endDate === 'undefined') {
if ($(this.element).is(':text')) {
var val = $(this.element).val(),
split = val.split(this.locale.separator);
start = end = null;
if (split.length == 2) {
start = moment(split[0], this.locale.format);
end = moment(split[1], this.locale.format);
} else if (this.singleDatePicker && val !== "") {
start = moment(val, this.locale.format);
end = moment(val, this.locale.format);
}
if (start !== null && end !== null) {
this.setStartDate(start);
this.setEndDate(end);
}
}
}
if (typeof options.ranges === 'object') {
for (range in options.ranges) {
if (typeof options.ranges[range][0] === 'string')
start = moment(options.ranges[range][0], this.locale.format);
else
start = moment(options.ranges[range][0]);
if (typeof options.ranges[range][1] === 'string')
end = moment(options.ranges[range][1], this.locale.format);
else
end = moment(options.ranges[range][1]);
// If the start or end date exceed those allowed by the minDate or maxSpan
// options, shorten the range to the allowable period.
if (this.minDate && start.isBefore(this.minDate))
start = this.minDate.clone();
var maxDate = this.maxDate;
if (this.maxSpan && maxDate && start.clone().add(this.maxSpan).isAfter(maxDate))
maxDate = start.clone().add(this.maxSpan);
if (maxDate && end.isAfter(maxDate))
end = maxDate.clone();
// If the end of the range is before the minimum or the start of the range is
// after the maximum, don't display this range option at all.
if ((this.minDate && end.isBefore(this.minDate, this.timepicker ? 'minute' : 'day'))
|| (maxDate && start.isAfter(maxDate, this.timepicker ? 'minute' : 'day')))
continue;
//Support unicode chars in the range names.
var elem = document.createElement('textarea');
elem.innerHTML = range;
var rangeHtml = elem.value;
this.ranges[rangeHtml] = [start, end];
}
var list = '<ul>';
for (range in this.ranges) {
list += '<li data-range-key="' + range + '">' + range + '</li>';
}
if (this.showCustomRangeLabel) {
list += '<li data-range-key="' + this.locale.customRangeLabel + '">' + this.locale.customRangeLabel + '</li>';
}
list += '</ul>';
this.container.find('.ranges').prepend(list);
}
if (typeof cb === 'function') {
this.callback = cb;
}
if (!this.timePicker) {
this.startDate = this.startDate.startOf('day');
this.endDate = this.endDate.endOf('day');
this.container.find('.calendar-time').hide();
}
//can't be used together for now
if (this.timePicker && this.autoApply)
this.autoApply = false;
if (this.autoApply) {
this.container.addClass('auto-apply');
}
if (typeof options.ranges === 'object')
this.container.addClass('show-ranges');
if (this.singleDatePicker) {
this.container.addClass('single');
this.container.find('.drp-calendar.left').addClass('single');
this.container.find('.drp-calendar.left').show();
this.container.find('.drp-calendar.right').hide();
if (!this.timePicker && this.autoApply) {
this.container.addClass('auto-apply');
}
}
if ((typeof options.ranges === 'undefined' && !this.singleDatePicker) || this.alwaysShowCalendars) {
this.container.addClass('show-calendar');
}
this.container.addClass('opens' + this.opens);
//apply CSS classes and labels to buttons
this.container.find('.applyBtn, .cancelBtn').addClass(this.buttonClasses);
if (this.applyButtonClasses.length)
this.container.find('.applyBtn').addClass(this.applyButtonClasses);
if (this.cancelButtonClasses.length)
this.container.find('.cancelBtn').addClass(this.cancelButtonClasses);
this.container.find('.applyBtn').html(this.locale.applyLabel);
this.container.find('.cancelBtn').html(this.locale.cancelLabel);
//
// event listeners
//
this.container.find('.drp-calendar')
.on('click.daterangepicker', '.prev', $.proxy(this.clickPrev, this))
.on('click.daterangepicker', '.next', $.proxy(this.clickNext, this))
.on('mousedown.daterangepicker', 'td.available', $.proxy(this.clickDate, this))
.on('mouseenter.daterangepicker', 'td.available', $.proxy(this.hoverDate, this))
.on('change.daterangepicker', 'select.yearselect', $.proxy(this.monthOrYearChanged, this))
.on('change.daterangepicker', 'select.monthselect', $.proxy(this.monthOrYearChanged, this))
.on('change.daterangepicker', 'select.hourselect,select.minuteselect,select.secondselect,select.ampmselect', $.proxy(this.timeChanged, this));
this.container.find('.ranges')
.on('click.daterangepicker', 'li', $.proxy(this.clickRange, this));
this.container.find('.drp-buttons')
.on('click.daterangepicker', 'button.applyBtn', $.proxy(this.clickApply, this))
.on('click.daterangepicker', 'button.cancelBtn', $.proxy(this.clickCancel, this));
if (this.element.is('input') || this.element.is('button')) {
this.element.on({
'click.daterangepicker': $.proxy(this.show, this),
'focus.daterangepicker': $.proxy(this.show, this),
'keyup.daterangepicker': $.proxy(this.elementChanged, this),
'keydown.daterangepicker': $.proxy(this.keydown, this) //IE 11 compatibility
});
} else {
this.element.on('click.daterangepicker', $.proxy(this.toggle, this));
this.element.on('keydown.daterangepicker', $.proxy(this.toggle, this));
}
//
// if attached to a text input, set the initial value
//
this.updateElement();
};
DateRangePicker.prototype = {
constructor: DateRangePicker,
setStartDate: function(startDate) {
if (typeof startDate === 'string')
this.startDate = moment(startDate, this.locale.format);
if (typeof startDate === 'object')
this.startDate = moment(startDate);
if (!this.timePicker)
this.startDate = this.startDate.startOf('day');
if (this.timePicker && this.timePickerIncrement)
this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
if (this.minDate && this.startDate.isBefore(this.minDate)) {
this.startDate = this.minDate.clone();
if (this.timePicker && this.timePickerIncrement)
this.startDate.minute(Math.round(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
}
if (this.maxDate && this.startDate.isAfter(this.maxDate)) {
this.startDate = this.maxDate.clone();
if (this.timePicker && this.timePickerIncrement)
this.startDate.minute(Math.floor(this.startDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
}
if (!this.isShowing)
this.updateElement();
this.updateMonthsInView();
},
setEndDate: function(endDate) {
if (typeof endDate === 'string')
this.endDate = moment(endDate, this.locale.format);
if (typeof endDate === 'object')
this.endDate = moment(endDate);
if (!this.timePicker)
this.endDate = this.endDate.endOf('day');
if (this.timePicker && this.timePickerIncrement)
this.endDate.minute(Math.round(this.endDate.minute() / this.timePickerIncrement) * this.timePickerIncrement);
if (this.endDate.isBefore(this.startDate))
this.endDate = this.startDate.clone();
if (this.maxDate && this.endDate.isAfter(this.maxDate))
this.endDate = this.maxDate.clone();
if (this.maxSpan && this.startDate.clone().add(this.maxSpan).isBefore(this.endDate))
this.endDate = this.startDate.clone().add(this.maxSpan);
this.previousRightTime = this.endDate.clone();
this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
if (!this.isShowing)
this.updateElement();
this.updateMonthsInView();
},
isInvalidDate: function() {
return false;
},
isCustomDate: function() {
return false;
},
updateView: function() {
if (this.timePicker) {
this.renderTimePicker('left');
this.renderTimePicker('right');
if (!this.endDate) {
this.container.find('.right .calendar-time select').prop('disabled', true).addClass('disabled');
} else {
this.container.find('.right .calendar-time select').prop('disabled', false).removeClass('disabled');
}
}
if (this.endDate)
this.container.find('.drp-selected').html(this.startDate.format(this.locale.format) + this.locale.separator + this.endDate.format(this.locale.format));
this.updateMonthsInView();
this.updateCalendars();
this.updateFormInputs();
},
updateMonthsInView: function() {
if (this.endDate) {
//if both dates are visible already, do nothing
if (!this.singleDatePicker && this.leftCalendar.month && this.rightCalendar.month &&
(this.startDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.startDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
&&
(this.endDate.format('YYYY-MM') == this.leftCalendar.month.format('YYYY-MM') || this.endDate.format('YYYY-MM') == this.rightCalendar.month.format('YYYY-MM'))
) {
return;
}
this.leftCalendar.month = this.startDate.clone().date(2);
if (!this.linkedCalendars && (this.endDate.month() != this.startDate.month() || this.endDate.year() != this.startDate.year())) {
this.rightCalendar.month = this.endDate.clone().date(2);
} else {
this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
}
} else {
if (this.leftCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM') && this.rightCalendar.month.format('YYYY-MM') != this.startDate.format('YYYY-MM')) {
this.leftCalendar.month = this.startDate.clone().date(2);
this.rightCalendar.month = this.startDate.clone().date(2).add(1, 'month');
}
}
if (this.maxDate && this.linkedCalendars && !this.singleDatePicker && this.rightCalendar.month > this.maxDate) {
this.rightCalendar.month = this.maxDate.clone().date(2);
this.leftCalendar.month = this.maxDate.clone().date(2).subtract(1, 'month');
}
},
updateCalendars: function() {
if (this.timePicker) {
var hour, minute, second;
if (this.endDate) {
hour = parseInt(this.container.find('.left .hourselect').val(), 10);
minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
if (isNaN(minute)) {
minute = parseInt(this.container.find('.left .minuteselect option:last').val(), 10);
}
second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
if (!this.timePicker24Hour) {
var ampm = this.container.find('.left .ampmselect').val();
if (ampm === 'PM' && hour < 12)
hour += 12;
if (ampm === 'AM' && hour === 12)
hour = 0;
}
} else {
hour = parseInt(this.container.find('.right .hourselect').val(), 10);
minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
if (isNaN(minute)) {
minute = parseInt(this.container.find('.right .minuteselect option:last').val(), 10);
}
second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
if (!this.timePicker24Hour) {
var ampm = this.container.find('.right .ampmselect').val();
if (ampm === 'PM' && hour < 12)
hour += 12;
if (ampm === 'AM' && hour === 12)
hour = 0;
}
}
this.leftCalendar.month.hour(hour).minute(minute).second(second);
this.rightCalendar.month.hour(hour).minute(minute).second(second);
}
this.renderCalendar('left');
this.renderCalendar('right');
//highlight any predefined range matching the current start and end dates
this.container.find('.ranges li').removeClass('active');
if (this.endDate == null) return;
this.calculateChosenLabel();
},
renderCalendar: function(side) {
//
// Build the matrix of dates that will populate the calendar
//
var calendar = side == 'left' ? this.leftCalendar : this.rightCalendar;
var month = calendar.month.month();
var year = calendar.month.year();
var hour = calendar.month.hour();
var minute = calendar.month.minute();
var second = calendar.month.second();
var daysInMonth = moment([year, month]).daysInMonth();
var firstDay = moment([year, month, 1]);
var lastDay = moment([year, month, daysInMonth]);
var lastMonth = moment(firstDay).subtract(1, 'month').month();
var lastYear = moment(firstDay).subtract(1, 'month').year();
var daysInLastMonth = moment([lastYear, lastMonth]).daysInMonth();
var dayOfWeek = firstDay.day();
//initialize a 6 rows x 7 columns array for the calendar
var calendar = [];
calendar.firstDay = firstDay;
calendar.lastDay = lastDay;
for (var i = 0; i < 6; i++) {
calendar[i] = [];
}
//populate the calendar with date objects
var startDay = daysInLastMonth - dayOfWeek + this.locale.firstDay + 1;
if (startDay > daysInLastMonth)
startDay -= 7;
if (dayOfWeek == this.locale.firstDay)
startDay = daysInLastMonth - 6;
var curDate = moment([lastYear, lastMonth, startDay, 12, minute, second]);
var col, row;
for (var i = 0, col = 0, row = 0; i < 42; i++, col++, curDate = moment(curDate).add(24, 'hour')) {
if (i > 0 && col % 7 === 0) {
col = 0;
row++;
}
calendar[row][col] = curDate.clone().hour(hour).minute(minute).second(second);
curDate.hour(12);
if (this.minDate && calendar[row][col].format('YYYY-MM-DD') == this.minDate.format('YYYY-MM-DD') && calendar[row][col].isBefore(this.minDate) && side == 'left') {
calendar[row][col] = this.minDate.clone();
}
if (this.maxDate && calendar[row][col].format('YYYY-MM-DD') == this.maxDate.format('YYYY-MM-DD') && calendar[row][col].isAfter(this.maxDate) && side == 'right') {
calendar[row][col] = this.maxDate.clone();
}
}
//make the calendar object available to hoverDate/clickDate
if (side == 'left') {
this.leftCalendar.calendar = calendar;
} else {
this.rightCalendar.calendar = calendar;
}
//
// Display the calendar
//
var minDate = side == 'left' ? this.minDate : this.startDate;
var maxDate = this.maxDate;
var selected = side == 'left' ? this.startDate : this.endDate;
var arrow = this.locale.direction == 'ltr' ? {left: 'chevron-left', right: 'chevron-right'} : {left: 'chevron-right', right: 'chevron-left'};
var html = '<table class="table-condensed">';
html += '<thead>';
html += '<tr>';
// add empty cell for week number
if (this.showWeekNumbers || this.showISOWeekNumbers)
html += '<th></th>';
if ((!minDate || minDate.isBefore(calendar.firstDay)) && (!this.linkedCalendars || side == 'left')) {
html += '<th class="prev available"><span></span></th>';
} else {
html += '<th></th>';
}
var dateHtml = this.locale.monthNames[calendar[1][1].month()] + calendar[1][1].format(" YYYY");
if (this.showDropdowns) {
var currentMonth = calendar[1][1].month();
var currentYear = calendar[1][1].year();
var maxYear = (maxDate && maxDate.year()) || (this.maxYear);
var minYear = (minDate && minDate.year()) || (this.minYear);
var inMinYear = currentYear == minYear;
var inMaxYear = currentYear == maxYear;
var monthHtml = '<select class="monthselect">';
for (var m = 0; m < 12; m++) {
if ((!inMinYear || (minDate && m >= minDate.month())) && (!inMaxYear || (maxDate && m <= maxDate.month()))) {
monthHtml += "<option value='" + m + "'" +
(m === currentMonth ? " selected='selected'" : "") +
">" + this.locale.monthNames[m] + "</option>";
} else {
monthHtml += "<option value='" + m + "'" +
(m === currentMonth ? " selected='selected'" : "") +
" disabled='disabled'>" + this.locale.monthNames[m] + "</option>";
}
}
monthHtml += "</select>";
var yearHtml = '<select class="yearselect">';
for (var y = minYear; y <= maxYear; y++) {
yearHtml += '<option value="' + y + '"' +
(y === currentYear ? ' selected="selected"' : '') +
'>' + y + '</option>';
}
yearHtml += '</select>';
dateHtml = monthHtml + yearHtml;
}
html += '<th colspan="5" class="month">' + dateHtml + '</th>';
if ((!maxDate || maxDate.isAfter(calendar.lastDay)) && (!this.linkedCalendars || side == 'right' || this.singleDatePicker)) {
html += '<th class="next available"><span></span></th>';
} else {
html += '<th></th>';
}
html += '</tr>';
html += '<tr>';
// add week number label
if (this.showWeekNumbers || this.showISOWeekNumbers)
html += '<th class="week">' + this.locale.weekLabel + '</th>';
$.each(this.locale.daysOfWeek, function(index, dayOfWeek) {
html += '<th>' + dayOfWeek + '</th>';
});
html += '</tr>';
html += '</thead>';
html += '<tbody>';
//adjust maxDate to reflect the maxSpan setting in order to
//grey out end dates beyond the maxSpan
if (this.endDate == null && this.maxSpan) {
var maxLimit = this.startDate.clone().add(this.maxSpan).endOf('day');
if (!maxDate || maxLimit.isBefore(maxDate)) {
maxDate = maxLimit;
}
}
for (var row = 0; row < 6; row++) {
html += '<tr>';
// add week number
if (this.showWeekNumbers)
html += '<td class="week">' + calendar[row][0].week() + '</td>';
else if (this.showISOWeekNumbers)
html += '<td class="week">' + calendar[row][0].isoWeek() + '</td>';
for (var col = 0; col < 7; col++) {
var classes = [];
//highlight today's date
if (calendar[row][col].isSame(new Date(), "day"))
classes.push('today');
//highlight weekends
if (calendar[row][col].isoWeekday() > 5)
classes.push('weekend');
//grey out the dates in other months displayed at beginning and end of this calendar
if (calendar[row][col].month() != calendar[1][1].month())
classes.push('off', 'ends');
//don't allow selection of dates before the minimum date
if (this.minDate && calendar[row][col].isBefore(this.minDate, 'day'))
classes.push('off', 'disabled');
//don't allow selection of dates after the maximum date
if (maxDate && calendar[row][col].isAfter(maxDate, 'day'))
classes.push('off', 'disabled');
//don't allow selection of date if a custom function decides it's invalid
if (this.isInvalidDate(calendar[row][col]))
classes.push('off', 'disabled');
//highlight the currently selected start date
if (calendar[row][col].format('YYYY-MM-DD') == this.startDate.format('YYYY-MM-DD'))
classes.push('active', 'start-date');
//highlight the currently selected end date
if (this.endDate != null && calendar[row][col].format('YYYY-MM-DD') == this.endDate.format('YYYY-MM-DD'))
classes.push('active', 'end-date');
//highlight dates in-between the selected dates
if (this.endDate != null && calendar[row][col] > this.startDate && calendar[row][col] < this.endDate)
classes.push('in-range');
//apply custom classes for this date
var isCustom = this.isCustomDate(calendar[row][col]);
if (isCustom !== false) {
if (typeof isCustom === 'string')
classes.push(isCustom);
else
Array.prototype.push.apply(classes, isCustom);
}
var cname = '', disabled = false;
for (var i = 0; i < classes.length; i++) {
cname += classes[i] + ' ';
if (classes[i] == 'disabled')
disabled = true;
}
if (!disabled)
cname += 'available';
html += '<td class="' + cname.replace(/^\s+|\s+$/g, '') + '" data-title="' + 'r' + row + 'c' + col + '">' + calendar[row][col].date() + '</td>';
}
html += '</tr>';
}
html += '</tbody>';
html += '</table>';
this.container.find('.drp-calendar.' + side + ' .calendar-table').html(html);
},
renderTimePicker: function(side) {
// Don't bother updating the time picker if it's currently disabled
// because an end date hasn't been clicked yet
if (side == 'right' && !this.endDate) return;
var html, selected, minDate, maxDate = this.maxDate;
if (this.maxSpan && (!this.maxDate || this.startDate.clone().add(this.maxSpan).isBefore(this.maxDate)))
maxDate = this.startDate.clone().add(this.maxSpan);
if (side == 'left') {
selected = this.startDate.clone();
minDate = this.minDate;
} else if (side == 'right') {
selected = this.endDate.clone();
minDate = this.startDate;
//Preserve the time already selected
var timeSelector = this.container.find('.drp-calendar.right .calendar-time');
if (timeSelector.html() != '') {
selected.hour(!isNaN(selected.hour()) ? selected.hour() : timeSelector.find('.hourselect option:selected').val());
selected.minute(!isNaN(selected.minute()) ? selected.minute() : timeSelector.find('.minuteselect option:selected').val());
selected.second(!isNaN(selected.second()) ? selected.second() : timeSelector.find('.secondselect option:selected').val());
if (!this.timePicker24Hour) {
var ampm = timeSelector.find('.ampmselect option:selected').val();
if (ampm === 'PM' && selected.hour() < 12)
selected.hour(selected.hour() + 12);
if (ampm === 'AM' && selected.hour() === 12)
selected.hour(0);
}
}
if (selected.isBefore(this.startDate))
selected = this.startDate.clone();
if (maxDate && selected.isAfter(maxDate))
selected = maxDate.clone();
}
//
// hours
//
html = '<select class="hourselect">';
var start = this.timePicker24Hour ? 0 : 1;
var end = this.timePicker24Hour ? 23 : 12;
for (var i = start; i <= end; i++) {
var i_in_24 = i;
if (!this.timePicker24Hour)
i_in_24 = selected.hour() >= 12 ? (i == 12 ? 12 : i + 12) : (i == 12 ? 0 : i);
var time = selected.clone().hour(i_in_24);
var disabled = false;
if (minDate && time.minute(59).isBefore(minDate))
disabled = true;
if (maxDate && time.minute(0).isAfter(maxDate))
disabled = true;
if (i_in_24 == selected.hour() && !disabled) {
html += '<option value="' + i + '" selected="selected">' + i + '</option>';
} else if (disabled) {
html += '<option value="' + i + '" disabled="disabled" class="disabled">' + i + '</option>';
} else {
html += '<option value="' + i + '">' + i + '</option>';
}
}
html += '</select> ';
//
// minutes
//
html += ': <select class="minuteselect">';
for (var i = 0; i < 60; i += this.timePickerIncrement) {
var padded = i < 10 ? '0' + i : i;
var time = selected.clone().minute(i);
var disabled = false;
if (minDate && time.second(59).isBefore(minDate))
disabled = true;
if (maxDate && time.second(0).isAfter(maxDate))
disabled = true;
if (selected.minute() == i && !disabled) {
html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
} else if (disabled) {
html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
} else {
html += '<option value="' + i + '">' + padded + '</option>';
}
}
html += '</select> ';
//
// seconds
//
if (this.timePickerSeconds) {
html += ': <select class="secondselect">';
for (var i = 0; i < 60; i++) {
var padded = i < 10 ? '0' + i : i;
var time = selected.clone().second(i);
var disabled = false;
if (minDate && time.isBefore(minDate))
disabled = true;
if (maxDate && time.isAfter(maxDate))
disabled = true;
if (selected.second() == i && !disabled) {
html += '<option value="' + i + '" selected="selected">' + padded + '</option>';
} else if (disabled) {
html += '<option value="' + i + '" disabled="disabled" class="disabled">' + padded + '</option>';
} else {
html += '<option value="' + i + '">' + padded + '</option>';
}
}
html += '</select> ';
}
//
// AM/PM
//
if (!this.timePicker24Hour) {
html += '<select class="ampmselect">';
var am_html = '';
var pm_html = '';
if (minDate && selected.clone().hour(12).minute(0).second(0).isBefore(minDate))
am_html = ' disabled="disabled" class="disabled"';
if (maxDate && selected.clone().hour(0).minute(0).second(0).isAfter(maxDate))
pm_html = ' disabled="disabled" class="disabled"';
if (selected.hour() >= 12) {
html += '<option value="AM"' + am_html + '>AM</option><option value="PM" selected="selected"' + pm_html + '>PM</option>';
} else {
html += '<option value="AM" selected="selected"' + am_html + '>AM</option><option value="PM"' + pm_html + '>PM</option>';
}
html += '</select>';
}
this.container.find('.drp-calendar.' + side + ' .calendar-time').html(html);
},
updateFormInputs: function() {
if (this.singleDatePicker || (this.endDate && (this.startDate.isBefore(this.endDate) || this.startDate.isSame(this.endDate)))) {
this.container.find('button.applyBtn').prop('disabled', false);
} else {
this.container.find('button.applyBtn').prop('disabled', true);
}
},
move: function() {
var parentOffset = { top: 0, left: 0 },
containerTop,
drops = this.drops;
var parentRightEdge = $(window).width();
if (!this.parentEl.is('body')) {
parentOffset = {
top: this.parentEl.offset().top - this.parentEl.scrollTop(),
left: this.parentEl.offset().left - this.parentEl.scrollLeft()
};
parentRightEdge = this.parentEl[0].clientWidth + this.parentEl.offset().left;
}
switch (drops) {
case 'auto':
containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
if (containerTop + this.container.outerHeight() >= this.parentEl[0].scrollHeight) {
containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
drops = 'up';
}
break;
case 'up':
containerTop = this.element.offset().top - this.container.outerHeight() - parentOffset.top;
break;
default:
containerTop = this.element.offset().top + this.element.outerHeight() - parentOffset.top;
break;
}
// Force the container to it's actual width
this.container.css({
top: 0,
left: 0,
right: 'auto'
});
var containerWidth = this.container.outerWidth();
this.container.toggleClass('drop-up', drops == 'up');
if (this.opens == 'left') {
var containerRight = parentRightEdge - this.element.offset().left - this.element.outerWidth();
if (containerWidth + containerRight > $(window).width()) {
this.container.css({
top: containerTop,
right: 'auto',
left: 9
});
} else {
this.container.css({
top: containerTop,
right: containerRight,
left: 'auto'
});
}
} else if (this.opens == 'center') {
var containerLeft = this.element.offset().left - parentOffset.left + this.element.outerWidth() / 2
- containerWidth / 2;
if (containerLeft < 0) {
this.container.css({
top: containerTop,
right: 'auto',
left: 9
});
} else if (containerLeft + containerWidth > $(window).width()) {
this.container.css({
top: containerTop,
left: 'auto',
right: 0
});
} else {
this.container.css({
top: containerTop,
left: containerLeft,
right: 'auto'
});
}
} else {
var containerLeft = this.element.offset().left - parentOffset.left;
if (containerLeft + containerWidth > $(window).width()) {
this.container.css({
top: containerTop,
left: 'auto',
right: 0
});
} else {
this.container.css({
top: containerTop,
left: containerLeft,
right: 'auto'
});
}
}
},
show: function(e) {
if (this.isShowing) return;
// Create a click proxy that is private to this instance of datepicker, for unbinding
this._outsideClickProxy = $.proxy(function(e) { this.outsideClick(e); }, this);
// Bind global datepicker mousedown for hiding and
$(document)
.on('mousedown.daterangepicker', this._outsideClickProxy)
// also support mobile devices
.on('touchend.daterangepicker', this._outsideClickProxy)
// also explicitly play nice with Bootstrap dropdowns, which stopPropagation when clicking them
.on('click.daterangepicker', '[data-toggle=dropdown]', this._outsideClickProxy)
// and also close when focus changes to outside the picker (eg. tabbing between controls)
.on('focusin.daterangepicker', this._outsideClickProxy);
// Reposition the picker if the window is resized while it's open
$(window).on('resize.daterangepicker', $.proxy(function(e) { this.move(e); }, this));
this.oldStartDate = this.startDate.clone();
this.oldEndDate = this.endDate.clone();
this.previousRightTime = this.endDate.clone();
this.updateView();
this.container.show();
this.move();
this.element.trigger('show.daterangepicker', this);
this.isShowing = true;
},
hide: function(e) {
if (!this.isShowing) return;
//incomplete date selection, revert to last values
if (!this.endDate) {
this.startDate = this.oldStartDate.clone();
this.endDate = this.oldEndDate.clone();
}
//if a new date range was selected, invoke the user callback function
if (!this.startDate.isSame(this.oldStartDate) || !this.endDate.isSame(this.oldEndDate))
this.callback(this.startDate.clone(), this.endDate.clone(), this.chosenLabel);
//if picker is attached to a text input, update it
this.updateElement();
$(document).off('.daterangepicker');
$(window).off('.daterangepicker');
this.container.hide();
this.element.trigger('hide.daterangepicker', this);
this.isShowing = false;
},
toggle: function(e) {
if (this.isShowing) {
this.hide();
} else {
this.show();
}
},
outsideClick: function(e) {
var target = $(e.target);
// if the page is clicked anywhere except within the daterangerpicker/button
// itself then call this.hide()
if (
// ie modal dialog fix
e.type == "focusin" ||
target.closest(this.element).length ||
target.closest(this.container).length ||
target.closest('.calendar-table').length
) return;
this.hide();
this.element.trigger('outsideClick.daterangepicker', this);
},
showCalendars: function() {
this.container.addClass('show-calendar');
this.move();
this.element.trigger('showCalendar.daterangepicker', this);
},
hideCalendars: function() {
this.container.removeClass('show-calendar');
this.element.trigger('hideCalendar.daterangepicker', this);
},
clickRange: function(e) {
var label = e.target.getAttribute('data-range-key');
this.chosenLabel = label;
if (label == this.locale.customRangeLabel) {
this.showCalendars();
} else {
var dates = this.ranges[label];
this.startDate = dates[0];
this.endDate = dates[1];
if (!this.timePicker) {
this.startDate.startOf('day');
this.endDate.endOf('day');
}
if (!this.alwaysShowCalendars)
this.hideCalendars();
this.clickApply();
}
},
clickPrev: function(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.subtract(1, 'month');
if (this.linkedCalendars)
this.rightCalendar.month.subtract(1, 'month');
} else {
this.rightCalendar.month.subtract(1, 'month');
}
this.updateCalendars();
},
clickNext: function(e) {
var cal = $(e.target).parents('.drp-calendar');
if (cal.hasClass('left')) {
this.leftCalendar.month.add(1, 'month');
} else {
this.rightCalendar.month.add(1, 'month');
if (this.linkedCalendars)
this.leftCalendar.month.add(1, 'month');
}
this.updateCalendars();
},
hoverDate: function(e) {
//ignore dates that can't be selected
if (!$(e.target).hasClass('available')) return;
var title = $(e.target).attr('data-title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(e.target).parents('.drp-calendar');
var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
//highlight the dates between the start date and the date being hovered as a potential end date
var leftCalendar = this.leftCalendar;
var rightCalendar = this.rightCalendar;
var startDate = this.startDate;
if (!this.endDate) {
this.container.find('.drp-calendar tbody td').each(function(index, el) {
//skip week numbers, only look at dates
if ($(el).hasClass('week')) return;
var title = $(el).attr('data-title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(el).parents('.drp-calendar');
var dt = cal.hasClass('left') ? leftCalendar.calendar[row][col] : rightCalendar.calendar[row][col];
if ((dt.isAfter(startDate) && dt.isBefore(date)) || dt.isSame(date, 'day')) {
$(el).addClass('in-range');
} else {
$(el).removeClass('in-range');
}
});
}
},
clickDate: function(e) {
if (!$(e.target).hasClass('available')) return;
var title = $(e.target).attr('data-title');
var row = title.substr(1, 1);
var col = title.substr(3, 1);
var cal = $(e.target).parents('.drp-calendar');
var date = cal.hasClass('left') ? this.leftCalendar.calendar[row][col] : this.rightCalendar.calendar[row][col];
//
// this function needs to do a few things:
// * alternate between selecting a start and end date for the range,
// * if the time picker is enabled, apply the hour/minute/second from the select boxes to the clicked date
// * if autoapply is enabled, and an end date was chosen, apply the selection
// * if single date picker mode, and time picker isn't enabled, apply the selection immediately
// * if one of the inputs above the calendars was focused, cancel that manual input
//
if (this.endDate || date.isBefore(this.startDate, 'day')) { //picking start
if (this.timePicker) {
var hour = parseInt(this.container.find('.left .hourselect').val(), 10);
if (!this.timePicker24Hour) {
var ampm = this.container.find('.left .ampmselect').val();
if (ampm === 'PM' && hour < 12)
hour += 12;
if (ampm === 'AM' && hour === 12)
hour = 0;
}
var minute = parseInt(this.container.find('.left .minuteselect').val(), 10);
if (isNaN(minute)) {
minute = parseInt(this.container.find('.left .minuteselect option:last').val(), 10);
}
var second = this.timePickerSeconds ? parseInt(this.container.find('.left .secondselect').val(), 10) : 0;
date = date.clone().hour(hour).minute(minute).second(second);
}
this.endDate = null;
this.setStartDate(date.clone());
} else if (!this.endDate && date.isBefore(this.startDate)) {
//special case: clicking the same date for start/end,
//but the time of the end date is before the start date
this.setEndDate(this.startDate.clone());
} else { // picking end
if (this.timePicker) {
var hour = parseInt(this.container.find('.right .hourselect').val(), 10);
if (!this.timePicker24Hour) {
var ampm = this.container.find('.right .ampmselect').val();
if (ampm === 'PM' && hour < 12)
hour += 12;
if (ampm === 'AM' && hour === 12)
hour = 0;
}
var minute = parseInt(this.container.find('.right .minuteselect').val(), 10);
if (isNaN(minute)) {
minute = parseInt(this.container.find('.right .minuteselect option:last').val(), 10);
}
var second = this.timePickerSeconds ? parseInt(this.container.find('.right .secondselect').val(), 10) : 0;
date = date.clone().hour(hour).minute(minute).second(second);
}
this.setEndDate(date.clone());
if (this.autoApply) {
this.calculateChosenLabel();
this.clickApply();
}
}
if (this.singleDatePicker) {
this.setEndDate(this.startDate);
if (!this.timePicker && this.autoApply)
this.clickApply();
}
this.updateView();
//This is to cancel the blur event handler if the mouse was in one of the inputs
e.stopPropagation();
},
calculateChosenLabel: function () {
var customRange = true;
var i = 0;
for (var range in this.ranges) {
if (this.timePicker) {
var format = this.timePickerSeconds ? "YYYY-MM-DD HH:mm:ss" : "YYYY-MM-DD HH:mm";
//ignore times when comparing dates if time picker seconds is not enabled
if (this.startDate.format(format) == this.ranges[range][0].format(format) && this.endDate.format(format) == this.ranges[range][1].format(format)) {
customRange = false;
this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key');
break;
}
} else {
//ignore times when comparing dates if time picker is not enabled
if (this.startDate.format('YYYY-MM-DD') == this.ranges[range][0].format('YYYY-MM-DD') && this.endDate.format('YYYY-MM-DD') == this.ranges[range][1].format('YYYY-MM-DD')) {
customRange = false;
this.chosenLabel = this.container.find('.ranges li:eq(' + i + ')').addClass('active').attr('data-range-key');
break;
}
}
i++;
}
if (customRange) {
if (this.showCustomRangeLabel) {
this.chosenLabel = this.container.find('.ranges li:last').addClass('active').attr('data-range-key');
} else {
this.chosenLabel = null;
}
this.showCalendars();
}
},
clickApply: function(e) {
this.hide();
this.element.trigger('apply.daterangepicker', this);
},
clickCancel: function(e) {
this.startDate = this.oldStartDate;
this.endDate = this.oldEndDate;
this.hide();
this.element.trigger('cancel.daterangepicker', this);
},
monthOrYearChanged: function(e) {
var isLeft = $(e.target).closest('.drp-calendar').hasClass('left'),
leftOrRight = isLeft ? 'left' : 'right',
cal = this.container.find('.drp-calendar.'+leftOrRight);
// Month must be Number for new moment versions
var month = parseInt(cal.find('.monthselect').val(), 10);
var year = cal.find('.yearselect').val();
if (!isLeft) {
if (year < this.startDate.year() || (year == this.startDate.year() && month < this.startDate.month())) {
month = this.startDate.month();
year = this.startDate.year();
}
}
if (this.minDate) {
if (year < this.minDate.year() || (year == this.minDate.year() && month < this.minDate.month())) {
month = this.minDate.month();
year = this.minDate.year();
}
}
if (this.maxDate) {
if (year > this.maxDate.year() || (year == this.maxDate.year() && month > this.maxDate.month())) {
month = this.maxDate.month();
year = this.maxDate.year();
}
}
if (isLeft) {
this.leftCalendar.month.month(month).year(year);
if (this.linkedCalendars)
this.rightCalendar.month = this.leftCalendar.month.clone().add(1, 'month');
} else {
this.rightCalendar.month.month(month).year(year);
if (this.linkedCalendars)
this.leftCalendar.month = this.rightCalendar.month.clone().subtract(1, 'month');
}
this.updateCalendars();
},
timeChanged: function(e) {
var cal = $(e.target).closest('.drp-calendar'),
isLeft = cal.hasClass('left');
var hour = parseInt(cal.find('.hourselect').val(), 10);
var minute = parseInt(cal.find('.minuteselect').val(), 10);
if (isNaN(minute)) {
minute = parseInt(cal.find('.minuteselect option:last').val(), 10);
}
var second = this.timePickerSeconds ? parseInt(cal.find('.secondselect').val(), 10) : 0;
if (!this.timePicker24Hour) {
var ampm = cal.find('.ampmselect').val();
if (ampm === 'PM' && hour < 12)
hour += 12;
if (ampm === 'AM' && hour === 12)
hour = 0;
}
if (isLeft) {
var start = this.startDate.clone();
start.hour(hour);
start.minute(minute);
start.second(second);
this.setStartDate(start);
if (this.singleDatePicker) {
this.endDate = this.startDate.clone();
} else if (this.endDate && this.endDate.format('YYYY-MM-DD') == start.format('YYYY-MM-DD') && this.endDate.isBefore(start)) {
this.setEndDate(start.clone());
}
} else if (this.endDate) {
var end = this.endDate.clone();
end.hour(hour);
end.minute(minute);
end.second(second);
this.setEndDate(end);
}
//update the calendars so all clickable dates reflect the new time component
this.updateCalendars();
//update the form inputs above the calendars with the new time
this.updateFormInputs();
//re-render the time pickers because changing one selection can affect what's enabled in another
this.renderTimePicker('left');
this.renderTimePicker('right');
},
elementChanged: function() {
if (!this.element.is('input')) return;
if (!this.element.val().length) return;
var dateString = this.element.val().split(this.locale.separator),
start = null,
end = null;
if (dateString.length === 2) {
start = moment(dateString[0], this.locale.format);
end = moment(dateString[1], this.locale.format);
}
if (this.singleDatePicker || start === null || end === null) {
start = moment(this.element.val(), this.locale.format);
end = start;
}
if (!start.isValid() || !end.isValid()) return;
this.setStartDate(start);
this.setEndDate(end);
this.updateView();
},
keydown: function(e) {
//hide on tab or enter
if ((e.keyCode === 9) || (e.keyCode === 13)) {
this.hide();
}
//hide on esc and prevent propagation
if (e.keyCode === 27) {
e.preventDefault();
e.stopPropagation();
this.hide();
}
},
updateElement: function() {
if (this.element.is('input') && this.autoUpdateInput) {
var newValue = this.startDate.format(this.locale.format);
if (!this.singleDatePicker) {
newValue += this.locale.separator + this.endDate.format(this.locale.format);
}
if (newValue !== this.element.val()) {
this.element.val(newValue).trigger('change');
}
}
},
remove: function() {
this.container.remove();
this.element.off('.daterangepicker');
this.element.removeData();
}
};
$.fn.daterangepicker = function(options, callback) {
var implementOptions = $.extend(true, {}, $.fn.daterangepicker.defaultOptions, options);
this.each(function() {
var el = $(this);
if (el.data('daterangepicker'))
el.data('daterangepicker').remove();
el.data('daterangepicker', new DateRangePicker(el, implementOptions, callback));
});
return this;
};
return DateRangePicker;
}));
|
281677160/openwrt-package
| 34,210 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include <nginx.h>
#include "ngx_rtmp.h"
#include "ngx_rtmp_variables.h"
static char *ngx_rtmp_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static ngx_int_t ngx_rtmp_optimize_servers(ngx_conf_t *cf,
ngx_rtmp_core_main_conf_t *cmcf, ngx_array_t *ports);
static ngx_int_t ngx_rtmp_add_addrs(ngx_conf_t *cf, ngx_rtmp_port_t *mport,
ngx_rtmp_conf_addr_t *addr);
#if (NGX_HAVE_INET6)
static ngx_int_t ngx_rtmp_add_addrs6(ngx_conf_t *cf, ngx_rtmp_port_t *mport,
ngx_rtmp_conf_addr_t *addr);
#endif
static ngx_int_t ngx_rtmp_cmp_conf_addrs(const void *one, const void *two);
static ngx_int_t ngx_rtmp_init_events(ngx_conf_t *cf,
ngx_rtmp_core_main_conf_t *cmcf);
static ngx_int_t ngx_rtmp_init_event_handlers(ngx_conf_t *cf,
ngx_rtmp_core_main_conf_t *cmcf);
static char * ngx_rtmp_merge_applications(ngx_conf_t *cf,
ngx_array_t *applications, void **app_conf, ngx_rtmp_module_t *module,
ngx_uint_t ctx_index);
static ngx_int_t ngx_rtmp_init_process(ngx_cycle_t *cycle);
#if (nginx_version >= 1007011)
ngx_queue_t ngx_rtmp_init_queue;
#elif (nginx_version >= 1007005)
ngx_thread_volatile ngx_queue_t ngx_rtmp_init_queue;
#else
ngx_thread_volatile ngx_event_t *ngx_rtmp_init_queue;
#endif
ngx_int_t NGX_RTMP_HEVC_CODEC_ID = NGX_RTMP_VIDEO_H265;
ngx_uint_t ngx_rtmp_max_module;
static ngx_command_t ngx_rtmp_commands[] = {
{ ngx_string("rtmp"),
NGX_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS,
ngx_rtmp_block,
0,
0,
NULL },
ngx_null_command
};
static ngx_core_module_t ngx_rtmp_module_ctx = {
ngx_string("rtmp"),
NULL,
NULL
};
ngx_module_t ngx_rtmp_module = {
NGX_MODULE_V1,
&ngx_rtmp_module_ctx, /* module context */
ngx_rtmp_commands, /* module directives */
NGX_CORE_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
ngx_rtmp_init_process, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static char *
ngx_rtmp_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *rv;
ngx_uint_t m, mi, s;
ngx_conf_t pcf;
ngx_array_t ports;
ngx_module_t **modules;
ngx_rtmp_module_t *module;
ngx_rtmp_conf_ctx_t *ctx;
ngx_rtmp_core_srv_conf_t *cscf, **cscfp;
ngx_rtmp_core_main_conf_t *cmcf;
ctx = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_conf_ctx_t));
if (ctx == NULL) {
return NGX_CONF_ERROR;
}
*(ngx_rtmp_conf_ctx_t **) conf = ctx;
/* count the number of the rtmp modules and set up their indices */
#if (nginx_version >= 1009011)
ngx_rtmp_max_module = ngx_count_modules(cf->cycle, NGX_RTMP_MODULE);
#else
ngx_rtmp_max_module = 0;
for (m = 0; ngx_modules[m]; m++) {
if (ngx_modules[m]->type != NGX_RTMP_MODULE) {
continue;
}
ngx_modules[m]->ctx_index = ngx_rtmp_max_module++;
}
#endif
/* the rtmp main_conf context, it is the same in the all rtmp contexts */
ctx->main_conf = ngx_pcalloc(cf->pool,
sizeof(void *) * ngx_rtmp_max_module);
if (ctx->main_conf == NULL) {
return NGX_CONF_ERROR;
}
/*
* the rtmp null srv_conf context, it is used to merge
* the server{}s' srv_conf's
*/
ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->srv_conf == NULL) {
return NGX_CONF_ERROR;
}
/*
* the rtmp null app_conf context, it is used to merge
* the server{}s' app_conf's
*/
ctx->app_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->app_conf == NULL) {
return NGX_CONF_ERROR;
}
/*
* create the main_conf's, the null srv_conf's, and the null app_conf's
* of the all rtmp modules
*/
#if (nginx_version >= 1009011)
modules = cf->cycle->modules;
#else
modules = ngx_modules;
#endif
for (m = 0; modules[m]; m++) {
if (modules[m]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[m]->ctx;
mi = modules[m]->ctx_index;
if (module->create_main_conf) {
ctx->main_conf[mi] = module->create_main_conf(cf);
if (ctx->main_conf[mi] == NULL) {
return NGX_CONF_ERROR;
}
}
if (module->create_srv_conf) {
ctx->srv_conf[mi] = module->create_srv_conf(cf);
if (ctx->srv_conf[mi] == NULL) {
return NGX_CONF_ERROR;
}
}
if (module->create_app_conf) {
ctx->app_conf[mi] = module->create_app_conf(cf);
if (ctx->app_conf[mi] == NULL) {
return NGX_CONF_ERROR;
}
}
}
pcf = *cf;
cf->ctx = ctx;
for (m = 0; modules[m]; m++) {
if (modules[m]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[m]->ctx;
if (module->preconfiguration) {
if (module->preconfiguration(cf) != NGX_OK) {
return NGX_CONF_ERROR;
}
}
}
/* parse inside the rtmp{} block */
cf->module_type = NGX_RTMP_MODULE;
cf->cmd_type = NGX_RTMP_MAIN_CONF;
rv = ngx_conf_parse(cf, NULL);
if (rv != NGX_CONF_OK) {
*cf = pcf;
return rv;
}
/* init rtmp{} main_conf's, merge the server{}s' srv_conf's */
cmcf = ctx->main_conf[ngx_rtmp_core_module.ctx_index];
cscfp = cmcf->servers.elts;
for (m = 0; modules[m]; m++) {
if (modules[m]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[m]->ctx;
mi = modules[m]->ctx_index;
/* init rtmp{} main_conf's */
cf->ctx = ctx;
if (module->init_main_conf) {
rv = module->init_main_conf(cf, ctx->main_conf[mi]);
if (rv != NGX_CONF_OK) {
*cf = pcf;
return rv;
}
}
for (s = 0; s < cmcf->servers.nelts; s++) {
/* merge the server{}s' srv_conf's */
cf->ctx = cscfp[s]->ctx;
if (module->merge_srv_conf) {
rv = module->merge_srv_conf(cf,
ctx->srv_conf[mi],
cscfp[s]->ctx->srv_conf[mi]);
if (rv != NGX_CONF_OK) {
*cf = pcf;
return rv;
}
}
if (module->merge_app_conf) {
/* merge the server{}'s app_conf */
/*ctx->app_conf = cscfp[s]->ctx->loc_conf;*/
rv = module->merge_app_conf(cf,
ctx->app_conf[mi],
cscfp[s]->ctx->app_conf[mi]);
if (rv != NGX_CONF_OK) {
*cf = pcf;
return rv;
}
/* merge the applications{}' app_conf's */
cscf = cscfp[s]->ctx->srv_conf[ngx_rtmp_core_module.ctx_index];
rv = ngx_rtmp_merge_applications(cf, &cscf->applications,
cscfp[s]->ctx->app_conf,
module, mi);
if (rv != NGX_CONF_OK) {
*cf = pcf;
return rv;
}
}
}
}
if (ngx_rtmp_init_events(cf, cmcf) != NGX_OK) {
return NGX_CONF_ERROR;
}
for (m = 0; modules[m]; m++) {
if (modules[m]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[m]->ctx;
if (module->postconfiguration) {
if (module->postconfiguration(cf) != NGX_OK) {
return NGX_CONF_ERROR;
}
}
}
*cf = pcf;
if (ngx_rtmp_init_event_handlers(cf, cmcf) != NGX_OK) {
return NGX_CONF_ERROR;
}
if (ngx_array_init(&ports, cf->temp_pool, 4, sizeof(ngx_rtmp_conf_port_t))
!= NGX_OK)
{
return NGX_CONF_ERROR;
}
if (ngx_rtmp_optimize_servers(cf, cmcf, cmcf->ports) != NGX_OK) {
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static char *
ngx_rtmp_merge_applications(ngx_conf_t *cf, ngx_array_t *applications,
void **app_conf, ngx_rtmp_module_t *module, ngx_uint_t ctx_index)
{
char *rv;
ngx_rtmp_conf_ctx_t *ctx, saved;
ngx_rtmp_core_app_conf_t **cacfp;
ngx_uint_t n;
ngx_rtmp_core_app_conf_t *cacf;
if (applications == NULL) {
return NGX_CONF_OK;
}
ctx = (ngx_rtmp_conf_ctx_t *) cf->ctx;
saved = *ctx;
cacfp = applications->elts;
for (n = 0; n < applications->nelts; ++n, ++cacfp) {
ctx->app_conf = (*cacfp)->app_conf;
rv = module->merge_app_conf(cf, app_conf[ctx_index],
(*cacfp)->app_conf[ctx_index]);
if (rv != NGX_CONF_OK) {
return rv;
}
cacf = (*cacfp)->app_conf[ngx_rtmp_core_module.ctx_index];
rv = ngx_rtmp_merge_applications(cf, &cacf->applications,
(*cacfp)->app_conf,
module, ctx_index);
if (rv != NGX_CONF_OK) {
return rv;
}
}
*ctx = saved;
return NGX_CONF_OK;
}
static ngx_int_t
ngx_rtmp_init_events(ngx_conf_t *cf, ngx_rtmp_core_main_conf_t *cmcf)
{
size_t n;
for(n = 0; n < NGX_RTMP_MAX_EVENT; ++n) {
if (ngx_array_init(&cmcf->events[n], cf->pool, 1,
sizeof(ngx_rtmp_handler_pt)) != NGX_OK)
{
return NGX_ERROR;
}
}
if (ngx_array_init(&cmcf->amf, cf->pool, 1,
sizeof(ngx_rtmp_amf_handler_t)) != NGX_OK)
{
return NGX_ERROR;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_init_event_handlers(ngx_conf_t *cf, ngx_rtmp_core_main_conf_t *cmcf)
{
ngx_hash_init_t calls_hash;
ngx_rtmp_handler_pt *eh;
ngx_rtmp_amf_handler_t *h;
ngx_hash_key_t *ha;
size_t n, m;
static size_t pm_events[] = {
NGX_RTMP_MSG_CHUNK_SIZE,
NGX_RTMP_MSG_ABORT,
NGX_RTMP_MSG_ACK,
NGX_RTMP_MSG_ACK_SIZE,
NGX_RTMP_MSG_BANDWIDTH
};
static size_t amf_events[] = {
NGX_RTMP_MSG_AMF_CMD,
NGX_RTMP_MSG_AMF_META,
NGX_RTMP_MSG_AMF_SHARED,
NGX_RTMP_MSG_AMF3_CMD,
NGX_RTMP_MSG_AMF3_META,
NGX_RTMP_MSG_AMF3_SHARED
};
/* init standard protocol events */
for(n = 0; n < sizeof(pm_events) / sizeof(pm_events[0]); ++n) {
eh = ngx_array_push(&cmcf->events[pm_events[n]]);
*eh = ngx_rtmp_protocol_message_handler;
}
/* init amf events */
for(n = 0; n < sizeof(amf_events) / sizeof(amf_events[0]); ++n) {
eh = ngx_array_push(&cmcf->events[amf_events[n]]);
*eh = ngx_rtmp_amf_message_handler;
}
/* init user protocol events */
eh = ngx_array_push(&cmcf->events[NGX_RTMP_MSG_USER]);
*eh = ngx_rtmp_user_message_handler;
/* aggregate to audio/video map */
eh = ngx_array_push(&cmcf->events[NGX_RTMP_MSG_AGGREGATE]);
*eh = ngx_rtmp_aggregate_message_handler;
/* init amf callbacks */
ngx_array_init(&cmcf->amf_arrays, cf->pool, 1, sizeof(ngx_hash_key_t));
h = cmcf->amf.elts;
for(n = 0; n < cmcf->amf.nelts; ++n, ++h) {
ha = cmcf->amf_arrays.elts;
for(m = 0; m < cmcf->amf_arrays.nelts; ++m, ++ha) {
if (h->name.len == ha->key.len
&& !ngx_strncmp(h->name.data, ha->key.data, ha->key.len))
{
break;
}
}
if (m == cmcf->amf_arrays.nelts) {
ha = ngx_array_push(&cmcf->amf_arrays);
ha->key = h->name;
ha->key_hash = ngx_hash_key_lc(ha->key.data, ha->key.len);
ha->value = ngx_array_create(cf->pool, 1,
sizeof(ngx_rtmp_handler_pt));
if (ha->value == NULL) {
return NGX_ERROR;
}
}
eh = ngx_array_push((ngx_array_t*)ha->value);
*eh = h->handler;
}
calls_hash.hash = &cmcf->amf_hash;
calls_hash.key = ngx_hash_key_lc;
calls_hash.max_size = 512;
calls_hash.bucket_size = ngx_cacheline_size;
calls_hash.name = "amf_hash";
calls_hash.pool = cf->pool;
calls_hash.temp_pool = NULL;
if (ngx_hash_init(&calls_hash, cmcf->amf_arrays.elts, cmcf->amf_arrays.nelts)
!= NGX_OK)
{
return NGX_ERROR;
}
return NGX_OK;
}
/* add the server core module configuration to the address:port */
static ngx_int_t
ngx_rtmp_add_server(ngx_conf_t *cf, ngx_rtmp_core_srv_conf_t *cscf,
ngx_rtmp_conf_addr_t *addr)
{
ngx_uint_t i;
ngx_rtmp_core_srv_conf_t **server;
if (addr->servers.elts == NULL) {
if (ngx_array_init(&addr->servers, cf->temp_pool, 4,
sizeof(ngx_rtmp_core_srv_conf_t *))
!= NGX_OK)
{
return NGX_ERROR;
}
} else {
server = addr->servers.elts;
for (i = 0; i < addr->servers.nelts; i++) {
if (server[i] == cscf) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"a duplicate listen %s", addr->opt.addr);
return NGX_ERROR;
}
}
}
server = ngx_array_push(&addr->servers);
if (server == NULL) {
return NGX_ERROR;
}
*server = cscf;
return NGX_OK;
}
/*
* add the server address, the server names and the server core module
* configurations to the port list
*/
static ngx_int_t
ngx_rtmp_add_address(ngx_conf_t *cf, ngx_rtmp_core_srv_conf_t *cscf,
ngx_rtmp_conf_port_t *port, ngx_rtmp_listen_opt_t *lsopt)
{
ngx_rtmp_conf_addr_t *addr;
if (port->addrs.elts == NULL) {
if (ngx_array_init(&port->addrs, cf->temp_pool, 4,
sizeof(ngx_rtmp_conf_addr_t))
!= NGX_OK)
{
return NGX_ERROR;
}
}
addr = ngx_array_push(&port->addrs);
if (addr == NULL) {
return NGX_ERROR;
}
addr->opt = *lsopt;
addr->hash.buckets = NULL;
addr->hash.size = 0;
addr->wc_head = NULL;
addr->wc_tail = NULL;
#if (NGX_PCRE)
addr->nregex = 0;
addr->regex = NULL;
#endif
addr->default_server = cscf;
addr->servers.elts = NULL;
return ngx_rtmp_add_server(cf, cscf, addr);
}
static ngx_int_t
ngx_rtmp_add_addresses(ngx_conf_t *cf, ngx_rtmp_core_srv_conf_t *cscf,
ngx_rtmp_conf_port_t *port, ngx_rtmp_listen_opt_t *lsopt)
{
ngx_uint_t i, default_server, proxy_protocol;
ngx_rtmp_conf_addr_t *addr;
/*
* we cannot compare whole sockaddr struct's as kernel
* may fill some fields in inherited sockaddr struct's
*/
addr = port->addrs.elts;
for (i = 0; i < port->addrs.nelts; i++) {
if (ngx_cmp_sockaddr(lsopt->sockaddr, lsopt->socklen,
addr[i].opt.sockaddr,
addr[i].opt.socklen, 0)
!= NGX_OK)
{
continue;
}
/* the address is already in the address list */
if (ngx_rtmp_add_server(cf, cscf, &addr[i]) != NGX_OK) {
return NGX_ERROR;
}
/* preserve default_server bit during listen options overwriting */
default_server = addr[i].opt.default_server;
proxy_protocol = lsopt->proxy_protocol || addr[i].opt.proxy_protocol;
if (lsopt->set) {
if (addr[i].opt.set) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"duplicate listen options for %s", addr[i].opt.addr);
return NGX_ERROR;
}
addr[i].opt = *lsopt;
}
/* check the duplicate "default" server for this address:port */
if (lsopt->default_server) {
if (default_server) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"a duplicate default server for %s", addr[i].opt.addr);
return NGX_ERROR;
}
default_server = 1;
addr[i].default_server = cscf;
}
addr[i].opt.default_server = default_server;
addr[i].opt.proxy_protocol = proxy_protocol;
return NGX_OK;
}
/* add the address to the addresses list that bound to this port */
return ngx_rtmp_add_address(cf, cscf, port, lsopt);
}
ngx_int_t
ngx_rtmp_add_listen(ngx_conf_t *cf, ngx_rtmp_core_srv_conf_t *cscf,
ngx_rtmp_listen_opt_t *lsopt)
{
in_port_t p;
ngx_uint_t i;
struct sockaddr *sa;
ngx_rtmp_conf_port_t *port;
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
if (cmcf->ports == NULL) {
cmcf->ports = ngx_array_create(cf->temp_pool, 2,
sizeof(ngx_rtmp_conf_port_t));
if (cmcf->ports == NULL) {
return NGX_ERROR;
}
}
sa = lsopt->sockaddr;
p = ngx_inet_get_port(sa);
port = cmcf->ports->elts;
for (i = 0; i < cmcf->ports->nelts; i++) {
if (p != port[i].port || sa->sa_family != port[i].family) {
continue;
}
/* a port is already in the port list */
return ngx_rtmp_add_addresses(cf, cscf, &port[i], lsopt);
}
/* add a port to the port list */
port = ngx_array_push(cmcf->ports);
if (port == NULL) {
return NGX_ERROR;
}
port->family = sa->sa_family;
port->port = p;
port->addrs.elts = NULL;
return ngx_rtmp_add_address(cf, cscf, port, lsopt);
}
static int ngx_libc_cdecl
ngx_rtmp_cmp_dns_wildcards(const void *one, const void *two)
{
ngx_hash_key_t *first, *second;
first = (ngx_hash_key_t *) one;
second = (ngx_hash_key_t *) two;
return ngx_dns_strcmp(first->key.data, second->key.data);
}
static ngx_int_t
ngx_rtmp_server_names(ngx_conf_t *cf, ngx_rtmp_core_main_conf_t *cmcf,
ngx_rtmp_conf_addr_t *addr)
{
ngx_int_t rc;
ngx_uint_t n, s;
ngx_hash_init_t hash;
ngx_hash_keys_arrays_t ha;
ngx_rtmp_server_name_t *name;
ngx_rtmp_core_srv_conf_t **cscfp;
#if (NGX_PCRE)
ngx_uint_t regex, i;
regex = 0;
#endif
ngx_memzero(&ha, sizeof(ngx_hash_keys_arrays_t));
ha.temp_pool = ngx_create_pool(NGX_DEFAULT_POOL_SIZE, cf->log);
if (ha.temp_pool == NULL) {
return NGX_ERROR;
}
ha.pool = cf->pool;
if (ngx_hash_keys_array_init(&ha, NGX_HASH_LARGE) != NGX_OK) {
goto failed;
}
cscfp = addr->servers.elts;
for (s = 0; s < addr->servers.nelts; s++) {
name = cscfp[s]->server_names.elts;
for (n = 0; n < cscfp[s]->server_names.nelts; n++) {
#if (NGX_PCRE)
if (name[n].regex) {
regex++;
continue;
}
#endif
rc = ngx_hash_add_key(&ha, &name[n].name, name[n].server,
NGX_HASH_WILDCARD_KEY);
if (rc == NGX_ERROR) {
return NGX_ERROR;
}
if (rc == NGX_DECLINED) {
ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
"invalid server name or wildcard \"%V\" on %s",
&name[n].name, addr->opt.addr);
return NGX_ERROR;
}
if (rc == NGX_BUSY) {
ngx_log_error(NGX_LOG_WARN, cf->log, 0,
"conflicting server name \"%V\" on %s, ignored",
&name[n].name, addr->opt.addr);
}
}
}
hash.key = ngx_hash_key_lc;
hash.max_size = cmcf->server_names_hash_max_size;
hash.bucket_size = cmcf->server_names_hash_bucket_size;
hash.name = "rtmp_server_names_hash";
hash.pool = cf->pool;
if (ha.keys.nelts) {
hash.hash = &addr->hash;
hash.temp_pool = NULL;
if (ngx_hash_init(&hash, ha.keys.elts, ha.keys.nelts) != NGX_OK) {
goto failed;
}
}
if (ha.dns_wc_head.nelts) {
ngx_qsort(ha.dns_wc_head.elts, (size_t) ha.dns_wc_head.nelts,
sizeof(ngx_hash_key_t), ngx_rtmp_cmp_dns_wildcards);
hash.hash = NULL;
hash.temp_pool = ha.temp_pool;
if (ngx_hash_wildcard_init(&hash, ha.dns_wc_head.elts,
ha.dns_wc_head.nelts)
!= NGX_OK)
{
goto failed;
}
addr->wc_head = (ngx_hash_wildcard_t *) hash.hash;
}
if (ha.dns_wc_tail.nelts) {
ngx_qsort(ha.dns_wc_tail.elts, (size_t) ha.dns_wc_tail.nelts,
sizeof(ngx_hash_key_t), ngx_rtmp_cmp_dns_wildcards);
hash.hash = NULL;
hash.temp_pool = ha.temp_pool;
if (ngx_hash_wildcard_init(&hash, ha.dns_wc_tail.elts,
ha.dns_wc_tail.nelts)
!= NGX_OK)
{
goto failed;
}
addr->wc_tail = (ngx_hash_wildcard_t *) hash.hash;
}
ngx_destroy_pool(ha.temp_pool);
#if (NGX_PCRE)
if (regex == 0) {
return NGX_OK;
}
addr->nregex = regex;
addr->regex = ngx_palloc(cf->pool, regex * sizeof(ngx_rtmp_server_name_t));
if (addr->regex == NULL) {
return NGX_ERROR;
}
i = 0;
for (s = 0; s < addr->servers.nelts; s++) {
name = cscfp[s]->server_names.elts;
for (n = 0; n < cscfp[s]->server_names.nelts; n++) {
if (name[n].regex) {
addr->regex[i++] = name[n];
}
}
}
#endif
return NGX_OK;
failed:
ngx_destroy_pool(ha.temp_pool);
return NGX_ERROR;
}
static ngx_listening_t *
ngx_rtmp_add_listening(ngx_conf_t *cf, ngx_rtmp_conf_addr_t *addr)
{
ngx_listening_t *ls;
ls = ngx_create_listening(cf, addr->opt.sockaddr,
addr->opt.socklen);
if (ls == NULL) {
return NULL;
}
ls->addr_ntop = 1;
ls->handler = ngx_rtmp_init_connection;
ls->pool_size = 4096;
/* TODO: error_log directive */
ls->logp = &cf->cycle->new_log;
ls->log.data = &ls->addr_text;
ls->log.handler = ngx_accept_log_error;
ls->keepalive = addr->opt.so_keepalive;
#if (NGX_HAVE_KEEPALIVE_TUNABLE)
ls->keepidle = addr->opt.tcp_keepidle;
ls->keepintvl = addr->opt.tcp_keepintvl;
ls->keepcnt = addr->opt.tcp_keepcnt;
#endif
#if (NGX_HAVE_INET6 && defined IPV6_V6ONLY)
ls->ipv6only = addr->opt.ipv6only;
#endif
#if (NGX_HAVE_REUSEPORT)
ls->reuseport = addr->opt.reuseport;
#endif
return ls;
}
static ngx_int_t
ngx_rtmp_init_listening(ngx_conf_t *cf, ngx_rtmp_conf_port_t *port)
{
ngx_uint_t i, last, bind_wildcard;
ngx_listening_t *ls;
ngx_rtmp_port_t *mport;
ngx_rtmp_conf_addr_t *addr;
addr = port->addrs.elts;
last = port->addrs.nelts;
/*
* If there is a binding to an "*:port" then we need to bind() to
* the "*:port" only and ignore other implicit bindings. The bindings
* have been already sorted: explicit bindings are on the start, then
* implicit bindings go, and wildcard binding is in the end.
*/
if (addr[last - 1].opt.wildcard) {
addr[last - 1].opt.bind = 1;
bind_wildcard = 1;
} else {
bind_wildcard = 0;
}
i = 0;
while (i < last) {
if (bind_wildcard && !addr[i].opt.bind) {
i++;
continue;
}
ls = ngx_rtmp_add_listening(cf, &addr[i]);
if (ls == NULL) {
return NGX_ERROR;
}
mport = ngx_palloc(cf->pool, sizeof(ngx_rtmp_port_t));
if (mport == NULL) {
return NGX_ERROR;
}
ls->servers = mport;
if (i == last - 1) {
mport->naddrs = last;
} else {
mport->naddrs = 1;
i = 0;
}
switch (ls->sockaddr->sa_family) {
#if (NGX_HAVE_INET6)
case AF_INET6:
if (ngx_rtmp_add_addrs6(cf, mport, addr) != NGX_OK) {
return NGX_ERROR;
}
break;
#endif
default: /* AF_INET */
if (ngx_rtmp_add_addrs(cf, mport, addr) != NGX_OK) {
return NGX_ERROR;
}
break;
}
#if nginx_version < 1015002
if (ngx_clone_listening(cf, ls) != NGX_OK) {
#else
if (ngx_clone_listening(cf->cycle, ls) != NGX_OK) {
#endif
return NGX_ERROR;
}
addr++;
last--;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_optimize_servers(ngx_conf_t *cf, ngx_rtmp_core_main_conf_t *cmcf,
ngx_array_t *ports)
{
ngx_uint_t i, p;
ngx_rtmp_conf_port_t *port;
ngx_rtmp_conf_addr_t *addr;
if (ports == NULL) {
return NGX_OK;
}
port = ports->elts;
for (p = 0; p < ports->nelts; p++) {
ngx_sort(port[p].addrs.elts, (size_t) port[p].addrs.nelts,
sizeof(ngx_rtmp_conf_addr_t), ngx_rtmp_cmp_conf_addrs);
/*
* check whether all name-based servers have the same
* configuration as a default server for given address:port
*/
addr = port[p].addrs.elts;
for (i = 0; i < port[p].addrs.nelts; ++i) {
if (addr[i].servers.nelts > 1
#if (NGX_PCRE)
|| addr[i].default_server->captures
#endif
)
{
if (ngx_rtmp_server_names(cf, cmcf, &addr[i]) != NGX_OK) {
return NGX_ERROR;
}
}
if (ngx_rtmp_init_listening(cf, &port[p]) != NGX_OK) {
return NGX_ERROR;
}
}
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_add_addrs(ngx_conf_t *cf, ngx_rtmp_port_t *mport,
ngx_rtmp_conf_addr_t *addr)
{
u_char *p;
size_t len;
ngx_uint_t i;
ngx_rtmp_in_addr_t *addrs;
struct sockaddr_in *sin;
u_char buf[NGX_SOCKADDR_STRLEN];
ngx_rtmp_virtual_names_t *vn;
mport->addrs = ngx_pcalloc(cf->pool,
mport->naddrs * sizeof(ngx_rtmp_in_addr_t));
if (mport->addrs == NULL) {
return NGX_ERROR;
}
addrs = mport->addrs;
for (i = 0; i < mport->naddrs; i++) {
sin = (struct sockaddr_in *) addr[i].opt.sockaddr;
addrs[i].addr = sin->sin_addr.s_addr;
addrs[i].conf.default_server = addr[i].default_server;
len = ngx_sock_ntop(addr[i].opt.sockaddr,
#if (nginx_version >= 1005003)
addr[i].opt.socklen,
#endif
buf, NGX_SOCKADDR_STRLEN, 1);
p = ngx_pnalloc(cf->pool, len);
if (p == NULL) {
return NGX_ERROR;
}
ngx_memcpy(p, buf, len);
addrs[i].conf.addr_text.len = len;
addrs[i].conf.addr_text.data = p;
addrs[i].conf.proxy_protocol = addr->opt.proxy_protocol;
if (addr[i].hash.buckets == NULL
&& (addr[i].wc_head == NULL
|| addr[i].wc_head->hash.buckets == NULL)
&& (addr[i].wc_tail == NULL
|| addr[i].wc_tail->hash.buckets == NULL)
#if (NGX_PCRE)
&& addr[i].nregex == 0
#endif
)
{
continue;
}
vn = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_virtual_names_t));
if (vn == NULL) {
return NGX_ERROR;
}
addrs[i].conf.virtual_names = vn;
vn->names.hash = addr[i].hash;
vn->names.wc_head = addr[i].wc_head;
vn->names.wc_tail = addr[i].wc_tail;
#if (NGX_PCRE)
vn->nregex = addr[i].nregex;
vn->regex = addr[i].regex;
#endif
}
return NGX_OK;
}
#if (NGX_HAVE_INET6)
static ngx_int_t
ngx_rtmp_add_addrs6(ngx_conf_t *cf, ngx_rtmp_port_t *mport,
ngx_rtmp_conf_addr_t *addr)
{
u_char *p;
size_t len;
ngx_uint_t i;
ngx_rtmp_in6_addr_t *addrs6;
struct sockaddr_in6 *sin6;
u_char buf[NGX_SOCKADDR_STRLEN];
ngx_rtmp_virtual_names_t *vn;
mport->addrs = ngx_pcalloc(cf->pool,
mport->naddrs * sizeof(ngx_rtmp_in6_addr_t));
if (mport->addrs == NULL) {
return NGX_ERROR;
}
addrs6 = mport->addrs;
for (i = 0; i < mport->naddrs; i++) {
sin6 = (struct sockaddr_in6 *) addr[i].opt.sockaddr;
addrs6[i].addr6 = sin6->sin6_addr;
addrs6[i].conf.default_server = addr[i].default_server;
len = ngx_sock_ntop(addr[i].opt.sockaddr,
#if (nginx_version >= 1005003)
addr[i].opt.socklen,
#endif
buf, NGX_SOCKADDR_STRLEN, 1);
p = ngx_pnalloc(cf->pool, len);
if (p == NULL) {
return NGX_ERROR;
}
ngx_memcpy(p, buf, len);
addrs6[i].conf.addr_text.len = len;
addrs6[i].conf.addr_text.data = p;
addrs6[i].conf.proxy_protocol = addr->opt.proxy_protocol;
if (addr[i].hash.buckets == NULL
&& (addr[i].wc_head == NULL
|| addr[i].wc_head->hash.buckets == NULL)
&& (addr[i].wc_tail == NULL
|| addr[i].wc_tail->hash.buckets == NULL)
#if (NGX_PCRE)
&& addr[i].nregex == 0
#endif
)
{
continue;
}
vn = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_virtual_names_t));
if (vn == NULL) {
return NGX_ERROR;
}
addrs6[i].conf.virtual_names = vn;
vn->names.hash = addr[i].hash;
vn->names.wc_head = addr[i].wc_head;
vn->names.wc_tail = addr[i].wc_tail;
#if (NGX_PCRE)
vn->nregex = addr[i].nregex;
vn->regex = addr[i].regex;
#endif
}
return NGX_OK;
}
#endif
static ngx_int_t
ngx_rtmp_cmp_conf_addrs(const void *one, const void *two)
{
ngx_rtmp_conf_addr_t *first, *second;
first = (ngx_rtmp_conf_addr_t *) one;
second = (ngx_rtmp_conf_addr_t *) two;
if (first->opt.wildcard) {
/* a wildcard must be the last resort, shift it to the end */
return 1;
}
if (first->opt.bind && !second->opt.bind) {
/* shift explicit bind()ed addresses to the start */
return -1;
}
if (!first->opt.bind && second->opt.bind) {
/* shift explicit bind()ed addresses to the start */
return 1;
}
/* do not sort by default */
return 0;
}
ngx_int_t
ngx_rtmp_fire_event(ngx_rtmp_session_t *s, ngx_uint_t evt,
ngx_rtmp_header_t *h, ngx_chain_t *in)
{
ngx_rtmp_core_main_conf_t *cmcf;
ngx_array_t *ch;
ngx_rtmp_handler_pt *hh;
size_t n;
cmcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_core_module);
ch = &cmcf->events[evt];
hh = ch->elts;
for(n = 0; n < ch->nelts; ++n, ++hh) {
if (*hh && (*hh)(s, h, in) != NGX_OK) {
return NGX_ERROR;
}
}
return NGX_OK;
}
void *
ngx_rtmp_rmemcpy(void *dst, const void* src, size_t n)
{
u_char *d, *s;
d = dst;
s = (u_char*)src + n - 1;
while(s >= (u_char*)src) {
*d++ = *s--;
}
return dst;
}
ngx_int_t
ngx_rtmp_find_virtual_server(ngx_rtmp_virtual_names_t *virtual_names,
ngx_str_t *host, ngx_rtmp_core_srv_conf_t **cscfp)
{
ngx_rtmp_core_srv_conf_t *cscf;
if (virtual_names == NULL) {
return NGX_DECLINED;
}
cscf = ngx_hash_find_combined(&virtual_names->names,
ngx_hash_key(host->data, host->len),
host->data, host->len);
if (cscf) {
*cscfp = cscf;
return NGX_OK;
}
#if (NGX_PCRE)
if (host->len && virtual_names->nregex) {
ngx_int_t n;
ngx_uint_t i;
ngx_rtmp_server_name_t *sn;
sn = virtual_names->regex;
for (i = 0; i < virtual_names->nregex; ++i) {
n = ngx_regex_exec(sn[i].regex->regex, host, NULL, 0);
if (n == NGX_REGEX_NO_MATCHED) {
continue;
}
if (n >= 0) {
*cscfp = sn[i].server;
return NGX_OK;
}
return NGX_ERROR;
}
}
#endif
return NGX_DECLINED;
}
ngx_int_t
ngx_rtmp_set_virtual_server(ngx_rtmp_session_t *s, ngx_str_t *host)
{
ngx_int_t rc;
ngx_rtmp_addr_conf_t *addr_conf;
ngx_rtmp_core_srv_conf_t *cscf;
#if (NGX_SUPPRESS_WARN)
cscf = NULL;
#endif
addr_conf = s->addr_conf;
rc = ngx_rtmp_find_virtual_server(addr_conf->virtual_names, host, &cscf);
if (rc == NGX_ERROR) {
return NGX_ERROR;
}
if (rc == NGX_DECLINED) {
return NGX_OK;
}
s->srv_conf = cscf->ctx->srv_conf;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_init_process(ngx_cycle_t *cycle)
{
#if (nginx_version >= 1007005)
ngx_queue_init(&ngx_rtmp_init_queue);
#endif
return NGX_OK;
}
|
281677160/openwrt-package
| 32,580 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp.h
|
/*
* Copyright (C) Roman Arutyunyan
*/
#ifndef _NGX_RTMP_H_INCLUDED_
#define _NGX_RTMP_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include <ngx_event_connect.h>
#include <nginx.h>
#include <ngx_http.h>
#include "ngx_rtmp_amf.h"
#include "ngx_rtmp_bandwidth.h"
#include "ngx_http_client.h"
#include "ngx_netcall.h"
#include "ngx_map.h"
#if (NGX_WIN32)
typedef __int8 int8_t;
typedef unsigned __int8 uint8_t;
#endif
#if (NGX_PCRE)
typedef struct {
ngx_uint_t capture;
ngx_int_t index;
} ngx_rtmp_regex_variable_t;
typedef struct {
ngx_regex_t *regex;
ngx_uint_t ncaptures;
ngx_rtmp_regex_variable_t *variables;
ngx_uint_t nvariables;
ngx_str_t name;
} ngx_rtmp_regex_t;
typedef struct {
ngx_rtmp_regex_t *regex;
void *value;
} ngx_rtmp_map_regex_t;
#endif
typedef struct {
void **main_conf;
void **srv_conf;
void **app_conf;
} ngx_rtmp_conf_ctx_t;
typedef struct {
void *addrs;
ngx_uint_t naddrs;
} ngx_rtmp_port_t;
typedef struct {
int family;
in_port_t port;
ngx_array_t addrs; /* array of ngx_rtmp_conf_addr_t */
} ngx_rtmp_conf_port_t;
#define NGX_RTMP_VERSION 3
#define NGX_LOG_DEBUG_RTMP NGX_LOG_DEBUG_CORE
#define NGX_RTMP_DEFAULT_CHUNK_SIZE 128
/* RTMP message types */
#define NGX_RTMP_MSG_CHUNK_SIZE 1
#define NGX_RTMP_MSG_ABORT 2
#define NGX_RTMP_MSG_ACK 3
#define NGX_RTMP_MSG_USER 4
#define NGX_RTMP_MSG_ACK_SIZE 5
#define NGX_RTMP_MSG_BANDWIDTH 6
#define NGX_RTMP_MSG_EDGE 7
#define NGX_RTMP_MSG_AUDIO 8
#define NGX_RTMP_MSG_VIDEO 9
#define NGX_RTMP_MSG_AMF3_META 15
#define NGX_RTMP_MSG_AMF3_SHARED 16
#define NGX_RTMP_MSG_AMF3_CMD 17
#define NGX_RTMP_MSG_AMF_META 18
#define NGX_RTMP_MSG_AMF_SHARED 19
#define NGX_RTMP_MSG_AMF_CMD 20
#define NGX_RTMP_MSG_AGGREGATE 22
#define NGX_RTMP_MSG_MAX 22
#define NGX_RTMP_CONNECT NGX_RTMP_MSG_MAX + 1
#define NGX_RTMP_DISCONNECT NGX_RTMP_MSG_MAX + 2
#define NGX_RTMP_HANDSHAKE_DONE NGX_RTMP_MSG_MAX + 3
#define NGX_MPEGTS_MSG_AUDIO NGX_RTMP_MSG_MAX + 4
#define NGX_MPEGTS_MSG_VIDEO NGX_RTMP_MSG_MAX + 5
#define NGX_MPEGTS_MSG_PATPMT NGX_RTMP_MSG_MAX + 6
#define NGX_MPEGTS_MSG_M3U8 NGX_RTMP_MSG_MAX + 7
#define NGX_MPEGTS_MSG_CLOSE NGX_RTMP_MSG_MAX + 8
#define NGX_RTMP_MAX_EVENT NGX_RTMP_MSG_MAX + 9
/* RMTP control message types */
#define NGX_RTMP_USER_STREAM_BEGIN 0
#define NGX_RTMP_USER_STREAM_EOF 1
#define NGX_RTMP_USER_STREAM_DRY 2
#define NGX_RTMP_USER_SET_BUFLEN 3
#define NGX_RTMP_USER_RECORDED 4
#define NGX_RTMP_USER_PING_REQUEST 6
#define NGX_RTMP_USER_PING_RESPONSE 7
#define NGX_RTMP_USER_UNKNOWN 8
#define NGX_RTMP_USER_BUFFER_END 31
/* Chunk header:
* max 3 basic header
* + max 11 message header
* + max 4 extended header (timestamp) */
#define NGX_RTMP_MAX_CHUNK_HEADER 18
#define IS_IRAP(_nal_type_) (_nal_type_ >= 16 && _nal_type_ <= 23)
/* Audio codecs */
enum {
/* Uncompressed codec id is actually 0,
* but we use another value for consistency */
NGX_RTMP_AUDIO_UNCOMPRESSED = 16,
NGX_RTMP_AUDIO_ADPCM = 1,
NGX_RTMP_AUDIO_MP3 = 2,
NGX_RTMP_AUDIO_LINEAR_LE = 3,
NGX_RTMP_AUDIO_NELLY16 = 4,
NGX_RTMP_AUDIO_NELLY8 = 5,
NGX_RTMP_AUDIO_NELLY = 6,
NGX_RTMP_AUDIO_G711A = 7,
NGX_RTMP_AUDIO_G711U = 8,
NGX_RTMP_AUDIO_AAC = 10,
NGX_RTMP_AUDIO_SPEEX = 11,
NGX_RTMP_AUDIO_MP3_8 = 14,
NGX_RTMP_AUDIO_DEVSPEC = 15,
};
/* Video codecs */
enum {
NGX_RTMP_VIDEO_JPEG = 1,
NGX_RTMP_VIDEO_SORENSON_H263 = 2,
NGX_RTMP_VIDEO_SCREEN = 3,
NGX_RTMP_VIDEO_ON2_VP6 = 4,
NGX_RTMP_VIDEO_ON2_VP6_ALPHA = 5,
NGX_RTMP_VIDEO_SCREEN2 = 6,
NGX_RTMP_VIDEO_H264 = 7,
NGX_RTMP_VIDEO_H265 = 12
};
extern ngx_int_t NGX_RTMP_HEVC_CODEC_ID;
typedef struct {
uint32_t csid; /* chunk stream id */
uint32_t timestamp; /* timestamp (delta) */
uint32_t mlen; /* message length */
uint8_t type; /* message type id */
uint32_t msid; /* message stream id */
} ngx_rtmp_header_t;
typedef struct {
ngx_rtmp_header_t hdr;
uint32_t dtime;
uint32_t len; /* current fragment length */
uint8_t ext;
ngx_chain_t *in;
} ngx_rtmp_stream_t;
typedef struct ngx_rtmp_frame_s ngx_rtmp_frame_t;
struct ngx_rtmp_frame_s {
ngx_rtmp_header_t hdr;
ngx_flag_t av_header;
ngx_flag_t keyframe;
ngx_flag_t mandatory;
ngx_uint_t ref;
ngx_rtmp_frame_t *next;
ngx_chain_t *chain;
};
typedef struct ngx_mpegts_frame_s ngx_mpegts_frame_t;
struct ngx_mpegts_frame_s {
uint64_t pts;
uint64_t dts;
ngx_uint_t pid;
ngx_uint_t sid;
ngx_uint_t cc;
unsigned key:1;
ngx_uint_t ref;
ngx_uint_t type;
ngx_uint_t length;
size_t pos;
ngx_mpegts_frame_t *next;
ngx_chain_t *chain;
};
/* disable zero-sized array warning by msvc */
#if (NGX_WIN32)
#pragma warning(push)
#pragma warning(disable:4200)
#endif
#define NGX_RTMP_LIVE 0
#define NGX_HTTP_FLV_LIVE 1
#define NGX_HLS_LIVE 2
#define NGX_MPEGTS_LIVE 3
typedef struct ngx_rtmp_session_s ngx_rtmp_session_t;
#define NGX_RTMP_MAX_MERGE_FRAME 64
typedef ngx_chain_t * (* ngx_rtmp_prepared_pt)(ngx_rtmp_session_t *s);
typedef struct ngx_live_stream_s ngx_live_stream_t;
typedef struct ngx_live_server_s ngx_live_server_t;
typedef struct ngx_rtmp_addr_conf_s ngx_rtmp_addr_conf_t;
#define NGX_LIVE_INIT 0
#define NGX_LIVE_HANDSHAKE_DONE 1
#define NGX_LIVE_CONNECT 2
#define NGX_LIVE_CREATE_STREAM 3
#define NGX_LIVE_PUBLISH 4
#define NGX_LIVE_PLAY 5
#define NGX_LIVE_AV 6
#define NGX_LIVE_CLOSE 7
#define NGX_LIVE_INTERNAL_ERR 0
#define NGX_LIVE_NORMAL_CLOSE 1
#define NGX_LIVE_RTMP_SEND_ERR 2
#define NGX_LIVE_RTMP_SEND_TIMEOUT 3
#define NGX_LIVE_FLV_SEND_ERR 4
#define NGX_LIVE_FLV_SEND_TIMEOUT 5
#define NGX_LIVE_RTMP_RECV_ERR 6
#define NGX_LIVE_FLV_RECV_ERR 7
#define NGX_LIVE_RELAY_TRANSIT 8
#define NGX_LIVE_RELAY_TIMEOUT 9
#define NGX_LIVE_CONTROL_DROP 10
#define NGX_LIVE_DROP_IDLE 11
#define NGX_LIVE_OCLP_NOTIFY_ERR 12
#define NGX_LIVE_OCLP_RELAY_ERR 13
#define NGX_LIVE_OCLP_PARA_ERR 14
#define NGX_LIVE_RELAY_CLOSE 15
#define NGX_LIVE_PROCESS_EXIT 16
struct ngx_rtmp_session_s {
ngx_atomic_uint_t number;
struct sockaddr *sockaddr;
ngx_msec_t roll_back;
unsigned int destroyed:1;
ngx_flag_t pause;
ngx_int_t acodec;
ngx_int_t vcodec;
uint32_t signature; /* "RTMP" */ /* <-- FIXME wtf */
ngx_event_t close;
ngx_pool_t *pool;
ngx_log_t *log;
ngx_rtmp_addr_conf_t *addr_conf;
void **ctx;
void **main_conf;
void **srv_conf;
void **app_conf;
ngx_live_server_t *live_server;
ngx_live_stream_t *live_stream;
ngx_str_t remote_addr_text;
ngx_str_t *addr_text;
int connected;
ngx_http_variable_value_t *variables;
#if (NGX_PCRE)
ngx_uint_t ncaptures;
int *captures;
u_char *captures_data;
#endif
#if (nginx_version >= 1007005)
ngx_queue_t posted_dry_events;
#else
ngx_event_t *posted_dry_events;
#endif
/* client buffer time in msec */
uint32_t buflen;
uint32_t ack_size;
ngx_str_t groupid;
/* app/name */
ngx_str_t stream;
/* stream name in publish or play*/
ngx_str_t name;
ngx_str_t pargs; /* play or publish args */
/* connection parameters */
ngx_str_t app;
ngx_str_t args;
ngx_str_t flashver;
ngx_str_t swf_url;
ngx_str_t tc_url;
uint32_t acodecs;
uint32_t vcodecs;
ngx_str_t page_url;
/* middleware */
ngx_str_t scheme;
ngx_str_t domain;
ngx_str_t serverid;
/* handshake data */
ngx_buf_t *hs_buf;
u_char *hs_digest;
unsigned hs_old:1;
ngx_uint_t hs_stage;
/* connection timestamps */
ngx_msec_t epoch;
ngx_msec_t peer_epoch;
ngx_msec_t base_time;
uint32_t current_time;
/* ping */
ngx_event_t ping_evt;
unsigned ping_active:1;
unsigned ping_reset:1;
/* auto-pushed? */
unsigned interprocess:1;
unsigned static_pull:1;
unsigned relay:1;
unsigned played:1;
unsigned published:1;
unsigned closed:1;
unsigned publishing:1;
unsigned finalized:1;
/* live type: 0- RTMP 1- http-flv 2- hls */
unsigned live_type:2;
ngx_uint_t status;
ngx_http_request_t *request;
unsigned flv_state;
ngx_uint_t flv_version;
ngx_uint_t flv_flags;
unsigned flv_data_offset;
unsigned flv_tagsize;
unsigned flv_first_pts;
/* input stream 0 (reserved by RTMP spec)
* is used as free chain link */
ngx_rtmp_stream_t *in_streams;
uint32_t in_csid;
ngx_uint_t in_chunk_size;
ngx_pool_t *in_pool;
uint32_t in_bytes;
uint32_t in_last_ack;
ngx_pool_t *in_old_pool;
ngx_int_t in_chunk_size_changing;
ngx_connection_t *connection;
/* merge frame and send */
ngx_mpegts_frame_t *prepare_mpegts_frame[NGX_RTMP_MAX_MERGE_FRAME];
ngx_rtmp_frame_t *prepare_frame[NGX_RTMP_MAX_MERGE_FRAME];
ngx_chain_t *merge[NGX_RTMP_MAX_MERGE_FRAME];
ngx_uint_t nframe;
ngx_rtmp_prepared_pt prepare_handler;
/* for trace and statistics */
ngx_int_t notify_status;
ngx_uint_t finalize_reason;
ngx_uint_t stage;
ngx_msec_t init_time;
ngx_msec_t handshake_done_time;
ngx_msec_t connect_time;
ngx_msec_t create_stream_time;
ngx_msec_t ptime; /* publish or play time */
ngx_msec_t first_data; /* audio video or metadata*/
ngx_msec_t first_metadata;
ngx_msec_t first_audio;
ngx_msec_t first_video;
ngx_msec_t close_stream_time;
/* circular buffer of RTMP message pointers */
ngx_msec_t timeout;
uint32_t out_bytes;
size_t out_pos, out_last;
ngx_chain_t *out_chain;
unsigned out_buffer:1;
size_t out_queue;
size_t out_cork;
ngx_mpegts_frame_t **mpegts_out;
ngx_rtmp_frame_t *out[0];
};
/* live stream manage */
#define NGX_LIVE_SERVERID_LEN 512
#define NGX_LIVE_STREAM_LEN 512
typedef struct ngx_rtmp_core_ctx_s ngx_rtmp_core_ctx_t;
typedef struct ngx_rtmp_live_ctx_s ngx_rtmp_live_ctx_t;
typedef struct ngx_mpegts_live_ctx_s ngx_mpegts_live_ctx_t;
typedef struct ngx_hls_live_ctx_s ngx_hls_live_ctx_t;
struct ngx_rtmp_core_ctx_s {
ngx_rtmp_core_ctx_t *next;
ngx_rtmp_session_t *session;
unsigned publishing:1;
};
#define NGX_RTMP_MAX_OCLP 8
#define NGX_RTMP_MAX_PUSH 8
struct ngx_live_stream_s {
u_char name[NGX_LIVE_STREAM_LEN];
ngx_int_t pslot;
ngx_rtmp_core_ctx_t *publish_ctx;
ngx_rtmp_core_ctx_t *play_ctx;
/* notify */
ngx_netcall_ctx_t *stream_nctx;
ngx_live_stream_t *next;
/* for live */
ngx_map_t pubctx;
ngx_rtmp_live_ctx_t *ctx;
ngx_mpegts_live_ctx_t *mpegts_ctx;
ngx_hls_live_ctx_t *hls_ctx;
ngx_rtmp_bandwidth_t bw_in;
ngx_rtmp_bandwidth_t bw_in_audio;
ngx_rtmp_bandwidth_t bw_in_video;
ngx_rtmp_bandwidth_t bw_out;
ngx_msec_t epoch;
unsigned active:1;
unsigned publishing:1;
unsigned notify_meta:1;
};
struct ngx_live_server_s {
u_char serverid[NGX_LIVE_SERVERID_LEN];
ngx_uint_t n_stream;
ngx_flag_t deleted;
ngx_live_server_t *next;
ngx_live_stream_t **streams;
};
ngx_live_server_t *ngx_live_create_server(ngx_str_t *serverid);
ngx_live_server_t *ngx_live_fetch_server(ngx_str_t *serverid);
void ngx_live_delete_server(ngx_str_t *serverid);
ngx_live_stream_t *ngx_live_create_stream(ngx_str_t *serverid,
ngx_str_t *stream);
ngx_live_stream_t *ngx_live_fetch_stream(ngx_str_t *serverid,
ngx_str_t *stream);
void ngx_live_delete_stream(ngx_str_t *serverid, ngx_str_t *stream);
void ngx_live_create_ctx(ngx_rtmp_session_t *s, unsigned publishing);
void ngx_live_delete_ctx(ngx_rtmp_session_t *s);
void ngx_live_print();
#if (NGX_WIN32)
#pragma warning(pop)
#endif
/* handler result code:
* NGX_ERROR - error
* NGX_OK - success, may continue
* NGX_DONE - success, input parsed, reply sent; need no
* more calls on this event */
typedef ngx_int_t (*ngx_rtmp_handler_pt)(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
typedef struct {
ngx_str_t name;
ngx_rtmp_handler_pt handler;
} ngx_rtmp_amf_handler_t;
typedef struct {
ngx_flag_t fast_reload;
ngx_array_t servers; /* ngx_rtmp_core_srv_conf_t */
ngx_array_t events[NGX_RTMP_MAX_EVENT];
ngx_hash_t amf_hash;
ngx_array_t amf_arrays;
ngx_array_t amf;
ngx_uint_t server_names_hash_max_size;
ngx_uint_t server_names_hash_bucket_size;
ngx_hash_t variables_hash;
ngx_array_t variables; /* ngx_http_variable_t */
ngx_array_t prefix_variables; /* ngx_http_variable_t */
ngx_uint_t ncaptures;
ngx_uint_t variables_hash_max_size;
ngx_uint_t variables_hash_bucket_size;
ngx_hash_keys_arrays_t *variables_keys;
ngx_array_t *ports; /* ngx_rtmp_conf_port_t */
} ngx_rtmp_core_main_conf_t;
/* global main conf for stats */
extern ngx_rtmp_core_main_conf_t *ngx_rtmp_core_main_conf;
typedef struct {
ngx_array_t applications; /* ngx_rtmp_core_app_conf_t */
ngx_str_t name;
ngx_uint_t merge_frame;
ngx_flag_t tcp_nodelay;
void **app_conf;
ngx_uint_t hevc_codec;
} ngx_rtmp_core_app_conf_t;
typedef struct ngx_rtmp_core_srv_conf_s {
ngx_array_t applications; /* ngx_rtmp_core_app_conf_t */
ngx_rtmp_core_app_conf_t *default_app;
ngx_msec_t timeout;
ngx_msec_t ping;
ngx_msec_t ping_timeout;
ngx_flag_t so_keepalive;
ngx_int_t max_streams;
ngx_uint_t ack_window;
ngx_int_t chunk_size;
ngx_pool_t *pool;
ngx_chain_t *free;
ngx_chain_t *free_hs;
size_t max_message;
ngx_flag_t play_time_fix;
ngx_flag_t publish_time_fix;
ngx_flag_t busy;
size_t out_queue;
size_t out_cork;
ngx_msec_t buflen;
ngx_rtmp_conf_ctx_t *ctx;
unsigned listen:1;
#if (NGX_PCRE)
unsigned captures:1;
#endif
ngx_str_t server_name;
ngx_str_t serverid;
/* array of the ngx_rtmp_server_name_t, "server_name" directive */
ngx_array_t server_names;
} ngx_rtmp_core_srv_conf_t;
typedef struct {
#if (NGX_PCRE)
ngx_rtmp_regex_t *regex;
#endif
ngx_rtmp_core_srv_conf_t *server; /* virtual name server conf */
ngx_str_t name;
} ngx_rtmp_server_name_t;
typedef struct {
ngx_hash_combined_t names;
ngx_uint_t nregex;
ngx_rtmp_server_name_t *regex;
} ngx_rtmp_virtual_names_t;
struct ngx_rtmp_addr_conf_s {
ngx_rtmp_core_srv_conf_t *default_server;
ngx_rtmp_virtual_names_t *virtual_names;
ngx_str_t addr_text;
unsigned proxy_protocol:1;
};
typedef struct {
in_addr_t addr;
ngx_rtmp_addr_conf_t conf;
} ngx_rtmp_in_addr_t;
#if (NGX_HAVE_INET6)
typedef struct {
struct in6_addr addr6;
ngx_rtmp_addr_conf_t conf;
} ngx_rtmp_in6_addr_t;
#endif
typedef struct {
struct sockaddr *sockaddr;
socklen_t socklen;
unsigned set:1;
unsigned default_server:1;
unsigned bind:1;
unsigned wildcard:1;
#if (NGX_HAVE_INET6 && defined IPV6_V6ONLY)
unsigned ipv6only:2;
#endif
unsigned reuseport:1;
unsigned so_keepalive:2;
unsigned proxy_protocol:1;
#if (NGX_HAVE_KEEPALIVE_TUNABLE)
int tcp_keepidle;
int tcp_keepintvl;
int tcp_keepcnt;
#endif
u_char addr[NGX_SOCKADDR_STRLEN + 1];
} ngx_rtmp_listen_opt_t;
typedef struct {
ngx_rtmp_listen_opt_t opt;
ngx_hash_t hash;
ngx_hash_wildcard_t *wc_head;
ngx_hash_wildcard_t *wc_tail;
#if (NGX_PCRE)
ngx_uint_t nregex;
ngx_rtmp_server_name_t *regex;
#endif
/* the default server configuration for this address:port */
ngx_rtmp_core_srv_conf_t *default_server;
ngx_array_t servers; /* array of ngx_http_core_srv_conf_t */
} ngx_rtmp_conf_addr_t;
/* nginx dynamic conf */
typedef struct {
ngx_str_t serverid;
} ngx_rtmp_core_srv_dconf_t;
typedef struct {
ngx_int_t (*preconfiguration)(ngx_conf_t *cf);
ngx_int_t (*postconfiguration)(ngx_conf_t *cf);
void *(*create_main_conf)(ngx_conf_t *cf);
char *(*init_main_conf)(ngx_conf_t *cf, void *conf);
void *(*create_srv_conf)(ngx_conf_t *cf);
char *(*merge_srv_conf)(ngx_conf_t *cf, void *prev,
void *conf);
void *(*create_app_conf)(ngx_conf_t *cf);
char *(*merge_app_conf)(ngx_conf_t *cf, void *prev,
void *conf);
} ngx_rtmp_module_t;
#define NGX_RTMP_MODULE 0x504D5452 /* "RTMP" */
#define NGX_RTMP_MAIN_CONF 0x02000000
#define NGX_RTMP_SRV_CONF 0x04000000
#define NGX_RTMP_APP_CONF 0x08000000
#define NGX_RTMP_REC_CONF 0x10000000
#define NGX_RTMP_MAIN_CONF_OFFSET offsetof(ngx_rtmp_conf_ctx_t, main_conf)
#define NGX_RTMP_SRV_CONF_OFFSET offsetof(ngx_rtmp_conf_ctx_t, srv_conf)
#define NGX_RTMP_APP_CONF_OFFSET offsetof(ngx_rtmp_conf_ctx_t, app_conf)
#define ngx_rtmp_get_module_ctx(s, module) (s)->ctx[module.ctx_index]
#define ngx_rtmp_set_ctx(s, c, module) s->ctx[module.ctx_index] = c;
#define ngx_rtmp_delete_ctx(s, module) s->ctx[module.ctx_index] = NULL;
#define ngx_rtmp_get_module_main_conf(s, module) \
(s)->main_conf[module.ctx_index]
#define ngx_rtmp_get_module_srv_conf(s, module) (s)->srv_conf[module.ctx_index]
#define ngx_rtmp_get_module_app_conf(s, module) ((s)->app_conf ? \
(s)->app_conf[module.ctx_index] : NULL)
#define ngx_rtmp_conf_get_module_main_conf(cf, module) \
((ngx_rtmp_conf_ctx_t *) cf->ctx)->main_conf[module.ctx_index]
#define ngx_rtmp_conf_get_module_srv_conf(cf, module) \
((ngx_rtmp_conf_ctx_t *) cf->ctx)->srv_conf[module.ctx_index]
#define ngx_rtmp_conf_get_module_app_conf(cf, module) \
((ngx_rtmp_conf_ctx_t *) cf->ctx)->app_conf[module.ctx_index]
#define ngx_rtmp_cycle_get_module_main_conf(cycle, module) \
(cycle->conf_ctx[ngx_rtmp_module.index] ? \
((ngx_rtmp_conf_ctx_t *) cycle->conf_ctx[ngx_rtmp_module.index]) \
->main_conf[module.ctx_index]: \
NULL)
/* for virtual server */
#if (NGX_PCRE)
ngx_rtmp_regex_t *ngx_rtmp_regex_compile(ngx_conf_t *cf,
ngx_regex_compile_t *rc);
ngx_int_t ngx_rtmp_regex_exec(ngx_rtmp_session_t *s, ngx_rtmp_regex_t *re,
ngx_str_t *str);
#endif
ngx_int_t ngx_rtmp_add_listen(ngx_conf_t *cf, ngx_rtmp_core_srv_conf_t *cscf,
ngx_rtmp_listen_opt_t *lsopt);
ngx_int_t ngx_rtmp_set_virtual_server(ngx_rtmp_session_t *s, ngx_str_t *host);
#ifdef NGX_DEBUG
char* ngx_rtmp_message_type(uint8_t type);
char* ngx_rtmp_user_message_type(uint16_t evt);
#endif
typedef struct {
ngx_array_t urls; // ngx_live_relay_url_t
ngx_str_t domain;
ngx_str_t app;
ngx_str_t name;
ngx_str_t pargs;
ngx_str_t referer; // rtmp page_url
ngx_str_t user_agent; // rtmp flashver
ngx_str_t stream;
void *tag; // module create relay
} ngx_live_relay_t;
void ngx_rtmp_init_connection(ngx_connection_t *c);
ngx_rtmp_session_t *ngx_rtmp_create_session(ngx_rtmp_addr_conf_t *addr_conf);
ngx_rtmp_session_t *ngx_rtmp_create_relay_session(ngx_rtmp_session_t *s,
void *tag);
ngx_rtmp_session_t *ngx_rtmp_create_static_session(ngx_live_relay_t *relay,
ngx_rtmp_addr_conf_t *addr_conf, void *tag);
void ngx_rtmp_set_combined_log(ngx_rtmp_session_t *s, void *d,
ngx_log_handler_pt h);
void ngx_rtmp_init_session(ngx_rtmp_session_t *s, ngx_connection_t *c);
void ngx_rtmp_finalize_session(ngx_rtmp_session_t *s);
void ngx_rtmp_finalize_fake_session(ngx_rtmp_session_t *s);
void ngx_rtmp_handshake(ngx_rtmp_session_t *s);
void ngx_rtmp_client_handshake(ngx_rtmp_session_t *s, unsigned async);
void ngx_rtmp_free_handshake_buffers(ngx_rtmp_session_t *s);
void ngx_rtmp_cycle(ngx_rtmp_session_t *s);
void ngx_rtmp_reset_ping(ngx_rtmp_session_t *s);
ngx_int_t ngx_rtmp_fire_event(ngx_rtmp_session_t *s, ngx_uint_t evt,
ngx_rtmp_header_t *h, ngx_chain_t *in);
ngx_int_t ngx_rtmp_set_chunk_size(ngx_rtmp_session_t *s, ngx_uint_t size);
/* Bit reverse: we need big-endians in many places */
void * ngx_rtmp_rmemcpy(void *dst, const void* src, size_t n);
#define ngx_rtmp_rcpymem(dst, src, n) \
(((u_char*)ngx_rtmp_rmemcpy(dst, src, n)) + (n))
static ngx_inline uint16_t
ngx_rtmp_r16(uint16_t n)
{
return (n << 8) | (n >> 8);
}
static ngx_inline uint32_t
ngx_rtmp_r32(uint32_t n)
{
return (n << 24) | ((n << 8) & 0xff0000) | ((n >> 8) & 0xff00) | (n >> 24);
}
static ngx_inline uint64_t
ngx_rtmp_r64(uint64_t n)
{
return (uint64_t) ngx_rtmp_r32((uint32_t) n) << 32 |
ngx_rtmp_r32((uint32_t) (n >> 32));
}
ngx_int_t
ngx_rtmp_find_virtual_server(ngx_rtmp_virtual_names_t *virtual_names,
ngx_str_t *host, ngx_rtmp_core_srv_conf_t **cscfp);
/* Receiving messages */
ngx_int_t ngx_rtmp_receive_message(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
ngx_int_t ngx_rtmp_protocol_message_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
ngx_int_t ngx_rtmp_user_message_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
ngx_int_t ngx_rtmp_aggregate_message_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
ngx_int_t ngx_rtmp_amf_message_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
ngx_int_t ngx_rtmp_amf_shared_object_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
/* Shared output buffers */
ngx_int_t ngx_rtmp_prepare_merge_frame(ngx_rtmp_session_t *s);
void ngx_rtmp_free_merge_frame(ngx_rtmp_session_t *s);
void ngx_rtmp_shared_append_chain(ngx_rtmp_frame_t *frame, size_t size,
ngx_chain_t *cl, ngx_flag_t mandatory);
ngx_rtmp_frame_t *ngx_rtmp_shared_alloc_frame(size_t size, ngx_chain_t *cl,
ngx_flag_t mandatory);
void ngx_rtmp_shared_free_frame(ngx_rtmp_frame_t *frame);
#define ngx_rtmp_shared_acquire_frame(frame) ++frame->ref;
ngx_chain_t *ngx_rtmp_shared_state(ngx_http_request_t *r);
void ngx_mpegts_shared_append_chain(ngx_mpegts_frame_t *frame, ngx_chain_t *cl,
ngx_flag_t mandatory);
ngx_mpegts_frame_t *ngx_rtmp_shared_alloc_mpegts_frame(ngx_chain_t *cl,
ngx_flag_t mandatory);
void ngx_rtmp_shared_free_mpegts_frame(ngx_mpegts_frame_t *frame);
#define ngx_rtmp_shared_acquire_mpegts_frame(frame) ++frame->ref;
/* Sending messages */
ngx_int_t ngx_rtmp_send_message(ngx_rtmp_session_t *s, ngx_rtmp_frame_t *out,
ngx_uint_t priority);
/* GOP */
ngx_int_t ngx_rtmp_gop_cache(ngx_rtmp_session_t *s, ngx_rtmp_frame_t *frame);
ngx_int_t ngx_rtmp_gop_send(ngx_rtmp_session_t *s, ngx_rtmp_session_t *ss);
/* RTMP Relation server */
ngx_rtmp_addr_conf_t *ngx_rtmp_find_related_addr_conf(ngx_cycle_t *cycle,
ngx_str_t *addr);
/* core */
ngx_int_t ngx_rtmp_arg(ngx_rtmp_session_t *s, u_char *name, size_t len,
ngx_str_t *value);
/* Note on priorities:
* the bigger value the lower the priority.
* priority=0 is the highest */
#define NGX_RTMP_LIMIT_SOFT 0
#define NGX_RTMP_LIMIT_HARD 1
#define NGX_RTMP_LIMIT_DYNAMIC 2
/* Protocol control messages */
ngx_rtmp_frame_t *ngx_rtmp_create_chunk_size(ngx_rtmp_session_t *s,
uint32_t chunk_size);
ngx_rtmp_frame_t *ngx_rtmp_create_abort(ngx_rtmp_session_t *s,
uint32_t csid);
ngx_rtmp_frame_t *ngx_rtmp_create_ack(ngx_rtmp_session_t *s,
uint32_t seq);
ngx_rtmp_frame_t *ngx_rtmp_create_ack_size(ngx_rtmp_session_t *s,
uint32_t ack_size);
ngx_rtmp_frame_t *ngx_rtmp_create_bandwidth(ngx_rtmp_session_t *s,
uint32_t ack_size, uint8_t limit_type);
ngx_int_t ngx_rtmp_send_chunk_size(ngx_rtmp_session_t *s,
uint32_t chunk_size);
ngx_int_t ngx_rtmp_send_abort(ngx_rtmp_session_t *s,
uint32_t csid);
ngx_int_t ngx_rtmp_send_ack(ngx_rtmp_session_t *s,
uint32_t seq);
ngx_int_t ngx_rtmp_send_ack_size(ngx_rtmp_session_t *s,
uint32_t ack_size);
ngx_int_t ngx_rtmp_send_bandwidth(ngx_rtmp_session_t *s,
uint32_t ack_size, uint8_t limit_type);
/* User control messages */
ngx_rtmp_frame_t *ngx_rtmp_create_stream_begin(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_rtmp_frame_t *ngx_rtmp_create_stream_eof(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_rtmp_frame_t *ngx_rtmp_create_stream_dry(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_rtmp_frame_t *ngx_rtmp_create_set_buflen(ngx_rtmp_session_t *s,
uint32_t msid, uint32_t buflen_msec);
ngx_rtmp_frame_t *ngx_rtmp_create_recorded(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_rtmp_frame_t *ngx_rtmp_create_ping_request(ngx_rtmp_session_t *s,
uint32_t timestamp);
ngx_rtmp_frame_t *ngx_rtmp_create_ping_response(ngx_rtmp_session_t *s,
uint32_t timestamp);
ngx_int_t ngx_rtmp_send_stream_begin(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_int_t ngx_rtmp_send_stream_eof(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_int_t ngx_rtmp_send_stream_dry(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_int_t ngx_rtmp_send_set_buflen(ngx_rtmp_session_t *s,
uint32_t msid, uint32_t buflen_msec);
ngx_int_t ngx_rtmp_send_recorded(ngx_rtmp_session_t *s,
uint32_t msid);
ngx_int_t ngx_rtmp_send_ping_request(ngx_rtmp_session_t *s,
uint32_t timestamp);
ngx_int_t ngx_rtmp_send_ping_response(ngx_rtmp_session_t *s,
uint32_t timestamp);
/* AMF sender/receiver */
ngx_int_t ngx_rtmp_append_amf(ngx_rtmp_session_t *s,
ngx_chain_t **first, ngx_chain_t **last,
ngx_rtmp_amf_elt_t *elts, size_t nelts);
ngx_int_t ngx_rtmp_receive_amf(ngx_rtmp_session_t *s, ngx_chain_t *in,
ngx_rtmp_amf_elt_t *elts, size_t nelts);
ngx_rtmp_frame_t *ngx_rtmp_create_amf(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_rtmp_amf_elt_t *elts, size_t nelts);
ngx_int_t ngx_rtmp_send_amf(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_rtmp_amf_elt_t *elts, size_t nelts);
/* AMF status sender */
ngx_rtmp_frame_t *ngx_rtmp_create_error(ngx_rtmp_session_t *s, char *code,
char* level, char *desc);
ngx_rtmp_frame_t *ngx_rtmp_create_status(ngx_rtmp_session_t *s, char *code,
char* level, char *desc);
ngx_rtmp_frame_t *ngx_rtmp_create_play_status(ngx_rtmp_session_t *s, char *code,
char* level, ngx_uint_t duration, ngx_uint_t bytes);
ngx_rtmp_frame_t *ngx_rtmp_create_sample_access(ngx_rtmp_session_t *s);
ngx_int_t ngx_rtmp_send_error(ngx_rtmp_session_t *s, char *code,
char* level, char *desc);
ngx_int_t ngx_rtmp_send_status(ngx_rtmp_session_t *s, char *code,
char* level, char *desc);
ngx_int_t ngx_rtmp_send_play_status(ngx_rtmp_session_t *s, char *code,
char* level, ngx_uint_t duration, ngx_uint_t bytes);
ngx_int_t ngx_rtmp_send_sample_access(ngx_rtmp_session_t *s);
void ngx_rtmp_mpegts_mux(ngx_rtmp_session_t *s);
/* Frame types */
#define NGX_RTMP_VIDEO_KEY_FRAME 1
#define NGX_RTMP_VIDEO_INTER_FRAME 2
#define NGX_RTMP_VIDEO_DISPOSABLE_FRAME 3
static ngx_inline ngx_int_t
ngx_rtmp_get_video_frame_type(ngx_chain_t *in)
{
return (in->buf->pos[0] & 0xf0) >> 4;
}
static ngx_inline ngx_int_t
ngx_rtmp_is_codec_header(ngx_chain_t *in)
{
return in->buf->pos + 1 < in->buf->last && in->buf->pos[1] == 0;
}
extern ngx_rtmp_bandwidth_t ngx_rtmp_bw_out;
extern ngx_rtmp_bandwidth_t ngx_rtmp_bw_in;
extern ngx_uint_t ngx_rtmp_naccepted;
#if (nginx_version >= 1007011)
extern ngx_queue_t ngx_rtmp_init_queue;
#elif (nginx_version >= 1007005)
extern ngx_thread_volatile ngx_queue_t ngx_rtmp_init_queue;
#else
extern ngx_thread_volatile ngx_event_t *ngx_rtmp_init_queue;
#endif
extern ngx_uint_t ngx_rtmp_max_module;
extern ngx_module_t ngx_rtmp_module;
extern ngx_module_t ngx_rtmp_core_module;
#endif /* _NGX_RTMP_H_INCLUDED_ */
|
2881099/FreeSql.AdminLTE
| 7,659 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/daterangepicker/daterangepicker.css
|
.daterangepicker {
position: absolute;
color: inherit;
background-color: #fff;
border-radius: 4px;
border: 1px solid #ddd;
width: 278px;
max-width: none;
padding: 0;
margin-top: 7px;
top: 100px;
left: 20px;
z-index: 3001;
display: none;
font-family: arial;
font-size: 15px;
line-height: 1em;
}
.daterangepicker:before, .daterangepicker:after {
position: absolute;
display: inline-block;
border-bottom-color: rgba(0, 0, 0, 0.2);
content: '';
}
.daterangepicker:before {
top: -7px;
border-right: 7px solid transparent;
border-left: 7px solid transparent;
border-bottom: 7px solid #ccc;
}
.daterangepicker:after {
top: -6px;
border-right: 6px solid transparent;
border-bottom: 6px solid #fff;
border-left: 6px solid transparent;
}
.daterangepicker.opensleft:before {
right: 9px;
}
.daterangepicker.opensleft:after {
right: 10px;
}
.daterangepicker.openscenter:before {
left: 0;
right: 0;
width: 0;
margin-left: auto;
margin-right: auto;
}
.daterangepicker.openscenter:after {
left: 0;
right: 0;
width: 0;
margin-left: auto;
margin-right: auto;
}
.daterangepicker.opensright:before {
left: 9px;
}
.daterangepicker.opensright:after {
left: 10px;
}
.daterangepicker.drop-up {
margin-top: -7px;
}
.daterangepicker.drop-up:before {
top: initial;
bottom: -7px;
border-bottom: initial;
border-top: 7px solid #ccc;
}
.daterangepicker.drop-up:after {
top: initial;
bottom: -6px;
border-bottom: initial;
border-top: 6px solid #fff;
}
.daterangepicker.single .daterangepicker .ranges, .daterangepicker.single .drp-calendar {
float: none;
}
.daterangepicker.single .drp-selected {
display: none;
}
.daterangepicker.show-calendar .drp-calendar {
display: block;
}
.daterangepicker.show-calendar .drp-buttons {
display: block;
}
.daterangepicker.auto-apply .drp-buttons {
display: none;
}
.daterangepicker .drp-calendar {
display: none;
max-width: 270px;
}
.daterangepicker .drp-calendar.left {
padding: 8px 0 8px 8px;
}
.daterangepicker .drp-calendar.right {
padding: 8px;
}
.daterangepicker .drp-calendar.single .calendar-table {
border: none;
}
.daterangepicker .calendar-table .next span, .daterangepicker .calendar-table .prev span {
color: #fff;
border: solid black;
border-width: 0 2px 2px 0;
border-radius: 0;
display: inline-block;
padding: 3px;
}
.daterangepicker .calendar-table .next span {
transform: rotate(-45deg);
-webkit-transform: rotate(-45deg);
}
.daterangepicker .calendar-table .prev span {
transform: rotate(135deg);
-webkit-transform: rotate(135deg);
}
.daterangepicker .calendar-table th, .daterangepicker .calendar-table td {
white-space: nowrap;
text-align: center;
vertical-align: middle;
min-width: 32px;
width: 32px;
height: 24px;
line-height: 24px;
font-size: 12px;
border-radius: 4px;
border: 1px solid transparent;
white-space: nowrap;
cursor: pointer;
}
.daterangepicker .calendar-table {
border: 1px solid #fff;
border-radius: 4px;
background-color: #fff;
}
.daterangepicker .calendar-table table {
width: 100%;
margin: 0;
border-spacing: 0;
border-collapse: collapse;
}
.daterangepicker td.available:hover, .daterangepicker th.available:hover {
background-color: #eee;
border-color: transparent;
color: inherit;
}
.daterangepicker td.week, .daterangepicker th.week {
font-size: 80%;
color: #ccc;
}
.daterangepicker td.off, .daterangepicker td.off.in-range, .daterangepicker td.off.start-date, .daterangepicker td.off.end-date {
background-color: #fff;
border-color: transparent;
color: #999;
}
.daterangepicker td.in-range {
background-color: #ebf4f8;
border-color: transparent;
color: #000;
border-radius: 0;
}
.daterangepicker td.start-date {
border-radius: 4px 0 0 4px;
}
.daterangepicker td.end-date {
border-radius: 0 4px 4px 0;
}
.daterangepicker td.start-date.end-date {
border-radius: 4px;
}
.daterangepicker td.active, .daterangepicker td.active:hover {
background-color: #357ebd;
border-color: transparent;
color: #fff;
}
.daterangepicker th.month {
width: auto;
}
.daterangepicker td.disabled, .daterangepicker option.disabled {
color: #999;
cursor: not-allowed;
text-decoration: line-through;
}
.daterangepicker select.monthselect, .daterangepicker select.yearselect {
font-size: 12px;
padding: 1px;
height: auto;
margin: 0;
cursor: default;
}
.daterangepicker select.monthselect {
margin-right: 2%;
width: 56%;
}
.daterangepicker select.yearselect {
width: 40%;
}
.daterangepicker select.hourselect, .daterangepicker select.minuteselect, .daterangepicker select.secondselect, .daterangepicker select.ampmselect {
width: 50px;
margin: 0 auto;
background: #eee;
border: 1px solid #eee;
padding: 2px;
outline: 0;
font-size: 12px;
}
.daterangepicker .calendar-time {
text-align: center;
margin: 4px auto 0 auto;
line-height: 30px;
position: relative;
}
.daterangepicker .calendar-time select.disabled {
color: #ccc;
cursor: not-allowed;
}
.daterangepicker .drp-buttons {
clear: both;
text-align: right;
padding: 8px;
border-top: 1px solid #ddd;
display: none;
line-height: 12px;
vertical-align: middle;
}
.daterangepicker .drp-selected {
display: inline-block;
font-size: 12px;
padding-right: 8px;
}
.daterangepicker .drp-buttons .btn {
margin-left: 8px;
font-size: 12px;
font-weight: bold;
padding: 4px 8px;
}
.daterangepicker.show-ranges.single.rtl .drp-calendar.left {
border-right: 1px solid #ddd;
}
.daterangepicker.show-ranges.single.ltr .drp-calendar.left {
border-left: 1px solid #ddd;
}
.daterangepicker.show-ranges.rtl .drp-calendar.right {
border-right: 1px solid #ddd;
}
.daterangepicker.show-ranges.ltr .drp-calendar.left {
border-left: 1px solid #ddd;
}
.daterangepicker .ranges {
float: none;
text-align: left;
margin: 0;
}
.daterangepicker.show-calendar .ranges {
margin-top: 8px;
}
.daterangepicker .ranges ul {
list-style: none;
margin: 0 auto;
padding: 0;
width: 100%;
}
.daterangepicker .ranges li {
font-size: 12px;
padding: 8px 12px;
cursor: pointer;
}
.daterangepicker .ranges li:hover {
background-color: #eee;
}
.daterangepicker .ranges li.active {
background-color: #08c;
color: #fff;
}
/* Larger Screen Styling */
@media (min-width: 564px) {
.daterangepicker {
width: auto;
}
.daterangepicker .ranges ul {
width: 140px;
}
.daterangepicker.single .ranges ul {
width: 100%;
}
.daterangepicker.single .drp-calendar.left {
clear: none;
}
.daterangepicker.single .ranges, .daterangepicker.single .drp-calendar {
float: left;
}
.daterangepicker {
direction: ltr;
text-align: left;
}
.daterangepicker .drp-calendar.left {
clear: left;
margin-right: 0;
}
.daterangepicker .drp-calendar.left .calendar-table {
border-right: none;
border-top-right-radius: 0;
border-bottom-right-radius: 0;
}
.daterangepicker .drp-calendar.right {
margin-left: 0;
}
.daterangepicker .drp-calendar.right .calendar-table {
border-left: none;
border-top-left-radius: 0;
border-bottom-left-radius: 0;
}
.daterangepicker .drp-calendar.left .calendar-table {
padding-right: 8px;
}
.daterangepicker .ranges, .daterangepicker .drp-calendar {
float: left;
}
}
@media (min-width: 730px) {
.daterangepicker .ranges {
width: auto;
}
.daterangepicker .ranges {
float: left;
}
.daterangepicker.rtl .ranges {
float: right;
}
.daterangepicker .drp-calendar.left {
clear: none !important;
}
}
|
2881099/FreeSql.AdminLTE
| 24,260 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.min.css
|
.swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4!important;grid-row:1/4!important;grid-template-columns:1fr 99fr 1fr;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 1px rgba(0,0,0,.075),0 1px 2px rgba(0,0,0,.075),1px 2px 4px rgba(0,0,0,.075),1px 3px 8px rgba(0,0,0,.075),2px 4px 16px rgba(0,0,0,.075);pointer-events:all}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:700}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-container{display:grid;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;box-sizing:border-box;grid-template-areas:"top-start top top-end" "center-start center center-end" "bottom-start bottom-center bottom-end";grid-template-rows:minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto);grid-template-rows:minmax(min-content,auto) minmax(min-content,auto) minmax(min-content,auto);height:100%;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:0 0!important}.swal2-container.swal2-bottom-start,.swal2-container.swal2-center-start,.swal2-container.swal2-top-start{grid-template-columns:minmax(0,1fr) auto auto}.swal2-container.swal2-bottom,.swal2-container.swal2-center,.swal2-container.swal2-top{grid-template-columns:auto minmax(0,1fr) auto}.swal2-container.swal2-bottom-end,.swal2-container.swal2-center-end,.swal2-container.swal2-top-end{grid-template-columns:auto auto minmax(0,1fr)}.swal2-container.swal2-top-start>.swal2-popup{align-self:start}.swal2-container.swal2-top>.swal2-popup{grid-column:2;align-self:start;justify-self:center}.swal2-container.swal2-top-end>.swal2-popup,.swal2-container.swal2-top-right>.swal2-popup{grid-column:3;align-self:start;justify-self:end}.swal2-container.swal2-center-left>.swal2-popup,.swal2-container.swal2-center-start>.swal2-popup{grid-row:2;align-self:center}.swal2-container.swal2-center>.swal2-popup{grid-column:2;grid-row:2;align-self:center;justify-self:center}.swal2-container.swal2-center-end>.swal2-popup,.swal2-container.swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;align-self:center;justify-self:end}.swal2-container.swal2-bottom-left>.swal2-popup,.swal2-container.swal2-bottom-start>.swal2-popup{grid-column:1;grid-row:3;align-self:end}.swal2-container.swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;justify-self:center;align-self:end}.swal2-container.swal2-bottom-end>.swal2-popup,.swal2-container.swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;align-self:end;justify-self:end}.swal2-container.swal2-grow-fullscreen>.swal2-popup,.swal2-container.swal2-grow-row>.swal2-popup{grid-column:1/4;width:100%}.swal2-container.swal2-grow-column>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}.swal2-container.swal2-no-transition{transition:none!important}.swal2-popup{display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0,100%);width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;color:#545454;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-title{position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:auto;margin:1.25em auto 0;padding:0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 transparent #2778c4 transparent}.swal2-styled{margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px transparent;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#7066e0;color:#fff;font-size:1em}.swal2-styled.swal2-confirm:focus{box-shadow:0 0 0 3px rgba(112,102,224,.5)}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#dc3741;color:#fff;font-size:1em}.swal2-styled.swal2-deny:focus{box-shadow:0 0 0 3px rgba(220,55,65,.5)}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#6e7881;color:#fff;font-size:1em}.swal2-styled.swal2-cancel:focus{box-shadow:0 0 0 3px rgba(110,120,129,.5)}.swal2-styled.swal2-default-outline:focus{box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled:focus{outline:0}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:inherit;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto!important;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:2em auto 1em}.swal2-close{z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:0 0;color:#ccc;font-family:serif;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}.swal2-close:hover{transform:none;background:0 0;color:#f27474}.swal2-close:focus{outline:0;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-html-container{z-index:1;justify-content:center;margin:1em 1.6em .3em;padding:0;overflow:auto;color:inherit;font-size:1.125em;font-weight:400;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em 2em 3px}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid #d9d9d9;border-radius:.1875em;background:inherit;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px transparent;color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em 2em 3px;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-file{width:75%;margin-right:auto;margin-left:auto;background:inherit;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:inherit;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{flex-shrink:0;margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto 0}.swal2-validation-message{align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:"!";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:.25em solid transparent;border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-warning.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-warning.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .5s;animation:swal2-animate-i-mark .5s}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-info.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-info.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .8s;animation:swal2-animate-i-mark .8s}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-question.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-question.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-question-mark .8s;animation:swal2-animate-question-mark .8s}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:inherit;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@-webkit-keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@-webkit-keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@-webkit-keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@-webkit-keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@-webkit-keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-container{background-color:transparent!important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:transparent;pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}
|
281677160/openwrt-package
| 23,969 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_control_module.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_http.h>
#include "ngx_rtmp.h"
#include "ngx_live.h"
#include "ngx_rtmp_live_module.h"
#include "ngx_live_record.h"
#include "ngx_rtmp_record_module.h"
#include "ngx_rtmp_dynamic.h"
static char *ngx_rtmp_control(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
static void *ngx_rtmp_control_create_loc_conf(ngx_conf_t *cf);
static char *ngx_rtmp_control_merge_loc_conf(ngx_conf_t *cf,
void *parent, void *child);
typedef const char * (*ngx_rtmp_control_handler_t)(ngx_http_request_t *r,
ngx_rtmp_session_t *);
#define NGX_RTMP_CONTROL_ALL 0xff
#define NGX_RTMP_CONTROL_RECORD 0x01
#define NGX_RTMP_CONTROL_DROP 0x02
#define NGX_RTMP_CONTROL_REDIRECT 0x04
#define NGX_RTMP_CONTROL_PAUSE 0x08
#define NGX_RTMP_CONTROL_RESUME 0x10
enum {
NGX_RTMP_CONTROL_FILTER_CLIENT = 0,
NGX_RTMP_CONTROL_FILTER_PUBLISHER,
NGX_RTMP_CONTROL_FILTER_SUBSCRIBER
};
typedef struct {
ngx_uint_t count;
ngx_uint_t filter;
ngx_str_t method;
ngx_str_t path;
ngx_array_t sessions; /* ngx_rtmp_session_t * */
} ngx_rtmp_control_ctx_t;
typedef struct {
ngx_uint_t control;
} ngx_rtmp_control_loc_conf_t;
static ngx_conf_bitmask_t ngx_rtmp_control_masks[] = {
{ ngx_string("all"), NGX_RTMP_CONTROL_ALL },
{ ngx_string("record"), NGX_RTMP_CONTROL_RECORD },
{ ngx_string("drop"), NGX_RTMP_CONTROL_DROP },
{ ngx_string("redirect"), NGX_RTMP_CONTROL_REDIRECT },
{ ngx_string("pause"), NGX_RTMP_CONTROL_PAUSE },
{ ngx_string("resume"), NGX_RTMP_CONTROL_RESUME },
{ ngx_null_string, 0 }
};
static ngx_command_t ngx_rtmp_control_commands[] = {
{ ngx_string("rtmp_control"),
NGX_HTTP_MAIN_CONF|NGX_HTTP_SRV_CONF|NGX_HTTP_LOC_CONF|NGX_CONF_1MORE,
ngx_rtmp_control,
NGX_HTTP_LOC_CONF_OFFSET,
offsetof(ngx_rtmp_control_loc_conf_t, control),
ngx_rtmp_control_masks },
ngx_null_command
};
static ngx_http_module_t ngx_rtmp_control_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_rtmp_control_create_loc_conf, /* create location configuration */
ngx_rtmp_control_merge_loc_conf, /* merge location configuration */
};
ngx_module_t ngx_rtmp_control_module = {
NGX_MODULE_V1,
&ngx_rtmp_control_module_ctx, /* module context */
ngx_rtmp_control_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static const char *
ngx_rtmp_control_record_handler(ngx_http_request_t *r, ngx_rtmp_session_t *s)
{
ngx_rtmp_control_ctx_t *ctx;
ngx_uint_t rn;
ngx_str_t rec = ngx_null_string;
ngx_rtmp_core_app_conf_t *cacf;
ngx_rtmp_record_app_conf_t *racf;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
cacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_core_module);
racf = cacf->app_conf[ngx_rtmp_record_module.ctx_index];
if (ngx_http_arg(r, (u_char *) "rec", sizeof("rec") - 1, &rec) != NGX_OK) {
rec.len = 0;
}
rn = ngx_rtmp_record_find(racf, &rec);
if (rn == NGX_CONF_UNSET_UINT) {
return "Recorder not found";
}
if (ctx->method.len == sizeof("start") - 1 &&
ngx_strncmp(ctx->method.data, "start", ctx->method.len) == 0)
{
ngx_rtmp_record_open(s, rn, &ctx->path);
return ngx_live_record_open(s);
} else if (ctx->method.len == sizeof("stop") - 1 &&
ngx_strncmp(ctx->method.data, "stop", ctx->method.len) == 0)
{
ngx_rtmp_record_close(s, rn, &ctx->path);
return ngx_live_record_close(s);
} else {
return "Undefined method";
}
}
static const char *
ngx_rtmp_control_drop_handler(ngx_http_request_t *r, ngx_rtmp_session_t *s)
{
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
s->finalize_reason = NGX_LIVE_CONTROL_DROP;
ngx_rtmp_finalize_session(s);
++ctx->count;
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_redirect_handler(ngx_http_request_t *r, ngx_rtmp_session_t *s)
{
ngx_str_t name;
ngx_rtmp_play_t vplay;
ngx_rtmp_publish_t vpublish;
ngx_rtmp_live_ctx_t *lctx;
ngx_rtmp_control_ctx_t *ctx;
ngx_rtmp_close_stream_t vc;
if (ngx_http_arg(r, (u_char *) "newname", sizeof("newname") - 1, &name)
!= NGX_OK)
{
return "newname not specified";
}
if (name.len >= NGX_RTMP_MAX_NAME) {
name.len = NGX_RTMP_MAX_NAME - 1;
}
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
ctx->count++;
ngx_memzero(&vc, sizeof(ngx_rtmp_close_stream_t));
/* close_stream should be synchronous */
ngx_rtmp_close_stream_filter(s, &vc);
lctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (lctx && lctx->publishing) {
/* publish */
ngx_memzero(&vpublish, sizeof(ngx_rtmp_publish_t));
ngx_memcpy(vpublish.name, name.data, name.len);
ngx_rtmp_cmd_fill_args(vpublish.name, vpublish.args);
if (ngx_rtmp_publish_filter(s, &vpublish) != NGX_OK) {
return "publish failed";
}
} else {
/* play */
ngx_memzero(&vplay, sizeof(ngx_rtmp_play_t));
ngx_memcpy(vplay.name, name.data, name.len);
ngx_rtmp_cmd_fill_args(vplay.name, vplay.args);
if (ngx_rtmp_play_filter(s, &vplay) != NGX_OK) {
return "play failed";
}
}
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_pause_handler(ngx_http_request_t *r, ngx_rtmp_session_t *s)
{
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
s->pause = 1;
++ctx->count;
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_resume_handler(ngx_http_request_t *r, ngx_rtmp_session_t *s)
{
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
if (s->pause == 1) {
s->pause = 2;
}
++ctx->count;
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_walk_session(ngx_http_request_t *r, ngx_rtmp_core_ctx_t *cctx)
{
ngx_str_t addr, *paddr, clientid;
ngx_rtmp_session_t *s, **ss;
ngx_rtmp_control_ctx_t *ctx;
s = cctx->session;
if (s == NULL) {
return NGX_CONF_OK;
}
if (ngx_http_arg(r, (u_char *) "addr", sizeof("addr") - 1, &addr)
== NGX_OK)
{
paddr = s->addr_text;
if (paddr->len != addr.len ||
ngx_strncmp(paddr->data, addr.data, addr.len))
{
return NGX_CONF_OK;
}
}
if (ngx_http_arg(r, (u_char *) "clientid", sizeof("clientid") - 1,
&clientid)
== NGX_OK)
{
if (s->number !=
(ngx_uint_t) ngx_atoi(clientid.data, clientid.len))
{
return NGX_CONF_OK;
}
}
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
switch (ctx->filter) {
case NGX_RTMP_CONTROL_FILTER_PUBLISHER:
if (!cctx->publishing) {
return NGX_CONF_OK;
}
break;
case NGX_RTMP_CONTROL_FILTER_SUBSCRIBER:
if (cctx->publishing) {
return NGX_CONF_OK;
}
break;
case NGX_RTMP_CONTROL_FILTER_CLIENT:
break;
}
ss = ngx_array_push(&ctx->sessions);
if (ss == NULL) {
return "allocation error";
}
*ss = s;
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_walk_stream(ngx_http_request_t *r, ngx_live_stream_t *st)
{
const char *s;
ngx_rtmp_core_ctx_t *ctx;
for (ctx = st->play_ctx; ctx; ctx = ctx->next) {
s = ngx_rtmp_control_walk_session(r, ctx);
if (s != NGX_CONF_OK) {
return s;
}
}
for (ctx = st->publish_ctx; ctx; ctx = ctx->next) {
s = ngx_rtmp_control_walk_session(r, ctx);
if (s != NGX_CONF_OK) {
return s;
}
}
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_walk_server(ngx_http_request_t *r, ngx_live_server_t *srv)
{
ngx_live_conf_t *lcf;
ngx_live_stream_t *st;
ngx_str_t serverid, app, name, stream;
size_t n;
const char *s;
u_char *p;
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
if (ngx_http_arg(r, (u_char *) "app", sizeof("app") - 1, &app) != NGX_OK) {
app.len = 0;
}
if (app.len == 0) {
for (n = 0; n < lcf->stream_buckets; ++n) {
for (st = srv->streams[n]; st; st = st->next) {
s = ngx_rtmp_control_walk_stream(r, st);
if (s != NGX_CONF_OK) {
return s;
}
}
}
return NGX_CONF_OK;
}
if (ngx_http_arg(r, (u_char *) "name", sizeof("name") - 1, &name)
!= NGX_OK)
{
name.len = 0;
}
serverid.data = srv->serverid;
serverid.len = ngx_strlen(srv->serverid);
/* serverid/app/name */
stream.len = serverid.len + 1 + app.len + 1 + name.len;
stream.data = ngx_pcalloc(r->pool, stream.len);
p = stream.data;
p = ngx_copy(p, serverid.data, serverid.len);
*p++ = '/';
p = ngx_copy(p, app.data, app.len);
*p++ = '/';
p = ngx_copy(p, name.data, name.len);
if (name.len == 0) {
for (n = 0; n < lcf->stream_buckets; ++n) {
for (st = srv->streams[n]; st; st = st->next) {
if (ngx_memcmp(stream.data, st->name, stream.len) == 0) {
s = ngx_rtmp_control_walk_stream(r, st);
if (s != NGX_CONF_OK) {
return s;
}
}
}
}
} else {
st = ngx_live_fetch_stream(&serverid, &stream);
if (st) {
s = ngx_rtmp_control_walk_stream(r, st);
if (s != NGX_CONF_OK) {
return s;
}
}
}
return NGX_CONF_OK;
}
static const char *
ngx_rtmp_control_walk(ngx_http_request_t *r, ngx_rtmp_control_handler_t h)
{
ngx_live_server_t *server;
ngx_str_t srv;
ngx_str_t serverid = ngx_null_string;
ngx_uint_t n;
const char *msg;
ngx_rtmp_session_t **s;
ngx_rtmp_control_ctx_t *ctx;
if (ngx_http_arg(r, (u_char *) "srv", sizeof("srv") - 1, &srv) != NGX_OK) {
return "Server not set";
}
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
serverid = srv;
if (!serverid.len) {
ngx_rmtp_get_serverid_by_domain(&serverid, &srv);
}
server = ngx_live_fetch_server(&serverid);
if (server == NULL) {
return NGX_CONF_OK;
}
msg = ngx_rtmp_control_walk_server(r, server);
if (msg != NGX_CONF_OK) {
return msg;
}
s = ctx->sessions.elts;
for (n = 0; n < ctx->sessions.nelts; n++) {
msg = h(r, s[n]);
if (msg != NGX_CONF_OK) {
return msg;
}
}
return NGX_CONF_OK;
}
static ngx_int_t
ngx_rtmp_control_record(ngx_http_request_t *r, ngx_str_t *method)
{
ngx_buf_t *b;
const char *msg;
ngx_chain_t cl;
ngx_rtmp_control_ctx_t *ctx;
size_t len;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
ctx->filter = NGX_RTMP_CONTROL_FILTER_PUBLISHER;
msg = ngx_rtmp_control_walk(r, ngx_rtmp_control_record_handler);
if (msg != NGX_CONF_OK) {
goto error;
}
/* output record path */
len = sizeof("ok\n") - 1;
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = len;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL) {
goto error;
}
ngx_memzero(&cl, sizeof(cl));
cl.buf = b;
b->last = ngx_cpymem(b->pos, "ok\n", len);
b->last_buf = 1;
ngx_http_send_header(r);
return ngx_http_output_filter(r, &cl);
error:
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
static ngx_int_t
ngx_rtmp_control_drop(ngx_http_request_t *r, ngx_str_t *method)
{
size_t len;
u_char *p;
ngx_buf_t *b;
ngx_chain_t cl;
const char *msg;
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
if (ctx->method.len == sizeof("publisher") - 1 &&
ngx_memcmp(ctx->method.data, "publisher", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_PUBLISHER;
} else if (ctx->method.len == sizeof("subscriber") - 1 &&
ngx_memcmp(ctx->method.data, "subscriber", ctx->method.len)
== 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_SUBSCRIBER;
} else if (method->len == sizeof("client") - 1 &&
ngx_memcmp(ctx->method.data, "client", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_CLIENT;
} else {
msg = "Undefined filter";
goto error;
}
msg = ngx_rtmp_control_walk(r, ngx_rtmp_control_drop_handler);
if (msg != NGX_CONF_OK) {
goto error;
}
/* output count */
len = NGX_INT_T_LEN;
p = ngx_palloc(r->connection->pool, len);
if (p == NULL) {
return NGX_ERROR;
}
len = (size_t) (ngx_snprintf(p, len, "%ui", ctx->count) - p);
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = len;
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
goto error;
}
b->start = b->pos = p;
b->end = b->last = p + len;
b->temporary = 1;
b->last_buf = 1;
ngx_memzero(&cl, sizeof(cl));
cl.buf = b;
ngx_http_send_header(r);
return ngx_http_output_filter(r, &cl);
error:
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
static ngx_int_t
ngx_rtmp_control_redirect(ngx_http_request_t *r, ngx_str_t *method)
{
size_t len;
u_char *p;
ngx_buf_t *b;
ngx_chain_t cl;
const char *msg;
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
if (ctx->method.len == sizeof("publisher") - 1 &&
ngx_memcmp(ctx->method.data, "publisher", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_PUBLISHER;
} else if (ctx->method.len == sizeof("subscriber") - 1 &&
ngx_memcmp(ctx->method.data, "subscriber", ctx->method.len)
== 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_SUBSCRIBER;
} else if (ctx->method.len == sizeof("client") - 1 &&
ngx_memcmp(ctx->method.data, "client", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_CLIENT;
} else {
msg = "Undefined filter";
goto error;
}
msg = ngx_rtmp_control_walk(r, ngx_rtmp_control_redirect_handler);
if (msg != NGX_CONF_OK) {
goto error;
}
/* output count */
len = NGX_INT_T_LEN;
p = ngx_pcalloc(r->connection->pool, len);
if (p == NULL) {
msg = "ngx_palloc failed";
goto error;
}
len = (size_t) (ngx_snprintf(p, len, "%ui", ctx->count) - p);
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = len;
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
msg = "calloc buf failed";
goto error;
}
b->start = b->pos = p;
b->end = b->last = p + len;
b->temporary = 1;
b->last_buf = 1;
ngx_memzero(&cl, sizeof(cl));
cl.buf = b;
ngx_http_send_header(r);
return ngx_http_output_filter(r, &cl);
error:
ngx_log_error(NGX_LOG_ERR, r->connection->log, 0,
"rtmp-control: redirect| %s", msg);
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
static ngx_int_t
ngx_rtmp_control_pause(ngx_http_request_t *r, ngx_str_t *method)
{
size_t len;
u_char *p;
ngx_buf_t *b;
ngx_chain_t cl;
const char *msg;
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
if (ctx->method.len == sizeof("publisher") - 1 &&
ngx_memcmp(ctx->method.data, "publisher", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_PUBLISHER;
} else if (ctx->method.len == sizeof("subscriber") - 1 &&
ngx_memcmp(ctx->method.data, "subscriber", ctx->method.len)
== 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_SUBSCRIBER;
} else if (method->len == sizeof("client") - 1 &&
ngx_memcmp(ctx->method.data, "client", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_CLIENT;
} else {
msg = "Undefined filter";
goto error;
}
msg = ngx_rtmp_control_walk(r, ngx_rtmp_control_pause_handler);
if (msg != NGX_CONF_OK) {
goto error;
}
/* output count */
len = NGX_INT_T_LEN;
p = ngx_palloc(r->connection->pool, len);
if (p == NULL) {
return NGX_ERROR;
}
len = (size_t) (ngx_snprintf(p, len, "%ui", ctx->count) - p);
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = len;
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
goto error;
}
b->start = b->pos = p;
b->end = b->last = p + len;
b->temporary = 1;
b->last_buf = 1;
ngx_memzero(&cl, sizeof(cl));
cl.buf = b;
ngx_http_send_header(r);
return ngx_http_output_filter(r, &cl);
error:
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
static ngx_int_t
ngx_rtmp_control_resume(ngx_http_request_t *r, ngx_str_t *method)
{
size_t len;
u_char *p;
ngx_buf_t *b;
ngx_chain_t cl;
const char *msg;
ngx_rtmp_control_ctx_t *ctx;
ctx = ngx_http_get_module_ctx(r, ngx_rtmp_control_module);
if (ctx->method.len == sizeof("publisher") - 1 &&
ngx_memcmp(ctx->method.data, "publisher", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_PUBLISHER;
} else if (ctx->method.len == sizeof("subscriber") - 1 &&
ngx_memcmp(ctx->method.data, "subscriber", ctx->method.len)
== 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_SUBSCRIBER;
} else if (method->len == sizeof("client") - 1 &&
ngx_memcmp(ctx->method.data, "client", ctx->method.len) == 0)
{
ctx->filter = NGX_RTMP_CONTROL_FILTER_CLIENT;
} else {
msg = "Undefined filter";
goto error;
}
msg = ngx_rtmp_control_walk(r, ngx_rtmp_control_resume_handler);
if (msg != NGX_CONF_OK) {
goto error;
}
/* output count */
len = NGX_INT_T_LEN;
p = ngx_palloc(r->connection->pool, len);
if (p == NULL) {
return NGX_ERROR;
}
len = (size_t) (ngx_snprintf(p, len, "%ui", ctx->count) - p);
r->headers_out.status = NGX_HTTP_OK;
r->headers_out.content_length_n = len;
b = ngx_calloc_buf(r->pool);
if (b == NULL) {
goto error;
}
b->start = b->pos = p;
b->end = b->last = p + len;
b->temporary = 1;
b->last_buf = 1;
ngx_memzero(&cl, sizeof(cl));
cl.buf = b;
ngx_http_send_header(r);
return ngx_http_output_filter(r, &cl);
error:
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
static ngx_int_t
ngx_rtmp_control_handler(ngx_http_request_t *r)
{
u_char *p;
ngx_str_t section, method;
ngx_uint_t n;
ngx_rtmp_control_ctx_t *ctx;
ngx_rtmp_control_loc_conf_t *llcf;
llcf = ngx_http_get_module_loc_conf(r, ngx_rtmp_control_module);
if (llcf->control == 0) {
return NGX_DECLINED;
}
/* uri format: .../section/method?args */
ngx_str_null(§ion);
ngx_str_null(&method);
for (n = r->uri.len; n; --n) {
p = &r->uri.data[n - 1];
if (*p != '/') {
continue;
}
if (method.data) {
section.data = p + 1;
section.len = method.data - section.data - 1;
break;
}
method.data = p + 1;
method.len = r->uri.data + r->uri.len - method.data;
}
ngx_log_error(NGX_LOG_INFO, r->connection->log, 0,
"rtmp_control: section='%V' method='%V'",
§ion, &method);
ctx = ngx_pcalloc(r->pool, sizeof(ngx_rtmp_control_ctx_t));
if (ctx == NULL) {
return NGX_ERROR;
}
ngx_http_set_ctx(r, ctx, ngx_rtmp_control_module);
if (ngx_array_init(&ctx->sessions, r->pool, 1, sizeof(void *)) != NGX_OK) {
return NGX_ERROR;
}
ctx->method = method;
#define NGX_RTMP_CONTROL_SECTION(flag, secname) \
if (llcf->control & NGX_RTMP_CONTROL_##flag && \
section.len == sizeof(#secname) - 1 && \
ngx_strncmp(section.data, #secname, sizeof(#secname) - 1) == 0) \
{ \
return ngx_rtmp_control_##secname(r, &method); \
}
NGX_RTMP_CONTROL_SECTION(RECORD, record);
NGX_RTMP_CONTROL_SECTION(DROP, drop);
NGX_RTMP_CONTROL_SECTION(REDIRECT, redirect);
NGX_RTMP_CONTROL_SECTION(PAUSE, pause);
NGX_RTMP_CONTROL_SECTION(RESUME, resume);
#undef NGX_RTMP_CONTROL_SECTION
return NGX_DECLINED;
}
static void *
ngx_rtmp_control_create_loc_conf(ngx_conf_t *cf)
{
ngx_rtmp_control_loc_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_control_loc_conf_t));
if (conf == NULL) {
return NULL;
}
conf->control = 0;
return conf;
}
static char *
ngx_rtmp_control_merge_loc_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_control_loc_conf_t *prev = parent;
ngx_rtmp_control_loc_conf_t *conf = child;
ngx_conf_merge_bitmask_value(conf->control, prev->control, 0);
return NGX_CONF_OK;
}
static char *
ngx_rtmp_control(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_core_loc_conf_t *clcf;
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
clcf->handler = ngx_rtmp_control_handler;
return ngx_conf_set_bitmask_slot(cf, cmd, conf);
}
|
2881099/FreeSql.AdminLTE
| 108,102 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.js
|
/*!
* sweetalert2 v11.4.0
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Sweetalert2 = factory());
}(this, function () { 'use strict';
const consolePrefix = 'SweetAlert2:';
/**
* Filter the unique values into a new array
* @param arr
*/
const uniqueArray = arr => {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
};
/**
* Capitalize the first letter of a string
* @param {string} str
* @returns {string}
*/
const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
/**
* @param {NodeList | HTMLCollection | NamedNodeMap} nodeList
* @returns {array}
*/
const toArray = nodeList => Array.prototype.slice.call(nodeList);
/**
* Standardize console warnings
* @param {string | array} message
*/
const warn = message => {
console.warn("".concat(consolePrefix, " ").concat(typeof message === 'object' ? message.join(' ') : message));
};
/**
* Standardize console errors
* @param {string} message
*/
const error = message => {
console.error("".concat(consolePrefix, " ").concat(message));
};
/**
* Private global state for `warnOnce`
* @type {Array}
* @private
*/
const previousWarnOnceMessages = [];
/**
* Show a console warning, but only if it hasn't already been shown
* @param {string} message
*/
const warnOnce = message => {
if (!previousWarnOnceMessages.includes(message)) {
previousWarnOnceMessages.push(message);
warn(message);
}
};
/**
* Show a one-time console warning about deprecated params/methods
*/
const warnAboutDeprecation = (deprecatedParam, useInstead) => {
warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
};
/**
* If `arg` is a function, call it (with no arguments or context) and return the result.
* Otherwise, just pass the value through
* @param arg
*/
const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
const isPromise = arg => arg && Promise.resolve(arg) === arg;
const defaultParams = {
title: '',
titleText: '',
text: '',
html: '',
footer: '',
icon: undefined,
iconColor: undefined,
iconHtml: undefined,
template: undefined,
toast: false,
showClass: {
popup: 'swal2-show',
backdrop: 'swal2-backdrop-show',
icon: 'swal2-icon-show'
},
hideClass: {
popup: 'swal2-hide',
backdrop: 'swal2-backdrop-hide',
icon: 'swal2-icon-hide'
},
customClass: {},
target: 'body',
color: undefined,
backdrop: true,
heightAuto: true,
allowOutsideClick: true,
allowEscapeKey: true,
allowEnterKey: true,
stopKeydownPropagation: true,
keydownListenerCapture: false,
showConfirmButton: true,
showDenyButton: false,
showCancelButton: false,
preConfirm: undefined,
preDeny: undefined,
confirmButtonText: 'OK',
confirmButtonAriaLabel: '',
confirmButtonColor: undefined,
denyButtonText: 'No',
denyButtonAriaLabel: '',
denyButtonColor: undefined,
cancelButtonText: 'Cancel',
cancelButtonAriaLabel: '',
cancelButtonColor: undefined,
buttonsStyling: true,
reverseButtons: false,
focusConfirm: true,
focusDeny: false,
focusCancel: false,
returnFocus: true,
showCloseButton: false,
closeButtonHtml: '×',
closeButtonAriaLabel: 'Close this dialog',
loaderHtml: '',
showLoaderOnConfirm: false,
showLoaderOnDeny: false,
imageUrl: undefined,
imageWidth: undefined,
imageHeight: undefined,
imageAlt: '',
timer: undefined,
timerProgressBar: false,
width: undefined,
padding: undefined,
background: undefined,
input: undefined,
inputPlaceholder: '',
inputLabel: '',
inputValue: '',
inputOptions: {},
inputAutoTrim: true,
inputAttributes: {},
inputValidator: undefined,
returnInputValueOnDeny: false,
validationMessage: undefined,
grow: false,
position: 'center',
progressSteps: [],
currentProgressStep: undefined,
progressStepsDistance: undefined,
willOpen: undefined,
didOpen: undefined,
didRender: undefined,
willClose: undefined,
didClose: undefined,
didDestroy: undefined,
scrollbarPadding: true
};
const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
const deprecatedParams = {};
const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
/**
* Is valid parameter
* @param {string} paramName
*/
const isValidParameter = paramName => {
return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
};
/**
* Is valid parameter for Swal.update() method
* @param {string} paramName
*/
const isUpdatableParameter = paramName => {
return updatableParams.indexOf(paramName) !== -1;
};
/**
* Is deprecated parameter
* @param {string} paramName
*/
const isDeprecatedParameter = paramName => {
return deprecatedParams[paramName];
};
const checkIfParamIsValid = param => {
if (!isValidParameter(param)) {
warn("Unknown parameter \"".concat(param, "\""));
}
};
const checkIfToastParamIsValid = param => {
if (toastIncompatibleParams.includes(param)) {
warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
}
};
const checkIfParamIsDeprecated = param => {
if (isDeprecatedParameter(param)) {
warnAboutDeprecation(param, isDeprecatedParameter(param));
}
};
/**
* Show relevant warnings for given params
*
* @param params
*/
const showWarningsForParams = params => {
if (!params.backdrop && params.allowOutsideClick) {
warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
}
for (const param in params) {
checkIfParamIsValid(param);
if (params.toast) {
checkIfToastParamIsValid(param);
}
checkIfParamIsDeprecated(param);
}
};
const swalPrefix = 'swal2-';
const prefix = items => {
const result = {};
for (const i in items) {
result[items[i]] = swalPrefix + items[i];
}
return result;
};
const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']);
const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
/**
* Gets the popup container which contains the backdrop and the popup itself.
*
* @returns {HTMLElement | null}
*/
const getContainer = () => document.body.querySelector(".".concat(swalClasses.container));
const elementBySelector = selectorString => {
const container = getContainer();
return container ? container.querySelector(selectorString) : null;
};
const elementByClass = className => {
return elementBySelector(".".concat(className));
};
const getPopup = () => elementByClass(swalClasses.popup);
const getIcon = () => elementByClass(swalClasses.icon);
const getTitle = () => elementByClass(swalClasses.title);
const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
const getImage = () => elementByClass(swalClasses.image);
const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
const getConfirmButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm));
const getDenyButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny));
const getInputLabel = () => elementByClass(swalClasses['input-label']);
const getLoader = () => elementBySelector(".".concat(swalClasses.loader));
const getCancelButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel));
const getActions = () => elementByClass(swalClasses.actions);
const getFooter = () => elementByClass(swalClasses.footer);
const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js
const focusable = "\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n";
const getFocusableElements = () => {
const focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
.sort((a, b) => {
const tabindexA = parseInt(a.getAttribute('tabindex'));
const tabindexB = parseInt(b.getAttribute('tabindex'));
if (tabindexA > tabindexB) {
return 1;
} else if (tabindexA < tabindexB) {
return -1;
}
return 0;
});
const otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');
return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible(el));
};
const isModal = () => {
return !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
};
const isToast = () => {
return getPopup() && hasClass(getPopup(), swalClasses.toast);
};
const isLoading = () => {
return getPopup().hasAttribute('data-loading');
};
const states = {
previousBodyPadding: null
};
/**
* Securely set innerHTML of an element
* https://github.com/sweetalert2/sweetalert2/issues/1926
*
* @param {HTMLElement} elem
* @param {string} html
*/
const setInnerHtml = (elem, html) => {
elem.textContent = '';
if (html) {
const parser = new DOMParser();
const parsed = parser.parseFromString(html, "text/html");
toArray(parsed.querySelector('head').childNodes).forEach(child => {
elem.appendChild(child);
});
toArray(parsed.querySelector('body').childNodes).forEach(child => {
elem.appendChild(child);
});
}
};
/**
* @param {HTMLElement} elem
* @param {string} className
* @returns {boolean}
*/
const hasClass = (elem, className) => {
if (!className) {
return false;
}
const classList = className.split(/\s+/);
for (let i = 0; i < classList.length; i++) {
if (!elem.classList.contains(classList[i])) {
return false;
}
}
return true;
};
const removeCustomClasses = (elem, params) => {
toArray(elem.classList).forEach(className => {
if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {
elem.classList.remove(className);
}
});
};
const applyCustomClass = (elem, params, className) => {
removeCustomClasses(elem, params);
if (params.customClass && params.customClass[className]) {
if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(typeof params.customClass[className], "\""));
}
addClass(elem, params.customClass[className]);
}
};
/**
* @param {HTMLElement} popup
* @param {string} inputType
* @returns {HTMLInputElement | null}
*/
const getInput = (popup, inputType) => {
if (!inputType) {
return null;
}
switch (inputType) {
case 'select':
case 'textarea':
case 'file':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses[inputType]));
case 'checkbox':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.checkbox, " input"));
case 'radio':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:checked")) || popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:first-child"));
case 'range':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.range, " input"));
default:
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.input));
}
};
/**
* @param {HTMLInputElement} input
*/
const focusInput = input => {
input.focus(); // place cursor at end of text in text input
if (input.type !== 'file') {
// http://stackoverflow.com/a/2345915
const val = input.value;
input.value = '';
input.value = val;
}
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[]} classList
* @param {boolean} condition
*/
const toggleClass = (target, classList, condition) => {
if (!target || !classList) {
return;
}
if (typeof classList === 'string') {
classList = classList.split(/\s+/).filter(Boolean);
}
classList.forEach(className => {
if (Array.isArray(target)) {
target.forEach(elem => {
condition ? elem.classList.add(className) : elem.classList.remove(className);
});
} else {
condition ? target.classList.add(className) : target.classList.remove(className);
}
});
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[]} classList
*/
const addClass = (target, classList) => {
toggleClass(target, classList, true);
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[]} classList
*/
const removeClass = (target, classList) => {
toggleClass(target, classList, false);
};
/**
* Get direct child of an element by class name
*
* @param {HTMLElement} elem
* @param {string} className
* @returns {HTMLElement | null}
*/
const getDirectChildByClass = (elem, className) => {
const childNodes = toArray(elem.childNodes);
for (let i = 0; i < childNodes.length; i++) {
if (hasClass(childNodes[i], className)) {
return childNodes[i];
}
}
};
/**
* @param {HTMLElement} elem
* @param {string} property
* @param {*} value
*/
const applyNumericalStyle = (elem, property, value) => {
if (value === "".concat(parseInt(value))) {
value = parseInt(value);
}
if (value || parseInt(value) === 0) {
elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value;
} else {
elem.style.removeProperty(property);
}
};
/**
* @param {HTMLElement} elem
* @param {string} display
*/
const show = function (elem) {
let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
elem.style.display = display;
};
/**
* @param {HTMLElement} elem
*/
const hide = elem => {
elem.style.display = 'none';
};
const setStyle = (parent, selector, property, value) => {
const el = parent.querySelector(selector);
if (el) {
el.style[property] = value;
}
};
const toggle = (elem, condition, display) => {
condition ? show(elem, display) : hide(elem);
}; // borrowed from jquery $(elem).is(':visible') implementation
const isVisible = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
const allButtonsAreHidden = () => !isVisible(getConfirmButton()) && !isVisible(getDenyButton()) && !isVisible(getCancelButton());
const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight); // borrowed from https://stackoverflow.com/a/46352119
const hasCssAnimation = elem => {
const style = window.getComputedStyle(elem);
const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
return animDuration > 0 || transDuration > 0;
};
const animateTimerProgressBar = function (timer) {
let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const timerProgressBar = getTimerProgressBar();
if (isVisible(timerProgressBar)) {
if (reset) {
timerProgressBar.style.transition = 'none';
timerProgressBar.style.width = '100%';
}
setTimeout(() => {
timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear");
timerProgressBar.style.width = '0%';
}, 10);
}
};
const stopTimerProgressBar = () => {
const timerProgressBar = getTimerProgressBar();
const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = '100%';
const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%");
};
/**
* Detect Node env
*
* @returns {boolean}
*/
const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
const RESTORE_FOCUS_TIMEOUT = 100;
const globalState = {};
const focusPreviousActiveElement = () => {
if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
globalState.previousActiveElement.focus();
globalState.previousActiveElement = null;
} else if (document.body) {
document.body.focus();
}
}; // Restore previous active (focused) element
const restoreActiveElement = returnFocus => {
return new Promise(resolve => {
if (!returnFocus) {
return resolve();
}
const x = window.scrollX;
const y = window.scrollY;
globalState.restoreFocusTimeout = setTimeout(() => {
focusPreviousActiveElement();
resolve();
}, RESTORE_FOCUS_TIMEOUT); // issues/900
window.scrollTo(x, y);
});
};
const sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses['html-container'], "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <button type=\"button\" class=\"").concat(swalClasses.close, "\"></button>\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, "\"></div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <div class=\"").concat(swalClasses['html-container'], "\" id=\"").concat(swalClasses['html-container'], "\"></div>\n <input class=\"").concat(swalClasses.input, "\" />\n <input type=\"file\" class=\"").concat(swalClasses.file, "\" />\n <div class=\"").concat(swalClasses.range, "\">\n <input type=\"range\" />\n <output></output>\n </div>\n <select class=\"").concat(swalClasses.select, "\"></select>\n <div class=\"").concat(swalClasses.radio, "\"></div>\n <label for=\"").concat(swalClasses.checkbox, "\" class=\"").concat(swalClasses.checkbox, "\">\n <input type=\"checkbox\" />\n <span class=\"").concat(swalClasses.label, "\"></span>\n </label>\n <textarea class=\"").concat(swalClasses.textarea, "\"></textarea>\n <div class=\"").concat(swalClasses['validation-message'], "\" id=\"").concat(swalClasses['validation-message'], "\"></div>\n <div class=\"").concat(swalClasses.actions, "\">\n <div class=\"").concat(swalClasses.loader, "\"></div>\n <button type=\"button\" class=\"").concat(swalClasses.confirm, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.deny, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\"></div>\n <div class=\"").concat(swalClasses['timer-progress-bar-container'], "\">\n <div class=\"").concat(swalClasses['timer-progress-bar'], "\"></div>\n </div>\n </div>\n").replace(/(^|\n)\s*/g, '');
const resetOldContainer = () => {
const oldContainer = getContainer();
if (!oldContainer) {
return false;
}
oldContainer.remove();
removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
return true;
};
const resetValidationMessage = () => {
globalState.currentInstance.resetValidationMessage();
};
const addInputChangeListeners = () => {
const popup = getPopup();
const input = getDirectChildByClass(popup, swalClasses.input);
const file = getDirectChildByClass(popup, swalClasses.file);
const range = popup.querySelector(".".concat(swalClasses.range, " input"));
const rangeOutput = popup.querySelector(".".concat(swalClasses.range, " output"));
const select = getDirectChildByClass(popup, swalClasses.select);
const checkbox = popup.querySelector(".".concat(swalClasses.checkbox, " input"));
const textarea = getDirectChildByClass(popup, swalClasses.textarea);
input.oninput = resetValidationMessage;
file.onchange = resetValidationMessage;
select.onchange = resetValidationMessage;
checkbox.onchange = resetValidationMessage;
textarea.oninput = resetValidationMessage;
range.oninput = () => {
resetValidationMessage();
rangeOutput.value = range.value;
};
range.onchange = () => {
resetValidationMessage();
range.nextSibling.value = range.value;
};
};
const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
const setupAccessibility = params => {
const popup = getPopup();
popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
if (!params.toast) {
popup.setAttribute('aria-modal', 'true');
}
};
const setupRTL = targetElement => {
if (window.getComputedStyle(targetElement).direction === 'rtl') {
addClass(getContainer(), swalClasses.rtl);
}
};
/*
* Add modal + backdrop to DOM
*/
const init = params => {
// Clean up the old popup container if it exists
const oldContainerExisted = resetOldContainer();
/* istanbul ignore if */
if (isNodeEnv()) {
error('SweetAlert2 requires document to initialize');
return;
}
const container = document.createElement('div');
container.className = swalClasses.container;
if (oldContainerExisted) {
addClass(container, swalClasses['no-transition']);
}
setInnerHtml(container, sweetHTML);
const targetElement = getTarget(params.target);
targetElement.appendChild(container);
setupAccessibility(params);
setupRTL(targetElement);
addInputChangeListeners();
};
/**
* @param {HTMLElement | object | string} param
* @param {HTMLElement} target
*/
const parseHtmlToContainer = (param, target) => {
// DOM element
if (param instanceof HTMLElement) {
target.appendChild(param);
} // Object
else if (typeof param === 'object') {
handleObject(param, target);
} // Plain string
else if (param) {
setInnerHtml(target, param);
}
};
/**
* @param {object} param
* @param {HTMLElement} target
*/
const handleObject = (param, target) => {
// JQuery element(s)
if (param.jquery) {
handleJqueryElem(target, param);
} // For other objects use their string representation
else {
setInnerHtml(target, param.toString());
}
};
const handleJqueryElem = (target, elem) => {
target.textContent = '';
if (0 in elem) {
for (let i = 0; (i in elem); i++) {
target.appendChild(elem[i].cloneNode(true));
}
} else {
target.appendChild(elem.cloneNode(true));
}
};
const animationEndEvent = (() => {
// Prevent run in Node env
/* istanbul ignore if */
if (isNodeEnv()) {
return false;
}
const testEl = document.createElement('div');
const transEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
// Chrome, Safari and Opera
animation: 'animationend' // Standard syntax
};
for (const i in transEndEventNames) {
if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
return transEndEventNames[i];
}
}
return false;
})();
// https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
const measureScrollbar = () => {
const scrollDiv = document.createElement('div');
scrollDiv.className = swalClasses['scrollbar-measure'];
document.body.appendChild(scrollDiv);
const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
const renderActions = (instance, params) => {
const actions = getActions();
const loader = getLoader(); // Actions (buttons) wrapper
if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
hide(actions);
} else {
show(actions);
} // Custom class
applyCustomClass(actions, params, 'actions'); // Render all the buttons
renderButtons(actions, loader, params); // Loader
setInnerHtml(loader, params.loaderHtml);
applyCustomClass(loader, params, 'loader');
};
function renderButtons(actions, loader, params) {
const confirmButton = getConfirmButton();
const denyButton = getDenyButton();
const cancelButton = getCancelButton(); // Render buttons
renderButton(confirmButton, 'confirm', params);
renderButton(denyButton, 'deny', params);
renderButton(cancelButton, 'cancel', params);
handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
if (params.reverseButtons) {
if (params.toast) {
actions.insertBefore(cancelButton, confirmButton);
actions.insertBefore(denyButton, confirmButton);
} else {
actions.insertBefore(cancelButton, loader);
actions.insertBefore(denyButton, loader);
actions.insertBefore(confirmButton, loader);
}
}
}
function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
if (!params.buttonsStyling) {
return removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
}
addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors
if (params.confirmButtonColor) {
confirmButton.style.backgroundColor = params.confirmButtonColor;
addClass(confirmButton, swalClasses['default-outline']);
}
if (params.denyButtonColor) {
denyButton.style.backgroundColor = params.denyButtonColor;
addClass(denyButton, swalClasses['default-outline']);
}
if (params.cancelButtonColor) {
cancelButton.style.backgroundColor = params.cancelButtonColor;
addClass(cancelButton, swalClasses['default-outline']);
}
}
function renderButton(button, buttonType, params) {
toggle(button, params["show".concat(capitalizeFirstLetter(buttonType), "Button")], 'inline-block');
setInnerHtml(button, params["".concat(buttonType, "ButtonText")]); // Set caption text
button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")]); // ARIA label
// Add buttons custom classes
button.className = swalClasses[buttonType];
applyCustomClass(button, params, "".concat(buttonType, "Button"));
addClass(button, params["".concat(buttonType, "ButtonClass")]);
}
function handleBackdropParam(container, backdrop) {
if (typeof backdrop === 'string') {
container.style.background = backdrop;
} else if (!backdrop) {
addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
}
}
function handlePositionParam(container, position) {
if (position in swalClasses) {
addClass(container, swalClasses[position]);
} else {
warn('The "position" parameter is not valid, defaulting to "center"');
addClass(container, swalClasses.center);
}
}
function handleGrowParam(container, grow) {
if (grow && typeof grow === 'string') {
const growClass = "grow-".concat(grow);
if (growClass in swalClasses) {
addClass(container, swalClasses[growClass]);
}
}
}
const renderContainer = (instance, params) => {
const container = getContainer();
if (!container) {
return;
}
handleBackdropParam(container, params.backdrop);
handlePositionParam(container, params.position);
handleGrowParam(container, params.grow); // Custom class
applyCustomClass(container, params, 'container');
};
/**
* This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* https://github.com/tc39/proposal-private-methods
* https://github.com/babel/babel/pull/7555
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateProps = {
awaitingPromise: new WeakMap(),
promise: new WeakMap(),
innerParams: new WeakMap(),
domCache: new WeakMap()
};
const inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
const renderInput = (instance, params) => {
const popup = getPopup();
const innerParams = privateProps.innerParams.get(instance);
const rerender = !innerParams || params.input !== innerParams.input;
inputTypes.forEach(inputType => {
const inputClass = swalClasses[inputType];
const inputContainer = getDirectChildByClass(popup, inputClass); // set attributes
setAttributes(inputType, params.inputAttributes); // set class
inputContainer.className = inputClass;
if (rerender) {
hide(inputContainer);
}
});
if (params.input) {
if (rerender) {
showInput(params);
} // set custom class
setCustomClass(params);
}
};
const showInput = params => {
if (!renderInputType[params.input]) {
return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
}
const inputContainer = getInputContainer(params.input);
const input = renderInputType[params.input](inputContainer, params);
show(input); // input autofocus
setTimeout(() => {
focusInput(input);
});
};
const removeAttributes = input => {
for (let i = 0; i < input.attributes.length; i++) {
const attrName = input.attributes[i].name;
if (!['type', 'value', 'style'].includes(attrName)) {
input.removeAttribute(attrName);
}
}
};
const setAttributes = (inputType, inputAttributes) => {
const input = getInput(getPopup(), inputType);
if (!input) {
return;
}
removeAttributes(input);
for (const attr in inputAttributes) {
input.setAttribute(attr, inputAttributes[attr]);
}
};
const setCustomClass = params => {
const inputContainer = getInputContainer(params.input);
if (params.customClass) {
addClass(inputContainer, params.customClass.input);
}
};
const setInputPlaceholder = (input, params) => {
if (!input.placeholder || params.inputPlaceholder) {
input.placeholder = params.inputPlaceholder;
}
};
const setInputLabel = (input, prependTo, params) => {
if (params.inputLabel) {
input.id = swalClasses.input;
const label = document.createElement('label');
const labelClass = swalClasses['input-label'];
label.setAttribute('for', input.id);
label.className = labelClass;
addClass(label, params.customClass.inputLabel);
label.innerText = params.inputLabel;
prependTo.insertAdjacentElement('beforebegin', label);
}
};
const getInputContainer = inputType => {
const inputClass = swalClasses[inputType] ? swalClasses[inputType] : swalClasses.input;
return getDirectChildByClass(getPopup(), inputClass);
};
const renderInputType = {};
renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {
if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
input.value = params.inputValue;
} else if (!isPromise(params.inputValue)) {
warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(typeof params.inputValue, "\""));
}
setInputLabel(input, input, params);
setInputPlaceholder(input, params);
input.type = params.input;
return input;
};
renderInputType.file = (input, params) => {
setInputLabel(input, input, params);
setInputPlaceholder(input, params);
return input;
};
renderInputType.range = (range, params) => {
const rangeInput = range.querySelector('input');
const rangeOutput = range.querySelector('output');
rangeInput.value = params.inputValue;
rangeInput.type = params.input;
rangeOutput.value = params.inputValue;
setInputLabel(rangeInput, range, params);
return range;
};
renderInputType.select = (select, params) => {
select.textContent = '';
if (params.inputPlaceholder) {
const placeholder = document.createElement('option');
setInnerHtml(placeholder, params.inputPlaceholder);
placeholder.value = '';
placeholder.disabled = true;
placeholder.selected = true;
select.appendChild(placeholder);
}
setInputLabel(select, select, params);
return select;
};
renderInputType.radio = radio => {
radio.textContent = '';
return radio;
};
renderInputType.checkbox = (checkboxContainer, params) => {
/** @type {HTMLInputElement} */
const checkbox = getInput(getPopup(), 'checkbox');
checkbox.value = '1';
checkbox.id = swalClasses.checkbox;
checkbox.checked = Boolean(params.inputValue);
const label = checkboxContainer.querySelector('span');
setInnerHtml(label, params.inputPlaceholder);
return checkboxContainer;
};
renderInputType.textarea = (textarea, params) => {
textarea.value = params.inputValue;
setInputPlaceholder(textarea, params);
setInputLabel(textarea, textarea, params);
const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); // https://github.com/sweetalert2/sweetalert2/issues/2291
setTimeout(() => {
// https://github.com/sweetalert2/sweetalert2/issues/1699
if ('MutationObserver' in window) {
const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
const textareaResizeHandler = () => {
const textareaWidth = textarea.offsetWidth + getMargin(textarea);
if (textareaWidth > initialPopupWidth) {
getPopup().style.width = "".concat(textareaWidth, "px");
} else {
getPopup().style.width = null;
}
};
new MutationObserver(textareaResizeHandler).observe(textarea, {
attributes: true,
attributeFilter: ['style']
});
}
});
return textarea;
};
const renderContent = (instance, params) => {
const htmlContainer = getHtmlContainer();
applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML
if (params.html) {
parseHtmlToContainer(params.html, htmlContainer);
show(htmlContainer, 'block');
} // Content as plain text
else if (params.text) {
htmlContainer.textContent = params.text;
show(htmlContainer, 'block');
} // No content
else {
hide(htmlContainer);
}
renderInput(instance, params);
};
const renderFooter = (instance, params) => {
const footer = getFooter();
toggle(footer, params.footer);
if (params.footer) {
parseHtmlToContainer(params.footer, footer);
} // Custom class
applyCustomClass(footer, params, 'footer');
};
const renderCloseButton = (instance, params) => {
const closeButton = getCloseButton();
setInnerHtml(closeButton, params.closeButtonHtml); // Custom class
applyCustomClass(closeButton, params, 'closeButton');
toggle(closeButton, params.showCloseButton);
closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
};
const renderIcon = (instance, params) => {
const innerParams = privateProps.innerParams.get(instance);
const icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon
if (innerParams && params.icon === innerParams.icon) {
// Custom or default content
setContent(icon, params);
applyStyles(icon, params);
return;
}
if (!params.icon && !params.iconHtml) {
return hide(icon);
}
if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
return hide(icon);
}
show(icon); // Custom or default content
setContent(icon, params);
applyStyles(icon, params); // Animate icon
addClass(icon, params.showClass.icon);
};
const applyStyles = (icon, params) => {
for (const iconType in iconTypes) {
if (params.icon !== iconType) {
removeClass(icon, iconTypes[iconType]);
}
}
addClass(icon, iconTypes[params.icon]); // Icon color
setColor(icon, params); // Success icon background color
adjustSuccessIconBackgroundColor(); // Custom class
applyCustomClass(icon, params, 'icon');
}; // Adjust success icon background color to match the popup background color
const adjustSuccessIconBackgroundColor = () => {
const popup = getPopup();
const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
for (let i = 0; i < successIconParts.length; i++) {
successIconParts[i].style.backgroundColor = popupBackgroundColor;
}
};
const successIconHtml = "\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n";
const errorIconHtml = "\n <span class=\"swal2-x-mark\">\n <span class=\"swal2-x-mark-line-left\"></span>\n <span class=\"swal2-x-mark-line-right\"></span>\n </span>\n";
const setContent = (icon, params) => {
icon.textContent = '';
if (params.iconHtml) {
setInnerHtml(icon, iconContent(params.iconHtml));
} else if (params.icon === 'success') {
setInnerHtml(icon, successIconHtml);
} else if (params.icon === 'error') {
setInnerHtml(icon, errorIconHtml);
} else {
const defaultIconHtml = {
question: '?',
warning: '!',
info: 'i'
};
setInnerHtml(icon, iconContent(defaultIconHtml[params.icon]));
}
};
const setColor = (icon, params) => {
if (!params.iconColor) {
return;
}
icon.style.color = params.iconColor;
icon.style.borderColor = params.iconColor;
for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
setStyle(icon, sel, 'backgroundColor', params.iconColor);
}
setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
};
const iconContent = content => "<div class=\"".concat(swalClasses['icon-content'], "\">").concat(content, "</div>");
const renderImage = (instance, params) => {
const image = getImage();
if (!params.imageUrl) {
return hide(image);
}
show(image, ''); // Src, alt
image.setAttribute('src', params.imageUrl);
image.setAttribute('alt', params.imageAlt); // Width, height
applyNumericalStyle(image, 'width', params.imageWidth);
applyNumericalStyle(image, 'height', params.imageHeight); // Class
image.className = swalClasses.image;
applyCustomClass(image, params, 'image');
};
const createStepElement = step => {
const stepEl = document.createElement('li');
addClass(stepEl, swalClasses['progress-step']);
setInnerHtml(stepEl, step);
return stepEl;
};
const createLineElement = params => {
const lineEl = document.createElement('li');
addClass(lineEl, swalClasses['progress-step-line']);
if (params.progressStepsDistance) {
lineEl.style.width = params.progressStepsDistance;
}
return lineEl;
};
const renderProgressSteps = (instance, params) => {
const progressStepsContainer = getProgressSteps();
if (!params.progressSteps || params.progressSteps.length === 0) {
return hide(progressStepsContainer);
}
show(progressStepsContainer);
progressStepsContainer.textContent = '';
if (params.currentProgressStep >= params.progressSteps.length) {
warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
}
params.progressSteps.forEach((step, index) => {
const stepEl = createStepElement(step);
progressStepsContainer.appendChild(stepEl);
if (index === params.currentProgressStep) {
addClass(stepEl, swalClasses['active-progress-step']);
}
if (index !== params.progressSteps.length - 1) {
const lineEl = createLineElement(params);
progressStepsContainer.appendChild(lineEl);
}
});
};
const renderTitle = (instance, params) => {
const title = getTitle();
toggle(title, params.title || params.titleText, 'block');
if (params.title) {
parseHtmlToContainer(params.title, title);
}
if (params.titleText) {
title.innerText = params.titleText;
} // Custom class
applyCustomClass(title, params, 'title');
};
const renderPopup = (instance, params) => {
const container = getContainer();
const popup = getPopup(); // Width
// https://github.com/sweetalert2/sweetalert2/issues/2170
if (params.toast) {
applyNumericalStyle(container, 'width', params.width);
popup.style.width = '100%';
popup.insertBefore(getLoader(), getIcon());
} else {
applyNumericalStyle(popup, 'width', params.width);
} // Padding
applyNumericalStyle(popup, 'padding', params.padding); // Color
if (params.color) {
popup.style.color = params.color;
} // Background
if (params.background) {
popup.style.background = params.background;
}
hide(getValidationMessage()); // Classes
addClasses(popup, params);
};
const addClasses = (popup, params) => {
// Default Class + showClass when updating Swal.update({})
popup.className = "".concat(swalClasses.popup, " ").concat(isVisible(popup) ? params.showClass.popup : '');
if (params.toast) {
addClass([document.documentElement, document.body], swalClasses['toast-shown']);
addClass(popup, swalClasses.toast);
} else {
addClass(popup, swalClasses.modal);
} // Custom class
applyCustomClass(popup, params, 'popup');
if (typeof params.customClass === 'string') {
addClass(popup, params.customClass);
} // Icon class (#1842)
if (params.icon) {
addClass(popup, swalClasses["icon-".concat(params.icon)]);
}
};
const render = (instance, params) => {
renderPopup(instance, params);
renderContainer(instance, params);
renderProgressSteps(instance, params);
renderIcon(instance, params);
renderImage(instance, params);
renderTitle(instance, params);
renderCloseButton(instance, params);
renderContent(instance, params);
renderActions(instance, params);
renderFooter(instance, params);
if (typeof params.didRender === 'function') {
params.didRender(getPopup());
}
};
const DismissReason = Object.freeze({
cancel: 'cancel',
backdrop: 'backdrop',
close: 'close',
esc: 'esc',
timer: 'timer'
});
// Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
// elements not within the active modal dialog will not be surfaced if a user opens a screen
// reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
const setAriaHidden = () => {
const bodyChildren = toArray(document.body.children);
bodyChildren.forEach(el => {
if (el === getContainer() || el.contains(getContainer())) {
return;
}
if (el.hasAttribute('aria-hidden')) {
el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
}
el.setAttribute('aria-hidden', 'true');
});
};
const unsetAriaHidden = () => {
const bodyChildren = toArray(document.body.children);
bodyChildren.forEach(el => {
if (el.hasAttribute('data-previous-aria-hidden')) {
el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
el.removeAttribute('data-previous-aria-hidden');
} else {
el.removeAttribute('aria-hidden');
}
});
};
const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
const getTemplateParams = params => {
const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
if (!template) {
return {};
}
/** @type {DocumentFragment} */
const templateContent = template.content;
showWarningsForElements(templateContent);
const result = Object.assign(getSwalParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalParams = templateContent => {
const result = {};
toArray(templateContent.querySelectorAll('swal-param')).forEach(param => {
showWarningsForAttributes(param, ['name', 'value']);
const paramName = param.getAttribute('name');
const value = param.getAttribute('value');
if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {
result[paramName] = false;
}
if (typeof defaultParams[paramName] === 'object') {
result[paramName] = JSON.parse(value);
}
});
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalButtons = templateContent => {
const result = {};
toArray(templateContent.querySelectorAll('swal-button')).forEach(button => {
showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
const type = button.getAttribute('type');
result["".concat(type, "ButtonText")] = button.innerHTML;
result["show".concat(capitalizeFirstLetter(type), "Button")] = true;
if (button.hasAttribute('color')) {
result["".concat(type, "ButtonColor")] = button.getAttribute('color');
}
if (button.hasAttribute('aria-label')) {
result["".concat(type, "ButtonAriaLabel")] = button.getAttribute('aria-label');
}
});
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalImage = templateContent => {
const result = {};
/** @type {HTMLElement} */
const image = templateContent.querySelector('swal-image');
if (image) {
showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
if (image.hasAttribute('src')) {
result.imageUrl = image.getAttribute('src');
}
if (image.hasAttribute('width')) {
result.imageWidth = image.getAttribute('width');
}
if (image.hasAttribute('height')) {
result.imageHeight = image.getAttribute('height');
}
if (image.hasAttribute('alt')) {
result.imageAlt = image.getAttribute('alt');
}
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalIcon = templateContent => {
const result = {};
/** @type {HTMLElement} */
const icon = templateContent.querySelector('swal-icon');
if (icon) {
showWarningsForAttributes(icon, ['type', 'color']);
if (icon.hasAttribute('type')) {
result.icon = icon.getAttribute('type');
}
if (icon.hasAttribute('color')) {
result.iconColor = icon.getAttribute('color');
}
result.iconHtml = icon.innerHTML;
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalInput = templateContent => {
const result = {};
/** @type {HTMLElement} */
const input = templateContent.querySelector('swal-input');
if (input) {
showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
result.input = input.getAttribute('type') || 'text';
if (input.hasAttribute('label')) {
result.inputLabel = input.getAttribute('label');
}
if (input.hasAttribute('placeholder')) {
result.inputPlaceholder = input.getAttribute('placeholder');
}
if (input.hasAttribute('value')) {
result.inputValue = input.getAttribute('value');
}
}
const inputOptions = templateContent.querySelectorAll('swal-input-option');
if (inputOptions.length) {
result.inputOptions = {};
toArray(inputOptions).forEach(option => {
showWarningsForAttributes(option, ['value']);
const optionValue = option.getAttribute('value');
const optionName = option.innerHTML;
result.inputOptions[optionValue] = optionName;
});
}
return result;
};
/**
* @param {DocumentFragment} templateContent
* @param {string[]} paramNames
*/
const getSwalStringParams = (templateContent, paramNames) => {
const result = {};
for (const i in paramNames) {
const paramName = paramNames[i];
/** @type {HTMLElement} */
const tag = templateContent.querySelector(paramName);
if (tag) {
showWarningsForAttributes(tag, []);
result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
}
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const showWarningsForElements = templateContent => {
const allowedElements = swalStringParams.concat(['swal-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
toArray(templateContent.children).forEach(el => {
const tagName = el.tagName.toLowerCase();
if (allowedElements.indexOf(tagName) === -1) {
warn("Unrecognized element <".concat(tagName, ">"));
}
});
};
/**
* @param {HTMLElement} el
* @param {string[]} allowedAttributes
*/
const showWarningsForAttributes = (el, allowedAttributes) => {
toArray(el.attributes).forEach(attribute => {
if (allowedAttributes.indexOf(attribute.name) === -1) {
warn(["Unrecognized attribute \"".concat(attribute.name, "\" on <").concat(el.tagName.toLowerCase(), ">."), "".concat(allowedAttributes.length ? "Allowed attributes are: ".concat(allowedAttributes.join(', ')) : 'To set the value, use HTML within the element.')]);
}
});
};
var defaultInputValidators = {
email: (string, validationMessage) => {
return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
},
url: (string, validationMessage) => {
// taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
}
};
function setDefaultInputValidators(params) {
// Use default `inputValidator` for supported input types if not provided
if (!params.inputValidator) {
Object.keys(defaultInputValidators).forEach(key => {
if (params.input === key) {
params.inputValidator = defaultInputValidators[key];
}
});
}
}
function validateCustomTargetElement(params) {
// Determine if the custom target element is valid
if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
warn('Target parameter is not valid, defaulting to "body"');
params.target = 'body';
}
}
/**
* Set type, text and actions on popup
*
* @param params
*/
function setParameters(params) {
setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
if (params.showLoaderOnConfirm && !params.preConfirm) {
warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\n' + 'https://sweetalert2.github.io/#ajax-request');
}
validateCustomTargetElement(params); // Replace newlines with <br> in title
if (typeof params.title === 'string') {
params.title = params.title.split('\n').join('<br />');
}
init(params);
}
class Timer {
constructor(callback, delay) {
this.callback = callback;
this.remaining = delay;
this.running = false;
this.start();
}
start() {
if (!this.running) {
this.running = true;
this.started = new Date();
this.id = setTimeout(this.callback, this.remaining);
}
return this.remaining;
}
stop() {
if (this.running) {
this.running = false;
clearTimeout(this.id);
this.remaining -= new Date().getTime() - this.started.getTime();
}
return this.remaining;
}
increase(n) {
const running = this.running;
if (running) {
this.stop();
}
this.remaining += n;
if (running) {
this.start();
}
return this.remaining;
}
getTimerLeft() {
if (this.running) {
this.stop();
this.start();
}
return this.remaining;
}
isRunning() {
return this.running;
}
}
const fixScrollbar = () => {
// for queues, do not do this more than once
if (states.previousBodyPadding !== null) {
return;
} // if the body has overflow
if (document.body.scrollHeight > window.innerHeight) {
// add padding so the content doesn't shift after removal of scrollbar
states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
document.body.style.paddingRight = "".concat(states.previousBodyPadding + measureScrollbar(), "px");
}
};
const undoScrollbar = () => {
if (states.previousBodyPadding !== null) {
document.body.style.paddingRight = "".concat(states.previousBodyPadding, "px");
states.previousBodyPadding = null;
}
};
/* istanbul ignore file */
const iOSfix = () => {
const iOS = // @ts-ignore
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
const offset = document.body.scrollTop;
document.body.style.top = "".concat(offset * -1, "px");
addClass(document.body, swalClasses.iosfix);
lockBodyScroll();
addBottomPaddingForTallPopups();
}
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1948
*/
const addBottomPaddingForTallPopups = () => {
const ua = navigator.userAgent;
const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
const webkit = !!ua.match(/WebKit/i);
const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
if (iOSSafari) {
const bottomPanelHeight = 44;
if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
getContainer().style.paddingBottom = "".concat(bottomPanelHeight, "px");
}
}
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1246
*/
const lockBodyScroll = () => {
const container = getContainer();
let preventTouchMove;
container.ontouchstart = e => {
preventTouchMove = shouldPreventTouchMove(e);
};
container.ontouchmove = e => {
if (preventTouchMove) {
e.preventDefault();
e.stopPropagation();
}
};
};
const shouldPreventTouchMove = event => {
const target = event.target;
const container = getContainer();
if (isStylus(event) || isZoom(event)) {
return false;
}
if (target === container) {
return true;
}
if (!isScrollable(container) && target.tagName !== 'INPUT' && // #1603
target.tagName !== 'TEXTAREA' && // #2266
!(isScrollable(getHtmlContainer()) && // #1944
getHtmlContainer().contains(target))) {
return true;
}
return false;
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1786
*
* @param {*} event
* @returns {boolean}
*/
const isStylus = event => {
return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1891
*
* @param {TouchEvent} event
* @returns {boolean}
*/
const isZoom = event => {
return event.touches && event.touches.length > 1;
};
const undoIOSfix = () => {
if (hasClass(document.body, swalClasses.iosfix)) {
const offset = parseInt(document.body.style.top, 10);
removeClass(document.body, swalClasses.iosfix);
document.body.style.top = '';
document.body.scrollTop = offset * -1;
}
};
const SHOW_CLASS_TIMEOUT = 10;
/**
* Open popup, add necessary classes and styles, fix scrollbar
*
* @param params
*/
const openPopup = params => {
const container = getContainer();
const popup = getPopup();
if (typeof params.willOpen === 'function') {
params.willOpen(popup);
}
const bodyStyles = window.getComputedStyle(document.body);
const initialBodyOverflow = bodyStyles.overflowY;
addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
setTimeout(() => {
setScrollingVisibility(container, popup);
}, SHOW_CLASS_TIMEOUT);
if (isModal()) {
fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
setAriaHidden();
}
if (!isToast() && !globalState.previousActiveElement) {
globalState.previousActiveElement = document.activeElement;
}
if (typeof params.didOpen === 'function') {
setTimeout(() => params.didOpen(popup));
}
removeClass(container, swalClasses['no-transition']);
};
const swalOpenAnimationFinished = event => {
const popup = getPopup();
if (event.target !== popup) {
return;
}
const container = getContainer();
popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
container.style.overflowY = 'auto';
};
const setScrollingVisibility = (container, popup) => {
if (animationEndEvent && hasCssAnimation(popup)) {
container.style.overflowY = 'hidden';
popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
} else {
container.style.overflowY = 'auto';
}
};
const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
iOSfix();
if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
fixScrollbar();
} // sweetalert2/issues/1247
setTimeout(() => {
container.scrollTop = 0;
});
};
const addClasses$1 = (container, popup, params) => {
addClass(container, params.showClass.backdrop); // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
popup.style.setProperty('opacity', '0', 'important');
show(popup, 'grid');
setTimeout(() => {
// Animate popup right after showing it
addClass(popup, params.showClass.popup); // and remove the opacity workaround
popup.style.removeProperty('opacity');
}, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
addClass([document.documentElement, document.body], swalClasses.shown);
if (params.heightAuto && params.backdrop && !params.toast) {
addClass([document.documentElement, document.body], swalClasses['height-auto']);
}
};
/**
* Shows loader (spinner), this is useful with AJAX requests.
* By default the loader be shown instead of the "Confirm" button.
*/
const showLoading = buttonToReplace => {
let popup = getPopup();
if (!popup) {
new Swal(); // eslint-disable-line no-new
}
popup = getPopup();
const loader = getLoader();
if (isToast()) {
hide(getIcon());
} else {
replaceButton(popup, buttonToReplace);
}
show(loader);
popup.setAttribute('data-loading', true);
popup.setAttribute('aria-busy', true);
popup.focus();
};
const replaceButton = (popup, buttonToReplace) => {
const actions = getActions();
const loader = getLoader();
if (!buttonToReplace && isVisible(getConfirmButton())) {
buttonToReplace = getConfirmButton();
}
show(actions);
if (buttonToReplace) {
hide(buttonToReplace);
loader.setAttribute('data-button-to-replace', buttonToReplace.className);
}
loader.parentNode.insertBefore(loader, buttonToReplace);
addClass([popup, actions], swalClasses.loading);
};
const handleInputOptionsAndValue = (instance, params) => {
if (params.input === 'select' || params.input === 'radio') {
handleInputOptions(instance, params);
} else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
showLoading(getConfirmButton());
handleInputValue(instance, params);
}
};
const getInputValue = (instance, innerParams) => {
const input = instance.getInput();
if (!input) {
return null;
}
switch (innerParams.input) {
case 'checkbox':
return getCheckboxValue(input);
case 'radio':
return getRadioValue(input);
case 'file':
return getFileValue(input);
default:
return innerParams.inputAutoTrim ? input.value.trim() : input.value;
}
};
const getCheckboxValue = input => input.checked ? 1 : 0;
const getRadioValue = input => input.checked ? input.value : null;
const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
const handleInputOptions = (instance, params) => {
const popup = getPopup();
const processInputOptions = inputOptions => populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);
if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
showLoading(getConfirmButton());
asPromise(params.inputOptions).then(inputOptions => {
instance.hideLoading();
processInputOptions(inputOptions);
});
} else if (typeof params.inputOptions === 'object') {
processInputOptions(params.inputOptions);
} else {
error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(typeof params.inputOptions));
}
};
const handleInputValue = (instance, params) => {
const input = instance.getInput();
hide(input);
asPromise(params.inputValue).then(inputValue => {
input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : "".concat(inputValue);
show(input);
input.focus();
instance.hideLoading();
}).catch(err => {
error("Error in inputValue promise: ".concat(err));
input.value = '';
show(input);
input.focus();
instance.hideLoading();
});
};
const populateInputOptions = {
select: (popup, inputOptions, params) => {
const select = getDirectChildByClass(popup, swalClasses.select);
const renderOption = (parent, optionLabel, optionValue) => {
const option = document.createElement('option');
option.value = optionValue;
setInnerHtml(option, optionLabel);
option.selected = isSelected(optionValue, params.inputValue);
parent.appendChild(option);
};
inputOptions.forEach(inputOption => {
const optionValue = inputOption[0];
const optionLabel = inputOption[1]; // <optgroup> spec:
// https://www.w3.org/TR/html401/interact/forms.html#h-17.6
// "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
// check whether this is a <optgroup>
if (Array.isArray(optionLabel)) {
// if it is an array, then it is an <optgroup>
const optgroup = document.createElement('optgroup');
optgroup.label = optionValue;
optgroup.disabled = false; // not configurable for now
select.appendChild(optgroup);
optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
} else {
// case of <option>
renderOption(select, optionLabel, optionValue);
}
});
select.focus();
},
radio: (popup, inputOptions, params) => {
const radio = getDirectChildByClass(popup, swalClasses.radio);
inputOptions.forEach(inputOption => {
const radioValue = inputOption[0];
const radioLabel = inputOption[1];
const radioInput = document.createElement('input');
const radioLabelElement = document.createElement('label');
radioInput.type = 'radio';
radioInput.name = swalClasses.radio;
radioInput.value = radioValue;
if (isSelected(radioValue, params.inputValue)) {
radioInput.checked = true;
}
const label = document.createElement('span');
setInnerHtml(label, radioLabel);
label.className = swalClasses.label;
radioLabelElement.appendChild(radioInput);
radioLabelElement.appendChild(label);
radio.appendChild(radioLabelElement);
});
const radios = radio.querySelectorAll('input');
if (radios.length) {
radios[0].focus();
}
}
};
/**
* Converts `inputOptions` into an array of `[value, label]`s
* @param inputOptions
*/
const formatInputOptions = inputOptions => {
const result = [];
if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
inputOptions.forEach((value, key) => {
let valueFormatted = value;
if (typeof valueFormatted === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
});
} else {
Object.keys(inputOptions).forEach(key => {
let valueFormatted = inputOptions[key];
if (typeof valueFormatted === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
});
}
return result;
};
const isSelected = (optionValue, inputValue) => {
return inputValue && inputValue.toString() === optionValue.toString();
};
const handleConfirmButtonClick = instance => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableButtons();
if (innerParams.input) {
handleConfirmOrDenyWithInput(instance, 'confirm');
} else {
confirm(instance, true);
}
};
const handleDenyButtonClick = instance => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableButtons();
if (innerParams.returnInputValueOnDeny) {
handleConfirmOrDenyWithInput(instance, 'deny');
} else {
deny(instance, false);
}
};
const handleCancelButtonClick = (instance, dismissWith) => {
instance.disableButtons();
dismissWith(DismissReason.cancel);
};
const handleConfirmOrDenyWithInput = (instance, type
/* 'confirm' | 'deny' */
) => {
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams.input) {
return error("The \"input\" parameter is needed to be set when using returnInputValueOn".concat(capitalizeFirstLetter(type)));
}
const inputValue = getInputValue(instance, innerParams);
if (innerParams.inputValidator) {
handleInputValidator(instance, inputValue, type);
} else if (!instance.getInput().checkValidity()) {
instance.enableButtons();
instance.showValidationMessage(innerParams.validationMessage);
} else if (type === 'deny') {
deny(instance, inputValue);
} else {
confirm(instance, inputValue);
}
};
const handleInputValidator = (instance, inputValue, type
/* 'confirm' | 'deny' */
) => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableInput();
const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
validationPromise.then(validationMessage => {
instance.enableButtons();
instance.enableInput();
if (validationMessage) {
instance.showValidationMessage(validationMessage);
} else if (type === 'deny') {
deny(instance, inputValue);
} else {
confirm(instance, inputValue);
}
});
};
const deny = (instance, value) => {
const innerParams = privateProps.innerParams.get(instance || undefined);
if (innerParams.showLoaderOnDeny) {
showLoading(getDenyButton());
}
if (innerParams.preDeny) {
privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
preDenyPromise.then(preDenyValue => {
if (preDenyValue === false) {
instance.hideLoading();
} else {
instance.closePopup({
isDenied: true,
value: typeof preDenyValue === 'undefined' ? value : preDenyValue
});
}
}).catch(error$$1 => rejectWith(instance || undefined, error$$1));
} else {
instance.closePopup({
isDenied: true,
value
});
}
};
const succeedWith = (instance, value) => {
instance.closePopup({
isConfirmed: true,
value
});
};
const rejectWith = (instance, error$$1) => {
instance.rejectPromise(error$$1);
};
const confirm = (instance, value) => {
const innerParams = privateProps.innerParams.get(instance || undefined);
if (innerParams.showLoaderOnConfirm) {
showLoading();
}
if (innerParams.preConfirm) {
instance.resetValidationMessage();
privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
preConfirmPromise.then(preConfirmValue => {
if (isVisible(getValidationMessage()) || preConfirmValue === false) {
instance.hideLoading();
} else {
succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
}
}).catch(error$$1 => rejectWith(instance || undefined, error$$1));
} else {
succeedWith(instance, value);
}
};
const handlePopupClick = (instance, domCache, dismissWith) => {
const innerParams = privateProps.innerParams.get(instance);
if (innerParams.toast) {
handleToastClick(instance, domCache, dismissWith);
} else {
// Ignore click events that had mousedown on the popup but mouseup on the container
// This can happen when the user drags a slider
handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
handleContainerMousedown(domCache);
handleModalClick(instance, domCache, dismissWith);
}
};
const handleToastClick = (instance, domCache, dismissWith) => {
// Closing toast by internal click
domCache.popup.onclick = () => {
const innerParams = privateProps.innerParams.get(instance);
if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
return;
}
dismissWith(DismissReason.close);
};
};
/**
* @param {*} innerParams
* @returns {boolean}
*/
const isAnyButtonShown = innerParams => {
return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;
};
let ignoreOutsideClick = false;
const handleModalMousedown = domCache => {
domCache.popup.onmousedown = () => {
domCache.container.onmouseup = function (e) {
domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
// have any other direct children aside of the popup
if (e.target === domCache.container) {
ignoreOutsideClick = true;
}
};
};
};
const handleContainerMousedown = domCache => {
domCache.container.onmousedown = () => {
domCache.popup.onmouseup = function (e) {
domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
ignoreOutsideClick = true;
}
};
};
};
const handleModalClick = (instance, domCache, dismissWith) => {
domCache.container.onclick = e => {
const innerParams = privateProps.innerParams.get(instance);
if (ignoreOutsideClick) {
ignoreOutsideClick = false;
return;
}
if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
dismissWith(DismissReason.backdrop);
}
};
};
/*
* Global function to determine if SweetAlert2 popup is shown
*/
const isVisible$1 = () => {
return isVisible(getPopup());
};
/*
* Global function to click 'Confirm' button
*/
const clickConfirm = () => getConfirmButton() && getConfirmButton().click();
/*
* Global function to click 'Deny' button
*/
const clickDeny = () => getDenyButton() && getDenyButton().click();
/*
* Global function to click 'Cancel' button
*/
const clickCancel = () => getCancelButton() && getCancelButton().click();
const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {
if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
if (!innerParams.toast) {
globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);
globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = true;
}
}; // Focus handling
const setFocus = (innerParams, index, increment) => {
const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
if (focusableElements.length) {
index = index + increment; // rollover to first item
if (index === focusableElements.length) {
index = 0; // go to last item
} else if (index === -1) {
index = focusableElements.length - 1;
}
return focusableElements[index].focus();
} // no visible focusable elements, focus the popup
getPopup().focus();
};
const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
const keydownHandler = (instance, e, dismissWith) => {
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams) {
return; // This instance has already been destroyed
}
if (innerParams.stopKeydownPropagation) {
e.stopPropagation();
} // ENTER
if (e.key === 'Enter') {
handleEnter(instance, e, innerParams);
} // TAB
else if (e.key === 'Tab') {
handleTab(e, innerParams);
} // ARROWS - switch focus between buttons
else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(e.key)) {
handleArrows(e.key);
} // ESC
else if (e.key === 'Escape') {
handleEsc(e, innerParams, dismissWith);
}
};
const handleEnter = (instance, e, innerParams) => {
// #2386 #720 #721
if (!callIfFunction(innerParams.allowEnterKey) || e.isComposing) {
return;
}
if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
if (['textarea', 'file'].includes(innerParams.input)) {
return; // do not submit
}
clickConfirm();
e.preventDefault();
}
};
const handleTab = (e, innerParams) => {
const targetElement = e.target;
const focusableElements = getFocusableElements();
let btnIndex = -1;
for (let i = 0; i < focusableElements.length; i++) {
if (targetElement === focusableElements[i]) {
btnIndex = i;
break;
}
} // Cycle to the next button
if (!e.shiftKey) {
setFocus(innerParams, btnIndex, 1);
} // Cycle to the prev button
else {
setFocus(innerParams, btnIndex, -1);
}
e.stopPropagation();
e.preventDefault();
};
const handleArrows = key => {
const confirmButton = getConfirmButton();
const denyButton = getDenyButton();
const cancelButton = getCancelButton();
if (![confirmButton, denyButton, cancelButton].includes(document.activeElement)) {
return;
}
const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
const buttonToFocus = document.activeElement[sibling];
if (buttonToFocus instanceof HTMLElement) {
buttonToFocus.focus();
}
};
const handleEsc = (e, innerParams, dismissWith) => {
if (callIfFunction(innerParams.allowEscapeKey)) {
e.preventDefault();
dismissWith(DismissReason.esc);
}
};
const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
const isElement = elem => elem instanceof Element || isJqueryElement(elem);
const argsToParams = args => {
const params = {};
if (typeof args[0] === 'object' && !isElement(args[0])) {
Object.assign(params, args[0]);
} else {
['title', 'html', 'icon'].forEach((name, index) => {
const arg = args[index];
if (typeof arg === 'string' || isElement(arg)) {
params[name] = arg;
} else if (arg !== undefined) {
error("Unexpected type of ".concat(name, "! Expected \"string\" or \"Element\", got ").concat(typeof arg));
}
});
}
return params;
};
function fire() {
const Swal = this; // eslint-disable-line @typescript-eslint/no-this-alias
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new Swal(...args);
}
/**
* Returns an extended version of `Swal` containing `params` as defaults.
* Useful for reusing Swal configuration.
*
* For example:
*
* Before:
* const textPromptOptions = { input: 'text', showCancelButton: true }
* const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
* const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
*
* After:
* const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
* const {value: firstName} = await TextPrompt('What is your first name?')
* const {value: lastName} = await TextPrompt('What is your last name?')
*
* @param mixinParams
*/
function mixin(mixinParams) {
class MixinSwal extends this {
_main(params, priorityMixinParams) {
return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
}
}
return MixinSwal;
}
/**
* If `timer` parameter is set, returns number of milliseconds of timer remained.
* Otherwise, returns undefined.
*/
const getTimerLeft = () => {
return globalState.timeout && globalState.timeout.getTimerLeft();
};
/**
* Stop timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
const stopTimer = () => {
if (globalState.timeout) {
stopTimerProgressBar();
return globalState.timeout.stop();
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
const resumeTimer = () => {
if (globalState.timeout) {
const remaining = globalState.timeout.start();
animateTimerProgressBar(remaining);
return remaining;
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
const toggleTimer = () => {
const timer = globalState.timeout;
return timer && (timer.running ? stopTimer() : resumeTimer());
};
/**
* Increase timer. Returns number of milliseconds of an updated timer.
* If `timer` parameter isn't set, returns undefined.
*/
const increaseTimer = n => {
if (globalState.timeout) {
const remaining = globalState.timeout.increase(n);
animateTimerProgressBar(remaining, true);
return remaining;
}
};
/**
* Check if timer is running. Returns true if timer is running
* or false if timer is paused or stopped.
* If `timer` parameter isn't set, returns undefined
*/
const isTimerRunning = () => {
return globalState.timeout && globalState.timeout.isRunning();
};
let bodyClickListenerAdded = false;
const clickHandlers = {};
function bindClickHandler() {
let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
clickHandlers[attr] = this;
if (!bodyClickListenerAdded) {
document.body.addEventListener('click', bodyClickListener);
bodyClickListenerAdded = true;
}
}
const bodyClickListener = event => {
for (let el = event.target; el && el !== document; el = el.parentNode) {
for (const attr in clickHandlers) {
const template = el.getAttribute(attr);
if (template) {
clickHandlers[attr].fire({
template
});
return;
}
}
}
};
var staticMethods = /*#__PURE__*/Object.freeze({
isValidParameter: isValidParameter,
isUpdatableParameter: isUpdatableParameter,
isDeprecatedParameter: isDeprecatedParameter,
argsToParams: argsToParams,
isVisible: isVisible$1,
clickConfirm: clickConfirm,
clickDeny: clickDeny,
clickCancel: clickCancel,
getContainer: getContainer,
getPopup: getPopup,
getTitle: getTitle,
getHtmlContainer: getHtmlContainer,
getImage: getImage,
getIcon: getIcon,
getInputLabel: getInputLabel,
getCloseButton: getCloseButton,
getActions: getActions,
getConfirmButton: getConfirmButton,
getDenyButton: getDenyButton,
getCancelButton: getCancelButton,
getLoader: getLoader,
getFooter: getFooter,
getTimerProgressBar: getTimerProgressBar,
getFocusableElements: getFocusableElements,
getValidationMessage: getValidationMessage,
isLoading: isLoading,
fire: fire,
mixin: mixin,
showLoading: showLoading,
enableLoading: showLoading,
getTimerLeft: getTimerLeft,
stopTimer: stopTimer,
resumeTimer: resumeTimer,
toggleTimer: toggleTimer,
increaseTimer: increaseTimer,
isTimerRunning: isTimerRunning,
bindClickHandler: bindClickHandler
});
/**
* Hides loader and shows back the button which was hidden by .showLoading()
*/
function hideLoading() {
// do nothing if popup is closed
const innerParams = privateProps.innerParams.get(this);
if (!innerParams) {
return;
}
const domCache = privateProps.domCache.get(this);
hide(domCache.loader);
if (isToast()) {
if (innerParams.icon) {
show(getIcon());
}
} else {
showRelatedButton(domCache);
}
removeClass([domCache.popup, domCache.actions], swalClasses.loading);
domCache.popup.removeAttribute('aria-busy');
domCache.popup.removeAttribute('data-loading');
domCache.confirmButton.disabled = false;
domCache.denyButton.disabled = false;
domCache.cancelButton.disabled = false;
}
const showRelatedButton = domCache => {
const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
if (buttonToReplace.length) {
show(buttonToReplace[0], 'inline-block');
} else if (allButtonsAreHidden()) {
hide(domCache.actions);
}
};
/**
* Gets the input DOM node, this method works with input parameter.
* @returns {HTMLElement | null}
*/
function getInput$1(instance) {
const innerParams = privateProps.innerParams.get(instance || this);
const domCache = privateProps.domCache.get(instance || this);
if (!domCache) {
return null;
}
return getInput(domCache.popup, innerParams.input);
}
/**
* This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* https://github.com/tc39/proposal-private-methods
* https://github.com/babel/babel/pull/7555
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateMethods = {
swalPromiseResolve: new WeakMap(),
swalPromiseReject: new WeakMap()
};
/*
* Instance method to close sweetAlert
*/
function removePopupAndResetState(instance, container, returnFocus, didClose) {
if (isToast()) {
triggerDidCloseAndDispose(instance, didClose);
} else {
restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); // workaround for #2088
// for some reason removing the container in Safari will scroll the document to bottom
if (isSafari) {
container.setAttribute('style', 'display:none !important');
container.removeAttribute('class');
container.innerHTML = '';
} else {
container.remove();
}
if (isModal()) {
undoScrollbar();
undoIOSfix();
unsetAriaHidden();
}
removeBodyClasses();
}
function removeBodyClasses() {
removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
}
function close(resolveValue) {
resolveValue = prepareResolveValue(resolveValue);
const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
const didClose = triggerClosePopup(this);
if (this.isAwaitingPromise()) {
// A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
if (!resolveValue.isDismissed) {
handleAwaitingPromise(this);
swalPromiseResolve(resolveValue);
}
} else if (didClose) {
// Resolve Swal promise
swalPromiseResolve(resolveValue);
}
}
function isAwaitingPromise() {
return !!privateProps.awaitingPromise.get(this);
}
const triggerClosePopup = instance => {
const popup = getPopup();
if (!popup) {
return false;
}
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
return false;
}
removeClass(popup, innerParams.showClass.popup);
addClass(popup, innerParams.hideClass.popup);
const backdrop = getContainer();
removeClass(backdrop, innerParams.showClass.backdrop);
addClass(backdrop, innerParams.hideClass.backdrop);
handlePopupAnimation(instance, popup, innerParams);
return true;
};
function rejectPromise(error) {
const rejectPromise = privateMethods.swalPromiseReject.get(this);
handleAwaitingPromise(this);
if (rejectPromise) {
// Reject Swal promise
rejectPromise(error);
}
}
const handleAwaitingPromise = instance => {
if (instance.isAwaitingPromise()) {
privateProps.awaitingPromise.delete(instance); // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
if (!privateProps.innerParams.get(instance)) {
instance._destroy();
}
}
};
const prepareResolveValue = resolveValue => {
// When user calls Swal.close()
if (typeof resolveValue === 'undefined') {
return {
isConfirmed: false,
isDenied: false,
isDismissed: true
};
}
return Object.assign({
isConfirmed: false,
isDenied: false,
isDismissed: false
}, resolveValue);
};
const handlePopupAnimation = (instance, popup, innerParams) => {
const container = getContainer(); // If animation is supported, animate
const animationIsSupported = animationEndEvent && hasCssAnimation(popup);
if (typeof innerParams.willClose === 'function') {
innerParams.willClose(popup);
}
if (animationIsSupported) {
animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
} else {
// Otherwise, remove immediately
removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
}
};
const animatePopup = (instance, popup, container, returnFocus, didClose) => {
globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
popup.addEventListener(animationEndEvent, function (e) {
if (e.target === popup) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
}
});
};
const triggerDidCloseAndDispose = (instance, didClose) => {
setTimeout(() => {
if (typeof didClose === 'function') {
didClose.bind(instance.params)();
}
instance._destroy();
});
};
function setButtonsDisabled(instance, buttons, disabled) {
const domCache = privateProps.domCache.get(instance);
buttons.forEach(button => {
domCache[button].disabled = disabled;
});
}
function setInputDisabled(input, disabled) {
if (!input) {
return false;
}
if (input.type === 'radio') {
const radiosContainer = input.parentNode.parentNode;
const radios = radiosContainer.querySelectorAll('input');
for (let i = 0; i < radios.length; i++) {
radios[i].disabled = disabled;
}
} else {
input.disabled = disabled;
}
}
function enableButtons() {
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
}
function disableButtons() {
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
}
function enableInput() {
return setInputDisabled(this.getInput(), false);
}
function disableInput() {
return setInputDisabled(this.getInput(), true);
}
function showValidationMessage(error) {
const domCache = privateProps.domCache.get(this);
const params = privateProps.innerParams.get(this);
setInnerHtml(domCache.validationMessage, error);
domCache.validationMessage.className = swalClasses['validation-message'];
if (params.customClass && params.customClass.validationMessage) {
addClass(domCache.validationMessage, params.customClass.validationMessage);
}
show(domCache.validationMessage);
const input = this.getInput();
if (input) {
input.setAttribute('aria-invalid', true);
input.setAttribute('aria-describedby', swalClasses['validation-message']);
focusInput(input);
addClass(input, swalClasses.inputerror);
}
} // Hide block with validation message
function resetValidationMessage$1() {
const domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
const input = this.getInput();
if (input) {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedby');
removeClass(input, swalClasses.inputerror);
}
}
function getProgressSteps$1() {
const domCache = privateProps.domCache.get(this);
return domCache.progressSteps;
}
/**
* Updates popup parameters.
*/
function update(params) {
const popup = getPopup();
const innerParams = privateProps.innerParams.get(this);
if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
return warn("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");
}
const validUpdatableParams = filterValidParams(params);
const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
render(this, updatedParams);
privateProps.innerParams.set(this, updatedParams);
Object.defineProperties(this, {
params: {
value: Object.assign({}, this.params, params),
writable: false,
enumerable: true
}
});
}
const filterValidParams = params => {
const validUpdatableParams = {};
Object.keys(params).forEach(param => {
if (isUpdatableParameter(param)) {
validUpdatableParams[param] = params[param];
} else {
warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md"));
}
});
return validUpdatableParams;
};
function _destroy() {
const domCache = privateProps.domCache.get(this);
const innerParams = privateProps.innerParams.get(this);
if (!innerParams) {
disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
return; // This instance has already been destroyed
} // Check if there is another Swal closing
if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
} // Check if there is a swal disposal defer timer
if (globalState.deferDisposalTimer) {
clearTimeout(globalState.deferDisposalTimer);
delete globalState.deferDisposalTimer;
}
if (typeof innerParams.didDestroy === 'function') {
innerParams.didDestroy();
}
disposeSwal(this);
}
const disposeSwal = instance => {
disposeWeakMaps(instance); // Unset this.params so GC will dispose it (#1569)
delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
delete globalState.keydownHandler;
delete globalState.keydownTarget; // Unset currentInstance
delete globalState.currentInstance;
};
const disposeWeakMaps = instance => {
// If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
if (instance.isAwaitingPromise()) {
unsetWeakMaps(privateProps, instance);
privateProps.awaitingPromise.set(instance, true);
} else {
unsetWeakMaps(privateMethods, instance);
unsetWeakMaps(privateProps, instance);
}
};
const unsetWeakMaps = (obj, instance) => {
for (const i in obj) {
obj[i].delete(instance);
}
};
var instanceMethods = /*#__PURE__*/Object.freeze({
hideLoading: hideLoading,
disableLoading: hideLoading,
getInput: getInput$1,
close: close,
isAwaitingPromise: isAwaitingPromise,
rejectPromise: rejectPromise,
closePopup: close,
closeModal: close,
closeToast: close,
enableButtons: enableButtons,
disableButtons: disableButtons,
enableInput: enableInput,
disableInput: disableInput,
showValidationMessage: showValidationMessage,
resetValidationMessage: resetValidationMessage$1,
getProgressSteps: getProgressSteps$1,
update: update,
_destroy: _destroy
});
let currentInstance;
class SweetAlert {
constructor() {
// Prevent run in Node env
if (typeof window === 'undefined') {
return;
}
currentInstance = this; // @ts-ignore
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const outerParams = Object.freeze(this.constructor.argsToParams(args));
Object.defineProperties(this, {
params: {
value: outerParams,
writable: false,
enumerable: true,
configurable: true
}
}); // @ts-ignore
const promise = this._main(this.params);
privateProps.promise.set(this, promise);
}
_main(userParams) {
let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
showWarningsForParams(Object.assign({}, mixinParams, userParams));
if (globalState.currentInstance) {
globalState.currentInstance._destroy();
if (isModal()) {
unsetAriaHidden();
}
}
globalState.currentInstance = this;
const innerParams = prepareParams(userParams, mixinParams);
setParameters(innerParams);
Object.freeze(innerParams); // clear the previous timer
if (globalState.timeout) {
globalState.timeout.stop();
delete globalState.timeout;
} // clear the restore focus timeout
clearTimeout(globalState.restoreFocusTimeout);
const domCache = populateDomCache(this);
render(this, innerParams);
privateProps.innerParams.set(this, innerParams);
return swalPromise(this, domCache, innerParams);
} // `catch` cannot be the name of a module export, so we define our thenable methods here instead
then(onFulfilled) {
const promise = privateProps.promise.get(this);
return promise.then(onFulfilled);
}
finally(onFinally) {
const promise = privateProps.promise.get(this);
return promise.finally(onFinally);
}
}
const swalPromise = (instance, domCache, innerParams) => {
return new Promise((resolve, reject) => {
// functions to handle all closings/dismissals
const dismissWith = dismiss => {
instance.closePopup({
isDismissed: true,
dismiss
});
};
privateMethods.swalPromiseResolve.set(instance, resolve);
privateMethods.swalPromiseReject.set(instance, reject);
domCache.confirmButton.onclick = () => handleConfirmButtonClick(instance);
domCache.denyButton.onclick = () => handleDenyButtonClick(instance);
domCache.cancelButton.onclick = () => handleCancelButtonClick(instance, dismissWith);
domCache.closeButton.onclick = () => dismissWith(DismissReason.close);
handlePopupClick(instance, domCache, dismissWith);
addKeydownHandler(instance, globalState, innerParams, dismissWith);
handleInputOptionsAndValue(instance, innerParams);
openPopup(innerParams);
setupTimer(globalState, innerParams, dismissWith);
initFocus(domCache, innerParams); // Scroll container to top on open (#1247, #1946)
setTimeout(() => {
domCache.container.scrollTop = 0;
});
});
};
const prepareParams = (userParams, mixinParams) => {
const templateParams = getTemplateParams(userParams);
const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
return params;
};
const populateDomCache = instance => {
const domCache = {
popup: getPopup(),
container: getContainer(),
actions: getActions(),
confirmButton: getConfirmButton(),
denyButton: getDenyButton(),
cancelButton: getCancelButton(),
loader: getLoader(),
closeButton: getCloseButton(),
validationMessage: getValidationMessage(),
progressSteps: getProgressSteps()
};
privateProps.domCache.set(instance, domCache);
return domCache;
};
const setupTimer = (globalState$$1, innerParams, dismissWith) => {
const timerProgressBar = getTimerProgressBar();
hide(timerProgressBar);
if (innerParams.timer) {
globalState$$1.timeout = new Timer(() => {
dismissWith('timer');
delete globalState$$1.timeout;
}, innerParams.timer);
if (innerParams.timerProgressBar) {
show(timerProgressBar);
applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
setTimeout(() => {
if (globalState$$1.timeout && globalState$$1.timeout.running) {
// timer can be already stopped or unset at this point
animateTimerProgressBar(innerParams.timer);
}
});
}
}
};
const initFocus = (domCache, innerParams) => {
if (innerParams.toast) {
return;
}
if (!callIfFunction(innerParams.allowEnterKey)) {
return blurActiveElement();
}
if (!focusButton(domCache, innerParams)) {
setFocus(innerParams, -1, 1);
}
};
const focusButton = (domCache, innerParams) => {
if (innerParams.focusDeny && isVisible(domCache.denyButton)) {
domCache.denyButton.focus();
return true;
}
if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
domCache.cancelButton.focus();
return true;
}
if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
domCache.confirmButton.focus();
return true;
}
return false;
};
const blurActiveElement = () => {
if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
document.activeElement.blur();
}
}; // Assign instance methods from src/instanceMethods/*.js to prototype
Object.assign(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
Object.assign(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
Object.keys(instanceMethods).forEach(key => {
SweetAlert[key] = function () {
if (currentInstance) {
return currentInstance[key](...arguments);
}
};
});
SweetAlert.DismissReason = DismissReason;
SweetAlert.version = '11.4.0';
const Swal = SweetAlert; // @ts-ignore
Swal.default = Swal;
return Swal;
}));
if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}
|
2881099/FreeSql.AdminLTE
| 29,903 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.css
|
.swal2-popup.swal2-toast {
box-sizing: border-box;
grid-column: 1/4 !important;
grid-row: 1/4 !important;
grid-template-columns: 1fr 99fr 1fr;
padding: 1em;
overflow-y: hidden;
background: #fff;
box-shadow: 0 0 1px rgba(0, 0, 0, 0.075), 0 1px 2px rgba(0, 0, 0, 0.075), 1px 2px 4px rgba(0, 0, 0, 0.075), 1px 3px 8px rgba(0, 0, 0, 0.075), 2px 4px 16px rgba(0, 0, 0, 0.075);
pointer-events: all;
}
.swal2-popup.swal2-toast > * {
grid-column: 2;
}
.swal2-popup.swal2-toast .swal2-title {
margin: 0.5em 1em;
padding: 0;
font-size: 1em;
text-align: initial;
}
.swal2-popup.swal2-toast .swal2-loading {
justify-content: center;
}
.swal2-popup.swal2-toast .swal2-input {
height: 2em;
margin: 0.5em;
font-size: 1em;
}
.swal2-popup.swal2-toast .swal2-validation-message {
font-size: 1em;
}
.swal2-popup.swal2-toast .swal2-footer {
margin: 0.5em 0 0;
padding: 0.5em 0 0;
font-size: 0.8em;
}
.swal2-popup.swal2-toast .swal2-close {
grid-column: 3/3;
grid-row: 1/99;
align-self: center;
width: 0.8em;
height: 0.8em;
margin: 0;
font-size: 2em;
}
.swal2-popup.swal2-toast .swal2-html-container {
margin: 0.5em 1em;
padding: 0;
font-size: 1em;
text-align: initial;
}
.swal2-popup.swal2-toast .swal2-html-container:empty {
padding: 0;
}
.swal2-popup.swal2-toast .swal2-loader {
grid-column: 1;
grid-row: 1/99;
align-self: center;
width: 2em;
height: 2em;
margin: 0.25em;
}
.swal2-popup.swal2-toast .swal2-icon {
grid-column: 1;
grid-row: 1/99;
align-self: center;
width: 2em;
min-width: 2em;
height: 2em;
margin: 0 0.5em 0 0;
}
.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content {
display: flex;
align-items: center;
font-size: 1.8em;
font-weight: bold;
}
.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring {
width: 2em;
height: 2em;
}
.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line] {
top: 0.875em;
width: 1.375em;
}
.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left] {
left: 0.3125em;
}
.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right] {
right: 0.3125em;
}
.swal2-popup.swal2-toast .swal2-actions {
justify-content: flex-start;
height: auto;
margin: 0;
margin-top: 0.5em;
padding: 0 0.5em;
}
.swal2-popup.swal2-toast .swal2-styled {
margin: 0.25em 0.5em;
padding: 0.4em 0.6em;
font-size: 1em;
}
.swal2-popup.swal2-toast .swal2-success {
border-color: #a5dc86;
}
.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line] {
position: absolute;
width: 1.6em;
height: 3em;
transform: rotate(45deg);
border-radius: 50%;
}
.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left] {
top: -0.8em;
left: -0.5em;
transform: rotate(-45deg);
transform-origin: 2em 2em;
border-radius: 4em 0 0 4em;
}
.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right] {
top: -0.25em;
left: 0.9375em;
transform-origin: 0 1.5em;
border-radius: 0 4em 4em 0;
}
.swal2-popup.swal2-toast .swal2-success .swal2-success-ring {
width: 2em;
height: 2em;
}
.swal2-popup.swal2-toast .swal2-success .swal2-success-fix {
top: 0;
left: 0.4375em;
width: 0.4375em;
height: 2.6875em;
}
.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line] {
height: 0.3125em;
}
.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip] {
top: 1.125em;
left: 0.1875em;
width: 0.75em;
}
.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long] {
top: 0.9375em;
right: 0.1875em;
width: 1.375em;
}
.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip {
-webkit-animation: swal2-toast-animate-success-line-tip 0.75s;
animation: swal2-toast-animate-success-line-tip 0.75s;
}
.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long {
-webkit-animation: swal2-toast-animate-success-line-long 0.75s;
animation: swal2-toast-animate-success-line-long 0.75s;
}
.swal2-popup.swal2-toast.swal2-show {
-webkit-animation: swal2-toast-show 0.5s;
animation: swal2-toast-show 0.5s;
}
.swal2-popup.swal2-toast.swal2-hide {
-webkit-animation: swal2-toast-hide 0.1s forwards;
animation: swal2-toast-hide 0.1s forwards;
}
.swal2-container {
display: grid;
position: fixed;
z-index: 1060;
top: 0;
right: 0;
bottom: 0;
left: 0;
box-sizing: border-box;
grid-template-areas: "top-start top top-end" "center-start center center-end" "bottom-start bottom-center bottom-end";
grid-template-rows: minmax(-webkit-min-content, auto) minmax(-webkit-min-content, auto) minmax(-webkit-min-content, auto);
grid-template-rows: minmax(min-content, auto) minmax(min-content, auto) minmax(min-content, auto);
height: 100%;
padding: 0.625em;
overflow-x: hidden;
transition: background-color 0.1s;
-webkit-overflow-scrolling: touch;
}
.swal2-container.swal2-backdrop-show, .swal2-container.swal2-noanimation {
background: rgba(0, 0, 0, 0.4);
}
.swal2-container.swal2-backdrop-hide {
background: transparent !important;
}
.swal2-container.swal2-top-start, .swal2-container.swal2-center-start, .swal2-container.swal2-bottom-start {
grid-template-columns: minmax(0, 1fr) auto auto;
}
.swal2-container.swal2-top, .swal2-container.swal2-center, .swal2-container.swal2-bottom {
grid-template-columns: auto minmax(0, 1fr) auto;
}
.swal2-container.swal2-top-end, .swal2-container.swal2-center-end, .swal2-container.swal2-bottom-end {
grid-template-columns: auto auto minmax(0, 1fr);
}
.swal2-container.swal2-top-start > .swal2-popup {
align-self: start;
}
.swal2-container.swal2-top > .swal2-popup {
grid-column: 2;
align-self: start;
justify-self: center;
}
.swal2-container.swal2-top-end > .swal2-popup, .swal2-container.swal2-top-right > .swal2-popup {
grid-column: 3;
align-self: start;
justify-self: end;
}
.swal2-container.swal2-center-start > .swal2-popup, .swal2-container.swal2-center-left > .swal2-popup {
grid-row: 2;
align-self: center;
}
.swal2-container.swal2-center > .swal2-popup {
grid-column: 2;
grid-row: 2;
align-self: center;
justify-self: center;
}
.swal2-container.swal2-center-end > .swal2-popup, .swal2-container.swal2-center-right > .swal2-popup {
grid-column: 3;
grid-row: 2;
align-self: center;
justify-self: end;
}
.swal2-container.swal2-bottom-start > .swal2-popup, .swal2-container.swal2-bottom-left > .swal2-popup {
grid-column: 1;
grid-row: 3;
align-self: end;
}
.swal2-container.swal2-bottom > .swal2-popup {
grid-column: 2;
grid-row: 3;
justify-self: center;
align-self: end;
}
.swal2-container.swal2-bottom-end > .swal2-popup, .swal2-container.swal2-bottom-right > .swal2-popup {
grid-column: 3;
grid-row: 3;
align-self: end;
justify-self: end;
}
.swal2-container.swal2-grow-row > .swal2-popup, .swal2-container.swal2-grow-fullscreen > .swal2-popup {
grid-column: 1/4;
width: 100%;
}
.swal2-container.swal2-grow-column > .swal2-popup, .swal2-container.swal2-grow-fullscreen > .swal2-popup {
grid-row: 1/4;
align-self: stretch;
}
.swal2-container.swal2-no-transition {
transition: none !important;
}
.swal2-popup {
display: none;
position: relative;
box-sizing: border-box;
grid-template-columns: minmax(0, 100%);
width: 32em;
max-width: 100%;
padding: 0 0 1.25em;
border: none;
border-radius: 5px;
background: #fff;
color: #545454;
font-family: inherit;
font-size: 1rem;
}
.swal2-popup:focus {
outline: none;
}
.swal2-popup.swal2-loading {
overflow-y: hidden;
}
.swal2-title {
position: relative;
max-width: 100%;
margin: 0;
padding: 0.8em 1em 0;
color: inherit;
font-size: 1.875em;
font-weight: 600;
text-align: center;
text-transform: none;
word-wrap: break-word;
}
.swal2-actions {
display: flex;
z-index: 1;
box-sizing: border-box;
flex-wrap: wrap;
align-items: center;
justify-content: center;
width: auto;
margin: 1.25em auto 0;
padding: 0;
}
.swal2-actions:not(.swal2-loading) .swal2-styled[disabled] {
opacity: 0.4;
}
.swal2-actions:not(.swal2-loading) .swal2-styled:hover {
background-image: linear-gradient(rgba(0, 0, 0, 0.1), rgba(0, 0, 0, 0.1));
}
.swal2-actions:not(.swal2-loading) .swal2-styled:active {
background-image: linear-gradient(rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.2));
}
.swal2-loader {
display: none;
align-items: center;
justify-content: center;
width: 2.2em;
height: 2.2em;
margin: 0 1.875em;
-webkit-animation: swal2-rotate-loading 1.5s linear 0s infinite normal;
animation: swal2-rotate-loading 1.5s linear 0s infinite normal;
border-width: 0.25em;
border-style: solid;
border-radius: 100%;
border-color: #2778c4 transparent #2778c4 transparent;
}
.swal2-styled {
margin: 0.3125em;
padding: 0.625em 1.1em;
transition: box-shadow 0.1s;
box-shadow: 0 0 0 3px transparent;
font-weight: 500;
}
.swal2-styled:not([disabled]) {
cursor: pointer;
}
.swal2-styled.swal2-confirm {
border: 0;
border-radius: 0.25em;
background: initial;
background-color: #7066e0;
color: #fff;
font-size: 1em;
}
.swal2-styled.swal2-confirm:focus {
box-shadow: 0 0 0 3px rgba(112, 102, 224, 0.5);
}
.swal2-styled.swal2-deny {
border: 0;
border-radius: 0.25em;
background: initial;
background-color: #dc3741;
color: #fff;
font-size: 1em;
}
.swal2-styled.swal2-deny:focus {
box-shadow: 0 0 0 3px rgba(220, 55, 65, 0.5);
}
.swal2-styled.swal2-cancel {
border: 0;
border-radius: 0.25em;
background: initial;
background-color: #6e7881;
color: #fff;
font-size: 1em;
}
.swal2-styled.swal2-cancel:focus {
box-shadow: 0 0 0 3px rgba(110, 120, 129, 0.5);
}
.swal2-styled.swal2-default-outline:focus {
box-shadow: 0 0 0 3px rgba(100, 150, 200, 0.5);
}
.swal2-styled:focus {
outline: none;
}
.swal2-styled::-moz-focus-inner {
border: 0;
}
.swal2-footer {
justify-content: center;
margin: 1em 0 0;
padding: 1em 1em 0;
border-top: 1px solid #eee;
color: inherit;
font-size: 1em;
}
.swal2-timer-progress-bar-container {
position: absolute;
right: 0;
bottom: 0;
left: 0;
grid-column: auto !important;
overflow: hidden;
border-bottom-right-radius: 5px;
border-bottom-left-radius: 5px;
}
.swal2-timer-progress-bar {
width: 100%;
height: 0.25em;
background: rgba(0, 0, 0, 0.2);
}
.swal2-image {
max-width: 100%;
margin: 2em auto 1em;
}
.swal2-close {
z-index: 2;
align-items: center;
justify-content: center;
width: 1.2em;
height: 1.2em;
margin-top: 0;
margin-right: 0;
margin-bottom: -1.2em;
padding: 0;
overflow: hidden;
transition: color 0.1s, box-shadow 0.1s;
border: none;
border-radius: 5px;
background: transparent;
color: #ccc;
font-family: serif;
font-family: monospace;
font-size: 2.5em;
cursor: pointer;
justify-self: end;
}
.swal2-close:hover {
transform: none;
background: transparent;
color: #f27474;
}
.swal2-close:focus {
outline: none;
box-shadow: inset 0 0 0 3px rgba(100, 150, 200, 0.5);
}
.swal2-close::-moz-focus-inner {
border: 0;
}
.swal2-html-container {
z-index: 1;
justify-content: center;
margin: 1em 1.6em 0.3em;
padding: 0;
overflow: auto;
color: inherit;
font-size: 1.125em;
font-weight: normal;
line-height: normal;
text-align: center;
word-wrap: break-word;
word-break: break-word;
}
.swal2-input,
.swal2-file,
.swal2-textarea,
.swal2-select,
.swal2-radio,
.swal2-checkbox {
margin: 1em 2em 3px;
}
.swal2-input,
.swal2-file,
.swal2-textarea {
box-sizing: border-box;
width: auto;
transition: border-color 0.1s, box-shadow 0.1s;
border: 1px solid #d9d9d9;
border-radius: 0.1875em;
background: inherit;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px transparent;
color: inherit;
font-size: 1.125em;
}
.swal2-input.swal2-inputerror,
.swal2-file.swal2-inputerror,
.swal2-textarea.swal2-inputerror {
border-color: #f27474 !important;
box-shadow: 0 0 2px #f27474 !important;
}
.swal2-input:focus,
.swal2-file:focus,
.swal2-textarea:focus {
border: 1px solid #b4dbed;
outline: none;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.06), 0 0 0 3px rgba(100, 150, 200, 0.5);
}
.swal2-input::-moz-placeholder, .swal2-file::-moz-placeholder, .swal2-textarea::-moz-placeholder {
color: #ccc;
}
.swal2-input:-ms-input-placeholder, .swal2-file:-ms-input-placeholder, .swal2-textarea:-ms-input-placeholder {
color: #ccc;
}
.swal2-input::placeholder,
.swal2-file::placeholder,
.swal2-textarea::placeholder {
color: #ccc;
}
.swal2-range {
margin: 1em 2em 3px;
background: #fff;
}
.swal2-range input {
width: 80%;
}
.swal2-range output {
width: 20%;
color: inherit;
font-weight: 600;
text-align: center;
}
.swal2-range input,
.swal2-range output {
height: 2.625em;
padding: 0;
font-size: 1.125em;
line-height: 2.625em;
}
.swal2-input {
height: 2.625em;
padding: 0 0.75em;
}
.swal2-file {
width: 75%;
margin-right: auto;
margin-left: auto;
background: inherit;
font-size: 1.125em;
}
.swal2-textarea {
height: 6.75em;
padding: 0.75em;
}
.swal2-select {
min-width: 50%;
max-width: 100%;
padding: 0.375em 0.625em;
background: inherit;
color: inherit;
font-size: 1.125em;
}
.swal2-radio,
.swal2-checkbox {
align-items: center;
justify-content: center;
background: #fff;
color: inherit;
}
.swal2-radio label,
.swal2-checkbox label {
margin: 0 0.6em;
font-size: 1.125em;
}
.swal2-radio input,
.swal2-checkbox input {
flex-shrink: 0;
margin: 0 0.4em;
}
.swal2-input-label {
display: flex;
justify-content: center;
margin: 1em auto 0;
}
.swal2-validation-message {
align-items: center;
justify-content: center;
margin: 1em 0 0;
padding: 0.625em;
overflow: hidden;
background: #f0f0f0;
color: #666666;
font-size: 1em;
font-weight: 300;
}
.swal2-validation-message::before {
content: "!";
display: inline-block;
width: 1.5em;
min-width: 1.5em;
height: 1.5em;
margin: 0 0.625em;
border-radius: 50%;
background-color: #f27474;
color: #fff;
font-weight: 600;
line-height: 1.5em;
text-align: center;
}
.swal2-icon {
position: relative;
box-sizing: content-box;
justify-content: center;
width: 5em;
height: 5em;
margin: 2.5em auto 0.6em;
border: 0.25em solid transparent;
border-radius: 50%;
border-color: #000;
font-family: inherit;
line-height: 5em;
cursor: default;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.swal2-icon .swal2-icon-content {
display: flex;
align-items: center;
font-size: 3.75em;
}
.swal2-icon.swal2-error {
border-color: #f27474;
color: #f27474;
}
.swal2-icon.swal2-error .swal2-x-mark {
position: relative;
flex-grow: 1;
}
.swal2-icon.swal2-error [class^=swal2-x-mark-line] {
display: block;
position: absolute;
top: 2.3125em;
width: 2.9375em;
height: 0.3125em;
border-radius: 0.125em;
background-color: #f27474;
}
.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left] {
left: 1.0625em;
transform: rotate(45deg);
}
.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right] {
right: 1em;
transform: rotate(-45deg);
}
.swal2-icon.swal2-error.swal2-icon-show {
-webkit-animation: swal2-animate-error-icon 0.5s;
animation: swal2-animate-error-icon 0.5s;
}
.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark {
-webkit-animation: swal2-animate-error-x-mark 0.5s;
animation: swal2-animate-error-x-mark 0.5s;
}
.swal2-icon.swal2-warning {
border-color: #facea8;
color: #f8bb86;
}
.swal2-icon.swal2-warning.swal2-icon-show {
-webkit-animation: swal2-animate-error-icon 0.5s;
animation: swal2-animate-error-icon 0.5s;
}
.swal2-icon.swal2-warning.swal2-icon-show .swal2-icon-content {
-webkit-animation: swal2-animate-i-mark 0.5s;
animation: swal2-animate-i-mark 0.5s;
}
.swal2-icon.swal2-info {
border-color: #9de0f6;
color: #3fc3ee;
}
.swal2-icon.swal2-info.swal2-icon-show {
-webkit-animation: swal2-animate-error-icon 0.5s;
animation: swal2-animate-error-icon 0.5s;
}
.swal2-icon.swal2-info.swal2-icon-show .swal2-icon-content {
-webkit-animation: swal2-animate-i-mark 0.8s;
animation: swal2-animate-i-mark 0.8s;
}
.swal2-icon.swal2-question {
border-color: #c9dae1;
color: #87adbd;
}
.swal2-icon.swal2-question.swal2-icon-show {
-webkit-animation: swal2-animate-error-icon 0.5s;
animation: swal2-animate-error-icon 0.5s;
}
.swal2-icon.swal2-question.swal2-icon-show .swal2-icon-content {
-webkit-animation: swal2-animate-question-mark 0.8s;
animation: swal2-animate-question-mark 0.8s;
}
.swal2-icon.swal2-success {
border-color: #a5dc86;
color: #a5dc86;
}
.swal2-icon.swal2-success [class^=swal2-success-circular-line] {
position: absolute;
width: 3.75em;
height: 7.5em;
transform: rotate(45deg);
border-radius: 50%;
}
.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left] {
top: -0.4375em;
left: -2.0635em;
transform: rotate(-45deg);
transform-origin: 3.75em 3.75em;
border-radius: 7.5em 0 0 7.5em;
}
.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right] {
top: -0.6875em;
left: 1.875em;
transform: rotate(-45deg);
transform-origin: 0 3.75em;
border-radius: 0 7.5em 7.5em 0;
}
.swal2-icon.swal2-success .swal2-success-ring {
position: absolute;
z-index: 2;
top: -0.25em;
left: -0.25em;
box-sizing: content-box;
width: 100%;
height: 100%;
border: 0.25em solid rgba(165, 220, 134, 0.3);
border-radius: 50%;
}
.swal2-icon.swal2-success .swal2-success-fix {
position: absolute;
z-index: 1;
top: 0.5em;
left: 1.625em;
width: 0.4375em;
height: 5.625em;
transform: rotate(-45deg);
}
.swal2-icon.swal2-success [class^=swal2-success-line] {
display: block;
position: absolute;
z-index: 2;
height: 0.3125em;
border-radius: 0.125em;
background-color: #a5dc86;
}
.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip] {
top: 2.875em;
left: 0.8125em;
width: 1.5625em;
transform: rotate(45deg);
}
.swal2-icon.swal2-success [class^=swal2-success-line][class$=long] {
top: 2.375em;
right: 0.5em;
width: 2.9375em;
transform: rotate(-45deg);
}
.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip {
-webkit-animation: swal2-animate-success-line-tip 0.75s;
animation: swal2-animate-success-line-tip 0.75s;
}
.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long {
-webkit-animation: swal2-animate-success-line-long 0.75s;
animation: swal2-animate-success-line-long 0.75s;
}
.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right {
-webkit-animation: swal2-rotate-success-circular-line 4.25s ease-in;
animation: swal2-rotate-success-circular-line 4.25s ease-in;
}
.swal2-progress-steps {
flex-wrap: wrap;
align-items: center;
max-width: 100%;
margin: 1.25em auto;
padding: 0;
background: inherit;
font-weight: 600;
}
.swal2-progress-steps li {
display: inline-block;
position: relative;
}
.swal2-progress-steps .swal2-progress-step {
z-index: 20;
flex-shrink: 0;
width: 2em;
height: 2em;
border-radius: 2em;
background: #2778c4;
color: #fff;
line-height: 2em;
text-align: center;
}
.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step {
background: #2778c4;
}
.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step ~ .swal2-progress-step {
background: #add8e6;
color: #fff;
}
.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step ~ .swal2-progress-step-line {
background: #add8e6;
}
.swal2-progress-steps .swal2-progress-step-line {
z-index: 10;
flex-shrink: 0;
width: 2.5em;
height: 0.4em;
margin: 0 -1px;
background: #2778c4;
}
[class^=swal2] {
-webkit-tap-highlight-color: transparent;
}
.swal2-show {
-webkit-animation: swal2-show 0.3s;
animation: swal2-show 0.3s;
}
.swal2-hide {
-webkit-animation: swal2-hide 0.15s forwards;
animation: swal2-hide 0.15s forwards;
}
.swal2-noanimation {
transition: none;
}
.swal2-scrollbar-measure {
position: absolute;
top: -9999px;
width: 50px;
height: 50px;
overflow: scroll;
}
.swal2-rtl .swal2-close {
margin-right: initial;
margin-left: 0;
}
.swal2-rtl .swal2-timer-progress-bar {
right: 0;
left: auto;
}
@-webkit-keyframes swal2-toast-show {
0% {
transform: translateY(-0.625em) rotateZ(2deg);
}
33% {
transform: translateY(0) rotateZ(-2deg);
}
66% {
transform: translateY(0.3125em) rotateZ(2deg);
}
100% {
transform: translateY(0) rotateZ(0deg);
}
}
@keyframes swal2-toast-show {
0% {
transform: translateY(-0.625em) rotateZ(2deg);
}
33% {
transform: translateY(0) rotateZ(-2deg);
}
66% {
transform: translateY(0.3125em) rotateZ(2deg);
}
100% {
transform: translateY(0) rotateZ(0deg);
}
}
@-webkit-keyframes swal2-toast-hide {
100% {
transform: rotateZ(1deg);
opacity: 0;
}
}
@keyframes swal2-toast-hide {
100% {
transform: rotateZ(1deg);
opacity: 0;
}
}
@-webkit-keyframes swal2-toast-animate-success-line-tip {
0% {
top: 0.5625em;
left: 0.0625em;
width: 0;
}
54% {
top: 0.125em;
left: 0.125em;
width: 0;
}
70% {
top: 0.625em;
left: -0.25em;
width: 1.625em;
}
84% {
top: 1.0625em;
left: 0.75em;
width: 0.5em;
}
100% {
top: 1.125em;
left: 0.1875em;
width: 0.75em;
}
}
@keyframes swal2-toast-animate-success-line-tip {
0% {
top: 0.5625em;
left: 0.0625em;
width: 0;
}
54% {
top: 0.125em;
left: 0.125em;
width: 0;
}
70% {
top: 0.625em;
left: -0.25em;
width: 1.625em;
}
84% {
top: 1.0625em;
left: 0.75em;
width: 0.5em;
}
100% {
top: 1.125em;
left: 0.1875em;
width: 0.75em;
}
}
@-webkit-keyframes swal2-toast-animate-success-line-long {
0% {
top: 1.625em;
right: 1.375em;
width: 0;
}
65% {
top: 1.25em;
right: 0.9375em;
width: 0;
}
84% {
top: 0.9375em;
right: 0;
width: 1.125em;
}
100% {
top: 0.9375em;
right: 0.1875em;
width: 1.375em;
}
}
@keyframes swal2-toast-animate-success-line-long {
0% {
top: 1.625em;
right: 1.375em;
width: 0;
}
65% {
top: 1.25em;
right: 0.9375em;
width: 0;
}
84% {
top: 0.9375em;
right: 0;
width: 1.125em;
}
100% {
top: 0.9375em;
right: 0.1875em;
width: 1.375em;
}
}
@-webkit-keyframes swal2-show {
0% {
transform: scale(0.7);
}
45% {
transform: scale(1.05);
}
80% {
transform: scale(0.95);
}
100% {
transform: scale(1);
}
}
@keyframes swal2-show {
0% {
transform: scale(0.7);
}
45% {
transform: scale(1.05);
}
80% {
transform: scale(0.95);
}
100% {
transform: scale(1);
}
}
@-webkit-keyframes swal2-hide {
0% {
transform: scale(1);
opacity: 1;
}
100% {
transform: scale(0.5);
opacity: 0;
}
}
@keyframes swal2-hide {
0% {
transform: scale(1);
opacity: 1;
}
100% {
transform: scale(0.5);
opacity: 0;
}
}
@-webkit-keyframes swal2-animate-success-line-tip {
0% {
top: 1.1875em;
left: 0.0625em;
width: 0;
}
54% {
top: 1.0625em;
left: 0.125em;
width: 0;
}
70% {
top: 2.1875em;
left: -0.375em;
width: 3.125em;
}
84% {
top: 3em;
left: 1.3125em;
width: 1.0625em;
}
100% {
top: 2.8125em;
left: 0.8125em;
width: 1.5625em;
}
}
@keyframes swal2-animate-success-line-tip {
0% {
top: 1.1875em;
left: 0.0625em;
width: 0;
}
54% {
top: 1.0625em;
left: 0.125em;
width: 0;
}
70% {
top: 2.1875em;
left: -0.375em;
width: 3.125em;
}
84% {
top: 3em;
left: 1.3125em;
width: 1.0625em;
}
100% {
top: 2.8125em;
left: 0.8125em;
width: 1.5625em;
}
}
@-webkit-keyframes swal2-animate-success-line-long {
0% {
top: 3.375em;
right: 2.875em;
width: 0;
}
65% {
top: 3.375em;
right: 2.875em;
width: 0;
}
84% {
top: 2.1875em;
right: 0;
width: 3.4375em;
}
100% {
top: 2.375em;
right: 0.5em;
width: 2.9375em;
}
}
@keyframes swal2-animate-success-line-long {
0% {
top: 3.375em;
right: 2.875em;
width: 0;
}
65% {
top: 3.375em;
right: 2.875em;
width: 0;
}
84% {
top: 2.1875em;
right: 0;
width: 3.4375em;
}
100% {
top: 2.375em;
right: 0.5em;
width: 2.9375em;
}
}
@-webkit-keyframes swal2-rotate-success-circular-line {
0% {
transform: rotate(-45deg);
}
5% {
transform: rotate(-45deg);
}
12% {
transform: rotate(-405deg);
}
100% {
transform: rotate(-405deg);
}
}
@keyframes swal2-rotate-success-circular-line {
0% {
transform: rotate(-45deg);
}
5% {
transform: rotate(-45deg);
}
12% {
transform: rotate(-405deg);
}
100% {
transform: rotate(-405deg);
}
}
@-webkit-keyframes swal2-animate-error-x-mark {
0% {
margin-top: 1.625em;
transform: scale(0.4);
opacity: 0;
}
50% {
margin-top: 1.625em;
transform: scale(0.4);
opacity: 0;
}
80% {
margin-top: -0.375em;
transform: scale(1.15);
}
100% {
margin-top: 0;
transform: scale(1);
opacity: 1;
}
}
@keyframes swal2-animate-error-x-mark {
0% {
margin-top: 1.625em;
transform: scale(0.4);
opacity: 0;
}
50% {
margin-top: 1.625em;
transform: scale(0.4);
opacity: 0;
}
80% {
margin-top: -0.375em;
transform: scale(1.15);
}
100% {
margin-top: 0;
transform: scale(1);
opacity: 1;
}
}
@-webkit-keyframes swal2-animate-error-icon {
0% {
transform: rotateX(100deg);
opacity: 0;
}
100% {
transform: rotateX(0deg);
opacity: 1;
}
}
@keyframes swal2-animate-error-icon {
0% {
transform: rotateX(100deg);
opacity: 0;
}
100% {
transform: rotateX(0deg);
opacity: 1;
}
}
@-webkit-keyframes swal2-rotate-loading {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@keyframes swal2-rotate-loading {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
@-webkit-keyframes swal2-animate-question-mark {
0% {
transform: rotateY(-360deg);
}
100% {
transform: rotateY(0);
}
}
@keyframes swal2-animate-question-mark {
0% {
transform: rotateY(-360deg);
}
100% {
transform: rotateY(0);
}
}
@-webkit-keyframes swal2-animate-i-mark {
0% {
transform: rotateZ(45deg);
opacity: 0;
}
25% {
transform: rotateZ(-25deg);
opacity: 0.4;
}
50% {
transform: rotateZ(15deg);
opacity: 0.8;
}
75% {
transform: rotateZ(-5deg);
opacity: 1;
}
100% {
transform: rotateX(0);
opacity: 1;
}
}
@keyframes swal2-animate-i-mark {
0% {
transform: rotateZ(45deg);
opacity: 0;
}
25% {
transform: rotateZ(-25deg);
opacity: 0.4;
}
50% {
transform: rotateZ(15deg);
opacity: 0.8;
}
75% {
transform: rotateZ(-5deg);
opacity: 1;
}
100% {
transform: rotateX(0);
opacity: 1;
}
}
body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) {
overflow: hidden;
}
body.swal2-height-auto {
height: auto !important;
}
body.swal2-no-backdrop .swal2-container {
background-color: transparent !important;
pointer-events: none;
}
body.swal2-no-backdrop .swal2-container .swal2-popup {
pointer-events: all;
}
body.swal2-no-backdrop .swal2-container .swal2-modal {
box-shadow: 0 0 10px rgba(0, 0, 0, 0.4);
}
@media print {
body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) {
overflow-y: scroll !important;
}
body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) > [aria-hidden=true] {
display: none;
}
body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container {
position: static !important;
}
}
body.swal2-toast-shown .swal2-container {
box-sizing: border-box;
width: 360px;
max-width: 100%;
background-color: transparent;
pointer-events: none;
}
body.swal2-toast-shown .swal2-container.swal2-top {
top: 0;
right: auto;
bottom: auto;
left: 50%;
transform: translateX(-50%);
}
body.swal2-toast-shown .swal2-container.swal2-top-end, body.swal2-toast-shown .swal2-container.swal2-top-right {
top: 0;
right: 0;
bottom: auto;
left: auto;
}
body.swal2-toast-shown .swal2-container.swal2-top-start, body.swal2-toast-shown .swal2-container.swal2-top-left {
top: 0;
right: auto;
bottom: auto;
left: 0;
}
body.swal2-toast-shown .swal2-container.swal2-center-start, body.swal2-toast-shown .swal2-container.swal2-center-left {
top: 50%;
right: auto;
bottom: auto;
left: 0;
transform: translateY(-50%);
}
body.swal2-toast-shown .swal2-container.swal2-center {
top: 50%;
right: auto;
bottom: auto;
left: 50%;
transform: translate(-50%, -50%);
}
body.swal2-toast-shown .swal2-container.swal2-center-end, body.swal2-toast-shown .swal2-container.swal2-center-right {
top: 50%;
right: 0;
bottom: auto;
left: auto;
transform: translateY(-50%);
}
body.swal2-toast-shown .swal2-container.swal2-bottom-start, body.swal2-toast-shown .swal2-container.swal2-bottom-left {
top: auto;
right: auto;
bottom: 0;
left: 0;
}
body.swal2-toast-shown .swal2-container.swal2-bottom {
top: auto;
right: auto;
bottom: 0;
left: 50%;
transform: translateX(-50%);
}
body.swal2-toast-shown .swal2-container.swal2-bottom-end, body.swal2-toast-shown .swal2-container.swal2-bottom-right {
top: auto;
right: 0;
bottom: 0;
left: auto;
}
|
294coder/Efficient-MIF
| 1,194 |
utils/FS_index/tools.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
Adapted versions of the functions used in:
Python Code on GitHub: https://github.com/sergiovitale/pansharpening-cnn-python-version
Copyright (c) 2018 Image Processing Research Group of University Federico II of Naples ('GRIP-UNINA').
"""
import numpy as np
def fir_filter_wind(Hd,w):
hd=np.rot90(np.fft.fftshift(np.rot90(Hd,2)),2)
h=np.fft.fftshift(np.fft.ifft2(hd))
h=np.rot90(h,2)
h=h*w
#h=h/np.sum(h)
return h
def gaussian2d (N, std):
t=np.arange(-(N-1)/2,(N+1)/2)
#t=np.arange(-(N-1)/2,(N+2)/2)
t1,t2=np.meshgrid(t,t)
std=np.double(std)
w = np.exp(-0.5*(t1/std)**2)*np.exp(-0.5*(t2/std)**2)
return w
def kaiser2d (N, beta):
t=np.arange(-(N-1)/2,(N+1)/2)/np.double(N-1)
#t=np.arange(-(N-1)/2,(N+2)/2)/np.double(N-1)
t1,t2=np.meshgrid(t,t)
t12=np.sqrt(t1*t1+t2*t2)
w1=np.kaiser(N,beta)
w=np.interp(t12,t,w1)
w[t12>t[-1]]=0
w[t12<t[0]]=0
return w
|
281677160/openwrt-package
| 17,089 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_amf.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp_amf.h"
#include "ngx_rtmp.h"
#include <string.h>
static ngx_inline void*
ngx_rtmp_amf_reverse_copy(void *dst, void* src, size_t len)
{
size_t k;
if (dst == NULL || src == NULL) {
return NULL;
}
for(k = 0; k < len; ++k) {
((u_char*)dst)[k] = ((u_char*)src)[len - 1 - k];
}
return dst;
}
#define NGX_RTMP_AMF_DEBUG_SIZE 16
#ifdef NGX_DEBUG
static void
ngx_rtmp_amf_debug(const char* op, ngx_log_t *log, u_char *p, size_t n)
{
u_char hstr[3 * NGX_RTMP_AMF_DEBUG_SIZE + 1];
u_char str[NGX_RTMP_AMF_DEBUG_SIZE + 1];
u_char *hp, *sp;
static u_char hex[] = "0123456789ABCDEF";
size_t i;
hp = hstr;
sp = str;
for(i = 0; i < n && i < NGX_RTMP_AMF_DEBUG_SIZE; ++i) {
*hp++ = ' ';
if (p) {
*hp++ = hex[(*p & 0xf0) >> 4];
*hp++ = hex[*p & 0x0f];
*sp++ = (*p >= 0x20 && *p <= 0x7e) ?
*p : (u_char)'?';
++p;
} else {
*hp++ = 'X';
*hp++ = 'X';
*sp++ = '?';
}
}
*hp = *sp = '\0';
ngx_log_debug4(NGX_LOG_DEBUG_RTMP, log, 0,
"AMF %s (%d)%s '%s'", op, n, hstr, str);
}
#endif
static ngx_int_t
ngx_rtmp_amf_get(ngx_rtmp_amf_ctx_t *ctx, void *p, size_t n)
{
size_t size;
ngx_chain_t *l;
size_t offset;
u_char *pos, *last;
#ifdef NGX_DEBUG
void *op = p;
size_t on = n;
#endif
if (!n)
return NGX_OK;
for(l = ctx->link, offset = ctx->offset; l; l = l->next, offset = 0) {
pos = l->buf->pos + offset;
last = l->buf->last;
if (last >= pos + n) {
if (p) {
p = ngx_cpymem(p, pos, n);
}
ctx->offset = offset + n;
ctx->link = l;
#ifdef NGX_DEBUG
ngx_rtmp_amf_debug("read", ctx->log, (u_char*)op, on);
#endif
return NGX_OK;
}
size = last - pos;
if (p) {
p = ngx_cpymem(p, pos, size);
}
n -= size;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, ctx->log, 0,
"AMF read eof (%d)", n);
return NGX_DONE;
}
static ngx_int_t
ngx_rtmp_amf_put(ngx_rtmp_amf_ctx_t *ctx, void *p, size_t n)
{
ngx_buf_t *b;
size_t size;
ngx_chain_t *l, *ln;
#ifdef NGX_DEBUG
ngx_rtmp_amf_debug("write", ctx->log, (u_char*)p, n);
#endif
l = ctx->link;
if (ctx->link && ctx->first == NULL) {
ctx->first = ctx->link;
}
while(n) {
b = l ? l->buf : NULL;
if (b == NULL || b->last == b->end) {
ln = ctx->alloc(ctx->arg);
if (ln == NULL) {
return NGX_ERROR;
}
if (ctx->first == NULL) {
ctx->first = ln;
}
if (l) {
l->next = ln;
}
l = ln;
ctx->link = l;
b = l->buf;
}
size = b->end - b->last;
if (size >= n) {
b->last = ngx_cpymem(b->last, p, n);
return NGX_OK;
}
b->last = ngx_cpymem(b->last, p, size);
p = (u_char*)p + size;
n -= size;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_amf_read_object(ngx_rtmp_amf_ctx_t *ctx, ngx_rtmp_amf_elt_t *elts,
size_t nelts)
{
uint8_t type;
uint16_t len;
size_t n, namelen, maxlen;
ngx_int_t rc;
u_char buf[2];
maxlen = 0;
for(n = 0; n < nelts; ++n) {
namelen = elts[n].name.len;
if (namelen > maxlen)
maxlen = namelen;
}
for( ;; ) {
#if !(NGX_WIN32)
char name[maxlen];
#else
char name[1024];
if (maxlen > sizeof(name)) {
return NGX_ERROR;
}
#endif
/* read key */
switch (ngx_rtmp_amf_get(ctx, buf, 2)) {
case NGX_DONE:
/* Envivio sends unfinalized arrays */
return NGX_OK;
case NGX_OK:
break;
default:
return NGX_ERROR;
}
ngx_rtmp_amf_reverse_copy(&len, buf, 2);
if (!len)
break;
if (len <= maxlen) {
rc = ngx_rtmp_amf_get(ctx, name, len);
} else {
rc = ngx_rtmp_amf_get(ctx, name, maxlen);
if (rc != NGX_OK)
return NGX_ERROR;
rc = ngx_rtmp_amf_get(ctx, 0, len - maxlen);
}
if (rc != NGX_OK)
return NGX_ERROR;
/* TODO: if we require array to be sorted on name
* then we could be able to use binary search */
for(n = 0; n < nelts
&& (len != elts[n].name.len
|| ngx_strncmp(name, elts[n].name.data, len));
++n);
if (ngx_rtmp_amf_read(ctx, n < nelts ? &elts[n] : NULL, 1) != NGX_OK)
return NGX_ERROR;
}
if (ngx_rtmp_amf_get(ctx, &type, 1) != NGX_OK
|| type != NGX_RTMP_AMF_END)
{
return NGX_ERROR;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_amf_read_array(ngx_rtmp_amf_ctx_t *ctx, ngx_rtmp_amf_elt_t *elts,
size_t nelts)
{
uint32_t len;
size_t n;
u_char buf[4];
/* read length */
if (ngx_rtmp_amf_get(ctx, buf, 4) != NGX_OK)
return NGX_ERROR;
ngx_rtmp_amf_reverse_copy(&len, buf, 4);
for (n = 0; n < len; ++n) {
if (ngx_rtmp_amf_read(ctx, n < nelts ? &elts[n] : NULL, 1) != NGX_OK)
return NGX_ERROR;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_amf_read_variant(ngx_rtmp_amf_ctx_t *ctx, ngx_rtmp_amf_elt_t *elts,
size_t nelts)
{
uint8_t type;
ngx_int_t rc;
size_t n;
ngx_rtmp_amf_elt_t elt;
rc = ngx_rtmp_amf_get(ctx, &type, 1);
if (rc != NGX_OK) {
return rc;
}
ngx_memzero(&elt, sizeof(elt));
for (n = 0; n < nelts; ++n, ++elts) {
if (type == elts->type) {
elt.data = elts->data;
elt.len = elts->len;
}
}
elt.type = type | NGX_RTMP_AMF_TYPELESS;
return ngx_rtmp_amf_read(ctx, &elt, 1);
}
static ngx_int_t
ngx_rtmp_amf_is_compatible_type(uint8_t t1, uint8_t t2)
{
return t1 == t2
|| (t1 == NGX_RTMP_AMF_OBJECT && t2 == NGX_RTMP_AMF_MIXED_ARRAY)
|| (t2 == NGX_RTMP_AMF_OBJECT && t1 == NGX_RTMP_AMF_MIXED_ARRAY);
}
ngx_int_t
ngx_rtmp_amf_read(ngx_rtmp_amf_ctx_t *ctx, ngx_rtmp_amf_elt_t *elts,
size_t nelts)
{
void *data;
ngx_int_t type;
uint8_t type8;
size_t n;
uint16_t len;
ngx_int_t rc;
u_char buf[8];
uint32_t max_index;
for(n = 0; n < nelts; ++n) {
if (elts && elts->type & NGX_RTMP_AMF_TYPELESS) {
type = elts->type & ~NGX_RTMP_AMF_TYPELESS;
data = elts->data;
} else {
switch (ngx_rtmp_amf_get(ctx, &type8, 1)) {
case NGX_DONE:
if (elts->type & NGX_RTMP_AMF_OPTIONAL) {
return NGX_OK;
} else {
return NGX_ERROR;
}
break;
case NGX_ERROR:
return NGX_ERROR;
}
type = type8;
data = (elts &&
ngx_rtmp_amf_is_compatible_type(
(uint8_t) (elts->type & 0xff), (uint8_t) type))
? elts->data
: NULL;
if (elts && (elts->type & NGX_RTMP_AMF_CONTEXT)) {
if (data) {
*(ngx_rtmp_amf_ctx_t *) data = *ctx;
}
data = NULL;
}
}
switch (type) {
case NGX_RTMP_AMF_NUMBER:
if (ngx_rtmp_amf_get(ctx, buf, 8) != NGX_OK) {
return NGX_ERROR;
}
ngx_rtmp_amf_reverse_copy(data, buf, 8);
break;
case NGX_RTMP_AMF_BOOLEAN:
if (ngx_rtmp_amf_get(ctx, data, 1) != NGX_OK) {
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_STRING:
if (ngx_rtmp_amf_get(ctx, buf, 2) != NGX_OK) {
return NGX_ERROR;
}
ngx_rtmp_amf_reverse_copy(&len, buf, 2);
if (data == NULL) {
rc = ngx_rtmp_amf_get(ctx, data, len);
} else if (elts->len <= len) {
rc = ngx_rtmp_amf_get(ctx, data, elts->len - 1);
if (rc != NGX_OK)
return NGX_ERROR;
((char*)data)[elts->len - 1] = 0;
rc = ngx_rtmp_amf_get(ctx, NULL, len - elts->len + 1);
} else {
rc = ngx_rtmp_amf_get(ctx, data, len);
((char*)data)[len] = 0;
}
if (rc != NGX_OK) {
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_NULL:
case NGX_RTMP_AMF_ARRAY_NULL:
break;
case NGX_RTMP_AMF_MIXED_ARRAY:
if (ngx_rtmp_amf_get(ctx, &max_index, 4) != NGX_OK) {
return NGX_ERROR;
}
if (ngx_rtmp_amf_read_object(ctx, data,
data && elts ? elts->len / sizeof(ngx_rtmp_amf_elt_t) : 0
) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_OBJECT:
if (ngx_rtmp_amf_read_object(ctx, data,
data && elts ? elts->len / sizeof(ngx_rtmp_amf_elt_t) : 0
) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_ARRAY:
if (ngx_rtmp_amf_read_array(ctx, data,
data && elts ? elts->len / sizeof(ngx_rtmp_amf_elt_t) : 0
) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_VARIANT_:
if (ngx_rtmp_amf_read_variant(ctx, data,
data && elts ? elts->len / sizeof(ngx_rtmp_amf_elt_t) : 0
) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_INT8:
if (ngx_rtmp_amf_get(ctx, data, 1) != NGX_OK) {
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_INT16:
if (ngx_rtmp_amf_get(ctx, buf, 2) != NGX_OK) {
return NGX_ERROR;
}
ngx_rtmp_amf_reverse_copy(data, buf, 2);
break;
case NGX_RTMP_AMF_INT32:
if (ngx_rtmp_amf_get(ctx, buf, 4) != NGX_OK) {
return NGX_ERROR;
}
ngx_rtmp_amf_reverse_copy(data, buf, 4);
break;
case NGX_RTMP_AMF_END:
return NGX_OK;
default:
return NGX_ERROR;
}
if (elts) {
++elts;
}
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_amf_write_object(ngx_rtmp_amf_ctx_t *ctx,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
uint16_t len;
size_t n;
u_char buf[2];
for(n = 0; n < nelts; ++n) {
len = (uint16_t) elts[n].name.len;
if (ngx_rtmp_amf_put(ctx,
ngx_rtmp_amf_reverse_copy(buf,
&len, 2), 2) != NGX_OK)
{
return NGX_ERROR;
}
if (ngx_rtmp_amf_put(ctx, elts[n].name.data, len) != NGX_OK) {
return NGX_ERROR;
}
if (ngx_rtmp_amf_write(ctx, &elts[n], 1) != NGX_OK) {
return NGX_ERROR;
}
}
if (ngx_rtmp_amf_put(ctx, "\0\0", 2) != NGX_OK) {
return NGX_ERROR;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_amf_write_array(ngx_rtmp_amf_ctx_t *ctx,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
uint32_t len;
size_t n;
u_char buf[4];
len = nelts;
if (ngx_rtmp_amf_put(ctx,
ngx_rtmp_amf_reverse_copy(buf,
&len, 4), 4) != NGX_OK)
{
return NGX_ERROR;
}
for(n = 0; n < nelts; ++n) {
if (ngx_rtmp_amf_write(ctx, &elts[n], 1) != NGX_OK) {
return NGX_ERROR;
}
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_amf_write(ngx_rtmp_amf_ctx_t *ctx,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
size_t n;
ngx_int_t type;
uint8_t type8;
void *data;
uint16_t len;
uint32_t max_index;
u_char buf[8];
for(n = 0; n < nelts; ++n) {
type = elts[n].type;
data = elts[n].data;
len = (uint16_t) elts[n].len;
if (type & NGX_RTMP_AMF_TYPELESS) {
type &= ~NGX_RTMP_AMF_TYPELESS;
} else {
type8 = (uint8_t)type;
if (ngx_rtmp_amf_put(ctx, &type8, 1) != NGX_OK)
return NGX_ERROR;
}
switch(type) {
case NGX_RTMP_AMF_NUMBER:
if (ngx_rtmp_amf_put(ctx,
ngx_rtmp_amf_reverse_copy(buf,
data, 8), 8) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_BOOLEAN:
if (ngx_rtmp_amf_put(ctx, data, 1) != NGX_OK) {
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_STRING:
if (len == 0 && data) {
len = (uint16_t) ngx_strlen((u_char*) data);
}
if (ngx_rtmp_amf_put(ctx,
ngx_rtmp_amf_reverse_copy(buf,
&len, 2), 2) != NGX_OK)
{
return NGX_ERROR;
}
if (ngx_rtmp_amf_put(ctx, data, len) != NGX_OK) {
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_NULL:
case NGX_RTMP_AMF_ARRAY_NULL:
break;
case NGX_RTMP_AMF_MIXED_ARRAY:
max_index = 0;
if (ngx_rtmp_amf_put(ctx, &max_index, 4) != NGX_OK) {
return NGX_ERROR;
}
type8 = NGX_RTMP_AMF_END;
if (ngx_rtmp_amf_write_object(ctx, data,
elts[n].len / sizeof(ngx_rtmp_amf_elt_t)) != NGX_OK
|| ngx_rtmp_amf_put(ctx, &type8, 1) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_OBJECT:
type8 = NGX_RTMP_AMF_END;
if (ngx_rtmp_amf_write_object(ctx, data,
elts[n].len / sizeof(ngx_rtmp_amf_elt_t)) != NGX_OK
|| ngx_rtmp_amf_put(ctx, &type8, 1) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_ARRAY:
if (ngx_rtmp_amf_write_array(ctx, data,
elts[n].len / sizeof(ngx_rtmp_amf_elt_t)) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_INT8:
if (ngx_rtmp_amf_put(ctx, data, 1) != NGX_OK) {
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_INT16:
if (ngx_rtmp_amf_put(ctx,
ngx_rtmp_amf_reverse_copy(buf,
data, 2), 2) != NGX_OK)
{
return NGX_ERROR;
}
break;
case NGX_RTMP_AMF_INT32:
if (ngx_rtmp_amf_put(ctx,
ngx_rtmp_amf_reverse_copy(buf,
data, 4), 4) != NGX_OK)
{
return NGX_ERROR;
}
break;
default:
return NGX_ERROR;
}
}
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 67,428 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.all.min.js
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Sweetalert2=t()}(this,function(){"use strict";const t="SweetAlert2:",y=e=>e.charAt(0).toUpperCase()+e.slice(1),i=e=>Array.prototype.slice.call(e),a=e=>{console.warn("".concat(t," ").concat("object"==typeof e?e.join(" "):e))},v=e=>{console.error("".concat(t," ").concat(e))},n=[],o=(e,t)=>{e='"'.concat(e,'" is deprecated and will be removed in the next major release. Please use "').concat(t,'" instead.'),n.includes(e)||(n.push(e),a(e))},w=e=>"function"==typeof e?e():e,C=e=>e&&"function"==typeof e.toPromise,k=e=>C(e)?e.toPromise():Promise.resolve(e),A=e=>e&&Promise.resolve(e)===e,r={title:"",titleText:"",text:"",html:"",footer:"",icon:void 0,iconColor:void 0,iconHtml:void 0,template:void 0,toast:!1,showClass:{popup:"swal2-show",backdrop:"swal2-backdrop-show",icon:"swal2-icon-show"},hideClass:{popup:"swal2-hide",backdrop:"swal2-backdrop-hide",icon:"swal2-icon-hide"},customClass:{},target:"body",color:void 0,backdrop:!0,heightAuto:!0,allowOutsideClick:!0,allowEscapeKey:!0,allowEnterKey:!0,stopKeydownPropagation:!0,keydownListenerCapture:!1,showConfirmButton:!0,showDenyButton:!1,showCancelButton:!1,preConfirm:void 0,preDeny:void 0,confirmButtonText:"OK",confirmButtonAriaLabel:"",confirmButtonColor:void 0,denyButtonText:"No",denyButtonAriaLabel:"",denyButtonColor:void 0,cancelButtonText:"Cancel",cancelButtonAriaLabel:"",cancelButtonColor:void 0,buttonsStyling:!0,reverseButtons:!1,focusConfirm:!0,focusDeny:!1,focusCancel:!1,returnFocus:!0,showCloseButton:!1,closeButtonHtml:"×",closeButtonAriaLabel:"Close this dialog",loaderHtml:"",showLoaderOnConfirm:!1,showLoaderOnDeny:!1,imageUrl:void 0,imageWidth:void 0,imageHeight:void 0,imageAlt:"",timer:void 0,timerProgressBar:!1,width:void 0,padding:void 0,background:void 0,input:void 0,inputPlaceholder:"",inputLabel:"",inputValue:"",inputOptions:{},inputAutoTrim:!0,inputAttributes:{},inputValidator:void 0,returnInputValueOnDeny:!1,validationMessage:void 0,grow:!1,position:"center",progressSteps:[],currentProgressStep:void 0,progressStepsDistance:void 0,willOpen:void 0,didOpen:void 0,didRender:void 0,willClose:void 0,didClose:void 0,didDestroy:void 0,scrollbarPadding:!0},s=["allowEscapeKey","allowOutsideClick","background","buttonsStyling","cancelButtonAriaLabel","cancelButtonColor","cancelButtonText","closeButtonAriaLabel","closeButtonHtml","color","confirmButtonAriaLabel","confirmButtonColor","confirmButtonText","currentProgressStep","customClass","denyButtonAriaLabel","denyButtonColor","denyButtonText","didClose","didDestroy","footer","hideClass","html","icon","iconColor","iconHtml","imageAlt","imageHeight","imageUrl","imageWidth","preConfirm","preDeny","progressSteps","returnFocus","reverseButtons","showCancelButton","showCloseButton","showConfirmButton","showDenyButton","text","title","titleText","willClose"],c={},P=["allowOutsideClick","allowEnterKey","backdrop","focusConfirm","focusDeny","focusCancel","returnFocus","heightAuto","keydownListenerCapture"],B=e=>Object.prototype.hasOwnProperty.call(r,e),x=e=>-1!==s.indexOf(e),E=e=>c[e],T=e=>{!e.backdrop&&e.allowOutsideClick&&a('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');for(const n in e)t=n,B(t)||a('Unknown parameter "'.concat(t,'"')),e.toast&&(t=n,P.includes(t)&&a('The parameter "'.concat(t,'" is incompatible with toasts'))),t=n,E(t)&&o(t,E(t));var t};var e=e=>{const t={};for(const n in e)t[e[n]]="swal2-"+e[n];return t};const p=e(["container","shown","height-auto","iosfix","popup","modal","no-backdrop","no-transition","toast","toast-shown","show","hide","close","title","html-container","actions","confirm","deny","cancel","default-outline","footer","icon","icon-content","image","input","file","range","select","radio","checkbox","label","textarea","inputerror","input-label","validation-message","progress-steps","active-progress-step","progress-step","progress-step-line","loader","loading","styled","top","top-start","top-end","top-left","top-right","center","center-start","center-end","center-left","center-right","bottom","bottom-start","bottom-end","bottom-left","bottom-right","grow-row","grow-column","grow-fullscreen","rtl","timer-progress-bar","timer-progress-bar-container","scrollbar-measure","icon-success","icon-warning","icon-info","icon-question","icon-error"]),S=e(["success","warning","info","question","error"]),m=()=>document.body.querySelector(".".concat(p.container)),L=e=>{const t=m();return t?t.querySelector(e):null},O=e=>L(".".concat(e)),g=()=>O(p.popup),j=()=>O(p.icon),M=()=>O(p.title),D=()=>O(p["html-container"]),I=()=>O(p.image),H=()=>O(p["progress-steps"]),q=()=>O(p["validation-message"]),V=()=>L(".".concat(p.actions," .").concat(p.confirm)),N=()=>L(".".concat(p.actions," .").concat(p.deny));const R=()=>L(".".concat(p.loader)),F=()=>L(".".concat(p.actions," .").concat(p.cancel)),U=()=>O(p.actions),W=()=>O(p.footer),z=()=>O(p["timer-progress-bar"]),_=()=>O(p.close),K=()=>{const e=i(g().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')).sort((e,t)=>{e=parseInt(e.getAttribute("tabindex")),t=parseInt(t.getAttribute("tabindex"));return t<e?1:e<t?-1:0});var t=i(g().querySelectorAll('\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex="0"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n')).filter(e=>"-1"!==e.getAttribute("tabindex"));return(t=>{const n=[];for(let e=0;e<t.length;e++)-1===n.indexOf(t[e])&&n.push(t[e]);return n})(e.concat(t)).filter(e=>ce(e))},Y=()=>!$(document.body,p["toast-shown"])&&!$(document.body,p["no-backdrop"]),Z=()=>g()&&$(g(),p.toast);function J(e){var t=1<arguments.length&&void 0!==arguments[1]&&arguments[1];const n=z();ce(n)&&(t&&(n.style.transition="none",n.style.width="100%"),setTimeout(()=>{n.style.transition="width ".concat(e/1e3,"s linear"),n.style.width="0%"},10))}const X={previousBodyPadding:null},l=(t,e)=>{if(t.textContent="",e){const n=new DOMParser,o=n.parseFromString(e,"text/html");i(o.querySelector("head").childNodes).forEach(e=>{t.appendChild(e)}),i(o.querySelector("body").childNodes).forEach(e=>{t.appendChild(e)})}},$=(t,e)=>{if(!e)return!1;var n=e.split(/\s+/);for(let e=0;e<n.length;e++)if(!t.classList.contains(n[e]))return!1;return!0},G=(t,n)=>{i(t.classList).forEach(e=>{Object.values(p).includes(e)||Object.values(S).includes(e)||Object.values(n.showClass).includes(e)||t.classList.remove(e)})},Q=(e,t,n)=>{if(G(e,t),t.customClass&&t.customClass[n]){if("string"!=typeof t.customClass[n]&&!t.customClass[n].forEach)return a("Invalid type of customClass.".concat(n,'! Expected string or iterable object, got "').concat(typeof t.customClass[n],'"'));u(e,t.customClass[n])}},ee=(e,t)=>{if(!t)return null;switch(t){case"select":case"textarea":case"file":return e.querySelector(".".concat(p.popup," > .").concat(p[t]));case"checkbox":return e.querySelector(".".concat(p.popup," > .").concat(p.checkbox," input"));case"radio":return e.querySelector(".".concat(p.popup," > .").concat(p.radio," input:checked"))||e.querySelector(".".concat(p.popup," > .").concat(p.radio," input:first-child"));case"range":return e.querySelector(".".concat(p.popup," > .").concat(p.range," input"));default:return e.querySelector(".".concat(p.popup," > .").concat(p.input))}},te=e=>{var t;e.focus(),"file"!==e.type&&(t=e.value,e.value="",e.value=t)},ne=(e,t,n)=>{e&&t&&(t="string"==typeof t?t.split(/\s+/).filter(Boolean):t).forEach(t=>{Array.isArray(e)?e.forEach(e=>{n?e.classList.add(t):e.classList.remove(t)}):n?e.classList.add(t):e.classList.remove(t)})},u=(e,t)=>{ne(e,t,!0)},oe=(e,t)=>{ne(e,t,!1)},ie=(e,t)=>{var n=i(e.childNodes);for(let e=0;e<n.length;e++)if($(n[e],t))return n[e]},ae=(e,t,n)=>{(n=n==="".concat(parseInt(n))?parseInt(n):n)||0===parseInt(n)?e.style[t]="number"==typeof n?"".concat(n,"px"):n:e.style.removeProperty(t)},d=function(e){e.style.display=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"flex"},h=e=>{e.style.display="none"},re=(e,t,n,o)=>{const i=e.querySelector(t);i&&(i.style[n]=o)},se=(e,t,n)=>{t?d(e,n):h(e)},ce=e=>!(!e||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)),le=()=>!ce(V())&&!ce(N())&&!ce(F()),ue=e=>!!(e.scrollHeight>e.clientHeight),de=e=>{const t=window.getComputedStyle(e);var e=parseFloat(t.getPropertyValue("animation-duration")||"0"),n=parseFloat(t.getPropertyValue("transition-duration")||"0");return 0<e||0<n},pe=()=>"undefined"==typeof window||"undefined"==typeof document,me=100,f={},ge=()=>{f.previousActiveElement&&f.previousActiveElement.focus?(f.previousActiveElement.focus(),f.previousActiveElement=null):document.body&&document.body.focus()},he=o=>new Promise(e=>{if(!o)return e();var t=window.scrollX,n=window.scrollY;f.restoreFocusTimeout=setTimeout(()=>{ge(),e()},me),window.scrollTo(t,n)}),fe='\n <div aria-labelledby="'.concat(p.title,'" aria-describedby="').concat(p["html-container"],'" class="').concat(p.popup,'" tabindex="-1">\n <button type="button" class="').concat(p.close,'"></button>\n <ul class="').concat(p["progress-steps"],'"></ul>\n <div class="').concat(p.icon,'"></div>\n <img class="').concat(p.image,'" />\n <h2 class="').concat(p.title,'" id="').concat(p.title,'"></h2>\n <div class="').concat(p["html-container"],'" id="').concat(p["html-container"],'"></div>\n <input class="').concat(p.input,'" />\n <input type="file" class="').concat(p.file,'" />\n <div class="').concat(p.range,'">\n <input type="range" />\n <output></output>\n </div>\n <select class="').concat(p.select,'"></select>\n <div class="').concat(p.radio,'"></div>\n <label for="').concat(p.checkbox,'" class="').concat(p.checkbox,'">\n <input type="checkbox" />\n <span class="').concat(p.label,'"></span>\n </label>\n <textarea class="').concat(p.textarea,'"></textarea>\n <div class="').concat(p["validation-message"],'" id="').concat(p["validation-message"],'"></div>\n <div class="').concat(p.actions,'">\n <div class="').concat(p.loader,'"></div>\n <button type="button" class="').concat(p.confirm,'"></button>\n <button type="button" class="').concat(p.deny,'"></button>\n <button type="button" class="').concat(p.cancel,'"></button>\n </div>\n <div class="').concat(p.footer,'"></div>\n <div class="').concat(p["timer-progress-bar-container"],'">\n <div class="').concat(p["timer-progress-bar"],'"></div>\n </div>\n </div>\n').replace(/(^|\n)\s*/g,""),be=()=>{const e=m();return!!e&&(e.remove(),oe([document.documentElement,document.body],[p["no-backdrop"],p["toast-shown"],p["has-column"]]),!0)},ye=()=>{f.currentInstance.resetValidationMessage()},ve=()=>{const e=g(),t=ie(e,p.input),n=ie(e,p.file),o=e.querySelector(".".concat(p.range," input")),i=e.querySelector(".".concat(p.range," output")),a=ie(e,p.select),r=e.querySelector(".".concat(p.checkbox," input")),s=ie(e,p.textarea);t.oninput=ye,n.onchange=ye,a.onchange=ye,r.onchange=ye,s.oninput=ye,o.oninput=()=>{ye(),i.value=o.value},o.onchange=()=>{ye(),o.nextSibling.value=o.value}},we=e=>"string"==typeof e?document.querySelector(e):e,Ce=e=>{const t=g();t.setAttribute("role",e.toast?"alert":"dialog"),t.setAttribute("aria-live",e.toast?"polite":"assertive"),e.toast||t.setAttribute("aria-modal","true")},ke=e=>{"rtl"===window.getComputedStyle(e).direction&&u(m(),p.rtl)},Ae=(e,t)=>{if(e instanceof HTMLElement)t.appendChild(e);else if("object"==typeof e){var n=e,o=t;if(n.jquery)Pe(o,n);else l(o,n.toString())}else e&&l(t,e)},Pe=(t,n)=>{if(t.textContent="",0 in n)for(let e=0;e in n;e++)t.appendChild(n[e].cloneNode(!0));else t.appendChild(n.cloneNode(!0))},Be=(()=>{if(pe())return!1;var e=document.createElement("div"),t={WebkitAnimation:"webkitAnimationEnd",animation:"animationend"};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&void 0!==e.style[n])return t[n];return!1})(),xe=(e,t)=>{var n,o,i,a,r,s=U(),c=R();(t.showConfirmButton||t.showDenyButton||t.showCancelButton?d:h)(s),Q(s,t,"actions"),s=s,n=c,o=t,i=V(),a=N(),r=F(),Ee(i,"confirm",o),Ee(a,"deny",o),Ee(r,"cancel",o),function(e,t,n,o){if(!o.buttonsStyling)return oe([e,t,n],p.styled);u([e,t,n],p.styled),o.confirmButtonColor&&(e.style.backgroundColor=o.confirmButtonColor,u(e,p["default-outline"]));o.denyButtonColor&&(t.style.backgroundColor=o.denyButtonColor,u(t,p["default-outline"]));o.cancelButtonColor&&(n.style.backgroundColor=o.cancelButtonColor,u(n,p["default-outline"]))}(i,a,r,o),o.reverseButtons&&(o.toast?(s.insertBefore(r,i),s.insertBefore(a,i)):(s.insertBefore(r,n),s.insertBefore(a,n),s.insertBefore(i,n))),l(c,t.loaderHtml),Q(c,t,"loader")};function Ee(e,t,n){se(e,n["show".concat(y(t),"Button")],"inline-block"),l(e,n["".concat(t,"ButtonText")]),e.setAttribute("aria-label",n["".concat(t,"ButtonAriaLabel")]),e.className=p[t],Q(e,n,"".concat(t,"Button")),u(e,n["".concat(t,"ButtonClass")])}const Te=(e,t)=>{var n,o,i=m();i&&(o=i,"string"==typeof(n=t.backdrop)?o.style.background=n:n||u([document.documentElement,document.body],p["no-backdrop"]),o=i,(n=t.position)in p?u(o,p[n]):(a('The "position" parameter is not valid, defaulting to "center"'),u(o,p.center)),n=i,!(o=t.grow)||"string"!=typeof o||(o="grow-".concat(o))in p&&u(n,p[o]),Q(i,t,"container"))};var b={awaitingPromise:new WeakMap,promise:new WeakMap,innerParams:new WeakMap,domCache:new WeakMap};const Se=["input","file","range","select","radio","checkbox","textarea"],Le=(e,r)=>{const s=g();var t,e=b.innerParams.get(e);const c=!e||r.input!==e.input;Se.forEach(e=>{var t=p[e];const n=ie(s,t);{var o=r.inputAttributes;const i=ee(g(),e);if(i){Oe(i);for(const a in o)i.setAttribute(a,o[a])}}n.className=t,c&&h(n)}),r.input&&(c&&(e=>{if(!Ie[e.input])return v('Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "'.concat(e.input,'"'));const t=De(e.input),n=Ie[e.input](t,e);d(n),setTimeout(()=>{te(n)})})(r),e=r,t=De(e.input),e.customClass&&u(t,e.customClass.input))},Oe=t=>{for(let e=0;e<t.attributes.length;e++){var n=t.attributes[e].name;["type","value","style"].includes(n)||t.removeAttribute(n)}},je=(e,t)=>{e.placeholder&&!t.inputPlaceholder||(e.placeholder=t.inputPlaceholder)},Me=(e,t,n)=>{if(n.inputLabel){e.id=p.input;const i=document.createElement("label");var o=p["input-label"];i.setAttribute("for",e.id),i.className=o,u(i,n.customClass.inputLabel),i.innerText=n.inputLabel,t.insertAdjacentElement("beforebegin",i)}},De=e=>{e=p[e]||p.input;return ie(g(),e)},Ie={},He=(Ie.text=Ie.email=Ie.password=Ie.number=Ie.tel=Ie.url=(e,t)=>("string"==typeof t.inputValue||"number"==typeof t.inputValue?e.value=t.inputValue:A(t.inputValue)||a('Unexpected type of inputValue! Expected "string", "number" or "Promise", got "'.concat(typeof t.inputValue,'"')),Me(e,e,t),je(e,t),e.type=t.input,e),Ie.file=(e,t)=>(Me(e,e,t),je(e,t),e),Ie.range=(e,t)=>{const n=e.querySelector("input"),o=e.querySelector("output");return n.value=t.inputValue,n.type=t.input,o.value=t.inputValue,Me(n,e,t),e},Ie.select=(e,t)=>{if(e.textContent="",t.inputPlaceholder){const n=document.createElement("option");l(n,t.inputPlaceholder),n.value="",n.disabled=!0,n.selected=!0,e.appendChild(n)}return Me(e,e,t),e},Ie.radio=e=>(e.textContent="",e),Ie.checkbox=(e,t)=>{const n=ee(g(),"checkbox");n.value="1",n.id=p.checkbox,n.checked=Boolean(t.inputValue);var o=e.querySelector("span");return l(o,t.inputPlaceholder),e},Ie.textarea=(n,e)=>{n.value=e.inputValue,je(n,e),Me(n,n,e);return setTimeout(()=>{if("MutationObserver"in window){const t=parseInt(window.getComputedStyle(g()).width);new MutationObserver(()=>{var e=n.offsetWidth+(e=n,parseInt(window.getComputedStyle(e).marginLeft)+parseInt(window.getComputedStyle(e).marginRight));e>t?g().style.width="".concat(e,"px"):g().style.width=null}).observe(n,{attributes:!0,attributeFilter:["style"]})}}),n},(e,t)=>{const n=D();Q(n,t,"htmlContainer"),t.html?(Ae(t.html,n),d(n,"block")):t.text?(n.textContent=t.text,d(n,"block")):h(n),Le(e,t)}),qe=(e,t)=>{var n=W();se(n,t.footer),t.footer&&Ae(t.footer,n),Q(n,t,"footer")},Ve=(e,t)=>{const n=_();l(n,t.closeButtonHtml),Q(n,t,"closeButton"),se(n,t.showCloseButton),n.setAttribute("aria-label",t.closeButtonAriaLabel)},Ne=(e,t)=>{var e=b.innerParams.get(e),n=j();return e&&t.icon===e.icon?(ze(n,t),void Re(n,t)):t.icon||t.iconHtml?t.icon&&-1===Object.keys(S).indexOf(t.icon)?(v('Unknown icon! Expected "success", "error", "warning", "info" or "question", got "'.concat(t.icon,'"')),h(n)):(d(n),ze(n,t),Re(n,t),void u(n,t.showClass.icon)):h(n)},Re=(e,t)=>{for(const n in S)t.icon!==n&&oe(e,S[n]);u(e,S[t.icon]),_e(e,t),Fe(),Q(e,t,"icon")},Fe=()=>{const e=g();var t=window.getComputedStyle(e).getPropertyValue("background-color");const n=e.querySelectorAll("[class^=swal2-success-circular-line], .swal2-success-fix");for(let e=0;e<n.length;e++)n[e].style.backgroundColor=t},Ue='\n <div class="swal2-success-circular-line-left"></div>\n <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>\n <div class="swal2-success-ring"></div> <div class="swal2-success-fix"></div>\n <div class="swal2-success-circular-line-right"></div>\n',We='\n <span class="swal2-x-mark">\n <span class="swal2-x-mark-line-left"></span>\n <span class="swal2-x-mark-line-right"></span>\n </span>\n',ze=(e,t)=>{var n;e.textContent="",t.iconHtml?l(e,Ke(t.iconHtml)):"success"===t.icon?l(e,Ue):"error"===t.icon?l(e,We):(n={question:"?",warning:"!",info:"i"},l(e,Ke(n[t.icon])))},_e=(e,t)=>{if(t.iconColor){e.style.color=t.iconColor,e.style.borderColor=t.iconColor;for(const n of[".swal2-success-line-tip",".swal2-success-line-long",".swal2-x-mark-line-left",".swal2-x-mark-line-right"])re(e,n,"backgroundColor",t.iconColor);re(e,".swal2-success-ring","borderColor",t.iconColor)}},Ke=e=>'<div class="'.concat(p["icon-content"],'">').concat(e,"</div>"),Ye=(e,t)=>{const n=I();if(!t.imageUrl)return h(n);d(n,""),n.setAttribute("src",t.imageUrl),n.setAttribute("alt",t.imageAlt),ae(n,"width",t.imageWidth),ae(n,"height",t.imageHeight),n.className=p.image,Q(n,t,"image")},Ze=(e,o)=>{const i=H();if(!o.progressSteps||0===o.progressSteps.length)return h(i);d(i),i.textContent="",o.currentProgressStep>=o.progressSteps.length&&a("Invalid currentProgressStep parameter, it should be less than progressSteps.length (currentProgressStep like JS arrays starts from 0)"),o.progressSteps.forEach((e,t)=>{e=e,n=document.createElement("li"),u(n,p["progress-step"]),l(n,e);var n,e=n;i.appendChild(e),t===o.currentProgressStep&&u(e,p["active-progress-step"]),t!==o.progressSteps.length-1&&(n=(e=>{const t=document.createElement("li");return u(t,p["progress-step-line"]),e.progressStepsDistance&&(t.style.width=e.progressStepsDistance),t})(o),i.appendChild(n))})},Je=(e,t)=>{const n=M();se(n,t.title||t.titleText,"block"),t.title&&Ae(t.title,n),t.titleText&&(n.innerText=t.titleText),Q(n,t,"title")},Xe=(e,t)=>{var n=m();const o=g();t.toast?(ae(n,"width",t.width),o.style.width="100%",o.insertBefore(R(),j())):ae(o,"width",t.width),ae(o,"padding",t.padding),t.color&&(o.style.color=t.color),t.background&&(o.style.background=t.background),h(q());n=o;(n.className="".concat(p.popup," ").concat(ce(n)?t.showClass.popup:""),t.toast)?(u([document.documentElement,document.body],p["toast-shown"]),u(n,p.toast)):u(n,p.modal);Q(n,t,"popup"),"string"==typeof t.customClass&&u(n,t.customClass);t.icon&&u(n,p["icon-".concat(t.icon)])},$e=(e,t)=>{Xe(e,t),Te(e,t),Ze(e,t),Ne(e,t),Ye(e,t),Je(e,t),Ve(e,t),He(e,t),xe(e,t),qe(e,t),"function"==typeof t.didRender&&t.didRender(g())},Ge=Object.freeze({cancel:"cancel",backdrop:"backdrop",close:"close",esc:"esc",timer:"timer"}),Qe=()=>{const e=i(document.body.children);e.forEach(e=>{e===m()||e.contains(m())||(e.hasAttribute("aria-hidden")&&e.setAttribute("data-previous-aria-hidden",e.getAttribute("aria-hidden")),e.setAttribute("aria-hidden","true"))})},et=()=>{const e=i(document.body.children);e.forEach(e=>{e.hasAttribute("data-previous-aria-hidden")?(e.setAttribute("aria-hidden",e.getAttribute("data-previous-aria-hidden")),e.removeAttribute("data-previous-aria-hidden")):e.removeAttribute("aria-hidden")})},tt=["swal-title","swal-html","swal-footer"],nt=e=>{const n={};return i(e.querySelectorAll("swal-param")).forEach(e=>{lt(e,["name","value"]);var t=e.getAttribute("name"),e=e.getAttribute("value");"boolean"==typeof r[t]&&"false"===e&&(n[t]=!1),"object"==typeof r[t]&&(n[t]=JSON.parse(e))}),n},ot=e=>{const n={};return i(e.querySelectorAll("swal-button")).forEach(e=>{lt(e,["type","color","aria-label"]);var t=e.getAttribute("type");n["".concat(t,"ButtonText")]=e.innerHTML,n["show".concat(y(t),"Button")]=!0,e.hasAttribute("color")&&(n["".concat(t,"ButtonColor")]=e.getAttribute("color")),e.hasAttribute("aria-label")&&(n["".concat(t,"ButtonAriaLabel")]=e.getAttribute("aria-label"))}),n},it=e=>{const t={},n=e.querySelector("swal-image");return n&&(lt(n,["src","width","height","alt"]),n.hasAttribute("src")&&(t.imageUrl=n.getAttribute("src")),n.hasAttribute("width")&&(t.imageWidth=n.getAttribute("width")),n.hasAttribute("height")&&(t.imageHeight=n.getAttribute("height")),n.hasAttribute("alt")&&(t.imageAlt=n.getAttribute("alt"))),t},at=e=>{const t={},n=e.querySelector("swal-icon");return n&&(lt(n,["type","color"]),n.hasAttribute("type")&&(t.icon=n.getAttribute("type")),n.hasAttribute("color")&&(t.iconColor=n.getAttribute("color")),t.iconHtml=n.innerHTML),t},rt=e=>{const n={},t=e.querySelector("swal-input");t&&(lt(t,["type","label","placeholder","value"]),n.input=t.getAttribute("type")||"text",t.hasAttribute("label")&&(n.inputLabel=t.getAttribute("label")),t.hasAttribute("placeholder")&&(n.inputPlaceholder=t.getAttribute("placeholder")),t.hasAttribute("value")&&(n.inputValue=t.getAttribute("value")));e=e.querySelectorAll("swal-input-option");return e.length&&(n.inputOptions={},i(e).forEach(e=>{lt(e,["value"]);var t=e.getAttribute("value"),e=e.innerHTML;n.inputOptions[t]=e})),n},st=(e,t)=>{const n={};for(const o in t){const i=t[o],a=e.querySelector(i);a&&(lt(a,[]),n[i.replace(/^swal-/,"")]=a.innerHTML.trim())}return n},ct=e=>{const t=tt.concat(["swal-param","swal-button","swal-image","swal-icon","swal-input","swal-input-option"]);i(e.children).forEach(e=>{e=e.tagName.toLowerCase();-1===t.indexOf(e)&&a("Unrecognized element <".concat(e,">"))})},lt=(t,n)=>{i(t.attributes).forEach(e=>{-1===n.indexOf(e.name)&&a(['Unrecognized attribute "'.concat(e.name,'" on <').concat(t.tagName.toLowerCase(),">."),"".concat(n.length?"Allowed attributes are: ".concat(n.join(", ")):"To set the value, use HTML within the element.")])})};var ut={email:(e,t)=>/^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(e)?Promise.resolve():Promise.resolve(t||"Invalid email address"),url:(e,t)=>/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(e)?Promise.resolve():Promise.resolve(t||"Invalid URL")};function dt(e){(t=e).inputValidator||Object.keys(ut).forEach(e=>{t.input===e&&(t.inputValidator=ut[e])}),e.showLoaderOnConfirm&&!e.preConfirm&&a("showLoaderOnConfirm is set to true, but preConfirm is not defined.\nshowLoaderOnConfirm should be used together with preConfirm, see usage example:\nhttps://sweetalert2.github.io/#ajax-request"),(n=e).target&&("string"!=typeof n.target||document.querySelector(n.target))&&("string"==typeof n.target||n.target.appendChild)||(a('Target parameter is not valid, defaulting to "body"'),n.target="body"),"string"==typeof e.title&&(e.title=e.title.split("\n").join("<br />"));var t,n=e,e=be();if(pe())v("SweetAlert2 requires document to initialize");else{const o=document.createElement("div"),i=(o.className=p.container,e&&u(o,p["no-transition"]),l(o,fe),we(n.target));i.appendChild(o),Ce(n),ke(i),ve()}}class pt{constructor(e,t){this.callback=e,this.remaining=t,this.running=!1,this.start()}start(){return this.running||(this.running=!0,this.started=new Date,this.id=setTimeout(this.callback,this.remaining)),this.remaining}stop(){return this.running&&(this.running=!1,clearTimeout(this.id),this.remaining-=(new Date).getTime()-this.started.getTime()),this.remaining}increase(e){var t=this.running;return t&&this.stop(),this.remaining+=e,t&&this.start(),this.remaining}getTimerLeft(){return this.running&&(this.stop(),this.start()),this.remaining}isRunning(){return this.running}}const mt=()=>{null===X.previousBodyPadding&&document.body.scrollHeight>window.innerHeight&&(X.previousBodyPadding=parseInt(window.getComputedStyle(document.body).getPropertyValue("padding-right")),document.body.style.paddingRight="".concat(X.previousBodyPadding+(()=>{const e=document.createElement("div");e.className=p["scrollbar-measure"],document.body.appendChild(e);var t=e.getBoundingClientRect().width-e.clientWidth;return document.body.removeChild(e),t})(),"px"))},gt=()=>{null!==X.previousBodyPadding&&(document.body.style.paddingRight="".concat(X.previousBodyPadding,"px"),X.previousBodyPadding=null)},ht=()=>{var e=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream||"MacIntel"===navigator.platform&&1<navigator.maxTouchPoints;if(e&&!$(document.body,p.iosfix)){var t,e=document.body.scrollTop;document.body.style.top="".concat(-1*e,"px"),u(document.body,p.iosfix);{const n=m();let t;n.ontouchstart=e=>{t=ft(e)},n.ontouchmove=e=>{t&&(e.preventDefault(),e.stopPropagation())}}{const o=navigator.userAgent,i=!!o.match(/iPad/i)||!!o.match(/iPhone/i),a=!!o.match(/WebKit/i),r=i&&a&&!o.match(/CriOS/i);r&&(t=44,g().scrollHeight>window.innerHeight-44&&(m().style.paddingBottom="".concat(44,"px")))}}},ft=e=>{var t,n=e.target,o=m();return!((t=e).touches&&t.touches.length&&"stylus"===t.touches[0].touchType||(t=e).touches&&1<t.touches.length)&&(n===o||!(ue(o)||"INPUT"===n.tagName||"TEXTAREA"===n.tagName||ue(D())&&D().contains(n)))},bt=()=>{var e;$(document.body,p.iosfix)&&(e=parseInt(document.body.style.top,10),oe(document.body,p.iosfix),document.body.style.top="",document.body.scrollTop=-1*e)},yt=10,vt=e=>{const t=g();if(e.target===t){const n=m();t.removeEventListener(Be,vt),n.style.overflowY="auto"}},wt=(e,t)=>{Be&&de(t)?(e.style.overflowY="hidden",t.addEventListener(Be,vt)):e.style.overflowY="auto"},Ct=(e,t,n)=>{ht(),t&&"hidden"!==n&&mt(),setTimeout(()=>{e.scrollTop=0})},kt=(e,t,n)=>{u(e,n.showClass.backdrop),t.style.setProperty("opacity","0","important"),d(t,"grid"),setTimeout(()=>{u(t,n.showClass.popup),t.style.removeProperty("opacity")},yt),u([document.documentElement,document.body],p.shown),n.heightAuto&&n.backdrop&&!n.toast&&u([document.documentElement,document.body],p["height-auto"])},At=e=>{let t=g();t||new vn,t=g();var n=R();if(Z())h(j());else{var o=t;const i=U(),a=R();!e&&ce(V())&&(e=V());d(i),e&&(h(e),a.setAttribute("data-button-to-replace",e.className));a.parentNode.insertBefore(a,e),u([o,i],p.loading)}d(n),t.setAttribute("data-loading",!0),t.setAttribute("aria-busy",!0),t.focus()},Pt=(t,n)=>{const o=g(),i=e=>xt[n.input](o,Et(e),n);C(n.inputOptions)||A(n.inputOptions)?(At(V()),k(n.inputOptions).then(e=>{t.hideLoading(),i(e)})):"object"==typeof n.inputOptions?i(n.inputOptions):v("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(typeof n.inputOptions))},Bt=(t,n)=>{const o=t.getInput();h(o),k(n.inputValue).then(e=>{o.value="number"===n.input?parseFloat(e)||0:"".concat(e),d(o),o.focus(),t.hideLoading()}).catch(e=>{v("Error in inputValue promise: ".concat(e)),o.value="",d(o),o.focus(),t.hideLoading()})},xt={select:(e,t,i)=>{const a=ie(e,p.select),r=(e,t,n)=>{const o=document.createElement("option");o.value=n,l(o,t),o.selected=Tt(n,i.inputValue),e.appendChild(o)};t.forEach(e=>{var t=e[0];const n=e[1];if(Array.isArray(n)){const o=document.createElement("optgroup");o.label=t,o.disabled=!1,a.appendChild(o),n.forEach(e=>r(o,e[1],e[0]))}else r(a,n,t)}),a.focus()},radio:(e,t,a)=>{const r=ie(e,p.radio),n=(t.forEach(e=>{var t=e[0],e=e[1];const n=document.createElement("input"),o=document.createElement("label"),i=(n.type="radio",n.name=p.radio,n.value=t,Tt(t,a.inputValue)&&(n.checked=!0),document.createElement("span"));l(i,e),i.className=p.label,o.appendChild(n),o.appendChild(i),r.appendChild(o)}),r.querySelectorAll("input"));n.length&&n[0].focus()}},Et=n=>{const o=[];return"undefined"!=typeof Map&&n instanceof Map?n.forEach((e,t)=>{let n=e;"object"==typeof n&&(n=Et(n)),o.push([t,n])}):Object.keys(n).forEach(e=>{let t=n[e];"object"==typeof t&&(t=Et(t)),o.push([e,t])}),o},Tt=(e,t)=>t&&t.toString()===e.toString(),St=(e,t)=>{var n=b.innerParams.get(e);if(!n.input)return v('The "input" parameter is needed to be set when using returnInputValueOn'.concat(y(t)));var o=((e,t)=>{const n=e.getInput();if(!n)return null;switch(t.input){case"checkbox":return n.checked?1:0;case"radio":return(o=n).checked?o.value:null;case"file":return(o=n).files.length?null!==o.getAttribute("multiple")?o.files:o.files[0]:null;default:return t.inputAutoTrim?n.value.trim():n.value}var o})(e,n);if(n.inputValidator){var i=e;var a=o;var r=t;const s=b.innerParams.get(i),c=(i.disableInput(),Promise.resolve().then(()=>k(s.inputValidator(a,s.validationMessage))));c.then(e=>{i.enableButtons(),i.enableInput(),e?i.showValidationMessage(e):("deny"===r?Lt:Mt)(i,a)})}else e.getInput().checkValidity()?("deny"===t?Lt:Mt)(e,o):(e.enableButtons(),e.showValidationMessage(n.validationMessage))},Lt=(t,n)=>{const e=b.innerParams.get(t||void 0);if(e.showLoaderOnDeny&&At(N()),e.preDeny){b.awaitingPromise.set(t||void 0,!0);const o=Promise.resolve().then(()=>k(e.preDeny(n,e.validationMessage)));o.then(e=>{!1===e?t.hideLoading():t.closePopup({isDenied:!0,value:void 0===e?n:e})}).catch(e=>jt(t||void 0,e))}else t.closePopup({isDenied:!0,value:n})},Ot=(e,t)=>{e.closePopup({isConfirmed:!0,value:t})},jt=(e,t)=>{e.rejectPromise(t)},Mt=(t,n)=>{const e=b.innerParams.get(t||void 0);if(e.showLoaderOnConfirm&&At(),e.preConfirm){t.resetValidationMessage(),b.awaitingPromise.set(t||void 0,!0);const o=Promise.resolve().then(()=>k(e.preConfirm(n,e.validationMessage)));o.then(e=>{ce(q())||!1===e?t.hideLoading():Ot(t,void 0===e?n:e)}).catch(e=>jt(t||void 0,e))}else Ot(t,n)},Dt=(n,e,o)=>{e.popup.onclick=()=>{var e,t=b.innerParams.get(n);t&&((e=t).showConfirmButton||e.showDenyButton||e.showCancelButton||e.showCloseButton||t.timer||t.input)||o(Ge.close)}};let It=!1;const Ht=t=>{t.popup.onmousedown=()=>{t.container.onmouseup=function(e){t.container.onmouseup=void 0,e.target===t.container&&(It=!0)}}},qt=t=>{t.container.onmousedown=()=>{t.popup.onmouseup=function(e){t.popup.onmouseup=void 0,e.target!==t.popup&&!t.popup.contains(e.target)||(It=!0)}}},Vt=(n,o,i)=>{o.container.onclick=e=>{var t=b.innerParams.get(n);It?It=!1:e.target===o.container&&w(t.allowOutsideClick)&&i(Ge.backdrop)}};const Nt=()=>V()&&V().click();const Rt=(e,t,n)=>{const o=K();if(o.length)return(t+=n)===o.length?t=0:-1===t&&(t=o.length-1),o[t].focus();g().focus()},Ft=["ArrowRight","ArrowDown"],Ut=["ArrowLeft","ArrowUp"],Wt=(e,n,o)=>{var i=b.innerParams.get(e);if(i)if(i.stopKeydownPropagation&&n.stopPropagation(),"Enter"===n.key)e=e,a=n,t=i,w(t.allowEnterKey)&&!a.isComposing&&a.target&&e.getInput()&&a.target.outerHTML===e.getInput().outerHTML&&(["textarea","file"].includes(t.input)||(Nt(),a.preventDefault()));else if("Tab"!==n.key){if([...Ft,...Ut].includes(n.key)){e=n.key;const s=V(),c=N(),d=F();if([s,c,d].includes(document.activeElement)){var t=Ft.includes(e)?"nextElementSibling":"previousElementSibling";const l=document.activeElement[t];l instanceof HTMLElement&&l.focus()}}else if("Escape"===n.key){var a=n,e=i;if(w(e.allowEscapeKey)){a.preventDefault();o(Ge.esc)}}}else{e=n;o=i;var u=e.target,r=K();let t=-1;for(let e=0;e<r.length;e++)if(u===r[e]){t=e;break}e.shiftKey?Rt(o,t,-1):Rt(o,t,1);e.stopPropagation(),e.preventDefault()}},zt=e=>"object"==typeof e&&e.jquery,_t=e=>e instanceof Element||zt(e);const Kt=()=>{if(f.timeout){{const n=z();var e=parseInt(window.getComputedStyle(n).width),t=(n.style.removeProperty("transition"),n.style.width="100%",parseInt(window.getComputedStyle(n).width)),e=e/t*100;n.style.removeProperty("transition"),n.style.width="".concat(e,"%")}return f.timeout.stop()}},Yt=()=>{var e;if(f.timeout)return e=f.timeout.start(),J(e),e};let Zt=!1;const Jt={};const Xt=t=>{for(let e=t.target;e&&e!==document;e=e.parentNode)for(const o in Jt){var n=e.getAttribute(o);if(n)return void Jt[o].fire({template:n})}};e=Object.freeze({isValidParameter:B,isUpdatableParameter:x,isDeprecatedParameter:E,argsToParams:n=>{const o={};return"object"!=typeof n[0]||_t(n[0])?["title","html","icon"].forEach((e,t)=>{t=n[t];"string"==typeof t||_t(t)?o[e]=t:void 0!==t&&v("Unexpected type of ".concat(e,'! Expected "string" or "Element", got ').concat(typeof t))}):Object.assign(o,n[0]),o},isVisible:()=>ce(g()),clickConfirm:Nt,clickDeny:()=>N()&&N().click(),clickCancel:()=>F()&&F().click(),getContainer:m,getPopup:g,getTitle:M,getHtmlContainer:D,getImage:I,getIcon:j,getInputLabel:()=>O(p["input-label"]),getCloseButton:_,getActions:U,getConfirmButton:V,getDenyButton:N,getCancelButton:F,getLoader:R,getFooter:W,getTimerProgressBar:z,getFocusableElements:K,getValidationMessage:q,isLoading:()=>g().hasAttribute("data-loading"),fire:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new this(...t)},mixin:function(n){class e extends this{_main(e,t){return super._main(e,Object.assign({},n,t))}}return e},showLoading:At,enableLoading:At,getTimerLeft:()=>f.timeout&&f.timeout.getTimerLeft(),stopTimer:Kt,resumeTimer:Yt,toggleTimer:()=>{var e=f.timeout;return e&&(e.running?Kt:Yt)()},increaseTimer:e=>{if(f.timeout)return e=f.timeout.increase(e),J(e,!0),e},isTimerRunning:()=>f.timeout&&f.timeout.isRunning(),bindClickHandler:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"data-swal-template";Jt[e]=this,Zt||(document.body.addEventListener("click",Xt),Zt=!0)}});function $t(){var e,t=b.innerParams.get(this);if(t){const n=b.domCache.get(this);h(n.loader),Z()?t.icon&&d(j()):(t=n,(e=t.popup.getElementsByClassName(t.loader.getAttribute("data-button-to-replace"))).length?d(e[0],"inline-block"):le()&&h(t.actions)),oe([n.popup,n.actions],p.loading),n.popup.removeAttribute("aria-busy"),n.popup.removeAttribute("data-loading"),n.confirmButton.disabled=!1,n.denyButton.disabled=!1,n.cancelButton.disabled=!1}}var Gt={swalPromiseResolve:new WeakMap,swalPromiseReject:new WeakMap};function Qt(e,t,n,o){Z()?on(e,o):(he(n).then(()=>on(e,o)),f.keydownTarget.removeEventListener("keydown",f.keydownHandler,{capture:f.keydownListenerCapture}),f.keydownHandlerAdded=!1),/^((?!chrome|android).)*safari/i.test(navigator.userAgent)?(t.setAttribute("style","display:none !important"),t.removeAttribute("class"),t.innerHTML=""):t.remove(),Y()&&(gt(),bt(),et()),oe([document.documentElement,document.body],[p.shown,p["height-auto"],p["no-backdrop"],p["toast-shown"]])}function en(e){e=void 0!==(n=e)?Object.assign({isConfirmed:!1,isDenied:!1,isDismissed:!1},n):{isConfirmed:!1,isDenied:!1,isDismissed:!0};const t=Gt.swalPromiseResolve.get(this);var n=(e=>{const t=g();if(!t)return false;const n=b.innerParams.get(e);if(!n||$(t,n.hideClass.popup))return false;oe(t,n.showClass.popup),u(t,n.hideClass.popup);const o=m();return oe(o,n.showClass.backdrop),u(o,n.hideClass.backdrop),nn(e,t,n),true})(this);this.isAwaitingPromise()?e.isDismissed||(tn(this),t(e)):n&&t(e)}const tn=e=>{e.isAwaitingPromise()&&(b.awaitingPromise.delete(e),b.innerParams.get(e)||e._destroy())},nn=(e,t,n)=>{var o,i,a,r=m(),s=Be&&de(t);"function"==typeof n.willClose&&n.willClose(t),s?(s=e,o=t,t=r,i=n.returnFocus,a=n.didClose,f.swalCloseEventFinishedCallback=Qt.bind(null,s,t,i,a),o.addEventListener(Be,function(e){e.target===o&&(f.swalCloseEventFinishedCallback(),delete f.swalCloseEventFinishedCallback)})):Qt(e,r,n.returnFocus,n.didClose)},on=(e,t)=>{setTimeout(()=>{"function"==typeof t&&t.bind(e.params)(),e._destroy()})};function an(e,t,n){const o=b.domCache.get(e);t.forEach(e=>{o[e].disabled=n})}function rn(e,t){if(!e)return!1;if("radio"===e.type){const n=e.parentNode.parentNode,o=n.querySelectorAll("input");for(let e=0;e<o.length;e++)o[e].disabled=t}else e.disabled=t}const sn=e=>{e.isAwaitingPromise()?(cn(b,e),b.awaitingPromise.set(e,!0)):(cn(Gt,e),cn(b,e))},cn=(e,t)=>{for(const n in e)e[n].delete(t)};var ln=Object.freeze({hideLoading:$t,disableLoading:$t,getInput:function(e){var t=b.innerParams.get(e||this);return(e=b.domCache.get(e||this))?ee(e.popup,t.input):null},close:en,isAwaitingPromise:function(){return!!b.awaitingPromise.get(this)},rejectPromise:function(e){const t=Gt.swalPromiseReject.get(this);tn(this),t&&t(e)},closePopup:en,closeModal:en,closeToast:en,enableButtons:function(){an(this,["confirmButton","denyButton","cancelButton"],!1)},disableButtons:function(){an(this,["confirmButton","denyButton","cancelButton"],!0)},enableInput:function(){return rn(this.getInput(),!1)},disableInput:function(){return rn(this.getInput(),!0)},showValidationMessage:function(e){const t=b.domCache.get(this);var n=b.innerParams.get(this);l(t.validationMessage,e),t.validationMessage.className=p["validation-message"],n.customClass&&n.customClass.validationMessage&&u(t.validationMessage,n.customClass.validationMessage),d(t.validationMessage);const o=this.getInput();o&&(o.setAttribute("aria-invalid",!0),o.setAttribute("aria-describedby",p["validation-message"]),te(o),u(o,p.inputerror))},resetValidationMessage:function(){var e=b.domCache.get(this);e.validationMessage&&h(e.validationMessage);const t=this.getInput();t&&(t.removeAttribute("aria-invalid"),t.removeAttribute("aria-describedby"),oe(t,p.inputerror))},getProgressSteps:function(){return b.domCache.get(this).progressSteps},update:function(e){var t=g(),n=b.innerParams.get(this);if(!t||$(t,n.hideClass.popup))return a("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");t=(t=>{const n={};return Object.keys(t).forEach(e=>{if(x(e))n[e]=t[e];else a('Invalid parameter to update: "'.concat(e,'". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md'))}),n})(e),n=Object.assign({},n,t),$e(this,n),b.innerParams.set(this,n),Object.defineProperties(this,{params:{value:Object.assign({},this.params,e),writable:!1,enumerable:!0}})},_destroy:function(){var e=b.domCache.get(this);const t=b.innerParams.get(this);t?(e.popup&&f.swalCloseEventFinishedCallback&&(f.swalCloseEventFinishedCallback(),delete f.swalCloseEventFinishedCallback),f.deferDisposalTimer&&(clearTimeout(f.deferDisposalTimer),delete f.deferDisposalTimer),"function"==typeof t.didDestroy&&t.didDestroy(),e=this,sn(e),delete e.params,delete f.keydownHandler,delete f.keydownTarget,delete f.currentInstance):sn(this)}});let un;class dn{constructor(){if("undefined"!=typeof window){un=this;for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var o=Object.freeze(this.constructor.argsToParams(t)),o=(Object.defineProperties(this,{params:{value:o,writable:!1,enumerable:!0,configurable:!0}}),this._main(this.params));b.promise.set(this,o)}}_main(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},e=(T(Object.assign({},t,e)),f.currentInstance&&(f.currentInstance._destroy(),Y()&&et()),f.currentInstance=this,mn(e,t)),t=(dt(e),Object.freeze(e),f.timeout&&(f.timeout.stop(),delete f.timeout),clearTimeout(f.restoreFocusTimeout),gn(this));return $e(this,e),b.innerParams.set(this,e),pn(this,t,e)}then(e){const t=b.promise.get(this);return t.then(e)}finally(e){const t=b.promise.get(this);return t.finally(e)}}const pn=(l,u,d)=>new Promise((e,t)=>{const n=e=>{l.closePopup({isDismissed:!0,dismiss:e})};var o,i,a;Gt.swalPromiseResolve.set(l,e),Gt.swalPromiseReject.set(l,t),u.confirmButton.onclick=()=>{var e=l,t=b.innerParams.get(e);e.disableButtons(),t.input?St(e,"confirm"):Mt(e,!0)},u.denyButton.onclick=()=>{var e=l,t=b.innerParams.get(e);e.disableButtons(),t.returnInputValueOnDeny?St(e,"deny"):Lt(e,!1)},u.cancelButton.onclick=()=>{var e=l,t=n;e.disableButtons(),t(Ge.cancel)},u.closeButton.onclick=()=>n(Ge.close),e=l,t=u,a=n,b.innerParams.get(e).toast?Dt(e,t,a):(Ht(t),qt(t),Vt(e,t,a)),o=l,e=f,t=d,i=n,e.keydownTarget&&e.keydownHandlerAdded&&(e.keydownTarget.removeEventListener("keydown",e.keydownHandler,{capture:e.keydownListenerCapture}),e.keydownHandlerAdded=!1),t.toast||(e.keydownHandler=e=>Wt(o,e,i),e.keydownTarget=t.keydownListenerCapture?window:g(),e.keydownListenerCapture=t.keydownListenerCapture,e.keydownTarget.addEventListener("keydown",e.keydownHandler,{capture:e.keydownListenerCapture}),e.keydownHandlerAdded=!0),a=l,"select"===(t=d).input||"radio"===t.input?Pt(a,t):["text","email","number","tel","textarea"].includes(t.input)&&(C(t.inputValue)||A(t.inputValue))&&(At(V()),Bt(a,t));{var r=d;const s=m(),c=g();"function"==typeof r.willOpen&&r.willOpen(c),e=window.getComputedStyle(document.body).overflowY,kt(s,c,r),setTimeout(()=>{wt(s,c)},yt),Y()&&(Ct(s,r.scrollbarPadding,e),Qe()),Z()||f.previousActiveElement||(f.previousActiveElement=document.activeElement),"function"==typeof r.didOpen&&setTimeout(()=>r.didOpen(c)),oe(s,p["no-transition"])}hn(f,d,n),fn(u,d),setTimeout(()=>{u.container.scrollTop=0})}),mn=(e,t)=>{var n=(e=>{e="string"==typeof e.template?document.querySelector(e.template):e.template;if(!e)return{};e=e.content,ct(e),e=Object.assign(nt(e),ot(e),it(e),at(e),rt(e),st(e,tt));return e})(e);const o=Object.assign({},r,t,n,e);return o.showClass=Object.assign({},r.showClass,o.showClass),o.hideClass=Object.assign({},r.hideClass,o.hideClass),o},gn=e=>{var t={popup:g(),container:m(),actions:U(),confirmButton:V(),denyButton:N(),cancelButton:F(),loader:R(),closeButton:_(),validationMessage:q(),progressSteps:H()};return b.domCache.set(e,t),t},hn=(e,t,n)=>{var o=z();h(o),t.timer&&(e.timeout=new pt(()=>{n("timer"),delete e.timeout},t.timer),t.timerProgressBar&&(d(o),Q(o,t,"timerProgressBar"),setTimeout(()=>{e.timeout&&e.timeout.running&&J(t.timer)})))},fn=(e,t)=>{if(!t.toast)return w(t.allowEnterKey)?void(bn(e,t)||Rt(t,-1,1)):yn()},bn=(e,t)=>t.focusDeny&&ce(e.denyButton)?(e.denyButton.focus(),!0):t.focusCancel&&ce(e.cancelButton)?(e.cancelButton.focus(),!0):!(!t.focusConfirm||!ce(e.confirmButton))&&(e.confirmButton.focus(),!0),yn=()=>{document.activeElement instanceof HTMLElement&&"function"==typeof document.activeElement.blur&&document.activeElement.blur()},vn=(Object.assign(dn.prototype,ln),Object.assign(dn,e),Object.keys(ln).forEach(e=>{dn[e]=function(){if(un)return un[e](...arguments)}}),dn.DismissReason=Ge,dn.version="11.4.0",dn);return vn.default=vn,vn}),void 0!==this&&this.Sweetalert2&&(this.swal=this.sweetAlert=this.Swal=this.SweetAlert=this.Sweetalert2);
"undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,".swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4!important;grid-row:1/4!important;grid-template-columns:1fr 99fr 1fr;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 1px rgba(0,0,0,.075),0 1px 2px rgba(0,0,0,.075),1px 2px 4px rgba(0,0,0,.075),1px 3px 8px rgba(0,0,0,.075),2px 4px 16px rgba(0,0,0,.075);pointer-events:all}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:700}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-container{display:grid;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;box-sizing:border-box;grid-template-areas:\"top-start top top-end\" \"center-start center center-end\" \"bottom-start bottom-center bottom-end\";grid-template-rows:minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto);grid-template-rows:minmax(min-content,auto) minmax(min-content,auto) minmax(min-content,auto);height:100%;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:0 0!important}.swal2-container.swal2-bottom-start,.swal2-container.swal2-center-start,.swal2-container.swal2-top-start{grid-template-columns:minmax(0,1fr) auto auto}.swal2-container.swal2-bottom,.swal2-container.swal2-center,.swal2-container.swal2-top{grid-template-columns:auto minmax(0,1fr) auto}.swal2-container.swal2-bottom-end,.swal2-container.swal2-center-end,.swal2-container.swal2-top-end{grid-template-columns:auto auto minmax(0,1fr)}.swal2-container.swal2-top-start>.swal2-popup{align-self:start}.swal2-container.swal2-top>.swal2-popup{grid-column:2;align-self:start;justify-self:center}.swal2-container.swal2-top-end>.swal2-popup,.swal2-container.swal2-top-right>.swal2-popup{grid-column:3;align-self:start;justify-self:end}.swal2-container.swal2-center-left>.swal2-popup,.swal2-container.swal2-center-start>.swal2-popup{grid-row:2;align-self:center}.swal2-container.swal2-center>.swal2-popup{grid-column:2;grid-row:2;align-self:center;justify-self:center}.swal2-container.swal2-center-end>.swal2-popup,.swal2-container.swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;align-self:center;justify-self:end}.swal2-container.swal2-bottom-left>.swal2-popup,.swal2-container.swal2-bottom-start>.swal2-popup{grid-column:1;grid-row:3;align-self:end}.swal2-container.swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;justify-self:center;align-self:end}.swal2-container.swal2-bottom-end>.swal2-popup,.swal2-container.swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;align-self:end;justify-self:end}.swal2-container.swal2-grow-fullscreen>.swal2-popup,.swal2-container.swal2-grow-row>.swal2-popup{grid-column:1/4;width:100%}.swal2-container.swal2-grow-column>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}.swal2-container.swal2-no-transition{transition:none!important}.swal2-popup{display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0,100%);width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;color:#545454;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-title{position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:auto;margin:1.25em auto 0;padding:0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 transparent #2778c4 transparent}.swal2-styled{margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px transparent;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#7066e0;color:#fff;font-size:1em}.swal2-styled.swal2-confirm:focus{box-shadow:0 0 0 3px rgba(112,102,224,.5)}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#dc3741;color:#fff;font-size:1em}.swal2-styled.swal2-deny:focus{box-shadow:0 0 0 3px rgba(220,55,65,.5)}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#6e7881;color:#fff;font-size:1em}.swal2-styled.swal2-cancel:focus{box-shadow:0 0 0 3px rgba(110,120,129,.5)}.swal2-styled.swal2-default-outline:focus{box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled:focus{outline:0}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:inherit;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto!important;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:2em auto 1em}.swal2-close{z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:0 0;color:#ccc;font-family:serif;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}.swal2-close:hover{transform:none;background:0 0;color:#f27474}.swal2-close:focus{outline:0;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-html-container{z-index:1;justify-content:center;margin:1em 1.6em .3em;padding:0;overflow:auto;color:inherit;font-size:1.125em;font-weight:400;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em 2em 3px}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid #d9d9d9;border-radius:.1875em;background:inherit;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px transparent;color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em 2em 3px;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-file{width:75%;margin-right:auto;margin-left:auto;background:inherit;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:inherit;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{flex-shrink:0;margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto 0}.swal2-validation-message{align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:.25em solid transparent;border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-warning.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-warning.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .5s;animation:swal2-animate-i-mark .5s}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-info.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-info.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .8s;animation:swal2-animate-i-mark .8s}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-question.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-question.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-question-mark .8s;animation:swal2-animate-question-mark .8s}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:inherit;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@-webkit-keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@-webkit-keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@-webkit-keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@-webkit-keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@-webkit-keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-container{background-color:transparent!important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:transparent;pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}");
|
294coder/Efficient-MIF
| 6,322 |
utils/FS_index/my_D_s.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
#
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
Spatial distortion index.
Interface:
D_s_index = D_s(I_F,I_MS,I_MS_LR,I_PAN,ratio,S,q)
Inputs:
I_F: Pansharpened image;
I_MS: MS image resampled to panchromatic scale;
I_MS_LR: Original MS image;
I_PAN: Panchromatic image;
ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
S: Block size;
q: Exponent value (optional); Default value: q = 1.
Outputs:
D_s_index: Spatial distortion index.
Notes:
Results very close to the MATLAB toolbox's ones. In particular, the results are more accurate than the MATLAB toolbox's ones
because the Q-index is applied in a sliding window way. Instead, for computational reasons, the MATLAB toolbox uses a distinct block implementation
of the Q-index.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
import numpy as np
from skimage.metrics import structural_similarity as ssim
from .interp23 import interp23
from .imresize import imresize
import torch
from torch.nn import functional as F
import math
#
# def gaussian(window_size, sigma):
# gauss = torch.Tensor([math.exp(-(x - window_size // 2) ** 2 / float(2 * sigma ** 2)) for x in range(window_size)])
# return gauss / gauss.sum()
def create_window(window_size, channel):
# _1D_window = gaussian(window_size, sigma).unsqueeze(1)
# _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0)
_2D_window = torch.ones(window_size, window_size)#.uniform_(0, 1)
window = _2D_window.expand(channel, 1, window_size, window_size).contiguous()
return window
def D_s(I_F, I_MS, I_MS_LR, I_PAN, ratio, S, q):
""" if 0, Toolbox 1.0, otherwise, original QNR paper """
flag_orig_paper = 0
if (I_F.shape != I_MS.shape):
print("The two images must have the same dimensions")
return -1
N = I_F.shape[0]
M = I_F.shape[1]
Nb = I_F.shape[2]
max_val = 1
if not isinstance(I_PAN, torch.Tensor):
I_F = torch.from_numpy(I_F/max_val).permute(2, 0, 1).float()*max_val
I_MS = torch.from_numpy(I_MS / max_val).permute(2, 0, 1).float() * max_val
I_MS_LR = torch.from_numpy(I_MS_LR / max_val).permute(2, 0, 1).float() * max_val
I_PAN = torch.from_numpy(I_PAN / max_val)[..., 0].float()
if (flag_orig_paper == 0):
"""Opt. 1 (as toolbox 1.0)"""
pan_filt = interp23(imresize(I_PAN, 1 / ratio), ratio)
else:
""" Opt. 2 (as paper QNR) """
pan_filt = imresize(I_PAN, 1 / ratio)
pan_filt = torch.from_numpy(pan_filt / max_val).unsqueeze(0).float()
I_PAN = I_PAN.unsqueeze(0)
Q_high, Q_high_map = uqi_ssim(I_F, I_PAN, Nb, win_size=S)
if (flag_orig_paper == 0):
""" Opt. 1 (as toolbox 1.0) """
Q_low, Q_low_map = uqi_ssim(I_MS, pan_filt, Nb, win_size=S)
else:
""" Opt. 2 (as paper QNR) """
Q_low, Q_low_map = uqi_ssim(I_MS_LR, pan_filt, Nb, win_size=S)
D_s_index = np.abs(Q_high - Q_low) ** q
D_s_map = np.abs(Q_high_map - Q_low_map) ** q
D_s_index = D_s_index.sum()
D_s_index = (D_s_index / Nb) ** (1 / q)
D_s_map = (D_s_map / Nb) ** (1 / q)
return D_s_index.item(), D_s_map.numpy().transpose([1, 2, 0])
def uqi_ssim(x, y, Nb, win_size):
# cov_norm = win_size**2 / (win_size**2 - 1)
window_ms = create_window(win_size, Nb) / (win_size**2)
window_pan = create_window(win_size, 1) / (win_size**2)
mu1 = F.conv2d(x, window_ms, groups=Nb, stride=win_size)
mu2 = F.conv2d(y, window_pan, stride=win_size)
mu1_sq = mu1.pow(2)
mu2_sq = mu2.pow(2)
mu1_mu2 = mu1 * mu2 # 点乘产生误差
sigma1_sq = F.conv2d(x * x, window_ms, groups=Nb, stride=win_size) - mu1_sq # 点乘产生误差
sigma2_sq = F.conv2d(y * y, window_pan, stride=win_size) - mu2_sq
sigma12 = F.conv2d(x * y, window_ms, groups=Nb, stride=win_size) - mu1_mu2 # 点乘产生误差
V1 = 2.0 * sigma12 # * cov_norm
V2 = sigma1_sq + sigma2_sq
Q = (2 * V1 * mu1_mu2) / (V2 * (mu1_sq + mu2_sq))
return Q.mean(1).mean(1), Q
def cov(x, y):
cov_xy = torch.matmul(x.transpose(-2, -1), y) / x.shape[-2]
cov_yx = torch.matmul(y.transpose(-2, -1), x) / y.shape[-2]
std_x = x.var(-2, keepdims=True)
std_y = y.var(-2, keepdims=True)
# print(cov_xy.shape, cov_yx.shape, std_x.shape, std_y.shape)
return torch.cat([std_x, cov_xy, cov_yx, std_y], dim=-2)
def uqi(x, y, Nb, win_size):
C, H, W = x.shape
x = F.unfold(x, kernel_size=win_size, stride=win_size)
x = x.permute(1, 0).reshape(-1, C, win_size**2, 1)
y = F.unfold(y, kernel_size=win_size, stride=win_size)
y = y.permute(1, 0).reshape(-1, win_size**2, 1)
num_patches = y.shape[0]
# print(x.shape, y.shape, mx.shape, my.shape)
Q = torch.zeros([num_patches, C])
for ii in range(Nb):
xx = x[:, ii, ...]#.unsqueeze(1)
mx = xx.mean(-2, keepdims=True)
my = y.mean(-2, keepdims=True)
# print(xx.shape, y.shape, mx.shape, my.shape)
C = cov(xx-mx, y-my)
# print(C.shape)
C = C.reshape(num_patches, 2, 2)
Q[:, ii, ...] = (4 * C[:, 0, 1] * mx[:, 0, 0]*my[:, 0, 0]) / ((C[:, 0, 0] + C[:, 1, 1]) * (mx[:, 0, 0]**2 + my[:, 0, 0]**2))
return Q.mean(0)
|
281677160/openwrt-package
| 1,933 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_amf.h
|
/*
* Copyright (C) Roman Arutyunyan
*/
#ifndef _NGX_RTMP_AMF_H_INCLUDED_
#define _NGX_RTMP_AMF_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
/* basic types */
#define NGX_RTMP_AMF_NUMBER 0x00
#define NGX_RTMP_AMF_BOOLEAN 0x01
#define NGX_RTMP_AMF_STRING 0x02
#define NGX_RTMP_AMF_OBJECT 0x03
#define NGX_RTMP_AMF_NULL 0x05
#define NGX_RTMP_AMF_ARRAY_NULL 0x06
#define NGX_RTMP_AMF_MIXED_ARRAY 0x08
#define NGX_RTMP_AMF_END 0x09
#define NGX_RTMP_AMF_ARRAY 0x0a
/* extended types */
#define NGX_RTMP_AMF_INT8 0x0100
#define NGX_RTMP_AMF_INT16 0x0101
#define NGX_RTMP_AMF_INT32 0x0102
#define NGX_RTMP_AMF_VARIANT_ 0x0103
/* r/w flags */
#define NGX_RTMP_AMF_OPTIONAL 0x1000
#define NGX_RTMP_AMF_TYPELESS 0x2000
#define NGX_RTMP_AMF_CONTEXT 0x4000
#define NGX_RTMP_AMF_VARIANT (NGX_RTMP_AMF_VARIANT_\
|NGX_RTMP_AMF_TYPELESS)
typedef struct {
ngx_int_t type;
ngx_str_t name;
void *data;
size_t len;
} ngx_rtmp_amf_elt_t;
typedef ngx_chain_t * (*ngx_rtmp_amf_alloc_pt)(void *arg);
typedef struct {
ngx_chain_t *link, *first;
size_t offset;
ngx_rtmp_amf_alloc_pt alloc;
void *arg;
ngx_log_t *log;
} ngx_rtmp_amf_ctx_t;
/* reading AMF */
ngx_int_t ngx_rtmp_amf_read(ngx_rtmp_amf_ctx_t *ctx,
ngx_rtmp_amf_elt_t *elts, size_t nelts);
/* writing AMF */
ngx_int_t ngx_rtmp_amf_write(ngx_rtmp_amf_ctx_t *ctx,
ngx_rtmp_amf_elt_t *elts, size_t nelts);
#endif /* _NGX_RTMP_AMF_H_INCLUDED_ */
|
281677160/openwrt-package
| 4,434 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_sys_stat_module.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include <ngx_http.h>
#include "ngx_rtmp.h"
#include "ngx_rbuf.h"
#include "ngx_poold.h"
#include "ngx_stream_zone_module.h"
#include "ngx_event_timer_module.h"
#include "ngx_event_resolver.h"
#include "ngx_dynamic_resolver.h"
#include "ngx_live.h"
static char *ngx_rtmp_sys_stat(ngx_conf_t *cf, ngx_command_t *cmd, void *conf);
extern ngx_chain_t *ngx_live_relay_static_state(ngx_http_request_t *r);
static ngx_command_t ngx_rtmp_sys_stat_commands[] = {
{ ngx_string("sys_stat"),
NGX_HTTP_LOC_CONF|NGX_CONF_NOARGS,
ngx_rtmp_sys_stat,
NGX_HTTP_LOC_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_http_module_t ngx_rtmp_sys_stat_module_ctx = {
NULL, /* preconfiguration */
NULL, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
NULL, /* create location configuration */
NULL /* merge location configuration */
};
ngx_module_t ngx_rtmp_sys_stat_module = {
NGX_MODULE_V1,
&ngx_rtmp_sys_stat_module_ctx, /* module context */
ngx_rtmp_sys_stat_commands, /* module directives */
NGX_HTTP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_int_t
ngx_rtmp_sys_stat_handler(ngx_http_request_t *r)
{
ngx_chain_t **ll, *out;
ngx_buf_t *b;
ngx_str_t detail_arg;
ngx_uint_t detail = 0;
size_t len;
if (ngx_http_arg(r, (u_char *) "detail", sizeof("detail") - 1, &detail_arg)
== NGX_OK)
{
detail = 1;
}
r->headers_out.status = NGX_HTTP_OK;
ngx_http_send_header(r);
ll = &out;
len = sizeof("--------------------------------------------------\n") - 1
+ sizeof("ngx_worker: ngx_process_slot: pid: \n") - 1
+ 3 * NGX_OFF_T_LEN;
*ll = ngx_alloc_chain_link(r->pool);
if (*ll == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
(*ll)->next = NULL;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
(*ll)->buf = b;
b->last = ngx_snprintf(b->last, len,
"--------------------------------------------------\n"
"ngx_worker: %i ngx_process_slot: %i pid: %i\n",
ngx_worker, ngx_process_slot, ngx_pid);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_live_state(r);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_live_relay_static_state(r);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_rtmp_shared_state(r);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_rbuf_state(r, detail);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_stream_zone_state(r, 0);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_event_timer_state(r);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_event_resolver_state(r);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_dynamic_resolver_state(r);
if (*ll) {
ll = &(*ll)->next;
}
*ll = ngx_poold_state(r, detail);
(*ll)->buf->last_buf = 1;
return ngx_http_output_filter(r, out);
}
static char *
ngx_rtmp_sys_stat(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_http_core_loc_conf_t *clcf;
clcf = ngx_http_conf_get_module_loc_conf(cf, ngx_http_core_module);
clcf->handler = ngx_rtmp_sys_stat_handler;
return NGX_CONF_OK;
}
|
2881099/FreeSql.AdminLTE
| 132,620 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.all.js
|
/*!
* sweetalert2 v11.4.0
* Released under the MIT License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.Sweetalert2 = factory());
}(this, function () { 'use strict';
const consolePrefix = 'SweetAlert2:';
/**
* Filter the unique values into a new array
* @param arr
*/
const uniqueArray = arr => {
const result = [];
for (let i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
};
/**
* Capitalize the first letter of a string
* @param {string} str
* @returns {string}
*/
const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
/**
* @param {NodeList | HTMLCollection | NamedNodeMap} nodeList
* @returns {array}
*/
const toArray = nodeList => Array.prototype.slice.call(nodeList);
/**
* Standardize console warnings
* @param {string | array} message
*/
const warn = message => {
console.warn("".concat(consolePrefix, " ").concat(typeof message === 'object' ? message.join(' ') : message));
};
/**
* Standardize console errors
* @param {string} message
*/
const error = message => {
console.error("".concat(consolePrefix, " ").concat(message));
};
/**
* Private global state for `warnOnce`
* @type {Array}
* @private
*/
const previousWarnOnceMessages = [];
/**
* Show a console warning, but only if it hasn't already been shown
* @param {string} message
*/
const warnOnce = message => {
if (!previousWarnOnceMessages.includes(message)) {
previousWarnOnceMessages.push(message);
warn(message);
}
};
/**
* Show a one-time console warning about deprecated params/methods
*/
const warnAboutDeprecation = (deprecatedParam, useInstead) => {
warnOnce("\"".concat(deprecatedParam, "\" is deprecated and will be removed in the next major release. Please use \"").concat(useInstead, "\" instead."));
};
/**
* If `arg` is a function, call it (with no arguments or context) and return the result.
* Otherwise, just pass the value through
* @param arg
*/
const callIfFunction = arg => typeof arg === 'function' ? arg() : arg;
const hasToPromiseFn = arg => arg && typeof arg.toPromise === 'function';
const asPromise = arg => hasToPromiseFn(arg) ? arg.toPromise() : Promise.resolve(arg);
const isPromise = arg => arg && Promise.resolve(arg) === arg;
const defaultParams = {
title: '',
titleText: '',
text: '',
html: '',
footer: '',
icon: undefined,
iconColor: undefined,
iconHtml: undefined,
template: undefined,
toast: false,
showClass: {
popup: 'swal2-show',
backdrop: 'swal2-backdrop-show',
icon: 'swal2-icon-show'
},
hideClass: {
popup: 'swal2-hide',
backdrop: 'swal2-backdrop-hide',
icon: 'swal2-icon-hide'
},
customClass: {},
target: 'body',
color: undefined,
backdrop: true,
heightAuto: true,
allowOutsideClick: true,
allowEscapeKey: true,
allowEnterKey: true,
stopKeydownPropagation: true,
keydownListenerCapture: false,
showConfirmButton: true,
showDenyButton: false,
showCancelButton: false,
preConfirm: undefined,
preDeny: undefined,
confirmButtonText: 'OK',
confirmButtonAriaLabel: '',
confirmButtonColor: undefined,
denyButtonText: 'No',
denyButtonAriaLabel: '',
denyButtonColor: undefined,
cancelButtonText: 'Cancel',
cancelButtonAriaLabel: '',
cancelButtonColor: undefined,
buttonsStyling: true,
reverseButtons: false,
focusConfirm: true,
focusDeny: false,
focusCancel: false,
returnFocus: true,
showCloseButton: false,
closeButtonHtml: '×',
closeButtonAriaLabel: 'Close this dialog',
loaderHtml: '',
showLoaderOnConfirm: false,
showLoaderOnDeny: false,
imageUrl: undefined,
imageWidth: undefined,
imageHeight: undefined,
imageAlt: '',
timer: undefined,
timerProgressBar: false,
width: undefined,
padding: undefined,
background: undefined,
input: undefined,
inputPlaceholder: '',
inputLabel: '',
inputValue: '',
inputOptions: {},
inputAutoTrim: true,
inputAttributes: {},
inputValidator: undefined,
returnInputValueOnDeny: false,
validationMessage: undefined,
grow: false,
position: 'center',
progressSteps: [],
currentProgressStep: undefined,
progressStepsDistance: undefined,
willOpen: undefined,
didOpen: undefined,
didRender: undefined,
willClose: undefined,
didClose: undefined,
didDestroy: undefined,
scrollbarPadding: true
};
const updatableParams = ['allowEscapeKey', 'allowOutsideClick', 'background', 'buttonsStyling', 'cancelButtonAriaLabel', 'cancelButtonColor', 'cancelButtonText', 'closeButtonAriaLabel', 'closeButtonHtml', 'color', 'confirmButtonAriaLabel', 'confirmButtonColor', 'confirmButtonText', 'currentProgressStep', 'customClass', 'denyButtonAriaLabel', 'denyButtonColor', 'denyButtonText', 'didClose', 'didDestroy', 'footer', 'hideClass', 'html', 'icon', 'iconColor', 'iconHtml', 'imageAlt', 'imageHeight', 'imageUrl', 'imageWidth', 'preConfirm', 'preDeny', 'progressSteps', 'returnFocus', 'reverseButtons', 'showCancelButton', 'showCloseButton', 'showConfirmButton', 'showDenyButton', 'text', 'title', 'titleText', 'willClose'];
const deprecatedParams = {};
const toastIncompatibleParams = ['allowOutsideClick', 'allowEnterKey', 'backdrop', 'focusConfirm', 'focusDeny', 'focusCancel', 'returnFocus', 'heightAuto', 'keydownListenerCapture'];
/**
* Is valid parameter
* @param {string} paramName
*/
const isValidParameter = paramName => {
return Object.prototype.hasOwnProperty.call(defaultParams, paramName);
};
/**
* Is valid parameter for Swal.update() method
* @param {string} paramName
*/
const isUpdatableParameter = paramName => {
return updatableParams.indexOf(paramName) !== -1;
};
/**
* Is deprecated parameter
* @param {string} paramName
*/
const isDeprecatedParameter = paramName => {
return deprecatedParams[paramName];
};
const checkIfParamIsValid = param => {
if (!isValidParameter(param)) {
warn("Unknown parameter \"".concat(param, "\""));
}
};
const checkIfToastParamIsValid = param => {
if (toastIncompatibleParams.includes(param)) {
warn("The parameter \"".concat(param, "\" is incompatible with toasts"));
}
};
const checkIfParamIsDeprecated = param => {
if (isDeprecatedParameter(param)) {
warnAboutDeprecation(param, isDeprecatedParameter(param));
}
};
/**
* Show relevant warnings for given params
*
* @param params
*/
const showWarningsForParams = params => {
if (!params.backdrop && params.allowOutsideClick) {
warn('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');
}
for (const param in params) {
checkIfParamIsValid(param);
if (params.toast) {
checkIfToastParamIsValid(param);
}
checkIfParamIsDeprecated(param);
}
};
const swalPrefix = 'swal2-';
const prefix = items => {
const result = {};
for (const i in items) {
result[items[i]] = swalPrefix + items[i];
}
return result;
};
const swalClasses = prefix(['container', 'shown', 'height-auto', 'iosfix', 'popup', 'modal', 'no-backdrop', 'no-transition', 'toast', 'toast-shown', 'show', 'hide', 'close', 'title', 'html-container', 'actions', 'confirm', 'deny', 'cancel', 'default-outline', 'footer', 'icon', 'icon-content', 'image', 'input', 'file', 'range', 'select', 'radio', 'checkbox', 'label', 'textarea', 'inputerror', 'input-label', 'validation-message', 'progress-steps', 'active-progress-step', 'progress-step', 'progress-step-line', 'loader', 'loading', 'styled', 'top', 'top-start', 'top-end', 'top-left', 'top-right', 'center', 'center-start', 'center-end', 'center-left', 'center-right', 'bottom', 'bottom-start', 'bottom-end', 'bottom-left', 'bottom-right', 'grow-row', 'grow-column', 'grow-fullscreen', 'rtl', 'timer-progress-bar', 'timer-progress-bar-container', 'scrollbar-measure', 'icon-success', 'icon-warning', 'icon-info', 'icon-question', 'icon-error']);
const iconTypes = prefix(['success', 'warning', 'info', 'question', 'error']);
/**
* Gets the popup container which contains the backdrop and the popup itself.
*
* @returns {HTMLElement | null}
*/
const getContainer = () => document.body.querySelector(".".concat(swalClasses.container));
const elementBySelector = selectorString => {
const container = getContainer();
return container ? container.querySelector(selectorString) : null;
};
const elementByClass = className => {
return elementBySelector(".".concat(className));
};
const getPopup = () => elementByClass(swalClasses.popup);
const getIcon = () => elementByClass(swalClasses.icon);
const getTitle = () => elementByClass(swalClasses.title);
const getHtmlContainer = () => elementByClass(swalClasses['html-container']);
const getImage = () => elementByClass(swalClasses.image);
const getProgressSteps = () => elementByClass(swalClasses['progress-steps']);
const getValidationMessage = () => elementByClass(swalClasses['validation-message']);
const getConfirmButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.confirm));
const getDenyButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.deny));
const getInputLabel = () => elementByClass(swalClasses['input-label']);
const getLoader = () => elementBySelector(".".concat(swalClasses.loader));
const getCancelButton = () => elementBySelector(".".concat(swalClasses.actions, " .").concat(swalClasses.cancel));
const getActions = () => elementByClass(swalClasses.actions);
const getFooter = () => elementByClass(swalClasses.footer);
const getTimerProgressBar = () => elementByClass(swalClasses['timer-progress-bar']);
const getCloseButton = () => elementByClass(swalClasses.close); // https://github.com/jkup/focusable/blob/master/index.js
const focusable = "\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex=\"0\"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n";
const getFocusableElements = () => {
const focusableElementsWithTabindex = toArray(getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')) // sort according to tabindex
.sort((a, b) => {
const tabindexA = parseInt(a.getAttribute('tabindex'));
const tabindexB = parseInt(b.getAttribute('tabindex'));
if (tabindexA > tabindexB) {
return 1;
} else if (tabindexA < tabindexB) {
return -1;
}
return 0;
});
const otherFocusableElements = toArray(getPopup().querySelectorAll(focusable)).filter(el => el.getAttribute('tabindex') !== '-1');
return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements)).filter(el => isVisible(el));
};
const isModal = () => {
return !hasClass(document.body, swalClasses['toast-shown']) && !hasClass(document.body, swalClasses['no-backdrop']);
};
const isToast = () => {
return getPopup() && hasClass(getPopup(), swalClasses.toast);
};
const isLoading = () => {
return getPopup().hasAttribute('data-loading');
};
const states = {
previousBodyPadding: null
};
/**
* Securely set innerHTML of an element
* https://github.com/sweetalert2/sweetalert2/issues/1926
*
* @param {HTMLElement} elem
* @param {string} html
*/
const setInnerHtml = (elem, html) => {
elem.textContent = '';
if (html) {
const parser = new DOMParser();
const parsed = parser.parseFromString(html, "text/html");
toArray(parsed.querySelector('head').childNodes).forEach(child => {
elem.appendChild(child);
});
toArray(parsed.querySelector('body').childNodes).forEach(child => {
elem.appendChild(child);
});
}
};
/**
* @param {HTMLElement} elem
* @param {string} className
* @returns {boolean}
*/
const hasClass = (elem, className) => {
if (!className) {
return false;
}
const classList = className.split(/\s+/);
for (let i = 0; i < classList.length; i++) {
if (!elem.classList.contains(classList[i])) {
return false;
}
}
return true;
};
const removeCustomClasses = (elem, params) => {
toArray(elem.classList).forEach(className => {
if (!Object.values(swalClasses).includes(className) && !Object.values(iconTypes).includes(className) && !Object.values(params.showClass).includes(className)) {
elem.classList.remove(className);
}
});
};
const applyCustomClass = (elem, params, className) => {
removeCustomClasses(elem, params);
if (params.customClass && params.customClass[className]) {
if (typeof params.customClass[className] !== 'string' && !params.customClass[className].forEach) {
return warn("Invalid type of customClass.".concat(className, "! Expected string or iterable object, got \"").concat(typeof params.customClass[className], "\""));
}
addClass(elem, params.customClass[className]);
}
};
/**
* @param {HTMLElement} popup
* @param {string} inputType
* @returns {HTMLInputElement | null}
*/
const getInput = (popup, inputType) => {
if (!inputType) {
return null;
}
switch (inputType) {
case 'select':
case 'textarea':
case 'file':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses[inputType]));
case 'checkbox':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.checkbox, " input"));
case 'radio':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:checked")) || popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.radio, " input:first-child"));
case 'range':
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.range, " input"));
default:
return popup.querySelector(".".concat(swalClasses.popup, " > .").concat(swalClasses.input));
}
};
/**
* @param {HTMLInputElement} input
*/
const focusInput = input => {
input.focus(); // place cursor at end of text in text input
if (input.type !== 'file') {
// http://stackoverflow.com/a/2345915
const val = input.value;
input.value = '';
input.value = val;
}
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[]} classList
* @param {boolean} condition
*/
const toggleClass = (target, classList, condition) => {
if (!target || !classList) {
return;
}
if (typeof classList === 'string') {
classList = classList.split(/\s+/).filter(Boolean);
}
classList.forEach(className => {
if (Array.isArray(target)) {
target.forEach(elem => {
condition ? elem.classList.add(className) : elem.classList.remove(className);
});
} else {
condition ? target.classList.add(className) : target.classList.remove(className);
}
});
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[]} classList
*/
const addClass = (target, classList) => {
toggleClass(target, classList, true);
};
/**
* @param {HTMLElement | HTMLElement[] | null} target
* @param {string | string[]} classList
*/
const removeClass = (target, classList) => {
toggleClass(target, classList, false);
};
/**
* Get direct child of an element by class name
*
* @param {HTMLElement} elem
* @param {string} className
* @returns {HTMLElement | null}
*/
const getDirectChildByClass = (elem, className) => {
const childNodes = toArray(elem.childNodes);
for (let i = 0; i < childNodes.length; i++) {
if (hasClass(childNodes[i], className)) {
return childNodes[i];
}
}
};
/**
* @param {HTMLElement} elem
* @param {string} property
* @param {*} value
*/
const applyNumericalStyle = (elem, property, value) => {
if (value === "".concat(parseInt(value))) {
value = parseInt(value);
}
if (value || parseInt(value) === 0) {
elem.style[property] = typeof value === 'number' ? "".concat(value, "px") : value;
} else {
elem.style.removeProperty(property);
}
};
/**
* @param {HTMLElement} elem
* @param {string} display
*/
const show = function (elem) {
let display = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'flex';
elem.style.display = display;
};
/**
* @param {HTMLElement} elem
*/
const hide = elem => {
elem.style.display = 'none';
};
const setStyle = (parent, selector, property, value) => {
const el = parent.querySelector(selector);
if (el) {
el.style[property] = value;
}
};
const toggle = (elem, condition, display) => {
condition ? show(elem, display) : hide(elem);
}; // borrowed from jquery $(elem).is(':visible') implementation
const isVisible = elem => !!(elem && (elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length));
const allButtonsAreHidden = () => !isVisible(getConfirmButton()) && !isVisible(getDenyButton()) && !isVisible(getCancelButton());
const isScrollable = elem => !!(elem.scrollHeight > elem.clientHeight); // borrowed from https://stackoverflow.com/a/46352119
const hasCssAnimation = elem => {
const style = window.getComputedStyle(elem);
const animDuration = parseFloat(style.getPropertyValue('animation-duration') || '0');
const transDuration = parseFloat(style.getPropertyValue('transition-duration') || '0');
return animDuration > 0 || transDuration > 0;
};
const animateTimerProgressBar = function (timer) {
let reset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
const timerProgressBar = getTimerProgressBar();
if (isVisible(timerProgressBar)) {
if (reset) {
timerProgressBar.style.transition = 'none';
timerProgressBar.style.width = '100%';
}
setTimeout(() => {
timerProgressBar.style.transition = "width ".concat(timer / 1000, "s linear");
timerProgressBar.style.width = '0%';
}, 10);
}
};
const stopTimerProgressBar = () => {
const timerProgressBar = getTimerProgressBar();
const timerProgressBarWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = '100%';
const timerProgressBarFullWidth = parseInt(window.getComputedStyle(timerProgressBar).width);
const timerProgressBarPercent = timerProgressBarWidth / timerProgressBarFullWidth * 100;
timerProgressBar.style.removeProperty('transition');
timerProgressBar.style.width = "".concat(timerProgressBarPercent, "%");
};
/**
* Detect Node env
*
* @returns {boolean}
*/
const isNodeEnv = () => typeof window === 'undefined' || typeof document === 'undefined';
const RESTORE_FOCUS_TIMEOUT = 100;
const globalState = {};
const focusPreviousActiveElement = () => {
if (globalState.previousActiveElement && globalState.previousActiveElement.focus) {
globalState.previousActiveElement.focus();
globalState.previousActiveElement = null;
} else if (document.body) {
document.body.focus();
}
}; // Restore previous active (focused) element
const restoreActiveElement = returnFocus => {
return new Promise(resolve => {
if (!returnFocus) {
return resolve();
}
const x = window.scrollX;
const y = window.scrollY;
globalState.restoreFocusTimeout = setTimeout(() => {
focusPreviousActiveElement();
resolve();
}, RESTORE_FOCUS_TIMEOUT); // issues/900
window.scrollTo(x, y);
});
};
const sweetHTML = "\n <div aria-labelledby=\"".concat(swalClasses.title, "\" aria-describedby=\"").concat(swalClasses['html-container'], "\" class=\"").concat(swalClasses.popup, "\" tabindex=\"-1\">\n <button type=\"button\" class=\"").concat(swalClasses.close, "\"></button>\n <ul class=\"").concat(swalClasses['progress-steps'], "\"></ul>\n <div class=\"").concat(swalClasses.icon, "\"></div>\n <img class=\"").concat(swalClasses.image, "\" />\n <h2 class=\"").concat(swalClasses.title, "\" id=\"").concat(swalClasses.title, "\"></h2>\n <div class=\"").concat(swalClasses['html-container'], "\" id=\"").concat(swalClasses['html-container'], "\"></div>\n <input class=\"").concat(swalClasses.input, "\" />\n <input type=\"file\" class=\"").concat(swalClasses.file, "\" />\n <div class=\"").concat(swalClasses.range, "\">\n <input type=\"range\" />\n <output></output>\n </div>\n <select class=\"").concat(swalClasses.select, "\"></select>\n <div class=\"").concat(swalClasses.radio, "\"></div>\n <label for=\"").concat(swalClasses.checkbox, "\" class=\"").concat(swalClasses.checkbox, "\">\n <input type=\"checkbox\" />\n <span class=\"").concat(swalClasses.label, "\"></span>\n </label>\n <textarea class=\"").concat(swalClasses.textarea, "\"></textarea>\n <div class=\"").concat(swalClasses['validation-message'], "\" id=\"").concat(swalClasses['validation-message'], "\"></div>\n <div class=\"").concat(swalClasses.actions, "\">\n <div class=\"").concat(swalClasses.loader, "\"></div>\n <button type=\"button\" class=\"").concat(swalClasses.confirm, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.deny, "\"></button>\n <button type=\"button\" class=\"").concat(swalClasses.cancel, "\"></button>\n </div>\n <div class=\"").concat(swalClasses.footer, "\"></div>\n <div class=\"").concat(swalClasses['timer-progress-bar-container'], "\">\n <div class=\"").concat(swalClasses['timer-progress-bar'], "\"></div>\n </div>\n </div>\n").replace(/(^|\n)\s*/g, '');
const resetOldContainer = () => {
const oldContainer = getContainer();
if (!oldContainer) {
return false;
}
oldContainer.remove();
removeClass([document.documentElement, document.body], [swalClasses['no-backdrop'], swalClasses['toast-shown'], swalClasses['has-column']]);
return true;
};
const resetValidationMessage = () => {
globalState.currentInstance.resetValidationMessage();
};
const addInputChangeListeners = () => {
const popup = getPopup();
const input = getDirectChildByClass(popup, swalClasses.input);
const file = getDirectChildByClass(popup, swalClasses.file);
const range = popup.querySelector(".".concat(swalClasses.range, " input"));
const rangeOutput = popup.querySelector(".".concat(swalClasses.range, " output"));
const select = getDirectChildByClass(popup, swalClasses.select);
const checkbox = popup.querySelector(".".concat(swalClasses.checkbox, " input"));
const textarea = getDirectChildByClass(popup, swalClasses.textarea);
input.oninput = resetValidationMessage;
file.onchange = resetValidationMessage;
select.onchange = resetValidationMessage;
checkbox.onchange = resetValidationMessage;
textarea.oninput = resetValidationMessage;
range.oninput = () => {
resetValidationMessage();
rangeOutput.value = range.value;
};
range.onchange = () => {
resetValidationMessage();
range.nextSibling.value = range.value;
};
};
const getTarget = target => typeof target === 'string' ? document.querySelector(target) : target;
const setupAccessibility = params => {
const popup = getPopup();
popup.setAttribute('role', params.toast ? 'alert' : 'dialog');
popup.setAttribute('aria-live', params.toast ? 'polite' : 'assertive');
if (!params.toast) {
popup.setAttribute('aria-modal', 'true');
}
};
const setupRTL = targetElement => {
if (window.getComputedStyle(targetElement).direction === 'rtl') {
addClass(getContainer(), swalClasses.rtl);
}
};
/*
* Add modal + backdrop to DOM
*/
const init = params => {
// Clean up the old popup container if it exists
const oldContainerExisted = resetOldContainer();
/* istanbul ignore if */
if (isNodeEnv()) {
error('SweetAlert2 requires document to initialize');
return;
}
const container = document.createElement('div');
container.className = swalClasses.container;
if (oldContainerExisted) {
addClass(container, swalClasses['no-transition']);
}
setInnerHtml(container, sweetHTML);
const targetElement = getTarget(params.target);
targetElement.appendChild(container);
setupAccessibility(params);
setupRTL(targetElement);
addInputChangeListeners();
};
/**
* @param {HTMLElement | object | string} param
* @param {HTMLElement} target
*/
const parseHtmlToContainer = (param, target) => {
// DOM element
if (param instanceof HTMLElement) {
target.appendChild(param);
} // Object
else if (typeof param === 'object') {
handleObject(param, target);
} // Plain string
else if (param) {
setInnerHtml(target, param);
}
};
/**
* @param {object} param
* @param {HTMLElement} target
*/
const handleObject = (param, target) => {
// JQuery element(s)
if (param.jquery) {
handleJqueryElem(target, param);
} // For other objects use their string representation
else {
setInnerHtml(target, param.toString());
}
};
const handleJqueryElem = (target, elem) => {
target.textContent = '';
if (0 in elem) {
for (let i = 0; (i in elem); i++) {
target.appendChild(elem[i].cloneNode(true));
}
} else {
target.appendChild(elem.cloneNode(true));
}
};
const animationEndEvent = (() => {
// Prevent run in Node env
/* istanbul ignore if */
if (isNodeEnv()) {
return false;
}
const testEl = document.createElement('div');
const transEndEventNames = {
WebkitAnimation: 'webkitAnimationEnd',
// Chrome, Safari and Opera
animation: 'animationend' // Standard syntax
};
for (const i in transEndEventNames) {
if (Object.prototype.hasOwnProperty.call(transEndEventNames, i) && typeof testEl.style[i] !== 'undefined') {
return transEndEventNames[i];
}
}
return false;
})();
// https://github.com/twbs/bootstrap/blob/master/js/src/modal.js
const measureScrollbar = () => {
const scrollDiv = document.createElement('div');
scrollDiv.className = swalClasses['scrollbar-measure'];
document.body.appendChild(scrollDiv);
const scrollbarWidth = scrollDiv.getBoundingClientRect().width - scrollDiv.clientWidth;
document.body.removeChild(scrollDiv);
return scrollbarWidth;
};
const renderActions = (instance, params) => {
const actions = getActions();
const loader = getLoader(); // Actions (buttons) wrapper
if (!params.showConfirmButton && !params.showDenyButton && !params.showCancelButton) {
hide(actions);
} else {
show(actions);
} // Custom class
applyCustomClass(actions, params, 'actions'); // Render all the buttons
renderButtons(actions, loader, params); // Loader
setInnerHtml(loader, params.loaderHtml);
applyCustomClass(loader, params, 'loader');
};
function renderButtons(actions, loader, params) {
const confirmButton = getConfirmButton();
const denyButton = getDenyButton();
const cancelButton = getCancelButton(); // Render buttons
renderButton(confirmButton, 'confirm', params);
renderButton(denyButton, 'deny', params);
renderButton(cancelButton, 'cancel', params);
handleButtonsStyling(confirmButton, denyButton, cancelButton, params);
if (params.reverseButtons) {
if (params.toast) {
actions.insertBefore(cancelButton, confirmButton);
actions.insertBefore(denyButton, confirmButton);
} else {
actions.insertBefore(cancelButton, loader);
actions.insertBefore(denyButton, loader);
actions.insertBefore(confirmButton, loader);
}
}
}
function handleButtonsStyling(confirmButton, denyButton, cancelButton, params) {
if (!params.buttonsStyling) {
return removeClass([confirmButton, denyButton, cancelButton], swalClasses.styled);
}
addClass([confirmButton, denyButton, cancelButton], swalClasses.styled); // Buttons background colors
if (params.confirmButtonColor) {
confirmButton.style.backgroundColor = params.confirmButtonColor;
addClass(confirmButton, swalClasses['default-outline']);
}
if (params.denyButtonColor) {
denyButton.style.backgroundColor = params.denyButtonColor;
addClass(denyButton, swalClasses['default-outline']);
}
if (params.cancelButtonColor) {
cancelButton.style.backgroundColor = params.cancelButtonColor;
addClass(cancelButton, swalClasses['default-outline']);
}
}
function renderButton(button, buttonType, params) {
toggle(button, params["show".concat(capitalizeFirstLetter(buttonType), "Button")], 'inline-block');
setInnerHtml(button, params["".concat(buttonType, "ButtonText")]); // Set caption text
button.setAttribute('aria-label', params["".concat(buttonType, "ButtonAriaLabel")]); // ARIA label
// Add buttons custom classes
button.className = swalClasses[buttonType];
applyCustomClass(button, params, "".concat(buttonType, "Button"));
addClass(button, params["".concat(buttonType, "ButtonClass")]);
}
function handleBackdropParam(container, backdrop) {
if (typeof backdrop === 'string') {
container.style.background = backdrop;
} else if (!backdrop) {
addClass([document.documentElement, document.body], swalClasses['no-backdrop']);
}
}
function handlePositionParam(container, position) {
if (position in swalClasses) {
addClass(container, swalClasses[position]);
} else {
warn('The "position" parameter is not valid, defaulting to "center"');
addClass(container, swalClasses.center);
}
}
function handleGrowParam(container, grow) {
if (grow && typeof grow === 'string') {
const growClass = "grow-".concat(grow);
if (growClass in swalClasses) {
addClass(container, swalClasses[growClass]);
}
}
}
const renderContainer = (instance, params) => {
const container = getContainer();
if (!container) {
return;
}
handleBackdropParam(container, params.backdrop);
handlePositionParam(container, params.position);
handleGrowParam(container, params.grow); // Custom class
applyCustomClass(container, params, 'container');
};
/**
* This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* https://github.com/tc39/proposal-private-methods
* https://github.com/babel/babel/pull/7555
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateProps = {
awaitingPromise: new WeakMap(),
promise: new WeakMap(),
innerParams: new WeakMap(),
domCache: new WeakMap()
};
const inputTypes = ['input', 'file', 'range', 'select', 'radio', 'checkbox', 'textarea'];
const renderInput = (instance, params) => {
const popup = getPopup();
const innerParams = privateProps.innerParams.get(instance);
const rerender = !innerParams || params.input !== innerParams.input;
inputTypes.forEach(inputType => {
const inputClass = swalClasses[inputType];
const inputContainer = getDirectChildByClass(popup, inputClass); // set attributes
setAttributes(inputType, params.inputAttributes); // set class
inputContainer.className = inputClass;
if (rerender) {
hide(inputContainer);
}
});
if (params.input) {
if (rerender) {
showInput(params);
} // set custom class
setCustomClass(params);
}
};
const showInput = params => {
if (!renderInputType[params.input]) {
return error("Unexpected type of input! Expected \"text\", \"email\", \"password\", \"number\", \"tel\", \"select\", \"radio\", \"checkbox\", \"textarea\", \"file\" or \"url\", got \"".concat(params.input, "\""));
}
const inputContainer = getInputContainer(params.input);
const input = renderInputType[params.input](inputContainer, params);
show(input); // input autofocus
setTimeout(() => {
focusInput(input);
});
};
const removeAttributes = input => {
for (let i = 0; i < input.attributes.length; i++) {
const attrName = input.attributes[i].name;
if (!['type', 'value', 'style'].includes(attrName)) {
input.removeAttribute(attrName);
}
}
};
const setAttributes = (inputType, inputAttributes) => {
const input = getInput(getPopup(), inputType);
if (!input) {
return;
}
removeAttributes(input);
for (const attr in inputAttributes) {
input.setAttribute(attr, inputAttributes[attr]);
}
};
const setCustomClass = params => {
const inputContainer = getInputContainer(params.input);
if (params.customClass) {
addClass(inputContainer, params.customClass.input);
}
};
const setInputPlaceholder = (input, params) => {
if (!input.placeholder || params.inputPlaceholder) {
input.placeholder = params.inputPlaceholder;
}
};
const setInputLabel = (input, prependTo, params) => {
if (params.inputLabel) {
input.id = swalClasses.input;
const label = document.createElement('label');
const labelClass = swalClasses['input-label'];
label.setAttribute('for', input.id);
label.className = labelClass;
addClass(label, params.customClass.inputLabel);
label.innerText = params.inputLabel;
prependTo.insertAdjacentElement('beforebegin', label);
}
};
const getInputContainer = inputType => {
const inputClass = swalClasses[inputType] ? swalClasses[inputType] : swalClasses.input;
return getDirectChildByClass(getPopup(), inputClass);
};
const renderInputType = {};
renderInputType.text = renderInputType.email = renderInputType.password = renderInputType.number = renderInputType.tel = renderInputType.url = (input, params) => {
if (typeof params.inputValue === 'string' || typeof params.inputValue === 'number') {
input.value = params.inputValue;
} else if (!isPromise(params.inputValue)) {
warn("Unexpected type of inputValue! Expected \"string\", \"number\" or \"Promise\", got \"".concat(typeof params.inputValue, "\""));
}
setInputLabel(input, input, params);
setInputPlaceholder(input, params);
input.type = params.input;
return input;
};
renderInputType.file = (input, params) => {
setInputLabel(input, input, params);
setInputPlaceholder(input, params);
return input;
};
renderInputType.range = (range, params) => {
const rangeInput = range.querySelector('input');
const rangeOutput = range.querySelector('output');
rangeInput.value = params.inputValue;
rangeInput.type = params.input;
rangeOutput.value = params.inputValue;
setInputLabel(rangeInput, range, params);
return range;
};
renderInputType.select = (select, params) => {
select.textContent = '';
if (params.inputPlaceholder) {
const placeholder = document.createElement('option');
setInnerHtml(placeholder, params.inputPlaceholder);
placeholder.value = '';
placeholder.disabled = true;
placeholder.selected = true;
select.appendChild(placeholder);
}
setInputLabel(select, select, params);
return select;
};
renderInputType.radio = radio => {
radio.textContent = '';
return radio;
};
renderInputType.checkbox = (checkboxContainer, params) => {
/** @type {HTMLInputElement} */
const checkbox = getInput(getPopup(), 'checkbox');
checkbox.value = '1';
checkbox.id = swalClasses.checkbox;
checkbox.checked = Boolean(params.inputValue);
const label = checkboxContainer.querySelector('span');
setInnerHtml(label, params.inputPlaceholder);
return checkboxContainer;
};
renderInputType.textarea = (textarea, params) => {
textarea.value = params.inputValue;
setInputPlaceholder(textarea, params);
setInputLabel(textarea, textarea, params);
const getMargin = el => parseInt(window.getComputedStyle(el).marginLeft) + parseInt(window.getComputedStyle(el).marginRight); // https://github.com/sweetalert2/sweetalert2/issues/2291
setTimeout(() => {
// https://github.com/sweetalert2/sweetalert2/issues/1699
if ('MutationObserver' in window) {
const initialPopupWidth = parseInt(window.getComputedStyle(getPopup()).width);
const textareaResizeHandler = () => {
const textareaWidth = textarea.offsetWidth + getMargin(textarea);
if (textareaWidth > initialPopupWidth) {
getPopup().style.width = "".concat(textareaWidth, "px");
} else {
getPopup().style.width = null;
}
};
new MutationObserver(textareaResizeHandler).observe(textarea, {
attributes: true,
attributeFilter: ['style']
});
}
});
return textarea;
};
const renderContent = (instance, params) => {
const htmlContainer = getHtmlContainer();
applyCustomClass(htmlContainer, params, 'htmlContainer'); // Content as HTML
if (params.html) {
parseHtmlToContainer(params.html, htmlContainer);
show(htmlContainer, 'block');
} // Content as plain text
else if (params.text) {
htmlContainer.textContent = params.text;
show(htmlContainer, 'block');
} // No content
else {
hide(htmlContainer);
}
renderInput(instance, params);
};
const renderFooter = (instance, params) => {
const footer = getFooter();
toggle(footer, params.footer);
if (params.footer) {
parseHtmlToContainer(params.footer, footer);
} // Custom class
applyCustomClass(footer, params, 'footer');
};
const renderCloseButton = (instance, params) => {
const closeButton = getCloseButton();
setInnerHtml(closeButton, params.closeButtonHtml); // Custom class
applyCustomClass(closeButton, params, 'closeButton');
toggle(closeButton, params.showCloseButton);
closeButton.setAttribute('aria-label', params.closeButtonAriaLabel);
};
const renderIcon = (instance, params) => {
const innerParams = privateProps.innerParams.get(instance);
const icon = getIcon(); // if the given icon already rendered, apply the styling without re-rendering the icon
if (innerParams && params.icon === innerParams.icon) {
// Custom or default content
setContent(icon, params);
applyStyles(icon, params);
return;
}
if (!params.icon && !params.iconHtml) {
return hide(icon);
}
if (params.icon && Object.keys(iconTypes).indexOf(params.icon) === -1) {
error("Unknown icon! Expected \"success\", \"error\", \"warning\", \"info\" or \"question\", got \"".concat(params.icon, "\""));
return hide(icon);
}
show(icon); // Custom or default content
setContent(icon, params);
applyStyles(icon, params); // Animate icon
addClass(icon, params.showClass.icon);
};
const applyStyles = (icon, params) => {
for (const iconType in iconTypes) {
if (params.icon !== iconType) {
removeClass(icon, iconTypes[iconType]);
}
}
addClass(icon, iconTypes[params.icon]); // Icon color
setColor(icon, params); // Success icon background color
adjustSuccessIconBackgroundColor(); // Custom class
applyCustomClass(icon, params, 'icon');
}; // Adjust success icon background color to match the popup background color
const adjustSuccessIconBackgroundColor = () => {
const popup = getPopup();
const popupBackgroundColor = window.getComputedStyle(popup).getPropertyValue('background-color');
const successIconParts = popup.querySelectorAll('[class^=swal2-success-circular-line], .swal2-success-fix');
for (let i = 0; i < successIconParts.length; i++) {
successIconParts[i].style.backgroundColor = popupBackgroundColor;
}
};
const successIconHtml = "\n <div class=\"swal2-success-circular-line-left\"></div>\n <span class=\"swal2-success-line-tip\"></span> <span class=\"swal2-success-line-long\"></span>\n <div class=\"swal2-success-ring\"></div> <div class=\"swal2-success-fix\"></div>\n <div class=\"swal2-success-circular-line-right\"></div>\n";
const errorIconHtml = "\n <span class=\"swal2-x-mark\">\n <span class=\"swal2-x-mark-line-left\"></span>\n <span class=\"swal2-x-mark-line-right\"></span>\n </span>\n";
const setContent = (icon, params) => {
icon.textContent = '';
if (params.iconHtml) {
setInnerHtml(icon, iconContent(params.iconHtml));
} else if (params.icon === 'success') {
setInnerHtml(icon, successIconHtml);
} else if (params.icon === 'error') {
setInnerHtml(icon, errorIconHtml);
} else {
const defaultIconHtml = {
question: '?',
warning: '!',
info: 'i'
};
setInnerHtml(icon, iconContent(defaultIconHtml[params.icon]));
}
};
const setColor = (icon, params) => {
if (!params.iconColor) {
return;
}
icon.style.color = params.iconColor;
icon.style.borderColor = params.iconColor;
for (const sel of ['.swal2-success-line-tip', '.swal2-success-line-long', '.swal2-x-mark-line-left', '.swal2-x-mark-line-right']) {
setStyle(icon, sel, 'backgroundColor', params.iconColor);
}
setStyle(icon, '.swal2-success-ring', 'borderColor', params.iconColor);
};
const iconContent = content => "<div class=\"".concat(swalClasses['icon-content'], "\">").concat(content, "</div>");
const renderImage = (instance, params) => {
const image = getImage();
if (!params.imageUrl) {
return hide(image);
}
show(image, ''); // Src, alt
image.setAttribute('src', params.imageUrl);
image.setAttribute('alt', params.imageAlt); // Width, height
applyNumericalStyle(image, 'width', params.imageWidth);
applyNumericalStyle(image, 'height', params.imageHeight); // Class
image.className = swalClasses.image;
applyCustomClass(image, params, 'image');
};
const createStepElement = step => {
const stepEl = document.createElement('li');
addClass(stepEl, swalClasses['progress-step']);
setInnerHtml(stepEl, step);
return stepEl;
};
const createLineElement = params => {
const lineEl = document.createElement('li');
addClass(lineEl, swalClasses['progress-step-line']);
if (params.progressStepsDistance) {
lineEl.style.width = params.progressStepsDistance;
}
return lineEl;
};
const renderProgressSteps = (instance, params) => {
const progressStepsContainer = getProgressSteps();
if (!params.progressSteps || params.progressSteps.length === 0) {
return hide(progressStepsContainer);
}
show(progressStepsContainer);
progressStepsContainer.textContent = '';
if (params.currentProgressStep >= params.progressSteps.length) {
warn('Invalid currentProgressStep parameter, it should be less than progressSteps.length ' + '(currentProgressStep like JS arrays starts from 0)');
}
params.progressSteps.forEach((step, index) => {
const stepEl = createStepElement(step);
progressStepsContainer.appendChild(stepEl);
if (index === params.currentProgressStep) {
addClass(stepEl, swalClasses['active-progress-step']);
}
if (index !== params.progressSteps.length - 1) {
const lineEl = createLineElement(params);
progressStepsContainer.appendChild(lineEl);
}
});
};
const renderTitle = (instance, params) => {
const title = getTitle();
toggle(title, params.title || params.titleText, 'block');
if (params.title) {
parseHtmlToContainer(params.title, title);
}
if (params.titleText) {
title.innerText = params.titleText;
} // Custom class
applyCustomClass(title, params, 'title');
};
const renderPopup = (instance, params) => {
const container = getContainer();
const popup = getPopup(); // Width
// https://github.com/sweetalert2/sweetalert2/issues/2170
if (params.toast) {
applyNumericalStyle(container, 'width', params.width);
popup.style.width = '100%';
popup.insertBefore(getLoader(), getIcon());
} else {
applyNumericalStyle(popup, 'width', params.width);
} // Padding
applyNumericalStyle(popup, 'padding', params.padding); // Color
if (params.color) {
popup.style.color = params.color;
} // Background
if (params.background) {
popup.style.background = params.background;
}
hide(getValidationMessage()); // Classes
addClasses(popup, params);
};
const addClasses = (popup, params) => {
// Default Class + showClass when updating Swal.update({})
popup.className = "".concat(swalClasses.popup, " ").concat(isVisible(popup) ? params.showClass.popup : '');
if (params.toast) {
addClass([document.documentElement, document.body], swalClasses['toast-shown']);
addClass(popup, swalClasses.toast);
} else {
addClass(popup, swalClasses.modal);
} // Custom class
applyCustomClass(popup, params, 'popup');
if (typeof params.customClass === 'string') {
addClass(popup, params.customClass);
} // Icon class (#1842)
if (params.icon) {
addClass(popup, swalClasses["icon-".concat(params.icon)]);
}
};
const render = (instance, params) => {
renderPopup(instance, params);
renderContainer(instance, params);
renderProgressSteps(instance, params);
renderIcon(instance, params);
renderImage(instance, params);
renderTitle(instance, params);
renderCloseButton(instance, params);
renderContent(instance, params);
renderActions(instance, params);
renderFooter(instance, params);
if (typeof params.didRender === 'function') {
params.didRender(getPopup());
}
};
const DismissReason = Object.freeze({
cancel: 'cancel',
backdrop: 'backdrop',
close: 'close',
esc: 'esc',
timer: 'timer'
});
// Adding aria-hidden="true" to elements outside of the active modal dialog ensures that
// elements not within the active modal dialog will not be surfaced if a user opens a screen
// reader’s list of elements (headings, form controls, landmarks, etc.) in the document.
const setAriaHidden = () => {
const bodyChildren = toArray(document.body.children);
bodyChildren.forEach(el => {
if (el === getContainer() || el.contains(getContainer())) {
return;
}
if (el.hasAttribute('aria-hidden')) {
el.setAttribute('data-previous-aria-hidden', el.getAttribute('aria-hidden'));
}
el.setAttribute('aria-hidden', 'true');
});
};
const unsetAriaHidden = () => {
const bodyChildren = toArray(document.body.children);
bodyChildren.forEach(el => {
if (el.hasAttribute('data-previous-aria-hidden')) {
el.setAttribute('aria-hidden', el.getAttribute('data-previous-aria-hidden'));
el.removeAttribute('data-previous-aria-hidden');
} else {
el.removeAttribute('aria-hidden');
}
});
};
const swalStringParams = ['swal-title', 'swal-html', 'swal-footer'];
const getTemplateParams = params => {
const template = typeof params.template === 'string' ? document.querySelector(params.template) : params.template;
if (!template) {
return {};
}
/** @type {DocumentFragment} */
const templateContent = template.content;
showWarningsForElements(templateContent);
const result = Object.assign(getSwalParams(templateContent), getSwalButtons(templateContent), getSwalImage(templateContent), getSwalIcon(templateContent), getSwalInput(templateContent), getSwalStringParams(templateContent, swalStringParams));
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalParams = templateContent => {
const result = {};
toArray(templateContent.querySelectorAll('swal-param')).forEach(param => {
showWarningsForAttributes(param, ['name', 'value']);
const paramName = param.getAttribute('name');
const value = param.getAttribute('value');
if (typeof defaultParams[paramName] === 'boolean' && value === 'false') {
result[paramName] = false;
}
if (typeof defaultParams[paramName] === 'object') {
result[paramName] = JSON.parse(value);
}
});
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalButtons = templateContent => {
const result = {};
toArray(templateContent.querySelectorAll('swal-button')).forEach(button => {
showWarningsForAttributes(button, ['type', 'color', 'aria-label']);
const type = button.getAttribute('type');
result["".concat(type, "ButtonText")] = button.innerHTML;
result["show".concat(capitalizeFirstLetter(type), "Button")] = true;
if (button.hasAttribute('color')) {
result["".concat(type, "ButtonColor")] = button.getAttribute('color');
}
if (button.hasAttribute('aria-label')) {
result["".concat(type, "ButtonAriaLabel")] = button.getAttribute('aria-label');
}
});
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalImage = templateContent => {
const result = {};
/** @type {HTMLElement} */
const image = templateContent.querySelector('swal-image');
if (image) {
showWarningsForAttributes(image, ['src', 'width', 'height', 'alt']);
if (image.hasAttribute('src')) {
result.imageUrl = image.getAttribute('src');
}
if (image.hasAttribute('width')) {
result.imageWidth = image.getAttribute('width');
}
if (image.hasAttribute('height')) {
result.imageHeight = image.getAttribute('height');
}
if (image.hasAttribute('alt')) {
result.imageAlt = image.getAttribute('alt');
}
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalIcon = templateContent => {
const result = {};
/** @type {HTMLElement} */
const icon = templateContent.querySelector('swal-icon');
if (icon) {
showWarningsForAttributes(icon, ['type', 'color']);
if (icon.hasAttribute('type')) {
result.icon = icon.getAttribute('type');
}
if (icon.hasAttribute('color')) {
result.iconColor = icon.getAttribute('color');
}
result.iconHtml = icon.innerHTML;
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const getSwalInput = templateContent => {
const result = {};
/** @type {HTMLElement} */
const input = templateContent.querySelector('swal-input');
if (input) {
showWarningsForAttributes(input, ['type', 'label', 'placeholder', 'value']);
result.input = input.getAttribute('type') || 'text';
if (input.hasAttribute('label')) {
result.inputLabel = input.getAttribute('label');
}
if (input.hasAttribute('placeholder')) {
result.inputPlaceholder = input.getAttribute('placeholder');
}
if (input.hasAttribute('value')) {
result.inputValue = input.getAttribute('value');
}
}
const inputOptions = templateContent.querySelectorAll('swal-input-option');
if (inputOptions.length) {
result.inputOptions = {};
toArray(inputOptions).forEach(option => {
showWarningsForAttributes(option, ['value']);
const optionValue = option.getAttribute('value');
const optionName = option.innerHTML;
result.inputOptions[optionValue] = optionName;
});
}
return result;
};
/**
* @param {DocumentFragment} templateContent
* @param {string[]} paramNames
*/
const getSwalStringParams = (templateContent, paramNames) => {
const result = {};
for (const i in paramNames) {
const paramName = paramNames[i];
/** @type {HTMLElement} */
const tag = templateContent.querySelector(paramName);
if (tag) {
showWarningsForAttributes(tag, []);
result[paramName.replace(/^swal-/, '')] = tag.innerHTML.trim();
}
}
return result;
};
/**
* @param {DocumentFragment} templateContent
*/
const showWarningsForElements = templateContent => {
const allowedElements = swalStringParams.concat(['swal-param', 'swal-button', 'swal-image', 'swal-icon', 'swal-input', 'swal-input-option']);
toArray(templateContent.children).forEach(el => {
const tagName = el.tagName.toLowerCase();
if (allowedElements.indexOf(tagName) === -1) {
warn("Unrecognized element <".concat(tagName, ">"));
}
});
};
/**
* @param {HTMLElement} el
* @param {string[]} allowedAttributes
*/
const showWarningsForAttributes = (el, allowedAttributes) => {
toArray(el.attributes).forEach(attribute => {
if (allowedAttributes.indexOf(attribute.name) === -1) {
warn(["Unrecognized attribute \"".concat(attribute.name, "\" on <").concat(el.tagName.toLowerCase(), ">."), "".concat(allowedAttributes.length ? "Allowed attributes are: ".concat(allowedAttributes.join(', ')) : 'To set the value, use HTML within the element.')]);
}
});
};
var defaultInputValidators = {
email: (string, validationMessage) => {
return /^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid email address');
},
url: (string, validationMessage) => {
// taken from https://stackoverflow.com/a/3809435 with a small change from #1306 and #2013
return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(string) ? Promise.resolve() : Promise.resolve(validationMessage || 'Invalid URL');
}
};
function setDefaultInputValidators(params) {
// Use default `inputValidator` for supported input types if not provided
if (!params.inputValidator) {
Object.keys(defaultInputValidators).forEach(key => {
if (params.input === key) {
params.inputValidator = defaultInputValidators[key];
}
});
}
}
function validateCustomTargetElement(params) {
// Determine if the custom target element is valid
if (!params.target || typeof params.target === 'string' && !document.querySelector(params.target) || typeof params.target !== 'string' && !params.target.appendChild) {
warn('Target parameter is not valid, defaulting to "body"');
params.target = 'body';
}
}
/**
* Set type, text and actions on popup
*
* @param params
*/
function setParameters(params) {
setDefaultInputValidators(params); // showLoaderOnConfirm && preConfirm
if (params.showLoaderOnConfirm && !params.preConfirm) {
warn('showLoaderOnConfirm is set to true, but preConfirm is not defined.\n' + 'showLoaderOnConfirm should be used together with preConfirm, see usage example:\n' + 'https://sweetalert2.github.io/#ajax-request');
}
validateCustomTargetElement(params); // Replace newlines with <br> in title
if (typeof params.title === 'string') {
params.title = params.title.split('\n').join('<br />');
}
init(params);
}
class Timer {
constructor(callback, delay) {
this.callback = callback;
this.remaining = delay;
this.running = false;
this.start();
}
start() {
if (!this.running) {
this.running = true;
this.started = new Date();
this.id = setTimeout(this.callback, this.remaining);
}
return this.remaining;
}
stop() {
if (this.running) {
this.running = false;
clearTimeout(this.id);
this.remaining -= new Date().getTime() - this.started.getTime();
}
return this.remaining;
}
increase(n) {
const running = this.running;
if (running) {
this.stop();
}
this.remaining += n;
if (running) {
this.start();
}
return this.remaining;
}
getTimerLeft() {
if (this.running) {
this.stop();
this.start();
}
return this.remaining;
}
isRunning() {
return this.running;
}
}
const fixScrollbar = () => {
// for queues, do not do this more than once
if (states.previousBodyPadding !== null) {
return;
} // if the body has overflow
if (document.body.scrollHeight > window.innerHeight) {
// add padding so the content doesn't shift after removal of scrollbar
states.previousBodyPadding = parseInt(window.getComputedStyle(document.body).getPropertyValue('padding-right'));
document.body.style.paddingRight = "".concat(states.previousBodyPadding + measureScrollbar(), "px");
}
};
const undoScrollbar = () => {
if (states.previousBodyPadding !== null) {
document.body.style.paddingRight = "".concat(states.previousBodyPadding, "px");
states.previousBodyPadding = null;
}
};
/* istanbul ignore file */
const iOSfix = () => {
const iOS = // @ts-ignore
/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;
if (iOS && !hasClass(document.body, swalClasses.iosfix)) {
const offset = document.body.scrollTop;
document.body.style.top = "".concat(offset * -1, "px");
addClass(document.body, swalClasses.iosfix);
lockBodyScroll();
addBottomPaddingForTallPopups();
}
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1948
*/
const addBottomPaddingForTallPopups = () => {
const ua = navigator.userAgent;
const iOS = !!ua.match(/iPad/i) || !!ua.match(/iPhone/i);
const webkit = !!ua.match(/WebKit/i);
const iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
if (iOSSafari) {
const bottomPanelHeight = 44;
if (getPopup().scrollHeight > window.innerHeight - bottomPanelHeight) {
getContainer().style.paddingBottom = "".concat(bottomPanelHeight, "px");
}
}
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1246
*/
const lockBodyScroll = () => {
const container = getContainer();
let preventTouchMove;
container.ontouchstart = e => {
preventTouchMove = shouldPreventTouchMove(e);
};
container.ontouchmove = e => {
if (preventTouchMove) {
e.preventDefault();
e.stopPropagation();
}
};
};
const shouldPreventTouchMove = event => {
const target = event.target;
const container = getContainer();
if (isStylus(event) || isZoom(event)) {
return false;
}
if (target === container) {
return true;
}
if (!isScrollable(container) && target.tagName !== 'INPUT' && // #1603
target.tagName !== 'TEXTAREA' && // #2266
!(isScrollable(getHtmlContainer()) && // #1944
getHtmlContainer().contains(target))) {
return true;
}
return false;
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1786
*
* @param {*} event
* @returns {boolean}
*/
const isStylus = event => {
return event.touches && event.touches.length && event.touches[0].touchType === 'stylus';
};
/**
* https://github.com/sweetalert2/sweetalert2/issues/1891
*
* @param {TouchEvent} event
* @returns {boolean}
*/
const isZoom = event => {
return event.touches && event.touches.length > 1;
};
const undoIOSfix = () => {
if (hasClass(document.body, swalClasses.iosfix)) {
const offset = parseInt(document.body.style.top, 10);
removeClass(document.body, swalClasses.iosfix);
document.body.style.top = '';
document.body.scrollTop = offset * -1;
}
};
const SHOW_CLASS_TIMEOUT = 10;
/**
* Open popup, add necessary classes and styles, fix scrollbar
*
* @param params
*/
const openPopup = params => {
const container = getContainer();
const popup = getPopup();
if (typeof params.willOpen === 'function') {
params.willOpen(popup);
}
const bodyStyles = window.getComputedStyle(document.body);
const initialBodyOverflow = bodyStyles.overflowY;
addClasses$1(container, popup, params); // scrolling is 'hidden' until animation is done, after that 'auto'
setTimeout(() => {
setScrollingVisibility(container, popup);
}, SHOW_CLASS_TIMEOUT);
if (isModal()) {
fixScrollContainer(container, params.scrollbarPadding, initialBodyOverflow);
setAriaHidden();
}
if (!isToast() && !globalState.previousActiveElement) {
globalState.previousActiveElement = document.activeElement;
}
if (typeof params.didOpen === 'function') {
setTimeout(() => params.didOpen(popup));
}
removeClass(container, swalClasses['no-transition']);
};
const swalOpenAnimationFinished = event => {
const popup = getPopup();
if (event.target !== popup) {
return;
}
const container = getContainer();
popup.removeEventListener(animationEndEvent, swalOpenAnimationFinished);
container.style.overflowY = 'auto';
};
const setScrollingVisibility = (container, popup) => {
if (animationEndEvent && hasCssAnimation(popup)) {
container.style.overflowY = 'hidden';
popup.addEventListener(animationEndEvent, swalOpenAnimationFinished);
} else {
container.style.overflowY = 'auto';
}
};
const fixScrollContainer = (container, scrollbarPadding, initialBodyOverflow) => {
iOSfix();
if (scrollbarPadding && initialBodyOverflow !== 'hidden') {
fixScrollbar();
} // sweetalert2/issues/1247
setTimeout(() => {
container.scrollTop = 0;
});
};
const addClasses$1 = (container, popup, params) => {
addClass(container, params.showClass.backdrop); // this workaround with opacity is needed for https://github.com/sweetalert2/sweetalert2/issues/2059
popup.style.setProperty('opacity', '0', 'important');
show(popup, 'grid');
setTimeout(() => {
// Animate popup right after showing it
addClass(popup, params.showClass.popup); // and remove the opacity workaround
popup.style.removeProperty('opacity');
}, SHOW_CLASS_TIMEOUT); // 10ms in order to fix #2062
addClass([document.documentElement, document.body], swalClasses.shown);
if (params.heightAuto && params.backdrop && !params.toast) {
addClass([document.documentElement, document.body], swalClasses['height-auto']);
}
};
/**
* Shows loader (spinner), this is useful with AJAX requests.
* By default the loader be shown instead of the "Confirm" button.
*/
const showLoading = buttonToReplace => {
let popup = getPopup();
if (!popup) {
new Swal(); // eslint-disable-line no-new
}
popup = getPopup();
const loader = getLoader();
if (isToast()) {
hide(getIcon());
} else {
replaceButton(popup, buttonToReplace);
}
show(loader);
popup.setAttribute('data-loading', true);
popup.setAttribute('aria-busy', true);
popup.focus();
};
const replaceButton = (popup, buttonToReplace) => {
const actions = getActions();
const loader = getLoader();
if (!buttonToReplace && isVisible(getConfirmButton())) {
buttonToReplace = getConfirmButton();
}
show(actions);
if (buttonToReplace) {
hide(buttonToReplace);
loader.setAttribute('data-button-to-replace', buttonToReplace.className);
}
loader.parentNode.insertBefore(loader, buttonToReplace);
addClass([popup, actions], swalClasses.loading);
};
const handleInputOptionsAndValue = (instance, params) => {
if (params.input === 'select' || params.input === 'radio') {
handleInputOptions(instance, params);
} else if (['text', 'email', 'number', 'tel', 'textarea'].includes(params.input) && (hasToPromiseFn(params.inputValue) || isPromise(params.inputValue))) {
showLoading(getConfirmButton());
handleInputValue(instance, params);
}
};
const getInputValue = (instance, innerParams) => {
const input = instance.getInput();
if (!input) {
return null;
}
switch (innerParams.input) {
case 'checkbox':
return getCheckboxValue(input);
case 'radio':
return getRadioValue(input);
case 'file':
return getFileValue(input);
default:
return innerParams.inputAutoTrim ? input.value.trim() : input.value;
}
};
const getCheckboxValue = input => input.checked ? 1 : 0;
const getRadioValue = input => input.checked ? input.value : null;
const getFileValue = input => input.files.length ? input.getAttribute('multiple') !== null ? input.files : input.files[0] : null;
const handleInputOptions = (instance, params) => {
const popup = getPopup();
const processInputOptions = inputOptions => populateInputOptions[params.input](popup, formatInputOptions(inputOptions), params);
if (hasToPromiseFn(params.inputOptions) || isPromise(params.inputOptions)) {
showLoading(getConfirmButton());
asPromise(params.inputOptions).then(inputOptions => {
instance.hideLoading();
processInputOptions(inputOptions);
});
} else if (typeof params.inputOptions === 'object') {
processInputOptions(params.inputOptions);
} else {
error("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(typeof params.inputOptions));
}
};
const handleInputValue = (instance, params) => {
const input = instance.getInput();
hide(input);
asPromise(params.inputValue).then(inputValue => {
input.value = params.input === 'number' ? parseFloat(inputValue) || 0 : "".concat(inputValue);
show(input);
input.focus();
instance.hideLoading();
}).catch(err => {
error("Error in inputValue promise: ".concat(err));
input.value = '';
show(input);
input.focus();
instance.hideLoading();
});
};
const populateInputOptions = {
select: (popup, inputOptions, params) => {
const select = getDirectChildByClass(popup, swalClasses.select);
const renderOption = (parent, optionLabel, optionValue) => {
const option = document.createElement('option');
option.value = optionValue;
setInnerHtml(option, optionLabel);
option.selected = isSelected(optionValue, params.inputValue);
parent.appendChild(option);
};
inputOptions.forEach(inputOption => {
const optionValue = inputOption[0];
const optionLabel = inputOption[1]; // <optgroup> spec:
// https://www.w3.org/TR/html401/interact/forms.html#h-17.6
// "...all OPTGROUP elements must be specified directly within a SELECT element (i.e., groups may not be nested)..."
// check whether this is a <optgroup>
if (Array.isArray(optionLabel)) {
// if it is an array, then it is an <optgroup>
const optgroup = document.createElement('optgroup');
optgroup.label = optionValue;
optgroup.disabled = false; // not configurable for now
select.appendChild(optgroup);
optionLabel.forEach(o => renderOption(optgroup, o[1], o[0]));
} else {
// case of <option>
renderOption(select, optionLabel, optionValue);
}
});
select.focus();
},
radio: (popup, inputOptions, params) => {
const radio = getDirectChildByClass(popup, swalClasses.radio);
inputOptions.forEach(inputOption => {
const radioValue = inputOption[0];
const radioLabel = inputOption[1];
const radioInput = document.createElement('input');
const radioLabelElement = document.createElement('label');
radioInput.type = 'radio';
radioInput.name = swalClasses.radio;
radioInput.value = radioValue;
if (isSelected(radioValue, params.inputValue)) {
radioInput.checked = true;
}
const label = document.createElement('span');
setInnerHtml(label, radioLabel);
label.className = swalClasses.label;
radioLabelElement.appendChild(radioInput);
radioLabelElement.appendChild(label);
radio.appendChild(radioLabelElement);
});
const radios = radio.querySelectorAll('input');
if (radios.length) {
radios[0].focus();
}
}
};
/**
* Converts `inputOptions` into an array of `[value, label]`s
* @param inputOptions
*/
const formatInputOptions = inputOptions => {
const result = [];
if (typeof Map !== 'undefined' && inputOptions instanceof Map) {
inputOptions.forEach((value, key) => {
let valueFormatted = value;
if (typeof valueFormatted === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
});
} else {
Object.keys(inputOptions).forEach(key => {
let valueFormatted = inputOptions[key];
if (typeof valueFormatted === 'object') {
// case of <optgroup>
valueFormatted = formatInputOptions(valueFormatted);
}
result.push([key, valueFormatted]);
});
}
return result;
};
const isSelected = (optionValue, inputValue) => {
return inputValue && inputValue.toString() === optionValue.toString();
};
const handleConfirmButtonClick = instance => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableButtons();
if (innerParams.input) {
handleConfirmOrDenyWithInput(instance, 'confirm');
} else {
confirm(instance, true);
}
};
const handleDenyButtonClick = instance => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableButtons();
if (innerParams.returnInputValueOnDeny) {
handleConfirmOrDenyWithInput(instance, 'deny');
} else {
deny(instance, false);
}
};
const handleCancelButtonClick = (instance, dismissWith) => {
instance.disableButtons();
dismissWith(DismissReason.cancel);
};
const handleConfirmOrDenyWithInput = (instance, type
/* 'confirm' | 'deny' */
) => {
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams.input) {
return error("The \"input\" parameter is needed to be set when using returnInputValueOn".concat(capitalizeFirstLetter(type)));
}
const inputValue = getInputValue(instance, innerParams);
if (innerParams.inputValidator) {
handleInputValidator(instance, inputValue, type);
} else if (!instance.getInput().checkValidity()) {
instance.enableButtons();
instance.showValidationMessage(innerParams.validationMessage);
} else if (type === 'deny') {
deny(instance, inputValue);
} else {
confirm(instance, inputValue);
}
};
const handleInputValidator = (instance, inputValue, type
/* 'confirm' | 'deny' */
) => {
const innerParams = privateProps.innerParams.get(instance);
instance.disableInput();
const validationPromise = Promise.resolve().then(() => asPromise(innerParams.inputValidator(inputValue, innerParams.validationMessage)));
validationPromise.then(validationMessage => {
instance.enableButtons();
instance.enableInput();
if (validationMessage) {
instance.showValidationMessage(validationMessage);
} else if (type === 'deny') {
deny(instance, inputValue);
} else {
confirm(instance, inputValue);
}
});
};
const deny = (instance, value) => {
const innerParams = privateProps.innerParams.get(instance || undefined);
if (innerParams.showLoaderOnDeny) {
showLoading(getDenyButton());
}
if (innerParams.preDeny) {
privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preDeny's promise is received
const preDenyPromise = Promise.resolve().then(() => asPromise(innerParams.preDeny(value, innerParams.validationMessage)));
preDenyPromise.then(preDenyValue => {
if (preDenyValue === false) {
instance.hideLoading();
} else {
instance.closePopup({
isDenied: true,
value: typeof preDenyValue === 'undefined' ? value : preDenyValue
});
}
}).catch(error$$1 => rejectWith(instance || undefined, error$$1));
} else {
instance.closePopup({
isDenied: true,
value
});
}
};
const succeedWith = (instance, value) => {
instance.closePopup({
isConfirmed: true,
value
});
};
const rejectWith = (instance, error$$1) => {
instance.rejectPromise(error$$1);
};
const confirm = (instance, value) => {
const innerParams = privateProps.innerParams.get(instance || undefined);
if (innerParams.showLoaderOnConfirm) {
showLoading();
}
if (innerParams.preConfirm) {
instance.resetValidationMessage();
privateProps.awaitingPromise.set(instance || undefined, true); // Flagging the instance as awaiting a promise so it's own promise's reject/resolve methods doesn't get destroyed until the result from this preConfirm's promise is received
const preConfirmPromise = Promise.resolve().then(() => asPromise(innerParams.preConfirm(value, innerParams.validationMessage)));
preConfirmPromise.then(preConfirmValue => {
if (isVisible(getValidationMessage()) || preConfirmValue === false) {
instance.hideLoading();
} else {
succeedWith(instance, typeof preConfirmValue === 'undefined' ? value : preConfirmValue);
}
}).catch(error$$1 => rejectWith(instance || undefined, error$$1));
} else {
succeedWith(instance, value);
}
};
const handlePopupClick = (instance, domCache, dismissWith) => {
const innerParams = privateProps.innerParams.get(instance);
if (innerParams.toast) {
handleToastClick(instance, domCache, dismissWith);
} else {
// Ignore click events that had mousedown on the popup but mouseup on the container
// This can happen when the user drags a slider
handleModalMousedown(domCache); // Ignore click events that had mousedown on the container but mouseup on the popup
handleContainerMousedown(domCache);
handleModalClick(instance, domCache, dismissWith);
}
};
const handleToastClick = (instance, domCache, dismissWith) => {
// Closing toast by internal click
domCache.popup.onclick = () => {
const innerParams = privateProps.innerParams.get(instance);
if (innerParams && (isAnyButtonShown(innerParams) || innerParams.timer || innerParams.input)) {
return;
}
dismissWith(DismissReason.close);
};
};
/**
* @param {*} innerParams
* @returns {boolean}
*/
const isAnyButtonShown = innerParams => {
return innerParams.showConfirmButton || innerParams.showDenyButton || innerParams.showCancelButton || innerParams.showCloseButton;
};
let ignoreOutsideClick = false;
const handleModalMousedown = domCache => {
domCache.popup.onmousedown = () => {
domCache.container.onmouseup = function (e) {
domCache.container.onmouseup = undefined; // We only check if the mouseup target is the container because usually it doesn't
// have any other direct children aside of the popup
if (e.target === domCache.container) {
ignoreOutsideClick = true;
}
};
};
};
const handleContainerMousedown = domCache => {
domCache.container.onmousedown = () => {
domCache.popup.onmouseup = function (e) {
domCache.popup.onmouseup = undefined; // We also need to check if the mouseup target is a child of the popup
if (e.target === domCache.popup || domCache.popup.contains(e.target)) {
ignoreOutsideClick = true;
}
};
};
};
const handleModalClick = (instance, domCache, dismissWith) => {
domCache.container.onclick = e => {
const innerParams = privateProps.innerParams.get(instance);
if (ignoreOutsideClick) {
ignoreOutsideClick = false;
return;
}
if (e.target === domCache.container && callIfFunction(innerParams.allowOutsideClick)) {
dismissWith(DismissReason.backdrop);
}
};
};
/*
* Global function to determine if SweetAlert2 popup is shown
*/
const isVisible$1 = () => {
return isVisible(getPopup());
};
/*
* Global function to click 'Confirm' button
*/
const clickConfirm = () => getConfirmButton() && getConfirmButton().click();
/*
* Global function to click 'Deny' button
*/
const clickDeny = () => getDenyButton() && getDenyButton().click();
/*
* Global function to click 'Cancel' button
*/
const clickCancel = () => getCancelButton() && getCancelButton().click();
const addKeydownHandler = (instance, globalState, innerParams, dismissWith) => {
if (globalState.keydownTarget && globalState.keydownHandlerAdded) {
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
if (!innerParams.toast) {
globalState.keydownHandler = e => keydownHandler(instance, e, dismissWith);
globalState.keydownTarget = innerParams.keydownListenerCapture ? window : getPopup();
globalState.keydownListenerCapture = innerParams.keydownListenerCapture;
globalState.keydownTarget.addEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = true;
}
}; // Focus handling
const setFocus = (innerParams, index, increment) => {
const focusableElements = getFocusableElements(); // search for visible elements and select the next possible match
if (focusableElements.length) {
index = index + increment; // rollover to first item
if (index === focusableElements.length) {
index = 0; // go to last item
} else if (index === -1) {
index = focusableElements.length - 1;
}
return focusableElements[index].focus();
} // no visible focusable elements, focus the popup
getPopup().focus();
};
const arrowKeysNextButton = ['ArrowRight', 'ArrowDown'];
const arrowKeysPreviousButton = ['ArrowLeft', 'ArrowUp'];
const keydownHandler = (instance, e, dismissWith) => {
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams) {
return; // This instance has already been destroyed
}
if (innerParams.stopKeydownPropagation) {
e.stopPropagation();
} // ENTER
if (e.key === 'Enter') {
handleEnter(instance, e, innerParams);
} // TAB
else if (e.key === 'Tab') {
handleTab(e, innerParams);
} // ARROWS - switch focus between buttons
else if ([...arrowKeysNextButton, ...arrowKeysPreviousButton].includes(e.key)) {
handleArrows(e.key);
} // ESC
else if (e.key === 'Escape') {
handleEsc(e, innerParams, dismissWith);
}
};
const handleEnter = (instance, e, innerParams) => {
// #2386 #720 #721
if (!callIfFunction(innerParams.allowEnterKey) || e.isComposing) {
return;
}
if (e.target && instance.getInput() && e.target.outerHTML === instance.getInput().outerHTML) {
if (['textarea', 'file'].includes(innerParams.input)) {
return; // do not submit
}
clickConfirm();
e.preventDefault();
}
};
const handleTab = (e, innerParams) => {
const targetElement = e.target;
const focusableElements = getFocusableElements();
let btnIndex = -1;
for (let i = 0; i < focusableElements.length; i++) {
if (targetElement === focusableElements[i]) {
btnIndex = i;
break;
}
} // Cycle to the next button
if (!e.shiftKey) {
setFocus(innerParams, btnIndex, 1);
} // Cycle to the prev button
else {
setFocus(innerParams, btnIndex, -1);
}
e.stopPropagation();
e.preventDefault();
};
const handleArrows = key => {
const confirmButton = getConfirmButton();
const denyButton = getDenyButton();
const cancelButton = getCancelButton();
if (![confirmButton, denyButton, cancelButton].includes(document.activeElement)) {
return;
}
const sibling = arrowKeysNextButton.includes(key) ? 'nextElementSibling' : 'previousElementSibling';
const buttonToFocus = document.activeElement[sibling];
if (buttonToFocus instanceof HTMLElement) {
buttonToFocus.focus();
}
};
const handleEsc = (e, innerParams, dismissWith) => {
if (callIfFunction(innerParams.allowEscapeKey)) {
e.preventDefault();
dismissWith(DismissReason.esc);
}
};
const isJqueryElement = elem => typeof elem === 'object' && elem.jquery;
const isElement = elem => elem instanceof Element || isJqueryElement(elem);
const argsToParams = args => {
const params = {};
if (typeof args[0] === 'object' && !isElement(args[0])) {
Object.assign(params, args[0]);
} else {
['title', 'html', 'icon'].forEach((name, index) => {
const arg = args[index];
if (typeof arg === 'string' || isElement(arg)) {
params[name] = arg;
} else if (arg !== undefined) {
error("Unexpected type of ".concat(name, "! Expected \"string\" or \"Element\", got ").concat(typeof arg));
}
});
}
return params;
};
function fire() {
const Swal = this; // eslint-disable-line @typescript-eslint/no-this-alias
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return new Swal(...args);
}
/**
* Returns an extended version of `Swal` containing `params` as defaults.
* Useful for reusing Swal configuration.
*
* For example:
*
* Before:
* const textPromptOptions = { input: 'text', showCancelButton: true }
* const {value: firstName} = await Swal.fire({ ...textPromptOptions, title: 'What is your first name?' })
* const {value: lastName} = await Swal.fire({ ...textPromptOptions, title: 'What is your last name?' })
*
* After:
* const TextPrompt = Swal.mixin({ input: 'text', showCancelButton: true })
* const {value: firstName} = await TextPrompt('What is your first name?')
* const {value: lastName} = await TextPrompt('What is your last name?')
*
* @param mixinParams
*/
function mixin(mixinParams) {
class MixinSwal extends this {
_main(params, priorityMixinParams) {
return super._main(params, Object.assign({}, mixinParams, priorityMixinParams));
}
}
return MixinSwal;
}
/**
* If `timer` parameter is set, returns number of milliseconds of timer remained.
* Otherwise, returns undefined.
*/
const getTimerLeft = () => {
return globalState.timeout && globalState.timeout.getTimerLeft();
};
/**
* Stop timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
const stopTimer = () => {
if (globalState.timeout) {
stopTimerProgressBar();
return globalState.timeout.stop();
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
const resumeTimer = () => {
if (globalState.timeout) {
const remaining = globalState.timeout.start();
animateTimerProgressBar(remaining);
return remaining;
}
};
/**
* Resume timer. Returns number of milliseconds of timer remained.
* If `timer` parameter isn't set, returns undefined.
*/
const toggleTimer = () => {
const timer = globalState.timeout;
return timer && (timer.running ? stopTimer() : resumeTimer());
};
/**
* Increase timer. Returns number of milliseconds of an updated timer.
* If `timer` parameter isn't set, returns undefined.
*/
const increaseTimer = n => {
if (globalState.timeout) {
const remaining = globalState.timeout.increase(n);
animateTimerProgressBar(remaining, true);
return remaining;
}
};
/**
* Check if timer is running. Returns true if timer is running
* or false if timer is paused or stopped.
* If `timer` parameter isn't set, returns undefined
*/
const isTimerRunning = () => {
return globalState.timeout && globalState.timeout.isRunning();
};
let bodyClickListenerAdded = false;
const clickHandlers = {};
function bindClickHandler() {
let attr = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'data-swal-template';
clickHandlers[attr] = this;
if (!bodyClickListenerAdded) {
document.body.addEventListener('click', bodyClickListener);
bodyClickListenerAdded = true;
}
}
const bodyClickListener = event => {
for (let el = event.target; el && el !== document; el = el.parentNode) {
for (const attr in clickHandlers) {
const template = el.getAttribute(attr);
if (template) {
clickHandlers[attr].fire({
template
});
return;
}
}
}
};
var staticMethods = /*#__PURE__*/Object.freeze({
isValidParameter: isValidParameter,
isUpdatableParameter: isUpdatableParameter,
isDeprecatedParameter: isDeprecatedParameter,
argsToParams: argsToParams,
isVisible: isVisible$1,
clickConfirm: clickConfirm,
clickDeny: clickDeny,
clickCancel: clickCancel,
getContainer: getContainer,
getPopup: getPopup,
getTitle: getTitle,
getHtmlContainer: getHtmlContainer,
getImage: getImage,
getIcon: getIcon,
getInputLabel: getInputLabel,
getCloseButton: getCloseButton,
getActions: getActions,
getConfirmButton: getConfirmButton,
getDenyButton: getDenyButton,
getCancelButton: getCancelButton,
getLoader: getLoader,
getFooter: getFooter,
getTimerProgressBar: getTimerProgressBar,
getFocusableElements: getFocusableElements,
getValidationMessage: getValidationMessage,
isLoading: isLoading,
fire: fire,
mixin: mixin,
showLoading: showLoading,
enableLoading: showLoading,
getTimerLeft: getTimerLeft,
stopTimer: stopTimer,
resumeTimer: resumeTimer,
toggleTimer: toggleTimer,
increaseTimer: increaseTimer,
isTimerRunning: isTimerRunning,
bindClickHandler: bindClickHandler
});
/**
* Hides loader and shows back the button which was hidden by .showLoading()
*/
function hideLoading() {
// do nothing if popup is closed
const innerParams = privateProps.innerParams.get(this);
if (!innerParams) {
return;
}
const domCache = privateProps.domCache.get(this);
hide(domCache.loader);
if (isToast()) {
if (innerParams.icon) {
show(getIcon());
}
} else {
showRelatedButton(domCache);
}
removeClass([domCache.popup, domCache.actions], swalClasses.loading);
domCache.popup.removeAttribute('aria-busy');
domCache.popup.removeAttribute('data-loading');
domCache.confirmButton.disabled = false;
domCache.denyButton.disabled = false;
domCache.cancelButton.disabled = false;
}
const showRelatedButton = domCache => {
const buttonToReplace = domCache.popup.getElementsByClassName(domCache.loader.getAttribute('data-button-to-replace'));
if (buttonToReplace.length) {
show(buttonToReplace[0], 'inline-block');
} else if (allButtonsAreHidden()) {
hide(domCache.actions);
}
};
/**
* Gets the input DOM node, this method works with input parameter.
* @returns {HTMLElement | null}
*/
function getInput$1(instance) {
const innerParams = privateProps.innerParams.get(instance || this);
const domCache = privateProps.domCache.get(instance || this);
if (!domCache) {
return null;
}
return getInput(domCache.popup, innerParams.input);
}
/**
* This module contains `WeakMap`s for each effectively-"private property" that a `Swal` has.
* For example, to set the private property "foo" of `this` to "bar", you can `privateProps.foo.set(this, 'bar')`
* This is the approach that Babel will probably take to implement private methods/fields
* https://github.com/tc39/proposal-private-methods
* https://github.com/babel/babel/pull/7555
* Once we have the changes from that PR in Babel, and our core class fits reasonable in *one module*
* then we can use that language feature.
*/
var privateMethods = {
swalPromiseResolve: new WeakMap(),
swalPromiseReject: new WeakMap()
};
/*
* Instance method to close sweetAlert
*/
function removePopupAndResetState(instance, container, returnFocus, didClose) {
if (isToast()) {
triggerDidCloseAndDispose(instance, didClose);
} else {
restoreActiveElement(returnFocus).then(() => triggerDidCloseAndDispose(instance, didClose));
globalState.keydownTarget.removeEventListener('keydown', globalState.keydownHandler, {
capture: globalState.keydownListenerCapture
});
globalState.keydownHandlerAdded = false;
}
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); // workaround for #2088
// for some reason removing the container in Safari will scroll the document to bottom
if (isSafari) {
container.setAttribute('style', 'display:none !important');
container.removeAttribute('class');
container.innerHTML = '';
} else {
container.remove();
}
if (isModal()) {
undoScrollbar();
undoIOSfix();
unsetAriaHidden();
}
removeBodyClasses();
}
function removeBodyClasses() {
removeClass([document.documentElement, document.body], [swalClasses.shown, swalClasses['height-auto'], swalClasses['no-backdrop'], swalClasses['toast-shown']]);
}
function close(resolveValue) {
resolveValue = prepareResolveValue(resolveValue);
const swalPromiseResolve = privateMethods.swalPromiseResolve.get(this);
const didClose = triggerClosePopup(this);
if (this.isAwaitingPromise()) {
// A swal awaiting for a promise (after a click on Confirm or Deny) cannot be dismissed anymore #2335
if (!resolveValue.isDismissed) {
handleAwaitingPromise(this);
swalPromiseResolve(resolveValue);
}
} else if (didClose) {
// Resolve Swal promise
swalPromiseResolve(resolveValue);
}
}
function isAwaitingPromise() {
return !!privateProps.awaitingPromise.get(this);
}
const triggerClosePopup = instance => {
const popup = getPopup();
if (!popup) {
return false;
}
const innerParams = privateProps.innerParams.get(instance);
if (!innerParams || hasClass(popup, innerParams.hideClass.popup)) {
return false;
}
removeClass(popup, innerParams.showClass.popup);
addClass(popup, innerParams.hideClass.popup);
const backdrop = getContainer();
removeClass(backdrop, innerParams.showClass.backdrop);
addClass(backdrop, innerParams.hideClass.backdrop);
handlePopupAnimation(instance, popup, innerParams);
return true;
};
function rejectPromise(error) {
const rejectPromise = privateMethods.swalPromiseReject.get(this);
handleAwaitingPromise(this);
if (rejectPromise) {
// Reject Swal promise
rejectPromise(error);
}
}
const handleAwaitingPromise = instance => {
if (instance.isAwaitingPromise()) {
privateProps.awaitingPromise.delete(instance); // The instance might have been previously partly destroyed, we must resume the destroy process in this case #2335
if (!privateProps.innerParams.get(instance)) {
instance._destroy();
}
}
};
const prepareResolveValue = resolveValue => {
// When user calls Swal.close()
if (typeof resolveValue === 'undefined') {
return {
isConfirmed: false,
isDenied: false,
isDismissed: true
};
}
return Object.assign({
isConfirmed: false,
isDenied: false,
isDismissed: false
}, resolveValue);
};
const handlePopupAnimation = (instance, popup, innerParams) => {
const container = getContainer(); // If animation is supported, animate
const animationIsSupported = animationEndEvent && hasCssAnimation(popup);
if (typeof innerParams.willClose === 'function') {
innerParams.willClose(popup);
}
if (animationIsSupported) {
animatePopup(instance, popup, container, innerParams.returnFocus, innerParams.didClose);
} else {
// Otherwise, remove immediately
removePopupAndResetState(instance, container, innerParams.returnFocus, innerParams.didClose);
}
};
const animatePopup = (instance, popup, container, returnFocus, didClose) => {
globalState.swalCloseEventFinishedCallback = removePopupAndResetState.bind(null, instance, container, returnFocus, didClose);
popup.addEventListener(animationEndEvent, function (e) {
if (e.target === popup) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
}
});
};
const triggerDidCloseAndDispose = (instance, didClose) => {
setTimeout(() => {
if (typeof didClose === 'function') {
didClose.bind(instance.params)();
}
instance._destroy();
});
};
function setButtonsDisabled(instance, buttons, disabled) {
const domCache = privateProps.domCache.get(instance);
buttons.forEach(button => {
domCache[button].disabled = disabled;
});
}
function setInputDisabled(input, disabled) {
if (!input) {
return false;
}
if (input.type === 'radio') {
const radiosContainer = input.parentNode.parentNode;
const radios = radiosContainer.querySelectorAll('input');
for (let i = 0; i < radios.length; i++) {
radios[i].disabled = disabled;
}
} else {
input.disabled = disabled;
}
}
function enableButtons() {
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], false);
}
function disableButtons() {
setButtonsDisabled(this, ['confirmButton', 'denyButton', 'cancelButton'], true);
}
function enableInput() {
return setInputDisabled(this.getInput(), false);
}
function disableInput() {
return setInputDisabled(this.getInput(), true);
}
function showValidationMessage(error) {
const domCache = privateProps.domCache.get(this);
const params = privateProps.innerParams.get(this);
setInnerHtml(domCache.validationMessage, error);
domCache.validationMessage.className = swalClasses['validation-message'];
if (params.customClass && params.customClass.validationMessage) {
addClass(domCache.validationMessage, params.customClass.validationMessage);
}
show(domCache.validationMessage);
const input = this.getInput();
if (input) {
input.setAttribute('aria-invalid', true);
input.setAttribute('aria-describedby', swalClasses['validation-message']);
focusInput(input);
addClass(input, swalClasses.inputerror);
}
} // Hide block with validation message
function resetValidationMessage$1() {
const domCache = privateProps.domCache.get(this);
if (domCache.validationMessage) {
hide(domCache.validationMessage);
}
const input = this.getInput();
if (input) {
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedby');
removeClass(input, swalClasses.inputerror);
}
}
function getProgressSteps$1() {
const domCache = privateProps.domCache.get(this);
return domCache.progressSteps;
}
/**
* Updates popup parameters.
*/
function update(params) {
const popup = getPopup();
const innerParams = privateProps.innerParams.get(this);
if (!popup || hasClass(popup, innerParams.hideClass.popup)) {
return warn("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");
}
const validUpdatableParams = filterValidParams(params);
const updatedParams = Object.assign({}, innerParams, validUpdatableParams);
render(this, updatedParams);
privateProps.innerParams.set(this, updatedParams);
Object.defineProperties(this, {
params: {
value: Object.assign({}, this.params, params),
writable: false,
enumerable: true
}
});
}
const filterValidParams = params => {
const validUpdatableParams = {};
Object.keys(params).forEach(param => {
if (isUpdatableParameter(param)) {
validUpdatableParams[param] = params[param];
} else {
warn("Invalid parameter to update: \"".concat(param, "\". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md"));
}
});
return validUpdatableParams;
};
function _destroy() {
const domCache = privateProps.domCache.get(this);
const innerParams = privateProps.innerParams.get(this);
if (!innerParams) {
disposeWeakMaps(this); // The WeakMaps might have been partly destroyed, we must recall it to dispose any remaining WeakMaps #2335
return; // This instance has already been destroyed
} // Check if there is another Swal closing
if (domCache.popup && globalState.swalCloseEventFinishedCallback) {
globalState.swalCloseEventFinishedCallback();
delete globalState.swalCloseEventFinishedCallback;
} // Check if there is a swal disposal defer timer
if (globalState.deferDisposalTimer) {
clearTimeout(globalState.deferDisposalTimer);
delete globalState.deferDisposalTimer;
}
if (typeof innerParams.didDestroy === 'function') {
innerParams.didDestroy();
}
disposeSwal(this);
}
const disposeSwal = instance => {
disposeWeakMaps(instance); // Unset this.params so GC will dispose it (#1569)
delete instance.params; // Unset globalState props so GC will dispose globalState (#1569)
delete globalState.keydownHandler;
delete globalState.keydownTarget; // Unset currentInstance
delete globalState.currentInstance;
};
const disposeWeakMaps = instance => {
// If the current instance is awaiting a promise result, we keep the privateMethods to call them once the promise result is retrieved #2335
if (instance.isAwaitingPromise()) {
unsetWeakMaps(privateProps, instance);
privateProps.awaitingPromise.set(instance, true);
} else {
unsetWeakMaps(privateMethods, instance);
unsetWeakMaps(privateProps, instance);
}
};
const unsetWeakMaps = (obj, instance) => {
for (const i in obj) {
obj[i].delete(instance);
}
};
var instanceMethods = /*#__PURE__*/Object.freeze({
hideLoading: hideLoading,
disableLoading: hideLoading,
getInput: getInput$1,
close: close,
isAwaitingPromise: isAwaitingPromise,
rejectPromise: rejectPromise,
closePopup: close,
closeModal: close,
closeToast: close,
enableButtons: enableButtons,
disableButtons: disableButtons,
enableInput: enableInput,
disableInput: disableInput,
showValidationMessage: showValidationMessage,
resetValidationMessage: resetValidationMessage$1,
getProgressSteps: getProgressSteps$1,
update: update,
_destroy: _destroy
});
let currentInstance;
class SweetAlert {
constructor() {
// Prevent run in Node env
if (typeof window === 'undefined') {
return;
}
currentInstance = this; // @ts-ignore
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
const outerParams = Object.freeze(this.constructor.argsToParams(args));
Object.defineProperties(this, {
params: {
value: outerParams,
writable: false,
enumerable: true,
configurable: true
}
}); // @ts-ignore
const promise = this._main(this.params);
privateProps.promise.set(this, promise);
}
_main(userParams) {
let mixinParams = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
showWarningsForParams(Object.assign({}, mixinParams, userParams));
if (globalState.currentInstance) {
globalState.currentInstance._destroy();
if (isModal()) {
unsetAriaHidden();
}
}
globalState.currentInstance = this;
const innerParams = prepareParams(userParams, mixinParams);
setParameters(innerParams);
Object.freeze(innerParams); // clear the previous timer
if (globalState.timeout) {
globalState.timeout.stop();
delete globalState.timeout;
} // clear the restore focus timeout
clearTimeout(globalState.restoreFocusTimeout);
const domCache = populateDomCache(this);
render(this, innerParams);
privateProps.innerParams.set(this, innerParams);
return swalPromise(this, domCache, innerParams);
} // `catch` cannot be the name of a module export, so we define our thenable methods here instead
then(onFulfilled) {
const promise = privateProps.promise.get(this);
return promise.then(onFulfilled);
}
finally(onFinally) {
const promise = privateProps.promise.get(this);
return promise.finally(onFinally);
}
}
const swalPromise = (instance, domCache, innerParams) => {
return new Promise((resolve, reject) => {
// functions to handle all closings/dismissals
const dismissWith = dismiss => {
instance.closePopup({
isDismissed: true,
dismiss
});
};
privateMethods.swalPromiseResolve.set(instance, resolve);
privateMethods.swalPromiseReject.set(instance, reject);
domCache.confirmButton.onclick = () => handleConfirmButtonClick(instance);
domCache.denyButton.onclick = () => handleDenyButtonClick(instance);
domCache.cancelButton.onclick = () => handleCancelButtonClick(instance, dismissWith);
domCache.closeButton.onclick = () => dismissWith(DismissReason.close);
handlePopupClick(instance, domCache, dismissWith);
addKeydownHandler(instance, globalState, innerParams, dismissWith);
handleInputOptionsAndValue(instance, innerParams);
openPopup(innerParams);
setupTimer(globalState, innerParams, dismissWith);
initFocus(domCache, innerParams); // Scroll container to top on open (#1247, #1946)
setTimeout(() => {
domCache.container.scrollTop = 0;
});
});
};
const prepareParams = (userParams, mixinParams) => {
const templateParams = getTemplateParams(userParams);
const params = Object.assign({}, defaultParams, mixinParams, templateParams, userParams); // precedence is described in #2131
params.showClass = Object.assign({}, defaultParams.showClass, params.showClass);
params.hideClass = Object.assign({}, defaultParams.hideClass, params.hideClass);
return params;
};
const populateDomCache = instance => {
const domCache = {
popup: getPopup(),
container: getContainer(),
actions: getActions(),
confirmButton: getConfirmButton(),
denyButton: getDenyButton(),
cancelButton: getCancelButton(),
loader: getLoader(),
closeButton: getCloseButton(),
validationMessage: getValidationMessage(),
progressSteps: getProgressSteps()
};
privateProps.domCache.set(instance, domCache);
return domCache;
};
const setupTimer = (globalState$$1, innerParams, dismissWith) => {
const timerProgressBar = getTimerProgressBar();
hide(timerProgressBar);
if (innerParams.timer) {
globalState$$1.timeout = new Timer(() => {
dismissWith('timer');
delete globalState$$1.timeout;
}, innerParams.timer);
if (innerParams.timerProgressBar) {
show(timerProgressBar);
applyCustomClass(timerProgressBar, innerParams, 'timerProgressBar');
setTimeout(() => {
if (globalState$$1.timeout && globalState$$1.timeout.running) {
// timer can be already stopped or unset at this point
animateTimerProgressBar(innerParams.timer);
}
});
}
}
};
const initFocus = (domCache, innerParams) => {
if (innerParams.toast) {
return;
}
if (!callIfFunction(innerParams.allowEnterKey)) {
return blurActiveElement();
}
if (!focusButton(domCache, innerParams)) {
setFocus(innerParams, -1, 1);
}
};
const focusButton = (domCache, innerParams) => {
if (innerParams.focusDeny && isVisible(domCache.denyButton)) {
domCache.denyButton.focus();
return true;
}
if (innerParams.focusCancel && isVisible(domCache.cancelButton)) {
domCache.cancelButton.focus();
return true;
}
if (innerParams.focusConfirm && isVisible(domCache.confirmButton)) {
domCache.confirmButton.focus();
return true;
}
return false;
};
const blurActiveElement = () => {
if (document.activeElement instanceof HTMLElement && typeof document.activeElement.blur === 'function') {
document.activeElement.blur();
}
}; // Assign instance methods from src/instanceMethods/*.js to prototype
Object.assign(SweetAlert.prototype, instanceMethods); // Assign static methods from src/staticMethods/*.js to constructor
Object.assign(SweetAlert, staticMethods); // Proxy to instance methods to constructor, for now, for backwards compatibility
Object.keys(instanceMethods).forEach(key => {
SweetAlert[key] = function () {
if (currentInstance) {
return currentInstance[key](...arguments);
}
};
});
SweetAlert.DismissReason = DismissReason;
SweetAlert.version = '11.4.0';
const Swal = SweetAlert; // @ts-ignore
Swal.default = Swal;
return Swal;
}));
if (typeof this !== 'undefined' && this.Sweetalert2){ this.swal = this.sweetAlert = this.Swal = this.SweetAlert = this.Sweetalert2}
"undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,".swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4!important;grid-row:1/4!important;grid-template-columns:1fr 99fr 1fr;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 1px rgba(0,0,0,.075),0 1px 2px rgba(0,0,0,.075),1px 2px 4px rgba(0,0,0,.075),1px 3px 8px rgba(0,0,0,.075),2px 4px 16px rgba(0,0,0,.075);pointer-events:all}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:.5em 1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:700}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.5em;padding:0 .5em}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-container{display:grid;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;box-sizing:border-box;grid-template-areas:\"top-start top top-end\" \"center-start center center-end\" \"bottom-start bottom-center bottom-end\";grid-template-rows:minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto) minmax(-webkit-min-content,auto);grid-template-rows:minmax(min-content,auto) minmax(min-content,auto) minmax(min-content,auto);height:100%;padding:.625em;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:0 0!important}.swal2-container.swal2-bottom-start,.swal2-container.swal2-center-start,.swal2-container.swal2-top-start{grid-template-columns:minmax(0,1fr) auto auto}.swal2-container.swal2-bottom,.swal2-container.swal2-center,.swal2-container.swal2-top{grid-template-columns:auto minmax(0,1fr) auto}.swal2-container.swal2-bottom-end,.swal2-container.swal2-center-end,.swal2-container.swal2-top-end{grid-template-columns:auto auto minmax(0,1fr)}.swal2-container.swal2-top-start>.swal2-popup{align-self:start}.swal2-container.swal2-top>.swal2-popup{grid-column:2;align-self:start;justify-self:center}.swal2-container.swal2-top-end>.swal2-popup,.swal2-container.swal2-top-right>.swal2-popup{grid-column:3;align-self:start;justify-self:end}.swal2-container.swal2-center-left>.swal2-popup,.swal2-container.swal2-center-start>.swal2-popup{grid-row:2;align-self:center}.swal2-container.swal2-center>.swal2-popup{grid-column:2;grid-row:2;align-self:center;justify-self:center}.swal2-container.swal2-center-end>.swal2-popup,.swal2-container.swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;align-self:center;justify-self:end}.swal2-container.swal2-bottom-left>.swal2-popup,.swal2-container.swal2-bottom-start>.swal2-popup{grid-column:1;grid-row:3;align-self:end}.swal2-container.swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;justify-self:center;align-self:end}.swal2-container.swal2-bottom-end>.swal2-popup,.swal2-container.swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;align-self:end;justify-self:end}.swal2-container.swal2-grow-fullscreen>.swal2-popup,.swal2-container.swal2-grow-row>.swal2-popup{grid-column:1/4;width:100%}.swal2-container.swal2-grow-column>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}.swal2-container.swal2-no-transition{transition:none!important}.swal2-popup{display:none;position:relative;box-sizing:border-box;grid-template-columns:minmax(0,100%);width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;color:#545454;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-title{position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:inherit;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:auto;margin:1.25em auto 0;padding:0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 transparent #2778c4 transparent}.swal2-styled{margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px transparent;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#7066e0;color:#fff;font-size:1em}.swal2-styled.swal2-confirm:focus{box-shadow:0 0 0 3px rgba(112,102,224,.5)}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#dc3741;color:#fff;font-size:1em}.swal2-styled.swal2-deny:focus{box-shadow:0 0 0 3px rgba(220,55,65,.5)}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#6e7881;color:#fff;font-size:1em}.swal2-styled.swal2-cancel:focus{box-shadow:0 0 0 3px rgba(110,120,129,.5)}.swal2-styled.swal2-default-outline:focus{box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled:focus{outline:0}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:inherit;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto!important;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:2em auto 1em}.swal2-close{z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:0 0;color:#ccc;font-family:serif;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}.swal2-close:hover{transform:none;background:0 0;color:#f27474}.swal2-close:focus{outline:0;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-html-container{z-index:1;justify-content:center;margin:1em 1.6em .3em;padding:0;overflow:auto;color:inherit;font-size:1.125em;font-weight:400;line-height:normal;text-align:center;word-wrap:break-word;word-break:break-word}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em 2em 3px}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid #d9d9d9;border-radius:.1875em;background:inherit;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px transparent;color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em 2em 3px;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-file{width:75%;margin-right:auto;margin-left:auto;background:inherit;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:inherit;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{flex-shrink:0;margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto 0}.swal2-validation-message{align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:.25em solid transparent;border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-warning.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-warning.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .5s;animation:swal2-animate-i-mark .5s}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-info.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-info.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-i-mark .8s;animation:swal2-animate-i-mark .8s}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-question.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-question.swal2-icon-show .swal2-icon-content{-webkit-animation:swal2-animate-question-mark .8s;animation:swal2-animate-question-mark .8s}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:inherit;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@-webkit-keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@-webkit-keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@-webkit-keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@-webkit-keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@keyframes swal2-animate-question-mark{0%{transform:rotateY(-360deg)}100%{transform:rotateY(0)}}@-webkit-keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-i-mark{0%{transform:rotateZ(45deg);opacity:0}25%{transform:rotateZ(-25deg);opacity:.4}50%{transform:rotateZ(15deg);opacity:.8}75%{transform:rotateZ(-5deg);opacity:1}100%{transform:rotateX(0);opacity:1}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-container{background-color:transparent!important;pointer-events:none}body.swal2-no-backdrop .swal2-container .swal2-popup{pointer-events:all}body.swal2-no-backdrop .swal2-container .swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:transparent;pointer-events:none}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}");
|
2881099/FreeSql.AdminLTE
| 42,910 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/sweetalert2/sweetalert2.min.js
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self).Sweetalert2=t()}(this,function(){"use strict";const t="SweetAlert2:",y=e=>e.charAt(0).toUpperCase()+e.slice(1),i=e=>Array.prototype.slice.call(e),a=e=>{console.warn("".concat(t," ").concat("object"==typeof e?e.join(" "):e))},v=e=>{console.error("".concat(t," ").concat(e))},n=[],o=(e,t)=>{e='"'.concat(e,'" is deprecated and will be removed in the next major release. Please use "').concat(t,'" instead.'),n.includes(e)||(n.push(e),a(e))},w=e=>"function"==typeof e?e():e,C=e=>e&&"function"==typeof e.toPromise,k=e=>C(e)?e.toPromise():Promise.resolve(e),A=e=>e&&Promise.resolve(e)===e,r={title:"",titleText:"",text:"",html:"",footer:"",icon:void 0,iconColor:void 0,iconHtml:void 0,template:void 0,toast:!1,showClass:{popup:"swal2-show",backdrop:"swal2-backdrop-show",icon:"swal2-icon-show"},hideClass:{popup:"swal2-hide",backdrop:"swal2-backdrop-hide",icon:"swal2-icon-hide"},customClass:{},target:"body",color:void 0,backdrop:!0,heightAuto:!0,allowOutsideClick:!0,allowEscapeKey:!0,allowEnterKey:!0,stopKeydownPropagation:!0,keydownListenerCapture:!1,showConfirmButton:!0,showDenyButton:!1,showCancelButton:!1,preConfirm:void 0,preDeny:void 0,confirmButtonText:"OK",confirmButtonAriaLabel:"",confirmButtonColor:void 0,denyButtonText:"No",denyButtonAriaLabel:"",denyButtonColor:void 0,cancelButtonText:"Cancel",cancelButtonAriaLabel:"",cancelButtonColor:void 0,buttonsStyling:!0,reverseButtons:!1,focusConfirm:!0,focusDeny:!1,focusCancel:!1,returnFocus:!0,showCloseButton:!1,closeButtonHtml:"×",closeButtonAriaLabel:"Close this dialog",loaderHtml:"",showLoaderOnConfirm:!1,showLoaderOnDeny:!1,imageUrl:void 0,imageWidth:void 0,imageHeight:void 0,imageAlt:"",timer:void 0,timerProgressBar:!1,width:void 0,padding:void 0,background:void 0,input:void 0,inputPlaceholder:"",inputLabel:"",inputValue:"",inputOptions:{},inputAutoTrim:!0,inputAttributes:{},inputValidator:void 0,returnInputValueOnDeny:!1,validationMessage:void 0,grow:!1,position:"center",progressSteps:[],currentProgressStep:void 0,progressStepsDistance:void 0,willOpen:void 0,didOpen:void 0,didRender:void 0,willClose:void 0,didClose:void 0,didDestroy:void 0,scrollbarPadding:!0},s=["allowEscapeKey","allowOutsideClick","background","buttonsStyling","cancelButtonAriaLabel","cancelButtonColor","cancelButtonText","closeButtonAriaLabel","closeButtonHtml","color","confirmButtonAriaLabel","confirmButtonColor","confirmButtonText","currentProgressStep","customClass","denyButtonAriaLabel","denyButtonColor","denyButtonText","didClose","didDestroy","footer","hideClass","html","icon","iconColor","iconHtml","imageAlt","imageHeight","imageUrl","imageWidth","preConfirm","preDeny","progressSteps","returnFocus","reverseButtons","showCancelButton","showCloseButton","showConfirmButton","showDenyButton","text","title","titleText","willClose"],c={},P=["allowOutsideClick","allowEnterKey","backdrop","focusConfirm","focusDeny","focusCancel","returnFocus","heightAuto","keydownListenerCapture"],B=e=>Object.prototype.hasOwnProperty.call(r,e),x=e=>-1!==s.indexOf(e),E=e=>c[e],T=e=>{!e.backdrop&&e.allowOutsideClick&&a('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`');for(const n in e)t=n,B(t)||a('Unknown parameter "'.concat(t,'"')),e.toast&&(t=n,P.includes(t)&&a('The parameter "'.concat(t,'" is incompatible with toasts'))),t=n,E(t)&&o(t,E(t));var t};var e=e=>{const t={};for(const n in e)t[e[n]]="swal2-"+e[n];return t};const p=e(["container","shown","height-auto","iosfix","popup","modal","no-backdrop","no-transition","toast","toast-shown","show","hide","close","title","html-container","actions","confirm","deny","cancel","default-outline","footer","icon","icon-content","image","input","file","range","select","radio","checkbox","label","textarea","inputerror","input-label","validation-message","progress-steps","active-progress-step","progress-step","progress-step-line","loader","loading","styled","top","top-start","top-end","top-left","top-right","center","center-start","center-end","center-left","center-right","bottom","bottom-start","bottom-end","bottom-left","bottom-right","grow-row","grow-column","grow-fullscreen","rtl","timer-progress-bar","timer-progress-bar-container","scrollbar-measure","icon-success","icon-warning","icon-info","icon-question","icon-error"]),S=e(["success","warning","info","question","error"]),m=()=>document.body.querySelector(".".concat(p.container)),L=e=>{const t=m();return t?t.querySelector(e):null},O=e=>L(".".concat(e)),g=()=>O(p.popup),j=()=>O(p.icon),M=()=>O(p.title),D=()=>O(p["html-container"]),I=()=>O(p.image),H=()=>O(p["progress-steps"]),q=()=>O(p["validation-message"]),V=()=>L(".".concat(p.actions," .").concat(p.confirm)),N=()=>L(".".concat(p.actions," .").concat(p.deny));const R=()=>L(".".concat(p.loader)),F=()=>L(".".concat(p.actions," .").concat(p.cancel)),U=()=>O(p.actions),W=()=>O(p.footer),z=()=>O(p["timer-progress-bar"]),_=()=>O(p.close),K=()=>{const e=i(g().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')).sort((e,t)=>{e=parseInt(e.getAttribute("tabindex")),t=parseInt(t.getAttribute("tabindex"));return t<e?1:e<t?-1:0});var t=i(g().querySelectorAll('\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex="0"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n')).filter(e=>"-1"!==e.getAttribute("tabindex"));return(t=>{const n=[];for(let e=0;e<t.length;e++)-1===n.indexOf(t[e])&&n.push(t[e]);return n})(e.concat(t)).filter(e=>ce(e))},Y=()=>!$(document.body,p["toast-shown"])&&!$(document.body,p["no-backdrop"]),Z=()=>g()&&$(g(),p.toast);function J(e){var t=1<arguments.length&&void 0!==arguments[1]&&arguments[1];const n=z();ce(n)&&(t&&(n.style.transition="none",n.style.width="100%"),setTimeout(()=>{n.style.transition="width ".concat(e/1e3,"s linear"),n.style.width="0%"},10))}const X={previousBodyPadding:null},l=(t,e)=>{if(t.textContent="",e){const n=new DOMParser,o=n.parseFromString(e,"text/html");i(o.querySelector("head").childNodes).forEach(e=>{t.appendChild(e)}),i(o.querySelector("body").childNodes).forEach(e=>{t.appendChild(e)})}},$=(t,e)=>{if(!e)return!1;var n=e.split(/\s+/);for(let e=0;e<n.length;e++)if(!t.classList.contains(n[e]))return!1;return!0},G=(t,n)=>{i(t.classList).forEach(e=>{Object.values(p).includes(e)||Object.values(S).includes(e)||Object.values(n.showClass).includes(e)||t.classList.remove(e)})},Q=(e,t,n)=>{if(G(e,t),t.customClass&&t.customClass[n]){if("string"!=typeof t.customClass[n]&&!t.customClass[n].forEach)return a("Invalid type of customClass.".concat(n,'! Expected string or iterable object, got "').concat(typeof t.customClass[n],'"'));u(e,t.customClass[n])}},ee=(e,t)=>{if(!t)return null;switch(t){case"select":case"textarea":case"file":return e.querySelector(".".concat(p.popup," > .").concat(p[t]));case"checkbox":return e.querySelector(".".concat(p.popup," > .").concat(p.checkbox," input"));case"radio":return e.querySelector(".".concat(p.popup," > .").concat(p.radio," input:checked"))||e.querySelector(".".concat(p.popup," > .").concat(p.radio," input:first-child"));case"range":return e.querySelector(".".concat(p.popup," > .").concat(p.range," input"));default:return e.querySelector(".".concat(p.popup," > .").concat(p.input))}},te=e=>{var t;e.focus(),"file"!==e.type&&(t=e.value,e.value="",e.value=t)},ne=(e,t,n)=>{e&&t&&(t="string"==typeof t?t.split(/\s+/).filter(Boolean):t).forEach(t=>{Array.isArray(e)?e.forEach(e=>{n?e.classList.add(t):e.classList.remove(t)}):n?e.classList.add(t):e.classList.remove(t)})},u=(e,t)=>{ne(e,t,!0)},oe=(e,t)=>{ne(e,t,!1)},ie=(e,t)=>{var n=i(e.childNodes);for(let e=0;e<n.length;e++)if($(n[e],t))return n[e]},ae=(e,t,n)=>{(n=n==="".concat(parseInt(n))?parseInt(n):n)||0===parseInt(n)?e.style[t]="number"==typeof n?"".concat(n,"px"):n:e.style.removeProperty(t)},d=function(e){e.style.display=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"flex"},h=e=>{e.style.display="none"},re=(e,t,n,o)=>{const i=e.querySelector(t);i&&(i.style[n]=o)},se=(e,t,n)=>{t?d(e,n):h(e)},ce=e=>!(!e||!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)),le=()=>!ce(V())&&!ce(N())&&!ce(F()),ue=e=>!!(e.scrollHeight>e.clientHeight),de=e=>{const t=window.getComputedStyle(e);var e=parseFloat(t.getPropertyValue("animation-duration")||"0"),n=parseFloat(t.getPropertyValue("transition-duration")||"0");return 0<e||0<n},pe=()=>"undefined"==typeof window||"undefined"==typeof document,me=100,f={},ge=()=>{f.previousActiveElement&&f.previousActiveElement.focus?(f.previousActiveElement.focus(),f.previousActiveElement=null):document.body&&document.body.focus()},he=o=>new Promise(e=>{if(!o)return e();var t=window.scrollX,n=window.scrollY;f.restoreFocusTimeout=setTimeout(()=>{ge(),e()},me),window.scrollTo(t,n)}),fe='\n <div aria-labelledby="'.concat(p.title,'" aria-describedby="').concat(p["html-container"],'" class="').concat(p.popup,'" tabindex="-1">\n <button type="button" class="').concat(p.close,'"></button>\n <ul class="').concat(p["progress-steps"],'"></ul>\n <div class="').concat(p.icon,'"></div>\n <img class="').concat(p.image,'" />\n <h2 class="').concat(p.title,'" id="').concat(p.title,'"></h2>\n <div class="').concat(p["html-container"],'" id="').concat(p["html-container"],'"></div>\n <input class="').concat(p.input,'" />\n <input type="file" class="').concat(p.file,'" />\n <div class="').concat(p.range,'">\n <input type="range" />\n <output></output>\n </div>\n <select class="').concat(p.select,'"></select>\n <div class="').concat(p.radio,'"></div>\n <label for="').concat(p.checkbox,'" class="').concat(p.checkbox,'">\n <input type="checkbox" />\n <span class="').concat(p.label,'"></span>\n </label>\n <textarea class="').concat(p.textarea,'"></textarea>\n <div class="').concat(p["validation-message"],'" id="').concat(p["validation-message"],'"></div>\n <div class="').concat(p.actions,'">\n <div class="').concat(p.loader,'"></div>\n <button type="button" class="').concat(p.confirm,'"></button>\n <button type="button" class="').concat(p.deny,'"></button>\n <button type="button" class="').concat(p.cancel,'"></button>\n </div>\n <div class="').concat(p.footer,'"></div>\n <div class="').concat(p["timer-progress-bar-container"],'">\n <div class="').concat(p["timer-progress-bar"],'"></div>\n </div>\n </div>\n').replace(/(^|\n)\s*/g,""),be=()=>{const e=m();return!!e&&(e.remove(),oe([document.documentElement,document.body],[p["no-backdrop"],p["toast-shown"],p["has-column"]]),!0)},ye=()=>{f.currentInstance.resetValidationMessage()},ve=()=>{const e=g(),t=ie(e,p.input),n=ie(e,p.file),o=e.querySelector(".".concat(p.range," input")),i=e.querySelector(".".concat(p.range," output")),a=ie(e,p.select),r=e.querySelector(".".concat(p.checkbox," input")),s=ie(e,p.textarea);t.oninput=ye,n.onchange=ye,a.onchange=ye,r.onchange=ye,s.oninput=ye,o.oninput=()=>{ye(),i.value=o.value},o.onchange=()=>{ye(),o.nextSibling.value=o.value}},we=e=>"string"==typeof e?document.querySelector(e):e,Ce=e=>{const t=g();t.setAttribute("role",e.toast?"alert":"dialog"),t.setAttribute("aria-live",e.toast?"polite":"assertive"),e.toast||t.setAttribute("aria-modal","true")},ke=e=>{"rtl"===window.getComputedStyle(e).direction&&u(m(),p.rtl)},Ae=(e,t)=>{if(e instanceof HTMLElement)t.appendChild(e);else if("object"==typeof e){var n=e,o=t;if(n.jquery)Pe(o,n);else l(o,n.toString())}else e&&l(t,e)},Pe=(t,n)=>{if(t.textContent="",0 in n)for(let e=0;e in n;e++)t.appendChild(n[e].cloneNode(!0));else t.appendChild(n.cloneNode(!0))},Be=(()=>{if(pe())return!1;var e=document.createElement("div"),t={WebkitAnimation:"webkitAnimationEnd",animation:"animationend"};for(const n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&void 0!==e.style[n])return t[n];return!1})(),xe=(e,t)=>{var n,o,i,a,r,s=U(),c=R();(t.showConfirmButton||t.showDenyButton||t.showCancelButton?d:h)(s),Q(s,t,"actions"),s=s,n=c,o=t,i=V(),a=N(),r=F(),Ee(i,"confirm",o),Ee(a,"deny",o),Ee(r,"cancel",o),function(e,t,n,o){if(!o.buttonsStyling)return oe([e,t,n],p.styled);u([e,t,n],p.styled),o.confirmButtonColor&&(e.style.backgroundColor=o.confirmButtonColor,u(e,p["default-outline"]));o.denyButtonColor&&(t.style.backgroundColor=o.denyButtonColor,u(t,p["default-outline"]));o.cancelButtonColor&&(n.style.backgroundColor=o.cancelButtonColor,u(n,p["default-outline"]))}(i,a,r,o),o.reverseButtons&&(o.toast?(s.insertBefore(r,i),s.insertBefore(a,i)):(s.insertBefore(r,n),s.insertBefore(a,n),s.insertBefore(i,n))),l(c,t.loaderHtml),Q(c,t,"loader")};function Ee(e,t,n){se(e,n["show".concat(y(t),"Button")],"inline-block"),l(e,n["".concat(t,"ButtonText")]),e.setAttribute("aria-label",n["".concat(t,"ButtonAriaLabel")]),e.className=p[t],Q(e,n,"".concat(t,"Button")),u(e,n["".concat(t,"ButtonClass")])}const Te=(e,t)=>{var n,o,i=m();i&&(o=i,"string"==typeof(n=t.backdrop)?o.style.background=n:n||u([document.documentElement,document.body],p["no-backdrop"]),o=i,(n=t.position)in p?u(o,p[n]):(a('The "position" parameter is not valid, defaulting to "center"'),u(o,p.center)),n=i,!(o=t.grow)||"string"!=typeof o||(o="grow-".concat(o))in p&&u(n,p[o]),Q(i,t,"container"))};var b={awaitingPromise:new WeakMap,promise:new WeakMap,innerParams:new WeakMap,domCache:new WeakMap};const Se=["input","file","range","select","radio","checkbox","textarea"],Le=(e,r)=>{const s=g();var t,e=b.innerParams.get(e);const c=!e||r.input!==e.input;Se.forEach(e=>{var t=p[e];const n=ie(s,t);{var o=r.inputAttributes;const i=ee(g(),e);if(i){Oe(i);for(const a in o)i.setAttribute(a,o[a])}}n.className=t,c&&h(n)}),r.input&&(c&&(e=>{if(!Ie[e.input])return v('Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "'.concat(e.input,'"'));const t=De(e.input),n=Ie[e.input](t,e);d(n),setTimeout(()=>{te(n)})})(r),e=r,t=De(e.input),e.customClass&&u(t,e.customClass.input))},Oe=t=>{for(let e=0;e<t.attributes.length;e++){var n=t.attributes[e].name;["type","value","style"].includes(n)||t.removeAttribute(n)}},je=(e,t)=>{e.placeholder&&!t.inputPlaceholder||(e.placeholder=t.inputPlaceholder)},Me=(e,t,n)=>{if(n.inputLabel){e.id=p.input;const i=document.createElement("label");var o=p["input-label"];i.setAttribute("for",e.id),i.className=o,u(i,n.customClass.inputLabel),i.innerText=n.inputLabel,t.insertAdjacentElement("beforebegin",i)}},De=e=>{e=p[e]||p.input;return ie(g(),e)},Ie={},He=(Ie.text=Ie.email=Ie.password=Ie.number=Ie.tel=Ie.url=(e,t)=>("string"==typeof t.inputValue||"number"==typeof t.inputValue?e.value=t.inputValue:A(t.inputValue)||a('Unexpected type of inputValue! Expected "string", "number" or "Promise", got "'.concat(typeof t.inputValue,'"')),Me(e,e,t),je(e,t),e.type=t.input,e),Ie.file=(e,t)=>(Me(e,e,t),je(e,t),e),Ie.range=(e,t)=>{const n=e.querySelector("input"),o=e.querySelector("output");return n.value=t.inputValue,n.type=t.input,o.value=t.inputValue,Me(n,e,t),e},Ie.select=(e,t)=>{if(e.textContent="",t.inputPlaceholder){const n=document.createElement("option");l(n,t.inputPlaceholder),n.value="",n.disabled=!0,n.selected=!0,e.appendChild(n)}return Me(e,e,t),e},Ie.radio=e=>(e.textContent="",e),Ie.checkbox=(e,t)=>{const n=ee(g(),"checkbox");n.value="1",n.id=p.checkbox,n.checked=Boolean(t.inputValue);var o=e.querySelector("span");return l(o,t.inputPlaceholder),e},Ie.textarea=(n,e)=>{n.value=e.inputValue,je(n,e),Me(n,n,e);return setTimeout(()=>{if("MutationObserver"in window){const t=parseInt(window.getComputedStyle(g()).width);new MutationObserver(()=>{var e=n.offsetWidth+(e=n,parseInt(window.getComputedStyle(e).marginLeft)+parseInt(window.getComputedStyle(e).marginRight));e>t?g().style.width="".concat(e,"px"):g().style.width=null}).observe(n,{attributes:!0,attributeFilter:["style"]})}}),n},(e,t)=>{const n=D();Q(n,t,"htmlContainer"),t.html?(Ae(t.html,n),d(n,"block")):t.text?(n.textContent=t.text,d(n,"block")):h(n),Le(e,t)}),qe=(e,t)=>{var n=W();se(n,t.footer),t.footer&&Ae(t.footer,n),Q(n,t,"footer")},Ve=(e,t)=>{const n=_();l(n,t.closeButtonHtml),Q(n,t,"closeButton"),se(n,t.showCloseButton),n.setAttribute("aria-label",t.closeButtonAriaLabel)},Ne=(e,t)=>{var e=b.innerParams.get(e),n=j();return e&&t.icon===e.icon?(ze(n,t),void Re(n,t)):t.icon||t.iconHtml?t.icon&&-1===Object.keys(S).indexOf(t.icon)?(v('Unknown icon! Expected "success", "error", "warning", "info" or "question", got "'.concat(t.icon,'"')),h(n)):(d(n),ze(n,t),Re(n,t),void u(n,t.showClass.icon)):h(n)},Re=(e,t)=>{for(const n in S)t.icon!==n&&oe(e,S[n]);u(e,S[t.icon]),_e(e,t),Fe(),Q(e,t,"icon")},Fe=()=>{const e=g();var t=window.getComputedStyle(e).getPropertyValue("background-color");const n=e.querySelectorAll("[class^=swal2-success-circular-line], .swal2-success-fix");for(let e=0;e<n.length;e++)n[e].style.backgroundColor=t},Ue='\n <div class="swal2-success-circular-line-left"></div>\n <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>\n <div class="swal2-success-ring"></div> <div class="swal2-success-fix"></div>\n <div class="swal2-success-circular-line-right"></div>\n',We='\n <span class="swal2-x-mark">\n <span class="swal2-x-mark-line-left"></span>\n <span class="swal2-x-mark-line-right"></span>\n </span>\n',ze=(e,t)=>{var n;e.textContent="",t.iconHtml?l(e,Ke(t.iconHtml)):"success"===t.icon?l(e,Ue):"error"===t.icon?l(e,We):(n={question:"?",warning:"!",info:"i"},l(e,Ke(n[t.icon])))},_e=(e,t)=>{if(t.iconColor){e.style.color=t.iconColor,e.style.borderColor=t.iconColor;for(const n of[".swal2-success-line-tip",".swal2-success-line-long",".swal2-x-mark-line-left",".swal2-x-mark-line-right"])re(e,n,"backgroundColor",t.iconColor);re(e,".swal2-success-ring","borderColor",t.iconColor)}},Ke=e=>'<div class="'.concat(p["icon-content"],'">').concat(e,"</div>"),Ye=(e,t)=>{const n=I();if(!t.imageUrl)return h(n);d(n,""),n.setAttribute("src",t.imageUrl),n.setAttribute("alt",t.imageAlt),ae(n,"width",t.imageWidth),ae(n,"height",t.imageHeight),n.className=p.image,Q(n,t,"image")},Ze=(e,o)=>{const i=H();if(!o.progressSteps||0===o.progressSteps.length)return h(i);d(i),i.textContent="",o.currentProgressStep>=o.progressSteps.length&&a("Invalid currentProgressStep parameter, it should be less than progressSteps.length (currentProgressStep like JS arrays starts from 0)"),o.progressSteps.forEach((e,t)=>{e=e,n=document.createElement("li"),u(n,p["progress-step"]),l(n,e);var n,e=n;i.appendChild(e),t===o.currentProgressStep&&u(e,p["active-progress-step"]),t!==o.progressSteps.length-1&&(n=(e=>{const t=document.createElement("li");return u(t,p["progress-step-line"]),e.progressStepsDistance&&(t.style.width=e.progressStepsDistance),t})(o),i.appendChild(n))})},Je=(e,t)=>{const n=M();se(n,t.title||t.titleText,"block"),t.title&&Ae(t.title,n),t.titleText&&(n.innerText=t.titleText),Q(n,t,"title")},Xe=(e,t)=>{var n=m();const o=g();t.toast?(ae(n,"width",t.width),o.style.width="100%",o.insertBefore(R(),j())):ae(o,"width",t.width),ae(o,"padding",t.padding),t.color&&(o.style.color=t.color),t.background&&(o.style.background=t.background),h(q());n=o;(n.className="".concat(p.popup," ").concat(ce(n)?t.showClass.popup:""),t.toast)?(u([document.documentElement,document.body],p["toast-shown"]),u(n,p.toast)):u(n,p.modal);Q(n,t,"popup"),"string"==typeof t.customClass&&u(n,t.customClass);t.icon&&u(n,p["icon-".concat(t.icon)])},$e=(e,t)=>{Xe(e,t),Te(e,t),Ze(e,t),Ne(e,t),Ye(e,t),Je(e,t),Ve(e,t),He(e,t),xe(e,t),qe(e,t),"function"==typeof t.didRender&&t.didRender(g())},Ge=Object.freeze({cancel:"cancel",backdrop:"backdrop",close:"close",esc:"esc",timer:"timer"}),Qe=()=>{const e=i(document.body.children);e.forEach(e=>{e===m()||e.contains(m())||(e.hasAttribute("aria-hidden")&&e.setAttribute("data-previous-aria-hidden",e.getAttribute("aria-hidden")),e.setAttribute("aria-hidden","true"))})},et=()=>{const e=i(document.body.children);e.forEach(e=>{e.hasAttribute("data-previous-aria-hidden")?(e.setAttribute("aria-hidden",e.getAttribute("data-previous-aria-hidden")),e.removeAttribute("data-previous-aria-hidden")):e.removeAttribute("aria-hidden")})},tt=["swal-title","swal-html","swal-footer"],nt=e=>{const n={};return i(e.querySelectorAll("swal-param")).forEach(e=>{lt(e,["name","value"]);var t=e.getAttribute("name"),e=e.getAttribute("value");"boolean"==typeof r[t]&&"false"===e&&(n[t]=!1),"object"==typeof r[t]&&(n[t]=JSON.parse(e))}),n},ot=e=>{const n={};return i(e.querySelectorAll("swal-button")).forEach(e=>{lt(e,["type","color","aria-label"]);var t=e.getAttribute("type");n["".concat(t,"ButtonText")]=e.innerHTML,n["show".concat(y(t),"Button")]=!0,e.hasAttribute("color")&&(n["".concat(t,"ButtonColor")]=e.getAttribute("color")),e.hasAttribute("aria-label")&&(n["".concat(t,"ButtonAriaLabel")]=e.getAttribute("aria-label"))}),n},it=e=>{const t={},n=e.querySelector("swal-image");return n&&(lt(n,["src","width","height","alt"]),n.hasAttribute("src")&&(t.imageUrl=n.getAttribute("src")),n.hasAttribute("width")&&(t.imageWidth=n.getAttribute("width")),n.hasAttribute("height")&&(t.imageHeight=n.getAttribute("height")),n.hasAttribute("alt")&&(t.imageAlt=n.getAttribute("alt"))),t},at=e=>{const t={},n=e.querySelector("swal-icon");return n&&(lt(n,["type","color"]),n.hasAttribute("type")&&(t.icon=n.getAttribute("type")),n.hasAttribute("color")&&(t.iconColor=n.getAttribute("color")),t.iconHtml=n.innerHTML),t},rt=e=>{const n={},t=e.querySelector("swal-input");t&&(lt(t,["type","label","placeholder","value"]),n.input=t.getAttribute("type")||"text",t.hasAttribute("label")&&(n.inputLabel=t.getAttribute("label")),t.hasAttribute("placeholder")&&(n.inputPlaceholder=t.getAttribute("placeholder")),t.hasAttribute("value")&&(n.inputValue=t.getAttribute("value")));e=e.querySelectorAll("swal-input-option");return e.length&&(n.inputOptions={},i(e).forEach(e=>{lt(e,["value"]);var t=e.getAttribute("value"),e=e.innerHTML;n.inputOptions[t]=e})),n},st=(e,t)=>{const n={};for(const o in t){const i=t[o],a=e.querySelector(i);a&&(lt(a,[]),n[i.replace(/^swal-/,"")]=a.innerHTML.trim())}return n},ct=e=>{const t=tt.concat(["swal-param","swal-button","swal-image","swal-icon","swal-input","swal-input-option"]);i(e.children).forEach(e=>{e=e.tagName.toLowerCase();-1===t.indexOf(e)&&a("Unrecognized element <".concat(e,">"))})},lt=(t,n)=>{i(t.attributes).forEach(e=>{-1===n.indexOf(e.name)&&a(['Unrecognized attribute "'.concat(e.name,'" on <').concat(t.tagName.toLowerCase(),">."),"".concat(n.length?"Allowed attributes are: ".concat(n.join(", ")):"To set the value, use HTML within the element.")])})};var ut={email:(e,t)=>/^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(e)?Promise.resolve():Promise.resolve(t||"Invalid email address"),url:(e,t)=>/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(e)?Promise.resolve():Promise.resolve(t||"Invalid URL")};function dt(e){(t=e).inputValidator||Object.keys(ut).forEach(e=>{t.input===e&&(t.inputValidator=ut[e])}),e.showLoaderOnConfirm&&!e.preConfirm&&a("showLoaderOnConfirm is set to true, but preConfirm is not defined.\nshowLoaderOnConfirm should be used together with preConfirm, see usage example:\nhttps://sweetalert2.github.io/#ajax-request"),(n=e).target&&("string"!=typeof n.target||document.querySelector(n.target))&&("string"==typeof n.target||n.target.appendChild)||(a('Target parameter is not valid, defaulting to "body"'),n.target="body"),"string"==typeof e.title&&(e.title=e.title.split("\n").join("<br />"));var t,n=e,e=be();if(pe())v("SweetAlert2 requires document to initialize");else{const o=document.createElement("div"),i=(o.className=p.container,e&&u(o,p["no-transition"]),l(o,fe),we(n.target));i.appendChild(o),Ce(n),ke(i),ve()}}class pt{constructor(e,t){this.callback=e,this.remaining=t,this.running=!1,this.start()}start(){return this.running||(this.running=!0,this.started=new Date,this.id=setTimeout(this.callback,this.remaining)),this.remaining}stop(){return this.running&&(this.running=!1,clearTimeout(this.id),this.remaining-=(new Date).getTime()-this.started.getTime()),this.remaining}increase(e){var t=this.running;return t&&this.stop(),this.remaining+=e,t&&this.start(),this.remaining}getTimerLeft(){return this.running&&(this.stop(),this.start()),this.remaining}isRunning(){return this.running}}const mt=()=>{null===X.previousBodyPadding&&document.body.scrollHeight>window.innerHeight&&(X.previousBodyPadding=parseInt(window.getComputedStyle(document.body).getPropertyValue("padding-right")),document.body.style.paddingRight="".concat(X.previousBodyPadding+(()=>{const e=document.createElement("div");e.className=p["scrollbar-measure"],document.body.appendChild(e);var t=e.getBoundingClientRect().width-e.clientWidth;return document.body.removeChild(e),t})(),"px"))},gt=()=>{null!==X.previousBodyPadding&&(document.body.style.paddingRight="".concat(X.previousBodyPadding,"px"),X.previousBodyPadding=null)},ht=()=>{var e=/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream||"MacIntel"===navigator.platform&&1<navigator.maxTouchPoints;if(e&&!$(document.body,p.iosfix)){var t,e=document.body.scrollTop;document.body.style.top="".concat(-1*e,"px"),u(document.body,p.iosfix);{const n=m();let t;n.ontouchstart=e=>{t=ft(e)},n.ontouchmove=e=>{t&&(e.preventDefault(),e.stopPropagation())}}{const o=navigator.userAgent,i=!!o.match(/iPad/i)||!!o.match(/iPhone/i),a=!!o.match(/WebKit/i),r=i&&a&&!o.match(/CriOS/i);r&&(t=44,g().scrollHeight>window.innerHeight-44&&(m().style.paddingBottom="".concat(44,"px")))}}},ft=e=>{var t,n=e.target,o=m();return!((t=e).touches&&t.touches.length&&"stylus"===t.touches[0].touchType||(t=e).touches&&1<t.touches.length)&&(n===o||!(ue(o)||"INPUT"===n.tagName||"TEXTAREA"===n.tagName||ue(D())&&D().contains(n)))},bt=()=>{var e;$(document.body,p.iosfix)&&(e=parseInt(document.body.style.top,10),oe(document.body,p.iosfix),document.body.style.top="",document.body.scrollTop=-1*e)},yt=10,vt=e=>{const t=g();if(e.target===t){const n=m();t.removeEventListener(Be,vt),n.style.overflowY="auto"}},wt=(e,t)=>{Be&&de(t)?(e.style.overflowY="hidden",t.addEventListener(Be,vt)):e.style.overflowY="auto"},Ct=(e,t,n)=>{ht(),t&&"hidden"!==n&&mt(),setTimeout(()=>{e.scrollTop=0})},kt=(e,t,n)=>{u(e,n.showClass.backdrop),t.style.setProperty("opacity","0","important"),d(t,"grid"),setTimeout(()=>{u(t,n.showClass.popup),t.style.removeProperty("opacity")},yt),u([document.documentElement,document.body],p.shown),n.heightAuto&&n.backdrop&&!n.toast&&u([document.documentElement,document.body],p["height-auto"])},At=e=>{let t=g();t||new vn,t=g();var n=R();if(Z())h(j());else{var o=t;const i=U(),a=R();!e&&ce(V())&&(e=V());d(i),e&&(h(e),a.setAttribute("data-button-to-replace",e.className));a.parentNode.insertBefore(a,e),u([o,i],p.loading)}d(n),t.setAttribute("data-loading",!0),t.setAttribute("aria-busy",!0),t.focus()},Pt=(t,n)=>{const o=g(),i=e=>xt[n.input](o,Et(e),n);C(n.inputOptions)||A(n.inputOptions)?(At(V()),k(n.inputOptions).then(e=>{t.hideLoading(),i(e)})):"object"==typeof n.inputOptions?i(n.inputOptions):v("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(typeof n.inputOptions))},Bt=(t,n)=>{const o=t.getInput();h(o),k(n.inputValue).then(e=>{o.value="number"===n.input?parseFloat(e)||0:"".concat(e),d(o),o.focus(),t.hideLoading()}).catch(e=>{v("Error in inputValue promise: ".concat(e)),o.value="",d(o),o.focus(),t.hideLoading()})},xt={select:(e,t,i)=>{const a=ie(e,p.select),r=(e,t,n)=>{const o=document.createElement("option");o.value=n,l(o,t),o.selected=Tt(n,i.inputValue),e.appendChild(o)};t.forEach(e=>{var t=e[0];const n=e[1];if(Array.isArray(n)){const o=document.createElement("optgroup");o.label=t,o.disabled=!1,a.appendChild(o),n.forEach(e=>r(o,e[1],e[0]))}else r(a,n,t)}),a.focus()},radio:(e,t,a)=>{const r=ie(e,p.radio),n=(t.forEach(e=>{var t=e[0],e=e[1];const n=document.createElement("input"),o=document.createElement("label"),i=(n.type="radio",n.name=p.radio,n.value=t,Tt(t,a.inputValue)&&(n.checked=!0),document.createElement("span"));l(i,e),i.className=p.label,o.appendChild(n),o.appendChild(i),r.appendChild(o)}),r.querySelectorAll("input"));n.length&&n[0].focus()}},Et=n=>{const o=[];return"undefined"!=typeof Map&&n instanceof Map?n.forEach((e,t)=>{let n=e;"object"==typeof n&&(n=Et(n)),o.push([t,n])}):Object.keys(n).forEach(e=>{let t=n[e];"object"==typeof t&&(t=Et(t)),o.push([e,t])}),o},Tt=(e,t)=>t&&t.toString()===e.toString(),St=(e,t)=>{var n=b.innerParams.get(e);if(!n.input)return v('The "input" parameter is needed to be set when using returnInputValueOn'.concat(y(t)));var o=((e,t)=>{const n=e.getInput();if(!n)return null;switch(t.input){case"checkbox":return n.checked?1:0;case"radio":return(o=n).checked?o.value:null;case"file":return(o=n).files.length?null!==o.getAttribute("multiple")?o.files:o.files[0]:null;default:return t.inputAutoTrim?n.value.trim():n.value}var o})(e,n);if(n.inputValidator){var i=e;var a=o;var r=t;const s=b.innerParams.get(i),c=(i.disableInput(),Promise.resolve().then(()=>k(s.inputValidator(a,s.validationMessage))));c.then(e=>{i.enableButtons(),i.enableInput(),e?i.showValidationMessage(e):("deny"===r?Lt:Mt)(i,a)})}else e.getInput().checkValidity()?("deny"===t?Lt:Mt)(e,o):(e.enableButtons(),e.showValidationMessage(n.validationMessage))},Lt=(t,n)=>{const e=b.innerParams.get(t||void 0);if(e.showLoaderOnDeny&&At(N()),e.preDeny){b.awaitingPromise.set(t||void 0,!0);const o=Promise.resolve().then(()=>k(e.preDeny(n,e.validationMessage)));o.then(e=>{!1===e?t.hideLoading():t.closePopup({isDenied:!0,value:void 0===e?n:e})}).catch(e=>jt(t||void 0,e))}else t.closePopup({isDenied:!0,value:n})},Ot=(e,t)=>{e.closePopup({isConfirmed:!0,value:t})},jt=(e,t)=>{e.rejectPromise(t)},Mt=(t,n)=>{const e=b.innerParams.get(t||void 0);if(e.showLoaderOnConfirm&&At(),e.preConfirm){t.resetValidationMessage(),b.awaitingPromise.set(t||void 0,!0);const o=Promise.resolve().then(()=>k(e.preConfirm(n,e.validationMessage)));o.then(e=>{ce(q())||!1===e?t.hideLoading():Ot(t,void 0===e?n:e)}).catch(e=>jt(t||void 0,e))}else Ot(t,n)},Dt=(n,e,o)=>{e.popup.onclick=()=>{var e,t=b.innerParams.get(n);t&&((e=t).showConfirmButton||e.showDenyButton||e.showCancelButton||e.showCloseButton||t.timer||t.input)||o(Ge.close)}};let It=!1;const Ht=t=>{t.popup.onmousedown=()=>{t.container.onmouseup=function(e){t.container.onmouseup=void 0,e.target===t.container&&(It=!0)}}},qt=t=>{t.container.onmousedown=()=>{t.popup.onmouseup=function(e){t.popup.onmouseup=void 0,e.target!==t.popup&&!t.popup.contains(e.target)||(It=!0)}}},Vt=(n,o,i)=>{o.container.onclick=e=>{var t=b.innerParams.get(n);It?It=!1:e.target===o.container&&w(t.allowOutsideClick)&&i(Ge.backdrop)}};const Nt=()=>V()&&V().click();const Rt=(e,t,n)=>{const o=K();if(o.length)return(t+=n)===o.length?t=0:-1===t&&(t=o.length-1),o[t].focus();g().focus()},Ft=["ArrowRight","ArrowDown"],Ut=["ArrowLeft","ArrowUp"],Wt=(e,n,o)=>{var i=b.innerParams.get(e);if(i)if(i.stopKeydownPropagation&&n.stopPropagation(),"Enter"===n.key)e=e,a=n,t=i,w(t.allowEnterKey)&&!a.isComposing&&a.target&&e.getInput()&&a.target.outerHTML===e.getInput().outerHTML&&(["textarea","file"].includes(t.input)||(Nt(),a.preventDefault()));else if("Tab"!==n.key){if([...Ft,...Ut].includes(n.key)){e=n.key;const s=V(),c=N(),d=F();if([s,c,d].includes(document.activeElement)){var t=Ft.includes(e)?"nextElementSibling":"previousElementSibling";const l=document.activeElement[t];l instanceof HTMLElement&&l.focus()}}else if("Escape"===n.key){var a=n,e=i;if(w(e.allowEscapeKey)){a.preventDefault();o(Ge.esc)}}}else{e=n;o=i;var u=e.target,r=K();let t=-1;for(let e=0;e<r.length;e++)if(u===r[e]){t=e;break}e.shiftKey?Rt(o,t,-1):Rt(o,t,1);e.stopPropagation(),e.preventDefault()}},zt=e=>"object"==typeof e&&e.jquery,_t=e=>e instanceof Element||zt(e);const Kt=()=>{if(f.timeout){{const n=z();var e=parseInt(window.getComputedStyle(n).width),t=(n.style.removeProperty("transition"),n.style.width="100%",parseInt(window.getComputedStyle(n).width)),e=e/t*100;n.style.removeProperty("transition"),n.style.width="".concat(e,"%")}return f.timeout.stop()}},Yt=()=>{var e;if(f.timeout)return e=f.timeout.start(),J(e),e};let Zt=!1;const Jt={};const Xt=t=>{for(let e=t.target;e&&e!==document;e=e.parentNode)for(const o in Jt){var n=e.getAttribute(o);if(n)return void Jt[o].fire({template:n})}};e=Object.freeze({isValidParameter:B,isUpdatableParameter:x,isDeprecatedParameter:E,argsToParams:n=>{const o={};return"object"!=typeof n[0]||_t(n[0])?["title","html","icon"].forEach((e,t)=>{t=n[t];"string"==typeof t||_t(t)?o[e]=t:void 0!==t&&v("Unexpected type of ".concat(e,'! Expected "string" or "Element", got ').concat(typeof t))}):Object.assign(o,n[0]),o},isVisible:()=>ce(g()),clickConfirm:Nt,clickDeny:()=>N()&&N().click(),clickCancel:()=>F()&&F().click(),getContainer:m,getPopup:g,getTitle:M,getHtmlContainer:D,getImage:I,getIcon:j,getInputLabel:()=>O(p["input-label"]),getCloseButton:_,getActions:U,getConfirmButton:V,getDenyButton:N,getCancelButton:F,getLoader:R,getFooter:W,getTimerProgressBar:z,getFocusableElements:K,getValidationMessage:q,isLoading:()=>g().hasAttribute("data-loading"),fire:function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return new this(...t)},mixin:function(n){class e extends this{_main(e,t){return super._main(e,Object.assign({},n,t))}}return e},showLoading:At,enableLoading:At,getTimerLeft:()=>f.timeout&&f.timeout.getTimerLeft(),stopTimer:Kt,resumeTimer:Yt,toggleTimer:()=>{var e=f.timeout;return e&&(e.running?Kt:Yt)()},increaseTimer:e=>{if(f.timeout)return e=f.timeout.increase(e),J(e,!0),e},isTimerRunning:()=>f.timeout&&f.timeout.isRunning(),bindClickHandler:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"data-swal-template";Jt[e]=this,Zt||(document.body.addEventListener("click",Xt),Zt=!0)}});function $t(){var e,t=b.innerParams.get(this);if(t){const n=b.domCache.get(this);h(n.loader),Z()?t.icon&&d(j()):(t=n,(e=t.popup.getElementsByClassName(t.loader.getAttribute("data-button-to-replace"))).length?d(e[0],"inline-block"):le()&&h(t.actions)),oe([n.popup,n.actions],p.loading),n.popup.removeAttribute("aria-busy"),n.popup.removeAttribute("data-loading"),n.confirmButton.disabled=!1,n.denyButton.disabled=!1,n.cancelButton.disabled=!1}}var Gt={swalPromiseResolve:new WeakMap,swalPromiseReject:new WeakMap};function Qt(e,t,n,o){Z()?on(e,o):(he(n).then(()=>on(e,o)),f.keydownTarget.removeEventListener("keydown",f.keydownHandler,{capture:f.keydownListenerCapture}),f.keydownHandlerAdded=!1),/^((?!chrome|android).)*safari/i.test(navigator.userAgent)?(t.setAttribute("style","display:none !important"),t.removeAttribute("class"),t.innerHTML=""):t.remove(),Y()&&(gt(),bt(),et()),oe([document.documentElement,document.body],[p.shown,p["height-auto"],p["no-backdrop"],p["toast-shown"]])}function en(e){e=void 0!==(n=e)?Object.assign({isConfirmed:!1,isDenied:!1,isDismissed:!1},n):{isConfirmed:!1,isDenied:!1,isDismissed:!0};const t=Gt.swalPromiseResolve.get(this);var n=(e=>{const t=g();if(!t)return false;const n=b.innerParams.get(e);if(!n||$(t,n.hideClass.popup))return false;oe(t,n.showClass.popup),u(t,n.hideClass.popup);const o=m();return oe(o,n.showClass.backdrop),u(o,n.hideClass.backdrop),nn(e,t,n),true})(this);this.isAwaitingPromise()?e.isDismissed||(tn(this),t(e)):n&&t(e)}const tn=e=>{e.isAwaitingPromise()&&(b.awaitingPromise.delete(e),b.innerParams.get(e)||e._destroy())},nn=(e,t,n)=>{var o,i,a,r=m(),s=Be&&de(t);"function"==typeof n.willClose&&n.willClose(t),s?(s=e,o=t,t=r,i=n.returnFocus,a=n.didClose,f.swalCloseEventFinishedCallback=Qt.bind(null,s,t,i,a),o.addEventListener(Be,function(e){e.target===o&&(f.swalCloseEventFinishedCallback(),delete f.swalCloseEventFinishedCallback)})):Qt(e,r,n.returnFocus,n.didClose)},on=(e,t)=>{setTimeout(()=>{"function"==typeof t&&t.bind(e.params)(),e._destroy()})};function an(e,t,n){const o=b.domCache.get(e);t.forEach(e=>{o[e].disabled=n})}function rn(e,t){if(!e)return!1;if("radio"===e.type){const n=e.parentNode.parentNode,o=n.querySelectorAll("input");for(let e=0;e<o.length;e++)o[e].disabled=t}else e.disabled=t}const sn=e=>{e.isAwaitingPromise()?(cn(b,e),b.awaitingPromise.set(e,!0)):(cn(Gt,e),cn(b,e))},cn=(e,t)=>{for(const n in e)e[n].delete(t)};var ln=Object.freeze({hideLoading:$t,disableLoading:$t,getInput:function(e){var t=b.innerParams.get(e||this);return(e=b.domCache.get(e||this))?ee(e.popup,t.input):null},close:en,isAwaitingPromise:function(){return!!b.awaitingPromise.get(this)},rejectPromise:function(e){const t=Gt.swalPromiseReject.get(this);tn(this),t&&t(e)},closePopup:en,closeModal:en,closeToast:en,enableButtons:function(){an(this,["confirmButton","denyButton","cancelButton"],!1)},disableButtons:function(){an(this,["confirmButton","denyButton","cancelButton"],!0)},enableInput:function(){return rn(this.getInput(),!1)},disableInput:function(){return rn(this.getInput(),!0)},showValidationMessage:function(e){const t=b.domCache.get(this);var n=b.innerParams.get(this);l(t.validationMessage,e),t.validationMessage.className=p["validation-message"],n.customClass&&n.customClass.validationMessage&&u(t.validationMessage,n.customClass.validationMessage),d(t.validationMessage);const o=this.getInput();o&&(o.setAttribute("aria-invalid",!0),o.setAttribute("aria-describedby",p["validation-message"]),te(o),u(o,p.inputerror))},resetValidationMessage:function(){var e=b.domCache.get(this);e.validationMessage&&h(e.validationMessage);const t=this.getInput();t&&(t.removeAttribute("aria-invalid"),t.removeAttribute("aria-describedby"),oe(t,p.inputerror))},getProgressSteps:function(){return b.domCache.get(this).progressSteps},update:function(e){var t=g(),n=b.innerParams.get(this);if(!t||$(t,n.hideClass.popup))return a("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");t=(t=>{const n={};return Object.keys(t).forEach(e=>{if(x(e))n[e]=t[e];else a('Invalid parameter to update: "'.concat(e,'". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md'))}),n})(e),n=Object.assign({},n,t),$e(this,n),b.innerParams.set(this,n),Object.defineProperties(this,{params:{value:Object.assign({},this.params,e),writable:!1,enumerable:!0}})},_destroy:function(){var e=b.domCache.get(this);const t=b.innerParams.get(this);t?(e.popup&&f.swalCloseEventFinishedCallback&&(f.swalCloseEventFinishedCallback(),delete f.swalCloseEventFinishedCallback),f.deferDisposalTimer&&(clearTimeout(f.deferDisposalTimer),delete f.deferDisposalTimer),"function"==typeof t.didDestroy&&t.didDestroy(),e=this,sn(e),delete e.params,delete f.keydownHandler,delete f.keydownTarget,delete f.currentInstance):sn(this)}});let un;class dn{constructor(){if("undefined"!=typeof window){un=this;for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];var o=Object.freeze(this.constructor.argsToParams(t)),o=(Object.defineProperties(this,{params:{value:o,writable:!1,enumerable:!0,configurable:!0}}),this._main(this.params));b.promise.set(this,o)}}_main(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},e=(T(Object.assign({},t,e)),f.currentInstance&&(f.currentInstance._destroy(),Y()&&et()),f.currentInstance=this,mn(e,t)),t=(dt(e),Object.freeze(e),f.timeout&&(f.timeout.stop(),delete f.timeout),clearTimeout(f.restoreFocusTimeout),gn(this));return $e(this,e),b.innerParams.set(this,e),pn(this,t,e)}then(e){const t=b.promise.get(this);return t.then(e)}finally(e){const t=b.promise.get(this);return t.finally(e)}}const pn=(l,u,d)=>new Promise((e,t)=>{const n=e=>{l.closePopup({isDismissed:!0,dismiss:e})};var o,i,a;Gt.swalPromiseResolve.set(l,e),Gt.swalPromiseReject.set(l,t),u.confirmButton.onclick=()=>{var e=l,t=b.innerParams.get(e);e.disableButtons(),t.input?St(e,"confirm"):Mt(e,!0)},u.denyButton.onclick=()=>{var e=l,t=b.innerParams.get(e);e.disableButtons(),t.returnInputValueOnDeny?St(e,"deny"):Lt(e,!1)},u.cancelButton.onclick=()=>{var e=l,t=n;e.disableButtons(),t(Ge.cancel)},u.closeButton.onclick=()=>n(Ge.close),e=l,t=u,a=n,b.innerParams.get(e).toast?Dt(e,t,a):(Ht(t),qt(t),Vt(e,t,a)),o=l,e=f,t=d,i=n,e.keydownTarget&&e.keydownHandlerAdded&&(e.keydownTarget.removeEventListener("keydown",e.keydownHandler,{capture:e.keydownListenerCapture}),e.keydownHandlerAdded=!1),t.toast||(e.keydownHandler=e=>Wt(o,e,i),e.keydownTarget=t.keydownListenerCapture?window:g(),e.keydownListenerCapture=t.keydownListenerCapture,e.keydownTarget.addEventListener("keydown",e.keydownHandler,{capture:e.keydownListenerCapture}),e.keydownHandlerAdded=!0),a=l,"select"===(t=d).input||"radio"===t.input?Pt(a,t):["text","email","number","tel","textarea"].includes(t.input)&&(C(t.inputValue)||A(t.inputValue))&&(At(V()),Bt(a,t));{var r=d;const s=m(),c=g();"function"==typeof r.willOpen&&r.willOpen(c),e=window.getComputedStyle(document.body).overflowY,kt(s,c,r),setTimeout(()=>{wt(s,c)},yt),Y()&&(Ct(s,r.scrollbarPadding,e),Qe()),Z()||f.previousActiveElement||(f.previousActiveElement=document.activeElement),"function"==typeof r.didOpen&&setTimeout(()=>r.didOpen(c)),oe(s,p["no-transition"])}hn(f,d,n),fn(u,d),setTimeout(()=>{u.container.scrollTop=0})}),mn=(e,t)=>{var n=(e=>{e="string"==typeof e.template?document.querySelector(e.template):e.template;if(!e)return{};e=e.content,ct(e),e=Object.assign(nt(e),ot(e),it(e),at(e),rt(e),st(e,tt));return e})(e);const o=Object.assign({},r,t,n,e);return o.showClass=Object.assign({},r.showClass,o.showClass),o.hideClass=Object.assign({},r.hideClass,o.hideClass),o},gn=e=>{var t={popup:g(),container:m(),actions:U(),confirmButton:V(),denyButton:N(),cancelButton:F(),loader:R(),closeButton:_(),validationMessage:q(),progressSteps:H()};return b.domCache.set(e,t),t},hn=(e,t,n)=>{var o=z();h(o),t.timer&&(e.timeout=new pt(()=>{n("timer"),delete e.timeout},t.timer),t.timerProgressBar&&(d(o),Q(o,t,"timerProgressBar"),setTimeout(()=>{e.timeout&&e.timeout.running&&J(t.timer)})))},fn=(e,t)=>{if(!t.toast)return w(t.allowEnterKey)?void(bn(e,t)||Rt(t,-1,1)):yn()},bn=(e,t)=>t.focusDeny&&ce(e.denyButton)?(e.denyButton.focus(),!0):t.focusCancel&&ce(e.cancelButton)?(e.cancelButton.focus(),!0):!(!t.focusConfirm||!ce(e.confirmButton))&&(e.confirmButton.focus(),!0),yn=()=>{document.activeElement instanceof HTMLElement&&"function"==typeof document.activeElement.blur&&document.activeElement.blur()},vn=(Object.assign(dn.prototype,ln),Object.assign(dn,e),Object.keys(ln).forEach(e=>{dn[e]=function(){if(un)return un[e](...arguments)}}),dn.DismissReason=Ge,dn.version="11.4.0",dn);return vn.default=vn,vn}),void 0!==this&&this.Sweetalert2&&(this.swal=this.sweetAlert=this.Swal=this.SweetAlert=this.Sweetalert2);
|
294coder/Efficient-MIF
| 3,021 |
utils/FS_index/interp23.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
interp23 interpolates the image I_Interpolated using a polynomial with 23 coefficients interpolator.
Interface:
image = interp23(image,ratio)
Inputs:
image: Image to interpolate;
ratio: Scale ratio between MS and PAN. Pre-condition: Resize factors power of 2.
Outputs:
image: Interpolated image.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
import numpy as np
from scipy import ndimage
def interp23(image, ratio):
if (2**round(np.log2(ratio)) != ratio):
print("Error: only resize factors of power 2")
return -1
r = image.shape[0]
c = image.shape[1]
if (np.size(image.shape) == 3):
b = image.shape[2]
else:
b = 1
CDF23 = 2*np.array([0.5, 0.305334091185, 0, -0.072698593239, 0, 0.021809577942, 0, -0.005192756653, 0, 0.000807762146, 0, -0.000060081482])
d = CDF23[::-1]
CDF23 = np.insert(CDF23, 0, d[:-1])
BaseCoeff = CDF23
first = 1
for z in range(1, int(np.log2(ratio))+1):
if (b == 1):
I1LRU = np.zeros(((2**z)*r, (2**z)*c))
else:
I1LRU = np.zeros(((2**z)*r, (2**z)*c, b))
if first:
if (b == 1):
I1LRU[1:I1LRU.shape[0]:2,1:I1LRU.shape[1]:2]=image
else:
I1LRU[1:I1LRU.shape[0]:2,1:I1LRU.shape[1]:2,:]=image
first = 0
else:
if (b == 1):
I1LRU[0:I1LRU.shape[0]:2,0:I1LRU.shape[1]:2]=image
else:
I1LRU[0:I1LRU.shape[0]:2,0:I1LRU.shape[1]:2,:]=image
for ii in range(b):
if (b == 1):
t = I1LRU
else:
t = I1LRU[:,:,ii]
for j in range(0,t.shape[0]):
t[j,:]=ndimage.correlate(t[j,:],BaseCoeff,mode='wrap')
for k in range(0,t.shape[1]):
t[:,k]=ndimage.correlate(t[:,k],BaseCoeff,mode='wrap')
if (b == 1):
I1LRU = t
else:
I1LRU[:,:,ii] = t
image = I1LRU
return image
|
281677160/openwrt-package
| 35,737 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_record_module.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp.h"
#include "ngx_rtmp_cmd_module.h"
#include "ngx_rtmp_codec_module.h"
#include "ngx_rtmp_record_module.h"
ngx_rtmp_record_done_pt ngx_rtmp_record_done;
static ngx_rtmp_publish_pt next_publish;
static ngx_rtmp_close_stream_pt next_close_stream;
static ngx_rtmp_stream_begin_pt next_stream_begin;
static ngx_rtmp_stream_eof_pt next_stream_eof;
static char *ngx_rtmp_record_recorder(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static ngx_int_t ngx_rtmp_record_postconfiguration(ngx_conf_t *cf);
static void * ngx_rtmp_record_create_app_conf(ngx_conf_t *cf);
static char * ngx_rtmp_record_merge_app_conf(ngx_conf_t *cf,
void *parent, void *child);
static ngx_int_t ngx_rtmp_record_write_frame(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx,
ngx_rtmp_header_t *h, ngx_chain_t *in, ngx_int_t inc_nframes);
static ngx_int_t ngx_rtmp_record_av(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in);
static ngx_int_t ngx_rtmp_record_node_av(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx, ngx_rtmp_header_t *h, ngx_chain_t *in);
static ngx_int_t ngx_rtmp_record_node_open(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx);
static ngx_int_t ngx_rtmp_record_node_close(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx);
static void ngx_rtmp_record_make_path(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx, ngx_str_t *path);
static ngx_int_t ngx_rtmp_record_init(ngx_rtmp_session_t *s);
static ngx_conf_bitmask_t ngx_rtmp_record_mask[] = {
{ ngx_string("off"), NGX_RTMP_RECORD_OFF },
{ ngx_string("all"), NGX_RTMP_RECORD_AUDIO |
NGX_RTMP_RECORD_VIDEO },
{ ngx_string("audio"), NGX_RTMP_RECORD_AUDIO },
{ ngx_string("video"), NGX_RTMP_RECORD_VIDEO },
{ ngx_string("keyframes"), NGX_RTMP_RECORD_KEYFRAMES },
{ ngx_string("manual"), NGX_RTMP_RECORD_MANUAL },
{ ngx_null_string, 0 }
};
static ngx_command_t ngx_rtmp_record_commands[] = {
{ ngx_string("record"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_1MORE,
ngx_conf_set_bitmask_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, flags),
ngx_rtmp_record_mask },
{ ngx_string("record_path"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, path),
NULL },
{ ngx_string("record_suffix"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, suffix),
NULL },
{ ngx_string("record_unique"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, unique),
NULL },
{ ngx_string("record_append"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, append),
NULL },
{ ngx_string("record_lock"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, lock_file),
NULL },
{ ngx_string("record_max_size"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, max_size),
NULL },
{ ngx_string("record_max_frames"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, max_frames),
NULL },
{ ngx_string("record_interval"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, interval),
NULL },
{ ngx_string("record_notify"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|
NGX_RTMP_REC_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_record_app_conf_t, notify),
NULL },
{ ngx_string("recorder"),
NGX_RTMP_APP_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1,
ngx_rtmp_record_recorder,
NGX_RTMP_APP_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_rtmp_record_module_ctx = {
NULL, /* preconfiguration */
ngx_rtmp_record_postconfiguration, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_rtmp_record_create_app_conf, /* create app configuration */
ngx_rtmp_record_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_rtmp_record_module = {
NGX_MODULE_V1,
&ngx_rtmp_record_module_ctx, /* module context */
ngx_rtmp_record_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_rtmp_record_create_app_conf(ngx_conf_t *cf)
{
ngx_rtmp_record_app_conf_t *racf;
racf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_record_app_conf_t));
if (racf == NULL) {
return NULL;
}
racf->max_size = NGX_CONF_UNSET_SIZE;
racf->max_frames = NGX_CONF_UNSET_SIZE;
racf->interval = NGX_CONF_UNSET_MSEC;
racf->unique = NGX_CONF_UNSET;
racf->append = NGX_CONF_UNSET;
racf->lock_file = NGX_CONF_UNSET;
racf->notify = NGX_CONF_UNSET;
racf->url = NGX_CONF_UNSET_PTR;
if (ngx_array_init(&racf->rec, cf->pool, 1, sizeof(void *)) != NGX_OK) {
return NULL;
}
return racf;
}
static char *
ngx_rtmp_record_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_record_app_conf_t *prev = parent;
ngx_rtmp_record_app_conf_t *conf = child;
ngx_rtmp_record_app_conf_t **rracf;
ngx_conf_merge_str_value(conf->path, prev->path, "");
ngx_conf_merge_str_value(conf->suffix, prev->suffix, ".flv");
ngx_conf_merge_size_value(conf->max_size, prev->max_size, 0);
ngx_conf_merge_size_value(conf->max_frames, prev->max_frames, 0);
ngx_conf_merge_value(conf->unique, prev->unique, 0);
ngx_conf_merge_value(conf->append, prev->append, 0);
ngx_conf_merge_value(conf->lock_file, prev->lock_file, 0);
ngx_conf_merge_value(conf->notify, prev->notify, 0);
ngx_conf_merge_msec_value(conf->interval, prev->interval,
(ngx_msec_t) NGX_CONF_UNSET);
ngx_conf_merge_bitmask_value(conf->flags, prev->flags, 0);
ngx_conf_merge_ptr_value(conf->url, prev->url, NULL);
if (conf->flags) {
rracf = ngx_array_push(&conf->rec);
if (rracf == NULL) {
return NGX_CONF_ERROR;
}
*rracf = conf;
}
return NGX_CONF_OK;
}
static ngx_int_t
ngx_rtmp_record_write_header(ngx_file_t *file)
{
static u_char flv_header[] = {
0x46, /* 'F' */
0x4c, /* 'L' */
0x56, /* 'V' */
0x01, /* version = 1 */
0x05, /* 00000 1 0 1 = has audio & video */
0x00,
0x00,
0x00,
0x09, /* header size */
0x00,
0x00,
0x00,
0x00 /* PreviousTagSize0 (not actually a header) */
};
return ngx_write_file(file, flv_header, sizeof(flv_header), 0) == NGX_ERROR
? NGX_ERROR
: NGX_OK;
}
static ngx_rtmp_record_rec_ctx_t *
ngx_rtmp_record_get_node_ctx(ngx_rtmp_session_t *s, ngx_uint_t n)
{
ngx_rtmp_record_ctx_t *ctx;
ngx_rtmp_record_rec_ctx_t *rctx;
if (ngx_rtmp_record_init(s) != NGX_OK) {
return NULL;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
if (n >= ctx->rec.nelts) {
return NULL;
}
rctx = ctx->rec.elts;
return &rctx[n];
}
ngx_int_t
ngx_rtmp_record_open(ngx_rtmp_session_t *s, ngx_uint_t n, ngx_str_t *path)
{
ngx_rtmp_record_rec_ctx_t *rctx;
ngx_int_t rc;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: #%ui manual open", n);
rctx = ngx_rtmp_record_get_node_ctx(s, n);
if (rctx == NULL) {
return NGX_ERROR;
}
rc = ngx_rtmp_record_node_open(s, rctx);
if (rc != NGX_OK) {
return rc;
}
if (path) {
ngx_rtmp_record_make_path(s, rctx, path);
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_record_close(ngx_rtmp_session_t *s, ngx_uint_t n, ngx_str_t *path)
{
ngx_rtmp_record_rec_ctx_t *rctx;
ngx_int_t rc;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: #%ui manual close", n);
rctx = ngx_rtmp_record_get_node_ctx(s, n);
if (rctx == NULL) {
return NGX_ERROR;
}
rc = ngx_rtmp_record_node_close(s, rctx);
if (rc != NGX_OK) {
return rc;
}
if (path) {
ngx_rtmp_record_make_path(s, rctx, path);
}
return NGX_OK;
}
ngx_uint_t
ngx_rtmp_record_find(ngx_rtmp_record_app_conf_t *racf, ngx_str_t *id)
{
ngx_rtmp_record_app_conf_t **pracf, *rracf;
ngx_uint_t n;
pracf = racf->rec.elts;
for (n = 0; n < racf->rec.nelts; ++n, ++pracf) {
rracf = *pracf;
if (rracf->id.len == id->len &&
ngx_strncmp(rracf->id.data, id->data, id->len) == 0)
{
return n;
}
}
return NGX_CONF_UNSET_UINT;
}
/* This funcion returns pointer to a static buffer */
static void
ngx_rtmp_record_make_path(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx, ngx_str_t *path)
{
ngx_rtmp_record_ctx_t *ctx;
ngx_rtmp_record_app_conf_t *rracf;
u_char *p, *l;
struct tm tm;
static u_char buf[NGX_TIME_T_LEN + 1];
static u_char pbuf[NGX_MAX_PATH + 1];
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
rracf = rctx->conf;
/* create file path */
p = pbuf;
l = pbuf + sizeof(pbuf) - 1;
p = ngx_cpymem(p, rracf->path.data,
ngx_min(rracf->path.len, (size_t)(l - p - 1)));
*p++ = '/';
p = (u_char *)ngx_escape_uri(p, ctx->name, ngx_min(ngx_strlen(ctx->name),
(size_t)(l - p)), NGX_ESCAPE_URI_COMPONENT);
/* append timestamp */
if (rracf->unique) {
p = ngx_cpymem(p, buf, ngx_min(ngx_sprintf(buf, "-%T",
rctx->timestamp) - buf, l - p));
}
if (ngx_strchr(rracf->suffix.data, '%')) {
ngx_libc_localtime(rctx->timestamp, &tm);
p += strftime((char *) p, l - p, (char *) rracf->suffix.data, &tm);
} else {
p = ngx_cpymem(p, rracf->suffix.data,
ngx_min(rracf->suffix.len, (size_t)(l - p)));
}
*p = 0;
path->data = pbuf;
path->len = p - pbuf;
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V path: '%V'", &rracf->id, path);
}
static void
ngx_rtmp_record_notify_error(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx)
{
ngx_rtmp_record_app_conf_t *rracf = rctx->conf;
rctx->failed = 1;
if (!rracf->notify) {
return;
}
ngx_rtmp_send_status(s, "NetStream.Record.Failed", "error",
rracf->id.data ? (char *) rracf->id.data : "");
}
static ngx_int_t
ngx_rtmp_record_node_open(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx)
{
ngx_rtmp_record_app_conf_t *rracf;
ngx_err_t err;
ngx_str_t path;
ngx_int_t mode, create_mode;
u_char buf[8], *p;
off_t file_size;
uint32_t tag_size, mlen, timestamp;
rracf = rctx->conf;
tag_size = 0;
if (rctx->file.fd != NGX_INVALID_FILE) {
return NGX_AGAIN;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V opening", &rracf->id);
ngx_memzero(rctx, sizeof(*rctx));
rctx->conf = rracf;
rctx->last = *ngx_cached_time;
rctx->timestamp = ngx_cached_time->sec;
ngx_rtmp_record_make_path(s, rctx, &path);
mode = rracf->append ? NGX_FILE_RDWR : NGX_FILE_WRONLY;
create_mode = rracf->append ? NGX_FILE_CREATE_OR_OPEN : NGX_FILE_TRUNCATE;
ngx_memzero(&rctx->file, sizeof(rctx->file));
rctx->file.offset = 0;
rctx->file.log = s->log;
rctx->file.fd = ngx_open_file(path.data, mode, create_mode,
NGX_FILE_DEFAULT_ACCESS);
ngx_str_set(&rctx->file.name, "recorded");
if (rctx->file.fd == NGX_INVALID_FILE) {
err = ngx_errno;
if (err != NGX_ENOENT) {
ngx_log_error(NGX_LOG_CRIT, s->log, err,
"record: %V failed to open file '%V'",
&rracf->id, &path);
}
ngx_rtmp_record_notify_error(s, rctx);
return NGX_OK;
}
#if !(NGX_WIN32)
if (rracf->lock_file) {
err = ngx_lock_fd(rctx->file.fd);
if (err) {
ngx_log_error(NGX_LOG_CRIT, s->log, err,
"record: %V lock failed", &rracf->id);
}
}
#endif
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V opened '%V'", &rracf->id, &path);
if (rracf->notify) {
ngx_rtmp_send_status(s, "NetStream.Record.Start", "status",
rracf->id.data ? (char *) rracf->id.data : "");
}
if (rracf->append) {
file_size = 0;
timestamp = 0;
#if (NGX_WIN32)
{
LONG lo, hi;
lo = 0;
hi = 0;
lo = SetFilePointer(rctx->file.fd, lo, &hi, FILE_END);
file_size = (lo == INVALID_SET_FILE_POINTER ?
(off_t) -1 : (off_t) hi << 32 | (off_t) lo);
}
#else
file_size = lseek(rctx->file.fd, 0, SEEK_END);
#endif
if (file_size == (off_t) -1) {
ngx_log_error(NGX_LOG_CRIT, s->log, ngx_errno,
"record: %V seek failed", &rracf->id);
goto done;
}
if (file_size < 4) {
goto done;
}
if (ngx_read_file(&rctx->file, buf, 4, file_size - 4) != 4) {
ngx_log_error(NGX_LOG_CRIT, s->log, ngx_errno,
"record: %V tag size read failed", &rracf->id);
goto done;
}
p = (u_char *) &tag_size;
p[0] = buf[3];
p[1] = buf[2];
p[2] = buf[1];
p[3] = buf[0];
if (tag_size == 0 || tag_size + 4 > file_size) {
file_size = 0;
goto done;
}
if (ngx_read_file(&rctx->file, buf, 8, file_size - tag_size - 4) != 8)
{
ngx_log_error(NGX_LOG_CRIT, s->log, ngx_errno,
"record: %V tag read failed", &rracf->id);
goto done;
}
p = (u_char *) &mlen;
p[0] = buf[3];
p[1] = buf[2];
p[2] = buf[1];
p[3] = 0;
if (tag_size != mlen + 11) {
ngx_log_error(NGX_LOG_CRIT, s->log, ngx_errno,
"record: %V tag size mismatch: "
"tag_size=%uD, mlen=%uD", &rracf->id, tag_size, mlen);
goto done;
}
p = (u_char *) ×tamp;
p[3] = buf[7];
p[0] = buf[6];
p[1] = buf[5];
p[2] = buf[4];
done:
rctx->file.offset = file_size;
rctx->time_shift = timestamp;
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: append offset=%O, time=%uD, tag_size=%uD",
file_size, timestamp, tag_size);
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_record_init(ngx_rtmp_session_t *s)
{
ngx_rtmp_record_app_conf_t *racf, **rracf;
ngx_rtmp_record_rec_ctx_t *rctx;
ngx_rtmp_record_ctx_t *ctx;
ngx_uint_t n;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
if (ctx) {
return NGX_OK;
}
racf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_record_module);
if (racf == NULL || racf->rec.nelts == 0) {
return NGX_OK;
}
ctx = ngx_pcalloc(s->connection->pool, sizeof(ngx_rtmp_record_ctx_t));
if (ctx == NULL) {
return NGX_ERROR;
}
ngx_rtmp_set_ctx(s, ctx, ngx_rtmp_record_module);
if (ngx_array_init(&ctx->rec, s->connection->pool, racf->rec.nelts,
sizeof(ngx_rtmp_record_rec_ctx_t))
!= NGX_OK)
{
return NGX_ERROR;
}
rracf = racf->rec.elts;
rctx = ngx_array_push_n(&ctx->rec, racf->rec.nelts);
if (rctx == NULL) {
return NGX_ERROR;
}
for (n = 0; n < racf->rec.nelts; ++n, ++rracf, ++rctx) {
ngx_memzero(rctx, sizeof(*rctx));
rctx->conf = *rracf;
rctx->file.fd = NGX_INVALID_FILE;
}
return NGX_OK;
}
static void
ngx_rtmp_record_start(ngx_rtmp_session_t *s)
{
ngx_rtmp_record_app_conf_t *racf;
ngx_rtmp_record_rec_ctx_t *rctx;
ngx_rtmp_record_ctx_t *ctx;
ngx_uint_t n;
racf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_record_module);
if (racf == NULL || racf->rec.nelts == 0) {
return;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
if (ctx == NULL) {
return;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: start");
rctx = ctx->rec.elts;
for (n = 0; n < ctx->rec.nelts; ++n, ++rctx) {
if (rctx->conf->flags & (NGX_RTMP_RECORD_OFF|NGX_RTMP_RECORD_MANUAL)) {
continue;
}
ngx_rtmp_record_node_open(s, rctx);
}
}
static void
ngx_rtmp_record_stop(ngx_rtmp_session_t *s)
{
ngx_rtmp_record_app_conf_t *racf;
ngx_rtmp_record_rec_ctx_t *rctx;
ngx_rtmp_record_ctx_t *ctx;
ngx_uint_t n;
racf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_record_module);
if (racf == NULL || racf->rec.nelts == 0) {
return;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
if (ctx == NULL) {
return;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: stop");
rctx = ctx->rec.elts;
for (n = 0; n < ctx->rec.nelts; ++n, ++rctx) {
ngx_rtmp_record_node_close(s, rctx);
}
}
static ngx_int_t
ngx_rtmp_record_publish(ngx_rtmp_session_t *s, ngx_rtmp_publish_t *v)
{
ngx_rtmp_record_app_conf_t *racf;
ngx_rtmp_record_ctx_t *ctx;
u_char *p;
if (s->interprocess) {
goto next;
}
racf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_record_module);
if (racf == NULL || racf->rec.nelts == 0) {
goto next;
}
if (ngx_rtmp_record_init(s) != NGX_OK) {
return NGX_ERROR;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: publish %ui nodes",
racf->rec.nelts);
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
ngx_memcpy(ctx->name, v->name, sizeof(ctx->name));
ngx_memcpy(ctx->args, v->args, sizeof(ctx->args));
/* terminate name on /../ */
for (p = ctx->name; *p; ++p) {
if (ngx_path_separator(p[0]) &&
p[1] == '.' && p[2] == '.' &&
ngx_path_separator(p[3]))
{
*p = 0;
break;
}
}
ngx_rtmp_record_start(s);
next:
return next_publish(s, v);
}
static ngx_int_t
ngx_rtmp_record_stream_begin(ngx_rtmp_session_t *s, ngx_rtmp_stream_begin_t *v)
{
if (s->interprocess) {
goto next;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: stream_begin");
ngx_rtmp_record_start(s);
next:
return next_stream_begin(s, v);
}
static ngx_int_t
ngx_rtmp_record_stream_eof(ngx_rtmp_session_t *s, ngx_rtmp_stream_begin_t *v)
{
if (s->interprocess) {
goto next;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: stream_eof");
ngx_rtmp_record_stop(s);
next:
return next_stream_eof(s, v);
}
static ngx_int_t
ngx_rtmp_record_node_close(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx)
{
ngx_rtmp_record_app_conf_t *rracf;
ngx_err_t err;
void **app_conf;
ngx_int_t rc;
ngx_rtmp_record_done_t v;
u_char av;
rracf = rctx->conf;
if (rctx->file.fd == NGX_INVALID_FILE) {
return NGX_AGAIN;
}
if (rctx->initialized) {
av = 0;
if (rctx->video) {
av |= 0x01;
}
if (rctx->audio) {
av |= 0x04;
}
if (ngx_write_file(&rctx->file, &av, 1, 4) == NGX_ERROR) {
ngx_log_error(NGX_LOG_CRIT, s->log, ngx_errno,
"record: %V error writing av mask", &rracf->id);
}
}
if (ngx_close_file(rctx->file.fd) == NGX_FILE_ERROR) {
err = ngx_errno;
ngx_log_error(NGX_LOG_CRIT, s->log, err,
"record: %V error closing file", &rracf->id);
ngx_rtmp_record_notify_error(s, rctx);
}
rctx->file.fd = NGX_INVALID_FILE;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V closed", &rracf->id);
if (rracf->notify) {
ngx_rtmp_send_status(s, "NetStream.Record.Stop", "status",
rracf->id.data ? (char *) rracf->id.data : "");
}
app_conf = s->app_conf;
if (rracf->rec_conf) {
s->app_conf = rracf->rec_conf;
}
v.recorder = rracf->id;
ngx_rtmp_record_make_path(s, rctx, &v.path);
rc = ngx_rtmp_record_done(s, &v);
s->app_conf = app_conf;
return rc;
}
static ngx_int_t
ngx_rtmp_record_close_stream(ngx_rtmp_session_t *s,
ngx_rtmp_close_stream_t *v)
{
if (s->interprocess) {
goto next;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: close_stream");
ngx_rtmp_record_stop(s);
next:
return next_close_stream(s, v);
}
static ngx_int_t
ngx_rtmp_record_write_frame(ngx_rtmp_session_t *s,
ngx_rtmp_record_rec_ctx_t *rctx,
ngx_rtmp_header_t *h, ngx_chain_t *in,
ngx_int_t inc_nframes)
{
u_char hdr[11], *p, *ph;
uint32_t timestamp, tag_size;
ngx_rtmp_record_app_conf_t *rracf;
rracf = rctx->conf;
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V frame: mlen=%uD",
&rracf->id, h->mlen);
if (h->type == NGX_RTMP_MSG_VIDEO) {
rctx->video = 1;
} else {
rctx->audio = 1;
}
timestamp = h->timestamp - rctx->epoch;
if ((int32_t) timestamp < 0) {
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V cut timestamp=%D", &rracf->id, timestamp);
timestamp = 0;
}
/* write tag header */
ph = hdr;
*ph++ = (u_char)h->type;
p = (u_char*)&h->mlen;
*ph++ = p[2];
*ph++ = p[1];
*ph++ = p[0];
p = (u_char*)×tamp;
*ph++ = p[2];
*ph++ = p[1];
*ph++ = p[0];
*ph++ = p[3];
*ph++ = 0;
*ph++ = 0;
*ph++ = 0;
tag_size = (ph - hdr) + h->mlen;
if (ngx_write_file(&rctx->file, hdr, ph - hdr, rctx->file.offset)
== NGX_ERROR)
{
ngx_rtmp_record_notify_error(s, rctx);
ngx_close_file(rctx->file.fd);
return NGX_ERROR;
}
/* write tag body
* FIXME: NGINX
* ngx_write_chain seems to fit best
* but it suffers from uncontrollable
* allocations.
* we're left with plain writing */
for(; in; in = in->next) {
if (in->buf->pos == in->buf->last) {
continue;
}
if (ngx_write_file(&rctx->file, in->buf->pos, in->buf->last
- in->buf->pos, rctx->file.offset)
== NGX_ERROR)
{
return NGX_ERROR;
}
}
/* write tag size */
ph = hdr;
p = (u_char*)&tag_size;
*ph++ = p[3];
*ph++ = p[2];
*ph++ = p[1];
*ph++ = p[0];
if (ngx_write_file(&rctx->file, hdr, ph - hdr,
rctx->file.offset)
== NGX_ERROR)
{
return NGX_ERROR;
}
rctx->nframes += inc_nframes;
/* watch max size */
if ((rracf->max_size && rctx->file.offset >= (ngx_int_t) rracf->max_size) ||
(rracf->max_frames && rctx->nframes >= rracf->max_frames))
{
ngx_rtmp_record_node_close(s, rctx);
}
return NGX_OK;
}
static size_t
ngx_rtmp_record_get_chain_mlen(ngx_chain_t *in)
{
size_t ret;
for (ret = 0; in; in = in->next) {
ret += (in->buf->last - in->buf->pos);
}
return ret;
}
static ngx_int_t
ngx_rtmp_record_av(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_rtmp_record_ctx_t *ctx;
ngx_rtmp_record_rec_ctx_t *rctx;
ngx_uint_t n;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_record_module);
if (ctx == NULL || s->pause) {
return NGX_OK;
}
rctx = ctx->rec.elts;
for (n = 0; n < ctx->rec.nelts; ++n, ++rctx) {
ngx_rtmp_record_node_av(s, rctx, h, in);
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_record_node_av(ngx_rtmp_session_t *s, ngx_rtmp_record_rec_ctx_t *rctx,
ngx_rtmp_header_t *h, ngx_chain_t *in)
{
ngx_time_t next;
ngx_rtmp_header_t ch;
ngx_rtmp_codec_ctx_t *codec_ctx;
ngx_int_t keyframe, brkframe;
ngx_rtmp_record_app_conf_t *rracf;
rracf = rctx->conf;
if (rracf->flags & NGX_RTMP_RECORD_OFF) {
ngx_rtmp_record_node_close(s, rctx);
return NGX_OK;
}
keyframe = (h->type == NGX_RTMP_MSG_VIDEO)
? (ngx_rtmp_get_video_frame_type(in) == NGX_RTMP_VIDEO_KEY_FRAME)
: 0;
brkframe = (h->type == NGX_RTMP_MSG_VIDEO)
? keyframe
: (rracf->flags & NGX_RTMP_RECORD_VIDEO) == 0;
if (brkframe && (rracf->flags & NGX_RTMP_RECORD_MANUAL) == 0) {
if (rracf->interval != (ngx_msec_t) NGX_CONF_UNSET) {
next = rctx->last;
next.msec += rracf->interval;
next.sec += (next.msec / 1000);
next.msec %= 1000;
if (ngx_cached_time->sec > next.sec ||
(ngx_cached_time->sec == next.sec &&
ngx_cached_time->msec > next.msec))
{
ngx_rtmp_record_node_close(s, rctx);
ngx_rtmp_record_node_open(s, rctx);
}
} else if (!rctx->failed) {
ngx_rtmp_record_node_open(s, rctx);
}
}
if ((rracf->flags & NGX_RTMP_RECORD_MANUAL) &&
!brkframe && rctx->nframes == 0)
{
return NGX_OK;
}
if (rctx->file.fd == NGX_INVALID_FILE) {
return NGX_OK;
}
if (h->type == NGX_RTMP_MSG_AUDIO &&
(rracf->flags & NGX_RTMP_RECORD_AUDIO) == 0)
{
return NGX_OK;
}
if (h->type == NGX_RTMP_MSG_VIDEO &&
(rracf->flags & NGX_RTMP_RECORD_VIDEO) == 0 &&
((rracf->flags & NGX_RTMP_RECORD_KEYFRAMES) == 0 || !keyframe))
{
return NGX_OK;
}
if (!rctx->initialized) {
rctx->initialized = 1;
rctx->epoch = h->timestamp - rctx->time_shift;
if (rctx->file.offset == 0 &&
ngx_rtmp_record_write_header(&rctx->file) != NGX_OK)
{
ngx_rtmp_record_node_close(s, rctx);
return NGX_OK;
}
}
codec_ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_codec_module);
if (codec_ctx) {
ch = *h;
/* AAC header */
if (!rctx->aac_header_sent && codec_ctx->aac_header &&
(rracf->flags & NGX_RTMP_RECORD_AUDIO))
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V writing AAC header", &rracf->id);
ch.type = NGX_RTMP_MSG_AUDIO;
ch.mlen =
ngx_rtmp_record_get_chain_mlen(codec_ctx->aac_header->chain);
if (ngx_rtmp_record_write_frame(s, rctx, &ch,
codec_ctx->aac_header->chain, 0)
!= NGX_OK)
{
return NGX_OK;
}
rctx->aac_header_sent = 1;
}
/* AVC header */
if (!rctx->avc_header_sent && codec_ctx->avc_header &&
(rracf->flags & (NGX_RTMP_RECORD_VIDEO|
NGX_RTMP_RECORD_KEYFRAMES)))
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V writing AVC header", &rracf->id);
ch.type = NGX_RTMP_MSG_VIDEO;
ch.mlen =
ngx_rtmp_record_get_chain_mlen(codec_ctx->avc_header->chain);
if (ngx_rtmp_record_write_frame(s, rctx, &ch,
codec_ctx->avc_header->chain, 0)
!= NGX_OK)
{
return NGX_OK;
}
rctx->avc_header_sent = 1;
}
}
if (h->type == NGX_RTMP_MSG_VIDEO) {
if (codec_ctx && codec_ctx->video_codec_id == NGX_RTMP_VIDEO_H264 &&
!rctx->avc_header_sent)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V skipping until H264 header", &rracf->id);
return NGX_OK;
}
if (ngx_rtmp_get_video_frame_type(in) == NGX_RTMP_VIDEO_KEY_FRAME &&
((codec_ctx && codec_ctx->video_codec_id != NGX_RTMP_VIDEO_H264) ||
!ngx_rtmp_is_codec_header(in)))
{
rctx->video_key_sent = 1;
}
if (!rctx->video_key_sent) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V skipping until keyframe", &rracf->id);
return NGX_OK;
}
} else {
if (codec_ctx && codec_ctx->audio_codec_id == NGX_RTMP_AUDIO_AAC &&
!rctx->aac_header_sent)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"record: %V skipping until AAC header", &rracf->id);
return NGX_OK;
}
}
return ngx_rtmp_record_write_frame(s, rctx, h, in, 1);
}
static ngx_int_t
ngx_rtmp_record_done_init(ngx_rtmp_session_t *s, ngx_rtmp_record_done_t *v)
{
return NGX_OK;
}
static char *
ngx_rtmp_record_recorder(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *rv;
ngx_int_t i;
ngx_str_t *value;
ngx_conf_t save;
ngx_module_t **modules;
ngx_rtmp_module_t *module;
ngx_rtmp_core_app_conf_t *cacf, **pcacf, *rcacf;
ngx_rtmp_record_app_conf_t *racf, **pracf, *rracf;
ngx_rtmp_conf_ctx_t *ctx, *pctx;
value = cf->args->elts;
cacf = ngx_rtmp_conf_get_module_app_conf(cf, ngx_rtmp_core_module);
racf = ngx_rtmp_conf_get_module_app_conf(cf, ngx_rtmp_record_module);
ctx = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_conf_ctx_t));
if (ctx == NULL) {
return NGX_CONF_ERROR;
}
pctx = cf->ctx;
ctx->main_conf = pctx->main_conf;
ctx->srv_conf = pctx->srv_conf;
ctx->app_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->app_conf == NULL) {
return NGX_CONF_ERROR;
}
#if (nginx_version >= 1009011)
modules = cf->cycle->modules;
#else
modules = ngx_modules;
#endif
for (i = 0; modules[i]; i++) {
if (modules[i]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[i]->ctx;
if (module->create_app_conf) {
ctx->app_conf[modules[i]->ctx_index] = module->create_app_conf(cf);
if (ctx->app_conf[modules[i]->ctx_index] == NULL) {
return NGX_CONF_ERROR;
}
}
}
/* add to sub-applications */
rcacf = ctx->app_conf[ngx_rtmp_core_module.ctx_index];
rcacf->app_conf = ctx->app_conf;
pcacf = ngx_array_push(&cacf->applications);
if (pcacf == NULL) {
return NGX_CONF_ERROR;
}
*pcacf = rcacf;
/* add to recorders */
rracf = ctx->app_conf[ngx_rtmp_record_module.ctx_index];
rracf->rec_conf = ctx->app_conf;
pracf = ngx_array_push(&racf->rec);
if (pracf == NULL) {
return NGX_CONF_ERROR;
}
*pracf = rracf;
rracf->id = value[1];
save = *cf;
cf->ctx = ctx;
cf->cmd_type = NGX_RTMP_REC_CONF;
rv = ngx_conf_parse(cf, NULL);
*cf= save;
return rv;
}
static ngx_int_t
ngx_rtmp_record_postconfiguration(ngx_conf_t *cf)
{
ngx_rtmp_core_main_conf_t *cmcf;
ngx_rtmp_handler_pt *h;
ngx_rtmp_record_done = ngx_rtmp_record_done_init;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
h = ngx_array_push(&cmcf->events[NGX_RTMP_MSG_AUDIO]);
*h = ngx_rtmp_record_av;
h = ngx_array_push(&cmcf->events[NGX_RTMP_MSG_VIDEO]);
*h = ngx_rtmp_record_av;
next_publish = ngx_rtmp_publish;
ngx_rtmp_publish = ngx_rtmp_record_publish;
next_close_stream = ngx_rtmp_close_stream;
ngx_rtmp_close_stream = ngx_rtmp_record_close_stream;
next_stream_begin = ngx_rtmp_stream_begin;
ngx_rtmp_stream_begin = ngx_rtmp_record_stream_begin;
next_stream_eof = ngx_rtmp_stream_eof;
ngx_rtmp_stream_eof = ngx_rtmp_record_stream_eof;
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 4,519 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js
|
/*!
DataTables Bootstrap 4 integration
©2011-2017 SpryMedia Ltd - datatables.net/license
*/
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(a,b,c){a instanceof String&&(a=String(a));for(var e=a.length,d=0;d<e;d++){var f=a[d];if(b.call(c,f,d,a))return{i:d,v:f}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){if(a==Array.prototype||a==Object.prototype)return a;a[b]=c.value;return a};$jscomp.getGlobal=function(a){a=["object"==typeof globalThis&&globalThis,a,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var b=0;b<a.length;++b){var c=a[b];if(c&&c.Math==Math)return c}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(a,b){var c=$jscomp.propertyToPolyfillSymbol[b];if(null==c)return a[b];c=a[c];return void 0!==c?c:a[b]};
$jscomp.polyfill=function(a,b,c,e){b&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(a,b,c,e):$jscomp.polyfillUnisolated(a,b,c,e))};$jscomp.polyfillUnisolated=function(a,b,c,e){c=$jscomp.global;a=a.split(".");for(e=0;e<a.length-1;e++){var d=a[e];if(!(d in c))return;c=c[d]}a=a[a.length-1];e=c[a];b=b(e);b!=e&&null!=b&&$jscomp.defineProperty(c,a,{configurable:!0,writable:!0,value:b})};
$jscomp.polyfillIsolated=function(a,b,c,e){var d=a.split(".");a=1===d.length;e=d[0];e=!a&&e in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var f=0;f<d.length-1;f++){var l=d[f];if(!(l in e))return;e=e[l]}d=d[d.length-1];c=$jscomp.IS_SYMBOL_NATIVE&&"es6"===c?e[d]:null;b=b(c);null!=b&&(a?$jscomp.defineProperty($jscomp.polyfills,d,{configurable:!0,writable:!0,value:b}):b!==c&&($jscomp.propertyToPolyfillSymbol[d]=$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(d):$jscomp.POLYFILL_PREFIX+d,d=
$jscomp.propertyToPolyfillSymbol[d],$jscomp.defineProperty(e,d,{configurable:!0,writable:!0,value:b})))};$jscomp.polyfill("Array.prototype.find",function(a){return a?a:function(b,c){return $jscomp.findInternal(this,b,c).v}},"es6","es3");
(function(a){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(b){return a(b,window,document)}):"object"===typeof exports?module.exports=function(b,c){b||(b=window);c&&c.fn.dataTable||(c=require("datatables.net")(b,c).$);return a(c,b,b.document)}:a(jQuery,window,document)})(function(a,b,c,e){var d=a.fn.dataTable;a.extend(!0,d.defaults,{dom:"<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>><'row'<'col-sm-12'tr>><'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
renderer:"bootstrap"});a.extend(d.ext.classes,{sWrapper:"dataTables_wrapper dt-bootstrap4",sFilterInput:"form-control form-control-sm",sLengthSelect:"custom-select custom-select-sm form-control form-control-sm",sProcessing:"dataTables_processing card",sPageButton:"paginate_button page-item"});d.ext.renderer.pageButton.bootstrap=function(f,l,A,B,m,t){var u=new d.Api(f),C=f.oClasses,n=f.oLanguage.oPaginate,D=f.oLanguage.oAria.paginate||{},h,k,v=0,y=function(q,w){var x,E=function(p){p.preventDefault();
a(p.currentTarget).hasClass("disabled")||u.page()==p.data.action||u.page(p.data.action).draw("page")};var r=0;for(x=w.length;r<x;r++){var g=w[r];if(Array.isArray(g))y(q,g);else{k=h="";switch(g){case "ellipsis":h="…";k="disabled";break;case "first":h=n.sFirst;k=g+(0<m?"":" disabled");break;case "previous":h=n.sPrevious;k=g+(0<m?"":" disabled");break;case "next":h=n.sNext;k=g+(m<t-1?"":" disabled");break;case "last":h=n.sLast;k=g+(m<t-1?"":" disabled");break;default:h=g+1,k=m===g?"active":""}if(h){var F=
a("<li>",{"class":C.sPageButton+" "+k,id:0===A&&"string"===typeof g?f.sTableId+"_"+g:null}).append(a("<a>",{href:"#","aria-controls":f.sTableId,"aria-label":D[g],"data-dt-idx":v,tabindex:f.iTabIndex,"class":"page-link"}).html(h)).appendTo(q);f.oApi._fnBindAction(F,{action:g},E);v++}}}};try{var z=a(l).find(c.activeElement).data("dt-idx")}catch(q){}y(a(l).empty().html('<ul class="pagination"/>').children("ul"),B);z!==e&&a(l).find("[data-dt-idx="+z+"]").trigger("focus")};return d});
|
294coder/Efficient-MIF
| 2,295 |
utils/FS_index/D_lambda_K.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
Spectral distorsion index
Interface:
Dl = D_lambda_K(fused,ms,ratio,sensor,S)
Inputs:
fused: Pansharpened image;
ms: Original MS image;
ratio: Scale ratio between MS and PAN. Pre-condition: Integer value;
sensor: String for type of sensor (e.g. 'WV2','IKONOS');
S: Block size.
Output:
Dl: Spectral distorsion index.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
from .MTF import MTF
# from .q2n import q2n
from .my_q2n import q2n
def D_lambda_K(fused,ms,ratio,sensor,S):
if (fused.shape[0] != (ms.shape[0]) or fused.shape[1] != ms.shape[1]) == 1:
print("The two images must have the same dimensions")
return -1
# N = fused.shape[0]
# M = fused.shape[1]
# if np.remainder(N,S-1) != 0:
# print("Number of rows must be multiple of the block size")
# return -1
# if np.remainder(M,S-1) != 0:
# print("Number of columns must be multiple of the block size")
# return -1
fused_degraded = MTF(fused,sensor,ratio)
# fused_degraded = fused_degraded[int(ratio/2):-1:int(ratio),int(ratio/2):-1:int(ratio),:]
Q2n_index, q2n_map = q2n(ms, fused_degraded, S, S)
Dl = 1 - Q2n_index
Dl_map = 1 - q2n_map
return Dl, Dl_map
|
294coder/Efficient-MIF
| 2,167 |
utils/FS_index/MTF.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
MTF filters the image I_MS using a Gaussin filter matched with the Modulation Transfer Function (MTF) of the MultiSpectral (MS) sensor.
Interface:
I_Filtered = MTF(I_MS,sensor,ratio)
Inputs:
I_MS: MS image;
sensor: String for type of sensor (e.g. 'WV2', 'IKONOS');
ratio: Scale ratio between MS and PAN.
Outputs:
I_Filtered: Output filtered MS image.
Notes:
The bottleneck of this function is the function scipy.filters.correlate that gets the same results as in the MATLAB toolbox
but it is very slow with respect to fftconvolve that instead gets slightly different results
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
from scipy import ndimage
import numpy as np
from .genMTF import genMTF
def MTF(I_MS,sensor,ratio):
h = genMTF(ratio, sensor,I_MS.shape[2])
I_MS_LP = np.zeros((I_MS.shape))
for ii in range(I_MS.shape[2]):
I_MS_LP[:,:,ii] = ndimage.filters.correlate(I_MS[:,:,ii],h[:,:,ii],mode='nearest')
### This can speed-up the processing, but with slightly different results with respect to the MATLAB toolbox
# hb = h[:,:,ii]
# I_MS_LP[:,:,ii] = signal.fftconvolve(I_MS[:,:,ii],hb[::-1],mode='same')
return np.double(I_MS_LP)
|
2881099/FreeSql.AdminLTE
| 4,705 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/datatables-bs4/js/dataTables.bootstrap4.js
|
/*! DataTables Bootstrap 4 integration
* ©2011-2017 SpryMedia Ltd - datatables.net/license
*/
/**
* DataTables integration for Bootstrap 4. This requires Bootstrap 4 and
* DataTables 1.10 or newer.
*
* This file sets the defaults and adds options to DataTables to style its
* controls using Bootstrap. See http://datatables.net/manual/styling/bootstrap
* for further information.
*/
(function( factory ){
if ( typeof define === 'function' && define.amd ) {
// AMD
define( ['jquery', 'datatables.net'], function ( $ ) {
return factory( $, window, document );
} );
}
else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
if ( ! root ) {
root = window;
}
if ( ! $ || ! $.fn.dataTable ) {
// Require DataTables, which attaches to jQuery, including
// jQuery if needed and have a $ property so we can access the
// jQuery object that is used
$ = require('datatables.net')(root, $).$;
}
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;
/* Set the defaults for DataTables initialisation */
$.extend( true, DataTable.defaults, {
dom:
"<'row'<'col-sm-12 col-md-6'l><'col-sm-12 col-md-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-12 col-md-5'i><'col-sm-12 col-md-7'p>>",
renderer: 'bootstrap'
} );
/* Default class modification */
$.extend( DataTable.ext.classes, {
sWrapper: "dataTables_wrapper dt-bootstrap4",
sFilterInput: "form-control form-control-sm",
sLengthSelect: "custom-select custom-select-sm form-control form-control-sm",
sProcessing: "dataTables_processing card",
sPageButton: "paginate_button page-item"
} );
/* Bootstrap paging button renderer */
DataTable.ext.renderer.pageButton.bootstrap = function ( settings, host, idx, buttons, page, pages ) {
var api = new DataTable.Api( settings );
var classes = settings.oClasses;
var lang = settings.oLanguage.oPaginate;
var aria = settings.oLanguage.oAria.paginate || {};
var btnDisplay, btnClass, counter=0;
var attach = function( container, buttons ) {
var i, ien, node, button;
var clickHandler = function ( e ) {
e.preventDefault();
if ( !$(e.currentTarget).hasClass('disabled') && api.page() != e.data.action ) {
api.page( e.data.action ).draw( 'page' );
}
};
for ( i=0, ien=buttons.length ; i<ien ; i++ ) {
button = buttons[i];
if ( Array.isArray( button ) ) {
attach( container, button );
}
else {
btnDisplay = '';
btnClass = '';
switch ( button ) {
case 'ellipsis':
btnDisplay = '…';
btnClass = 'disabled';
break;
case 'first':
btnDisplay = lang.sFirst;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'previous':
btnDisplay = lang.sPrevious;
btnClass = button + (page > 0 ?
'' : ' disabled');
break;
case 'next':
btnDisplay = lang.sNext;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
case 'last':
btnDisplay = lang.sLast;
btnClass = button + (page < pages-1 ?
'' : ' disabled');
break;
default:
btnDisplay = button + 1;
btnClass = page === button ?
'active' : '';
break;
}
if ( btnDisplay ) {
node = $('<li>', {
'class': classes.sPageButton+' '+btnClass,
'id': idx === 0 && typeof button === 'string' ?
settings.sTableId +'_'+ button :
null
} )
.append( $('<a>', {
'href': '#',
'aria-controls': settings.sTableId,
'aria-label': aria[ button ],
'data-dt-idx': counter,
'tabindex': settings.iTabIndex,
'class': 'page-link'
} )
.html( btnDisplay )
)
.appendTo( container );
settings.oApi._fnBindAction(
node, {action: button}, clickHandler
);
counter++;
}
}
}
};
// IE9 throws an 'unknown error' if document.activeElement is used
// inside an iframe or frame.
var activeEl;
try {
// Because this approach is destroying and recreating the paging
// elements, focus is lost on the select button which is bad for
// accessibility. So we want to restore focus once the draw has
// completed
activeEl = $(host).find(document.activeElement).data('dt-idx');
}
catch (e) {}
attach(
$(host).empty().html('<ul class="pagination"/>').children('ul'),
buttons
);
if ( activeEl !== undefined ) {
$(host).find( '[data-dt-idx='+activeEl+']' ).trigger('focus');
}
};
return DataTable;
}));
|
281677160/openwrt-package
| 40,426 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_exec_module.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp_cmd_module.h"
#include "ngx_rtmp_eval.h"
#include "ngx_poold.h"
#include <stdlib.h>
#ifdef NGX_LINUX
#include <unistd.h>
#endif
#if !(NGX_WIN32)
static ngx_rtmp_publish_pt next_publish;
static ngx_rtmp_play_pt next_play;
static ngx_rtmp_close_stream_pt next_close_stream;
#endif
static ngx_int_t ngx_rtmp_exec_init_process(ngx_cycle_t *cycle);
static ngx_int_t ngx_rtmp_exec_postconfiguration(ngx_conf_t *cf);
static void * ngx_rtmp_exec_create_main_conf(ngx_conf_t *cf);
static char * ngx_rtmp_exec_init_main_conf(ngx_conf_t *cf, void *conf);
static void * ngx_rtmp_exec_create_app_conf(ngx_conf_t *cf);
static char * ngx_rtmp_exec_merge_app_conf(ngx_conf_t *cf,
void *parent, void *child);
/*static char * ngx_rtmp_exec_block(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);*/
static char * ngx_rtmp_exec_conf(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char *ngx_rtmp_exec_kill_signal(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
#define NGX_RTMP_EXEC_RESPAWN 0x01
#define NGX_RTMP_EXEC_KILL 0x02
#define NGX_RTMP_EXEC_PUBLISHING 0x01
#define NGX_RTMP_EXEC_PLAYING 0x02
enum {
NGX_RTMP_EXEC_PUSH,
NGX_RTMP_EXEC_PULL,
NGX_RTMP_EXEC_PUBLISH,
NGX_RTMP_EXEC_PUBLISH_DONE,
NGX_RTMP_EXEC_PLAY,
NGX_RTMP_EXEC_PLAY_DONE,
NGX_RTMP_EXEC_RECORD_DONE,
NGX_RTMP_EXEC_MAX,
NGX_RTMP_EXEC_STATIC
};
typedef struct {
ngx_str_t id;
ngx_uint_t type;
ngx_str_t cmd;
ngx_array_t args; /* ngx_str_t */
ngx_array_t names;
} ngx_rtmp_exec_conf_t;
typedef struct {
ngx_rtmp_exec_conf_t *conf;
ngx_log_t *log;
ngx_rtmp_eval_t **eval;
void *eval_ctx;
unsigned active:1;
unsigned managed:1;
ngx_pid_t pid;
ngx_pid_t *save_pid;
int pipefd;
ngx_connection_t dummy_conn; /*needed by ngx_xxx_event*/
ngx_event_t read_evt, write_evt;
ngx_event_t respawn_evt;
ngx_msec_t respawn_timeout;
ngx_int_t kill_signal;
} ngx_rtmp_exec_t;
typedef struct {
ngx_array_t static_conf; /* ngx_rtmp_exec_conf_t */
ngx_array_t static_exec; /* ngx_rtmp_exec_t */
ngx_msec_t respawn_timeout;
ngx_int_t kill_signal;
ngx_log_t *log;
} ngx_rtmp_exec_main_conf_t;
typedef struct ngx_rtmp_exec_pull_ctx_s ngx_rtmp_exec_pull_ctx_t;
struct ngx_rtmp_exec_pull_ctx_s {
ngx_pool_t *pool;
ngx_uint_t counter;
ngx_str_t name;
ngx_str_t app;
ngx_array_t pull_exec; /* ngx_rtmp_exec_t */
ngx_rtmp_exec_pull_ctx_t *next;
};
typedef struct {
ngx_int_t active;
ngx_array_t conf[NGX_RTMP_EXEC_MAX];
/* ngx_rtmp_exec_conf_t */
ngx_flag_t respawn;
ngx_flag_t options;
ngx_uint_t nbuckets;
ngx_rtmp_exec_pull_ctx_t **pull;
} ngx_rtmp_exec_app_conf_t;
typedef struct {
ngx_uint_t flags;
ngx_str_t path; /* /tmp/rec/myfile-123.flv */
ngx_str_t filename; /* myfile-123.flv */
ngx_str_t basename; /* myfile-123 */
ngx_str_t dirname; /* /tmp/rec */
ngx_str_t recorder;
u_char name[NGX_RTMP_MAX_NAME];
u_char args[NGX_RTMP_MAX_ARGS];
u_char starttime[NGX_RTMP_MAX_NAME];
ngx_array_t push_exec; /* ngx_rtmp_exec_t */
ngx_rtmp_exec_pull_ctx_t *pull;
} ngx_rtmp_exec_ctx_t;
#if !(NGX_WIN32)
static void ngx_rtmp_exec_respawn(ngx_event_t *ev);
static ngx_int_t ngx_rtmp_exec_kill(ngx_rtmp_exec_t *e, ngx_int_t kill_signal);
static ngx_int_t ngx_rtmp_exec_run(ngx_rtmp_exec_t *e);
#endif
static ngx_command_t ngx_rtmp_exec_commands[] = {
/*
{ ngx_string("exec_block"),
NGX_RTMP_APP_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS|NGX_CONF_TAKE1,
ngx_rtmp_exec_block,
NGX_RTMP_APP_CONF_OFFSET,
0,
NULL },
*/
{ ngx_string("exec"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PUSH * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_push"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PUSH * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_pull"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PULL * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_publish"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PUBLISH * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_publish_done"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PUBLISH_DONE * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_play"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PLAY * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_play_done"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_PLAY_DONE * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_record_done"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_RTMP_REC_CONF|
NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, conf) +
NGX_RTMP_EXEC_RECORD_DONE * sizeof(ngx_array_t),
NULL },
{ ngx_string("exec_static"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_rtmp_exec_conf,
NGX_RTMP_MAIN_CONF_OFFSET,
offsetof(ngx_rtmp_exec_main_conf_t, static_conf),
NULL },
{ ngx_string("respawn"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, respawn),
NULL },
{ ngx_string("respawn_timeout"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_MAIN_CONF_OFFSET,
offsetof(ngx_rtmp_exec_main_conf_t, respawn_timeout),
NULL },
{ ngx_string("exec_kill_signal"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_rtmp_exec_kill_signal,
NGX_RTMP_MAIN_CONF_OFFSET,
0,
NULL },
{ ngx_string("exec_options"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_exec_app_conf_t, options),
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_rtmp_exec_module_ctx = {
NULL, /* preconfiguration */
ngx_rtmp_exec_postconfiguration, /* postconfiguration */
ngx_rtmp_exec_create_main_conf, /* create main configuration */
ngx_rtmp_exec_init_main_conf, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_rtmp_exec_create_app_conf, /* create app configuration */
ngx_rtmp_exec_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_rtmp_exec_module = {
NGX_MODULE_V1,
&ngx_rtmp_exec_module_ctx, /* module context */
ngx_rtmp_exec_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
ngx_rtmp_exec_init_process, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void
ngx_rtmp_exec_eval_ctx_cstr(void *sctx, ngx_rtmp_eval_t *e, ngx_str_t *ret)
{
ngx_rtmp_session_t *s = sctx;
ngx_rtmp_exec_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
if (ctx == NULL) {
ret->len = 0;
return;
}
ret->data = (u_char *) ctx + e->offset;
ret->len = ngx_strlen(ret->data);
}
static void
ngx_rtmp_exec_eval_ctx_str(void *sctx, ngx_rtmp_eval_t *e, ngx_str_t *ret)
{
ngx_rtmp_session_t *s = sctx;
ngx_rtmp_exec_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
if (ctx == NULL) {
ret->len = 0;
return;
}
*ret = * (ngx_str_t *) ((u_char *) ctx + e->offset);
}
static void
ngx_rtmp_exec_eval_pctx_str(void *ctx, ngx_rtmp_eval_t *e, ngx_str_t *ret)
{
*ret = *(ngx_str_t *) ((u_char *) ctx + e->offset);
}
static ngx_rtmp_eval_t ngx_rtmp_exec_push_specific_eval[] = {
{ ngx_string("name"),
ngx_rtmp_exec_eval_ctx_cstr,
offsetof(ngx_rtmp_exec_ctx_t, name) },
{ ngx_string("args"),
ngx_rtmp_exec_eval_ctx_cstr,
offsetof(ngx_rtmp_exec_ctx_t, args) },
ngx_rtmp_null_eval
};
static ngx_rtmp_eval_t * ngx_rtmp_exec_push_eval[] = {
ngx_rtmp_eval_session,
ngx_rtmp_exec_push_specific_eval,
NULL
};
static ngx_rtmp_eval_t ngx_rtmp_exec_pull_specific_eval[] = {
{ ngx_string("name"),
ngx_rtmp_exec_eval_pctx_str,
offsetof(ngx_rtmp_exec_pull_ctx_t, name) },
{ ngx_string("app"),
ngx_rtmp_exec_eval_pctx_str,
offsetof(ngx_rtmp_exec_pull_ctx_t, app) },
ngx_rtmp_null_eval
};
static ngx_rtmp_eval_t * ngx_rtmp_exec_pull_eval[] = {
ngx_rtmp_exec_pull_specific_eval,
NULL
};
static ngx_rtmp_eval_t ngx_rtmp_exec_event_specific_eval[] = {
{ ngx_string("name"),
ngx_rtmp_exec_eval_ctx_cstr,
offsetof(ngx_rtmp_exec_ctx_t, name) },
{ ngx_string("args"),
ngx_rtmp_exec_eval_ctx_cstr,
offsetof(ngx_rtmp_exec_ctx_t, args) },
{ ngx_string("path"),
ngx_rtmp_exec_eval_ctx_str,
offsetof(ngx_rtmp_exec_ctx_t, path) },
{ ngx_string("filename"),
ngx_rtmp_exec_eval_ctx_str,
offsetof(ngx_rtmp_exec_ctx_t, filename) },
{ ngx_string("basename"),
ngx_rtmp_exec_eval_ctx_str,
offsetof(ngx_rtmp_exec_ctx_t, basename) },
{ ngx_string("dirname"),
ngx_rtmp_exec_eval_ctx_str,
offsetof(ngx_rtmp_exec_ctx_t, dirname) },
{ ngx_string("recorder"),
ngx_rtmp_exec_eval_ctx_str,
offsetof(ngx_rtmp_exec_ctx_t, recorder) },
{ ngx_string("starttime"),
ngx_rtmp_exec_eval_ctx_cstr,
offsetof(ngx_rtmp_exec_ctx_t, starttime) },
ngx_rtmp_null_eval
};
static ngx_rtmp_eval_t * ngx_rtmp_exec_event_eval[] = {
ngx_rtmp_eval_session,
ngx_rtmp_exec_event_specific_eval,
NULL
};
static void *
ngx_rtmp_exec_create_main_conf(ngx_conf_t *cf)
{
ngx_rtmp_exec_main_conf_t *emcf;
emcf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_exec_main_conf_t));
if (emcf == NULL) {
return NULL;
}
emcf->respawn_timeout = NGX_CONF_UNSET_MSEC;
emcf->kill_signal = NGX_CONF_UNSET;
if (ngx_array_init(&emcf->static_conf, cf->pool, 1,
sizeof(ngx_rtmp_exec_conf_t)) != NGX_OK)
{
return NULL;
}
return emcf;
}
static char *
ngx_rtmp_exec_init_main_conf(ngx_conf_t *cf, void *conf)
{
ngx_rtmp_exec_main_conf_t *emcf = conf;
ngx_rtmp_exec_conf_t *ec;
ngx_rtmp_exec_t *e;
ngx_uint_t n;
if (emcf->respawn_timeout == NGX_CONF_UNSET_MSEC) {
emcf->respawn_timeout = 5000;
}
#if !(NGX_WIN32)
if (emcf->kill_signal == NGX_CONF_UNSET) {
emcf->kill_signal = SIGKILL;
}
#endif
if (ngx_array_init(&emcf->static_exec, cf->pool,
emcf->static_conf.nelts,
sizeof(ngx_rtmp_exec_t)) != NGX_OK)
{
return NGX_CONF_ERROR;
}
e = ngx_array_push_n(&emcf->static_exec, emcf->static_conf.nelts);
if (e == NULL) {
return NGX_CONF_ERROR;
}
emcf->log = &cf->cycle->new_log;
ec = emcf->static_conf.elts;
for (n = 0; n < emcf->static_conf.nelts; n++, e++, ec++) {
ngx_memzero(e, sizeof(*e));
e->conf = ec;
e->managed = 1;
e->log = emcf->log;
e->respawn_timeout = emcf->respawn_timeout;
e->kill_signal = emcf->kill_signal;
}
return NGX_CONF_OK;
}
static void *
ngx_rtmp_exec_create_app_conf(ngx_conf_t *cf)
{
ngx_rtmp_exec_app_conf_t *eacf;
eacf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_exec_app_conf_t));
if (eacf == NULL) {
return NULL;
}
eacf->respawn = NGX_CONF_UNSET;
eacf->options = NGX_CONF_UNSET;
eacf->nbuckets = NGX_CONF_UNSET_UINT;
return eacf;
}
static ngx_int_t
ngx_rtmp_exec_merge_confs(ngx_array_t *conf, ngx_array_t *prev)
{
size_t n;
ngx_rtmp_exec_conf_t *ec, *pec;
if (prev->nelts == 0) {
return NGX_OK;
}
if (conf->nelts == 0) {
*conf = *prev;
return NGX_OK;
}
ec = ngx_array_push_n(conf, prev->nelts);
if (ec == NULL) {
return NGX_ERROR;
}
pec = prev->elts;
for (n = 0; n < prev->nelts; n++, ec++, pec++) {
*ec = *pec;
}
return NGX_OK;
}
static char *
ngx_rtmp_exec_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_exec_app_conf_t *prev = parent;
ngx_rtmp_exec_app_conf_t *conf = child;
ngx_uint_t n;
ngx_conf_merge_value(conf->respawn, prev->respawn, 1);
ngx_conf_merge_uint_value(conf->nbuckets, prev->nbuckets, 1024);
for (n = 0; n < NGX_RTMP_EXEC_MAX; n++) {
if (ngx_rtmp_exec_merge_confs(&conf->conf[n], &prev->conf[n]) != NGX_OK)
{
return NGX_CONF_ERROR;
}
if (conf->conf[n].nelts) {
conf->active = 1;
prev->active = 1;
}
}
if (conf->conf[NGX_RTMP_EXEC_PULL].nelts > 0) {
conf->pull = ngx_pcalloc(cf->pool, sizeof(void *) * conf->nbuckets);
if (conf->pull == NULL) {
return NGX_CONF_ERROR;
}
}
return NGX_CONF_OK;
}
static ngx_int_t
ngx_rtmp_exec_init_process(ngx_cycle_t *cycle)
{
#if !(NGX_WIN32)
ngx_rtmp_core_main_conf_t *cmcf = ngx_rtmp_core_main_conf;
ngx_rtmp_core_srv_conf_t **cscf;
ngx_rtmp_conf_ctx_t *cctx;
ngx_rtmp_exec_main_conf_t *emcf;
ngx_rtmp_exec_t *e;
ngx_uint_t n;
if (cmcf == NULL || cmcf->servers.nelts == 0) {
return NGX_OK;
}
/* execs are always started by the first worker */
if (ngx_process_slot) {
return NGX_OK;
}
cscf = cmcf->servers.elts;
cctx = (*cscf)->ctx;
emcf = cctx->main_conf[ngx_rtmp_exec_module.ctx_index];
/* FreeBSD note:
* When worker is restarted, child process (ffmpeg) will
* not be terminated if it's connected to another
* (still alive) worker. That leads to starting
* another instance of exec_static process.
* Need to kill previously started processes.
*
* On Linux "prctl" syscall is used to kill child
* when nginx worker is terminated.
*/
e = emcf->static_exec.elts;
for (n = 0; n < emcf->static_exec.nelts; ++n, ++e) {
e->respawn_evt.data = e;
e->respawn_evt.log = e->log;
e->respawn_evt.handler = ngx_rtmp_exec_respawn;
ngx_post_event((&e->respawn_evt), &ngx_rtmp_init_queue);
}
#endif
return NGX_OK;
}
#if !(NGX_WIN32)
static void
ngx_rtmp_exec_respawn(ngx_event_t *ev)
{
ngx_rtmp_exec_run((ngx_rtmp_exec_t *) ev->data);
}
static void
ngx_rtmp_exec_child_dead(ngx_event_t *ev)
{
ngx_connection_t *dummy_conn = ev->data;
ngx_rtmp_exec_t *e;
e = dummy_conn->data;
ngx_log_error(NGX_LOG_INFO, e->log, 0,
"exec: child %ui exited; %s", (ngx_int_t) e->pid,
e->respawn_timeout == NGX_CONF_UNSET_MSEC ? "respawning" :
"ignoring");
ngx_rtmp_exec_kill(e, 0);
if (e->respawn_timeout == NGX_CONF_UNSET_MSEC) {
return;
}
if (e->respawn_timeout == 0) {
ngx_rtmp_exec_run(e);
return;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, e->log, 0,
"exec: shedule respawn %Mmsec", e->respawn_timeout);
e->respawn_evt.data = e;
e->respawn_evt.log = e->log;
e->respawn_evt.handler = ngx_rtmp_exec_respawn;
ngx_add_timer(&e->respawn_evt, e->respawn_timeout);
}
static ngx_int_t
ngx_rtmp_exec_kill(ngx_rtmp_exec_t *e, ngx_int_t kill_signal)
{
if (e->respawn_evt.timer_set) {
ngx_del_timer(&e->respawn_evt);
}
if (e->read_evt.active) {
ngx_del_event(&e->read_evt, NGX_READ_EVENT, 0);
}
if (e->active == 0) {
return NGX_OK;
}
ngx_log_error(NGX_LOG_INFO, e->log, 0,
"exec: terminating child %ui", (ngx_int_t) e->pid);
e->active = 0;
close(e->pipefd);
if (e->save_pid) {
*e->save_pid = NGX_INVALID_PID;
}
if (kill_signal == 0) {
return NGX_OK;
}
if (kill(e->pid, kill_signal) == -1) {
ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
"exec: kill failed pid=%i", (ngx_int_t) e->pid);
} else {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, e->log, 0,
"exec: killed pid=%i", (ngx_int_t) e->pid);
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_exec_run(ngx_rtmp_exec_t *e)
{
int fd, ret, maxfd, pipefd[2];
char **args, **arg_out;
ngx_pid_t pid;
ngx_str_t *arg_in, a;
ngx_uint_t n;
ngx_rtmp_exec_conf_t *ec;
ec = e->conf;
ngx_log_error(NGX_LOG_INFO, e->log, 0,
"exec: starting %s child '%V'",
e->managed ? "managed" : "unmanaged", &ec->cmd);
pipefd[0] = -1;
pipefd[1] = -1;
if (e->managed) {
if (e->active) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, e->log, 0,
"exec: already active '%V'", &ec->cmd);
return NGX_OK;
}
if (pipe(pipefd) == -1) {
ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
"exec: pipe failed");
return NGX_ERROR;
}
/* make pipe write end survive through exec */
ret = fcntl(pipefd[1], F_GETFD);
if (ret != -1) {
ret &= ~FD_CLOEXEC;
ret = fcntl(pipefd[1], F_SETFD, ret);
}
if (ret == -1) {
close(pipefd[0]);
close(pipefd[1]);
ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
"exec: fcntl failed");
return NGX_ERROR;
}
}
pid = fork();
switch (pid) {
case -1:
/* failure */
if (pipefd[0] != -1) {
close(pipefd[0]);
}
if (pipefd[1] != -1) {
close(pipefd[1]);
}
ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
"exec: fork failed");
return NGX_ERROR;
case 0:
/* child */
#if (NGX_LINUX)
if (e->managed) {
prctl(PR_SET_PDEATHSIG, e->kill_signal, 0, 0, 0);
}
#endif
/* close all descriptors but pipe write end */
maxfd = sysconf(_SC_OPEN_MAX);
for (fd = 0; fd < maxfd; ++fd) {
if (fd == pipefd[1]) {
continue;
}
close(fd);
}
fd = open("/dev/null", O_RDWR);
dup2(fd, STDIN_FILENO);
dup2(fd, STDOUT_FILENO);
dup2(fd, STDERR_FILENO);
args = ngx_alloc((ec->args.nelts + 2) * sizeof(char *), e->log);
if (args == NULL) {
exit(1);
}
arg_in = ec->args.elts;
arg_out = args;
*arg_out++ = (char *) ec->cmd.data;
for (n = 0; n < ec->args.nelts; n++, ++arg_in) {
if (e->eval == NULL) {
a = *arg_in;
} else {
ngx_rtmp_eval(e->eval_ctx, arg_in, e->eval, &a, e->log);
}
if (ngx_rtmp_eval_streams(&a) != NGX_DONE) {
continue;
}
*arg_out++ = (char *) a.data;
}
*arg_out = NULL;
#if (NGX_DEBUG)
{
char **p;
for (p = args; *p; p++) {
ngx_write_fd(STDERR_FILENO, "'", 1);
ngx_write_fd(STDERR_FILENO, *p, strlen(*p));
ngx_write_fd(STDERR_FILENO, "' ", 2);
}
ngx_write_fd(STDERR_FILENO, "\n", 1);
}
#endif
if (execvp((char *) ec->cmd.data, args) == -1) {
char *msg;
msg = strerror(errno);
ngx_write_fd(STDERR_FILENO, "execvp error: ", 14);
ngx_write_fd(STDERR_FILENO, msg, strlen(msg));
ngx_write_fd(STDERR_FILENO, "\n", 1);
exit(1);
}
break;
default:
/* parent */
if (pipefd[1] != -1) {
close(pipefd[1]);
}
if (pipefd[0] != -1) {
e->active = 1;
e->pid = pid;
e->pipefd = pipefd[0];
if (e->save_pid) {
*e->save_pid = pid;
}
e->dummy_conn.fd = e->pipefd;
e->dummy_conn.data = e;
e->dummy_conn.read = &e->read_evt;
e->dummy_conn.write = &e->write_evt;
e->read_evt.data = &e->dummy_conn;
e->write_evt.data = &e->dummy_conn;
e->read_evt.log = e->log;
e->read_evt.handler = ngx_rtmp_exec_child_dead;
if (ngx_add_event(&e->read_evt, NGX_READ_EVENT, 0) != NGX_OK) {
ngx_log_error(NGX_LOG_INFO, e->log, ngx_errno,
"exec: failed to add child control event");
}
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, e->log, 0,
"exec: child '%V' started pid=%i",
&ec->cmd, (ngx_int_t) pid);
break;
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_exec_init_ctx(ngx_rtmp_session_t *s, u_char name[NGX_RTMP_MAX_NAME],
u_char args[NGX_RTMP_MAX_ARGS], ngx_uint_t flags)
{
ngx_uint_t n;
ngx_array_t *push_conf;
ngx_rtmp_exec_t *e;
ngx_rtmp_exec_ctx_t *ctx;
ngx_rtmp_exec_conf_t *ec;
ngx_rtmp_exec_app_conf_t *eacf;
ngx_rtmp_exec_main_conf_t *emcf;
time_t t;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
if (ctx != NULL) {
goto done;
}
ctx = ngx_pcalloc(s->pool, sizeof(ngx_rtmp_exec_ctx_t));
if (ctx == NULL) {
return NGX_ERROR;
}
ngx_rtmp_set_ctx(s, ctx, ngx_rtmp_exec_module);
eacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_exec_module);
emcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_exec_module);
push_conf = &eacf->conf[NGX_RTMP_EXEC_PUSH];
if (push_conf->nelts > 0) {
if (ngx_array_init(&ctx->push_exec, s->pool,
push_conf->nelts,
sizeof(ngx_rtmp_exec_t)) != NGX_OK)
{
return NGX_ERROR;
}
e = ngx_array_push_n(&ctx->push_exec, push_conf->nelts);
if (e == NULL) {
return NGX_ERROR;
}
ec = push_conf->elts;
for (n = 0; n < push_conf->nelts; n++, e++, ec++) {
ngx_memzero(e, sizeof(*e));
e->conf = ec;
e->managed = 1;
e->log = s->log;
e->eval = ngx_rtmp_exec_push_eval;
e->eval_ctx = s;
e->kill_signal = emcf->kill_signal;
e->respawn_timeout = (eacf->respawn ? emcf->respawn_timeout :
NGX_CONF_UNSET_MSEC);
}
}
done:
ngx_memcpy(ctx->name, name, NGX_RTMP_MAX_NAME);
ngx_memcpy(ctx->args, args, NGX_RTMP_MAX_ARGS);
t = time( 0 );
strftime((char *)(ctx->starttime), sizeof(ctx->starttime),
"%Y%m%d%H%M%S", localtime(&t));
ctx->flags |= flags;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_exec_init_pull_ctx(ngx_rtmp_session_t *s,
u_char name[NGX_RTMP_MAX_NAME])
{
size_t len;
ngx_uint_t n;
ngx_pool_t *pool;
ngx_array_t *pull_conf;
ngx_rtmp_exec_t *e;
ngx_rtmp_exec_ctx_t *ctx;
ngx_rtmp_exec_conf_t *ec;
ngx_rtmp_exec_pull_ctx_t *pctx, **ppctx;
ngx_rtmp_exec_app_conf_t *eacf;
ngx_rtmp_exec_main_conf_t *emcf;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
if (ctx->pull != NULL) {
return NGX_OK;
}
eacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_exec_module);
pull_conf = &eacf->conf[NGX_RTMP_EXEC_PULL];
if (pull_conf->nelts == 0) {
return NGX_OK;
}
emcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_exec_module);
len = ngx_strlen(name);
ppctx = &eacf->pull[ngx_hash_key(name, len) % eacf->nbuckets];
for (; *ppctx; ppctx = &(*ppctx)->next) {
pctx = *ppctx;
if (pctx->name.len == len &&
ngx_strncmp(name, pctx->name.data, len) == 0)
{
goto done;
}
}
pool = NGX_CREATE_POOL(4096, emcf->log);
if (pool == NULL) {
return NGX_ERROR;
}
pctx = ngx_pcalloc(pool, sizeof(ngx_rtmp_exec_pull_ctx_t));
if (pctx == NULL) {
goto error;
}
pctx->pool = pool;
pctx->name.len = len;
pctx->name.data = ngx_palloc(pool, len);
if (pctx->name.data == NULL) {
goto error;
}
ngx_memcpy(pctx->name.data, name, len);
pctx->app.len = s->app.len;
pctx->app.data = ngx_palloc(pool, s->app.len);
if (pctx->app.data == NULL) {
goto error;
}
ngx_memcpy(pctx->app.data, s->app.data, s->app.len);
if (ngx_array_init(&pctx->pull_exec, pool, pull_conf->nelts,
sizeof(ngx_rtmp_exec_t)) != NGX_OK)
{
goto error;
}
e = ngx_array_push_n(&pctx->pull_exec, pull_conf->nelts);
if (e == NULL) {
goto error;
}
ec = pull_conf->elts;
for (n = 0; n < pull_conf->nelts; n++, e++, ec++) {
ngx_memzero(e, sizeof(*e));
e->conf = ec;
e->managed = 1;
e->log = emcf->log;
e->eval = ngx_rtmp_exec_pull_eval;
e->eval_ctx = pctx;
e->kill_signal = emcf->kill_signal;
e->respawn_timeout = (eacf->respawn ? emcf->respawn_timeout :
NGX_CONF_UNSET_MSEC);
}
*ppctx = pctx;
done:
ctx->pull = pctx;
ctx->pull->counter++;
return NGX_OK;
error:
NGX_DESTROY_POOL(pool);
return NGX_ERROR;
}
static ngx_int_t
ngx_rtmp_exec_filter(ngx_rtmp_session_t *s, ngx_rtmp_exec_conf_t *ec)
{
size_t len;
ngx_str_t *v;
ngx_uint_t n;
ngx_rtmp_exec_ctx_t *ctx;
if (ec->names.nelts == 0) {
return NGX_OK;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
len = ngx_strlen(ctx->name);
v = ec->names.elts;
for (n = 0; n < ec->names.nelts; n++, s++) {
if (v->len == len && ngx_strncmp(v->data, ctx->name, len) == 0) {
return NGX_OK;
}
}
return NGX_DECLINED;
}
static void
ngx_rtmp_exec_unmanaged(ngx_rtmp_session_t *s, ngx_array_t *e, const char *op)
{
ngx_uint_t n;
ngx_rtmp_exec_t en;
ngx_rtmp_exec_conf_t *ec;
if (e->nelts == 0) {
return;
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"exec: %s %uz unmanaged command(s)", op, e->nelts);
ec = e->elts;
for (n = 0; n < e->nelts; n++, ec++) {
if (ngx_rtmp_exec_filter(s, ec) != NGX_OK) {
continue;
}
ngx_memzero(&en, sizeof(ngx_rtmp_exec_t));
en.conf = ec;
en.eval = ngx_rtmp_exec_event_eval;
en.eval_ctx = s;
en.log = s->log;
ngx_rtmp_exec_run(&en);
}
}
static void
ngx_rtmp_exec_managed(ngx_rtmp_session_t *s, ngx_array_t *e, const char *op)
{
ngx_uint_t n;
ngx_rtmp_exec_t *en;
if (e->nelts == 0) {
return;
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"exec: %s %uz managed command(s)", op, e->nelts);
en = e->elts;
for (n = 0; n < e->nelts; n++, en++) {
if (ngx_rtmp_exec_filter(s, en->conf) == NGX_OK) {
ngx_rtmp_exec_run(en);
}
}
}
static ngx_int_t
ngx_rtmp_exec_publish(ngx_rtmp_session_t *s, ngx_rtmp_publish_t *v)
{
ngx_rtmp_exec_ctx_t *ctx;
ngx_rtmp_exec_app_conf_t *eacf;
eacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_exec_module);
if (eacf == NULL || !eacf->active) {
goto next;
}
if (s->interprocess) {
goto next;
}
if (ngx_rtmp_exec_init_ctx(s, v->name, v->args, NGX_RTMP_EXEC_PUBLISHING)
!= NGX_OK)
{
goto next;
}
ngx_rtmp_exec_unmanaged(s, &eacf->conf[NGX_RTMP_EXEC_PUBLISH], "publish");
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
ngx_rtmp_exec_managed(s, &ctx->push_exec, "push");
next:
return next_publish(s, v);
}
static ngx_int_t
ngx_rtmp_exec_play(ngx_rtmp_session_t *s, ngx_rtmp_play_t *v)
{
ngx_rtmp_exec_ctx_t *ctx;
ngx_rtmp_exec_pull_ctx_t *pctx;
ngx_rtmp_exec_app_conf_t *eacf;
eacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_exec_module);
if (eacf == NULL || !eacf->active) {
goto next;
}
if (ngx_rtmp_exec_init_ctx(s, v->name, v->args, NGX_RTMP_EXEC_PLAYING)
!= NGX_OK)
{
goto next;
}
ngx_rtmp_exec_unmanaged(s, &eacf->conf[NGX_RTMP_EXEC_PLAY], "play");
if (ngx_rtmp_exec_init_pull_ctx(s, v->name) != NGX_OK) {
goto next;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
pctx = ctx->pull;
if (pctx && pctx->counter == 1) {
ngx_rtmp_exec_managed(s, &pctx->pull_exec, "pull");
}
next:
return next_play(s, v);
}
static ngx_int_t
ngx_rtmp_exec_close_stream(ngx_rtmp_session_t *s, ngx_rtmp_close_stream_t *v)
{
size_t n;
ngx_rtmp_exec_t *e;
ngx_rtmp_exec_ctx_t *ctx;
ngx_rtmp_exec_pull_ctx_t *pctx, **ppctx;
ngx_rtmp_exec_app_conf_t *eacf;
eacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_exec_module);
if (eacf == NULL) {
goto next;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_exec_module);
if (ctx == NULL) {
goto next;
}
if (ctx->flags & NGX_RTMP_EXEC_PUBLISHING) {
ngx_rtmp_exec_unmanaged(s, &eacf->conf[NGX_RTMP_EXEC_PUBLISH_DONE],
"publish_done");
}
if (ctx->flags & NGX_RTMP_EXEC_PLAYING) {
ngx_rtmp_exec_unmanaged(s, &eacf->conf[NGX_RTMP_EXEC_PLAY_DONE],
"play_done");
}
ctx->flags = 0;
if (ctx->push_exec.nelts > 0) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"exec: delete %uz push command(s)",
ctx->push_exec.nelts);
e = ctx->push_exec.elts;
for (n = 0; n < ctx->push_exec.nelts; n++, e++) {
ngx_rtmp_exec_kill(e, e->kill_signal);
}
}
pctx = ctx->pull;
if (pctx && --pctx->counter == 0) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"exec: delete %uz pull command(s)",
pctx->pull_exec.nelts);
e = pctx->pull_exec.elts;
for (n = 0; n < pctx->pull_exec.nelts; n++, e++) {
ngx_rtmp_exec_kill(e, e->kill_signal);
}
ppctx = &eacf->pull[ngx_hash_key(pctx->name.data, pctx->name.len) %
eacf->nbuckets];
for (; *ppctx; ppctx = &(*ppctx)->next) {
if (pctx == *ppctx) {
*ppctx = pctx->next;
break;
}
}
NGX_DESTROY_POOL(pctx->pool);
}
ctx->pull = NULL;
next:
return next_close_stream(s, v);
}
#endif /* NGX_WIN32 */
static char *
ngx_rtmp_exec_conf(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *p = conf;
size_t n, nargs;
ngx_str_t *s, *value, v;
ngx_array_t *confs;
ngx_rtmp_exec_conf_t *ec;
ngx_rtmp_exec_app_conf_t *eacf;
confs = (ngx_array_t *) (p + cmd->offset);
eacf = ngx_rtmp_conf_get_module_app_conf(cf, ngx_rtmp_exec_module);
if (confs->nalloc == 0 && ngx_array_init(confs, cf->pool, 1,
sizeof(ngx_rtmp_exec_conf_t))
!= NGX_OK)
{
return NGX_CONF_ERROR;
}
value = cf->args->elts;
ec = ngx_array_push(confs);
if (ec == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(ec, sizeof(ngx_rtmp_exec_conf_t));
/* type is undefined for explicit execs */
ec->type = NGX_CONF_UNSET_UINT;
ec->cmd = value[1];
if (ngx_array_init(&ec->names, cf->pool, 1, sizeof(ngx_str_t)) != NGX_OK) {
return NGX_CONF_ERROR;
}
if (cf->args->nelts == 2) {
return NGX_CONF_OK;
}
nargs = cf->args->nelts - 2;
if (ngx_array_init(&ec->args, cf->pool, nargs, sizeof(ngx_str_t)) != NGX_OK)
{
return NGX_CONF_ERROR;
}
for (n = 2; n < cf->args->nelts; n++) {
v = value[n];
if (eacf->options == 1) {
if (v.len >= 5 && ngx_strncmp(v.data, "name=", 5) == 0) {
s = ngx_array_push(&ec->names);
if (s == NULL) {
return NGX_CONF_ERROR;
}
v.data += 5;
v.len -= 5;
*s = v;
continue;
}
}
s = ngx_array_push(&ec->args);
if (s == NULL) {
return NGX_CONF_ERROR;
}
*s = v;
}
return NGX_CONF_OK;
}
/*
static char *
ngx_rtmp_exec_block(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *rv;
ngx_str_t *value;
ngx_conf_t save;
ngx_array_t *confs;
ngx_rtmp_conf_ctx_t *ctx, *pctx;
ngx_rtmp_exec_conf_t *ec, *eec;
ngx_rtmp_exec_app_conf_t *eacf;
ngx_rtmp_exec_main_conf_t *emcf;
value = cf->args->elts;
eacf = ngx_rtmp_conf_get_module_app_conf(cf, ngx_rtmp_exec_module);
emcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_exec_module);
ctx = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_conf_ctx_t));
if (ctx == NULL) {
return NGX_CONF_ERROR;
}
pctx = cf->ctx;
ctx->main_conf = pctx->main_conf;
ctx->srv_conf = pctx->srv_conf;
ctx->app_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->app_conf == NULL) {
return NGX_CONF_ERROR;
}
ec = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_exec_conf_t));
if (ec == NULL) {
return NGX_CONF_ERROR;
}
ec->id = value[1];
ec->type = NGX_CONF_UNSET_UINT;
ctx->app_conf[ngx_rtmp_exec_module.ctx_index] = ec;
save = *cf;
cf->ctx = ctx;
cf->cmd_type = NGX_RTMP_EXEC_CONF;
rv = ngx_conf_parse(cf, NULL);
*cf= save;
switch (ec->type) {
case NGX_RTMP_EXEC_STATIC:
confs = &emcf->static_conf;
break;
case NGX_CONF_UNSET_UINT:
return "unspecified exec type";
default:
confs = &eacf->conf[ec->type];
}
if (confs->nalloc == 0 && ngx_array_init(confs, cf->pool, 1,
sizeof(ngx_rtmp_exec_conf_t))
!= NGX_OK)
{
return NGX_CONF_ERROR;
}
eec = ngx_array_push(confs);
if (eec == NULL) {
return NGX_CONF_ERROR;
}
*eec = *ec;
return rv;
}
*/
static char *
ngx_rtmp_exec_kill_signal(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_rtmp_exec_main_conf_t *emcf = conf;
ngx_str_t *value;
value = cf->args->elts;
value++;
emcf->kill_signal = ngx_atoi(value->data, value->len);
if (emcf->kill_signal != NGX_ERROR) {
return NGX_CONF_OK;
}
#define NGX_RMTP_EXEC_SIGNAL(name) \
if (value->len == sizeof(#name) - 1 && \
ngx_strncasecmp(value->data, (u_char *) #name, value->len) == 0) \
{ \
emcf->kill_signal = SIG##name; \
return NGX_CONF_OK; \
}
/* POSIX.1-1990 signals */
#if !(NGX_WIN32)
NGX_RMTP_EXEC_SIGNAL(HUP);
NGX_RMTP_EXEC_SIGNAL(INT);
NGX_RMTP_EXEC_SIGNAL(QUIT);
NGX_RMTP_EXEC_SIGNAL(ILL);
NGX_RMTP_EXEC_SIGNAL(ABRT);
NGX_RMTP_EXEC_SIGNAL(FPE);
NGX_RMTP_EXEC_SIGNAL(KILL);
NGX_RMTP_EXEC_SIGNAL(SEGV);
NGX_RMTP_EXEC_SIGNAL(PIPE);
NGX_RMTP_EXEC_SIGNAL(ALRM);
NGX_RMTP_EXEC_SIGNAL(TERM);
NGX_RMTP_EXEC_SIGNAL(USR1);
NGX_RMTP_EXEC_SIGNAL(USR2);
NGX_RMTP_EXEC_SIGNAL(CHLD);
NGX_RMTP_EXEC_SIGNAL(CONT);
NGX_RMTP_EXEC_SIGNAL(STOP);
NGX_RMTP_EXEC_SIGNAL(TSTP);
NGX_RMTP_EXEC_SIGNAL(TTIN);
NGX_RMTP_EXEC_SIGNAL(TTOU);
#endif
#undef NGX_RMTP_EXEC_SIGNAL
return "unknown signal";
}
static ngx_int_t
ngx_rtmp_exec_postconfiguration(ngx_conf_t *cf)
{
#if !(NGX_WIN32)
next_publish = ngx_rtmp_publish;
ngx_rtmp_publish = ngx_rtmp_exec_publish;
next_play = ngx_rtmp_play;
ngx_rtmp_play = ngx_rtmp_exec_play;
next_close_stream = ngx_rtmp_close_stream;
ngx_rtmp_close_stream = ngx_rtmp_exec_close_stream;
#endif /* NGX_WIN32 */
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 8,424 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/datatables-bs4/css/dataTables.bootstrap4.css
|
@charset "UTF-8";
table.dataTable th.dt-left,
table.dataTable td.dt-left {
text-align: left;
}
table.dataTable th.dt-center,
table.dataTable td.dt-center,
table.dataTable td.dataTables_empty {
text-align: center;
}
table.dataTable th.dt-right,
table.dataTable td.dt-right {
text-align: right;
}
table.dataTable th.dt-justify,
table.dataTable td.dt-justify {
text-align: justify;
}
table.dataTable th.dt-nowrap,
table.dataTable td.dt-nowrap {
white-space: nowrap;
}
table.dataTable thead th.dt-head-left,
table.dataTable thead td.dt-head-left,
table.dataTable tfoot th.dt-head-left,
table.dataTable tfoot td.dt-head-left {
text-align: left;
}
table.dataTable thead th.dt-head-center,
table.dataTable thead td.dt-head-center,
table.dataTable tfoot th.dt-head-center,
table.dataTable tfoot td.dt-head-center {
text-align: center;
}
table.dataTable thead th.dt-head-right,
table.dataTable thead td.dt-head-right,
table.dataTable tfoot th.dt-head-right,
table.dataTable tfoot td.dt-head-right {
text-align: right;
}
table.dataTable thead th.dt-head-justify,
table.dataTable thead td.dt-head-justify,
table.dataTable tfoot th.dt-head-justify,
table.dataTable tfoot td.dt-head-justify {
text-align: justify;
}
table.dataTable thead th.dt-head-nowrap,
table.dataTable thead td.dt-head-nowrap,
table.dataTable tfoot th.dt-head-nowrap,
table.dataTable tfoot td.dt-head-nowrap {
white-space: nowrap;
}
table.dataTable tbody th.dt-body-left,
table.dataTable tbody td.dt-body-left {
text-align: left;
}
table.dataTable tbody th.dt-body-center,
table.dataTable tbody td.dt-body-center {
text-align: center;
}
table.dataTable tbody th.dt-body-right,
table.dataTable tbody td.dt-body-right {
text-align: right;
}
table.dataTable tbody th.dt-body-justify,
table.dataTable tbody td.dt-body-justify {
text-align: justify;
}
table.dataTable tbody th.dt-body-nowrap,
table.dataTable tbody td.dt-body-nowrap {
white-space: nowrap;
}
table.dataTable td.dt-control {
text-align: center;
cursor: pointer;
}
table.dataTable td.dt-control:before {
height: 1em;
width: 1em;
margin-top: -9px;
display: inline-block;
color: white;
border: 0.15em solid white;
border-radius: 1em;
box-shadow: 0 0 0.2em #444;
box-sizing: content-box;
text-align: center;
text-indent: 0 !important;
font-family: "Courier New", Courier, monospace;
line-height: 1em;
content: "+";
background-color: #31b131;
}
table.dataTable tr.dt-hasChild td.dt-control:before {
content: "-";
background-color: #d33333;
}
table.dataTable {
clear: both;
margin-top: 6px !important;
margin-bottom: 6px !important;
max-width: none !important;
border-collapse: separate !important;
border-spacing: 0;
}
table.dataTable td,
table.dataTable th {
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
table.dataTable td.dataTables_empty,
table.dataTable th.dataTables_empty {
text-align: center;
}
table.dataTable.nowrap th,
table.dataTable.nowrap td {
white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_length label {
font-weight: normal;
text-align: left;
white-space: nowrap;
}
div.dataTables_wrapper div.dataTables_length select {
width: auto;
display: inline-block;
}
div.dataTables_wrapper div.dataTables_filter {
text-align: right;
}
div.dataTables_wrapper div.dataTables_filter label {
font-weight: normal;
white-space: nowrap;
text-align: left;
}
div.dataTables_wrapper div.dataTables_filter input {
margin-left: 0.5em;
display: inline-block;
width: auto;
}
div.dataTables_wrapper div.dataTables_info {
padding-top: 0.85em;
}
div.dataTables_wrapper div.dataTables_paginate {
margin: 0;
white-space: nowrap;
text-align: right;
}
div.dataTables_wrapper div.dataTables_paginate ul.pagination {
margin: 2px 0;
white-space: nowrap;
justify-content: flex-end;
}
div.dataTables_wrapper div.dataTables_processing {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
margin-left: -100px;
margin-top: -26px;
text-align: center;
padding: 1em 0;
}
table.dataTable > thead > tr > th:active,
table.dataTable > thead > tr > td:active {
outline: none;
}
table.dataTable > thead > tr > th:not(.sorting_disabled),
table.dataTable > thead > tr > td:not(.sorting_disabled) {
padding-right: 30px;
}
table.dataTable > thead .sorting,
table.dataTable > thead .sorting_asc,
table.dataTable > thead .sorting_desc,
table.dataTable > thead .sorting_asc_disabled,
table.dataTable > thead .sorting_desc_disabled {
cursor: pointer;
position: relative;
}
table.dataTable > thead .sorting:before, table.dataTable > thead .sorting:after,
table.dataTable > thead .sorting_asc:before,
table.dataTable > thead .sorting_asc:after,
table.dataTable > thead .sorting_desc:before,
table.dataTable > thead .sorting_desc:after,
table.dataTable > thead .sorting_asc_disabled:before,
table.dataTable > thead .sorting_asc_disabled:after,
table.dataTable > thead .sorting_desc_disabled:before,
table.dataTable > thead .sorting_desc_disabled:after {
position: absolute;
bottom: 0.9em;
display: block;
opacity: 0.3;
}
table.dataTable > thead .sorting:before,
table.dataTable > thead .sorting_asc:before,
table.dataTable > thead .sorting_desc:before,
table.dataTable > thead .sorting_asc_disabled:before,
table.dataTable > thead .sorting_desc_disabled:before {
right: 1em;
content: "↑";
}
table.dataTable > thead .sorting:after,
table.dataTable > thead .sorting_asc:after,
table.dataTable > thead .sorting_desc:after,
table.dataTable > thead .sorting_asc_disabled:after,
table.dataTable > thead .sorting_desc_disabled:after {
right: 0.5em;
content: "↓";
}
table.dataTable > thead .sorting_asc:before,
table.dataTable > thead .sorting_desc:after {
opacity: 1;
}
table.dataTable > thead .sorting_asc_disabled:before,
table.dataTable > thead .sorting_desc_disabled:after {
opacity: 0;
}
div.dataTables_scrollHead table.dataTable {
margin-bottom: 0 !important;
}
div.dataTables_scrollBody > table {
border-top: none;
margin-top: 0 !important;
margin-bottom: 0 !important;
}
div.dataTables_scrollBody > table > thead .sorting:before,
div.dataTables_scrollBody > table > thead .sorting_asc:before,
div.dataTables_scrollBody > table > thead .sorting_desc:before,
div.dataTables_scrollBody > table > thead .sorting:after,
div.dataTables_scrollBody > table > thead .sorting_asc:after,
div.dataTables_scrollBody > table > thead .sorting_desc:after {
display: none;
}
div.dataTables_scrollBody > table > tbody tr:first-child th,
div.dataTables_scrollBody > table > tbody tr:first-child td {
border-top: none;
}
div.dataTables_scrollFoot > .dataTables_scrollFootInner {
box-sizing: content-box;
}
div.dataTables_scrollFoot > .dataTables_scrollFootInner > table {
margin-top: 0 !important;
border-top: none;
}
@media screen and (max-width: 767px) {
div.dataTables_wrapper div.dataTables_length,
div.dataTables_wrapper div.dataTables_filter,
div.dataTables_wrapper div.dataTables_info,
div.dataTables_wrapper div.dataTables_paginate {
text-align: center;
}
div.dataTables_wrapper div.dataTables_paginate ul.pagination {
justify-content: center !important;
}
}
table.dataTable.table-sm > thead > tr > th:not(.sorting_disabled) {
padding-right: 20px;
}
table.dataTable.table-sm .sorting:before,
table.dataTable.table-sm .sorting_asc:before,
table.dataTable.table-sm .sorting_desc:before {
top: 5px;
right: 0.85em;
}
table.dataTable.table-sm .sorting:after,
table.dataTable.table-sm .sorting_asc:after,
table.dataTable.table-sm .sorting_desc:after {
top: 5px;
}
table.table-bordered.dataTable {
border-right-width: 0;
}
table.table-bordered.dataTable th,
table.table-bordered.dataTable td {
border-left-width: 0;
}
table.table-bordered.dataTable th:last-child, table.table-bordered.dataTable th:last-child,
table.table-bordered.dataTable td:last-child,
table.table-bordered.dataTable td:last-child {
border-right-width: 1px;
}
table.table-bordered.dataTable tbody th,
table.table-bordered.dataTable tbody td {
border-bottom-width: 0;
}
div.dataTables_scrollHead table.table-bordered {
border-bottom-width: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row {
margin: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row > div[class^=col-]:first-child {
padding-left: 0;
}
div.table-responsive > div.dataTables_wrapper > div.row > div[class^=col-]:last-child {
padding-right: 0;
}
|
294coder/Efficient-MIF
| 5,365 |
utils/FS_index/imresize.py
|
"""
Python Code on GitHub: https://codeload.github.com/fatheral/matlab_imresize/zip/master
MIT License
Copyright (c) 2020 Alex
"""
from __future__ import print_function
import numpy as np
from math import ceil, floor
def deriveSizeFromScale(img_shape, scale):
output_shape = []
for k in range(2):
output_shape.append(int(ceil(scale[k] * img_shape[k])))
return output_shape
def deriveScaleFromSize(img_shape_in, img_shape_out):
scale = []
for k in range(2):
scale.append(1.0 * img_shape_out[k] / img_shape_in[k])
return scale
def triangle(x):
x = np.array(x).astype(np.float64)
lessthanzero = np.logical_and((x>=-1),x<0)
greaterthanzero = np.logical_and((x<=1),x>=0)
f = np.multiply((x+1),lessthanzero) + np.multiply((1-x),greaterthanzero)
return f
def cubic(x):
x = np.array(x).astype(np.float64)
absx = np.absolute(x)
absx2 = np.multiply(absx, absx)
absx3 = np.multiply(absx2, absx)
f = np.multiply(1.5*absx3 - 2.5*absx2 + 1, absx <= 1) + np.multiply(-0.5*absx3 + 2.5*absx2 - 4*absx + 2, (1 < absx) & (absx <= 2))
return f
def contributions(in_length, out_length, scale, kernel, k_width):
if scale < 1:
h = lambda x: scale * kernel(scale * x)
kernel_width = 1.0 * k_width / scale
else:
h = kernel
kernel_width = k_width
x = np.arange(1, out_length+1).astype(np.float64)
u = x / scale + 0.5 * (1 - 1 / scale)
left = np.floor(u - kernel_width / 2)
P = int(ceil(kernel_width)) + 2
ind = np.expand_dims(left, axis=1) + np.arange(P) - 1 # -1 because indexing from 0
indices = ind.astype(np.int32)
weights = h(np.expand_dims(u, axis=1) - indices - 1) # -1 because indexing from 0
weights = np.divide(weights, np.expand_dims(np.sum(weights, axis=1), axis=1))
aux = np.concatenate((np.arange(in_length), np.arange(in_length - 1, -1, step=-1))).astype(np.int32)
indices = aux[np.mod(indices, aux.size)]
ind2store = np.nonzero(np.any(weights, axis=0))
weights = weights[:, ind2store]
indices = indices[:, ind2store]
return weights, indices
def imresizemex(inimg, weights, indices, dim):
in_shape = inimg.shape
w_shape = weights.shape
out_shape = list(in_shape)
out_shape[dim] = w_shape[0]
outimg = np.zeros(out_shape)
if dim == 0:
for i_img in range(in_shape[1]):
for i_w in range(w_shape[0]):
w = weights[i_w, :]
ind = indices[i_w, :]
im_slice = inimg[ind, i_img].astype(np.float64)
outimg[i_w, i_img] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
elif dim == 1:
for i_img in range(in_shape[0]):
for i_w in range(w_shape[0]):
w = weights[i_w, :]
ind = indices[i_w, :]
im_slice = inimg[i_img, ind].astype(np.float64)
outimg[i_img, i_w] = np.sum(np.multiply(np.squeeze(im_slice, axis=0), w.T), axis=0)
if inimg.dtype == np.uint8:
outimg = np.clip(outimg, 0, 255)
return np.around(outimg).astype(np.uint8)
else:
return outimg
def imresizevec(inimg, weights, indices, dim):
wshape = weights.shape
if dim == 0:
weights = weights.reshape((wshape[0], wshape[2], 1, 1))
outimg = np.sum(weights*((inimg[indices].squeeze(axis=1)).astype(np.float64)), axis=1)
elif dim == 1:
weights = weights.reshape((1, wshape[0], wshape[2], 1))
outimg = np.sum(weights*((inimg[:, indices].squeeze(axis=2)).astype(np.float64)), axis=2)
if inimg.dtype == np.uint8:
outimg = np.clip(outimg, 0, 255)
return np.around(outimg).astype(np.uint8)
else:
return outimg
def resizeAlongDim(A, dim, weights, indices, mode="vec"):
if mode == "org":
out = imresizemex(A, weights, indices, dim)
else:
out = imresizevec(A, weights, indices, dim)
return out
def imresize(I, scalar_scale=None, method='bicubic', output_shape=None, mode="vec"):
if method == 'bicubic':
kernel = cubic
elif method == 'bilinear':
kernel = triangle
else:
print ('Error: Unidentified method supplied')
kernel_width = 4.0
# Fill scale and output_size
if scalar_scale is not None:
scalar_scale = float(scalar_scale)
scale = [scalar_scale, scalar_scale]
output_size = deriveSizeFromScale(I.shape, scale)
elif output_shape is not None:
scale = deriveScaleFromSize(I.shape, output_shape)
output_size = list(output_shape)
else:
print ('Error: scalar_scale OR output_shape should be defined!')
return
scale_np = np.array(scale)
order = np.argsort(scale_np)
weights = []
indices = []
for k in range(2):
w, ind = contributions(I.shape[k], output_size[k], scale[k], kernel, kernel_width)
weights.append(w)
indices.append(ind)
B = np.copy(I)
flag2D = False
if B.ndim == 2:
B = np.expand_dims(B, axis=2)
flag2D = True
for k in range(2):
dim = order[k]
B = resizeAlongDim(B, dim, weights[dim], indices[dim], mode)
if flag2D:
B = np.squeeze(B, axis=2)
return B
def convertDouble2Byte(I):
B = np.clip(I, 0.0, 1.0)
B = 255*B
return np.around(B).astype(np.uint8)
|
294coder/Efficient-MIF
| 10,282 |
utils/FS_index/hqnr2.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
#
import sys
sys.path.append('./')
import numpy as np
from scipy import ndimage
import cv2
from .HQNR import HQNR
from .my_D_s import D_s as my_Ds
from .imresize import imresize
def mtf_resize(img, satellite='QuickBird', scale=4):
# satellite GNyq
scale = int(scale)
if satellite == 'QuickBird':
GNyq = [0.34, 0.32, 0.30, 0.22] # Band Order: B,G,R,NIR
GNyqPan = 0.15
elif satellite == 'IKONOS':
GNyq = [0.26, 0.28, 0.29, 0.28] # Band Order: B,G,R,NIR
GNyqPan = 0.17
elif satellite == 'WV3':
GNyq = [0.325, 0.355, 0.360, 0.350, 0.365, 0.360, 0.335, 0.315] # Band Order: B,G,R,NIR
GNyqPan = 0.14
else:
raise NotImplementedError('satellite: QuickBird or IKONOS or WV3')
# lowpass
img_ = img.squeeze()
img_ = img_.astype(np.float64)
if img_.ndim == 2: # Pan
H, W = img_.shape
lowpass = GNyq2win(GNyqPan, scale, N=41)
elif img_.ndim == 3: # MS
H, W, _ = img.shape
lowpass = [GNyq2win(gnyq, scale, N=41) for gnyq in GNyq]
lowpass = np.stack(lowpass, axis=-1)
img_ = ndimage.filters.correlate(img_, lowpass, mode='nearest')
# downsampling
output_size = (H // scale, W // scale)
img_ = cv2.resize(img_, dsize=output_size, interpolation=cv2.INTER_NEAREST)
return img_
def gaussian2d(N, std):
t = np.arange(-(N - 1) // 2, (N + 2) // 2)
t1, t2 = np.meshgrid(t, t)
std = np.double(std)
w = np.exp(-0.5 * (t1 / std) ** 2) * np.exp(-0.5 * (t2 / std) ** 2)
return w
def kaiser2d(N, beta):
t = np.arange(-(N - 1) // 2, (N + 2) // 2) / np.double(N - 1)
t1, t2 = np.meshgrid(t, t)
t12 = np.sqrt(t1 * t1 + t2 * t2)
w1 = np.kaiser(N, beta)
w = np.interp(t12, t, w1)
w[t12 > t[-1]] = 0
w[t12 < t[0]] = 0
return w
def fir_filter_wind(Hd, w):
"""
compute fir (finite impulse response) filter with window method
Hd: desired freqeuncy response (2D)
w: window (2D)
"""
hd = np.rot90(np.fft.fftshift(np.rot90(Hd, 2)), 2)
h = np.fft.fftshift(np.fft.ifft2(hd))
h = np.rot90(h, 2)
h = h * w
h = h / np.sum(h)
return h
def GNyq2win(GNyq, scale=4, N=41):
"""Generate a 2D convolutional window from a given GNyq
GNyq: Nyquist frequency
scale: spatial size of PAN / spatial size of MS
"""
# fir filter with window method
fcut = 1 / scale
alpha = np.sqrt(((N - 1) * (fcut / 2)) ** 2 / (-2 * np.log(GNyq)))
H = gaussian2d(N, alpha)
Hd = H / np.max(H)
w = kaiser2d(N, 0.5)
h = fir_filter_wind(Hd, w)
return np.real(h)
def _qindex(img1, img2, block_size=8):
"""Q-index for 2D (one-band) image, shape (H, W); uint or float [0, 1]"""
assert block_size > 1, 'block_size shold be greater than 1!'
img1_ = img1.astype(np.float64)
img2_ = img2.astype(np.float64)
window = np.ones((block_size, block_size)) / (block_size ** 2)
# window_size = block_size**2
# filter, valid
pad_topleft = int(np.floor(block_size / 2))
pad_bottomright = block_size - 1 - pad_topleft
mu1 = cv2.filter2D(img1_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright]
mu2 = cv2.filter2D(img2_, -1, window)[pad_topleft:-pad_bottomright, pad_topleft:-pad_bottomright]
mu1_sq = mu1 ** 2
mu2_sq = mu2 ** 2
mu1_mu2 = mu1 * mu2
sigma1_sq = cv2.filter2D(img1_ ** 2, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu1_sq
sigma2_sq = cv2.filter2D(img2_ ** 2, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu2_sq
# print(mu1_mu2.shape)
# print(sigma2_sq.shape)
sigma12 = cv2.filter2D(img1_ * img2_, -1, window)[pad_topleft:-pad_bottomright,
pad_topleft:-pad_bottomright] - mu1_mu2
# all = 1, include the case of simga == mu == 0
qindex_map = np.ones(sigma12.shape)
# sigma == 0 and mu != 0
idx = ((sigma1_sq + sigma2_sq) == 0) * ((mu1_sq + mu2_sq) != 0)
qindex_map[idx] = 2 * mu1_mu2[idx] / (mu1_sq + mu2_sq)[idx]
# sigma !=0 and mu == 0
idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) == 0)
qindex_map[idx] = 2 * sigma12[idx] / (sigma1_sq + sigma2_sq)[idx]
# sigma != 0 and mu != 0
idx = ((sigma1_sq + sigma2_sq) != 0) * ((mu1_sq + mu2_sq) != 0)
qindex_map[idx] = ((2 * mu1_mu2[idx]) * (2 * sigma12[idx])) / (
(mu1_sq + mu2_sq)[idx] * (sigma1_sq + sigma2_sq)[idx])
return np.mean(qindex_map), qindex_map
def qindex(img1, img2, block_size=8):
"""Q-index for 2D (H, W) or 3D (H, W, C) image; uint or float [0, 1]"""
if not img1.shape == img2.shape:
raise ValueError('Input images must have the same dimensions.')
if img1.ndim == 2:
return _qindex(img1, img2, block_size)
elif img1.ndim == 3:
qindexs = [_qindex(img1[..., i], img2[..., i], block_size) for i in range(img1.shape[2])]
return np.array(qindexs).mean()
else:
raise ValueError('Wrong input image dimensions.')
def D_lambda(img_fake, img_lm, block_size=32, p=1):
"""Spectral distortion
img_fake, generated HRMS
img_lm, LRMS"""
assert img_fake.ndim == img_lm.ndim == 3, 'Images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert C_f == C_r, 'Fake and lm should have the same number of bands!'
# D_lambda
Q_fake = []
Q_lm = []
for i in range(C_f):
for j in range(i + 1, C_f):
# for fake
band1 = img_fake[..., i]
band2 = img_fake[..., j]
Q_fake.append(_qindex(band1, band2, block_size=block_size))
# for real
band1 = img_lm[..., i]
band2 = img_lm[..., j]
Q_lm.append(_qindex(band1, band2, block_size=block_size))
Q_fake = np.array(Q_fake)
Q_lm = np.array(Q_lm)
D_lambda_index = (np.abs(Q_fake - Q_lm) ** p).mean()
return D_lambda_index ** (1 / p)
def D_s(img_fake, img_lm, pan, satellite='QuickBird', scale=4, block_size=32, q=1):
"""Spatial distortion
img_fake, generated HRMS
img_lm, LRMS
pan, HRPan"""
# fake and lm
assert img_fake.ndim == img_lm.ndim == 3, 'MS images must be 3D!'
H_f, W_f, C_f = img_fake.shape
H_r, W_r, C_r = img_lm.shape
assert H_f // H_r == W_f // W_r == scale, 'Spatial resolution should be compatible with scale'
assert C_f == C_r, 'Fake and lm should have the same number of bands!'
# fake and pan
assert pan.ndim == 3, 'Panchromatic image must be 3D!'
H_p, W_p, C_p = pan.shape
assert C_p == 1, 'size of 3rd dim of Panchromatic image must be 1'
assert H_f == H_p and W_f == W_p, "Pan's and fake's spatial resolution should be the same"
# get LRPan, 2D
pan_lr = mtf_resize(pan, satellite=satellite, scale=scale)
# print(pan_lr.shape)
# D_s
Q_hr = []
Q_lr = []
for i in range(C_f):
# for HR fake
band1 = img_fake[..., i]
band2 = pan[..., 0] # the input PAN is 3D with size=1 along 3rd dim
# print(band1.shape)
# print(band2.shape)
Q_hr.append(_qindex(band1, band2, block_size=block_size))
band1 = img_lm[..., i]
band2 = pan_lr # this is 2D
# print(band1.shape)
# print(band2.shape)
Q_lr.append(_qindex(band1, band2, block_size=block_size))
Q_hr = np.array(Q_hr)
Q_lr = np.array(Q_lr)
D_s_index = (np.abs(Q_hr - Q_lr) ** q).mean()
return D_s_index ** (1 / q)
def qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1):
"""QNR - No reference IQA"""
if pan.ndim == 2:
pan = pan[:, :, None]
D_lambda_idx = D_lambda(ps_ms, msexp, S, p)
D_s_idx = D_s(ps_ms, ms, pan, 'WV3', ratio, S, q)
QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta
return QNR_idx, D_lambda_idx, D_s_idx
def my_qnr(ps_ms, ms, msexp, pan, ratio, S, p=1, q=1, alpha=1, beta=1):
"""QNR - No reference IQA"""
# D_lambda_idx = D_lambda(img_fake, img_lm, block_size, p)
# D_s_idx = D_s(img_fake, img_lm, pan, satellite, scale, block_size, q)
D_lambda_idx = D_lambda(ps_ms, msexp, S, p)
D_s_idx = my_Ds(ps_ms, msexp, ms, pan, ratio, S, q)
QNR_idx = (1 - D_lambda_idx) ** alpha * (1 - D_s_idx) ** beta
return QNR_idx, D_lambda_idx, D_s_idx
def indexes_evaluation_FS(I_F, I_MS_LR, I_PAN, L, th_values, I_MS, sensor, ratio, Qblocks_size, flagQNR):
if th_values == 1:
I_F[I_F > 2 ** L] = 2 ** L
I_F[I_F < 0] = 0
assert flagQNR == False, 'flagQNR should be False'
if flagQNR:
QNR_index, D_lambda, D_S = my_qnr(I_F, I_MS_LR, I_MS, I_PAN, ratio, Qblocks_size)
else:
QNR_index, D_lambda, D_S, HQNR_map = HQNR(I_F, I_MS_LR, I_MS, I_PAN, Qblocks_size, sensor, ratio)
return QNR_index, D_lambda, D_S, HQNR_map
if __name__ == '__main__':
import scipy.io as sio
ratio = 4
index = 16
I_F = sio.loadmat(r'E:\HSI_PAN_result\pan_other_methods\WV3_Full\FusionNet\results\output_mulExm_' + f'{index}.mat')['sr'].astype(np.float32)
I_MS = sio.loadmat(r'E:\HSI_PAN_result\pan_other_methods\WV3_Full\EXP\results\output_mulExm_' + f'{index}.mat')['sr']
I_MS_LR = imresize(I_MS, 1/ratio) # I_F[...,[4,2,0]]
I_PAN = sio.loadmat(r'E:\HSI_PAN_result\pan_other_methods\WV3_Full\PAN\results\output_mulExm_' + f'{index}.mat')['sr']
L = 11
th_values = 0
sensor = 'wv3'.upper()
tag_ab = 'sensor-based'
Qblocks_size = 32
if th_values:
I_F[I_F > 2**L] = 2**L
I_F[I_F < 0] = 0
QNR_index, D_lambda, D_S, HQNR_map = indexes_evaluation_FS(I_F, I_MS_LR, I_PAN, L, th_values, I_MS, sensor, ratio, Qblocks_size, False)
print(QNR_index)
import matplotlib as mpl
import matplotlib.pyplot as plt
cmap = mpl.colormaps['jet'].resampled(256)
sup = 1
HQNR_map = imresize(HQNR_map, 512//16)
HQNR_map = HQNR_map - HQNR_map.min()
HQNR_map = HQNR_map / HQNR_map.max()
HQNR_map = HQNR_map / sup
# color mapping
HQNR_map = cmap(HQNR_map)
# HQNR_map = HQNR_map.astype(np.uint8)
plt.imshow(HQNR_map)
# plt.colorbar()
plt.show()
|
281677160/openwrt-package
| 34,355 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_log_module.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp_cmd_module.h"
#include "ngx_rtmp_codec_module.h"
static ngx_rtmp_publish_pt next_publish;
static ngx_rtmp_play_pt next_play;
static ngx_int_t ngx_rtmp_log_postconfiguration(ngx_conf_t *cf);
static void *ngx_rtmp_log_create_main_conf(ngx_conf_t *cf);
static void * ngx_rtmp_log_create_app_conf(ngx_conf_t *cf);
static char * ngx_rtmp_log_merge_app_conf(ngx_conf_t *cf,
void *parent, void *child);
static char * ngx_rtmp_log_set_log(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char * ngx_rtmp_log_set_format(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char * ngx_rtmp_log_compile_format(ngx_conf_t *cf, ngx_array_t *ops,
ngx_array_t *args, ngx_uint_t s);
typedef struct ngx_rtmp_log_op_s ngx_rtmp_log_op_t;
#define MAX_ACCESS_LOG_LINE_LEN 4096
typedef size_t (*ngx_rtmp_log_op_getlen_pt)(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op);
typedef u_char * (*ngx_rtmp_log_op_getdata_pt)(ngx_rtmp_session_t *s,
u_char *buf, ngx_rtmp_log_op_t *log);
struct ngx_rtmp_log_op_s {
ngx_rtmp_log_op_getlen_pt getlen;
ngx_rtmp_log_op_getdata_pt getdata;
ngx_str_t value;
ngx_uint_t offset;
};
typedef struct {
ngx_str_t name;
ngx_rtmp_log_op_getlen_pt getlen;
ngx_rtmp_log_op_getdata_pt getdata;
ngx_uint_t offset;
} ngx_rtmp_log_var_t;
typedef struct {
ngx_str_t name;
ngx_array_t *ops; /* ngx_rtmp_log_op_t */
} ngx_rtmp_log_fmt_t;
typedef struct {
ngx_open_file_t *file;
time_t disk_full_time;
time_t error_log_time;
ngx_msec_t trunc_timer;
ngx_rtmp_log_fmt_t *format;
} ngx_rtmp_log_t;
typedef struct {
ngx_array_t *logs; /* ngx_rtmp_log_t */
ngx_uint_t off;
} ngx_rtmp_log_app_conf_t;
typedef struct {
ngx_array_t formats; /* ngx_rtmp_log_fmt_t */
ngx_uint_t combined_used;
} ngx_rtmp_log_main_conf_t;
typedef struct {
ngx_rtmp_session_t *session;
ngx_event_t event;
ngx_rtmp_log_t *log;
} ngx_rtmp_log_timer_ctx_t;
typedef struct {
unsigned play:1;
unsigned publish:1;
ngx_uint_t last_bytes;
u_char name[NGX_RTMP_MAX_NAME];
u_char stream[NGX_RTMP_MAX_NAME];
u_char args[NGX_RTMP_MAX_ARGS];
ngx_array_t timers; /* ngx_rtmp_log_timer_ctx_t */
} ngx_rtmp_log_ctx_t;
static ngx_str_t ngx_rtmp_access_log = ngx_string(NGX_HTTP_LOG_PATH);
static ngx_command_t ngx_rtmp_log_commands[] = {
{ ngx_string("access_log"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE123,
ngx_rtmp_log_set_log,
NGX_RTMP_APP_CONF_OFFSET,
0,
NULL },
{ ngx_string("log_format"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_2MORE,
ngx_rtmp_log_set_format,
NGX_RTMP_MAIN_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_rtmp_log_module_ctx = {
NULL, /* preconfiguration */
ngx_rtmp_log_postconfiguration, /* postconfiguration */
ngx_rtmp_log_create_main_conf, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_rtmp_log_create_app_conf, /* create app configuration */
ngx_rtmp_log_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_rtmp_log_module = {
NGX_MODULE_V1,
&ngx_rtmp_log_module_ctx, /* module context */
ngx_rtmp_log_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static ngx_str_t ngx_rtmp_combined_fmt =
ngx_string("$remote_addr [$time_local] $command "
"\"$app\" \"$name\" \"$args\" - "
"$bytes_received $bytes_sent "
"\"$pageurl\" \"$flashver\" ($session_readable_time)");
static size_t
ngx_rtmp_log_var_default_getlen(ngx_rtmp_session_t *s, ngx_rtmp_log_op_t *op)
{
return op->value.len;
}
static u_char *
ngx_rtmp_log_var_default_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
return ngx_cpymem(buf, op->value.data, op->value.len);
}
static size_t
ngx_rtmp_log_var_parg_getlen(ngx_rtmp_session_t *s, ngx_rtmp_log_op_t *op)
{
ngx_str_t *name = &(op->value);
u_char *arg;
size_t len;
ngx_str_t value;
len = name->len - (sizeof("parg_") - 1);
arg = name->data + sizeof("parg_") - 1;
if (ngx_rtmp_arg(s, arg, len, &value) != NGX_OK) {
return op->value.len;
}
return value.len;
}
static u_char *
ngx_rtmp_log_var_parg_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_str_t *name = &(op->value);
u_char *arg;
size_t len;
ngx_str_t value;
len = name->len - (sizeof("parg_") - 1);
arg = name->data + sizeof("parg_") - 1;
if (ngx_rtmp_arg(s, arg, len, &value) != NGX_OK) {
return ngx_cpymem(buf, op->value.data, op->value.len);
}
return ngx_cpymem(buf, value.data, value.len);
}
static size_t
ngx_rtmp_log_var_connection_getlen(ngx_rtmp_session_t *s, ngx_rtmp_log_op_t *op)
{
return NGX_INT_T_LEN;
}
static u_char *
ngx_rtmp_log_var_connection_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
return ngx_sprintf(buf, "%ui", (ngx_uint_t) s->number);
}
static size_t
ngx_rtmp_log_var_remote_addr_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return s->remote_addr_text.len;
}
static u_char *
ngx_rtmp_log_var_remote_addr_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
return ngx_cpymem(buf, s->remote_addr_text.data,
s->remote_addr_text.len);
}
static size_t
ngx_rtmp_log_var_msec_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return NGX_TIME_T_LEN + 4;
}
static u_char *
ngx_rtmp_log_var_msec_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_time_t *tp;
tp = ngx_timeofday();
return ngx_sprintf(buf, "%T.%03M", tp->sec, tp->msec);
}
static size_t
ngx_rtmp_log_var_sec_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return NGX_TIME_T_LEN + 4;
}
static u_char *
ngx_rtmp_log_var_sec_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_time_t *tp;
tp = ngx_timeofday();
return ngx_sprintf(buf, "%T", tp->sec);
}
static size_t
ngx_rtmp_log_var_session_string_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return ((ngx_str_t *) ((u_char *) s + op->offset))->len;
}
static u_char *
ngx_rtmp_log_var_session_string_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_str_t *str;
str = (ngx_str_t *) ((u_char *) s + op->offset);
return ngx_cpymem(buf, str->data, str->len);
}
static size_t
ngx_rtmp_log_var_command_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return sizeof("PLAY+PUBLISH") - 1;
}
static u_char *
ngx_rtmp_log_var_command_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_rtmp_log_ctx_t *ctx;
ngx_str_t *cmd;
ngx_uint_t n;
static ngx_str_t commands[] = {
ngx_string("NONE"),
ngx_string("PLAY"),
ngx_string("PUBLISH"),
ngx_string("PLAY+PUBLISH")
};
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_log_module);
n = ctx ? (ctx->play + ctx->publish * 2) : 0;
cmd = &commands[n];
return ngx_cpymem(buf, cmd->data, cmd->len);
}
static size_t
ngx_rtmp_log_var_context_cstring_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return ngx_max(NGX_RTMP_MAX_NAME, NGX_RTMP_MAX_ARGS);
}
static u_char *
ngx_rtmp_log_var_context_cstring_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_rtmp_log_ctx_t *ctx;
u_char *p;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_log_module);
if (ctx == NULL) {
return buf;
}
p = (u_char *) ctx + op->offset;
while (*p) {
*buf++ = *p++;
}
return buf;
}
static size_t
ngx_rtmp_log_var_session_uint32_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return NGX_INT32_LEN;
}
static u_char *
ngx_rtmp_log_var_session_uint32_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
uint32_t *v;
v = (uint32_t *) ((uint8_t *) s + op->offset);
return ngx_sprintf(buf, "%uD", *v);
}
static u_char *
ngx_rtmp_log_var_session_video_flag(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_rtmp_codec_ctx_t *ctx;
ngx_int_t flag;
flag = 0;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_codec_module);
if (ctx) {
flag = (ctx->video_codec_id > 0);
}
return ngx_sprintf(buf, "%d", flag);
}
static u_char *
ngx_rtmp_log_var_session_audio_flag(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_rtmp_codec_ctx_t *ctx;
ngx_int_t flag;
flag = 0;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_codec_module);
if (ctx) {
flag = (ctx->audio_codec_id > 0);
}
return ngx_sprintf(buf, "%d", flag);
}
static u_char *
ngx_rtmp_log_var_session_bitrate_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
ngx_rtmp_log_ctx_t *ctx;
uint32_t bitrate;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_log_module);
if (!ctx) {
return buf;
}
bitrate = 0;
if (s->publishing) {
bitrate = 8 * (s->in_bytes - ctx->last_bytes);
ctx->last_bytes = s->in_bytes;
} else {
bitrate = 8 * (s->out_bytes - ctx->last_bytes);
ctx->last_bytes = s->out_bytes;
}
return ngx_sprintf(buf, "%D", bitrate);
}
static size_t
ngx_rtmp_log_var_time_local_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return ngx_cached_http_log_time.len;
}
static u_char *
ngx_rtmp_log_var_time_local_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
return ngx_cpymem(buf, ngx_cached_http_log_time.data,
ngx_cached_http_log_time.len);
}
static size_t
ngx_rtmp_log_var_session_time_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return NGX_INT64_LEN;
}
static u_char *
ngx_rtmp_log_var_session_time_getdata(ngx_rtmp_session_t *s, u_char *buf,
ngx_rtmp_log_op_t *op)
{
return ngx_sprintf(buf, "%L",
(int64_t) (ngx_current_msec - s->epoch) / 1000);
}
static size_t
ngx_rtmp_log_var_session_readable_time_getlen(ngx_rtmp_session_t *s,
ngx_rtmp_log_op_t *op)
{
return NGX_INT_T_LEN + sizeof("d 23h 59m 59s") - 1;
}
static u_char *
ngx_rtmp_log_var_session_readable_time_getdata(ngx_rtmp_session_t *s,
u_char *buf, ngx_rtmp_log_op_t *op)
{
int64_t v;
ngx_uint_t days, hours, minutes, seconds;
v = (ngx_current_msec - s->epoch) / 1000;
days = (ngx_uint_t) (v / (60 * 60 * 24));
hours = (ngx_uint_t) (v / (60 * 60) % 24);
minutes = (ngx_uint_t) (v / 60 % 60);
seconds = (ngx_uint_t) (v % 60);
if (days) {
buf = ngx_sprintf(buf, "%uid ", days);
}
if (days || hours) {
buf = ngx_sprintf(buf, "%uih ", hours);
}
if (days || hours || minutes) {
buf = ngx_sprintf(buf, "%uim ", minutes);
}
buf = ngx_sprintf(buf, "%uis", seconds);
return buf;
}
static ngx_rtmp_log_var_t ngx_rtmp_log_vars[] = {
{ ngx_string("connection"),
ngx_rtmp_log_var_connection_getlen,
ngx_rtmp_log_var_connection_getdata,
0 },
{ ngx_string("remote_addr"),
ngx_rtmp_log_var_remote_addr_getlen,
ngx_rtmp_log_var_remote_addr_getdata,
0 },
{ ngx_string("app"),
ngx_rtmp_log_var_session_string_getlen,
ngx_rtmp_log_var_session_string_getdata,
offsetof(ngx_rtmp_session_t, app) },
{ ngx_string("flashver"),
ngx_rtmp_log_var_session_string_getlen,
ngx_rtmp_log_var_session_string_getdata,
offsetof(ngx_rtmp_session_t, flashver) },
{ ngx_string("swfurl"),
ngx_rtmp_log_var_session_string_getlen,
ngx_rtmp_log_var_session_string_getdata,
offsetof(ngx_rtmp_session_t, swf_url) },
{ ngx_string("tcurl"),
ngx_rtmp_log_var_session_string_getlen,
ngx_rtmp_log_var_session_string_getdata,
offsetof(ngx_rtmp_session_t, tc_url) },
{ ngx_string("domain"),
ngx_rtmp_log_var_session_string_getlen,
ngx_rtmp_log_var_session_string_getdata,
offsetof(ngx_rtmp_session_t, domain) },
{ ngx_string("parg_"),
ngx_rtmp_log_var_parg_getlen,
ngx_rtmp_log_var_parg_getdata,
0 },
{ ngx_string("pageurl"),
ngx_rtmp_log_var_session_string_getlen,
ngx_rtmp_log_var_session_string_getdata,
offsetof(ngx_rtmp_session_t, page_url) },
{ ngx_string("command"),
ngx_rtmp_log_var_command_getlen,
ngx_rtmp_log_var_command_getdata,
0 },
{ ngx_string("name"),
ngx_rtmp_log_var_context_cstring_getlen,
ngx_rtmp_log_var_context_cstring_getdata,
offsetof(ngx_rtmp_log_ctx_t, name) },
{ ngx_string("stream"),
ngx_rtmp_log_var_context_cstring_getlen,
ngx_rtmp_log_var_context_cstring_getdata,
offsetof(ngx_rtmp_log_ctx_t, stream) },
{ ngx_string("args"),
ngx_rtmp_log_var_context_cstring_getlen,
ngx_rtmp_log_var_context_cstring_getdata,
offsetof(ngx_rtmp_log_ctx_t, args) },
{ ngx_string("bytes_sent"),
ngx_rtmp_log_var_session_uint32_getlen,
ngx_rtmp_log_var_session_uint32_getdata,
offsetof(ngx_rtmp_session_t, out_bytes) },
{ ngx_string("bytes_received"),
ngx_rtmp_log_var_session_uint32_getlen,
ngx_rtmp_log_var_session_uint32_getdata,
offsetof(ngx_rtmp_session_t, in_bytes) },
{ ngx_string("time_local"),
ngx_rtmp_log_var_time_local_getlen,
ngx_rtmp_log_var_time_local_getdata,
0 },
{ ngx_string("msec"),
ngx_rtmp_log_var_msec_getlen,
ngx_rtmp_log_var_msec_getdata,
0 },
{ ngx_string("ntp"),
ngx_rtmp_log_var_sec_getlen,
ngx_rtmp_log_var_sec_getdata,
0 },
{ ngx_string("session_time"),
ngx_rtmp_log_var_session_time_getlen,
ngx_rtmp_log_var_session_time_getdata,
0 },
{ ngx_string("session_readable_time"),
ngx_rtmp_log_var_session_readable_time_getlen,
ngx_rtmp_log_var_session_readable_time_getdata,
0 },
{ ngx_string("bitrate"),
ngx_rtmp_log_var_session_uint32_getlen,
ngx_rtmp_log_var_session_bitrate_getdata,
0 },
{ ngx_string("be_video"),
ngx_rtmp_log_var_session_uint32_getlen,
ngx_rtmp_log_var_session_video_flag,
0 },
{ ngx_string("be_audio"),
ngx_rtmp_log_var_session_uint32_getlen,
ngx_rtmp_log_var_session_audio_flag,
0 },
{ ngx_null_string, NULL, NULL, 0 }
};
static void *
ngx_rtmp_log_create_main_conf(ngx_conf_t *cf)
{
ngx_rtmp_log_main_conf_t *lmcf;
ngx_rtmp_log_fmt_t *fmt;
lmcf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_log_main_conf_t));
if (lmcf == NULL) {
return NULL;
}
if (ngx_array_init(&lmcf->formats, cf->pool, 4, sizeof(ngx_rtmp_log_fmt_t))
!= NGX_OK)
{
return NULL;
}
fmt = ngx_array_push(&lmcf->formats);
if (fmt == NULL) {
return NULL;
}
ngx_str_set(&fmt->name, "combined");
fmt->ops = ngx_array_create(cf->pool, 16, sizeof(ngx_rtmp_log_op_t));
if (fmt->ops == NULL) {
return NULL;
}
return lmcf;
}
static void *
ngx_rtmp_log_create_app_conf(ngx_conf_t *cf)
{
ngx_rtmp_log_app_conf_t *lacf;
lacf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_log_app_conf_t));
if (lacf == NULL) {
return NULL;
}
return lacf;
}
static char *
ngx_rtmp_log_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_log_app_conf_t *prev = parent;
ngx_rtmp_log_app_conf_t *conf = child;
ngx_rtmp_log_main_conf_t *lmcf;
ngx_rtmp_log_fmt_t *fmt;
ngx_rtmp_log_t *log;
if (conf->logs || conf->off) {
return NGX_OK;
}
conf->logs = prev->logs;
conf->off = prev->off;
if (conf->logs || conf->off) {
return NGX_OK;
}
conf->logs = ngx_array_create(cf->pool, 2, sizeof(ngx_rtmp_log_t));
if (conf->logs == NULL) {
return NGX_CONF_ERROR;
}
log = ngx_array_push(conf->logs);
if (log == NULL) {
return NGX_CONF_ERROR;
}
log->file = ngx_conf_open_file(cf->cycle, &ngx_rtmp_access_log);
if (log->file == NULL) {
return NGX_CONF_ERROR;
}
log->disk_full_time = 0;
log->error_log_time = 0;
log->trunc_timer = 0;
lmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_log_module);
fmt = lmcf->formats.elts;
log->format = &fmt[0];
lmcf->combined_used = 1;
return NGX_CONF_OK;
}
/*
* access_log off;
* access_log file;
* access_log file format_name;
* access_log file trunc=1m;
* access_log file format_name trunc=1m;
*/
static char *
ngx_rtmp_log_set_log(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_rtmp_log_app_conf_t *lacf = conf;
ngx_rtmp_log_main_conf_t *lmcf;
ngx_rtmp_log_fmt_t *fmt;
ngx_rtmp_log_t *log;
ngx_str_t *value, name, timer;
ngx_uint_t n;
ngx_flag_t format_configured;
name.len = 0;
format_configured = 0;
value = cf->args->elts;
if (ngx_strcmp(value[1].data, "off") == 0) {
lacf->off = 1;
return NGX_CONF_OK;
}
if (lacf->logs == NULL) {
lacf->logs = ngx_array_create(cf->pool, 2, sizeof(ngx_rtmp_log_t));
if (lacf->logs == NULL) {
return NGX_CONF_ERROR;
}
}
log = ngx_array_push(lacf->logs);
if (log == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(log, sizeof(*log));
lmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_log_module);
log->file = ngx_conf_open_file(cf->cycle, &value[1]);
if (log->file == NULL) {
return NGX_CONF_ERROR;
}
for (n = 2; n < cf->args->nelts; ++n) {
/* sizeof("trunc=") - 1 = 6 */
if (ngx_memcmp("trunc=", value[n].data, 6) == 0) {
timer.data = value[n].data + 6;
timer.len = value[n].len - 6;
log->trunc_timer = ngx_parse_time(&timer, 0);
if (log->trunc_timer == (ngx_msec_t) NGX_ERROR) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0,
"unknown trunc timer format \"%V\"", &timer);
return NGX_CONF_ERROR;
}
} else {
if (format_configured) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0,
"format name has been configured");
return NGX_CONF_ERROR;
}
format_configured = 1;
name = value[n];
}
}
if (name.len == 0) {
ngx_str_set(&name, "combined");
lmcf->combined_used = 1;
} else {
if (ngx_strcmp(name.data, "combined") == 0) {
lmcf->combined_used = 1;
}
}
fmt = lmcf->formats.elts;
for (n = 0; n < lmcf->formats.nelts; ++n, ++fmt) {
if (fmt->name.len == name.len &&
ngx_strncasecmp(fmt->name.data, name.data, name.len) == 0)
{
log->format = fmt;
break;
}
}
if (log->format == NULL) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0, "unknown log format \"%V\"",
&name);
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static char *
ngx_rtmp_log_set_format(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_rtmp_log_main_conf_t *lmcf = conf;
ngx_rtmp_log_fmt_t *fmt;
ngx_str_t *value;
ngx_uint_t i;
value = cf->args->elts;
if (cf->cmd_type != NGX_RTMP_MAIN_CONF) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0,
"\"log_format\" directive can only be used on "
"\"rtmp\" level");
}
fmt = lmcf->formats.elts;
for (i = 0; i < lmcf->formats.nelts; i++) {
if (fmt[i].name.len == value[1].len &&
ngx_strcmp(fmt[i].name.data, value[1].data) == 0)
{
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"duplicate \"log_format\" name \"%V\"",
&value[1]);
return NGX_CONF_ERROR;
}
}
fmt = ngx_array_push(&lmcf->formats);
if (fmt == NULL) {
return NGX_CONF_ERROR;
}
fmt->name = value[1];
fmt->ops = ngx_array_create(cf->pool, 16, sizeof(ngx_rtmp_log_op_t));
if (fmt->ops == NULL) {
return NGX_CONF_ERROR;
}
return ngx_rtmp_log_compile_format(cf, fmt->ops, cf->args, 2);
}
static char *
ngx_rtmp_log_compile_format(ngx_conf_t *cf, ngx_array_t *ops, ngx_array_t *args,
ngx_uint_t s)
{
size_t i, len;
u_char *data, *d, c;
ngx_uint_t bracket;
ngx_str_t *value, var, pre_var;
ngx_rtmp_log_op_t *op;
ngx_rtmp_log_var_t *v;
u_char *p;
value = args->elts;
for (; s < args->nelts; ++s) {
i = 0;
len = value[s].len;
d = value[s].data;
while (i < len) {
op = ngx_array_push(ops);
if (op == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(op, sizeof(*op));
data = &d[i];
if (d[i] == '$') {
if (++i == len) {
goto invalid;
}
if (d[i] == '{') {
bracket = 1;
if (++i == len) {
goto invalid;
}
} else {
bracket = 0;
}
var.data = &d[i];
for (var.len = 0; i < len; ++i, ++var.len) {
c = d[i];
if (c == '}' && bracket) {
++i;
bracket = 0;
break;
}
if ((c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
(c >= '0' && c <= '9') ||
(c == '_'))
{
continue;
}
break;
}
if (bracket) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"missing closing bracket in \"%V\"",
&var);
return NGX_CONF_ERROR;
}
if (var.len == 0) {
goto invalid;
}
for (v = ngx_rtmp_log_vars; v->name.len; ++v) {
if (v->name.len == var.len &&
ngx_strncmp(v->name.data, var.data, var.len) == 0)
{
op->getlen = v->getlen;
op->getdata = v->getdata;
op->offset = v->offset;
break;
}
}
if (v->name.len == 0) {
p = ngx_strnstr(var.data, "_", var.len);
if (p == NULL) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unknown variable \"%V\"", &var);
return NGX_CONF_ERROR;
}
pre_var.data = var.data;
pre_var.len = p - var.data + 1;
for (v = ngx_rtmp_log_vars; v->name.len; ++v) {
if (v->name.len == pre_var.len &&
!ngx_strncmp(v->name.data, pre_var.data, pre_var.len))
{
op->getlen = v->getlen;
op->getdata = v->getdata;
op->offset = v->offset;
op->value = var;
break;
}
}
}
if (v->name.len == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"unknown variable \"%V\"", &var);
return NGX_CONF_ERROR;
}
continue;
}
++i;
while (i < len && d[i] != '$') {
++i;
}
op->getlen = ngx_rtmp_log_var_default_getlen;
op->getdata = ngx_rtmp_log_var_default_getdata;
op->value.len = &d[i] - data;
op->value.data = ngx_pnalloc(cf->pool, op->value.len);
if (op->value.data == NULL) {
return NGX_CONF_ERROR;
}
ngx_memcpy(op->value.data, data, op->value.len);
}
}
return NGX_CONF_OK;
invalid:
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "invalid parameter \"%s\"", data);
return NGX_CONF_ERROR;
}
static ngx_rtmp_log_ctx_t *
ngx_rtmp_log_set_names(ngx_rtmp_session_t *s, u_char *name, u_char *args)
{
ngx_rtmp_log_ctx_t *ctx;
ngx_rtmp_log_app_conf_t *lacf;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_log_module);
if (ctx == NULL) {
ctx = ngx_pcalloc(s->pool, sizeof(ngx_rtmp_log_ctx_t));
if (ctx == NULL) {
return NULL;
}
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_log_module);
if (lacf->logs) {
if (ngx_array_init(&ctx->timers, s->pool,
lacf->logs->nelts, sizeof(ngx_rtmp_log_timer_ctx_t)) != NGX_OK)
{
return NULL;
}
}
ngx_rtmp_set_ctx(s, ctx, ngx_rtmp_log_module);
}
ngx_memcpy(ctx->stream, s->stream.data, s->stream.len);
ngx_memcpy(ctx->name, name, NGX_RTMP_MAX_NAME);
ngx_memcpy(ctx->args, args, NGX_RTMP_MAX_ARGS);
return ctx;
}
static void
ngx_rtmp_log_write(ngx_rtmp_session_t *s, ngx_rtmp_log_t *log, u_char *buf,
size_t len)
{
u_char *name;
time_t now;
ssize_t n;
int err;
err = 0;
name = log->file->name.data;
n = ngx_write_fd(log->file->fd, buf, len);
if (n == (ssize_t) len) {
return;
}
now = ngx_time();
if (n == -1) {
err = ngx_errno;
if (err == NGX_ENOSPC) {
log->disk_full_time = now;
}
if (now - log->error_log_time > 59) {
ngx_log_error(NGX_LOG_ALERT, s->log, err,
ngx_write_fd_n " to \"%s\" failed", name);
log->error_log_time = now;
}
}
if (now - log->error_log_time > 59) {
ngx_log_error(NGX_LOG_ALERT, s->log, err,
ngx_write_fd_n " to \"%s\" was incomplete: %z of %uz",
name, n, len);
log->error_log_time = now;
}
}
static void
ngx_rtmp_log_pre_write(ngx_rtmp_session_t *s, ngx_rtmp_log_t *log)
{
ngx_rtmp_log_op_t *op;
u_char line[MAX_ACCESS_LOG_LINE_LEN], *p;
size_t len;
ngx_uint_t n;
if (ngx_time() == log->disk_full_time) {
/* FreeBSD full disk protection;
* nginx http logger does the same */
return;
}
len = 0;
op = log->format->ops->elts;
for (n = 0; n < log->format->ops->nelts; ++n, ++op) {
len += op->getlen(s, op);
}
len += NGX_LINEFEED_SIZE;
if (len > MAX_ACCESS_LOG_LINE_LEN) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"Access line len %z greater than %d",
len, MAX_ACCESS_LOG_LINE_LEN);
ngx_rtmp_finalize_session(s);
return;
}
p = line;
op = log->format->ops->elts;
for (n = 0; n < log->format->ops->nelts; ++n, ++op) {
p = op->getdata(s, p, op);
}
ngx_linefeed(p);
ngx_rtmp_log_write(s, log, line, p - line);
}
static void
ngx_rtmp_log_trunc_timer(ngx_event_t *ev)
{
ngx_rtmp_log_timer_ctx_t *ltctx;
ngx_rtmp_session_t *s;
ngx_rtmp_log_t *log;
ngx_msec_t t;
ltctx = ev->data;
s = ltctx->session;
log = ltctx->log;
ngx_rtmp_log_pre_write(s, log);
t = log->trunc_timer - ngx_current_msec % log->trunc_timer;
ngx_add_timer(ev, t);
}
static void
ngx_rtmp_log_add_trunc_timer(ngx_rtmp_session_t *s, ngx_rtmp_log_ctx_t *ctx,
ngx_rtmp_log_t *log)
{
ngx_rtmp_log_timer_ctx_t *ltctx;
ngx_event_t *e;
ngx_msec_t t;
ltctx = ngx_array_push(&ctx->timers);
ngx_memzero(ltctx, sizeof(ngx_rtmp_log_timer_ctx_t));
ltctx->session = s;
ltctx->log = log;
e = <ctx->event;
e->data = ltctx;
e->log = s->log;
e->handler = ngx_rtmp_log_trunc_timer;
t = log->trunc_timer - ngx_current_msec % log->trunc_timer;
ngx_add_timer(e, t);
}
static ngx_int_t
ngx_rtmp_log_publish(ngx_rtmp_session_t *s, ngx_rtmp_publish_t *v)
{
ngx_rtmp_log_app_conf_t *lacf;
ngx_rtmp_log_t *log;
ngx_rtmp_log_ctx_t *ctx;
ngx_uint_t i;
if (s->interprocess || s->relay) {
goto next;
}
ctx = ngx_rtmp_log_set_names(s, v->name, v->args);
if (ctx == NULL) {
goto next;
}
if (ctx->publish) { /* avoid multi push */
goto next;
}
ctx->publish = 1;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_log_module);
if (lacf->logs == NULL) {
goto next;
}
log = lacf->logs->elts;
for (i = 0; i < lacf->logs->nelts; ++i, ++log) {
if (log->trunc_timer != 0) {
ngx_rtmp_log_add_trunc_timer(s, ctx, log);
}
}
next:
return next_publish(s, v);
}
static ngx_int_t
ngx_rtmp_log_play(ngx_rtmp_session_t *s, ngx_rtmp_play_t *v)
{
ngx_rtmp_log_app_conf_t *lacf;
ngx_rtmp_log_t *log;
ngx_rtmp_log_ctx_t *ctx;
ngx_uint_t i;
if (s->interprocess || s->relay) {
goto next;
}
ctx = ngx_rtmp_log_set_names(s, v->name, v->args);
if (ctx == NULL) {
goto next;
}
if (ctx->play) { /* avoid mulit pull */
goto next;
}
ctx->play = 1;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_log_module);
if (lacf->logs == NULL) {
goto next;
}
log = lacf->logs->elts;
for (i = 0; i < lacf->logs->nelts; ++i, ++log) {
if (log->trunc_timer != 0) {
ngx_rtmp_log_add_trunc_timer(s, ctx, log);
}
}
next:
return next_play(s, v);
}
static ngx_int_t
ngx_rtmp_log_disconnect(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_rtmp_log_app_conf_t *lacf;
ngx_rtmp_log_ctx_t *ctx;
ngx_rtmp_log_timer_ctx_t *ltctx;
ngx_rtmp_log_t *log;
ngx_uint_t i;
if (s->interprocess || s->relay) {
return NGX_OK;
}
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_log_module);
if (lacf == NULL || lacf->off || lacf->logs == NULL) {
return NGX_OK;
}
log = lacf->logs->elts;
for (i = 0; i < lacf->logs->nelts; ++i, ++log) {
ngx_rtmp_log_pre_write(s, log);
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_log_module);
if (ctx == NULL) {
return NGX_OK;
}
ltctx = ctx->timers.elts;
for (i = 0; i < ctx->timers.nelts; ++i, ++ltctx) {
ngx_del_timer(<ctx->event);
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_log_postconfiguration(ngx_conf_t *cf)
{
ngx_rtmp_core_main_conf_t *cmcf;
ngx_rtmp_handler_pt *h;
ngx_rtmp_log_main_conf_t *lmcf;
ngx_array_t a;
ngx_rtmp_log_fmt_t *fmt;
ngx_str_t *value;
lmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_log_module);
if (lmcf->combined_used) {
if (ngx_array_init(&a, cf->pool, 1, sizeof(ngx_str_t)) != NGX_OK) {
return NGX_ERROR;
}
value = ngx_array_push(&a);
if (value == NULL) {
return NGX_ERROR;
}
*value = ngx_rtmp_combined_fmt;
fmt = lmcf->formats.elts;
if (ngx_rtmp_log_compile_format(cf, fmt->ops, &a, 0)
!= NGX_CONF_OK)
{
return NGX_ERROR;
}
}
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
h = ngx_array_push(&cmcf->events[NGX_RTMP_DISCONNECT]);
*h = ngx_rtmp_log_disconnect;
next_publish = ngx_rtmp_publish;
ngx_rtmp_publish = ngx_rtmp_log_publish;
next_play = ngx_rtmp_play;
ngx_rtmp_play = ngx_rtmp_log_play;
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 7,492 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css
|
table.dataTable th.dt-left,table.dataTable td.dt-left{text-align:left}table.dataTable th.dt-center,table.dataTable td.dt-center,table.dataTable td.dataTables_empty{text-align:center}table.dataTable th.dt-right,table.dataTable td.dt-right{text-align:right}table.dataTable th.dt-justify,table.dataTable td.dt-justify{text-align:justify}table.dataTable th.dt-nowrap,table.dataTable td.dt-nowrap{white-space:nowrap}table.dataTable thead th.dt-head-left,table.dataTable thead td.dt-head-left,table.dataTable tfoot th.dt-head-left,table.dataTable tfoot td.dt-head-left{text-align:left}table.dataTable thead th.dt-head-center,table.dataTable thead td.dt-head-center,table.dataTable tfoot th.dt-head-center,table.dataTable tfoot td.dt-head-center{text-align:center}table.dataTable thead th.dt-head-right,table.dataTable thead td.dt-head-right,table.dataTable tfoot th.dt-head-right,table.dataTable tfoot td.dt-head-right{text-align:right}table.dataTable thead th.dt-head-justify,table.dataTable thead td.dt-head-justify,table.dataTable tfoot th.dt-head-justify,table.dataTable tfoot td.dt-head-justify{text-align:justify}table.dataTable thead th.dt-head-nowrap,table.dataTable thead td.dt-head-nowrap,table.dataTable tfoot th.dt-head-nowrap,table.dataTable tfoot td.dt-head-nowrap{white-space:nowrap}table.dataTable tbody th.dt-body-left,table.dataTable tbody td.dt-body-left{text-align:left}table.dataTable tbody th.dt-body-center,table.dataTable tbody td.dt-body-center{text-align:center}table.dataTable tbody th.dt-body-right,table.dataTable tbody td.dt-body-right{text-align:right}table.dataTable tbody th.dt-body-justify,table.dataTable tbody td.dt-body-justify{text-align:justify}table.dataTable tbody th.dt-body-nowrap,table.dataTable tbody td.dt-body-nowrap{white-space:nowrap}table.dataTable td.dt-control{text-align:center;cursor:pointer}table.dataTable td.dt-control:before{height:1em;width:1em;margin-top:-9px;display:inline-block;color:white;border:.15em solid white;border-radius:1em;box-shadow:0 0 .2em #444;box-sizing:content-box;text-align:center;text-indent:0 !important;font-family:"Courier New",Courier,monospace;line-height:1em;content:"+";background-color:#31b131}table.dataTable tr.dt-hasChild td.dt-control:before{content:"-";background-color:#d33333}table.dataTable{clear:both;margin-top:6px !important;margin-bottom:6px !important;max-width:none !important;border-collapse:separate !important;border-spacing:0}table.dataTable td,table.dataTable th{-webkit-box-sizing:content-box;box-sizing:content-box}table.dataTable td.dataTables_empty,table.dataTable th.dataTables_empty{text-align:center}table.dataTable.nowrap th,table.dataTable.nowrap td{white-space:nowrap}div.dataTables_wrapper div.dataTables_length label{font-weight:normal;text-align:left;white-space:nowrap}div.dataTables_wrapper div.dataTables_length select{width:auto;display:inline-block}div.dataTables_wrapper div.dataTables_filter{text-align:right}div.dataTables_wrapper div.dataTables_filter label{font-weight:normal;white-space:nowrap;text-align:left}div.dataTables_wrapper div.dataTables_filter input{margin-left:.5em;display:inline-block;width:auto}div.dataTables_wrapper div.dataTables_info{padding-top:.85em}div.dataTables_wrapper div.dataTables_paginate{margin:0;white-space:nowrap;text-align:right}div.dataTables_wrapper div.dataTables_paginate ul.pagination{margin:2px 0;white-space:nowrap;justify-content:flex-end}div.dataTables_wrapper div.dataTables_processing{position:absolute;top:50%;left:50%;width:200px;margin-left:-100px;margin-top:-26px;text-align:center;padding:1em 0}table.dataTable>thead>tr>th:active,table.dataTable>thead>tr>td:active{outline:none}table.dataTable>thead>tr>th:not(.sorting_disabled),table.dataTable>thead>tr>td:not(.sorting_disabled){padding-right:30px}table.dataTable>thead .sorting,table.dataTable>thead .sorting_asc,table.dataTable>thead .sorting_desc,table.dataTable>thead .sorting_asc_disabled,table.dataTable>thead .sorting_desc_disabled{cursor:pointer;position:relative}table.dataTable>thead .sorting:before,table.dataTable>thead .sorting:after,table.dataTable>thead .sorting_asc:before,table.dataTable>thead .sorting_asc:after,table.dataTable>thead .sorting_desc:before,table.dataTable>thead .sorting_desc:after,table.dataTable>thead .sorting_asc_disabled:before,table.dataTable>thead .sorting_asc_disabled:after,table.dataTable>thead .sorting_desc_disabled:before,table.dataTable>thead .sorting_desc_disabled:after{position:absolute;bottom:.9em;display:block;opacity:.3}table.dataTable>thead .sorting:before,table.dataTable>thead .sorting_asc:before,table.dataTable>thead .sorting_desc:before,table.dataTable>thead .sorting_asc_disabled:before,table.dataTable>thead .sorting_desc_disabled:before{right:1em;content:"↑"}table.dataTable>thead .sorting:after,table.dataTable>thead .sorting_asc:after,table.dataTable>thead .sorting_desc:after,table.dataTable>thead .sorting_asc_disabled:after,table.dataTable>thead .sorting_desc_disabled:after{right:.5em;content:"↓"}table.dataTable>thead .sorting_asc:before,table.dataTable>thead .sorting_desc:after{opacity:1}table.dataTable>thead .sorting_asc_disabled:before,table.dataTable>thead .sorting_desc_disabled:after{opacity:0}div.dataTables_scrollHead table.dataTable{margin-bottom:0 !important}div.dataTables_scrollBody>table{border-top:none;margin-top:0 !important;margin-bottom:0 !important}div.dataTables_scrollBody>table>thead .sorting:before,div.dataTables_scrollBody>table>thead .sorting_asc:before,div.dataTables_scrollBody>table>thead .sorting_desc:before,div.dataTables_scrollBody>table>thead .sorting:after,div.dataTables_scrollBody>table>thead .sorting_asc:after,div.dataTables_scrollBody>table>thead .sorting_desc:after{display:none}div.dataTables_scrollBody>table>tbody tr:first-child th,div.dataTables_scrollBody>table>tbody tr:first-child td{border-top:none}div.dataTables_scrollFoot>.dataTables_scrollFootInner{box-sizing:content-box}div.dataTables_scrollFoot>.dataTables_scrollFootInner>table{margin-top:0 !important;border-top:none}@media screen and (max-width: 767px){div.dataTables_wrapper div.dataTables_length,div.dataTables_wrapper div.dataTables_filter,div.dataTables_wrapper div.dataTables_info,div.dataTables_wrapper div.dataTables_paginate{text-align:center}div.dataTables_wrapper div.dataTables_paginate ul.pagination{justify-content:center !important}}table.dataTable.table-sm>thead>tr>th:not(.sorting_disabled){padding-right:20px}table.dataTable.table-sm .sorting:before,table.dataTable.table-sm .sorting_asc:before,table.dataTable.table-sm .sorting_desc:before{top:5px;right:.85em}table.dataTable.table-sm .sorting:after,table.dataTable.table-sm .sorting_asc:after,table.dataTable.table-sm .sorting_desc:after{top:5px}table.table-bordered.dataTable{border-right-width:0}table.table-bordered.dataTable th,table.table-bordered.dataTable td{border-left-width:0}table.table-bordered.dataTable th:last-child,table.table-bordered.dataTable th:last-child,table.table-bordered.dataTable td:last-child,table.table-bordered.dataTable td:last-child{border-right-width:1px}table.table-bordered.dataTable tbody th,table.table-bordered.dataTable tbody td{border-bottom-width:0}div.dataTables_scrollHead table.table-bordered{border-bottom-width:0}div.table-responsive>div.dataTables_wrapper>div.row{margin:0}div.table-responsive>div.dataTables_wrapper>div.row>div[class^=col-]:first-child{padding-left:0}div.table-responsive>div.dataTables_wrapper>div.row>div[class^=col-]:last-child{padding-right:0}
|
294coder/Efficient-MIF
| 8,030 |
utils/FS_index/my_q2n.py
|
# GPL License
# Copyright (C) UESTC
# All Rights Reserved
# @Author : Xiao Wu
# @reference:
#
# 由于dat及其方差等数值舍入存在误差,最终结果有0.001左右的误差
import numpy as np
import torch
import math
def q2n(gt, x, q_blocks_size, q_shift):
'''
'''
if isinstance(gt, torch.Tensor):
gt = gt.cpu().numpy()
x = x.cpu().numpy()
N1, N2, N3 = gt.shape # 255 255 8
size2 = q_blocks_size # 32
stepx = math.ceil(N1 / q_shift) # 8
stepy = math.ceil(N2 / q_shift) # 8
if stepy <= 0:
stepy = 1
stepx = 1
est1 = (stepx - 1) * q_shift + q_blocks_size - N1 # 1
est2 = (stepy - 1) * q_shift + q_blocks_size - N2 # 1
# if np.sum(np.array([est1 != 0, est2 != 0])) > 0:
# refref = np.zeros(shape=[N1+1, N2+1])
# fusfus = refref.copy()
if sum([(est1!=0), (est2!=0)]) > 0:
for i in range(N3):
a1 = gt[..., 0]
ia1 = np.zeros(shape=[N1 + est1, N2 + est2])
ia1[:N1, : N2] = a1
ia1[:, N2:N2 + est2] = ia1[:, N2-1:-1:N2 - est2 + 1]
ia1[N1:N1 + est1, ...] = ia1[N1-1:-1:N1-est1+1, ...]
if i == 0:
refref = ia1[..., np.newaxis] # np.concatenate(refref, ia1, axis=3)
else:
refref = np.concatenate([refref, ia1[..., np.newaxis]], axis=-1)
if i < N3:
gt = gt[..., 1:]
gt = refref
for i in range(N3):
a2 = x[..., 0]
ia2 = np.zeros(shape=[N1 + est1, N2 + est2])
ia2[: N1, : N2] = a2
ia2[:, N2:N2 + est2] = ia2[:, N2 - 1:-1:N2 - est2 + 1]
ia2[N1:N1 + est1, ...] = ia2[N1 - 1:-1:N1 - est1 + 1, ...]
if i == 0:
fusfus = ia2[..., np.newaxis] # np.concatenate(refref, ia1, axis=3)
else:
fusfus = np.concatenate([fusfus, ia2[..., np.newaxis]], axis=-1)
if i < N3:
x = x[..., 1:]
x = fusfus
# Equivalent to uint16(gt) in matlab (Xiao Wu in UESTC)
x = np.round(x.clip(0)).astype(np.uint16)
gt = np.round(gt.clip(0)).astype(np.uint16)
N1, N2, N3 = gt.shape
if math.ceil(math.log2(N3)) - math.log2(N3) != 0:
Ndif = pow(2, math.ceil(math.log2(N3))) - N3
dif = np.zeros(shape=[N1, N2, Ndif], dtype=np.uint16)
gt = np.concatenate([gt, dif], axis=-1)
x = np.concatenate([x, dif], axis=-1)
_, _, N3 = gt.shape
valori = np.zeros(shape=[stepx, stepy, N3])
for j in range(stepx):
for i in range(stepy):
o = onions_quality(gt[j * q_shift:j * q_shift + q_blocks_size,
i * q_shift: i * q_shift + size2, :],
x[j * q_shift:j * q_shift + q_blocks_size,
i * q_shift: i * q_shift + size2, :],
q_blocks_size)
# 0.971379489438014 0.00553590637316723 0.00305237797490489 -0.0188289323262161 -0.00420556598390016 -0.0173947468044076 -0.0202144450367593 0.0102693855205061
valori[j, i, :] = o
q2n_idx_map = np.sqrt(np.sum(valori ** 2, axis=-1))
q2n_index = np.mean(q2n_idx_map)
return q2n_index, q2n_idx_map
def norm_blocco(x, eps=1e-8):
a = x.mean()
c = x.std()
if c == 0:
c = eps
return (x - a) / c + 1, a, c
def onions_quality(dat1, dat2, size1):
dat1 = np.float64(dat1)
dat2 = np.float64(dat2)
dat2 = np.concatenate([dat2[..., 0, np.newaxis], -dat2[..., 1:]], axis=-1)
_, _, N3 = dat1.shape
size2 = size1
# Block norm
'''
319.6474609375 37.05174450544686
357.970703125 61.54042371537683
518.708984375 111.53732768071865
608.23828125 154.26606056030568
593.412109375 163.97722215177643
554.8486328125 113.96758695803403
690.16015625 151.29524031046248
442.2314453125 94.12877724960003
mat
319.6475 37.0698
357.9707 61.5705
518.7090 111.5918
608.2383 154.3414
593.4121 164.0573
554.8486 114.0233
690.1602 151.3692
442.2314 94.1748
'''
for i in range(N3):
a1, s, t = norm_blocco(np.squeeze(dat1[..., i]))
# print(s,t)
dat1[..., i] = a1
if s == 0:
if i == 0:
dat2[..., i] = dat2[..., i] - s + 1
else:
dat2[..., i] = -(-dat2[..., i] - s + 1)
else:
if i == 0:
dat2[..., i] = ((dat2[..., i] - s) / t) + 1
else:
dat2[..., i] = -(((-dat2[..., i] - s) / t) + 1)
m1 = np.zeros(shape=[N3])
m2 = m1.copy()
mod_q1m = 0
mod_q2m = 0
mod_q1 = np.zeros(shape=[size1, size2])
mod_q2 = np.zeros(shape=[size1, size2])
for i in range(N3):
m1[..., i] = np.mean(np.squeeze(dat1[..., i]))
m2[..., i] = np.mean(np.squeeze(dat2[..., i]))
mod_q1m += m1[..., i] ** 2
mod_q2m += m2[..., i] ** 2
mod_q1 += np.squeeze(dat1[..., i]) ** 2
mod_q2 += np.squeeze(dat2[..., i]) ** 2
mod_q1m = np.sqrt(mod_q1m)
mod_q2m = np.sqrt(mod_q2m)
mod_q1 = np.sqrt(mod_q1)
mod_q2 = np.sqrt(mod_q2)
termine2 = mod_q1m * mod_q2m # 7.97
termine4 = mod_q1m ** 2 + mod_q2m ** 2 #
int1 = (size1 * size2) / (size1 * size2 - 1) * np.mean(mod_q1 ** 2)
int2 = (size1 * size2) / (size1 * size2 - 1) * np.mean(mod_q2 ** 2)
termine3 = int1 + int2 - (size1 * size2) / ((size1 * size2 - 1)) * (mod_q1m ** 2 + mod_q2m ** 2) # 17.8988 ** 2
mean_bias = 2 * termine2 / termine4 # 1
if termine3 == 0:
q = np.zeros(shape=[1, N3])
q[:, :, N3 - 1] = mean_bias
else:
cbm = 2 / termine3
# 32 32 8
qu = onion_mult2D(dat1, dat2)
qm = onion_mult(m1.reshape(-1), m2.reshape(-1))
qv = np.zeros(shape=[N3])
for i in range(N3):
qv[i] = (size1 * size2) / ((size1 * size2) - 1) * np.mean(np.squeeze(qu[:, :, i]))
q = qv - (size1 * size2) / ((size1 * size2) - 1) * qm
q = q * mean_bias * cbm
return q
def onion_mult2D(onion1, onion2):
_, _, N3 = onion1.shape
if N3 > 1:
L = N3 // 2
a = onion1[..., : L]
b = onion1[..., L:]
b = np.concatenate([b[..., 0, np.newaxis], -b[..., 1:]], axis=-1)
c = onion2[..., : L]
d = onion2[..., L:]
d = np.concatenate([d[..., 0, np.newaxis], -d[..., 1:]], axis=-1)
if N3 == 2:
ris = np.concatenate([a * c - d * b, a * d + c * b], axis=-1)
else:
ris1 = onion_mult2D(a, c)
ris2 = onion_mult2D(d, np.concatenate([b[..., 0, np.newaxis], -b[..., 1:]], axis=-1))
ris3 = onion_mult2D(np.concatenate([a[..., 0, np.newaxis], -a[..., 1:]], axis=-1), d)
ris4 = onion_mult2D(c, b)
aux1 = ris1 - ris2
aux2 = ris3 + ris4
ris = np.concatenate([aux1, aux2], axis=-1)
else:
ris = onion1 * onion2
return ris
def onion_mult(onion1, onion2):
# _, N = onion1.shape
N = len(onion1)
if N > 1:
L = N // 2
a = onion1[:L]
b = onion1[L:]
# b[1:] = -b[1:]
b = np.append(np.array(b[0]), -b[1:])
c = onion2[:L]
d = onion2[L:]
# d[1:] = -d[1:]
d = np.append(np.array(d[0]), -d[1:])
if N == 2:
ris = np.append(a * c - d * b, a * d + c * b)
else:
ris1 = onion_mult(a, c)
# b[1:] = -b[1:]
ris2 = onion_mult(d, np.append(np.array(b[0]), -b[1:]))
# a[1:] = -a[1:]
ris3 = onion_mult(np.append(np.array(a[0]), -a[1:]), d)
ris4 = onion_mult(c, b)
aux1 = ris1 - ris2
aux2 = ris3 + ris4
ris = np.append(aux1, aux2)
else:
ris = np.array(onion1).reshape(-1) * np.array(onion2).reshape(-1)
return ris
|
2881099/FreeSql.AdminLTE
| 29,067 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/datatables-fixedheader/js/dataTables.fixedHeader.js
|
/*! FixedHeader 3.2.1
* ©2009-2021 SpryMedia Ltd - datatables.net/license
*/
/**
* @summary FixedHeader
* @description Fix a table's header or footer, so it is always visible while
* scrolling
* @version 3.2.1
* @file dataTables.fixedHeader.js
* @author SpryMedia Ltd (www.sprymedia.co.uk)
* @contact www.sprymedia.co.uk/contact
* @copyright Copyright 2009-2021 SpryMedia Ltd.
*
* This source file is free software, available under the following license:
* MIT license - http://datatables.net/license/mit
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
*
* For details please refer to: http://www.datatables.net
*/
(function( factory ){
if ( typeof define === 'function' && define.amd ) {
// AMD
define( ['jquery', 'datatables.net'], function ( $ ) {
return factory( $, window, document );
} );
}
else if ( typeof exports === 'object' ) {
// CommonJS
module.exports = function (root, $) {
if ( ! root ) {
root = window;
}
if ( ! $ || ! $.fn.dataTable ) {
$ = require('datatables.net')(root, $).$;
}
return factory( $, root, root.document );
};
}
else {
// Browser
factory( jQuery, window, document );
}
}(function( $, window, document, undefined ) {
'use strict';
var DataTable = $.fn.dataTable;
var _instCounter = 0;
var FixedHeader = function ( dt, config ) {
// Sanity check - you just know it will happen
if ( ! (this instanceof FixedHeader) ) {
throw "FixedHeader must be initialised with the 'new' keyword.";
}
// Allow a boolean true for defaults
if ( config === true ) {
config = {};
}
dt = new DataTable.Api( dt );
this.c = $.extend( true, {}, FixedHeader.defaults, config );
this.s = {
dt: dt,
position: {
theadTop: 0,
tbodyTop: 0,
tfootTop: 0,
tfootBottom: 0,
width: 0,
left: 0,
tfootHeight: 0,
theadHeight: 0,
windowHeight: $(window).height(),
visible: true
},
headerMode: null,
footerMode: null,
autoWidth: dt.settings()[0].oFeatures.bAutoWidth,
namespace: '.dtfc'+(_instCounter++),
scrollLeft: {
header: -1,
footer: -1
},
enable: true
};
this.dom = {
floatingHeader: null,
thead: $(dt.table().header()),
tbody: $(dt.table().body()),
tfoot: $(dt.table().footer()),
header: {
host: null,
floating: null,
floatingParent: $('<div class="dtfh-floatingparent">'),
placeholder: null
},
footer: {
host: null,
floating: null,
floatingParent: $('<div class="dtfh-floatingparent">'),
placeholder: null
}
};
this.dom.header.host = this.dom.thead.parent();
this.dom.footer.host = this.dom.tfoot.parent();
var dtSettings = dt.settings()[0];
if ( dtSettings._fixedHeader ) {
throw "FixedHeader already initialised on table "+dtSettings.nTable.id;
}
dtSettings._fixedHeader = this;
this._constructor();
};
/*
* Variable: FixedHeader
* Purpose: Prototype for FixedHeader
* Scope: global
*/
$.extend( FixedHeader.prototype, {
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* API methods
*/
/**
* Kill off FH and any events
*/
destroy: function () {
this.s.dt.off( '.dtfc' );
$(window).off( this.s.namespace );
if ( this.c.header ) {
this._modeChange( 'in-place', 'header', true );
}
if ( this.c.footer && this.dom.tfoot.length ) {
this._modeChange( 'in-place', 'footer', true );
}
},
/**
* Enable / disable the fixed elements
*
* @param {boolean} enable `true` to enable, `false` to disable
*/
enable: function ( enable, update )
{
this.s.enable = enable;
if ( update || update === undefined ) {
this._positions();
this._scroll( true );
}
},
/**
* Get enabled status
*/
enabled: function ()
{
return this.s.enable;
},
/**
* Set header offset
*
* @param {int} new value for headerOffset
*/
headerOffset: function ( offset )
{
if ( offset !== undefined ) {
this.c.headerOffset = offset;
this.update();
}
return this.c.headerOffset;
},
/**
* Set footer offset
*
* @param {int} new value for footerOffset
*/
footerOffset: function ( offset )
{
if ( offset !== undefined ) {
this.c.footerOffset = offset;
this.update();
}
return this.c.footerOffset;
},
/**
* Recalculate the position of the fixed elements and force them into place
*/
update: function (force)
{
var table = this.s.dt.table().node();
if ( $(table).is(':visible') ) {
this.enable( true, false );
}
else {
this.enable( false, false );
}
// Don't update if header is not in the document atm (due to
// async events)
if ($(table).children('thead').length === 0) {
return;
}
this._positions();
this._scroll( force !== undefined ? force : true );
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Constructor
*/
/**
* FixedHeader constructor - adding the required event listeners and
* simple initialisation
*
* @private
*/
_constructor: function ()
{
var that = this;
var dt = this.s.dt;
$(window)
.on( 'scroll'+this.s.namespace, function () {
that._scroll();
} )
.on( 'resize'+this.s.namespace, DataTable.util.throttle( function () {
that.s.position.windowHeight = $(window).height();
that.update();
}, 50 ) );
var autoHeader = $('.fh-fixedHeader');
if ( ! this.c.headerOffset && autoHeader.length ) {
this.c.headerOffset = autoHeader.outerHeight();
}
var autoFooter = $('.fh-fixedFooter');
if ( ! this.c.footerOffset && autoFooter.length ) {
this.c.footerOffset = autoFooter.outerHeight();
}
dt
.on( 'column-reorder.dt.dtfc column-visibility.dt.dtfc column-sizing.dt.dtfc responsive-display.dt.dtfc', function (e, ctx) {
that.update();
} )
.on( 'draw.dt.dtfc', function (e, ctx) {
// For updates from our own table, don't reclone, but for all others, do
that.update(ctx === dt.settings()[0] ? false : true);
} );
dt.on( 'destroy.dtfc', function () {
that.destroy();
} );
this._positions();
this._scroll();
},
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Private methods
*/
/**
* Clone a fixed item to act as a place holder for the original element
* which is moved into a clone of the table element, and moved around the
* document to give the fixed effect.
*
* @param {string} item 'header' or 'footer'
* @param {boolean} force Force the clone to happen, or allow automatic
* decision (reuse existing if available)
* @private
*/
_clone: function ( item, force )
{
var dt = this.s.dt;
var itemDom = this.dom[ item ];
var itemElement = item === 'header' ?
this.dom.thead :
this.dom.tfoot;
// If footer and scrolling is enabled then we don't clone
// Instead the table's height is decreased accordingly - see `_scroll()`
if (item === 'footer' && this._scrollEnabled()) {
return;
}
if ( ! force && itemDom.floating ) {
// existing floating element - reuse it
itemDom.floating.removeClass( 'fixedHeader-floating fixedHeader-locked' );
}
else {
if ( itemDom.floating ) {
if(itemDom.placeholder !== null) {
itemDom.placeholder.remove();
}
this._unsize( item );
itemDom.floating.children().detach();
itemDom.floating.remove();
}
var tableNode = $(dt.table().node());
var scrollBody = $(tableNode.parent());
var scrollEnabled = this._scrollEnabled();
itemDom.floating = $( dt.table().node().cloneNode( false ) )
.attr( 'aria-hidden', 'true' )
.css({
'table-layout': 'fixed',
top: 0,
left: 0
})
.removeAttr( 'id' )
.append( itemElement );
itemDom.floatingParent
.css({
width: scrollBody.width(),
overflow: 'hidden',
height: 'fit-content',
position: 'fixed',
left: scrollEnabled ? tableNode.offset().left + scrollBody.scrollLeft() : 0
})
.css(
item === 'header' ?
{
top: this.c.headerOffset,
bottom: ''
} :
{
top: '',
bottom: this.c.footerOffset
}
)
.addClass(item === 'footer' ? 'dtfh-floatingparentfoot' : 'dtfh-floatingparenthead')
.append(itemDom.floating)
.appendTo( 'body' );
this._stickyPosition(itemDom.floating, '-');
var scrollLeftUpdate = () => {
var scrollLeft = scrollBody.scrollLeft()
this.s.scrollLeft = {footer: scrollLeft, header: scrollLeft};
itemDom.floatingParent.scrollLeft(this.s.scrollLeft.header);
}
scrollLeftUpdate();
scrollBody.scroll(scrollLeftUpdate)
// Insert a fake thead/tfoot into the DataTable to stop it jumping around
itemDom.placeholder = itemElement.clone( false );
itemDom.placeholder
.find( '*[id]' )
.removeAttr( 'id' );
itemDom.host.prepend( itemDom.placeholder );
// Clone widths
this._matchWidths( itemDom.placeholder, itemDom.floating );
}
},
/**
* This method sets the sticky position of the header elements to match fixed columns
* @param {JQuery<HTMLElement>} el
* @param {string} sign
*/
_stickyPosition(el, sign) {
if (this._scrollEnabled()) {
var that = this
var rtl = $(that.s.dt.table().node()).css('direction') === 'rtl';
el.find('th').each(function() {
// Find out if fixed header has previously set this column
if ($(this).css('position') === 'sticky') {
var right = $(this).css('right');
var left = $(this).css('left');
if (right !== 'auto' && !rtl) {
// New position either adds or dismisses the barWidth
var potential = +right.replace(/px/g, '') + (sign === '-' ? -1 : 1) * that.s.dt.settings()[0].oBrowser.barWidth;
$(this).css('right', potential > 0 ? potential : 0);
}
else if(left !== 'auto' && rtl) {
var potential = +left.replace(/px/g, '') + (sign === '-' ? -1 : 1) * that.s.dt.settings()[0].oBrowser.barWidth;
$(this).css('left', potential > 0 ? potential : 0);
}
}
});
}
},
/**
* Copy widths from the cells in one element to another. This is required
* for the footer as the footer in the main table takes its sizes from the
* header columns. That isn't present in the footer so to have it still
* align correctly, the sizes need to be copied over. It is also required
* for the header when auto width is not enabled
*
* @param {jQuery} from Copy widths from
* @param {jQuery} to Copy widths to
* @private
*/
_matchWidths: function ( from, to ) {
var get = function ( name ) {
return $(name, from)
.map( function () {
return $(this).css('width').replace(/[^\d\.]/g, '') * 1;
} ).toArray();
};
var set = function ( name, toWidths ) {
$(name, to).each( function ( i ) {
$(this).css( {
width: toWidths[i],
minWidth: toWidths[i]
} );
} );
};
var thWidths = get( 'th' );
var tdWidths = get( 'td' );
set( 'th', thWidths );
set( 'td', tdWidths );
},
/**
* Remove assigned widths from the cells in an element. This is required
* when inserting the footer back into the main table so the size is defined
* by the header columns and also when auto width is disabled in the
* DataTable.
*
* @param {string} item The `header` or `footer`
* @private
*/
_unsize: function ( item ) {
var el = this.dom[ item ].floating;
if ( el && (item === 'footer' || (item === 'header' && ! this.s.autoWidth)) ) {
$('th, td', el).css( {
width: '',
minWidth: ''
} );
}
else if ( el && item === 'header' ) {
$('th, td', el).css( 'min-width', '' );
}
},
/**
* Reposition the floating elements to take account of horizontal page
* scroll
*
* @param {string} item The `header` or `footer`
* @param {int} scrollLeft Document scrollLeft
* @private
*/
_horizontal: function ( item, scrollLeft )
{
var itemDom = this.dom[ item ];
var position = this.s.position;
var lastScrollLeft = this.s.scrollLeft;
if ( itemDom.floating && lastScrollLeft[ item ] !== scrollLeft ) {
// If scrolling is enabled we need to match the floating header to the body
if (this._scrollEnabled()) {
var newScrollLeft = $($(this.s.dt.table().node()).parent()).scrollLeft()
itemDom.floating.scrollLeft(newScrollLeft);
itemDom.floatingParent.scrollLeft(newScrollLeft);
}
lastScrollLeft[ item ] = scrollLeft;
}
},
/**
* Change from one display mode to another. Each fixed item can be in one
* of:
*
* * `in-place` - In the main DataTable
* * `in` - Floating over the DataTable
* * `below` - (Header only) Fixed to the bottom of the table body
* * `above` - (Footer only) Fixed to the top of the table body
*
* @param {string} mode Mode that the item should be shown in
* @param {string} item 'header' or 'footer'
* @param {boolean} forceChange Force a redraw of the mode, even if already
* in that mode.
* @private
*/
_modeChange: function ( mode, item, forceChange )
{
var dt = this.s.dt;
var itemDom = this.dom[ item ];
var position = this.s.position;
// Just determine if scroll is enabled once
var scrollEnabled = this._scrollEnabled();
// If footer and scrolling is enabled then we don't clone
// Instead the table's height is decreased accordingly - see `_scroll()`
if (item === 'footer' && scrollEnabled) {
return;
}
// It isn't trivial to add a !important css attribute...
var importantWidth = function (w) {
itemDom.floating.attr('style', function(i,s) {
return (s || '') + 'width: '+w+'px !important;';
});
// If not scrolling also have to update the floatingParent
if (!scrollEnabled) {
itemDom.floatingParent.attr('style', function(i,s) {
return (s || '') + 'width: '+w+'px !important;';
});
}
};
// Record focus. Browser's will cause input elements to loose focus if
// they are inserted else where in the doc
var tablePart = this.dom[ item==='footer' ? 'tfoot' : 'thead' ];
var focus = $.contains( tablePart[0], document.activeElement ) ?
document.activeElement :
null;
var scrollBody = $($(this.s.dt.table().node()).parent());
if ( mode === 'in-place' ) {
// Insert the header back into the table's real header
if ( itemDom.placeholder ) {
itemDom.placeholder.remove();
itemDom.placeholder = null;
}
this._unsize( item );
if ( item === 'header' ) {
itemDom.host.prepend( tablePart );
}
else {
itemDom.host.append( tablePart );
}
if ( itemDom.floating ) {
itemDom.floating.remove();
itemDom.floating = null;
this._stickyPosition(itemDom.host, '+');
}
if ( itemDom.floatingParent ) {
itemDom.floatingParent.remove();
}
$($(itemDom.host.parent()).parent()).scrollLeft(scrollBody.scrollLeft())
}
else if ( mode === 'in' ) {
// Remove the header from the read header and insert into a fixed
// positioned floating table clone
this._clone( item, forceChange );
// Get useful position values
var scrollOffset = scrollBody.offset();
var windowTop = $(document).scrollTop();
var windowHeight = $(window).height();
var windowBottom = windowTop + windowHeight;
var bodyTop = scrollEnabled ? scrollOffset.top : position.tbodyTop;
var bodyBottom = scrollEnabled ? scrollOffset.top + scrollBody.outerHeight() : position.tfootTop
// Calculate the amount that the footer or header needs to be shuffled
var shuffle = item === 'footer' ?
// footer and top of body isn't on screen
bodyTop > windowBottom ?
// Yes - push the footer below
position.tfootHeight :
// No - bottom set to the gap between the top of the body and the bottom of the window
bodyTop + position.tfootHeight - windowBottom :
// Otherwise must be a header so get the difference from the bottom of the
// desired floating header and the bottom of the table body
windowTop + this.c.headerOffset + position.theadHeight - bodyBottom
// Set the top or bottom based off of the offset and the shuffle value
var prop = item === 'header' ? 'top' : 'bottom';
var val = this.c[item+'Offset'] - (shuffle > 0 ? shuffle : 0);
itemDom.floating.addClass( 'fixedHeader-floating' );
itemDom.floatingParent
.css(prop, val)
.css( {
'left': position.left,
'height': item === 'header' ? position.theadHeight : position.tfootHeight,
'z-index': 2
})
.append(itemDom.floating);
importantWidth(position.width);
if ( item === 'footer' ) {
itemDom.floating.css( 'top', '' );
}
}
else if ( mode === 'below' ) { // only used for the header
// Fix the position of the floating header at base of the table body
this._clone( item, forceChange );
itemDom.floating.addClass( 'fixedHeader-locked' );
itemDom.floatingParent.css({
position: 'absolute',
top: position.tfootTop - position.theadHeight,
left: position.left+'px'
});
importantWidth(position.width);
}
else if ( mode === 'above' ) { // only used for the footer
// Fix the position of the floating footer at top of the table body
this._clone( item, forceChange );
itemDom.floating.addClass( 'fixedHeader-locked' );
itemDom.floatingParent.css({
position: 'absolute',
top: position.tbodyTop,
left: position.left+'px'
});
importantWidth(position.width);
}
// Restore focus if it was lost
if ( focus && focus !== document.activeElement ) {
setTimeout( function () {
focus.focus();
}, 10 );
}
this.s.scrollLeft.header = -1;
this.s.scrollLeft.footer = -1;
this.s[item+'Mode'] = mode;
},
/**
* Cache the positional information that is required for the mode
* calculations that FixedHeader performs.
*
* @private
*/
_positions: function ()
{
var dt = this.s.dt;
var table = dt.table();
var position = this.s.position;
var dom = this.dom;
var tableNode = $(table.node());
var scrollEnabled = this._scrollEnabled();
// Need to use the header and footer that are in the main table,
// regardless of if they are clones, since they hold the positions we
// want to measure from
var thead = $(dt.table().header());
var tfoot = $(dt.table().footer());
var tbody = dom.tbody;
var scrollBody = tableNode.parent();
position.visible = tableNode.is(':visible');
position.width = tableNode.outerWidth();
position.left = tableNode.offset().left;
position.theadTop = thead.offset().top;
position.tbodyTop = scrollEnabled ? scrollBody.offset().top : tbody.offset().top;
position.tbodyHeight = scrollEnabled ? scrollBody.outerHeight() : tbody.outerHeight();
position.theadHeight = thead.outerHeight();
position.theadBottom = position.theadTop + position.theadHeight;
if ( tfoot.length ) {
position.tfootTop = position.tbodyTop + position.tbodyHeight; //tfoot.offset().top;
position.tfootBottom = position.tfootTop + tfoot.outerHeight();
position.tfootHeight = tfoot.outerHeight();
}
else {
position.tfootTop = position.tbodyTop + tbody.outerHeight();
position.tfootBottom = position.tfootTop;
position.tfootHeight = position.tfootTop;
}
},
/**
* Mode calculation - determine what mode the fixed items should be placed
* into.
*
* @param {boolean} forceChange Force a redraw of the mode, even if already
* in that mode.
* @private
*/
_scroll: function ( forceChange )
{
// ScrollBody details
var scrollEnabled = this._scrollEnabled();
var scrollBody = $(this.s.dt.table().node()).parent();
var scrollOffset = scrollBody.offset();
var scrollHeight = scrollBody.outerHeight();
// Window details
var windowLeft = $(document).scrollLeft();
var windowTop = $(document).scrollTop();
var windowHeight = $(window).height();
var windowBottom = windowHeight + windowTop
var position = this.s.position;
var headerMode, footerMode;
// Body Details
var bodyTop = (scrollEnabled ? scrollOffset.top : position.tbodyTop);
var bodyLeft = (scrollEnabled ? scrollOffset.left : position.left);
var bodyBottom = (scrollEnabled ? scrollOffset.top + scrollHeight : position.tfootTop);
var bodyWidth = (scrollEnabled ? scrollBody.outerWidth() : position.tbodyWidth);
var windowBottom = windowTop + windowHeight;
if ( this.c.header ) {
if ( ! this.s.enable ) {
headerMode = 'in-place';
}
// The header is in it's normal place if the body top is lower than
// the scroll of the window plus the headerOffset and the height of the header
else if ( ! position.visible || windowTop + this.c.headerOffset + position.theadHeight <= bodyTop) {
headerMode = 'in-place';
}
// The header should be floated if
else if (
// The scrolling plus the header offset plus the height of the header is lower than the top of the body
windowTop + this.c.headerOffset + position.theadHeight > bodyTop &&
// And the scrolling at the top plus the header offset is above the bottom of the body
windowTop + this.c.headerOffset < bodyBottom
) {
headerMode = 'in';
var scrollBody = $($(this.s.dt.table().node()).parent());
// Further to the above, If the scrolling plus the header offset plus the header height is lower
// than the bottom of the table a shuffle is required so have to force the calculation
if(windowTop + this.c.headerOffset + position.theadHeight > bodyBottom || this.dom.header.floatingParent === undefined){
forceChange = true;
}
else {
this.dom.header.floatingParent
.css({
'top': this.c.headerOffset,
'position': 'fixed'
})
.append(this.dom.header.floating);
}
}
// Anything else and the view is below the table
else {
headerMode = 'below';
}
if ( forceChange || headerMode !== this.s.headerMode ) {
this._modeChange( headerMode, 'header', forceChange );
}
this._horizontal( 'header', windowLeft );
}
var header = {
offset: {top: 0, left: 0},
height: 0
}
var footer = {
offset: {top: 0, left: 0},
height: 0
}
if ( this.c.footer && this.dom.tfoot.length ) {
if ( ! this.s.enable ) {
footerMode = 'in-place';
}
else if ( ! position.visible || position.tfootBottom + this.c.footerOffset <= windowBottom ) {
footerMode = 'in-place';
}
else if (
bodyBottom + position.tfootHeight + this.c.footerOffset > windowBottom &&
bodyTop + this.c.footerOffset < windowBottom
) {
footerMode = 'in';
forceChange = true;
}
else {
footerMode = 'above';
}
if ( forceChange || footerMode !== this.s.footerMode ) {
this._modeChange( footerMode, 'footer', forceChange );
}
this._horizontal( 'footer', windowLeft );
var getOffsetHeight = (el) => {
return {
offset: el.offset(),
height: el.outerHeight()
}
}
header = this.dom.header.floating ? getOffsetHeight(this.dom.header.floating) : getOffsetHeight(this.dom.thead);
footer = this.dom.footer.floating ? getOffsetHeight(this.dom.footer.floating) : getOffsetHeight(this.dom.tfoot);
// If scrolling is enabled and the footer is off the screen
if (scrollEnabled && footer.offset.top > windowTop){// && footer.offset.top >= windowBottom) {
// Calculate the gap between the top of the scrollBody and the top of the window
var overlap = windowTop - scrollOffset.top;
// The new height is the bottom of the window
var newHeight = windowBottom +
// If the gap between the top of the scrollbody and the window is more than
// the height of the header then the top of the table is still visible so add that gap
// Doing this has effectively calculated the height from the top of the table to the bottom of the current page
(overlap > -header.height ? overlap : 0) -
// Take from that
(
// The top of the header plus
header.offset.top +
// The header height if the standard header is present
(overlap < -header.height ? header.height : 0) +
// And the height of the footer
footer.height
)
// Don't want a negative height
if (newHeight < 0) {
newHeight = 0;
}
// At the end of the above calculation the space between the header (top of the page if floating)
// and the point just above the footer should be the new value for the height of the table.
scrollBody.outerHeight(newHeight);
// Need some rounding here as sometimes very small decimal places are encountered
// If the actual height is bigger or equal to the height we just applied then the footer is "Floating"
if(Math.round(scrollBody.outerHeight()) >= Math.round(newHeight)) {
$(this.dom.tfoot.parent()).addClass("fixedHeader-floating");
}
// Otherwise max-width has kicked in so it is not floating
else {
$(this.dom.tfoot.parent()).removeClass("fixedHeader-floating");
}
}
}
if(this.dom.header.floating){
this.dom.header.floatingParent.css('left', bodyLeft-windowLeft);
}
if(this.dom.footer.floating){
this.dom.footer.floatingParent.css('left', bodyLeft-windowLeft);
}
// If fixed columns is being used on this table then the blockers need to be copied across
// Cloning these is cleaner than creating as our own as it will keep consistency with fixedColumns automatically
// ASSUMING that the class remains the same
if (this.s.dt.settings()[0]._fixedColumns !== undefined) {
var adjustBlocker = (side, end, el) => {
if (el === undefined) {
let blocker = $('div.dtfc-'+side+'-'+end+'-blocker');
el = blocker.length === 0 ?
null :
blocker.clone().appendTo('body').css('z-index', 1);
}
if(el !== null) {
el.css({
top: end === 'top' ? header.offset.top : footer.offset.top,
left: side === 'right' ? bodyLeft + bodyWidth - el.width() : bodyLeft
});
}
return el;
}
// Adjust all blockers
this.dom.header.rightBlocker = adjustBlocker('right', 'top', this.dom.header.rightBlocker);
this.dom.header.leftBlocker = adjustBlocker('left', 'top', this.dom.header.leftBlocker);
this.dom.footer.rightBlocker = adjustBlocker('right', 'bottom', this.dom.footer.rightBlocker);
this.dom.footer.leftBlocker = adjustBlocker('left', 'bottom', this.dom.footer.leftBlocker);
}
},
/**
* Function to check if scrolling is enabled on the table or not
* @returns Boolean value indicating if scrolling on the table is enabled or not
*/
_scrollEnabled: function() {
var oScroll = this.s.dt.settings()[0].oScroll;
if(oScroll.sY !== "" || oScroll.sX !== "") {
return true;
}
return false
}
} );
/**
* Version
* @type {String}
* @static
*/
FixedHeader.version = "3.2.1";
/**
* Defaults
* @type {Object}
* @static
*/
FixedHeader.defaults = {
header: true,
footer: false,
headerOffset: 0,
footerOffset: 0
};
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* DataTables interfaces
*/
// Attach for constructor access
$.fn.dataTable.FixedHeader = FixedHeader;
$.fn.DataTable.FixedHeader = FixedHeader;
// DataTables creation - check if the FixedHeader option has been defined on the
// table and if so, initialise
$(document).on( 'init.dt.dtfh', function (e, settings, json) {
if ( e.namespace !== 'dt' ) {
return;
}
var init = settings.oInit.fixedHeader;
var defaults = DataTable.defaults.fixedHeader;
if ( (init || defaults) && ! settings._fixedHeader ) {
var opts = $.extend( {}, defaults, init );
if ( init !== false ) {
new FixedHeader( settings, opts );
}
}
} );
// DataTables API methods
DataTable.Api.register( 'fixedHeader()', function () {} );
DataTable.Api.register( 'fixedHeader.adjust()', function () {
return this.iterator( 'table', function ( ctx ) {
var fh = ctx._fixedHeader;
if ( fh ) {
fh.update();
}
} );
} );
DataTable.Api.register( 'fixedHeader.enable()', function ( flag ) {
return this.iterator( 'table', function ( ctx ) {
var fh = ctx._fixedHeader;
flag = ( flag !== undefined ? flag : true );
if ( fh && flag !== fh.enabled() ) {
fh.enable( flag );
}
} );
} );
DataTable.Api.register( 'fixedHeader.enabled()', function () {
if ( this.context.length ) {
var fh = this.context[0]._fixedHeader;
if ( fh ) {
return fh.enabled();
}
}
return false;
} );
DataTable.Api.register( 'fixedHeader.disable()', function ( ) {
return this.iterator( 'table', function ( ctx ) {
var fh = ctx._fixedHeader;
if ( fh && fh.enabled() ) {
fh.enable( false );
}
} );
} );
$.each( ['header', 'footer'], function ( i, el ) {
DataTable.Api.register( 'fixedHeader.'+el+'Offset()', function ( offset ) {
var ctx = this.context;
if ( offset === undefined ) {
return ctx.length && ctx[0]._fixedHeader ?
ctx[0]._fixedHeader[el +'Offset']() :
undefined;
}
return this.iterator( 'table', function ( ctx ) {
var fh = ctx._fixedHeader;
if ( fh ) {
fh[ el +'Offset' ]( offset );
}
} );
} );
} );
return FixedHeader;
}));
|
281677160/openwrt-package
| 2,594 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_variables.h
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#ifndef _NGX_RTMP_VARIABLES_H_INCLUDED_
#define _NGX_RTMP_VARIABLES_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp.h"
typedef ngx_variable_value_t ngx_rtmp_variable_value_t;
#define ngx_rtmp_variable(v) { sizeof(v) - 1, 1, 0, 0, 0, (u_char *) v }
typedef struct ngx_rtmp_variable_s ngx_rtmp_variable_t;
typedef void (*ngx_rtmp_set_variable_pt) (ngx_rtmp_session_t *s,
ngx_rtmp_variable_value_t *v, uintptr_t data);
typedef ngx_int_t (*ngx_rtmp_get_variable_pt) (ngx_rtmp_session_t *s,
ngx_rtmp_variable_value_t *v, uintptr_t data);
#define NGX_RTMP_VAR_CHANGEABLE 1
#define NGX_RTMP_VAR_NOCACHEABLE 2
#define NGX_RTMP_VAR_INDEXED 4
#define NGX_RTMP_VAR_NOHASH 8
#define NGX_RTMP_VAR_WEAK 16
#define NGX_RTMP_VAR_PREFIX 32
struct ngx_rtmp_variable_s {
ngx_str_t name; /* must be first to build the hash */
ngx_rtmp_set_variable_pt set_handler;
ngx_rtmp_get_variable_pt get_handler;
uintptr_t data;
ngx_uint_t flags;
ngx_uint_t index;
};
ngx_rtmp_variable_t *ngx_rtmp_add_variable(ngx_conf_t *cf, ngx_str_t *name,
ngx_uint_t flags);
ngx_int_t ngx_rtmp_get_variable_index(ngx_conf_t *cf, ngx_str_t *name);
ngx_rtmp_variable_value_t *ngx_rtmp_get_indexed_variable(ngx_rtmp_session_t *s,
ngx_uint_t index);
ngx_rtmp_variable_value_t *ngx_rtmp_get_flushed_variable(ngx_rtmp_session_t *s,
ngx_uint_t index);
ngx_rtmp_variable_value_t *ngx_rtmp_get_variable(ngx_rtmp_session_t *s,
ngx_str_t *name, ngx_uint_t key);
ngx_int_t ngx_rtmp_variable_unknown_header(ngx_rtmp_variable_value_t *v,
ngx_str_t *var, ngx_list_part_t *part, size_t prefix);
typedef struct {
ngx_hash_combined_t hash;
#if (NGX_PCRE)
ngx_rtmp_map_regex_t *regex;
ngx_uint_t nregex;
#endif
} ngx_rtmp_map_t;
void *ngx_rtmp_map_find(ngx_rtmp_session_t *s, ngx_rtmp_map_t *map,
ngx_str_t *match);
ngx_int_t ngx_rtmp_variables_add_core_vars(ngx_conf_t *cf);
ngx_int_t ngx_rtmp_variables_init_vars(ngx_conf_t *cf);
ngx_int_t ngx_rtmp_variable_transform_index(ngx_conf_t *cf,
ngx_str_t *origin, ngx_str_t *target);
ngx_int_t ngx_rtmp_fetch_variable(ngx_rtmp_session_t *s, ngx_pool_t *pool,
ngx_str_t *origin, ngx_str_t *target);
extern ngx_rtmp_variable_value_t ngx_rtmp_variable_null_value;
extern ngx_rtmp_variable_value_t ngx_rtmp_variable_true_value;
#endif
|
294coder/Efficient-MIF
| 2,531 |
utils/FS_index/genMTF.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
Generate a bank of filters shaped on the MTF of the sensor. Each filter
corresponds to a band acquired by the sensor.
Interface:
h = genMTF(ratio, sensor, nbands)
Inputs:
ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
sensor: String for type of sensor (e.g. 'WV2','IKONOS');
nbands: Number of spectral bands.
Outputs:
h: Gaussian filter mimicking the MTF of the MS sensor.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
import numpy as np
from .tools import fir_filter_wind, gaussian2d, kaiser2d
def genMTF(ratio, sensor, nbands):
N = 41
if sensor=='QB':
GNyq = np.asarray([0.34, 0.32, 0.30, 0.22],dtype='float32') # Band Order: B,G,R,NIR
elif sensor=='IKONOS':
GNyq = np.asarray([0.26,0.28,0.29,0.28],dtype='float32') # Band Order: B,G,R,NIR
elif sensor=='GeoEye1' or sensor=='WV4':
GNyq = np.asarray([0.23,0.23,0.23,0.23],dtype='float32') # Band Order: B,G,R,NIR
elif sensor=='WV2':
GNyq = [0.35*np.ones(nbands),0.27]
elif sensor=='WV3':
GNyq = np.asarray([0.325,0.355,0.360,0.350,0.365,0.360,0.335,0.315],dtype='float32')
else:
GNyq = 0.3 * np.ones(nbands)
"""MTF"""
h = np.zeros((N, N, nbands))
fcut = 1/ratio
h = np.zeros((N,N,nbands))
for ii in range(nbands):
alpha = np.sqrt(((N-1)*(fcut/2))**2/(-2*np.log(GNyq[ii])))
H=gaussian2d(N,alpha)
Hd=H/np.max(H)
w=kaiser2d(N,0.5)
h[:,:,ii] = np.real(fir_filter_wind(Hd,w))
return h
|
294coder/Efficient-MIF
| 2,177 |
utils/FS_index/MTF_pan.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
MTF filters the image I_MS using a Gaussin filter matched with the Modulation Transfer Function (MTF) of the MultiSpectral (MS) sensor.
Interface:
I_Filtered = MTF(I_MS,sensor,ratio)
Inputs:
I_MS: MS image;
sensor: String for type of sensor (e.g. 'WV2', 'IKONOS');
ratio: Scale ratio between MS and PAN.
Outputs:
I_Filtered: Output filtered MS image.
Notes:
The bottleneck of this function is the function scipy.filters.correlate that gets the same results as in the MATLAB toolbox
but it is very slow with respect to fftconvolve that instead gets slightly different results
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
from scipy import ndimage
import numpy as np
from .genMTF_pan import genMTF_pan
def MTF_pan(I_MS, sensor, ratio):
h = genMTF_pan(ratio, sensor, I_MS.shape[2])
I_MS_LP = np.zeros((I_MS.shape))
for ii in range(I_MS.shape[2]):
I_MS_LP[:, :, ii] = ndimage.filters.correlate(I_MS[:, :, ii], h, mode='nearest')
### This can speed-up the processing, but with slightly different results with respect to the MATLAB toolbox
# hb = h[:,:,ii]
# I_MS_LP[:,:,ii] = signal.fftconvolve(I_MS[:,:,ii],hb[::-1],mode='same')
return np.double(I_MS_LP)
|
281677160/openwrt-package
| 16,708 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_live_relay_httpflv.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_live_relay.h"
#include "ngx_http_client.h"
#include "ngx_toolkit_misc.h"
#include "ngx_dynamic_resolver.h"
#include "ngx_rbuf.h"
typedef struct {
ngx_uint_t status;
char *code;
char *level;
char *desc;
} ngx_http_status_code_t;
static ngx_http_status_code_t ngx_http_relay_status_code[] = {
{ 400, "NetStream.Play.BadName", "error", "Bad Request" },
{ 403, "NetStream.Play.Forbidden", "error", "Forbidden" },
{ 404, "NetStream.Play.StreamNotFound", "error", "No such stream" },
{ 503, "NetStream.Play.ServiceUnavailable", "error", "Service Unavailable"},
{ 0, "NetStream.Play.StreamError", "error", "Stream Error" }
};
static ngx_int_t
ngx_live_relay_httpflv_parse(ngx_rtmp_session_t *s, ngx_buf_t *b)
{
u_char ch, *p, *pc;
ngx_rtmp_stream_t *st;
ngx_rtmp_header_t *h;
ngx_chain_t **ll;
size_t len;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_int_t rc = NGX_AGAIN;
enum {
flv_header_F = 0,
flv_header_FL,
flv_header_FLV,
flv_header_Version,
flv_header_Flags,
flv_header_DataOffset0,
flv_header_DataOffset1,
flv_header_DataOffset2,
flv_header_DataOffset3,
flv_tagsize0,
flv_tagsize1,
flv_tagsize2,
flv_tagsize3,
flv_tagtype,
flv_datasize0,
flv_datasize1,
flv_datasize2,
flv_timestamp0,
flv_timestamp1,
flv_timestamp2,
flv_timestamp_extended,
flv_streamid0,
flv_streamid1,
flv_streamid2,
flv_data
} state;
state = s->flv_state;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
for (p = b->pos; p < b->last; ++p) {
ch = *p;
switch (state) {
case flv_header_F:
switch (ch) {
case 'F':
state = flv_header_FL;
break;
default:
rc = NGX_ERROR;
goto done;
}
break;
case flv_header_FL:
switch (ch) {
case 'L':
state = flv_header_FLV;
break;
default:
rc = NGX_ERROR;
goto done;
}
break;
case flv_header_FLV:
switch (ch) {
case 'V':
state = flv_header_Version;
break;
default:
rc = NGX_ERROR;
goto done;
}
break;
case flv_header_Version:
s->flv_version = ch;
if (s->flv_version != 1) {
rc = NGX_ERROR;
goto done;
}
state = flv_header_Flags;
break;
case flv_header_Flags:
s->flv_flags = ch;
state = flv_header_DataOffset0;
break;
case flv_header_DataOffset0:
pc = (u_char *) &s->flv_data_offset;
pc[3] = ch;
state = flv_header_DataOffset1;
break;
case flv_header_DataOffset1:
pc = (u_char *) &s->flv_data_offset;
pc[2] = ch;
state = flv_header_DataOffset2;
break;
case flv_header_DataOffset2:
pc = (u_char *) &s->flv_data_offset;
pc[1] = ch;
state = flv_header_DataOffset3;
break;
case flv_header_DataOffset3:
pc = (u_char *) &s->flv_data_offset;
pc[0] = ch;
state = flv_tagsize0;
break;
case flv_tagsize0:
s->flv_tagsize = 0;
pc = (u_char *) &s->flv_tagsize;
pc[3] = ch;
state = flv_tagsize1;
break;
case flv_tagsize1:
pc = (u_char *) &s->flv_tagsize;
pc[2] = ch;
state = flv_tagsize2;
break;
case flv_tagsize2:
pc = (u_char *) &s->flv_tagsize;
pc[1] = ch;
state = flv_tagsize3;
break;
case flv_tagsize3:
pc = (u_char *) &s->flv_tagsize;
pc[0] = ch;
st = &s->in_streams[0];
h = &st->hdr;
if (h->mlen == 0 && s->flv_first_pts == 0) {
s->flv_first_pts = 1;
if (s->flv_tagsize != 0) {
rc = NGX_ERROR;
goto done;
}
} else {
if (h->mlen + 11 != s->flv_tagsize) {
rc = NGX_ERROR;
goto done;
}
}
state = flv_tagtype;
break;
case flv_tagtype:
if (ch != NGX_RTMP_MSG_AMF_META && ch != NGX_RTMP_MSG_AUDIO
&& ch != NGX_RTMP_MSG_VIDEO)
{
rc = NGX_ERROR;
goto done;
}
st = &s->in_streams[0];
h = &st->hdr;
h->type = ch;
state = flv_datasize0;
break;
case flv_datasize0:
st = &s->in_streams[0];
h = &st->hdr;
h->mlen = 0;
pc = (u_char *) &h->mlen;
pc[2] = ch;
state = flv_datasize1;
break;
case flv_datasize1:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->mlen;
pc[1] = ch;
state = flv_datasize2;
break;
case flv_datasize2:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->mlen;
pc[0] = ch;
state = flv_timestamp0;
st->len = h->mlen;
break;
case flv_timestamp0:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->timestamp;
pc[2] = ch;
state = flv_timestamp1;
break;
case flv_timestamp1:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->timestamp;
pc[1] = ch;
state = flv_timestamp2;
break;
case flv_timestamp2:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->timestamp;
pc[0] = ch;
state = flv_timestamp_extended;
break;
case flv_timestamp_extended:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->timestamp;
pc[3] = ch;
state = flv_streamid0;
break;
case flv_streamid0:
st = &s->in_streams[0];
h = &st->hdr;
h->msid = 0;
pc = (u_char *) &h->msid;
pc[2] = ch;
state = flv_streamid1;
break;
case flv_streamid1:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->msid;
pc[1] = ch;
state = flv_streamid2;
break;
case flv_streamid2:
st = &s->in_streams[0];
h = &st->hdr;
pc = (u_char *) &h->msid;
pc[0] = ch;
state = flv_data;
break;
case flv_data:
st = &s->in_streams[0];
for (ll = &st->in; (*ll) && (*ll)->buf->last == (*ll)->buf->end;
ll = &(*ll)->next);
for (;;) {
if (*ll == NULL) {
*ll = ngx_get_chainbuf(cscf->chunk_size, 1);
}
len = ngx_min(st->len, b->last - p);
if ((*ll)->buf->end - (*ll)->buf->last >= (long) len) {
(*ll)->buf->last = ngx_cpymem((*ll)->buf->last, p, len);
p += len;
st->len -= len;
break;
}
len = (*ll)->buf->end - (*ll)->buf->last;
(*ll)->buf->last = ngx_cpymem((*ll)->buf->last, p, len);
p += len;
st->len -= len;
ll = &(*ll)->next;
}
if (st->len != 0) {
rc = NGX_AGAIN;
goto done;
}
state = flv_tagsize0;
rc = NGX_OK;
goto done;
}
}
done:
b->pos = p;
s->flv_state = state;
return rc;
}
static void
ngx_live_relay_httpflv_recv_body(void *request, ngx_http_request_t *hcr)
{
ngx_int_t n;
ngx_rtmp_session_t *s;
ngx_chain_t *cl, *l, *in;
ngx_rtmp_header_t *h;
ngx_rtmp_stream_t *st = NULL;
s = request;
n = ngx_http_client_read_body(hcr, &cl);
if (n == 0 || n == NGX_ERROR) {
s->finalize_reason = n == 0? NGX_LIVE_NORMAL_CLOSE:
NGX_LIVE_FLV_RECV_ERR;
ngx_log_error(NGX_LOG_INFO, s->log, ngx_errno,
"http relay, recv body error");
ngx_rtmp_finalize_session(s);
return;
}
l = cl;
for (;;) {
if (l && l->buf->pos == l->buf->last) {
l = l->next;
}
if (l == NULL) {
return;
}
n = ngx_live_relay_httpflv_parse(s, l->buf);
if (n == NGX_ERROR) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"http relay, parse flv frame failed in state %d",
s->flv_state);
ngx_http_client_finalize_request(hcr, 1);
return;
}
if (n == NGX_AGAIN) {
continue;
}
/* NGX_OK */
st = &s->in_streams[0];
h = &st->hdr;
in = st->in;
if (ngx_rtmp_receive_message(s, h, in) != NGX_OK) {
ngx_rtmp_finalize_session(s);
return;
}
ngx_put_chainbufs(st->in);
st->in = NULL;
}
}
static void
ngx_live_relay_httpflv_cleanup(void *data)
{
ngx_rtmp_session_t *s;
s = data;
ngx_log_error(NGX_LOG_INFO, s->log, 0, "http flv client, cleanup");
if (s) {
if (s->close.posted) {
ngx_delete_posted_event(&s->close);
}
if (s->finalize_reason == 0) {
s->finalize_reason = NGX_LIVE_FLV_RECV_ERR;
}
ngx_rtmp_finalize_fake_session(s);
}
}
static void
ngx_live_relay_httpflv_error(ngx_rtmp_session_t *s, ngx_uint_t status)
{
ngx_live_stream_t *st;
ngx_rtmp_core_ctx_t *cctx;
char *code, *level, *desc;
size_t i;
for (i = 0; ngx_http_relay_status_code[i].status; ++i) {
if (status != ngx_http_relay_status_code[i].status) {
continue;
}
break;
}
code = ngx_http_relay_status_code[i].code;
level = ngx_http_relay_status_code[i].level;
desc = ngx_http_relay_status_code[i].desc;
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"http relay transit, %d: level='%s' code='%s' description='%s'",
status, level, code, desc);
st = ngx_live_create_stream(&s->serverid, &s->stream);
cctx = st->play_ctx;
for (; cctx; cctx = cctx->next) {
cctx->session->status = status;
ngx_rtmp_send_status(cctx->session, code, level, desc);
if (ngx_strcmp(level, "error") == 0 && !cctx->session->static_pull) {
cctx->session->finalize_reason = NGX_LIVE_RELAY_TRANSIT;
ngx_rtmp_finalize_session(cctx->session);
}
}
}
static void
ngx_live_relay_httpflv_recv(void *request, ngx_http_request_t *hcr)
{
ngx_rtmp_session_t *s;
ngx_uint_t status_code;
s = request;
status_code = ngx_http_client_status_code(hcr);
s->stage = NGX_LIVE_PLAY;
s->ptime = ngx_current_msec;
s->connection = hcr->connection;
ngx_rtmp_set_combined_log(s, hcr->connection->log->data,
hcr->connection->log->handler);
s->log->connection = s->connection->number;
if (ngx_rtmp_core_main_conf->fast_reload && (ngx_exiting || ngx_terminate)) {
ngx_live_relay_httpflv_error(s, NGX_LIVE_PROCESS_EXIT);
s->finalize_reason = NGX_LIVE_PROCESS_EXIT;
ngx_http_client_finalize_request(hcr, 1);
return;
}
if (status_code != NGX_HTTP_OK) {
ngx_live_relay_httpflv_error(s, status_code);
s->finalize_reason = NGX_LIVE_FLV_RECV_ERR;
ngx_http_client_finalize_request(hcr, 1);
return;
}
ngx_live_relay_publish_local(s);
ngx_http_client_set_read_handler(hcr, ngx_live_relay_httpflv_recv_body);
ngx_live_relay_httpflv_recv_body(request, hcr);
}
static ngx_int_t
ngx_live_relay_httpflv_send_request(ngx_rtmp_session_t *s,
ngx_live_relay_url_t *url)
{
ngx_http_request_t *hcr;
ngx_str_t request_url;
size_t len;
ngx_live_relay_ctx_t *ctx;
ngx_http_cleanup_t *cln;
u_char *p;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
// request url
// http:// + url + ':' + port + '/' + app + '/' + name + ['?' + pargs]
len = 7 + url->url.host.len + 1 + sizeof("65535") - 1
+ 1 + ctx->app.len + 1 + ctx->name.len;
if (ctx->pargs.len) {
len = len + 1 + ctx->pargs.len;
}
request_url.data = ngx_pcalloc(s->pool, len);
if (request_url.data == NULL) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"alloc mem for request url failed");
return NGX_ERROR;
}
if (ctx->pargs.len) {
p = ngx_snprintf(request_url.data, len, "http://%V:%d/%V/%V?%V",
&url->url.host, url->port, &ctx->app, &ctx->name, &ctx->pargs);
} else {
p = ngx_snprintf(request_url.data, len, "http://%V:%d/%V/%V",
&url->url.host, url->port, &ctx->app, &ctx->name);
}
request_url.len = p - request_url.data;
// request headers
ngx_keyval_t headers[] = {
{ ngx_string("Host"), ctx->domain },
{ ngx_string("Referer"), ctx->referer },
{ ngx_string("User-Agent"), ctx->user_agent },
{ ngx_null_string, ngx_null_string }
};
s->stage = NGX_LIVE_CONNECT;
s->connect_time = ngx_current_msec;
hcr = ngx_http_client_get(s->log, &request_url, headers, s);
ngx_http_client_set_read_handler(hcr, ngx_live_relay_httpflv_recv);
cln = ngx_http_client_cleanup_add(hcr, 0);
if (cln == NULL) {
ngx_log_error(NGX_LOG_ERR, s->log, 0, "http client add cleanup failed");
ngx_live_relay_httpflv_error(s, NGX_HTTP_INTERNAL_SERVER_ERROR);
ngx_http_client_finalize_request(hcr, 1);
return NGX_ERROR;
}
cln->handler = ngx_live_relay_httpflv_cleanup;
cln->data = s;
s->request = hcr;
s->live_type = NGX_HTTP_FLV_LIVE;
return NGX_OK;
}
ngx_int_t
ngx_live_relay_create_httpflv(ngx_rtmp_session_t *s, ngx_live_relay_t *relay,
ngx_live_relay_url_t *url)
{
ngx_live_relay_ctx_t *rctx;
// must use ngx_sockaddr_t, because sizeof(struct sockaddr)
// is not long enouph, content will be covered by other var
ngx_sockaddr_t nsa;
struct sockaddr *sa;
socklen_t len;
rctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (rctx == NULL) {
return NGX_ERROR;
}
#define NGX_LIVE_RELAY_CTX(para) \
if (ngx_copy_str(s->pool, &rctx->para, &relay->para) != NGX_OK) { \
goto destroy; \
}
NGX_LIVE_RELAY_CTX(domain);
NGX_LIVE_RELAY_CTX(app);
NGX_LIVE_RELAY_CTX(name);
NGX_LIVE_RELAY_CTX(pargs);
NGX_LIVE_RELAY_CTX(referer);
NGX_LIVE_RELAY_CTX(user_agent);
#undef NGX_LIVE_RELAY_CTX
rctx->tag = relay->tag;
// get address, host in url must be resolv sync
sa = (struct sockaddr *) &nsa;
len = ngx_dynamic_resolver_gethostbyname(&url->url.host, sa);
if (len == 0) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"relay httpflv: gethostbyname failed %V", &url->url.host);
goto destroy;
}
// send http request
if (ngx_live_relay_httpflv_send_request(s, url) != NGX_OK) {
goto destroy;
}
return NGX_OK;
destroy:
ngx_rtmp_finalize_session(s);
return NGX_ERROR;
}
|
2881099/FreeSql.AdminLTE
| 14,307 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/datatables-fixedheader/js/dataTables.fixedHeader.min.js
|
/*!
Copyright 2009-2021 SpryMedia Ltd.
This source file is free software, available under the following license:
MIT license - http://datatables.net/license/mit
This source file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the license files for details.
For details please refer to: http://www.datatables.net
FixedHeader 3.2.1
©2009-2021 SpryMedia Ltd - datatables.net/license
*/
var $jscomp=$jscomp||{};$jscomp.scope={};$jscomp.findInternal=function(b,g,h){b instanceof String&&(b=String(b));for(var l=b.length,k=0;k<l;k++){var v=b[k];if(g.call(h,v,k,b))return{i:k,v:v}}return{i:-1,v:void 0}};$jscomp.ASSUME_ES5=!1;$jscomp.ASSUME_NO_NATIVE_MAP=!1;$jscomp.ASSUME_NO_NATIVE_SET=!1;$jscomp.SIMPLE_FROUND_POLYFILL=!1;$jscomp.ISOLATE_POLYFILLS=!1;
$jscomp.defineProperty=$jscomp.ASSUME_ES5||"function"==typeof Object.defineProperties?Object.defineProperty:function(b,g,h){if(b==Array.prototype||b==Object.prototype)return b;b[g]=h.value;return b};$jscomp.getGlobal=function(b){b=["object"==typeof globalThis&&globalThis,b,"object"==typeof window&&window,"object"==typeof self&&self,"object"==typeof global&&global];for(var g=0;g<b.length;++g){var h=b[g];if(h&&h.Math==Math)return h}throw Error("Cannot find global object");};$jscomp.global=$jscomp.getGlobal(this);
$jscomp.IS_SYMBOL_NATIVE="function"===typeof Symbol&&"symbol"===typeof Symbol("x");$jscomp.TRUST_ES6_POLYFILLS=!$jscomp.ISOLATE_POLYFILLS||$jscomp.IS_SYMBOL_NATIVE;$jscomp.polyfills={};$jscomp.propertyToPolyfillSymbol={};$jscomp.POLYFILL_PREFIX="$jscp$";var $jscomp$lookupPolyfilledValue=function(b,g){var h=$jscomp.propertyToPolyfillSymbol[g];if(null==h)return b[g];h=b[h];return void 0!==h?h:b[g]};
$jscomp.polyfill=function(b,g,h,l){g&&($jscomp.ISOLATE_POLYFILLS?$jscomp.polyfillIsolated(b,g,h,l):$jscomp.polyfillUnisolated(b,g,h,l))};$jscomp.polyfillUnisolated=function(b,g,h,l){h=$jscomp.global;b=b.split(".");for(l=0;l<b.length-1;l++){var k=b[l];if(!(k in h))return;h=h[k]}b=b[b.length-1];l=h[b];g=g(l);g!=l&&null!=g&&$jscomp.defineProperty(h,b,{configurable:!0,writable:!0,value:g})};
$jscomp.polyfillIsolated=function(b,g,h,l){var k=b.split(".");b=1===k.length;l=k[0];l=!b&&l in $jscomp.polyfills?$jscomp.polyfills:$jscomp.global;for(var v=0;v<k.length-1;v++){var t=k[v];if(!(t in l))return;l=l[t]}k=k[k.length-1];h=$jscomp.IS_SYMBOL_NATIVE&&"es6"===h?l[k]:null;g=g(h);null!=g&&(b?$jscomp.defineProperty($jscomp.polyfills,k,{configurable:!0,writable:!0,value:g}):g!==h&&($jscomp.propertyToPolyfillSymbol[k]=$jscomp.IS_SYMBOL_NATIVE?$jscomp.global.Symbol(k):$jscomp.POLYFILL_PREFIX+k,k=
$jscomp.propertyToPolyfillSymbol[k],$jscomp.defineProperty(l,k,{configurable:!0,writable:!0,value:g})))};$jscomp.polyfill("Array.prototype.find",function(b){return b?b:function(g,h){return $jscomp.findInternal(this,g,h).v}},"es6","es3");
(function(b){"function"===typeof define&&define.amd?define(["jquery","datatables.net"],function(g){return b(g,window,document)}):"object"===typeof exports?module.exports=function(g,h){g||(g=window);h&&h.fn.dataTable||(h=require("datatables.net")(g,h).$);return b(h,g,g.document)}:b(jQuery,window,document)})(function(b,g,h,l){var k=b.fn.dataTable,v=0,t=function(a,c){if(!(this instanceof t))throw"FixedHeader must be initialised with the 'new' keyword.";!0===c&&(c={});a=new k.Api(a);this.c=b.extend(!0,
{},t.defaults,c);this.s={dt:a,position:{theadTop:0,tbodyTop:0,tfootTop:0,tfootBottom:0,width:0,left:0,tfootHeight:0,theadHeight:0,windowHeight:b(g).height(),visible:!0},headerMode:null,footerMode:null,autoWidth:a.settings()[0].oFeatures.bAutoWidth,namespace:".dtfc"+v++,scrollLeft:{header:-1,footer:-1},enable:!0};this.dom={floatingHeader:null,thead:b(a.table().header()),tbody:b(a.table().body()),tfoot:b(a.table().footer()),header:{host:null,floating:null,floatingParent:b('<div class="dtfh-floatingparent">'),
placeholder:null},footer:{host:null,floating:null,floatingParent:b('<div class="dtfh-floatingparent">'),placeholder:null}};this.dom.header.host=this.dom.thead.parent();this.dom.footer.host=this.dom.tfoot.parent();a=a.settings()[0];if(a._fixedHeader)throw"FixedHeader already initialised on table "+a.nTable.id;a._fixedHeader=this;this._constructor()};b.extend(t.prototype,{destroy:function(){this.s.dt.off(".dtfc");b(g).off(this.s.namespace);this.c.header&&this._modeChange("in-place","header",!0);this.c.footer&&
this.dom.tfoot.length&&this._modeChange("in-place","footer",!0)},enable:function(a,c){this.s.enable=a;if(c||c===l)this._positions(),this._scroll(!0)},enabled:function(){return this.s.enable},headerOffset:function(a){a!==l&&(this.c.headerOffset=a,this.update());return this.c.headerOffset},footerOffset:function(a){a!==l&&(this.c.footerOffset=a,this.update());return this.c.footerOffset},update:function(a){var c=this.s.dt.table().node();b(c).is(":visible")?this.enable(!0,!1):this.enable(!1,!1);0!==b(c).children("thead").length&&
(this._positions(),this._scroll(a!==l?a:!0))},_constructor:function(){var a=this,c=this.s.dt;b(g).on("scroll"+this.s.namespace,function(){a._scroll()}).on("resize"+this.s.namespace,k.util.throttle(function(){a.s.position.windowHeight=b(g).height();a.update()},50));var d=b(".fh-fixedHeader");!this.c.headerOffset&&d.length&&(this.c.headerOffset=d.outerHeight());d=b(".fh-fixedFooter");!this.c.footerOffset&&d.length&&(this.c.footerOffset=d.outerHeight());c.on("column-reorder.dt.dtfc column-visibility.dt.dtfc column-sizing.dt.dtfc responsive-display.dt.dtfc",
function(f,e){a.update()}).on("draw.dt.dtfc",function(f,e){a.update(e===c.settings()[0]?!1:!0)});c.on("destroy.dtfc",function(){a.destroy()});this._positions();this._scroll()},_clone:function(a,c){var d=this,f=this.s.dt,e=this.dom[a],p="header"===a?this.dom.thead:this.dom.tfoot;if("footer"!==a||!this._scrollEnabled())if(!c&&e.floating)e.floating.removeClass("fixedHeader-floating fixedHeader-locked");else{e.floating&&(null!==e.placeholder&&e.placeholder.remove(),this._unsize(a),e.floating.children().detach(),
e.floating.remove());c=b(f.table().node());var n=b(c.parent()),q=this._scrollEnabled();e.floating=b(f.table().node().cloneNode(!1)).attr("aria-hidden","true").css({"table-layout":"fixed",top:0,left:0}).removeAttr("id").append(p);e.floatingParent.css({width:n.width(),overflow:"hidden",height:"fit-content",position:"fixed",left:q?c.offset().left+n.scrollLeft():0}).css("header"===a?{top:this.c.headerOffset,bottom:""}:{top:"",bottom:this.c.footerOffset}).addClass("footer"===a?"dtfh-floatingparentfoot":
"dtfh-floatingparenthead").append(e.floating).appendTo("body");this._stickyPosition(e.floating,"-");a=function(){var r=n.scrollLeft();d.s.scrollLeft={footer:r,header:r};e.floatingParent.scrollLeft(d.s.scrollLeft.header)};a();n.scroll(a);e.placeholder=p.clone(!1);e.placeholder.find("*[id]").removeAttr("id");e.host.prepend(e.placeholder);this._matchWidths(e.placeholder,e.floating)}},_stickyPosition:function(a,c){if(this._scrollEnabled()){var d=this,f="rtl"===b(d.s.dt.table().node()).css("direction");
a.find("th").each(function(){if("sticky"===b(this).css("position")){var e=b(this).css("right"),p=b(this).css("left");"auto"===e||f?"auto"!==p&&f&&(e=+p.replace(/px/g,"")+("-"===c?-1:1)*d.s.dt.settings()[0].oBrowser.barWidth,b(this).css("left",0<e?e:0)):(e=+e.replace(/px/g,"")+("-"===c?-1:1)*d.s.dt.settings()[0].oBrowser.barWidth,b(this).css("right",0<e?e:0))}})}},_matchWidths:function(a,c){var d=function(p){return b(p,a).map(function(){return 1*b(this).css("width").replace(/[^\d\.]/g,"")}).toArray()},
f=function(p,n){b(p,c).each(function(q){b(this).css({width:n[q],minWidth:n[q]})})},e=d("th");d=d("td");f("th",e);f("td",d)},_unsize:function(a){var c=this.dom[a].floating;c&&("footer"===a||"header"===a&&!this.s.autoWidth)?b("th, td",c).css({width:"",minWidth:""}):c&&"header"===a&&b("th, td",c).css("min-width","")},_horizontal:function(a,c){var d=this.dom[a],f=this.s.scrollLeft;if(d.floating&&f[a]!==c){if(this._scrollEnabled()){var e=b(b(this.s.dt.table().node()).parent()).scrollLeft();d.floating.scrollLeft(e);
d.floatingParent.scrollLeft(e)}f[a]=c}},_modeChange:function(a,c,d){var f=this.dom[c],e=this.s.position,p=this._scrollEnabled();if("footer"!==c||!p){var n=function(B){f.floating.attr("style",function(w,x){return(x||"")+"width: "+B+"px !important;"});p||f.floatingParent.attr("style",function(w,x){return(x||"")+"width: "+B+"px !important;"})},q=this.dom["footer"===c?"tfoot":"thead"],r=b.contains(q[0],h.activeElement)?h.activeElement:null,m=b(b(this.s.dt.table().node()).parent());if("in-place"===a)f.placeholder&&
(f.placeholder.remove(),f.placeholder=null),this._unsize(c),"header"===c?f.host.prepend(q):f.host.append(q),f.floating&&(f.floating.remove(),f.floating=null,this._stickyPosition(f.host,"+")),f.floatingParent&&f.floatingParent.remove(),b(b(f.host.parent()).parent()).scrollLeft(m.scrollLeft());else if("in"===a){this._clone(c,d);q=m.offset();d=b(h).scrollTop();var y=b(g).height();y=d+y;var z=p?q.top:e.tbodyTop;m=p?q.top+m.outerHeight():e.tfootTop;d="footer"===c?z>y?e.tfootHeight:z+e.tfootHeight-y:d+
this.c.headerOffset+e.theadHeight-m;m="header"===c?"top":"bottom";d=this.c[c+"Offset"]-(0<d?d:0);f.floating.addClass("fixedHeader-floating");f.floatingParent.css(m,d).css({left:e.left,height:"header"===c?e.theadHeight:e.tfootHeight,"z-index":2}).append(f.floating);n(e.width);"footer"===c&&f.floating.css("top","")}else"below"===a?(this._clone(c,d),f.floating.addClass("fixedHeader-locked"),f.floatingParent.css({position:"absolute",top:e.tfootTop-e.theadHeight,left:e.left+"px"}),n(e.width)):"above"===
a&&(this._clone(c,d),f.floating.addClass("fixedHeader-locked"),f.floatingParent.css({position:"absolute",top:e.tbodyTop,left:e.left+"px"}),n(e.width));r&&r!==h.activeElement&&setTimeout(function(){r.focus()},10);this.s.scrollLeft.header=-1;this.s.scrollLeft.footer=-1;this.s[c+"Mode"]=a}},_positions:function(){var a=this.s.dt,c=a.table(),d=this.s.position,f=this.dom;c=b(c.node());var e=this._scrollEnabled(),p=b(a.table().header());a=b(a.table().footer());f=f.tbody;var n=c.parent();d.visible=c.is(":visible");
d.width=c.outerWidth();d.left=c.offset().left;d.theadTop=p.offset().top;d.tbodyTop=e?n.offset().top:f.offset().top;d.tbodyHeight=e?n.outerHeight():f.outerHeight();d.theadHeight=p.outerHeight();d.theadBottom=d.theadTop+d.theadHeight;a.length?(d.tfootTop=d.tbodyTop+d.tbodyHeight,d.tfootBottom=d.tfootTop+a.outerHeight(),d.tfootHeight=a.outerHeight()):(d.tfootTop=d.tbodyTop+f.outerHeight(),d.tfootBottom=d.tfootTop,d.tfootHeight=d.tfootTop)},_scroll:function(a){var c=this._scrollEnabled(),d=b(this.s.dt.table().node()).parent(),
f=d.offset(),e=d.outerHeight(),p=b(h).scrollLeft(),n=b(h).scrollTop(),q=b(g).height(),r=q+n,m=this.s.position,y=c?f.top:m.tbodyTop,z=c?f.left:m.left;e=c?f.top+e:m.tfootTop;var B=c?d.outerWidth():m.tbodyWidth;r=n+q;this.c.header&&(this.s.enable?!m.visible||n+this.c.headerOffset+m.theadHeight<=y?q="in-place":n+this.c.headerOffset+m.theadHeight>y&&n+this.c.headerOffset<e?(q="in",d=b(b(this.s.dt.table().node()).parent()),n+this.c.headerOffset+m.theadHeight>e||this.dom.header.floatingParent===l?a=!0:this.dom.header.floatingParent.css({top:this.c.headerOffset,
position:"fixed"}).append(this.dom.header.floating)):q="below":q="in-place",(a||q!==this.s.headerMode)&&this._modeChange(q,"header",a),this._horizontal("header",p));var w={offset:{top:0,left:0},height:0},x={offset:{top:0,left:0},height:0};this.c.footer&&this.dom.tfoot.length&&(this.s.enable?!m.visible||m.tfootBottom+this.c.footerOffset<=r?m="in-place":e+m.tfootHeight+this.c.footerOffset>r&&y+this.c.footerOffset<r?(m="in",a=!0):m="above":m="in-place",(a||m!==this.s.footerMode)&&this._modeChange(m,
"footer",a),this._horizontal("footer",p),a=function(A){return{offset:A.offset(),height:A.outerHeight()}},w=this.dom.header.floating?a(this.dom.header.floating):a(this.dom.thead),x=this.dom.footer.floating?a(this.dom.footer.floating):a(this.dom.tfoot),c&&x.offset.top>n&&(c=n-f.top,r=r+(c>-w.height?c:0)-(w.offset.top+(c<-w.height?w.height:0)+x.height),0>r&&(r=0),d.outerHeight(r),Math.round(d.outerHeight())>=Math.round(r)?b(this.dom.tfoot.parent()).addClass("fixedHeader-floating"):b(this.dom.tfoot.parent()).removeClass("fixedHeader-floating")));
this.dom.header.floating&&this.dom.header.floatingParent.css("left",z-p);this.dom.footer.floating&&this.dom.footer.floatingParent.css("left",z-p);this.s.dt.settings()[0]._fixedColumns!==l&&(d=function(A,C,u){u===l&&(u=b("div.dtfc-"+A+"-"+C+"-blocker"),u=0===u.length?null:u.clone().appendTo("body").css("z-index",1));null!==u&&u.css({top:"top"===C?w.offset.top:x.offset.top,left:"right"===A?z+B-u.width():z});return u},this.dom.header.rightBlocker=d("right","top",this.dom.header.rightBlocker),this.dom.header.leftBlocker=
d("left","top",this.dom.header.leftBlocker),this.dom.footer.rightBlocker=d("right","bottom",this.dom.footer.rightBlocker),this.dom.footer.leftBlocker=d("left","bottom",this.dom.footer.leftBlocker))},_scrollEnabled:function(){var a=this.s.dt.settings()[0].oScroll;return""!==a.sY||""!==a.sX?!0:!1}});t.version="3.2.1";t.defaults={header:!0,footer:!1,headerOffset:0,footerOffset:0};b.fn.dataTable.FixedHeader=t;b.fn.DataTable.FixedHeader=t;b(h).on("init.dt.dtfh",function(a,c,d){"dt"===a.namespace&&(a=c.oInit.fixedHeader,
d=k.defaults.fixedHeader,!a&&!d||c._fixedHeader||(d=b.extend({},d,a),!1!==a&&new t(c,d)))});k.Api.register("fixedHeader()",function(){});k.Api.register("fixedHeader.adjust()",function(){return this.iterator("table",function(a){(a=a._fixedHeader)&&a.update()})});k.Api.register("fixedHeader.enable()",function(a){return this.iterator("table",function(c){c=c._fixedHeader;a=a!==l?a:!0;c&&a!==c.enabled()&&c.enable(a)})});k.Api.register("fixedHeader.enabled()",function(){if(this.context.length){var a=this.context[0]._fixedHeader;
if(a)return a.enabled()}return!1});k.Api.register("fixedHeader.disable()",function(){return this.iterator("table",function(a){(a=a._fixedHeader)&&a.enabled()&&a.enable(!1)})});b.each(["header","footer"],function(a,c){k.Api.register("fixedHeader."+c+"Offset()",function(d){var f=this.context;return d===l?f.length&&f[0]._fixedHeader?f[0]._fixedHeader[c+"Offset"]():l:this.iterator("table",function(e){if(e=e._fixedHeader)e[c+"Offset"](d)})})});return t});
|
281677160/openwrt-package
| 31,057 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_live_module.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp_live_module.h"
#include "ngx_rtmp_cmd_module.h"
#include "ngx_rtmp_codec_module.h"
static ngx_rtmp_publish_pt next_publish;
static ngx_rtmp_play_pt next_play;
static ngx_rtmp_close_stream_pt next_close_stream;
static ngx_rtmp_pause_pt next_pause;
static ngx_rtmp_stream_begin_pt next_stream_begin;
static ngx_rtmp_stream_eof_pt next_stream_eof;
static ngx_int_t ngx_rtmp_live_postconfiguration(ngx_conf_t *cf);
static void * ngx_rtmp_live_create_app_conf(ngx_conf_t *cf);
static char * ngx_rtmp_live_merge_app_conf(ngx_conf_t *cf,
void *parent, void *child);
static char *ngx_rtmp_live_set_msec_slot(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static void ngx_rtmp_live_start(ngx_rtmp_session_t *s);
static void ngx_rtmp_live_stop(ngx_rtmp_session_t *s);
static ngx_command_t ngx_rtmp_live_commands[] = {
{ ngx_string("live"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, live),
NULL },
{ ngx_string("buffer"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, buflen),
NULL },
{ ngx_string("sync"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_rtmp_live_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, sync),
NULL },
{ ngx_string("interleave"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, interleave),
NULL },
{ ngx_string("wait_key"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, wait_key),
NULL },
{ ngx_string("wait_video"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, wait_video),
NULL },
{ ngx_string("publish_notify"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, publish_notify),
NULL },
{ ngx_string("play_restart"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, play_restart),
NULL },
{ ngx_string("idle_streams"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, idle_streams),
NULL },
{ ngx_string("drop_idle_publisher"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_rtmp_live_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_live_app_conf_t, idle_timeout),
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_rtmp_live_module_ctx = {
NULL, /* preconfiguration */
ngx_rtmp_live_postconfiguration, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_rtmp_live_create_app_conf, /* create app configuration */
ngx_rtmp_live_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_rtmp_live_module = {
NGX_MODULE_V1,
&ngx_rtmp_live_module_ctx, /* module context */
ngx_rtmp_live_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_rtmp_live_create_app_conf(ngx_conf_t *cf)
{
ngx_rtmp_live_app_conf_t *lacf;
lacf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_live_app_conf_t));
if (lacf == NULL) {
return NULL;
}
lacf->live = NGX_CONF_UNSET;
lacf->buflen = NGX_CONF_UNSET_MSEC;
lacf->sync = NGX_CONF_UNSET_MSEC;
lacf->idle_timeout = NGX_CONF_UNSET_MSEC;
lacf->interleave = NGX_CONF_UNSET;
lacf->wait_key = NGX_CONF_UNSET;
lacf->wait_video = NGX_CONF_UNSET;
lacf->publish_notify = NGX_CONF_UNSET;
lacf->play_restart = NGX_CONF_UNSET;
lacf->idle_streams = NGX_CONF_UNSET;
return lacf;
}
static char *
ngx_rtmp_live_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_live_app_conf_t *prev = parent;
ngx_rtmp_live_app_conf_t *conf = child;
ngx_conf_merge_value(conf->live, prev->live, 0);
ngx_conf_merge_msec_value(conf->buflen, prev->buflen, 0);
ngx_conf_merge_msec_value(conf->sync, prev->sync, 300);
ngx_conf_merge_msec_value(conf->idle_timeout, prev->idle_timeout, 0);
ngx_conf_merge_value(conf->interleave, prev->interleave, 0);
ngx_conf_merge_value(conf->wait_key, prev->wait_key, 1);
ngx_conf_merge_value(conf->wait_video, prev->wait_video, 0);
ngx_conf_merge_value(conf->publish_notify, prev->publish_notify, 0);
ngx_conf_merge_value(conf->play_restart, prev->play_restart, 0);
ngx_conf_merge_value(conf->idle_streams, prev->idle_streams, 1);
return NGX_CONF_OK;
}
static char *
ngx_rtmp_live_set_msec_slot(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *p = conf;
ngx_str_t *value;
ngx_msec_t *msp;
msp = (ngx_msec_t *) (p + cmd->offset);
value = cf->args->elts;
if (value[1].len == sizeof("off") - 1 &&
ngx_strncasecmp(value[1].data, (u_char *) "off", value[1].len) == 0)
{
*msp = 0;
return NGX_CONF_OK;
}
return ngx_conf_set_msec_slot(cf, cmd, conf);
}
static void
ngx_rtmp_live_idle(ngx_event_t *pev)
{
ngx_connection_t *c;
ngx_rtmp_session_t *s;
c = pev->data;
s = c->data;
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"live: drop idle publisher");
s->finalize_reason = NGX_LIVE_DROP_IDLE;
ngx_rtmp_finalize_session(s);
}
static void
ngx_rtmp_live_set_status(ngx_rtmp_session_t *s, ngx_rtmp_frame_t *control,
ngx_rtmp_frame_t **status, size_t nstatus,
unsigned active)
{
ngx_rtmp_live_app_conf_t *lacf;
ngx_rtmp_live_ctx_t *ctx, *pctx;
ngx_rtmp_frame_t **frame;
ngx_event_t *e;
size_t n;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: set active=%ui", active);
if (ctx->active == active) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: unchanged active=%ui", active);
return;
}
ctx->active = active;
if (ctx->publishing) {
/* publisher */
if (lacf->idle_timeout) {
e = &ctx->idle_evt;
if (active && !ctx->idle_evt.timer_set) {
e->data = s->connection;
e->log = s->log;
e->handler = ngx_rtmp_live_idle;
ngx_add_timer(e, lacf->idle_timeout);
} else if (!active && ctx->idle_evt.timer_set) {
ngx_del_timer(e);
}
}
ctx->stream->active = active;
for (pctx = ctx->stream->ctx; pctx; pctx = pctx->next) {
if (pctx->publishing == 0) {
ngx_rtmp_live_set_status(pctx->session, control, status,
nstatus, active);
}
}
return;
}
/* subscriber */
if (control && ngx_rtmp_send_message(s, control, 0) != NGX_OK) {
ngx_rtmp_finalize_session(s);
return;
}
if (!ctx->silent) {
frame = status;
for (n = 0; n < nstatus; ++n, ++frame) {
if (*frame && ngx_rtmp_send_message(s, *frame, 0) != NGX_OK) {
ngx_rtmp_finalize_session(s);
return;
}
}
}
ctx->cs[0].active = 0;
ctx->cs[0].dropped = 0;
ctx->cs[1].active = 0;
ctx->cs[1].dropped = 0;
}
static void
ngx_rtmp_live_start(ngx_rtmp_session_t *s)
{
ngx_rtmp_live_app_conf_t *lacf;
ngx_rtmp_frame_t *control;
ngx_rtmp_frame_t *status[3];
size_t n, nstatus;
if (s->live_type == NGX_HLS_LIVE) {
return;
}
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
control = ngx_rtmp_create_stream_begin(s, NGX_RTMP_MSID);
nstatus = 0;
if (lacf->play_restart) {
status[nstatus++] = ngx_rtmp_create_status(s, "NetStream.Play.Start",
"status", "Start live");
status[nstatus++] = ngx_rtmp_create_sample_access(s);
}
if (lacf->publish_notify) {
status[nstatus++] = ngx_rtmp_create_status(s,
"NetStream.Play.PublishNotify",
"status", "Start publishing");
}
ngx_rtmp_live_set_status(s, control, status, nstatus, 1);
if (control) {
ngx_rtmp_shared_free_frame(control);
}
for (n = 0; n < nstatus; ++n) {
ngx_rtmp_shared_free_frame(status[n]);
}
}
static void
ngx_rtmp_live_stop(ngx_rtmp_session_t *s)
{
ngx_rtmp_live_app_conf_t *lacf;
ngx_rtmp_frame_t *control;
ngx_rtmp_frame_t *status[3];
size_t n, nstatus;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
control = ngx_rtmp_create_stream_eof(s, NGX_RTMP_MSID);
nstatus = 0;
if (lacf->play_restart) {
status[nstatus++] = ngx_rtmp_create_status(s, "NetStream.Play.Stop",
"status", "Stop live");
}
if (lacf->publish_notify) {
status[nstatus++] = ngx_rtmp_create_status(s,
"NetStream.Play.UnpublishNotify",
"status", "Stop publishing");
}
ngx_rtmp_live_set_status(s, control, status, nstatus, 0);
if (control) {
ngx_rtmp_shared_free_frame(control);
}
for (n = 0; n < nstatus; ++n) {
ngx_rtmp_shared_free_frame(status[n]);
}
}
static ngx_int_t
ngx_rtmp_live_stream_begin(ngx_rtmp_session_t *s, ngx_rtmp_stream_begin_t *v)
{
ngx_rtmp_live_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL || ctx->stream == NULL || !ctx->publishing) {
goto next;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: stream_begin");
ngx_rtmp_live_start(s);
next:
return next_stream_begin(s, v);
}
static ngx_int_t
ngx_rtmp_live_stream_eof(ngx_rtmp_session_t *s, ngx_rtmp_stream_eof_t *v)
{
ngx_rtmp_live_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL || ctx->stream == NULL || !ctx->publishing) {
goto next;
}
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: stream_eof");
ngx_rtmp_live_stop(s);
next:
return next_stream_eof(s, v);
}
static void
ngx_rtmp_live_join(ngx_rtmp_session_t *s, u_char *name, unsigned publisher)
{
ngx_rtmp_live_ctx_t *ctx;
ngx_live_stream_t *st;
ngx_rtmp_live_app_conf_t *lacf;
ngx_str_t pubpri;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
if (lacf == NULL) {
return;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx && ctx->stream) {
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: already joined");
return;
}
if (ctx == NULL) {
ctx = ngx_palloc(s->pool, sizeof(ngx_rtmp_live_ctx_t));
ngx_rtmp_set_ctx(s, ctx, ngx_rtmp_live_module);
}
ngx_memzero(ctx, sizeof(*ctx));
ctx->session = s;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: join '%s'", name);
st = s->live_stream;
if (!(publisher || st->publish_ctx || lacf->idle_streams)) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"live: stream not found");
s->status = 404;
ngx_rtmp_send_status(s, "NetStream.Play.StreamNotFound", "error",
"No such stream");
ngx_rtmp_finalize_session(s);
return;
}
if (publisher) {
// set publish priority
if (s->relay) { // relay pull
ctx->pubpri = -1;
} else {
if (ngx_rtmp_arg(s, (u_char *) "pubpri", 6, &pubpri) == NGX_OK) {
ctx->pubpri = ngx_atoi(pubpri.data, pubpri.len);
if (ctx->pubpri == NGX_ERROR) { // invalid publish priority
ctx->pubpri = 0;
}
}
}
// duplicate publish priority
if (ngx_map_find(&st->pubctx, (intptr_t) ctx->pubpri)) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"live: already publishing");
ngx_rtmp_send_status(s, "NetStream.Publish.BadName", "error",
"Already publishing");
return;
}
ctx->node.raw_key = (intptr_t) ctx->pubpri;
ngx_map_insert(&st->pubctx, &ctx->node, 0);
st->publishing = 1;
}
ctx->stream = st;
ctx->publishing = publisher;
ctx->next = st->ctx;
st->ctx = ctx;
if (lacf->buflen) {
s->out_buffer = 1;
}
ctx->cs[0].csid = NGX_RTMP_CSID_VIDEO;
ctx->cs[1].csid = NGX_RTMP_CSID_AUDIO;
if (!ctx->publishing && ctx->stream->active) {
ngx_rtmp_live_start(s);
}
}
static ngx_int_t
ngx_rtmp_live_close_stream(ngx_rtmp_session_t *s, ngx_rtmp_close_stream_t *v)
{
ngx_rtmp_session_t *ss;
ngx_rtmp_live_ctx_t *ctx, **cctx, *pctx;
ngx_rtmp_live_app_conf_t *lacf;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
if (lacf == NULL) {
goto next;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL) {
goto next;
}
if (ctx->stream == NULL) {
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: not joined");
goto next;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: leave '%s'", ctx->stream->name);
if (s->publishing) {
ngx_map_delete(&s->live_stream->pubctx, (intptr_t) ctx->pubpri);
}
if (ctx->stream->publishing && ctx->publishing) {
ctx->stream->publishing = 0;
}
for (cctx = &ctx->stream->ctx; *cctx; cctx = &(*cctx)->next) {
if (*cctx == ctx) {
*cctx = ctx->next;
break;
}
}
if (ctx->publishing || ctx->stream->active) {
ngx_rtmp_live_stop(s);
}
if (ctx->publishing) {
ngx_rtmp_send_status(s, "NetStream.Unpublish.Success",
"status", "Stop publishing");
if (!lacf->idle_streams) {
for (pctx = ctx->stream->ctx; pctx; pctx = pctx->next) {
if (pctx->publishing == 0) {
ss = pctx->session;
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: no publisher");
ngx_rtmp_finalize_session(ss);
}
}
}
}
if (ctx->stream->ctx) {
ctx->stream = NULL;
goto next;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: delete empty stream '%s'",
ctx->stream->name);
ctx->stream = NULL;
if (!ctx->silent && !ctx->publishing && !lacf->play_restart) {
ngx_rtmp_send_status(s, "NetStream.Play.Stop", "status", "Stop live");
}
next:
return next_close_stream(s, v);
}
static ngx_int_t
ngx_rtmp_live_pause(ngx_rtmp_session_t *s, ngx_rtmp_pause_t *v)
{
ngx_rtmp_live_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL || ctx->stream == NULL) {
goto next;
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: pause=%i timestamp=%f",
(ngx_int_t) v->pause, v->position);
if (v->pause) {
if (ngx_rtmp_send_status(s, "NetStream.Pause.Notify", "status",
"Paused live")
!= NGX_OK)
{
return NGX_ERROR;
}
ctx->paused = 1;
ngx_rtmp_live_stop(s);
} else {
if (ngx_rtmp_send_status(s, "NetStream.Unpause.Notify", "status",
"Unpaused live")
!= NGX_OK)
{
return NGX_ERROR;
}
ctx->paused = 0;
ngx_rtmp_live_start(s);
}
next:
return next_pause(s, v);
}
static ngx_int_t
ngx_rtmp_live_av(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_rtmp_live_ctx_t *ctx, *pctx;
ngx_rtmp_codec_ctx_t *codec_ctx;
ngx_rtmp_frame_t *header, *coheader, *meta, *avframe, *dummy;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_rtmp_live_app_conf_t *lacf;
ngx_rtmp_session_t *ss;
ngx_rtmp_header_t ch, lh, clh;
ngx_int_t rc, mandatory, dummy_audio;
ngx_uint_t prio;
ngx_uint_t peers;
ngx_uint_t meta_version;
ngx_uint_t csidx;
uint32_t delta;
ngx_rtmp_live_chunk_stream_t *cs;
u_char frametype;
#define MSG_TYPE (h->type == NGX_RTMP_MSG_VIDEO ? "video" : "audio")
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
if (lacf == NULL) {
return NGX_ERROR;
}
if (!lacf->live || in == NULL || in->buf == NULL || s->pause == 1) {
return NGX_OK;
}
codec_ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_codec_module);
if (s->pause == 2) {
if ((codec_ctx && codec_ctx->video_codec_id == 0) ||
(h->type == NGX_RTMP_MSG_VIDEO &&
ngx_rtmp_get_video_frame_type(in) == NGX_RTMP_VIDEO_KEY_FRAME))
{
s->pause = 0;
} else {
return NGX_OK;
}
}
if (h->type == NGX_RTMP_MSG_VIDEO) {
frametype = in->buf->pos[0] & 0xf0;
if (frametype != 0x10 && frametype != 0x20) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"codec: receive unkwnon frametype %02xD", frametype);
return NGX_OK;
}
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL || ctx->stream == NULL) {
return NGX_OK;
}
if (ctx->publishing == 0) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: %s from non-publisher", MSG_TYPE);
return NGX_OK;
}
if (!ctx->stream->active) {
ngx_rtmp_live_start(s);
}
if (ctx->idle_evt.timer_set) {
ngx_add_timer(&ctx->idle_evt, lacf->idle_timeout);
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: %s packet timestamp=%uD",
MSG_TYPE, h->timestamp);
s->current_time = h->timestamp;
peers = 0;
header = NULL;
coheader = NULL;
meta = NULL;
dummy = NULL;
meta_version = 0;
mandatory = 0;
prio = (h->type == NGX_RTMP_MSG_VIDEO ?
ngx_rtmp_get_video_frame_type(in) : 0);
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
csidx = !(lacf->interleave || h->type == NGX_RTMP_MSG_VIDEO);
cs = &ctx->cs[csidx];
ngx_memzero(&ch, sizeof(ch));
ch.timestamp = h->timestamp;
ch.msid = NGX_RTMP_MSID;
ch.csid = cs->csid;
ch.type = h->type;
ch.mlen = h->mlen;
lh = ch;
if (cs->active) {
lh.timestamp = cs->timestamp;
}
clh = lh;
clh.type = (h->type == NGX_RTMP_MSG_AUDIO ? NGX_RTMP_MSG_VIDEO :
NGX_RTMP_MSG_AUDIO);
cs->active = 1;
cs->timestamp = ch.timestamp;
delta = ch.timestamp - lh.timestamp;
/*
if (delta >> 31) {
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: clipping non-monotonical timestamp %uD->%uD",
lh.timestamp, ch.timestamp);
delta = 0;
ch.timestamp = lh.timestamp;
}
*/
avframe = ngx_rtmp_shared_alloc_frame(cscf->chunk_size, in, 0);
avframe->hdr = ch;
if (codec_ctx) {
if (h->type == NGX_RTMP_MSG_AUDIO) {
header = codec_ctx->aac_header;
if (lacf->interleave) {
coheader = codec_ctx->avc_header;
}
if (codec_ctx->audio_codec_id == NGX_RTMP_AUDIO_AAC &&
ngx_rtmp_is_codec_header(in))
{
prio = 0;
mandatory = 1;
}
} else {
header = codec_ctx->avc_header;
if (lacf->interleave) {
coheader = codec_ctx->aac_header;
}
if (codec_ctx->video_codec_id == NGX_RTMP_VIDEO_H264 &&
ngx_rtmp_is_codec_header(in))
{
prio = 0;
mandatory = 1;
}
}
if (codec_ctx->meta) {
meta = codec_ctx->meta;
meta_version = codec_ctx->meta_version;
}
}
if (ngx_rtmp_gop_cache(s, avframe) == NGX_ERROR) {
return NGX_ERROR;
}
/* broadcast to all subscribers */
for (pctx = ctx->stream->ctx; pctx; pctx = pctx->next) {
// not the highest priority
if (ngx_map_rbegin(&ctx->stream->pubctx) != &ctx->node) {
break;
}
// do not send to publish session
if (pctx->publishing || pctx->paused || s->pause) {
continue;
}
ss = pctx->session;
cs = &pctx->cs[csidx];
if (ss->live_type == NGX_MPEGTS_LIVE || ss->live_type == NGX_HLS_LIVE) {
continue;
}
/* send gop cache is set */
switch (ngx_rtmp_gop_send(s, ss)) {
case NGX_DECLINED:
break;
case NGX_ERROR:
ngx_rtmp_finalize_session(ss);
continue;
default:
peers++;
continue;
}
/* send metadata */
if (meta && meta_version != pctx->meta_version) {
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: meta");
if (ngx_rtmp_send_message(ss, meta, 0) == NGX_OK) {
pctx->meta_version = meta_version;
}
}
/* sync stream */
if (cs->active && (lacf->sync && cs->dropped > lacf->sync)) {
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: sync %s dropped=%uD", MSG_TYPE, cs->dropped);
cs->active = 0;
cs->dropped = 0;
}
/* absolute packet */
if (!cs->active) {
if (mandatory) {
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: skipping header");
continue;
}
if (lacf->wait_video && h->type == NGX_RTMP_MSG_AUDIO &&
!pctx->cs[0].active)
{
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: waiting for video");
continue;
}
if (lacf->wait_key && prio != NGX_RTMP_VIDEO_KEY_FRAME &&
(lacf->interleave || h->type == NGX_RTMP_MSG_VIDEO))
{
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: skip non-key");
continue;
}
dummy_audio = 0;
if (lacf->wait_video && h->type == NGX_RTMP_MSG_VIDEO &&
!pctx->cs[1].active)
{
dummy_audio = 1;
if (dummy == NULL) {
dummy = ngx_rtmp_shared_alloc_frame(cscf->chunk_size,
NULL, 1);
dummy->hdr = clh;
}
}
if (header || coheader) {
/* send absolute codec header */
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: abs %s header timestamp=%uD",
MSG_TYPE, lh.timestamp);
if (header) {
header->hdr = lh;
rc = ngx_rtmp_send_message(ss, header, 0);
if (rc != NGX_OK) {
continue;
}
}
if (coheader) {
coheader->hdr = clh;
rc = ngx_rtmp_send_message(ss, coheader, 0);
if (rc != NGX_OK) {
continue;
}
} else if (dummy_audio) {
ngx_rtmp_send_message(ss, dummy, 0);
}
cs->timestamp = lh.timestamp;
cs->active = 1;
ss->current_time = cs->timestamp;
}
}
/* send av packet */
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: rel %s packet delta=%uD",
MSG_TYPE, delta);
if (ngx_rtmp_send_message(ss, avframe, prio) != NGX_OK) {
++pctx->ndropped;
cs->dropped += delta;
if (mandatory) {
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, ss->log, 0,
"live: mandatory packet failed");
ngx_rtmp_finalize_session(ss);
}
continue;
}
cs->timestamp += delta;
++peers;
ss->current_time = cs->timestamp;
}
if (avframe) {
ngx_rtmp_shared_free_frame(avframe);
}
if (dummy) {
ngx_rtmp_shared_free_frame(dummy);
}
ngx_rtmp_update_bandwidth(&ctx->stream->bw_in, h->mlen);
ngx_rtmp_update_bandwidth(&ctx->stream->bw_out, h->mlen * peers);
ngx_rtmp_update_bandwidth(h->type == NGX_RTMP_MSG_AUDIO ?
&ctx->stream->bw_in_audio :
&ctx->stream->bw_in_video,
h->mlen);
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_live_publish(ngx_rtmp_session_t *s, ngx_rtmp_publish_t *v)
{
ngx_rtmp_live_app_conf_t *lacf;
ngx_rtmp_live_ctx_t *ctx;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
if (lacf == NULL || !lacf->live) {
goto next;
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: publish: name='%s' type='%s'",
v->name, v->type);
/* join stream as publisher */
ngx_rtmp_live_join(s, v->name, 1);
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL || !ctx->publishing) {
goto next;
}
ctx->silent = v->silent;
if (!ctx->silent) {
ngx_rtmp_send_status(s, "NetStream.Publish.Start",
"status", "Start publishing");
}
next:
return next_publish(s, v);
}
static ngx_int_t
ngx_rtmp_live_play(ngx_rtmp_session_t *s, ngx_rtmp_play_t *v)
{
ngx_rtmp_live_app_conf_t *lacf;
ngx_rtmp_live_ctx_t *ctx;
ngx_rtmp_session_t *ps;
lacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_live_module);
if (lacf == NULL || !lacf->live ||
s->live_type == NGX_HLS_LIVE || s->live_type == NGX_MPEGTS_LIVE)
{
goto next;
}
ngx_log_debug4(NGX_LOG_DEBUG_RTMP, s->log, 0,
"live: play: name='%s' start=%uD duration=%uD reset=%d",
v->name, (uint32_t) v->start,
(uint32_t) v->duration, (uint32_t) v->reset);
/* join stream as subscriber */
ngx_rtmp_live_join(s, v->name, 0);
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_live_module);
if (ctx == NULL) {
goto next;
}
ctx->silent = v->silent;
if (!ctx->silent && !lacf->play_restart) {
ngx_rtmp_send_status(s, "NetStream.Play.Start",
"status", "Start live");
ngx_rtmp_send_sample_access(s);
}
if (s->live_stream->publish_ctx && s->live_stream->publish_ctx->session) {
ps = s->live_stream->publish_ctx->session;
ngx_rtmp_gop_send(ps, s);
}
next:
return next_play(s, v);
}
static ngx_int_t
ngx_rtmp_live_postconfiguration(ngx_conf_t *cf)
{
ngx_rtmp_core_main_conf_t *cmcf;
ngx_rtmp_handler_pt *h;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
/* register raw event handlers */
h = ngx_array_push(&cmcf->events[NGX_RTMP_MSG_AUDIO]);
*h = ngx_rtmp_live_av;
h = ngx_array_push(&cmcf->events[NGX_RTMP_MSG_VIDEO]);
*h = ngx_rtmp_live_av;
/* chain handlers */
next_publish = ngx_rtmp_publish;
ngx_rtmp_publish = ngx_rtmp_live_publish;
next_play = ngx_rtmp_play;
ngx_rtmp_play = ngx_rtmp_live_play;
next_close_stream = ngx_rtmp_close_stream;
ngx_rtmp_close_stream = ngx_rtmp_live_close_stream;
next_pause = ngx_rtmp_pause;
ngx_rtmp_pause = ngx_rtmp_live_pause;
next_stream_begin = ngx_rtmp_stream_begin;
ngx_rtmp_stream_begin = ngx_rtmp_live_stream_begin;
next_stream_eof = ngx_rtmp_stream_eof;
ngx_rtmp_stream_eof = ngx_rtmp_live_stream_eof;
return NGX_OK;
}
|
294coder/Efficient-MIF
| 2,768 |
utils/FS_index/HQNR.py
|
# -*- coding: utf-8 -*-
"""
Copyright (c) 2020 Vivone Gemine.
All rights reserved. This work should only be used for nonprofit purposes.
@author: Vivone Gemine (website: https://sites.google.com/site/vivonegemine/home )
"""
"""
Description:
Hybrid Quality with No Reference (HQNR) index.
Interface:
[HQNR_index,D_lambda,D_S] = HQNR(ps_ms,ms,msexp,pan,S,sensor,ratio)
Inputs:
ps_ms: Pansharpened image;
ms: Original MS image;
msexp: MS image resampled to panchromatic scale;
pan: Panchromatic image;
S: Block size;
sensor: String for type of sensor (e.g. 'WV2','IKONOS');
ratio: Scale ratio between MS and PAN. Pre-condition: Integer value.
Outputs:
HQNR_index: HQNR index;
D_lambda: Spectral distortion index;
D_S: Spatial distortion index.
Notes:
Results very close to the MATLAB toolbox's ones. In particular, the results of D_S are more accurate than the MATLAB toolbox's ones
because the Q-index is applied in a sliding window way. Instead, for computational reasons, the MATLAB toolbox uses a distinct block implementation
of the Q-index.
References:
G. Vivone, M. Dalla Mura, A. Garzelli, and F. Pacifici, "A Benchmarking Protocol for Pansharpening: Dataset, Pre-processing, and Quality Assessment", IEEE Journal of Selected Topics in Applied Earth Observations and Remote Sensing, vol. 14, pp. 6102-6118, 2021.
G. Vivone, M. Dalla Mura, A. Garzelli, R. Restaino, G. Scarpa, M. O. Ulfarsson, L. Alparone, and J. Chanussot, "A New Benchmark Based on Recent Advances in Multispectral Pansharpening: Revisiting Pansharpening With Classical and Emerging Pansharpening Methods", IEEE Geoscience and Remote Sensing Magazine, vol. 9, no. 1, pp. 53 - 81, March 2021.
"""
import numpy as np
from .D_lambda_K import D_lambda_K
# from .D_s import D_s
from .my_D_s import D_s
def HQNR(ps_ms, ms, msexp, pan, S, sensor, ratio):
"""HQNR index and maps
Args:
ps_ms (ndarray): fusion
ms (ndarray): MS_LR
msexp (ndarray): MS
pan (ndarray): pan
S (int): block size
sensor (str): sensor type
ratio (int): fusion ratio
Returns:
[float, float, float, ndarray, ndarray, ndarray]: indices and maps
"""
D_lambda, D_l_map = D_lambda_K(ps_ms, msexp, ratio, sensor, S) # .copy()
D_S, D_S_map = D_s(ps_ms, msexp, ms, pan, ratio, S, 1)
HQNR_index = (1 - D_lambda) * (1 - D_S)
HQNR_map = (1 - D_l_map) * (1 - D_S_map.mean(-1))
return HQNR_index, D_lambda, D_S, HQNR_map
|
294coder/Efficient-MIF
| 2,943 |
utils/sailency/__init__.py
|
from .utils import (
vis_saliency,
vis_saliency_kde,
click_select_position,
grad_abs_norm,
grad_norm,
prepare_images,
make_pil_grid,
blend_input,
)
from .utils import cv2_to_pil, pil_to_cv2, gini, PIL2Tensor, Tensor2PIL
from .attributes import attr_grad
from .BackProp import I_gradient, attribution_objective, Path_gradient
from .BackProp import saliency_map_PG as saliency_map
from .BackProp import GaussianBlurPath, LinearPath
from .utils import grad_norm, IG_baseline, interpolation, isotropic_gaussian_kernel
import numpy as np
# from beartype import beartype
import torch
import torch.nn as nn
import cv2
# @beartype
def LAM(
model,
hr: np.ndarray,
lr_list: list[np.ndarray],
h: int,
w: int,
sigma: float = 1.2,
fold: int = 50,
l: int = 9,
alpha: float = 0.5,
window_size: int = 16,
*,
on_cuda: bool = True
):
if isinstance(model, nn.Module):
assert (
next(model.parameters()).is_cuda == on_cuda
), "parameters should {} be on cuda".format("on" if on_cuda else "not")
else:
assert callable(model), 'if @model is not an nn.Module, it should be a eval function of the model(a method)'
tensor_hr = torch.tensor(hr)
lr = lr_list[1][0] #ms
tensor_lr = lr # torch.tensor(lr.numpy().cpu())
img_hr = Tensor2PIL(tensor_hr[[0, 2, 4]])
img_lr = Tensor2PIL(tensor_lr[[0, 2, 4]])
draw_img = pil_to_cv2(img_hr)
cv2.rectangle(draw_img, (w, h), (w + window_size, h + window_size), (0, 0, 255), 2)
position_pil = cv2_to_pil(draw_img)
attr_objective = attribution_objective(attr_grad, h, w, window=window_size)
gaus_blur_path_func = GaussianBlurPath(sigma, fold, l) #LinearPath(fold)#
interpolated_grad_numpy, result_numpy, interpolated_numpy = Path_gradient(
lr_list, model, attr_objective, gaus_blur_path_func, cuda=on_cuda
)
grad_numpy, result = saliency_map(interpolated_grad_numpy, result_numpy)
abs_normed_grad_numpy = grad_abs_norm(grad_numpy)
print("gradient estimation done")
saliency_image_abs = vis_saliency(abs_normed_grad_numpy, zoomin=1)
print('absolute saliency map done')
# saliency_image_kde = vis_saliency_kde(abs_normed_grad_numpy)
# print('kde saliency map done')
blend_abs_and_input = cv2_to_pil(
pil_to_cv2(saliency_image_abs) * (1.0 - alpha)
+ pil_to_cv2(img_lr.resize(img_hr.size)) * alpha
)
# blend_kde_and_input = cv2_to_pil(
# pil_to_cv2(saliency_image_kde) * (1.0 - alpha)
# + pil_to_cv2(img_lr.resize(img_hr.size)) * alpha
# )
pil = make_pil_grid(
[
position_pil,
saliency_image_abs,
blend_abs_and_input,
# blend_kde_and_input,
Tensor2PIL(torch.clamp(torch.from_numpy(result[:,[0,2,4]]), min=0.0, max=1.0)),
]
)
pil.save('result.png')
return pil
|
281677160/openwrt-package
| 11,451 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_live_relay_inner.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_live_relay.h"
#include "ngx_stream_zone_module.h"
#include "ngx_multiport.h"
static ngx_live_push_pt next_push;
static ngx_live_pull_pt next_pull;
static ngx_live_push_close_pt next_push_close;
static ngx_live_pull_close_pt next_pull_close;
static void *ngx_live_relay_inner_create_app_conf(ngx_conf_t *cf);
static char *ngx_live_relay_inner_merge_app_conf(ngx_conf_t *cf,
void *parent, void *child);
static ngx_int_t ngx_live_relay_inner_postconfiguration(ngx_conf_t *cf);
typedef struct {
ngx_flag_t inner_pull;
ngx_str_t inner_pull_port;
} ngx_live_relay_inner_app_conf_t;
static ngx_command_t ngx_live_relay_inner_commands[] = {
{ ngx_string("rtmp_auto_pull"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_live_relay_inner_app_conf_t, inner_pull),
NULL },
{ ngx_string("rtmp_auto_pull_port"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_live_relay_inner_app_conf_t, inner_pull_port),
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_live_relay_inner_module_ctx = {
NULL, /* preconfiguration */
ngx_live_relay_inner_postconfiguration, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_live_relay_inner_create_app_conf, /* create app configuration */
ngx_live_relay_inner_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_live_relay_inner_module = {
NGX_MODULE_V1,
&ngx_live_relay_inner_module_ctx, /* module context */
ngx_live_relay_inner_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_live_relay_inner_create_app_conf(ngx_conf_t *cf)
{
ngx_live_relay_inner_app_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_live_relay_inner_app_conf_t));
if (conf == NULL) {
return NULL;
}
conf->inner_pull = NGX_CONF_UNSET;
return conf;
}
static char *
ngx_live_relay_inner_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_live_relay_inner_app_conf_t *prev = parent;
ngx_live_relay_inner_app_conf_t *conf = child;
ngx_conf_merge_value(conf->inner_pull, prev->inner_pull, 1);
ngx_conf_merge_str_value(conf->inner_pull_port, prev->inner_pull_port,
"unix:/tmp/inner.sock");
return NGX_CONF_OK;
}
static ngx_int_t
ngx_live_relay_inner_create_relay(ngx_rtmp_session_t *rs,
ngx_live_relay_t *relay, ngx_int_t pslot)
{
ngx_live_relay_inner_app_conf_t *riacf;
ngx_live_relay_url_t *url;
ngx_str_t port;
riacf = ngx_rtmp_get_module_app_conf(rs, ngx_live_relay_inner_module);
ngx_memzero(relay, sizeof(ngx_live_relay_t));
if (ngx_array_init(&relay->urls, rs->pool, 1, sizeof(ngx_live_relay_url_t))
!= NGX_OK)
{
ngx_log_error(NGX_LOG_ERR, rs->log, 0,
"inner relay, relay init error: %V", &riacf->inner_pull_port);
return NGX_ERROR;
}
url = ngx_array_push(&relay->urls);
if (url == NULL) {
ngx_log_error(NGX_LOG_ERR, rs->log, 0,
"inner relay, get url failed: %V", &riacf->inner_pull_port);
return NGX_ERROR;
}
relay->tag = &ngx_live_relay_inner_module;
ngx_memzero(url, sizeof(ngx_live_relay_url_t));
ngx_memzero(&port, sizeof(ngx_str_t));
if (ngx_multiport_get_port(rs->pool, &port,
&riacf->inner_pull_port, pslot) == NGX_ERROR)
{
ngx_log_error(NGX_LOG_ERR, rs->log, 0,
"inner relay, get mulitport error: %V",
&riacf->inner_pull_port);
return NGX_ERROR;
}
url->url.host = port;
url->url.host_with_port = port;
url->relay_type = NGX_LIVE_RELAY_RTMP;
return NGX_OK;
}
static void
ngx_live_relay_inner_handler(ngx_event_t *ev)
{
ngx_rtmp_session_t *s;
ngx_live_relay_app_conf_t *lracf;
ngx_live_relay_ctx_t *ctx;
ngx_live_relay_t relay;
s = ev->data;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (!ctx->failed_delay && ev->timedout) { // connect timeout
ngx_log_error(NGX_LOG_ERR, s->log, NGX_ETIMEDOUT,
"inner relay, relay timeout");
s->finalize_reason = NGX_LIVE_RELAY_TIMEOUT;
ngx_rtmp_finalize_session(s);
return;
}
// relay pull, no player or relay push no publisher
if ((s->publishing && s->live_stream->play_ctx == NULL)
|| (!s->publishing && s->live_stream->publish_ctx == NULL))
{
return;
}
lracf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_module);
ngx_add_timer(&ctx->reconnect, lracf->relay_reconnect);
if (ngx_live_relay_inner_create_relay(s, &relay, s->live_stream->pslot)
!= NGX_OK)
{
return;
}
ngx_live_relay_create(s, &relay);
}
// if stream's need to continue pull or push chain, otherwise return NGX_OK
static ngx_int_t
ngx_live_relay_inner_relay(ngx_rtmp_session_t *s, unsigned publishing)
{
ngx_rtmp_session_t *rs;
ngx_live_relay_ctx_t *ctx, *pctx;
ngx_live_relay_app_conf_t *lracf;
ngx_int_t pslot;
pslot = ngx_stream_zone_insert_stream(&s->stream);
if (pslot == NGX_ERROR) { // stream zone not configured or configured error
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"inner relay, insert stream %V failed", &s->stream);
return NGX_DECLINED;
}
ngx_log_error(NGX_LOG_INFO, s->log, 0,
"inner relay, stream %V not in current process, "
"pslot:%i ngx_process_slot:%i",
&s->stream, pslot, ngx_process_slot);
s->live_stream->pslot = pslot;
if (pslot == ngx_process_slot) { // current process become stream owner
return NGX_DECLINED;
}
rs = ngx_rtmp_create_relay_session(s, &ngx_live_relay_inner_module);
if (rs == NULL) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"inner relay, create relay session failed");
return NGX_DECLINED;
}
rs->publishing = publishing;
rs->live_stream = s->live_stream;
ngx_live_create_ctx(rs, publishing);
ctx = ngx_rtmp_get_module_ctx(rs, ngx_live_relay_module);
ctx->reconnect.log = rs->log;
ctx->reconnect.data = rs;
ctx->reconnect.handler = ngx_live_relay_inner_handler;
lracf = ngx_rtmp_get_module_app_conf(rs, ngx_live_relay_module);
// play trigger pull or publish trigger push
if (s->publishing != rs->publishing) {
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
// normal publisher close, need to trigger pull
if (s->publishing && !s->relay) {
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
// reconnect
pctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (pctx->successd) { // prev relay susccessd
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
if (!pctx->reconnect.timer_set) { // prev relay timeout
ctx->failed_reconnect = ngx_min(pctx->failed_reconnect * 2,
lracf->relay_reconnect);
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
if (pctx->failed_reconnect) {
ctx->failed_reconnect = ngx_min(pctx->failed_reconnect * 2,
lracf->relay_reconnect);
} else {
ctx->failed_reconnect = lracf->failed_reconnect;
}
ctx->failed_delay = 1;
ngx_add_timer(&ctx->reconnect, ctx->failed_reconnect);
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_inner_push(ngx_rtmp_session_t *s)
{
ngx_live_relay_inner_app_conf_t *riacf;
riacf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_inner_module);
if (!riacf->inner_pull) {
goto next;
}
if (s->relay) {
goto next;
}
if (ngx_live_relay_inner_relay(s, 0) == NGX_OK) {
return NGX_OK;
}
next:
return next_push(s);
}
static ngx_int_t
ngx_live_relay_inner_pull(ngx_rtmp_session_t *s)
{
ngx_live_relay_inner_app_conf_t *riacf;
riacf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_inner_module);
if (!riacf->inner_pull) {
goto next;
}
if (!s->publishing && s->relay) { // relay push
goto next;
}
if (s->live_stream->pslot != -1) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"inner relay, stream %V already in current process",
&s->stream);
if (s->live_stream->pslot == ngx_process_slot) {
// stream leader is in current process, continue pull or push chain
goto next;
}
return NGX_OK;
}
if (ngx_live_relay_inner_relay(s, 1) == NGX_OK) {
return NGX_OK;
}
next:
return next_pull(s);
}
static ngx_int_t
ngx_live_relay_inner_push_close(ngx_rtmp_session_t *s)
{
ngx_live_relay_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx->tag != &ngx_live_relay_inner_module) {
goto next;
}
// relay push and has publisher in stream
if (!ctx->giveup && s->live_stream->publish_ctx) {
ngx_live_relay_inner_relay(s, 0);
}
next:
return next_push_close(s);
}
static ngx_int_t
ngx_live_relay_inner_pull_close(ngx_rtmp_session_t *s)
{
ngx_live_relay_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
goto next;
}
if (ctx->tag != &ngx_live_relay_inner_module) {
goto next;
}
// inner relay close
s->live_stream->pslot = -1;
next:
return next_pull_close(s);
}
static ngx_int_t
ngx_live_relay_inner_postconfiguration(ngx_conf_t *cf)
{
/* chain handlers */
next_push = ngx_live_push;
ngx_live_push = ngx_live_relay_inner_push;
next_pull = ngx_live_pull;
ngx_live_pull = ngx_live_relay_inner_pull;
next_push_close = ngx_live_push_close;
ngx_live_push_close = ngx_live_relay_inner_push_close;
next_pull_close = ngx_live_pull_close;
ngx_live_pull_close = ngx_live_relay_inner_pull_close;
return NGX_OK;
}
|
294coder/Efficient-MIF
| 1,933 |
utils/sailency/attributes.py
|
import torch
import cv2
import torch.nn.functional as F
def _tensor_size(t):
return t.size()[1] * t.size()[2] * t.size()[3]
def reduce_func(method):
"""
:param method: ['mean', 'sum', 'max', 'min', 'count', 'std']
:return:
"""
if method == 'sum':
return torch.sum
elif method == 'mean':
return torch.mean
elif method == 'count':
return lambda x: sum(x.size())
else:
raise NotImplementedError()
def attr_id(tensor, h, w, window=8, reduce='sum'):
"""
:param tensor: B, C, H, W tensor
:param h: h position
:param w: w position
:param window: size of window
:param reduce: reduce method, ['mean', 'sum', 'max', 'min']
:return:
"""
crop = tensor[:, :, h: h + window, w: w + window]
return reduce_func(reduce)(crop)
def attr_grad(tensor, h, w, window=8, reduce='sum'):
"""
:param tensor: B, C, H, W tensor
:param h: h position
:param w: w position
:param window: size of window
:param reduce: reduce method, ['mean', 'sum', 'max', 'min']
:return:
"""
h_x = tensor.size()[2]
w_x = tensor.size()[3]
h_grad = torch.pow(tensor[:, :, :h_x - 1, :] - tensor[:, :, 1:, :], 2)
w_grad = torch.pow(tensor[:, :, :, :w_x - 1] - tensor[:, :, :, 1:], 2)
grad = torch.pow(h_grad[:, :, :, :-1] + w_grad[:, :, :-1, :], 1 / 2)
crop = grad[:, :, h: h + window, w: w + window]
return reduce_func(reduce)(crop)
# gabor_filter = cv2.getGaborKernel((21, 21), 10.0, -np.pi/4, 8.0, 1, 0, ktype=cv2.CV_32F)
def attr_gabor_generator(gabor_filter):
filter = torch.from_numpy(gabor_filter).view((1, 1,) + gabor_filter.shape).repeat(1,3,1,1)
def attr_gabor(tensor, h, w, window=8, reduce='sum'):
after_filter = F.conv2d(tensor, filter, bias=None)
crop = after_filter[:, :, h: h + window, w: w + window]
return reduce_func(reduce)(crop)
return attr_gabor
|
281677160/openwrt-package
| 41,746 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_variables.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <nginx.h>
#include "ngx_rtmp.h"
#include "ngx_rtmp_variables.h"
#include "ngx_live_relay.h"
static ngx_int_t ngx_rtmp_variable_session_get_str(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_session_get_uint(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_session_get_int(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_session_get_msec(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_relay_get_str(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_relay_get_uint(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_finalize_reason(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_stage(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_remote_addr(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_remote_port(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_local_addr(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_local_port(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_nginx_version(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_pid(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_msec(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_time_iso8601(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_time_local(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_ngx_worker(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_int_t ngx_rtmp_variable_argument(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data);
static ngx_rtmp_variable_t ngx_rtmp_core_variables[] = {
{ ngx_string("domain"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, domain), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("app"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, app), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("name"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, name), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("stream"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, stream), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("pargs"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, pargs), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("args"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, args), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("flashver"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, flashver), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("swf_url"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, swf_url), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("tc_url"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, tc_url), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("page_url"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, page_url), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("acodecs"), NULL, ngx_rtmp_variable_session_get_uint,
offsetof(ngx_rtmp_session_t, acodecs), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("vcodecs"), NULL, ngx_rtmp_variable_session_get_uint,
offsetof(ngx_rtmp_session_t, vcodecs), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("scheme"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, scheme), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("serverid"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, serverid), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("groupid"), NULL, ngx_rtmp_variable_session_get_str,
offsetof(ngx_rtmp_session_t, groupid), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("notify_status"), NULL, ngx_rtmp_variable_session_get_int,
offsetof(ngx_rtmp_session_t, notify_status), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("finalize_reason"), NULL, ngx_rtmp_variable_finalize_reason,
0, NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("stage"), NULL, ngx_rtmp_variable_stage,
0, NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("init"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, init_time), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("handshake_done"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, handshake_done_time),
NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("connect"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, connect_time), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("create_stream"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, create_stream_time),
NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("ptime"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, ptime), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("first_data"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, first_data), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("first_metadata"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, first_metadata),
NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("first_audio"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, first_audio), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("first_video"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, first_video), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("close_stream"), NULL, ngx_rtmp_variable_session_get_msec,
offsetof(ngx_rtmp_session_t, close_stream_time),
NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_domain"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, domain), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_app"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, app), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_name"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, name), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_args"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, args), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_pargs"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, pargs), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_referer"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, referer), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_user_agent"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, user_agent), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_swf_url"), NULL, ngx_rtmp_variable_relay_get_str,
offsetof(ngx_live_relay_ctx_t, swf_url), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_acodecs"), NULL, ngx_rtmp_variable_relay_get_uint,
offsetof(ngx_live_relay_ctx_t, acodecs), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("relay_vcodecs"), NULL, ngx_rtmp_variable_relay_get_uint,
offsetof(ngx_live_relay_ctx_t, vcodecs), NGX_RTMP_VAR_NOCACHEABLE, 0},
{ ngx_string("remote_addr"), NULL, ngx_rtmp_variable_remote_addr,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("remote_port"), NULL, ngx_rtmp_variable_remote_port,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("server_addr"), NULL, ngx_rtmp_variable_local_addr,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("server_port"), NULL, ngx_rtmp_variable_local_port,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("nginx_version"), NULL,
ngx_rtmp_variable_nginx_version, 0, 0, 0},
{ ngx_string("pid"), NULL, ngx_rtmp_variable_pid, 0, 0, 0},
{ ngx_string("msec"), NULL, ngx_rtmp_variable_msec,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("time_iso8601"), NULL, ngx_rtmp_variable_time_iso8601,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("time_local"), NULL, ngx_rtmp_variable_time_local,
0, NGX_RTMP_VAR_NOCACHEABLE, 0 },
{ ngx_string("ngx_worker"), NULL, ngx_rtmp_variable_ngx_worker,
0, 0, 0},
{ ngx_string("parg_"), NULL, ngx_rtmp_variable_argument,
0, NGX_RTMP_VAR_NOCACHEABLE|NGX_RTMP_VAR_PREFIX, 0 },
{ ngx_null_string, NULL, NULL, 0, 0, 0 }
};
ngx_rtmp_variable_value_t ngx_rtmp_variable_null_value =
ngx_rtmp_variable("");
ngx_rtmp_variable_value_t ngx_rtmp_variable_true_value =
ngx_rtmp_variable("1");
static ngx_uint_t ngx_rtmp_variable_depth = 100;
extern char *ngx_live_stage[];
extern char *ngx_live_err[];
static ngx_int_t
ngx_rtmp_variable_session_get_str(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_str_t *str;
str = (ngx_str_t *) ((u_char *) s + data);
v->data = str->data;
v->len = str->len;
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_session_get_uint(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_uint_t *ui;
ui = (ngx_uint_t *) ((u_char *) s + data);
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_INT_T_LEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->len = ngx_sprintf(v->data, "%ui", *ui) - v->data;
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_session_get_int(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_int_t *i;
i = (ngx_int_t *) ((u_char *) s + data);
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_INT_T_LEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->len = ngx_sprintf(v->data, "%i", *i) - v->data;
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_session_get_msec(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_msec_t *m;
m = (ngx_msec_t *) ((u_char *) s + data);
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_INT_T_LEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->len = ngx_sprintf(v->data, "%i", *m) - v->data;
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_relay_get_str(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_live_relay_ctx_t *ctx;
ngx_str_t *str;
if (!s->relay) {
v->not_found = 1;
return NGX_OK;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
str = (ngx_str_t *) ((u_char *) ctx + data);
v->data = str->data;
v->len = str->len;
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_relay_get_uint(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_live_relay_ctx_t *ctx;
ngx_uint_t *ui;
if (!s->relay) {
v->not_found = 1;
return NGX_OK;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
ui = (ngx_uint_t *) ((u_char *) ctx + data);
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_INT_T_LEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->len = ngx_sprintf(v->data, "%ui", *ui) - v->data;
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_finalize_reason(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
v->data = (u_char *) ngx_live_err[s->finalize_reason];
v->len = ngx_strlen(v->data);
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_stage(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
v->data = (u_char *) ngx_live_stage[s->stage];
v->len = ngx_strlen(v->data);
v->valid = 1;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_remote_addr(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_sockaddr_t nsa;
struct sockaddr *sa;
socklen_t len;
if (s->connection == NULL || s->connection->fd == (ngx_socket_t) -1) {
v->not_found = 1;
return NGX_OK;
}
sa = (struct sockaddr *) &nsa;
len = sizeof(nsa);
if (getpeername(s->connection->fd, sa, &len) == -1) {
v->not_found = 1;
return NGX_OK;
}
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_SOCKADDRLEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->len = ngx_sock_ntop(sa, sizeof(nsa), v->data, NGX_SOCKADDRLEN, 0);
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_remote_port(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_sockaddr_t nsa;
struct sockaddr *sa;
socklen_t len;
in_port_t port;
if (s->connection == NULL || s->connection->fd == (ngx_socket_t) -1) {
v->not_found = 1;
return NGX_OK;
}
sa = (struct sockaddr *) &nsa;
len = sizeof(nsa);
if (getpeername(s->connection->fd, sa, &len) == -1) {
v->not_found = 1;
return NGX_OK;
}
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, sizeof("65535") - 1);
if (v->data == NULL) {
return NGX_ERROR;
}
}
port = ngx_inet_get_port(sa);
if (port == 0) {
v->not_found = 1;
return NGX_OK;
}
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->len = ngx_sprintf(v->data, "%ui", port) - v->data;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_local_addr(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_sockaddr_t nsa;
struct sockaddr *sa;
socklen_t len;
if (s->connection == NULL || s->connection->fd == (ngx_socket_t) -1) {
v->not_found = 1;
return NGX_OK;
}
sa = (struct sockaddr *) &nsa;
len = sizeof(nsa);
if (getsockname(s->connection->fd, sa, &len) == -1) {
v->not_found = 1;
return NGX_OK;
}
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_SOCKADDRLEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->len = ngx_sock_ntop(sa, sizeof(nsa), v->data, NGX_SOCKADDRLEN, 0);
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_local_port(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_sockaddr_t nsa;
struct sockaddr *sa;
socklen_t len;
in_port_t port;
if (s->connection == NULL || s->connection->fd == (ngx_socket_t) -1) {
v->not_found = 1;
return NGX_OK;
}
sa = (struct sockaddr *) &nsa;
len = sizeof(nsa);
if (getsockname(s->connection->fd, sa, &len) == -1) {
v->not_found = 1;
return NGX_OK;
}
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, sizeof("65535") - 1);
if (v->data == NULL) {
return NGX_ERROR;
}
}
port = ngx_inet_get_port(sa);
if (port == 0) {
v->not_found = 1;
return NGX_OK;
}
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->len = ngx_sprintf(v->data, "%ui", port) - v->data;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_nginx_version(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
v->len = sizeof(NGINX_VERSION) - 1;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
v->data = (u_char *) NGINX_VERSION;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_pid(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_INT64_LEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->len = ngx_sprintf(v->data, "%P", ngx_pid) - v->data;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_msec(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_time_t *tp;
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_TIME_T_LEN + 4);
if (v->data == NULL) {
return NGX_ERROR;
}
}
tp = ngx_timeofday();
v->len = ngx_sprintf(v->data, "%T.%03M", tp->sec, tp->msec) - v->data;
v->valid = 1;
v->no_cacheable = 1;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_time_iso8601(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, ngx_cached_http_log_iso8601.len);
if (v->data == NULL) {
return NGX_ERROR;
}
}
ngx_memcpy(v->data, ngx_cached_http_log_iso8601.data,
ngx_cached_http_log_iso8601.len);
v->len = ngx_cached_http_log_iso8601.len;
v->valid = 1;
v->no_cacheable = 1;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_time_local(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, ngx_cached_http_log_time.len);
if (v->data == NULL) {
return NGX_ERROR;
}
}
ngx_memcpy(v->data, ngx_cached_http_log_time.data,
ngx_cached_http_log_time.len);
v->len = ngx_cached_http_log_time.len;
v->valid = 1;
v->no_cacheable = 1;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_ngx_worker(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
if (v->data == NULL) {
v->data = ngx_pnalloc(s->pool, NGX_INT64_LEN);
if (v->data == NULL) {
return NGX_ERROR;
}
}
v->len = ngx_sprintf(v->data, "%ui", ngx_worker) - v->data;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_variable_argument(ngx_rtmp_session_t *s,
ngx_http_variable_value_t *v, uintptr_t data)
{
ngx_str_t *name = (ngx_str_t *) data;
u_char *arg;
size_t len;
ngx_str_t value;
len = name->len - (sizeof("parg_") - 1);
arg = name->data + sizeof("parg_") - 1;
if (ngx_rtmp_arg(s, arg, len, &value) != NGX_OK) {
v->not_found = 1;
return NGX_OK;
}
v->data = value.data;
v->len = value.len;
v->valid = 1;
v->no_cacheable = 0;
v->not_found = 0;
return NGX_OK;
}
static ngx_rtmp_variable_t *
ngx_rtmp_add_prefix_variable(ngx_conf_t *cf, ngx_str_t *name, ngx_uint_t flags)
{
ngx_uint_t i;
ngx_rtmp_variable_t *v;
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
v = cmcf->prefix_variables.elts;
for (i = 0; i < cmcf->prefix_variables.nelts; i++) {
if (name->len != v[i].name.len
|| ngx_strncasecmp(name->data, v[i].name.data, name->len) != 0)
{
continue;
}
v = &v[i];
if (!(v->flags & NGX_HTTP_VAR_CHANGEABLE)) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"the duplicate \"%V\" variable", name);
return NULL;
}
v->flags &= flags | ~NGX_HTTP_VAR_WEAK;
return v;
}
v = ngx_array_push(&cmcf->prefix_variables);
if (v == NULL) {
return NULL;
}
v->name.len = name->len;
v->name.data = ngx_pnalloc(cf->pool, name->len);
if (v->name.data == NULL) {
return NULL;
}
ngx_strlow(v->name.data, name->data, name->len);
v->set_handler = NULL;
v->get_handler = NULL;
v->data = 0;
v->flags = flags;
v->index = 0;
return v;
}
static u_char *
ngx_rtmp_strlechr(u_char *p, u_char *last)
{
while (p != last) {
if ((*p >= '0' && *p <= '9') ||
(*p >= 'a' && *p <= 'z') ||
(*p >= 'A' && *p <= 'Z') ||
*p == '_')
{
p++;
continue;
}
return p;
}
return NULL;
}
ngx_int_t
ngx_rtmp_variable_transform_index(ngx_conf_t *cf, ngx_str_t *origin, ngx_str_t *target)
{
u_char *p, *e, *t;
u_char *wp, *we;
ngx_str_t str, var;
ngx_buf_t *buf;
ngx_int_t index;
p = origin->data;
e = origin->data + origin->len;
buf = ngx_create_temp_buf(cf->pool, 2 * origin->len);
if (buf == NULL) {
return NGX_ERROR;
}
wp = buf->start;
we = buf->end;
while (p < e) {
t = ngx_strlchr(p, e, '$');
if (t == NULL) {
t = e;
}
str.data = p;
str.len = t - p;
wp = ngx_slprintf(wp, we, "%V", &str);
if (t == e) {
break;
}
var.data = ++t;
t = ngx_rtmp_strlechr(t, e);
if (t == NULL) {
t = e;
}
var.len = t - var.data;
index = ngx_rtmp_get_variable_index(cf, &var);
if (index == NGX_ERROR) {
return NGX_ERROR;
}
wp = ngx_slprintf(wp, we, "$%d", index);
p = t;
}
target->data = buf->start;
target->len = wp - buf->start;
return NGX_OK;
}
ngx_int_t
ngx_rtmp_fetch_variable(ngx_rtmp_session_t *s, ngx_pool_t *pool,
ngx_str_t *origin, ngx_str_t *target)
{
ngx_rtmp_variable_value_t *vv;
u_char *p, *e, *t;
u_char *wp, *we;
ngx_chain_t *ch, *cl, *ct;
u_char *pt;
ngx_uint_t length;
ngx_int_t index;
ngx_str_t var;
length = 0;
p = origin->data;
e = p + origin->len;
#define NGX_RTMP_NOTIFY_BUF(__start__, __end__) \
ct = cl; \
pt = ngx_pcalloc(pool, sizeof(ngx_chain_t) + \
sizeof(ngx_buf_t) + __end__ - __start__); \
cl = (ngx_chain_t*)pt; \
cl->buf = (ngx_buf_t*)(pt + sizeof(ngx_chain_t)); \
cl->buf->start = \
cl->buf->pos = \
cl->buf->last = pt + sizeof(ngx_chain_t) + sizeof(ngx_buf_t); \
if (ch == NULL) { \
ch = cl; \
} else { \
ct->next = cl; \
} \
cl->buf->last = ngx_cpymem(cl->buf->pos, __start__, __end__ - __start__); \
length += __end__ - __start__
ch = cl = ct = NULL;
while(p < e) {
t = ngx_strlchr(p, e, '$');
if (t == NULL) {
t = e;
}
NGX_RTMP_NOTIFY_BUF(p, t);
if (t == e) {
break;
}
var.data = ++t;
t = ngx_rtmp_strlechr(t, e);
if (t == NULL) {
t = e;
}
var.len = t - var.data;
index = ngx_atoi(var.data, var.len);
vv = ngx_rtmp_get_indexed_variable(s, index);
if (vv == NULL) {
p = t;
continue;
}
wp = vv->data;
we = vv->data + vv->len;
NGX_RTMP_NOTIFY_BUF(wp, we);
p = t;
}
#undef NGX_RTMP_NOTIFY_BUF
wp = ngx_pcalloc(pool, length);
we = wp;
for (ct = ch; ct;) {
we = ngx_cpymem(we, ct->buf->pos, ct->buf->last - ct->buf->pos);
cl = ct->next;
ngx_pfree(pool, ct);
ct = cl;
}
target->data = wp;
target->len = we - wp;
if (target->len != length) {
ngx_log_error(NGX_LOG_ERR, s->connection->log, 0,
"variable: fetch_variable| target len = %d, content length = %d",
target->len, length);
return NGX_ERROR;
}
return NGX_OK;
}
ngx_rtmp_variable_t *
ngx_rtmp_add_variable(ngx_conf_t *cf, ngx_str_t *name, ngx_uint_t flags)
{
ngx_int_t rc;
ngx_uint_t i;
ngx_hash_key_t *key;
ngx_rtmp_variable_t *v;
ngx_rtmp_core_main_conf_t *cmcf;
if (name->len == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"invalid variable name \"$\"");
return NULL;
}
if (flags & NGX_HTTP_VAR_PREFIX) {
return ngx_rtmp_add_prefix_variable(cf, name, flags);
}
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
key = cmcf->variables_keys->keys.elts;
for (i = 0; i < cmcf->variables_keys->keys.nelts; i++) {
if (name->len != key[i].key.len
|| ngx_strncasecmp(name->data, key[i].key.data, name->len) != 0)
{
continue;
}
v = key[i].value;
if (!(v->flags & NGX_HTTP_VAR_CHANGEABLE)) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"the duplicate \"%V\" variable", name);
return NULL;
}
v->flags &= flags | ~NGX_HTTP_VAR_WEAK;
return v;
}
v = ngx_palloc(cf->pool, sizeof(ngx_rtmp_variable_t));
if (v == NULL) {
return NULL;
}
v->name.len = name->len;
v->name.data = ngx_pnalloc(cf->pool, name->len);
if (v->name.data == NULL) {
return NULL;
}
ngx_strlow(v->name.data, name->data, name->len);
v->set_handler = NULL;
v->get_handler = NULL;
v->data = 0;
v->flags = flags;
v->index = 0;
rc = ngx_hash_add_key(cmcf->variables_keys, &v->name, v, 0);
if (rc == NGX_ERROR) {
return NULL;
}
if (rc == NGX_BUSY) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"conflicting variable name \"%V\"", name);
return NULL;
}
return v;
}
ngx_int_t
ngx_rtmp_get_variable_index(ngx_conf_t *cf, ngx_str_t *name)
{
ngx_uint_t i = 0, n;
ngx_rtmp_variable_t *v, *av;
ngx_rtmp_core_main_conf_t *cmcf;
ngx_hash_key_t *key;
if (name->len == 0) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"invalid variable name \"$\"");
return NGX_ERROR;
}
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
v = cmcf->variables.elts;
key = cmcf->variables_keys->keys.elts;
if (v == NULL) {
if (ngx_array_init(&cmcf->variables, cf->pool, 4,
sizeof(ngx_http_variable_t))
!= NGX_OK)
{
return NGX_ERROR;
}
} else {
for (i = 0; i < cmcf->variables.nelts; i++) {
if (name->len != v[i].name.len
|| ngx_strncasecmp(name->data, v[i].name.data, name->len) != 0)
{
continue;
}
return i;
}
}
v = ngx_array_push(&cmcf->variables);
if (v == NULL) {
return NGX_ERROR;
}
v->name.len = name->len;
v->name.data = ngx_pnalloc(cf->pool, name->len);
if (v->name.data == NULL) {
return NGX_ERROR;
}
ngx_strlow(v->name.data, name->data, name->len);
for (n = 0; n < cmcf->variables_keys->keys.nelts; n++) {
av = key[n].value;
if (av->get_handler
&& v->name.len == key[n].key.len
&& ngx_strncmp(v->name.data, key[n].key.data, v->name.len) == 0)
{
v->get_handler = av->get_handler;
v->data = av->data;
av->flags= NGX_RTMP_VAR_INDEXED;
v->flags = av->flags;
av->index = i;
goto next;
}
}
ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
"variables: get_variable_index| unknown \"%V\" variable",
&v->name);
return NGX_ERROR;
next:
v->set_handler = NULL;
v->index = cmcf->variables.nelts - 1;
return v->index;
}
ngx_rtmp_variable_value_t *
ngx_rtmp_get_indexed_variable(ngx_rtmp_session_t *s, ngx_uint_t index)
{
ngx_rtmp_variable_t *v;
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_core_module);
if (cmcf->variables.nelts <= index) {
ngx_log_error(NGX_LOG_ALERT, s->log, 0,
"unknown variable index: %ui", index);
return NULL;
}
if (s->variables[index].not_found || s->variables[index].valid) {
return &s->variables[index];
}
v = cmcf->variables.elts;
if (ngx_rtmp_variable_depth == 0) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"cycle while evaluating variable \"%V\"",
&v[index].name);
return NULL;
}
ngx_rtmp_variable_depth--;
if (v[index].get_handler(s, &s->variables[index], v[index].data)
== NGX_OK)
{
ngx_rtmp_variable_depth++;
if (v[index].flags & NGX_HTTP_VAR_NOCACHEABLE) {
s->variables[index].no_cacheable = 1;
}
return &s->variables[index];
}
ngx_rtmp_variable_depth++;
s->variables[index].valid = 0;
s->variables[index].not_found = 1;
return NULL;
}
ngx_rtmp_variable_value_t *
ngx_rtmp_get_flushed_variable(ngx_rtmp_session_t *s, ngx_uint_t index)
{
ngx_rtmp_variable_value_t *v;
v = &s->variables[index];
if (v->valid || v->not_found) {
if (!v->no_cacheable) {
return v;
}
v->valid = 0;
v->not_found = 0;
}
return ngx_rtmp_get_indexed_variable(s, index);
}
ngx_rtmp_variable_value_t *
ngx_rtmp_get_variable(ngx_rtmp_session_t *s, ngx_str_t *name, ngx_uint_t key)
{
size_t len;
ngx_uint_t i, n;
ngx_rtmp_variable_t *v;
ngx_rtmp_variable_value_t *vv;
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_core_module);
v = ngx_hash_find(&cmcf->variables_hash, key, name->data, name->len);
if (v) {
if (v->flags & NGX_HTTP_VAR_INDEXED) {
return ngx_rtmp_get_flushed_variable(s, v->index);
}
if (ngx_rtmp_variable_depth == 0) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"cycle while evaluating variable \"%V\"", name);
return NULL;
}
ngx_rtmp_variable_depth--;
vv = ngx_palloc(s->pool, sizeof(ngx_rtmp_variable_value_t));
if (vv && v->get_handler(s, vv, v->data) == NGX_OK) {
ngx_rtmp_variable_depth++;
return vv;
}
ngx_rtmp_variable_depth++;
return NULL;
}
vv = ngx_palloc(s->pool, sizeof(ngx_rtmp_variable_value_t));
if (vv == NULL) {
return NULL;
}
len = 0;
v = cmcf->prefix_variables.elts;
n = cmcf->prefix_variables.nelts;
for (i = 0; i < cmcf->prefix_variables.nelts; i++) {
if (name->len >= v[i].name.len && name->len > len
&& ngx_strncmp(name->data, v[i].name.data, v[i].name.len) == 0)
{
len = v[i].name.len;
n = i;
}
}
if (n != cmcf->prefix_variables.nelts) {
if (v[n].get_handler(s, vv, (uintptr_t) name) == NGX_OK) {
return vv;
}
return NULL;
}
vv->not_found = 1;
return vv;
}
void *
ngx_rtmp_map_find(ngx_rtmp_session_t *s, ngx_rtmp_map_t *map, ngx_str_t *match)
{
void *value;
u_char *low;
size_t len;
ngx_uint_t key;
len = match->len;
if (len) {
low = ngx_pnalloc(s->pool, len);
if (low == NULL) {
return NULL;
}
} else {
low = NULL;
}
key = ngx_hash_strlow(low, match->data, len);
value = ngx_hash_find_combined(&map->hash, key, low, len);
if (value) {
return value;
}
#if (NGX_PCRE)
if (len && map->nregex) {
ngx_int_t n;
ngx_uint_t i;
ngx_rtmp_map_regex_t *reg;
reg = map->regex;
for (i = 0; i < map->nregex; i++) {
n = ngx_rtmp_regex_exec(s, reg[i].regex, match);
if (n == NGX_OK) {
return reg[i].value;
}
if (n == NGX_DECLINED) {
continue;
}
/* NGX_ERROR */
return NULL;
}
}
#endif
return NULL;
}
#if (NGX_PCRE)
static ngx_int_t
ngx_rtmp_variable_not_found(ngx_rtmp_session_t *s, ngx_rtmp_variable_value_t *v,
uintptr_t data)
{
v->not_found = 1;
return NGX_OK;
}
ngx_rtmp_regex_t *
ngx_rtmp_regex_compile(ngx_conf_t *cf, ngx_regex_compile_t *rc)
{
u_char *p;
size_t size;
ngx_str_t name;
ngx_uint_t i, n;
ngx_rtmp_variable_t *v;
ngx_rtmp_regex_t *re;
ngx_rtmp_regex_variable_t *rv;
ngx_rtmp_core_main_conf_t *cmcf;
rc->pool = cf->pool;
if (ngx_regex_compile(rc) != NGX_OK) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0, "%V", &rc->err);
return NULL;
}
re = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_regex_t));
if (re == NULL) {
return NULL;
}
re->regex = rc->regex;
re->ncaptures = rc->captures;
re->name = rc->pattern;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
cmcf->ncaptures = ngx_max(cmcf->ncaptures, re->ncaptures);
n = (ngx_uint_t) rc->named_captures;
if (n == 0) {
return re;
}
rv = ngx_palloc(rc->pool, n * sizeof(ngx_rtmp_regex_variable_t));
if (rv == NULL) {
return NULL;
}
re->variables = rv;
re->nvariables = n;
size = rc->name_size;
p = rc->names;
for (i = 0; i < n; i++) {
rv[i].capture = 2 * ((p[0] << 8) + p[1]);
name.data = &p[2];
name.len = ngx_strlen(name.data);
v = ngx_rtmp_add_variable(cf, &name, NGX_HTTP_VAR_CHANGEABLE);
if (v == NULL) {
return NULL;
}
rv[i].index = ngx_rtmp_get_variable_index(cf, &name);
if (rv[i].index == NGX_ERROR) {
return NULL;
}
v->get_handler = ngx_rtmp_variable_not_found;
p += size;
}
return re;
}
ngx_int_t
ngx_rtmp_regex_exec(ngx_rtmp_session_t *s, ngx_rtmp_regex_t *re, ngx_str_t *str)
{
ngx_int_t rc, index;
ngx_uint_t i, n, len;
ngx_rtmp_variable_value_t *vv;
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_core_module);
if (re->ncaptures) {
len = cmcf->ncaptures;
if (s->captures == NULL) {
s->captures = ngx_palloc(s->pool, len * sizeof(int));
if (s->captures == NULL) {
return NGX_ERROR;
}
}
} else {
len = 0;
}
rc = ngx_regex_exec(re->regex, str, s->captures, len);
if (rc == NGX_REGEX_NO_MATCHED) {
return NGX_DECLINED;
}
if (rc < 0) {
ngx_log_error(NGX_LOG_ALERT, s->log, 0,
ngx_regex_exec_n " failed: %i on \"%V\" using \"%V\"",
rc, str, &re->name);
return NGX_ERROR;
}
for (i = 0; i < re->nvariables; i++) {
n = re->variables[i].capture;
index = re->variables[i].index;
vv = &s->variables[index];
vv->len = s->captures[n + 1] - s->captures[n];
vv->valid = 1;
vv->no_cacheable = 0;
vv->not_found = 0;
vv->data = &str->data[s->captures[n]];
#if (NGX_DEBUG)
{
ngx_rtmp_variable_t *v;
v = cmcf->variables.elts;
ngx_log_debug2(NGX_LOG_DEBUG_HTTP, s->log, 0,
"http regex set $%V to \"%v\"", &v[index].name, vv);
}
#endif
}
s->ncaptures = rc * 2;
s->captures_data = str->data;
return NGX_OK;
}
#endif
ngx_int_t
ngx_rtmp_variables_add_core_vars(ngx_conf_t *cf)
{
ngx_rtmp_variable_t *cv, *v;
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
cmcf->variables_keys = ngx_pcalloc(cf->temp_pool,
sizeof(ngx_hash_keys_arrays_t));
if (cmcf->variables_keys == NULL) {
return NGX_ERROR;
}
cmcf->variables_keys->pool = cf->pool;
cmcf->variables_keys->temp_pool = cf->pool;
if (ngx_hash_keys_array_init(cmcf->variables_keys, NGX_HASH_SMALL)
!= NGX_OK)
{
return NGX_ERROR;
}
if (ngx_array_init(&cmcf->prefix_variables, cf->pool, 8,
sizeof(ngx_rtmp_variable_t))
!= NGX_OK)
{
return NGX_ERROR;
}
for (cv = ngx_rtmp_core_variables; cv->name.len; cv++) {
v = ngx_rtmp_add_variable(cf, &cv->name, cv->flags);
if (v == NULL) {
return NGX_ERROR;
}
*v = *cv;
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_variables_init_vars(ngx_conf_t *cf)
{
size_t len;
ngx_uint_t i, n;
ngx_hash_key_t *key;
ngx_hash_init_t hash;
ngx_rtmp_variable_t *v, *av, *pv;
ngx_rtmp_core_main_conf_t *cmcf;
/* set the handlers for the indexed http variables */
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
v = cmcf->variables.elts;
pv = cmcf->prefix_variables.elts;
key = cmcf->variables_keys->keys.elts;
for (i = 0; i < cmcf->variables.nelts; i++) {
for (n = 0; n < cmcf->variables_keys->keys.nelts; n++) {
av = key[n].value;
if (v[i].name.len == key[n].key.len
&& ngx_strncmp(v[i].name.data, key[n].key.data, v[i].name.len)
== 0)
{
v[i].get_handler = av->get_handler;
v[i].data = av->data;
av->flags |= NGX_HTTP_VAR_INDEXED;
v[i].flags = av->flags;
av->index = i;
if (av->get_handler == NULL
|| (av->flags & NGX_HTTP_VAR_WEAK))
{
break;
}
goto next;
}
}
len = 0;
av = NULL;
for (n = 0; n < cmcf->prefix_variables.nelts; n++) {
if (v[i].name.len >= pv[n].name.len && v[i].name.len > len
&& ngx_strncmp(v[i].name.data, pv[n].name.data, pv[n].name.len)
== 0)
{
av = &pv[n];
len = pv[n].name.len;
}
}
if (av) {
v[i].get_handler = av->get_handler;
v[i].data = (uintptr_t) &v[i].name;
v[i].flags = av->flags;
goto next;
}
if (v[i].get_handler == NULL) {
ngx_log_error(NGX_LOG_EMERG, cf->log, 0,
"unknown \"%V\" variable", &v[i].name);
return NGX_ERROR;
}
next:
continue;
}
for (n = 0; n < cmcf->variables_keys->keys.nelts; n++) {
av = key[n].value;
if (av->flags & NGX_HTTP_VAR_NOHASH) {
key[n].key.data = NULL;
}
}
hash.hash = &cmcf->variables_hash;
hash.key = ngx_hash_key;
hash.max_size = cmcf->variables_hash_max_size;
hash.bucket_size = cmcf->variables_hash_bucket_size;
hash.name = "variables_hash";
hash.pool = cf->pool;
hash.temp_pool = NULL;
if (ngx_hash_init(&hash, cmcf->variables_keys->keys.elts,
cmcf->variables_keys->keys.nelts)
!= NGX_OK)
{
return NGX_ERROR;
}
cmcf->variables_keys = NULL;
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 224,320 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/keymap/vim.js
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
/**
* Supported keybindings:
* Too many to list. Refer to defaultKeymap below.
*
* Supported Ex commands:
* Refer to defaultExCommandMap below.
*
* Registers: unnamed, -, ., :, /, _, a-z, A-Z, 0-9
* (Does not respect the special case for number registers when delete
* operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
* TODO: Implement the remaining registers.
*
* Marks: a-z, A-Z, and 0-9
* TODO: Implement the remaining special marks. They have more complex
* behavior.
*
* Events:
* 'vim-mode-change' - raised on the editor anytime the current mode changes,
* Event object: {mode: "visual", subMode: "linewise"}
*
* Code structure:
* 1. Default keymap
* 2. Variable declarations and short basic helpers
* 3. Instance (External API) implementation
* 4. Internal state tracking objects (input state, counter) implementation
* and instantiation
* 5. Key handler (the main command dispatcher) implementation
* 6. Motion, operator, and action implementations
* 7. Helper functions for the key handler, motions, operators, and actions
* 8. Set up Vim to work as a keymap for CodeMirror.
* 9. Ex command implementations.
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/dialog/dialog"), require("../addon/edit/matchbrackets.js"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
'use strict';
var Pos = CodeMirror.Pos;
function transformCursor(cm, range) {
var vim = cm.state.vim;
if (!vim || vim.insertMode) return range.head;
var head = vim.sel.head;
if (!head) return range.head;
if (vim.visualBlock) {
if (range.head.line != head.line) {
return;
}
}
if (range.from() == range.anchor && !range.empty()) {
if (range.head.line == head.line && range.head.ch != head.ch)
return new Pos(range.head.line, range.head.ch - 1);
}
return range.head;
}
var defaultKeymap = [
// Key to key mapping. This goes first to make it possible to override
// existing mappings.
{ keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
{ keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
{ keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
{ keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
{ keys: 'g<Up>', type: 'keyToKey', toKeys: 'gk' },
{ keys: 'g<Down>', type: 'keyToKey', toKeys: 'gj' },
{ keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
{ keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
{ keys: '<Del>', type: 'keyToKey', toKeys: 'x', context: 'normal'},
{ keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
{ keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
{ keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
{ keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
{ keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
{ keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
{ keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
{ keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
{ keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
{ keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
{ keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
{ keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
{ keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
{ keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
{ keys: '<Home>', type: 'keyToKey', toKeys: '0' },
{ keys: '<End>', type: 'keyToKey', toKeys: '$' },
{ keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
{ keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
{ keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
{ keys: '<Ins>', type: 'keyToKey', toKeys: 'i', context: 'normal'},
{ keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
// Motions
{ keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
{ keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
{ keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
{ keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
{ keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
{ keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
{ keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
{ keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
{ keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
{ keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
{ keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
{ keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
{ keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
{ keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
{ keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
{ keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
{ keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
{ keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
{ keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
{ keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},
{ keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},
{ keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
{ keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
{ keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
{ keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
{ keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
{ keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
{keys: "g$", type: "motion", motion: "moveToEndOfDisplayLine"},
{keys: "g^", type: "motion", motion: "moveToStartOfDisplayLine"},
{keys: "g0", type: "motion", motion: "moveToStartOfDisplayLine"},
{ keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
{ keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
{ keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
{ keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
{ keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
{ keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
{ keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
{ keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
{ keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
{ keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
{ keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
{ keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
{ keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
{ keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
{ keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
{ keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
{ keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
{ keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
// the next two aren't motions but must come before more general motion declarations
{ keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
{ keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
{ keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
{ keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
{ keys: '|', type: 'motion', motion: 'moveToColumn'},
{ keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
{ keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
// Operators
{ keys: 'd', type: 'operator', operator: 'delete' },
{ keys: 'y', type: 'operator', operator: 'yank' },
{ keys: 'c', type: 'operator', operator: 'change' },
{ keys: '=', type: 'operator', operator: 'indentAuto' },
{ keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
{ keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
{ keys: 'g~', type: 'operator', operator: 'changeCase' },
{ keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
{ keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
{ keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
{ keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
{ keys: 'gn', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: true }},
{ keys: 'gN', type: 'motion', motion: 'findAndSelectNextInclusive', motionArgs: { forward: false }},
// Operator-Motion dual commands
{ keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
{ keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
{ keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
{ keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
{ keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},
{ keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
{ keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
{ keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
{ keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
{ keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
{ keys: '<C-u>', type: 'operatorMotion', operator: 'delete', motion: 'moveToStartOfLine', context: 'insert' },
{ keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
//ignore C-w in normal mode
{ keys: '<C-w>', type: 'idle', context: 'normal' },
// Actions
{ keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
{ keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
{ keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
{ keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
{ keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
{ keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
{ keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
{ keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
{ keys: 'gi', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'lastEdit' }, context: 'normal' },
{ keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
{ keys: 'gI', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'bol'}, context: 'normal' },
{ keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
{ keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
{ keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
{ keys: 'v', type: 'action', action: 'toggleVisualMode' },
{ keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
{ keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
{ keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
{ keys: 'gv', type: 'action', action: 'reselectLastSelection' },
{ keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
{ keys: 'gJ', type: 'action', action: 'joinLines', actionArgs: { keepSpaces: true }, isEdit: true },
{ keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
{ keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
{ keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
{ keys: '@<character>', type: 'action', action: 'replayMacro' },
{ keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
// Handle Replace-mode as a special case of insert mode.
{ keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }, context: 'normal'},
{ keys: 'R', type: 'operator', operator: 'change', operatorArgs: { linewise: true, fullLine: true }, context: 'visual', exitVisualBlock: true},
{ keys: 'u', type: 'action', action: 'undo', context: 'normal' },
{ keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
{ keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
{ keys: '<C-r>', type: 'action', action: 'redo' },
{ keys: 'm<character>', type: 'action', action: 'setMark' },
{ keys: '"<character>', type: 'action', action: 'setRegister' },
{ keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
{ keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
{ keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
{ keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
{ keys: '.', type: 'action', action: 'repeatLastEdit' },
{ keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
{ keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
{ keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
{ keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
// Text object motions
{ keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
{ keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
// Search
{ keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
{ keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
{ keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
{ keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
{ keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
{ keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
// Ex command
{ keys: ':', type: 'ex' }
];
var defaultKeymapLength = defaultKeymap.length;
/**
* Ex commands
* Care must be taken when adding to the default Ex command map. For any
* pair of commands that have a shared prefix, at least one of their
* shortNames must not match the prefix of the other command.
*/
var defaultExCommandMap = [
{ name: 'colorscheme', shortName: 'colo' },
{ name: 'map' },
{ name: 'imap', shortName: 'im' },
{ name: 'nmap', shortName: 'nm' },
{ name: 'vmap', shortName: 'vm' },
{ name: 'unmap' },
{ name: 'write', shortName: 'w' },
{ name: 'undo', shortName: 'u' },
{ name: 'redo', shortName: 'red' },
{ name: 'set', shortName: 'se' },
{ name: 'setlocal', shortName: 'setl' },
{ name: 'setglobal', shortName: 'setg' },
{ name: 'sort', shortName: 'sor' },
{ name: 'substitute', shortName: 's', possiblyAsync: true },
{ name: 'nohlsearch', shortName: 'noh' },
{ name: 'yank', shortName: 'y' },
{ name: 'delmarks', shortName: 'delm' },
{ name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
{ name: 'vglobal', shortName: 'v' },
{ name: 'global', shortName: 'g' }
];
var Vim = function() {
function enterVimMode(cm) {
cm.setOption('disableInput', true);
cm.setOption('showCursorWhenSelecting', false);
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
cm.on('cursorActivity', onCursorActivity);
maybeInitVimState(cm);
CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
}
function leaveVimMode(cm) {
cm.setOption('disableInput', false);
cm.off('cursorActivity', onCursorActivity);
CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
cm.state.vim = null;
if (highlightTimeout) clearTimeout(highlightTimeout);
}
function detachVimMap(cm, next) {
if (this == CodeMirror.keyMap.vim) {
cm.options.$customCursor = null;
CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
}
if (!next || next.attach != attachVimMap)
leaveVimMode(cm);
}
function attachVimMap(cm, prev) {
if (this == CodeMirror.keyMap.vim) {
if (cm.curOp) cm.curOp.selectionChanged = true;
cm.options.$customCursor = transformCursor;
CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
}
if (!prev || prev.attach != attachVimMap)
enterVimMode(cm);
}
// Deprecated, simply setting the keymap works again.
CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
if (val && cm.getOption("keyMap") != "vim")
cm.setOption("keyMap", "vim");
else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
cm.setOption("keyMap", "default");
});
function cmKey(key, cm) {
if (!cm) { return undefined; }
if (this[key]) { return this[key]; }
var vimKey = cmKeyToVimKey(key);
if (!vimKey) {
return false;
}
var cmd = vimApi.findKey(cm, vimKey);
if (typeof cmd == 'function') {
CodeMirror.signal(cm, 'vim-keypress', vimKey);
}
return cmd;
}
var modifiers = {Shift:'S',Ctrl:'C',Alt:'A',Cmd:'D',Mod:'A',CapsLock:''};
var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'};
function cmKeyToVimKey(key) {
if (key.charAt(0) == '\'') {
// Keypress character binding of format "'a'"
return key.charAt(1);
}
var pieces = key.split(/-(?!$)/);
var lastPiece = pieces[pieces.length - 1];
if (pieces.length == 1 && pieces[0].length == 1) {
// No-modifier bindings use literal character bindings above. Skip.
return false;
} else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
// Ignore Shift+char bindings as they should be handled by literal character.
return false;
}
var hasCharacter = false;
for (var i = 0; i < pieces.length; i++) {
var piece = pieces[i];
if (piece in modifiers) { pieces[i] = modifiers[piece]; }
else { hasCharacter = true; }
if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
}
if (!hasCharacter) {
// Vim does not support modifier only keys.
return false;
}
// TODO: Current bindings expect the character to be lower case, but
// it looks like vim key notation uses upper case.
if (isUpperCase(lastPiece)) {
pieces[pieces.length - 1] = lastPiece.toLowerCase();
}
return '<' + pieces.join('-') + '>';
}
function getOnPasteFn(cm) {
var vim = cm.state.vim;
if (!vim.onPasteFn) {
vim.onPasteFn = function() {
if (!vim.insertMode) {
cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
actions.enterInsertMode(cm, {}, vim);
}
};
}
return vim.onPasteFn;
}
var numberRegex = /[\d]/;
var wordCharTest = [CodeMirror.isWordChar, function(ch) {
return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
}], bigWordCharTest = [function(ch) {
return /\S/.test(ch);
}];
function makeKeyRange(start, size) {
var keys = [];
for (var i = start; i < start + size; i++) {
keys.push(String.fromCharCode(i));
}
return keys;
}
var upperCaseAlphabet = makeKeyRange(65, 26);
var lowerCaseAlphabet = makeKeyRange(97, 26);
var numbers = makeKeyRange(48, 10);
var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '_', '/']);
var upperCaseChars;
try { upperCaseChars = new RegExp("^[\\p{Lu}]$", "u"); }
catch (_) { upperCaseChars = /^[A-Z]$/; }
function isLine(cm, line) {
return line >= cm.firstLine() && line <= cm.lastLine();
}
function isLowerCase(k) {
return (/^[a-z]$/).test(k);
}
function isMatchableSymbol(k) {
return '()[]{}'.indexOf(k) != -1;
}
function isNumber(k) {
return numberRegex.test(k);
}
function isUpperCase(k) {
return upperCaseChars.test(k);
}
function isWhiteSpaceString(k) {
return (/^\s*$/).test(k);
}
function isEndOfSentenceSymbol(k) {
return '.?!'.indexOf(k) != -1;
}
function inArray(val, arr) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] == val) {
return true;
}
}
return false;
}
var options = {};
function defineOption(name, defaultValue, type, aliases, callback) {
if (defaultValue === undefined && !callback) {
throw Error('defaultValue is required unless callback is provided');
}
if (!type) { type = 'string'; }
options[name] = {
type: type,
defaultValue: defaultValue,
callback: callback
};
if (aliases) {
for (var i = 0; i < aliases.length; i++) {
options[aliases[i]] = options[name];
}
}
if (defaultValue) {
setOption(name, defaultValue);
}
}
function setOption(name, value, cm, cfg) {
var option = options[name];
cfg = cfg || {};
var scope = cfg.scope;
if (!option) {
return new Error('Unknown option: ' + name);
}
if (option.type == 'boolean') {
if (value && value !== true) {
return new Error('Invalid argument: ' + name + '=' + value);
} else if (value !== false) {
// Boolean options are set to true if value is not defined.
value = true;
}
}
if (option.callback) {
if (scope !== 'local') {
option.callback(value, undefined);
}
if (scope !== 'global' && cm) {
option.callback(value, cm);
}
} else {
if (scope !== 'local') {
option.value = option.type == 'boolean' ? !!value : value;
}
if (scope !== 'global' && cm) {
cm.state.vim.options[name] = {value: value};
}
}
}
function getOption(name, cm, cfg) {
var option = options[name];
cfg = cfg || {};
var scope = cfg.scope;
if (!option) {
return new Error('Unknown option: ' + name);
}
if (option.callback) {
var local = cm && option.callback(undefined, cm);
if (scope !== 'global' && local !== undefined) {
return local;
}
if (scope !== 'local') {
return option.callback();
}
return;
} else {
var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
return (local || (scope !== 'local') && option || {}).value;
}
}
defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
// Option is local. Do nothing for global.
if (cm === undefined) {
return;
}
// The 'filetype' option proxies to the CodeMirror 'mode' option.
if (name === undefined) {
var mode = cm.getOption('mode');
return mode == 'null' ? '' : mode;
} else {
var mode = name == '' ? 'null' : name;
cm.setOption('mode', mode);
}
});
var createCircularJumpList = function() {
var size = 100;
var pointer = -1;
var head = 0;
var tail = 0;
var buffer = new Array(size);
function add(cm, oldCur, newCur) {
var current = pointer % size;
var curMark = buffer[current];
function useNextSlot(cursor) {
var next = ++pointer % size;
var trashMark = buffer[next];
if (trashMark) {
trashMark.clear();
}
buffer[next] = cm.setBookmark(cursor);
}
if (curMark) {
var markPos = curMark.find();
// avoid recording redundant cursor position
if (markPos && !cursorEqual(markPos, oldCur)) {
useNextSlot(oldCur);
}
} else {
useNextSlot(oldCur);
}
useNextSlot(newCur);
head = pointer;
tail = pointer - size + 1;
if (tail < 0) {
tail = 0;
}
}
function move(cm, offset) {
pointer += offset;
if (pointer > head) {
pointer = head;
} else if (pointer < tail) {
pointer = tail;
}
var mark = buffer[(size + pointer) % size];
// skip marks that are temporarily removed from text buffer
if (mark && !mark.find()) {
var inc = offset > 0 ? 1 : -1;
var newCur;
var oldCur = cm.getCursor();
do {
pointer += inc;
mark = buffer[(size + pointer) % size];
// skip marks that are the same as current position
if (mark &&
(newCur = mark.find()) &&
!cursorEqual(oldCur, newCur)) {
break;
}
} while (pointer < head && pointer > tail);
}
return mark;
}
function find(cm, offset) {
var oldPointer = pointer;
var mark = move(cm, offset);
pointer = oldPointer;
return mark && mark.find();
}
return {
cachedCursor: undefined, //used for # and * jumps
add: add,
find: find,
move: move
};
};
// Returns an object to track the changes associated insert mode. It
// clones the object that is passed in, or creates an empty object one if
// none is provided.
var createInsertModeChanges = function(c) {
if (c) {
// Copy construction
return {
changes: c.changes,
expectCursorActivityForChange: c.expectCursorActivityForChange
};
}
return {
// Change list
changes: [],
// Set to true on change, false on cursorActivity.
expectCursorActivityForChange: false
};
};
function MacroModeState() {
this.latestRegister = undefined;
this.isPlaying = false;
this.isRecording = false;
this.replaySearchQueries = [];
this.onRecordingDone = undefined;
this.lastInsertModeChanges = createInsertModeChanges();
}
MacroModeState.prototype = {
exitMacroRecordMode: function() {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.onRecordingDone) {
macroModeState.onRecordingDone(); // close dialog
}
macroModeState.onRecordingDone = undefined;
macroModeState.isRecording = false;
},
enterMacroRecordMode: function(cm, registerName) {
var register =
vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.clear();
this.latestRegister = registerName;
if (cm.openDialog) {
this.onRecordingDone = cm.openDialog(
document.createTextNode('(recording)['+registerName+']'), null, {bottom:true});
}
this.isRecording = true;
}
}
};
function maybeInitVimState(cm) {
if (!cm.state.vim) {
// Store instance state in the CodeMirror object.
cm.state.vim = {
inputState: new InputState(),
// Vim's input state that triggered the last edit, used to repeat
// motions and operators with '.'.
lastEditInputState: undefined,
// Vim's action command before the last edit, used to repeat actions
// with '.' and insert mode repeat.
lastEditActionCommand: undefined,
// When using jk for navigation, if you move from a longer line to a
// shorter line, the cursor may clip to the end of the shorter line.
// If j is pressed again and cursor goes to the next line, the
// cursor should go back to its horizontal position on the longer
// line if it can. This is to keep track of the horizontal position.
lastHPos: -1,
// Doing the same with screen-position for gj/gk
lastHSPos: -1,
// The last motion command run. Cleared if a non-motion command gets
// executed in between.
lastMotion: null,
marks: {},
insertMode: false,
// Repeat count for changes made in insert mode, triggered by key
// sequences like 3,i. Only exists when insertMode is true.
insertModeRepeat: undefined,
visualMode: false,
// If we are in visual line mode. No effect if visualMode is false.
visualLine: false,
visualBlock: false,
lastSelection: null,
lastPastedText: null,
sel: {},
// Buffer-local/window-local values of vim options.
options: {}
};
}
return cm.state.vim;
}
var vimGlobalState;
function resetVimGlobalState() {
vimGlobalState = {
// The current search query.
searchQuery: null,
// Whether we are searching backwards.
searchIsReversed: false,
// Replace part of the last substituted pattern
lastSubstituteReplacePart: undefined,
jumpList: createCircularJumpList(),
macroModeState: new MacroModeState,
// Recording latest f, t, F or T motion command.
lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
registerController: new RegisterController({}),
// search history buffer
searchHistoryController: new HistoryController(),
// ex Command history buffer
exCommandHistoryController : new HistoryController()
};
for (var optionName in options) {
var option = options[optionName];
option.value = option.defaultValue;
}
}
var lastInsertModeKeyTimer;
var vimApi= {
buildKeyMap: function() {
// TODO: Convert keymap into dictionary format for fast lookup.
},
// Testing hook, though it might be useful to expose the register
// controller anyway.
getRegisterController: function() {
return vimGlobalState.registerController;
},
// Testing hook.
resetVimGlobalState_: resetVimGlobalState,
// Testing hook.
getVimGlobalState_: function() {
return vimGlobalState;
},
// Testing hook.
maybeInitVimState_: maybeInitVimState,
suppressErrorLogging: false,
InsertModeKey: InsertModeKey,
map: function(lhs, rhs, ctx) {
// Add user defined key bindings.
exCommandDispatcher.map(lhs, rhs, ctx);
},
unmap: function(lhs, ctx) {
return exCommandDispatcher.unmap(lhs, ctx);
},
// Non-recursive map function.
// NOTE: This will not create mappings to key maps that aren't present
// in the default key map. See TODO at bottom of function.
noremap: function(lhs, rhs, ctx) {
function toCtxArray(ctx) {
return ctx ? [ctx] : ['normal', 'insert', 'visual'];
}
var ctxsToMap = toCtxArray(ctx);
// Look through all actual defaults to find a map candidate.
var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;
for (var i = actualLength - origLength;
i < actualLength && ctxsToMap.length;
i++) {
var mapping = defaultKeymap[i];
// Omit mappings that operate in the wrong context(s) and those of invalid type.
if (mapping.keys == rhs &&
(!ctx || !mapping.context || mapping.context === ctx) &&
mapping.type.substr(0, 2) !== 'ex' &&
mapping.type.substr(0, 3) !== 'key') {
// Make a shallow copy of the original keymap entry.
var newMapping = {};
for (var key in mapping) {
newMapping[key] = mapping[key];
}
// Modify it point to the new mapping with the proper context.
newMapping.keys = lhs;
if (ctx && !newMapping.context) {
newMapping.context = ctx;
}
// Add it to the keymap with a higher priority than the original.
this._mapCommand(newMapping);
// Record the mapped contexts as complete.
var mappedCtxs = toCtxArray(mapping.context);
ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; });
}
}
// TODO: Create non-recursive keyToKey mappings for the unmapped contexts once those exist.
},
// Remove all user-defined mappings for the provided context.
mapclear: function(ctx) {
// Partition the existing keymap into user-defined and true defaults.
var actualLength = defaultKeymap.length,
origLength = defaultKeymapLength;
var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
defaultKeymap = defaultKeymap.slice(actualLength - origLength);
if (ctx) {
// If a specific context is being cleared, we need to keep mappings
// from all other contexts.
for (var i = userKeymap.length - 1; i >= 0; i--) {
var mapping = userKeymap[i];
if (ctx !== mapping.context) {
if (mapping.context) {
this._mapCommand(mapping);
} else {
// `mapping` applies to all contexts so create keymap copies
// for each context except the one being cleared.
var contexts = ['normal', 'insert', 'visual'];
for (var j in contexts) {
if (contexts[j] !== ctx) {
var newMapping = {};
for (var key in mapping) {
newMapping[key] = mapping[key];
}
newMapping.context = contexts[j];
this._mapCommand(newMapping);
}
}
}
}
}
}
},
// TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace
// them, or somehow make them work with the existing CodeMirror setOption/getOption API.
setOption: setOption,
getOption: getOption,
defineOption: defineOption,
defineEx: function(name, prefix, func){
if (!prefix) {
prefix = name;
} else if (name.indexOf(prefix) !== 0) {
throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
}
exCommands[name]=func;
exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
},
handleKey: function (cm, key, origin) {
var command = this.findKey(cm, key, origin);
if (typeof command === 'function') {
return command();
}
},
/**
* This is the outermost function called by CodeMirror, after keys have
* been mapped to their Vim equivalents.
*
* Finds a command based on the key (and cached keys if there is a
* multi-key sequence). Returns `undefined` if no key is matched, a noop
* function if a partial match is found (multi-key), and a function to
* execute the bound command if a a key is matched. The function always
* returns true.
*/
findKey: function(cm, key, origin) {
var vim = maybeInitVimState(cm);
function handleMacroRecording() {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isRecording) {
if (key == 'q') {
macroModeState.exitMacroRecordMode();
clearInputState(cm);
return true;
}
if (origin != 'mapping') {
logKey(macroModeState, key);
}
}
}
function handleEsc() {
if (key == '<Esc>') {
// Clear input state and get back to normal mode.
clearInputState(cm);
if (vim.visualMode) {
exitVisualMode(cm);
} else if (vim.insertMode) {
exitInsertMode(cm);
}
return true;
}
}
function doKeyToKey(keys) {
// TODO: prevent infinite recursion.
var match;
while (keys) {
// Pull off one command key, which is either a single character
// or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
match = (/<\w+-.+?>|<\w+>|./).exec(keys);
key = match[0];
keys = keys.substring(match.index + key.length);
vimApi.handleKey(cm, key, 'mapping');
}
}
function handleKeyInsertMode() {
if (handleEsc()) { return true; }
var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
var keysAreChars = key.length == 1;
var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
// Need to check all key substrings in insert mode.
while (keys.length > 1 && match.type != 'full') {
var keys = vim.inputState.keyBuffer = keys.slice(1);
var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
if (thisMatch.type != 'none') { match = thisMatch; }
}
if (match.type == 'none') { clearInputState(cm); return false; }
else if (match.type == 'partial') {
if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
lastInsertModeKeyTimer = window.setTimeout(
function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
getOption('insertModeEscKeysTimeout'));
return !keysAreChars;
}
if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
if (keysAreChars) {
var selections = cm.listSelections();
for (var i = 0; i < selections.length; i++) {
var here = selections[i].head;
cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
}
vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
}
clearInputState(cm);
return match.command;
}
function handleKeyNonInsertMode() {
if (handleMacroRecording() || handleEsc()) { return true; }
var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
if (/^[1-9]\d*$/.test(keys)) { return true; }
var keysMatcher = /^(\d*)(.*)$/.exec(keys);
if (!keysMatcher) { clearInputState(cm); return false; }
var context = vim.visualMode ? 'visual' :
'normal';
var mainKey = keysMatcher[2] || keysMatcher[1];
if (vim.inputState.operatorShortcut && vim.inputState.operatorShortcut.slice(-1) == mainKey) {
// multikey operators act linewise by repeating only the last character
mainKey = vim.inputState.operatorShortcut;
}
var match = commandDispatcher.matchCommand(mainKey, defaultKeymap, vim.inputState, context);
if (match.type == 'none') { clearInputState(cm); return false; }
else if (match.type == 'partial') { return true; }
vim.inputState.keyBuffer = '';
var keysMatcher = /^(\d*)(.*)$/.exec(keys);
if (keysMatcher[1] && keysMatcher[1] != '0') {
vim.inputState.pushRepeatDigit(keysMatcher[1]);
}
return match.command;
}
var command;
if (vim.insertMode) { command = handleKeyInsertMode(); }
else { command = handleKeyNonInsertMode(); }
if (command === false) {
return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined;
} else if (command === true) {
// TODO: Look into using CodeMirror's multi-key handling.
// Return no-op since we are caching the key. Counts as handled, but
// don't want act on it just yet.
return function() { return true; };
} else {
return function() {
return cm.operation(function() {
cm.curOp.isVimOp = true;
try {
if (command.type == 'keyToKey') {
doKeyToKey(command.toKeys);
} else {
commandDispatcher.processCommand(cm, vim, command);
}
} catch (e) {
// clear VIM state in case it's in a bad state.
cm.state.vim = undefined;
maybeInitVimState(cm);
if (!vimApi.suppressErrorLogging) {
console['log'](e);
}
throw e;
}
return true;
});
};
}
},
handleEx: function(cm, input) {
exCommandDispatcher.processCommand(cm, input);
},
defineMotion: defineMotion,
defineAction: defineAction,
defineOperator: defineOperator,
mapCommand: mapCommand,
_mapCommand: _mapCommand,
defineRegister: defineRegister,
exitVisualMode: exitVisualMode,
exitInsertMode: exitInsertMode
};
// Represents the current input state.
function InputState() {
this.prefixRepeat = [];
this.motionRepeat = [];
this.operator = null;
this.operatorArgs = null;
this.motion = null;
this.motionArgs = null;
this.keyBuffer = []; // For matching multi-key commands.
this.registerName = null; // Defaults to the unnamed register.
}
InputState.prototype.pushRepeatDigit = function(n) {
if (!this.operator) {
this.prefixRepeat = this.prefixRepeat.concat(n);
} else {
this.motionRepeat = this.motionRepeat.concat(n);
}
};
InputState.prototype.getRepeat = function() {
var repeat = 0;
if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
repeat = 1;
if (this.prefixRepeat.length > 0) {
repeat *= parseInt(this.prefixRepeat.join(''), 10);
}
if (this.motionRepeat.length > 0) {
repeat *= parseInt(this.motionRepeat.join(''), 10);
}
}
return repeat;
};
function clearInputState(cm, reason) {
cm.state.vim.inputState = new InputState();
CodeMirror.signal(cm, 'vim-command-done', reason);
}
/*
* Register stores information about copy and paste registers. Besides
* text, a register must store whether it is linewise (i.e., when it is
* pasted, should it insert itself into a new line, or should the text be
* inserted at the cursor position.)
*/
function Register(text, linewise, blockwise) {
this.clear();
this.keyBuffer = [text || ''];
this.insertModeChanges = [];
this.searchQueries = [];
this.linewise = !!linewise;
this.blockwise = !!blockwise;
}
Register.prototype = {
setText: function(text, linewise, blockwise) {
this.keyBuffer = [text || ''];
this.linewise = !!linewise;
this.blockwise = !!blockwise;
},
pushText: function(text, linewise) {
// if this register has ever been set to linewise, use linewise.
if (linewise) {
if (!this.linewise) {
this.keyBuffer.push('\n');
}
this.linewise = true;
}
this.keyBuffer.push(text);
},
pushInsertModeChanges: function(changes) {
this.insertModeChanges.push(createInsertModeChanges(changes));
},
pushSearchQuery: function(query) {
this.searchQueries.push(query);
},
clear: function() {
this.keyBuffer = [];
this.insertModeChanges = [];
this.searchQueries = [];
this.linewise = false;
},
toString: function() {
return this.keyBuffer.join('');
}
};
/**
* Defines an external register.
*
* The name should be a single character that will be used to reference the register.
* The register should support setText, pushText, clear, and toString(). See Register
* for a reference implementation.
*/
function defineRegister(name, register) {
var registers = vimGlobalState.registerController.registers;
if (!name || name.length != 1) {
throw Error('Register name must be 1 character');
}
if (registers[name]) {
throw Error('Register already defined ' + name);
}
registers[name] = register;
validRegisters.push(name);
}
/*
* vim registers allow you to keep many independent copy and paste buffers.
* See http://usevim.com/2012/04/13/registers/ for an introduction.
*
* RegisterController keeps the state of all the registers. An initial
* state may be passed in. The unnamed register '"' will always be
* overridden.
*/
function RegisterController(registers) {
this.registers = registers;
this.unnamedRegister = registers['"'] = new Register();
registers['.'] = new Register();
registers[':'] = new Register();
registers['/'] = new Register();
}
RegisterController.prototype = {
pushText: function(registerName, operator, text, linewise, blockwise) {
// The black hole register, "_, means delete/yank to nowhere.
if (registerName === '_') return;
if (linewise && text.charAt(text.length - 1) !== '\n'){
text += '\n';
}
// Lowercase and uppercase registers refer to the same register.
// Uppercase just means append.
var register = this.isValidRegister(registerName) ?
this.getRegister(registerName) : null;
// if no register/an invalid register was specified, things go to the
// default registers
if (!register) {
switch (operator) {
case 'yank':
// The 0 register contains the text from the most recent yank.
this.registers['0'] = new Register(text, linewise, blockwise);
break;
case 'delete':
case 'change':
if (text.indexOf('\n') == -1) {
// Delete less than 1 line. Update the small delete register.
this.registers['-'] = new Register(text, linewise);
} else {
// Shift down the contents of the numbered registers and put the
// deleted text into register 1.
this.shiftNumericRegisters_();
this.registers['1'] = new Register(text, linewise);
}
break;
}
// Make sure the unnamed register is set to what just happened
this.unnamedRegister.setText(text, linewise, blockwise);
return;
}
// If we've gotten to this point, we've actually specified a register
var append = isUpperCase(registerName);
if (append) {
register.pushText(text, linewise);
} else {
register.setText(text, linewise, blockwise);
}
// The unnamed register always has the same value as the last used
// register.
this.unnamedRegister.setText(register.toString(), linewise);
},
// Gets the register named @name. If one of @name doesn't already exist,
// create it. If @name is invalid, return the unnamedRegister.
getRegister: function(name) {
if (!this.isValidRegister(name)) {
return this.unnamedRegister;
}
name = name.toLowerCase();
if (!this.registers[name]) {
this.registers[name] = new Register();
}
return this.registers[name];
},
isValidRegister: function(name) {
return name && inArray(name, validRegisters);
},
shiftNumericRegisters_: function() {
for (var i = 9; i >= 2; i--) {
this.registers[i] = this.getRegister('' + (i - 1));
}
}
};
function HistoryController() {
this.historyBuffer = [];
this.iterator = 0;
this.initialPrefix = null;
}
HistoryController.prototype = {
// the input argument here acts a user entered prefix for a small time
// until we start autocompletion in which case it is the autocompleted.
nextMatch: function (input, up) {
var historyBuffer = this.historyBuffer;
var dir = up ? -1 : 1;
if (this.initialPrefix === null) this.initialPrefix = input;
for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
var element = historyBuffer[i];
for (var j = 0; j <= element.length; j++) {
if (this.initialPrefix == element.substring(0, j)) {
this.iterator = i;
return element;
}
}
}
// should return the user input in case we reach the end of buffer.
if (i >= historyBuffer.length) {
this.iterator = historyBuffer.length;
return this.initialPrefix;
}
// return the last autocompleted query or exCommand as it is.
if (i < 0 ) return input;
},
pushInput: function(input) {
var index = this.historyBuffer.indexOf(input);
if (index > -1) this.historyBuffer.splice(index, 1);
if (input.length) this.historyBuffer.push(input);
},
reset: function() {
this.initialPrefix = null;
this.iterator = this.historyBuffer.length;
}
};
var commandDispatcher = {
matchCommand: function(keys, keyMap, inputState, context) {
var matches = commandMatches(keys, keyMap, context, inputState);
if (!matches.full && !matches.partial) {
return {type: 'none'};
} else if (!matches.full && matches.partial) {
return {type: 'partial'};
}
var bestMatch;
for (var i = 0; i < matches.full.length; i++) {
var match = matches.full[i];
if (!bestMatch) {
bestMatch = match;
}
}
if (bestMatch.keys.slice(-11) == '<character>') {
var character = lastChar(keys);
if (!character) return {type: 'none'};
inputState.selectedCharacter = character;
}
return {type: 'full', command: bestMatch};
},
processCommand: function(cm, vim, command) {
vim.inputState.repeatOverride = command.repeatOverride;
switch (command.type) {
case 'motion':
this.processMotion(cm, vim, command);
break;
case 'operator':
this.processOperator(cm, vim, command);
break;
case 'operatorMotion':
this.processOperatorMotion(cm, vim, command);
break;
case 'action':
this.processAction(cm, vim, command);
break;
case 'search':
this.processSearch(cm, vim, command);
break;
case 'ex':
case 'keyToEx':
this.processEx(cm, vim, command);
break;
default:
break;
}
},
processMotion: function(cm, vim, command) {
vim.inputState.motion = command.motion;
vim.inputState.motionArgs = copyArgs(command.motionArgs);
this.evalInput(cm, vim);
},
processOperator: function(cm, vim, command) {
var inputState = vim.inputState;
if (inputState.operator) {
if (inputState.operator == command.operator) {
// Typing an operator twice like 'dd' makes the operator operate
// linewise
inputState.motion = 'expandToLine';
inputState.motionArgs = { linewise: true };
this.evalInput(cm, vim);
return;
} else {
// 2 different operators in a row doesn't make sense.
clearInputState(cm);
}
}
inputState.operator = command.operator;
inputState.operatorArgs = copyArgs(command.operatorArgs);
if (command.keys.length > 1) {
inputState.operatorShortcut = command.keys;
}
if (command.exitVisualBlock) {
vim.visualBlock = false;
updateCmSelection(cm);
}
if (vim.visualMode) {
// Operating on a selection in visual mode. We don't need a motion.
this.evalInput(cm, vim);
}
},
processOperatorMotion: function(cm, vim, command) {
var visualMode = vim.visualMode;
var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
if (operatorMotionArgs) {
// Operator motions may have special behavior in visual mode.
if (visualMode && operatorMotionArgs.visualLine) {
vim.visualLine = true;
}
}
this.processOperator(cm, vim, command);
if (!visualMode) {
this.processMotion(cm, vim, command);
}
},
processAction: function(cm, vim, command) {
var inputState = vim.inputState;
var repeat = inputState.getRepeat();
var repeatIsExplicit = !!repeat;
var actionArgs = copyArgs(command.actionArgs) || {};
if (inputState.selectedCharacter) {
actionArgs.selectedCharacter = inputState.selectedCharacter;
}
// Actions may or may not have motions and operators. Do these first.
if (command.operator) {
this.processOperator(cm, vim, command);
}
if (command.motion) {
this.processMotion(cm, vim, command);
}
if (command.motion || command.operator) {
this.evalInput(cm, vim);
}
actionArgs.repeat = repeat || 1;
actionArgs.repeatIsExplicit = repeatIsExplicit;
actionArgs.registerName = inputState.registerName;
clearInputState(cm);
vim.lastMotion = null;
if (command.isEdit) {
this.recordLastEdit(vim, inputState, command);
}
actions[command.action](cm, actionArgs, vim);
},
processSearch: function(cm, vim, command) {
if (!cm.getSearchCursor) {
// Search depends on SearchCursor.
return;
}
var forward = command.searchArgs.forward;
var wholeWordOnly = command.searchArgs.wholeWordOnly;
getSearchState(cm).setReversed(!forward);
var promptPrefix = (forward) ? '/' : '?';
var originalQuery = getSearchState(cm).getQuery();
var originalScrollPos = cm.getScrollInfo();
function handleQuery(query, ignoreCase, smartCase) {
vimGlobalState.searchHistoryController.pushInput(query);
vimGlobalState.searchHistoryController.reset();
try {
updateSearchQuery(cm, query, ignoreCase, smartCase);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + query);
clearInputState(cm);
return;
}
commandDispatcher.processMotion(cm, vim, {
type: 'motion',
motion: 'findNext',
motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
});
}
function onPromptClose(query) {
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
handleQuery(query, true /** ignoreCase */, true /** smartCase */);
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isRecording) {
logSearchQuery(macroModeState, query);
}
}
function onPromptKeyUp(e, query, close) {
var keyName = CodeMirror.keyName(e), up, offset;
if (keyName == 'Up' || keyName == 'Down') {
up = keyName == 'Up' ? true : false;
offset = e.target ? e.target.selectionEnd : 0;
query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
close(query);
if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
} else {
if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
vimGlobalState.searchHistoryController.reset();
}
var parsedQuery;
try {
parsedQuery = updateSearchQuery(cm, query,
true /** ignoreCase */, true /** smartCase */);
} catch (e) {
// Swallow bad regexes for incremental search.
}
if (parsedQuery) {
cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
} else {
clearSearchHighlight(cm);
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
}
}
function onPromptKeyDown(e, query, close) {
var keyName = CodeMirror.keyName(e);
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
(keyName == 'Backspace' && query == '')) {
vimGlobalState.searchHistoryController.pushInput(query);
vimGlobalState.searchHistoryController.reset();
updateSearchQuery(cm, originalQuery);
clearSearchHighlight(cm);
cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
CodeMirror.e_stop(e);
clearInputState(cm);
close();
cm.focus();
} else if (keyName == 'Up' || keyName == 'Down') {
CodeMirror.e_stop(e);
} else if (keyName == 'Ctrl-U') {
// Ctrl-U clears input.
CodeMirror.e_stop(e);
close('');
}
}
switch (command.searchArgs.querySrc) {
case 'prompt':
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) {
var query = macroModeState.replaySearchQueries.shift();
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
} else {
showPrompt(cm, {
onClose: onPromptClose,
prefix: promptPrefix,
desc: '(JavaScript regexp)',
onKeyUp: onPromptKeyUp,
onKeyDown: onPromptKeyDown
});
}
break;
case 'wordUnderCursor':
var word = expandWordUnderCursor(cm, false /** inclusive */,
true /** forward */, false /** bigWord */,
true /** noSymbol */);
var isKeyword = true;
if (!word) {
word = expandWordUnderCursor(cm, false /** inclusive */,
true /** forward */, false /** bigWord */,
false /** noSymbol */);
isKeyword = false;
}
if (!word) {
return;
}
var query = cm.getLine(word.start.line).substring(word.start.ch,
word.end.ch);
if (isKeyword && wholeWordOnly) {
query = '\\b' + query + '\\b';
} else {
query = escapeRegex(query);
}
// cachedCursor is used to save the old position of the cursor
// when * or # causes vim to seek for the nearest word and shift
// the cursor before entering the motion.
vimGlobalState.jumpList.cachedCursor = cm.getCursor();
cm.setCursor(word.start);
handleQuery(query, true /** ignoreCase */, false /** smartCase */);
break;
}
},
processEx: function(cm, vim, command) {
function onPromptClose(input) {
// Give the prompt some time to close so that if processCommand shows
// an error, the elements don't overlap.
vimGlobalState.exCommandHistoryController.pushInput(input);
vimGlobalState.exCommandHistoryController.reset();
exCommandDispatcher.processCommand(cm, input);
}
function onPromptKeyDown(e, input, close) {
var keyName = CodeMirror.keyName(e), up, offset;
if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
(keyName == 'Backspace' && input == '')) {
vimGlobalState.exCommandHistoryController.pushInput(input);
vimGlobalState.exCommandHistoryController.reset();
CodeMirror.e_stop(e);
clearInputState(cm);
close();
cm.focus();
}
if (keyName == 'Up' || keyName == 'Down') {
CodeMirror.e_stop(e);
up = keyName == 'Up' ? true : false;
offset = e.target ? e.target.selectionEnd : 0;
input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
close(input);
if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
} else if (keyName == 'Ctrl-U') {
// Ctrl-U clears input.
CodeMirror.e_stop(e);
close('');
} else {
if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
vimGlobalState.exCommandHistoryController.reset();
}
}
if (command.type == 'keyToEx') {
// Handle user defined Ex to Ex mappings
exCommandDispatcher.processCommand(cm, command.exArgs.input);
} else {
if (vim.visualMode) {
showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
} else {
showPrompt(cm, { onClose: onPromptClose, prefix: ':',
onKeyDown: onPromptKeyDown});
}
}
},
evalInput: function(cm, vim) {
// If the motion command is set, execute both the operator and motion.
// Otherwise return.
var inputState = vim.inputState;
var motion = inputState.motion;
var motionArgs = inputState.motionArgs || {};
var operator = inputState.operator;
var operatorArgs = inputState.operatorArgs || {};
var registerName = inputState.registerName;
var sel = vim.sel;
// TODO: Make sure cm and vim selections are identical outside visual mode.
var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
var oldHead = copyCursor(origHead);
var oldAnchor = copyCursor(origAnchor);
var newHead, newAnchor;
var repeat;
if (operator) {
this.recordLastEdit(vim, inputState);
}
if (inputState.repeatOverride !== undefined) {
// If repeatOverride is specified, that takes precedence over the
// input state's repeat. Used by Ex mode and can be user defined.
repeat = inputState.repeatOverride;
} else {
repeat = inputState.getRepeat();
}
if (repeat > 0 && motionArgs.explicitRepeat) {
motionArgs.repeatIsExplicit = true;
} else if (motionArgs.noRepeat ||
(!motionArgs.explicitRepeat && repeat === 0)) {
repeat = 1;
motionArgs.repeatIsExplicit = false;
}
if (inputState.selectedCharacter) {
// If there is a character input, stick it in all of the arg arrays.
motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
inputState.selectedCharacter;
}
motionArgs.repeat = repeat;
clearInputState(cm);
if (motion) {
var motionResult = motions[motion](cm, origHead, motionArgs, vim, inputState);
vim.lastMotion = motions[motion];
if (!motionResult) {
return;
}
if (motionArgs.toJumplist) {
var jumpList = vimGlobalState.jumpList;
// if the current motion is # or *, use cachedCursor
var cachedCursor = jumpList.cachedCursor;
if (cachedCursor) {
recordJumpPosition(cm, cachedCursor, motionResult);
delete jumpList.cachedCursor;
} else {
recordJumpPosition(cm, origHead, motionResult);
}
}
if (motionResult instanceof Array) {
newAnchor = motionResult[0];
newHead = motionResult[1];
} else {
newHead = motionResult;
}
// TODO: Handle null returns from motion commands better.
if (!newHead) {
newHead = copyCursor(origHead);
}
if (vim.visualMode) {
if (!(vim.visualBlock && newHead.ch === Infinity)) {
newHead = clipCursorToContent(cm, newHead);
}
if (newAnchor) {
newAnchor = clipCursorToContent(cm, newAnchor);
}
newAnchor = newAnchor || oldAnchor;
sel.anchor = newAnchor;
sel.head = newHead;
updateCmSelection(cm);
updateMark(cm, vim, '<',
cursorIsBefore(newAnchor, newHead) ? newAnchor
: newHead);
updateMark(cm, vim, '>',
cursorIsBefore(newAnchor, newHead) ? newHead
: newAnchor);
} else if (!operator) {
newHead = clipCursorToContent(cm, newHead);
cm.setCursor(newHead.line, newHead.ch);
}
}
if (operator) {
if (operatorArgs.lastSel) {
// Replaying a visual mode operation
newAnchor = oldAnchor;
var lastSel = operatorArgs.lastSel;
var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
if (lastSel.visualLine) {
// Linewise Visual mode: The same number of lines.
newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
} else if (lastSel.visualBlock) {
// Blockwise Visual mode: The same number of lines and columns.
newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
} else if (lastSel.head.line == lastSel.anchor.line) {
// Normal Visual mode within one line: The same number of characters.
newHead = new Pos(oldAnchor.line, oldAnchor.ch + chOffset);
} else {
// Normal Visual mode with several lines: The same number of lines, in the
// last line the same number of characters as in the last line the last time.
newHead = new Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
}
vim.visualMode = true;
vim.visualLine = lastSel.visualLine;
vim.visualBlock = lastSel.visualBlock;
sel = vim.sel = {
anchor: newAnchor,
head: newHead
};
updateCmSelection(cm);
} else if (vim.visualMode) {
operatorArgs.lastSel = {
anchor: copyCursor(sel.anchor),
head: copyCursor(sel.head),
visualBlock: vim.visualBlock,
visualLine: vim.visualLine
};
}
var curStart, curEnd, linewise, mode;
var cmSel;
if (vim.visualMode) {
// Init visual op
curStart = cursorMin(sel.head, sel.anchor);
curEnd = cursorMax(sel.head, sel.anchor);
linewise = vim.visualLine || operatorArgs.linewise;
mode = vim.visualBlock ? 'block' :
linewise ? 'line' :
'char';
cmSel = makeCmSelection(cm, {
anchor: curStart,
head: curEnd
}, mode);
if (linewise) {
var ranges = cmSel.ranges;
if (mode == 'block') {
// Linewise operators in visual block mode extend to end of line
for (var i = 0; i < ranges.length; i++) {
ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
}
} else if (mode == 'line') {
ranges[0].head = new Pos(ranges[0].head.line + 1, 0);
}
}
} else {
// Init motion op
curStart = copyCursor(newAnchor || oldAnchor);
curEnd = copyCursor(newHead || oldHead);
if (cursorIsBefore(curEnd, curStart)) {
var tmp = curStart;
curStart = curEnd;
curEnd = tmp;
}
linewise = motionArgs.linewise || operatorArgs.linewise;
if (linewise) {
// Expand selection to entire line.
expandSelectionToLine(cm, curStart, curEnd);
} else if (motionArgs.forward) {
// Clip to trailing newlines only if the motion goes forward.
clipToLine(cm, curStart, curEnd);
}
mode = 'char';
var exclusive = !motionArgs.inclusive || linewise;
cmSel = makeCmSelection(cm, {
anchor: curStart,
head: curEnd
}, mode, exclusive);
}
cm.setSelections(cmSel.ranges, cmSel.primary);
vim.lastMotion = null;
operatorArgs.repeat = repeat; // For indent in visual mode.
operatorArgs.registerName = registerName;
// Keep track of linewise as it affects how paste and change behave.
operatorArgs.linewise = linewise;
var operatorMoveTo = operators[operator](
cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
if (vim.visualMode) {
exitVisualMode(cm, operatorMoveTo != null);
}
if (operatorMoveTo) {
cm.setCursor(operatorMoveTo);
}
}
},
recordLastEdit: function(vim, inputState, actionCommand) {
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) { return; }
vim.lastEditInputState = inputState;
vim.lastEditActionCommand = actionCommand;
macroModeState.lastInsertModeChanges.changes = [];
macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
macroModeState.lastInsertModeChanges.visualBlock = vim.visualBlock ? vim.sel.head.line - vim.sel.anchor.line : 0;
}
};
/**
* typedef {Object{line:number,ch:number}} Cursor An object containing the
* position of the cursor.
*/
// All of the functions below return Cursor objects.
var motions = {
moveToTopLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
moveToMiddleLine: function(cm) {
var range = getUserVisibleLines(cm);
var line = Math.floor((range.top + range.bottom) * 0.5);
return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
moveToBottomLine: function(cm, _head, motionArgs) {
var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
return new Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
},
expandToLine: function(_cm, head, motionArgs) {
// Expands forward to end of line, and then to next line if repeat is
// >1. Does not handle backward motion!
var cur = head;
return new Pos(cur.line + motionArgs.repeat - 1, Infinity);
},
findNext: function(cm, _head, motionArgs) {
var state = getSearchState(cm);
var query = state.getQuery();
if (!query) {
return;
}
var prev = !motionArgs.forward;
// If search is initiated with ? instead of /, negate direction.
prev = (state.isReversed()) ? !prev : prev;
highlightSearchMatches(cm, query);
return findNext(cm, prev/** prev */, query, motionArgs.repeat);
},
/**
* Find and select the next occurrence of the search query. If the cursor is currently
* within a match, then find and select the current match. Otherwise, find the next occurrence in the
* appropriate direction.
*
* This differs from `findNext` in the following ways:
*
* 1. Instead of only returning the "from", this returns a "from", "to" range.
* 2. If the cursor is currently inside a search match, this selects the current match
* instead of the next match.
* 3. If there is no associated operator, this will turn on visual mode.
*/
findAndSelectNextInclusive: function(cm, _head, motionArgs, vim, prevInputState) {
var state = getSearchState(cm);
var query = state.getQuery();
if (!query) {
return;
}
var prev = !motionArgs.forward;
prev = (state.isReversed()) ? !prev : prev;
// next: [from, to] | null
var next = findNextFromAndToInclusive(cm, prev, query, motionArgs.repeat, vim);
// No matches.
if (!next) {
return;
}
// If there's an operator that will be executed, return the selection.
if (prevInputState.operator) {
return next;
}
// At this point, we know that there is no accompanying operator -- let's
// deal with visual mode in order to select an appropriate match.
var from = next[0];
// For whatever reason, when we use the "to" as returned by searchcursor.js directly,
// the resulting selection is extended by 1 char. Let's shrink it so that only the
// match is selected.
var to = new Pos(next[1].line, next[1].ch - 1);
if (vim.visualMode) {
// If we were in visualLine or visualBlock mode, get out of it.
if (vim.visualLine || vim.visualBlock) {
vim.visualLine = false;
vim.visualBlock = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
}
// If we're currently in visual mode, we should extend the selection to include
// the search result.
var anchor = vim.sel.anchor;
if (anchor) {
if (state.isReversed()) {
if (motionArgs.forward) {
return [anchor, from];
}
return [anchor, to];
} else {
if (motionArgs.forward) {
return [anchor, to];
}
return [anchor, from];
}
}
} else {
// Let's turn visual mode on.
vim.visualMode = true;
vim.visualLine = false;
vim.visualBlock = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: ""});
}
return prev ? [to, from] : [from, to];
},
goToMark: function(cm, _head, motionArgs, vim) {
var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
if (pos) {
return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
}
return null;
},
moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
if (vim.visualBlock && motionArgs.sameLine) {
var sel = vim.sel;
return [
clipCursorToContent(cm, new Pos(sel.anchor.line, sel.head.ch)),
clipCursorToContent(cm, new Pos(sel.head.line, sel.anchor.ch))
];
} else {
return ([vim.sel.head, vim.sel.anchor]);
}
},
jumpToMark: function(cm, head, motionArgs, vim) {
var best = head;
for (var i = 0; i < motionArgs.repeat; i++) {
var cursor = best;
for (var key in vim.marks) {
if (!isLowerCase(key)) {
continue;
}
var mark = vim.marks[key].find();
var isWrongDirection = (motionArgs.forward) ?
cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
if (isWrongDirection) {
continue;
}
if (motionArgs.linewise && (mark.line == cursor.line)) {
continue;
}
var equal = cursorEqual(cursor, best);
var between = (motionArgs.forward) ?
cursorIsBetween(cursor, mark, best) :
cursorIsBetween(best, mark, cursor);
if (equal || between) {
best = mark;
}
}
}
if (motionArgs.linewise) {
// Vim places the cursor on the first non-whitespace character of
// the line if there is one, else it places the cursor at the end
// of the line, regardless of whether a mark was found.
best = new Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
}
return best;
},
moveByCharacters: function(_cm, head, motionArgs) {
var cur = head;
var repeat = motionArgs.repeat;
var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
return new Pos(cur.line, ch);
},
moveByLines: function(cm, head, motionArgs, vim) {
var cur = head;
var endCh = cur.ch;
// Depending what our last motion was, we may want to do different
// things. If our last motion was moving vertically, we want to
// preserve the HPos from our last horizontal move. If our last motion
// was going to the end of a line, moving vertically we should go to
// the end of the line, etc.
switch (vim.lastMotion) {
case this.moveByLines:
case this.moveByDisplayLines:
case this.moveByScroll:
case this.moveToColumn:
case this.moveToEol:
endCh = vim.lastHPos;
break;
default:
vim.lastHPos = endCh;
}
var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
var first = cm.firstLine();
var last = cm.lastLine();
var posV = cm.findPosV(cur, (motionArgs.forward ? repeat : -repeat), 'line', vim.lastHSPos);
var hasMarkedText = motionArgs.forward ? posV.line > line : posV.line < line;
if (hasMarkedText) {
line = posV.line;
endCh = posV.ch;
}
// Vim go to line begin or line end when cursor at first/last line and
// move to previous/next line is triggered.
if (line < first && cur.line == first){
return this.moveToStartOfLine(cm, head, motionArgs, vim);
} else if (line > last && cur.line == last){
return moveToEol(cm, head, motionArgs, vim, true);
}
if (motionArgs.toFirstChar){
endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
vim.lastHPos = endCh;
}
vim.lastHSPos = cm.charCoords(new Pos(line, endCh),'div').left;
return new Pos(line, endCh);
},
moveByDisplayLines: function(cm, head, motionArgs, vim) {
var cur = head;
switch (vim.lastMotion) {
case this.moveByDisplayLines:
case this.moveByScroll:
case this.moveByLines:
case this.moveToColumn:
case this.moveToEol:
break;
default:
vim.lastHSPos = cm.charCoords(cur,'div').left;
}
var repeat = motionArgs.repeat;
var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
if (res.hitSide) {
if (motionArgs.forward) {
var lastCharCoords = cm.charCoords(res, 'div');
var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
var res = cm.coordsChar(goalCoords, 'div');
} else {
var resCoords = cm.charCoords(new Pos(cm.firstLine(), 0), 'div');
resCoords.left = vim.lastHSPos;
res = cm.coordsChar(resCoords, 'div');
}
}
vim.lastHPos = res.ch;
return res;
},
moveByPage: function(cm, head, motionArgs) {
// CodeMirror only exposes functions that move the cursor page down, so
// doing this bad hack to move the cursor and move it back. evalInput
// will move the cursor to where it should be in the end.
var curStart = head;
var repeat = motionArgs.repeat;
return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
},
moveByParagraph: function(cm, head, motionArgs) {
var dir = motionArgs.forward ? 1 : -1;
return findParagraph(cm, head, motionArgs.repeat, dir);
},
moveBySentence: function(cm, head, motionArgs) {
var dir = motionArgs.forward ? 1 : -1;
return findSentence(cm, head, motionArgs.repeat, dir);
},
moveByScroll: function(cm, head, motionArgs, vim) {
var scrollbox = cm.getScrollInfo();
var curEnd = null;
var repeat = motionArgs.repeat;
if (!repeat) {
repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
}
var orig = cm.charCoords(head, 'local');
motionArgs.repeat = repeat;
var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
if (!curEnd) {
return null;
}
var dest = cm.charCoords(curEnd, 'local');
cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
return curEnd;
},
moveByWords: function(cm, head, motionArgs) {
return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
!!motionArgs.wordEnd, !!motionArgs.bigWord);
},
moveTillCharacter: function(cm, _head, motionArgs) {
var repeat = motionArgs.repeat;
var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter);
var increment = motionArgs.forward ? -1 : 1;
recordLastCharacterSearch(increment, motionArgs);
if (!curEnd) return null;
curEnd.ch += increment;
return curEnd;
},
moveToCharacter: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
recordLastCharacterSearch(0, motionArgs);
return moveToCharacter(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter) || head;
},
moveToSymbol: function(cm, head, motionArgs) {
var repeat = motionArgs.repeat;
return findSymbol(cm, repeat, motionArgs.forward,
motionArgs.selectedCharacter) || head;
},
moveToColumn: function(cm, head, motionArgs, vim) {
var repeat = motionArgs.repeat;
// repeat is equivalent to which column we want to move to!
vim.lastHPos = repeat - 1;
vim.lastHSPos = cm.charCoords(head,'div').left;
return moveToColumn(cm, repeat);
},
moveToEol: function(cm, head, motionArgs, vim) {
return moveToEol(cm, head, motionArgs, vim, false);
},
moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
// Go to the start of the line where the text begins, or the end for
// whitespace-only lines
var cursor = head;
return new Pos(cursor.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
},
moveToMatchedSymbol: function(cm, head) {
var cursor = head;
var line = cursor.line;
var ch = cursor.ch;
var lineText = cm.getLine(line);
var symbol;
for (; ch < lineText.length; ch++) {
symbol = lineText.charAt(ch);
if (symbol && isMatchableSymbol(symbol)) {
var style = cm.getTokenTypeAt(new Pos(line, ch + 1));
if (style !== "string" && style !== "comment") {
break;
}
}
}
if (ch < lineText.length) {
// Only include angle brackets in analysis if they are being matched.
var re = (ch === '<' || ch === '>') ? /[(){}[\]<>]/ : /[(){}[\]]/;
var matched = cm.findMatchingBracket(new Pos(line, ch), {bracketRegex: re});
return matched.to;
} else {
return cursor;
}
},
moveToStartOfLine: function(_cm, head) {
return new Pos(head.line, 0);
},
moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
if (motionArgs.repeatIsExplicit) {
lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
}
return new Pos(lineNum,
findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
},
moveToStartOfDisplayLine: function(cm) {
cm.execCommand("goLineLeft");
return cm.getCursor();
},
moveToEndOfDisplayLine: function(cm) {
cm.execCommand("goLineRight");
var head = cm.getCursor();
if (head.sticky == "before") head.ch--;
return head;
},
textObjectManipulation: function(cm, head, motionArgs, vim) {
// TODO: lots of possible exceptions that can be thrown here. Try da(
// outside of a () block.
var mirroredPairs = {'(': ')', ')': '(',
'{': '}', '}': '{',
'[': ']', ']': '[',
'<': '>', '>': '<'};
var selfPaired = {'\'': true, '"': true, '`': true};
var character = motionArgs.selectedCharacter;
// 'b' refers to '()' block.
// 'B' refers to '{}' block.
if (character == 'b') {
character = '(';
} else if (character == 'B') {
character = '{';
}
// Inclusive is the difference between a and i
// TODO: Instead of using the additional text object map to perform text
// object operations, merge the map into the defaultKeyMap and use
// motionArgs to define behavior. Define separate entries for 'aw',
// 'iw', 'a[', 'i[', etc.
var inclusive = !motionArgs.textObjectInner;
var tmp;
if (mirroredPairs[character]) {
tmp = selectCompanionObject(cm, head, character, inclusive);
} else if (selfPaired[character]) {
tmp = findBeginningAndEnd(cm, head, character, inclusive);
} else if (character === 'W') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
true /** bigWord */);
} else if (character === 'w') {
tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
false /** bigWord */);
} else if (character === 'p') {
tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
motionArgs.linewise = true;
if (vim.visualMode) {
if (!vim.visualLine) { vim.visualLine = true; }
} else {
var operatorArgs = vim.inputState.operatorArgs;
if (operatorArgs) { operatorArgs.linewise = true; }
tmp.end.line--;
}
} else if (character === 't') {
tmp = expandTagUnderCursor(cm, head, inclusive);
} else {
// No text object defined for this, don't move.
return null;
}
if (!cm.state.vim.visualMode) {
return [tmp.start, tmp.end];
} else {
return expandSelection(cm, tmp.start, tmp.end);
}
},
repeatLastCharacterSearch: function(cm, head, motionArgs) {
var lastSearch = vimGlobalState.lastCharacterSearch;
var repeat = motionArgs.repeat;
var forward = motionArgs.forward === lastSearch.forward;
var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
cm.moveH(-increment, 'char');
motionArgs.inclusive = forward ? true : false;
var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
if (!curEnd) {
cm.moveH(increment, 'char');
return head;
}
curEnd.ch += increment;
return curEnd;
}
};
function defineMotion(name, fn) {
motions[name] = fn;
}
function fillArray(val, times) {
var arr = [];
for (var i = 0; i < times; i++) {
arr.push(val);
}
return arr;
}
/**
* An operator acts on a text selection. It receives the list of selections
* as input. The corresponding CodeMirror selection is guaranteed to
* match the input selection.
*/
var operators = {
change: function(cm, args, ranges) {
var finalHead, text;
var vim = cm.state.vim;
var anchor = ranges[0].anchor,
head = ranges[0].head;
if (!vim.visualMode) {
text = cm.getRange(anchor, head);
var lastState = vim.lastEditInputState || {};
if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
// Exclude trailing whitespace if the range is not all whitespace.
var match = (/\s+$/).exec(text);
if (match && lastState.motionArgs && lastState.motionArgs.forward) {
head = offsetCursor(head, 0, - match[0].length);
text = text.slice(0, - match[0].length);
}
}
var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
var wasLastLine = cm.firstLine() == cm.lastLine();
if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
cm.replaceRange('', prevLineEnd, head);
} else {
cm.replaceRange('', anchor, head);
}
if (args.linewise) {
// Push the next line back down, if there is a next line.
if (!wasLastLine) {
cm.setCursor(prevLineEnd);
CodeMirror.commands.newlineAndIndent(cm);
}
// make sure cursor ends up at the end of the line.
anchor.ch = Number.MAX_VALUE;
}
finalHead = anchor;
} else if (args.fullLine) {
head.ch = Number.MAX_VALUE;
head.line--;
cm.setSelection(anchor, head)
text = cm.getSelection();
cm.replaceSelection("");
finalHead = anchor;
} else {
text = cm.getSelection();
var replacement = fillArray('', ranges.length);
cm.replaceSelections(replacement);
finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
}
vimGlobalState.registerController.pushText(
args.registerName, 'change', text,
args.linewise, ranges.length > 1);
actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
},
// delete is a javascript keyword.
'delete': function(cm, args, ranges) {
var finalHead, text;
var vim = cm.state.vim;
if (!vim.visualBlock) {
var anchor = ranges[0].anchor,
head = ranges[0].head;
if (args.linewise &&
head.line != cm.firstLine() &&
anchor.line == cm.lastLine() &&
anchor.line == head.line - 1) {
// Special case for dd on last line (and first line).
if (anchor.line == cm.firstLine()) {
anchor.ch = 0;
} else {
anchor = new Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
}
}
text = cm.getRange(anchor, head);
cm.replaceRange('', anchor, head);
finalHead = anchor;
if (args.linewise) {
finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
}
} else {
text = cm.getSelection();
var replacement = fillArray('', ranges.length);
cm.replaceSelections(replacement);
finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
}
vimGlobalState.registerController.pushText(
args.registerName, 'delete', text,
args.linewise, vim.visualBlock);
return clipCursorToContent(cm, finalHead);
},
indent: function(cm, args, ranges) {
var vim = cm.state.vim;
var startLine = ranges[0].anchor.line;
var endLine = vim.visualBlock ?
ranges[ranges.length - 1].anchor.line :
ranges[0].head.line;
// In visual mode, n> shifts the selection right n times, instead of
// shifting n lines right once.
var repeat = (vim.visualMode) ? args.repeat : 1;
if (args.linewise) {
// The only way to delete a newline is to delete until the start of
// the next line, so in linewise mode evalInput will include the next
// line. We don't want this in indent, so we go back a line.
endLine--;
}
for (var i = startLine; i <= endLine; i++) {
for (var j = 0; j < repeat; j++) {
cm.indentLine(i, args.indentRight);
}
}
return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
},
indentAuto: function(cm, _args, ranges) {
cm.execCommand("indentAuto");
return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
},
changeCase: function(cm, args, ranges, oldAnchor, newHead) {
var selections = cm.getSelections();
var swapped = [];
var toLower = args.toLower;
for (var j = 0; j < selections.length; j++) {
var toSwap = selections[j];
var text = '';
if (toLower === true) {
text = toSwap.toLowerCase();
} else if (toLower === false) {
text = toSwap.toUpperCase();
} else {
for (var i = 0; i < toSwap.length; i++) {
var character = toSwap.charAt(i);
text += isUpperCase(character) ? character.toLowerCase() :
character.toUpperCase();
}
}
swapped.push(text);
}
cm.replaceSelections(swapped);
if (args.shouldMoveCursor){
return newHead;
} else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
} else if (args.linewise){
return oldAnchor;
} else {
return cursorMin(ranges[0].anchor, ranges[0].head);
}
},
yank: function(cm, args, ranges, oldAnchor) {
var vim = cm.state.vim;
var text = cm.getSelection();
var endPos = vim.visualMode
? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
: oldAnchor;
vimGlobalState.registerController.pushText(
args.registerName, 'yank',
text, args.linewise, vim.visualBlock);
return endPos;
}
};
function defineOperator(name, fn) {
operators[name] = fn;
}
var actions = {
jumpListWalk: function(cm, actionArgs, vim) {
if (vim.visualMode) {
return;
}
var repeat = actionArgs.repeat;
var forward = actionArgs.forward;
var jumpList = vimGlobalState.jumpList;
var mark = jumpList.move(cm, forward ? repeat : -repeat);
var markPos = mark ? mark.find() : undefined;
markPos = markPos ? markPos : cm.getCursor();
cm.setCursor(markPos);
},
scroll: function(cm, actionArgs, vim) {
if (vim.visualMode) {
return;
}
var repeat = actionArgs.repeat || 1;
var lineHeight = cm.defaultTextHeight();
var top = cm.getScrollInfo().top;
var delta = lineHeight * repeat;
var newPos = actionArgs.forward ? top + delta : top - delta;
var cursor = copyCursor(cm.getCursor());
var cursorCoords = cm.charCoords(cursor, 'local');
if (actionArgs.forward) {
if (newPos > cursorCoords.top) {
cursor.line += (newPos - cursorCoords.top) / lineHeight;
cursor.line = Math.ceil(cursor.line);
cm.setCursor(cursor);
cursorCoords = cm.charCoords(cursor, 'local');
cm.scrollTo(null, cursorCoords.top);
} else {
// Cursor stays within bounds. Just reposition the scroll window.
cm.scrollTo(null, newPos);
}
} else {
var newBottom = newPos + cm.getScrollInfo().clientHeight;
if (newBottom < cursorCoords.bottom) {
cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
cursor.line = Math.floor(cursor.line);
cm.setCursor(cursor);
cursorCoords = cm.charCoords(cursor, 'local');
cm.scrollTo(
null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
} else {
// Cursor stays within bounds. Just reposition the scroll window.
cm.scrollTo(null, newPos);
}
}
},
scrollToCursor: function(cm, actionArgs) {
var lineNum = cm.getCursor().line;
var charCoords = cm.charCoords(new Pos(lineNum, 0), 'local');
var height = cm.getScrollInfo().clientHeight;
var y = charCoords.top;
var lineHeight = charCoords.bottom - y;
switch (actionArgs.position) {
case 'center': y = y - (height / 2) + lineHeight;
break;
case 'bottom': y = y - height + lineHeight;
break;
}
cm.scrollTo(null, y);
},
replayMacro: function(cm, actionArgs, vim) {
var registerName = actionArgs.selectedCharacter;
var repeat = actionArgs.repeat;
var macroModeState = vimGlobalState.macroModeState;
if (registerName == '@') {
registerName = macroModeState.latestRegister;
} else {
macroModeState.latestRegister = registerName;
}
while(repeat--){
executeMacroRegister(cm, vim, macroModeState, registerName);
}
},
enterMacroRecordMode: function(cm, actionArgs) {
var macroModeState = vimGlobalState.macroModeState;
var registerName = actionArgs.selectedCharacter;
if (vimGlobalState.registerController.isValidRegister(registerName)) {
macroModeState.enterMacroRecordMode(cm, registerName);
}
},
toggleOverwrite: function(cm) {
if (!cm.state.overwrite) {
cm.toggleOverwrite(true);
cm.setOption('keyMap', 'vim-replace');
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
} else {
cm.toggleOverwrite(false);
cm.setOption('keyMap', 'vim-insert');
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
}
},
enterInsertMode: function(cm, actionArgs, vim) {
if (cm.getOption('readOnly')) { return; }
vim.insertMode = true;
vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
var insertAt = (actionArgs) ? actionArgs.insertAt : null;
var sel = vim.sel;
var head = actionArgs.head || cm.getCursor('head');
var height = cm.listSelections().length;
if (insertAt == 'eol') {
head = new Pos(head.line, lineLength(cm, head.line));
} else if (insertAt == 'bol') {
head = new Pos(head.line, 0);
} else if (insertAt == 'charAfter') {
head = offsetCursor(head, 0, 1);
} else if (insertAt == 'firstNonBlank') {
head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
} else if (insertAt == 'startOfSelectedArea') {
if (!vim.visualMode)
return;
if (!vim.visualBlock) {
if (sel.head.line < sel.anchor.line) {
head = sel.head;
} else {
head = new Pos(sel.anchor.line, 0);
}
} else {
head = new Pos(
Math.min(sel.head.line, sel.anchor.line),
Math.min(sel.head.ch, sel.anchor.ch));
height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'endOfSelectedArea') {
if (!vim.visualMode)
return;
if (!vim.visualBlock) {
if (sel.head.line >= sel.anchor.line) {
head = offsetCursor(sel.head, 0, 1);
} else {
head = new Pos(sel.anchor.line, 0);
}
} else {
head = new Pos(
Math.min(sel.head.line, sel.anchor.line),
Math.max(sel.head.ch, sel.anchor.ch) + 1);
height = Math.abs(sel.head.line - sel.anchor.line) + 1;
}
} else if (insertAt == 'inplace') {
if (vim.visualMode){
return;
}
} else if (insertAt == 'lastEdit') {
head = getLastEditPos(cm) || head;
}
cm.setOption('disableInput', false);
if (actionArgs && actionArgs.replace) {
// Handle Replace-mode as a special case of insert mode.
cm.toggleOverwrite(true);
cm.setOption('keyMap', 'vim-replace');
CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
} else {
cm.toggleOverwrite(false);
cm.setOption('keyMap', 'vim-insert');
CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
}
if (!vimGlobalState.macroModeState.isPlaying) {
// Only record if not replaying.
cm.on('change', onChange);
CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
}
if (vim.visualMode) {
exitVisualMode(cm);
}
selectForInsert(cm, head, height);
},
toggleVisualMode: function(cm, actionArgs, vim) {
var repeat = actionArgs.repeat;
var anchor = cm.getCursor();
var head;
// TODO: The repeat should actually select number of characters/lines
// equal to the repeat times the size of the previous visual
// operation.
if (!vim.visualMode) {
// Entering visual mode
vim.visualMode = true;
vim.visualLine = !!actionArgs.linewise;
vim.visualBlock = !!actionArgs.blockwise;
head = clipCursorToContent(
cm, new Pos(anchor.line, anchor.ch + repeat - 1));
vim.sel = {
anchor: anchor,
head: head
};
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
updateCmSelection(cm);
updateMark(cm, vim, '<', cursorMin(anchor, head));
updateMark(cm, vim, '>', cursorMax(anchor, head));
} else if (vim.visualLine ^ actionArgs.linewise ||
vim.visualBlock ^ actionArgs.blockwise) {
// Toggling between modes
vim.visualLine = !!actionArgs.linewise;
vim.visualBlock = !!actionArgs.blockwise;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
updateCmSelection(cm);
} else {
exitVisualMode(cm);
}
},
reselectLastSelection: function(cm, _actionArgs, vim) {
var lastSelection = vim.lastSelection;
if (vim.visualMode) {
updateLastSelection(cm, vim);
}
if (lastSelection) {
var anchor = lastSelection.anchorMark.find();
var head = lastSelection.headMark.find();
if (!anchor || !head) {
// If the marks have been destroyed due to edits, do nothing.
return;
}
vim.sel = {
anchor: anchor,
head: head
};
vim.visualMode = true;
vim.visualLine = lastSelection.visualLine;
vim.visualBlock = lastSelection.visualBlock;
updateCmSelection(cm);
updateMark(cm, vim, '<', cursorMin(anchor, head));
updateMark(cm, vim, '>', cursorMax(anchor, head));
CodeMirror.signal(cm, 'vim-mode-change', {
mode: 'visual',
subMode: vim.visualLine ? 'linewise' :
vim.visualBlock ? 'blockwise' : ''});
}
},
joinLines: function(cm, actionArgs, vim) {
var curStart, curEnd;
if (vim.visualMode) {
curStart = cm.getCursor('anchor');
curEnd = cm.getCursor('head');
if (cursorIsBefore(curEnd, curStart)) {
var tmp = curEnd;
curEnd = curStart;
curStart = tmp;
}
curEnd.ch = lineLength(cm, curEnd.line) - 1;
} else {
// Repeat is the number of lines to join. Minimum 2 lines.
var repeat = Math.max(actionArgs.repeat, 2);
curStart = cm.getCursor();
curEnd = clipCursorToContent(cm, new Pos(curStart.line + repeat - 1,
Infinity));
}
var finalCh = 0;
for (var i = curStart.line; i < curEnd.line; i++) {
finalCh = lineLength(cm, curStart.line);
var tmp = new Pos(curStart.line + 1,
lineLength(cm, curStart.line + 1));
var text = cm.getRange(curStart, tmp);
text = actionArgs.keepSpaces
? text.replace(/\n\r?/g, '')
: text.replace(/\n\s*/g, ' ');
cm.replaceRange(text, curStart, tmp);
}
var curFinalPos = new Pos(curStart.line, finalCh);
if (vim.visualMode) {
exitVisualMode(cm, false);
}
cm.setCursor(curFinalPos);
},
newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
vim.insertMode = true;
var insertAt = copyCursor(cm.getCursor());
if (insertAt.line === cm.firstLine() && !actionArgs.after) {
// Special case for inserting newline before start of document.
cm.replaceRange('\n', new Pos(cm.firstLine(), 0));
cm.setCursor(cm.firstLine(), 0);
} else {
insertAt.line = (actionArgs.after) ? insertAt.line :
insertAt.line - 1;
insertAt.ch = lineLength(cm, insertAt.line);
cm.setCursor(insertAt);
var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
CodeMirror.commands.newlineAndIndent;
newlineFn(cm);
}
this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
},
paste: function(cm, actionArgs, vim) {
var cur = copyCursor(cm.getCursor());
var register = vimGlobalState.registerController.getRegister(
actionArgs.registerName);
var text = register.toString();
if (!text) {
return;
}
if (actionArgs.matchIndent) {
var tabSize = cm.getOption("tabSize");
// length that considers tabs and tabSize
var whitespaceLength = function(str) {
var tabs = (str.split("\t").length - 1);
var spaces = (str.split(" ").length - 1);
return tabs * tabSize + spaces * 1;
};
var currentLine = cm.getLine(cm.getCursor().line);
var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
// chomp last newline b/c don't want it to match /^\s*/gm
var chompedText = text.replace(/\n$/, '');
var wasChomped = text !== chompedText;
var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
var text = chompedText.replace(/^\s*/gm, function(wspace) {
var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
if (newIndent < 0) {
return "";
}
else if (cm.getOption("indentWithTabs")) {
var quotient = Math.floor(newIndent / tabSize);
return Array(quotient + 1).join('\t');
}
else {
return Array(newIndent + 1).join(' ');
}
});
text += wasChomped ? "\n" : "";
}
if (actionArgs.repeat > 1) {
var text = Array(actionArgs.repeat + 1).join(text);
}
var linewise = register.linewise;
var blockwise = register.blockwise;
if (blockwise) {
text = text.split('\n');
if (linewise) {
text.pop();
}
for (var i = 0; i < text.length; i++) {
text[i] = (text[i] == '') ? ' ' : text[i];
}
cur.ch += actionArgs.after ? 1 : 0;
cur.ch = Math.min(lineLength(cm, cur.line), cur.ch);
} else if (linewise) {
if(vim.visualMode) {
text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
} else if (actionArgs.after) {
// Move the newline at the end to the start instead, and paste just
// before the newline character of the line we are on right now.
text = '\n' + text.slice(0, text.length - 1);
cur.ch = lineLength(cm, cur.line);
} else {
cur.ch = 0;
}
} else {
cur.ch += actionArgs.after ? 1 : 0;
}
var curPosFinal;
var idx;
if (vim.visualMode) {
// save the pasted text for reselection if the need arises
vim.lastPastedText = text;
var lastSelectionCurEnd;
var selectedArea = getSelectedAreaRange(cm, vim);
var selectionStart = selectedArea[0];
var selectionEnd = selectedArea[1];
var selectedText = cm.getSelection();
var selections = cm.listSelections();
var emptyStrings = new Array(selections.length).join('1').split('1');
// save the curEnd marker before it get cleared due to cm.replaceRange.
if (vim.lastSelection) {
lastSelectionCurEnd = vim.lastSelection.headMark.find();
}
// push the previously selected text to unnamed register
vimGlobalState.registerController.unnamedRegister.setText(selectedText);
if (blockwise) {
// first delete the selected text
cm.replaceSelections(emptyStrings);
// Set new selections as per the block length of the yanked text
selectionEnd = new Pos(selectionStart.line + text.length-1, selectionStart.ch);
cm.setCursor(selectionStart);
selectBlock(cm, selectionEnd);
cm.replaceSelections(text);
curPosFinal = selectionStart;
} else if (vim.visualBlock) {
cm.replaceSelections(emptyStrings);
cm.setCursor(selectionStart);
cm.replaceRange(text, selectionStart, selectionStart);
curPosFinal = selectionStart;
} else {
cm.replaceRange(text, selectionStart, selectionEnd);
curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
}
// restore the the curEnd marker
if(lastSelectionCurEnd) {
vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
}
if (linewise) {
curPosFinal.ch=0;
}
} else {
if (blockwise) {
cm.setCursor(cur);
for (var i = 0; i < text.length; i++) {
var line = cur.line+i;
if (line > cm.lastLine()) {
cm.replaceRange('\n', new Pos(line, 0));
}
var lastCh = lineLength(cm, line);
if (lastCh < cur.ch) {
extendLineToColumn(cm, line, cur.ch);
}
}
cm.setCursor(cur);
selectBlock(cm, new Pos(cur.line + text.length-1, cur.ch));
cm.replaceSelections(text);
curPosFinal = cur;
} else {
cm.replaceRange(text, cur);
// Now fine tune the cursor to where we want it.
if (linewise && actionArgs.after) {
curPosFinal = new Pos(
cur.line + 1,
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
} else if (linewise && !actionArgs.after) {
curPosFinal = new Pos(
cur.line,
findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
} else if (!linewise && actionArgs.after) {
idx = cm.indexFromPos(cur);
curPosFinal = cm.posFromIndex(idx + text.length - 1);
} else {
idx = cm.indexFromPos(cur);
curPosFinal = cm.posFromIndex(idx + text.length);
}
}
}
if (vim.visualMode) {
exitVisualMode(cm, false);
}
cm.setCursor(curPosFinal);
},
undo: function(cm, actionArgs) {
cm.operation(function() {
repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
cm.setCursor(cm.getCursor('anchor'));
});
},
redo: function(cm, actionArgs) {
repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
},
setRegister: function(_cm, actionArgs, vim) {
vim.inputState.registerName = actionArgs.selectedCharacter;
},
setMark: function(cm, actionArgs, vim) {
var markName = actionArgs.selectedCharacter;
updateMark(cm, vim, markName, cm.getCursor());
},
replace: function(cm, actionArgs, vim) {
var replaceWith = actionArgs.selectedCharacter;
var curStart = cm.getCursor();
var replaceTo;
var curEnd;
var selections = cm.listSelections();
if (vim.visualMode) {
curStart = cm.getCursor('start');
curEnd = cm.getCursor('end');
} else {
var line = cm.getLine(curStart.line);
replaceTo = curStart.ch + actionArgs.repeat;
if (replaceTo > line.length) {
replaceTo=line.length;
}
curEnd = new Pos(curStart.line, replaceTo);
}
if (replaceWith=='\n') {
if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
// special case, where vim help says to replace by just one line-break
(CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
} else {
var replaceWithStr = cm.getRange(curStart, curEnd);
//replace all characters in range by selected, but keep linebreaks
replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
if (vim.visualBlock) {
// Tabs are split in visua block before replacing
var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
replaceWithStr = cm.getSelection();
replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
cm.replaceSelections(replaceWithStr);
} else {
cm.replaceRange(replaceWithStr, curStart, curEnd);
}
if (vim.visualMode) {
curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
selections[0].anchor : selections[0].head;
cm.setCursor(curStart);
exitVisualMode(cm, false);
} else {
cm.setCursor(offsetCursor(curEnd, 0, -1));
}
}
},
incrementNumberToken: function(cm, actionArgs) {
var cur = cm.getCursor();
var lineStr = cm.getLine(cur.line);
var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
var match;
var start;
var end;
var numberStr;
while ((match = re.exec(lineStr)) !== null) {
start = match.index;
end = start + match[0].length;
if (cur.ch < end)break;
}
if (!actionArgs.backtrack && (end <= cur.ch))return;
if (match) {
var baseStr = match[2] || match[4]
var digits = match[3] || match[5]
var increment = actionArgs.increase ? 1 : -1;
var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];
var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
numberStr = number.toString(base);
var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''
if (numberStr.charAt(0) === '-') {
numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
} else {
numberStr = baseStr + zeroPadding + numberStr;
}
var from = new Pos(cur.line, start);
var to = new Pos(cur.line, end);
cm.replaceRange(numberStr, from, to);
} else {
return;
}
cm.setCursor(new Pos(cur.line, start + numberStr.length - 1));
},
repeatLastEdit: function(cm, actionArgs, vim) {
var lastEditInputState = vim.lastEditInputState;
if (!lastEditInputState) { return; }
var repeat = actionArgs.repeat;
if (repeat && actionArgs.repeatIsExplicit) {
vim.lastEditInputState.repeatOverride = repeat;
} else {
repeat = vim.lastEditInputState.repeatOverride || repeat;
}
repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
},
indent: function(cm, actionArgs) {
cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
},
exitInsertMode: exitInsertMode
};
function defineAction(name, fn) {
actions[name] = fn;
}
/*
* Below are miscellaneous utility functions used by vim.js
*/
/**
* Clips cursor to ensure that line is within the buffer's range
* If includeLineBreak is true, then allow cur.ch == lineLength.
*/
function clipCursorToContent(cm, cur) {
var vim = cm.state.vim;
var includeLineBreak = vim.insertMode || vim.visualMode;
var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
var maxCh = lineLength(cm, line) - 1 + !!includeLineBreak;
var ch = Math.min(Math.max(0, cur.ch), maxCh);
return new Pos(line, ch);
}
function copyArgs(args) {
var ret = {};
for (var prop in args) {
if (args.hasOwnProperty(prop)) {
ret[prop] = args[prop];
}
}
return ret;
}
function offsetCursor(cur, offsetLine, offsetCh) {
if (typeof offsetLine === 'object') {
offsetCh = offsetLine.ch;
offsetLine = offsetLine.line;
}
return new Pos(cur.line + offsetLine, cur.ch + offsetCh);
}
function commandMatches(keys, keyMap, context, inputState) {
// Partial matches are not applied. They inform the key handler
// that the current key sequence is a subsequence of a valid key
// sequence, so that the key buffer is not cleared.
var match, partial = [], full = [];
for (var i = 0; i < keyMap.length; i++) {
var command = keyMap[i];
if (context == 'insert' && command.context != 'insert' ||
command.context && command.context != context ||
inputState.operator && command.type == 'action' ||
!(match = commandMatch(keys, command.keys))) { continue; }
if (match == 'partial') { partial.push(command); }
if (match == 'full') { full.push(command); }
}
return {
partial: partial.length && partial,
full: full.length && full
};
}
function commandMatch(pressed, mapped) {
if (mapped.slice(-11) == '<character>') {
// Last character matches anything.
var prefixLen = mapped.length - 11;
var pressedPrefix = pressed.slice(0, prefixLen);
var mappedPrefix = mapped.slice(0, prefixLen);
return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
} else {
return pressed == mapped ? 'full' :
mapped.indexOf(pressed) == 0 ? 'partial' : false;
}
}
function lastChar(keys) {
var match = /^.*(<[^>]+>)$/.exec(keys);
var selectedCharacter = match ? match[1] : keys.slice(-1);
if (selectedCharacter.length > 1){
switch(selectedCharacter){
case '<CR>':
selectedCharacter='\n';
break;
case '<Space>':
selectedCharacter=' ';
break;
default:
selectedCharacter='';
break;
}
}
return selectedCharacter;
}
function repeatFn(cm, fn, repeat) {
return function() {
for (var i = 0; i < repeat; i++) {
fn(cm);
}
};
}
function copyCursor(cur) {
return new Pos(cur.line, cur.ch);
}
function cursorEqual(cur1, cur2) {
return cur1.ch == cur2.ch && cur1.line == cur2.line;
}
function cursorIsBefore(cur1, cur2) {
if (cur1.line < cur2.line) {
return true;
}
if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
return true;
}
return false;
}
function cursorMin(cur1, cur2) {
if (arguments.length > 2) {
cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
}
return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
}
function cursorMax(cur1, cur2) {
if (arguments.length > 2) {
cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
}
return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
}
function cursorIsBetween(cur1, cur2, cur3) {
// returns true if cur2 is between cur1 and cur3.
var cur1before2 = cursorIsBefore(cur1, cur2);
var cur2before3 = cursorIsBefore(cur2, cur3);
return cur1before2 && cur2before3;
}
function lineLength(cm, lineNum) {
return cm.getLine(lineNum).length;
}
function trim(s) {
if (s.trim) {
return s.trim();
}
return s.replace(/^\s+|\s+$/g, '');
}
function escapeRegex(s) {
return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
}
function extendLineToColumn(cm, lineNum, column) {
var endCh = lineLength(cm, lineNum);
var spaces = new Array(column-endCh+1).join(' ');
cm.setCursor(new Pos(lineNum, endCh));
cm.replaceRange(spaces, cm.getCursor());
}
// This functions selects a rectangular block
// of text with selectionEnd as any of its corner
// Height of block:
// Difference in selectionEnd.line and first/last selection.line
// Width of the block:
// Distance between selectionEnd.ch and any(first considered here) selection.ch
function selectBlock(cm, selectionEnd) {
var selections = [], ranges = cm.listSelections();
var head = copyCursor(cm.clipPos(selectionEnd));
var isClipped = !cursorEqual(selectionEnd, head);
var curHead = cm.getCursor('head');
var primIndex = getIndex(ranges, curHead);
var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
var max = ranges.length - 1;
var index = max - primIndex > primIndex ? max : 0;
var base = ranges[index].anchor;
var firstLine = Math.min(base.line, head.line);
var lastLine = Math.max(base.line, head.line);
var baseCh = base.ch, headCh = head.ch;
var dir = ranges[index].head.ch - baseCh;
var newDir = headCh - baseCh;
if (dir > 0 && newDir <= 0) {
baseCh++;
if (!isClipped) { headCh--; }
} else if (dir < 0 && newDir >= 0) {
baseCh--;
if (!wasClipped) { headCh++; }
} else if (dir < 0 && newDir == -1) {
baseCh--;
headCh++;
}
for (var line = firstLine; line <= lastLine; line++) {
var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
selections.push(range);
}
cm.setSelections(selections);
selectionEnd.ch = headCh;
base.ch = baseCh;
return base;
}
function selectForInsert(cm, head, height) {
var sel = [];
for (var i = 0; i < height; i++) {
var lineHead = offsetCursor(head, i, 0);
sel.push({anchor: lineHead, head: lineHead});
}
cm.setSelections(sel, 0);
}
// getIndex returns the index of the cursor in the selections.
function getIndex(ranges, cursor, end) {
for (var i = 0; i < ranges.length; i++) {
var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
if (atAnchor || atHead) {
return i;
}
}
return -1;
}
function getSelectedAreaRange(cm, vim) {
var lastSelection = vim.lastSelection;
var getCurrentSelectedAreaRange = function() {
var selections = cm.listSelections();
var start = selections[0];
var end = selections[selections.length-1];
var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
return [selectionStart, selectionEnd];
};
var getLastSelectedAreaRange = function() {
var selectionStart = cm.getCursor();
var selectionEnd = cm.getCursor();
var block = lastSelection.visualBlock;
if (block) {
var width = block.width;
var height = block.height;
selectionEnd = new Pos(selectionStart.line + height, selectionStart.ch + width);
var selections = [];
// selectBlock creates a 'proper' rectangular block.
// We do not want that in all cases, so we manually set selections.
for (var i = selectionStart.line; i < selectionEnd.line; i++) {
var anchor = new Pos(i, selectionStart.ch);
var head = new Pos(i, selectionEnd.ch);
var range = {anchor: anchor, head: head};
selections.push(range);
}
cm.setSelections(selections);
} else {
var start = lastSelection.anchorMark.find();
var end = lastSelection.headMark.find();
var line = end.line - start.line;
var ch = end.ch - start.ch;
selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
if (lastSelection.visualLine) {
selectionStart = new Pos(selectionStart.line, 0);
selectionEnd = new Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
}
cm.setSelection(selectionStart, selectionEnd);
}
return [selectionStart, selectionEnd];
};
if (!vim.visualMode) {
// In case of replaying the action.
return getLastSelectedAreaRange();
} else {
return getCurrentSelectedAreaRange();
}
}
// Updates the previous selection with the current selection's values. This
// should only be called in visual mode.
function updateLastSelection(cm, vim) {
var anchor = vim.sel.anchor;
var head = vim.sel.head;
// To accommodate the effect of lastPastedText in the last selection
if (vim.lastPastedText) {
head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
vim.lastPastedText = null;
}
vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
'headMark': cm.setBookmark(head),
'anchor': copyCursor(anchor),
'head': copyCursor(head),
'visualMode': vim.visualMode,
'visualLine': vim.visualLine,
'visualBlock': vim.visualBlock};
}
function expandSelection(cm, start, end) {
var sel = cm.state.vim.sel;
var head = sel.head;
var anchor = sel.anchor;
var tmp;
if (cursorIsBefore(end, start)) {
tmp = end;
end = start;
start = tmp;
}
if (cursorIsBefore(head, anchor)) {
head = cursorMin(start, head);
anchor = cursorMax(anchor, end);
} else {
anchor = cursorMin(start, anchor);
head = cursorMax(head, end);
head = offsetCursor(head, 0, -1);
if (head.ch == -1 && head.line != cm.firstLine()) {
head = new Pos(head.line - 1, lineLength(cm, head.line - 1));
}
}
return [anchor, head];
}
/**
* Updates the CodeMirror selection to match the provided vim selection.
* If no arguments are given, it uses the current vim selection state.
*/
function updateCmSelection(cm, sel, mode) {
var vim = cm.state.vim;
sel = sel || vim.sel;
var mode = mode ||
vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
var cmSel = makeCmSelection(cm, sel, mode);
cm.setSelections(cmSel.ranges, cmSel.primary);
}
function makeCmSelection(cm, sel, mode, exclusive) {
var head = copyCursor(sel.head);
var anchor = copyCursor(sel.anchor);
if (mode == 'char') {
var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
head = offsetCursor(sel.head, 0, headOffset);
anchor = offsetCursor(sel.anchor, 0, anchorOffset);
return {
ranges: [{anchor: anchor, head: head}],
primary: 0
};
} else if (mode == 'line') {
if (!cursorIsBefore(sel.head, sel.anchor)) {
anchor.ch = 0;
var lastLine = cm.lastLine();
if (head.line > lastLine) {
head.line = lastLine;
}
head.ch = lineLength(cm, head.line);
} else {
head.ch = 0;
anchor.ch = lineLength(cm, anchor.line);
}
return {
ranges: [{anchor: anchor, head: head}],
primary: 0
};
} else if (mode == 'block') {
var top = Math.min(anchor.line, head.line),
fromCh = anchor.ch,
bottom = Math.max(anchor.line, head.line),
toCh = head.ch;
if (fromCh < toCh) { toCh += 1 }
else { fromCh += 1 };
var height = bottom - top + 1;
var primary = head.line == top ? 0 : height - 1;
var ranges = [];
for (var i = 0; i < height; i++) {
ranges.push({
anchor: new Pos(top + i, fromCh),
head: new Pos(top + i, toCh)
});
}
return {
ranges: ranges,
primary: primary
};
}
}
function getHead(cm) {
var cur = cm.getCursor('head');
if (cm.getSelection().length == 1) {
// Small corner case when only 1 character is selected. The "real"
// head is the left of head and anchor.
cur = cursorMin(cur, cm.getCursor('anchor'));
}
return cur;
}
/**
* If moveHead is set to false, the CodeMirror selection will not be
* touched. The caller assumes the responsibility of putting the cursor
* in the right place.
*/
function exitVisualMode(cm, moveHead) {
var vim = cm.state.vim;
if (moveHead !== false) {
cm.setCursor(clipCursorToContent(cm, vim.sel.head));
}
updateLastSelection(cm, vim);
vim.visualMode = false;
vim.visualLine = false;
vim.visualBlock = false;
if (!vim.insertMode) CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
}
// Remove any trailing newlines from the selection. For
// example, with the caret at the start of the last word on the line,
// 'dw' should word, but not the newline, while 'w' should advance the
// caret to the first character of the next line.
function clipToLine(cm, curStart, curEnd) {
var selection = cm.getRange(curStart, curEnd);
// Only clip if the selection ends with trailing newline + whitespace
if (/\n\s*$/.test(selection)) {
var lines = selection.split('\n');
// We know this is all whitespace.
lines.pop();
// Cases:
// 1. Last word is an empty line - do not clip the trailing '\n'
// 2. Last word is not an empty line - clip the trailing '\n'
var line;
// Find the line containing the last word, and clip all whitespace up
// to it.
for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
curEnd.line--;
curEnd.ch = 0;
}
// If the last word is not an empty line, clip an additional newline
if (line) {
curEnd.line--;
curEnd.ch = lineLength(cm, curEnd.line);
} else {
curEnd.ch = 0;
}
}
}
// Expand the selection to line ends.
function expandSelectionToLine(_cm, curStart, curEnd) {
curStart.ch = 0;
curEnd.ch = 0;
curEnd.line++;
}
function findFirstNonWhiteSpaceCharacter(text) {
if (!text) {
return 0;
}
var firstNonWS = text.search(/\S/);
return firstNonWS == -1 ? text.length : firstNonWS;
}
function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
var cur = getHead(cm);
var line = cm.getLine(cur.line);
var idx = cur.ch;
// Seek to first word or non-whitespace character, depending on if
// noSymbol is true.
var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
while (!test(line.charAt(idx))) {
idx++;
if (idx >= line.length) { return null; }
}
if (bigWord) {
test = bigWordCharTest[0];
} else {
test = wordCharTest[0];
if (!test(line.charAt(idx))) {
test = wordCharTest[1];
}
}
var end = idx, start = idx;
while (test(line.charAt(end)) && end < line.length) { end++; }
while (test(line.charAt(start)) && start >= 0) { start--; }
start++;
if (inclusive) {
// If present, include all whitespace after word.
// Otherwise, include all whitespace before word, except indentation.
var wordEnd = end;
while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
if (wordEnd == end) {
var wordStart = start;
while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
if (!start) { start = wordStart; }
}
}
return { start: new Pos(cur.line, start), end: new Pos(cur.line, end) };
}
/**
* Depends on the following:
*
* - editor mode should be htmlmixedmode / xml
* - mode/xml/xml.js should be loaded
* - addon/fold/xml-fold.js should be loaded
*
* If any of the above requirements are not true, this function noops.
*
* This is _NOT_ a 100% accurate implementation of vim tag text objects.
* The following caveats apply (based off cursory testing, I'm sure there
* are other discrepancies):
*
* - Does not work inside comments:
* ```
* <!-- <div>broken</div> -->
* ```
* - Does not work when tags have different cases:
* ```
* <div>broken</DIV>
* ```
* - Does not work when cursor is inside a broken tag:
* ```
* <div><brok><en></div>
* ```
*/
function expandTagUnderCursor(cm, head, inclusive) {
var cur = head;
if (!CodeMirror.findMatchingTag || !CodeMirror.findEnclosingTag) {
return { start: cur, end: cur };
}
var tags = CodeMirror.findMatchingTag(cm, head) || CodeMirror.findEnclosingTag(cm, head);
if (!tags || !tags.open || !tags.close) {
return { start: cur, end: cur };
}
if (inclusive) {
return { start: tags.open.from, end: tags.close.to };
}
return { start: tags.open.to, end: tags.close.from };
}
function recordJumpPosition(cm, oldCur, newCur) {
if (!cursorEqual(oldCur, newCur)) {
vimGlobalState.jumpList.add(cm, oldCur, newCur);
}
}
function recordLastCharacterSearch(increment, args) {
vimGlobalState.lastCharacterSearch.increment = increment;
vimGlobalState.lastCharacterSearch.forward = args.forward;
vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
}
var symbolToMode = {
'(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
'[': 'section', ']': 'section',
'*': 'comment', '/': 'comment',
'm': 'method', 'M': 'method',
'#': 'preprocess'
};
var findSymbolModes = {
bracket: {
isComplete: function(state) {
if (state.nextCh === state.symb) {
state.depth++;
if (state.depth >= 1)return true;
} else if (state.nextCh === state.reverseSymb) {
state.depth--;
}
return false;
}
},
section: {
init: function(state) {
state.curMoveThrough = true;
state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
},
isComplete: function(state) {
return state.index === 0 && state.nextCh === state.symb;
}
},
comment: {
isComplete: function(state) {
var found = state.lastCh === '*' && state.nextCh === '/';
state.lastCh = state.nextCh;
return found;
}
},
// TODO: The original Vim implementation only operates on level 1 and 2.
// The current implementation doesn't check for code block level and
// therefore it operates on any levels.
method: {
init: function(state) {
state.symb = (state.symb === 'm' ? '{' : '}');
state.reverseSymb = state.symb === '{' ? '}' : '{';
},
isComplete: function(state) {
if (state.nextCh === state.symb)return true;
return false;
}
},
preprocess: {
init: function(state) {
state.index = 0;
},
isComplete: function(state) {
if (state.nextCh === '#') {
var token = state.lineText.match(/^#(\w+)/)[1];
if (token === 'endif') {
if (state.forward && state.depth === 0) {
return true;
}
state.depth++;
} else if (token === 'if') {
if (!state.forward && state.depth === 0) {
return true;
}
state.depth--;
}
if (token === 'else' && state.depth === 0)return true;
}
return false;
}
}
};
function findSymbol(cm, repeat, forward, symb) {
var cur = copyCursor(cm.getCursor());
var increment = forward ? 1 : -1;
var endLine = forward ? cm.lineCount() : -1;
var curCh = cur.ch;
var line = cur.line;
var lineText = cm.getLine(line);
var state = {
lineText: lineText,
nextCh: lineText.charAt(curCh),
lastCh: null,
index: curCh,
symb: symb,
reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
forward: forward,
depth: 0,
curMoveThrough: false
};
var mode = symbolToMode[symb];
if (!mode)return cur;
var init = findSymbolModes[mode].init;
var isComplete = findSymbolModes[mode].isComplete;
if (init) { init(state); }
while (line !== endLine && repeat) {
state.index += increment;
state.nextCh = state.lineText.charAt(state.index);
if (!state.nextCh) {
line += increment;
state.lineText = cm.getLine(line) || '';
if (increment > 0) {
state.index = 0;
} else {
var lineLen = state.lineText.length;
state.index = (lineLen > 0) ? (lineLen-1) : 0;
}
state.nextCh = state.lineText.charAt(state.index);
}
if (isComplete(state)) {
cur.line = line;
cur.ch = state.index;
repeat--;
}
}
if (state.nextCh || state.curMoveThrough) {
return new Pos(line, state.index);
}
return cur;
}
/*
* Returns the boundaries of the next word. If the cursor in the middle of
* the word, then returns the boundaries of the current word, starting at
* the cursor. If the cursor is at the start/end of a word, and we are going
* forward/backward, respectively, find the boundaries of the next word.
*
* @param {CodeMirror} cm CodeMirror object.
* @param {Cursor} cur The cursor position.
* @param {boolean} forward True to search forward. False to search
* backward.
* @param {boolean} bigWord True if punctuation count as part of the word.
* False if only [a-zA-Z0-9] characters count as part of the word.
* @param {boolean} emptyLineIsWord True if empty lines should be treated
* as words.
* @return {Object{from:number, to:number, line: number}} The boundaries of
* the word, or null if there are no more words.
*/
function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
var lineNum = cur.line;
var pos = cur.ch;
var line = cm.getLine(lineNum);
var dir = forward ? 1 : -1;
var charTests = bigWord ? bigWordCharTest: wordCharTest;
if (emptyLineIsWord && line == '') {
lineNum += dir;
line = cm.getLine(lineNum);
if (!isLine(cm, lineNum)) {
return null;
}
pos = (forward) ? 0 : line.length;
}
while (true) {
if (emptyLineIsWord && line == '') {
return { from: 0, to: 0, line: lineNum };
}
var stop = (dir > 0) ? line.length : -1;
var wordStart = stop, wordEnd = stop;
// Find bounds of next word.
while (pos != stop) {
var foundWord = false;
for (var i = 0; i < charTests.length && !foundWord; ++i) {
if (charTests[i](line.charAt(pos))) {
wordStart = pos;
// Advance to end of word.
while (pos != stop && charTests[i](line.charAt(pos))) {
pos += dir;
}
wordEnd = pos;
foundWord = wordStart != wordEnd;
if (wordStart == cur.ch && lineNum == cur.line &&
wordEnd == wordStart + dir) {
// We started at the end of a word. Find the next one.
continue;
} else {
return {
from: Math.min(wordStart, wordEnd + 1),
to: Math.max(wordStart, wordEnd),
line: lineNum };
}
}
}
if (!foundWord) {
pos += dir;
}
}
// Advance to next/prev line.
lineNum += dir;
if (!isLine(cm, lineNum)) {
return null;
}
line = cm.getLine(lineNum);
pos = (dir > 0) ? 0 : line.length;
}
}
/**
* @param {CodeMirror} cm CodeMirror object.
* @param {Pos} cur The position to start from.
* @param {int} repeat Number of words to move past.
* @param {boolean} forward True to search forward. False to search
* backward.
* @param {boolean} wordEnd True to move to end of word. False to move to
* beginning of word.
* @param {boolean} bigWord True if punctuation count as part of the word.
* False if only alphabet characters count as part of the word.
* @return {Cursor} The position the cursor should move to.
*/
function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
var curStart = copyCursor(cur);
var words = [];
if (forward && !wordEnd || !forward && wordEnd) {
repeat++;
}
// For 'e', empty lines are not considered words, go figure.
var emptyLineIsWord = !(forward && wordEnd);
for (var i = 0; i < repeat; i++) {
var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
if (!word) {
var eodCh = lineLength(cm, cm.lastLine());
words.push(forward
? {line: cm.lastLine(), from: eodCh, to: eodCh}
: {line: 0, from: 0, to: 0});
break;
}
words.push(word);
cur = new Pos(word.line, forward ? (word.to - 1) : word.from);
}
var shortCircuit = words.length != repeat;
var firstWord = words[0];
var lastWord = words.pop();
if (forward && !wordEnd) {
// w
if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
// We did not start in the middle of a word. Discard the extra word at the end.
lastWord = words.pop();
}
return new Pos(lastWord.line, lastWord.from);
} else if (forward && wordEnd) {
return new Pos(lastWord.line, lastWord.to - 1);
} else if (!forward && wordEnd) {
// ge
if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
// We did not start in the middle of a word. Discard the extra word at the end.
lastWord = words.pop();
}
return new Pos(lastWord.line, lastWord.to);
} else {
// b
return new Pos(lastWord.line, lastWord.from);
}
}
function moveToEol(cm, head, motionArgs, vim, keepHPos) {
var cur = head;
var retval= new Pos(cur.line + motionArgs.repeat - 1, Infinity);
var end=cm.clipPos(retval);
end.ch--;
if (!keepHPos) {
vim.lastHPos = Infinity;
vim.lastHSPos = cm.charCoords(end,'div').left;
}
return retval;
}
function moveToCharacter(cm, repeat, forward, character) {
var cur = cm.getCursor();
var start = cur.ch;
var idx;
for (var i = 0; i < repeat; i ++) {
var line = cm.getLine(cur.line);
idx = charIdxInLine(start, line, character, forward, true);
if (idx == -1) {
return null;
}
start = idx;
}
return new Pos(cm.getCursor().line, idx);
}
function moveToColumn(cm, repeat) {
// repeat is always >= 1, so repeat - 1 always corresponds
// to the column we want to go to.
var line = cm.getCursor().line;
return clipCursorToContent(cm, new Pos(line, repeat - 1));
}
function updateMark(cm, vim, markName, pos) {
if (!inArray(markName, validMarks)) {
return;
}
if (vim.marks[markName]) {
vim.marks[markName].clear();
}
vim.marks[markName] = cm.setBookmark(pos);
}
function charIdxInLine(start, line, character, forward, includeChar) {
// Search for char in line.
// motion_options: {forward, includeChar}
// If includeChar = true, include it too.
// If forward = true, search forward, else search backwards.
// If char is not found on this line, do nothing
var idx;
if (forward) {
idx = line.indexOf(character, start + 1);
if (idx != -1 && !includeChar) {
idx -= 1;
}
} else {
idx = line.lastIndexOf(character, start - 1);
if (idx != -1 && !includeChar) {
idx += 1;
}
}
return idx;
}
function findParagraph(cm, head, repeat, dir, inclusive) {
var line = head.line;
var min = cm.firstLine();
var max = cm.lastLine();
var start, end, i = line;
function isEmpty(i) { return !cm.getLine(i); }
function isBoundary(i, dir, any) {
if (any) { return isEmpty(i) != isEmpty(i + dir); }
return !isEmpty(i) && isEmpty(i + dir);
}
if (dir) {
while (min <= i && i <= max && repeat > 0) {
if (isBoundary(i, dir)) { repeat--; }
i += dir;
}
return new Pos(i, 0);
}
var vim = cm.state.vim;
if (vim.visualLine && isBoundary(line, 1, true)) {
var anchor = vim.sel.anchor;
if (isBoundary(anchor.line, -1, true)) {
if (!inclusive || anchor.line != line) {
line += 1;
}
}
}
var startState = isEmpty(line);
for (i = line; i <= max && repeat; i++) {
if (isBoundary(i, 1, true)) {
if (!inclusive || isEmpty(i) != startState) {
repeat--;
}
}
}
end = new Pos(i, 0);
// select boundary before paragraph for the last one
if (i > max && !startState) { startState = true; }
else { inclusive = false; }
for (i = line; i > min; i--) {
if (!inclusive || isEmpty(i) == startState || i == line) {
if (isBoundary(i, -1, true)) { break; }
}
}
start = new Pos(i, 0);
return { start: start, end: end };
}
function findSentence(cm, cur, repeat, dir) {
/*
Takes an index object
{
line: the line string,
ln: line number,
pos: index in line,
dir: direction of traversal (-1 or 1)
}
and modifies the line, ln, and pos members to represent the
next valid position or sets them to null if there are
no more valid positions.
*/
function nextChar(cm, idx) {
if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
idx.ln += idx.dir;
if (!isLine(cm, idx.ln)) {
idx.line = null;
idx.ln = null;
idx.pos = null;
return;
}
idx.line = cm.getLine(idx.ln);
idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
}
else {
idx.pos += idx.dir;
}
}
/*
Performs one iteration of traversal in forward direction
Returns an index object of the new location
*/
function forward(cm, ln, pos, dir) {
var line = cm.getLine(ln);
var stop = (line === "");
var curr = {
line: line,
ln: ln,
pos: pos,
dir: dir,
}
var last_valid = {
ln: curr.ln,
pos: curr.pos,
}
var skip_empty_lines = (curr.line === "");
// Move one step to skip character we start on
nextChar(cm, curr);
while (curr.line !== null) {
last_valid.ln = curr.ln;
last_valid.pos = curr.pos;
if (curr.line === "" && !skip_empty_lines) {
return { ln: curr.ln, pos: curr.pos, };
}
else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
return { ln: curr.ln, pos: curr.pos, };
}
else if (isEndOfSentenceSymbol(curr.line[curr.pos])
&& !stop
&& (curr.pos === curr.line.length - 1
|| isWhiteSpaceString(curr.line[curr.pos + 1]))) {
stop = true;
}
nextChar(cm, curr);
}
/*
Set the position to the last non whitespace character on the last
valid line in the case that we reach the end of the document.
*/
var line = cm.getLine(last_valid.ln);
last_valid.pos = 0;
for(var i = line.length - 1; i >= 0; --i) {
if (!isWhiteSpaceString(line[i])) {
last_valid.pos = i;
break;
}
}
return last_valid;
}
/*
Performs one iteration of traversal in reverse direction
Returns an index object of the new location
*/
function reverse(cm, ln, pos, dir) {
var line = cm.getLine(ln);
var curr = {
line: line,
ln: ln,
pos: pos,
dir: dir,
}
var last_valid = {
ln: curr.ln,
pos: null,
};
var skip_empty_lines = (curr.line === "");
// Move one step to skip character we start on
nextChar(cm, curr);
while (curr.line !== null) {
if (curr.line === "" && !skip_empty_lines) {
if (last_valid.pos !== null) {
return last_valid;
}
else {
return { ln: curr.ln, pos: curr.pos };
}
}
else if (isEndOfSentenceSymbol(curr.line[curr.pos])
&& last_valid.pos !== null
&& !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
return last_valid;
}
else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
skip_empty_lines = false;
last_valid = { ln: curr.ln, pos: curr.pos }
}
nextChar(cm, curr);
}
/*
Set the position to the first non whitespace character on the last
valid line in the case that we reach the beginning of the document.
*/
var line = cm.getLine(last_valid.ln);
last_valid.pos = 0;
for(var i = 0; i < line.length; ++i) {
if (!isWhiteSpaceString(line[i])) {
last_valid.pos = i;
break;
}
}
return last_valid;
}
var curr_index = {
ln: cur.line,
pos: cur.ch,
};
while (repeat > 0) {
if (dir < 0) {
curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
}
else {
curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
}
repeat--;
}
return new Pos(curr_index.ln, curr_index.pos);
}
// TODO: perhaps this finagling of start and end positions belongs
// in codemirror/replaceRange?
function selectCompanionObject(cm, head, symb, inclusive) {
var cur = head, start, end;
var bracketRegexp = ({
'(': /[()]/, ')': /[()]/,
'[': /[[\]]/, ']': /[[\]]/,
'{': /[{}]/, '}': /[{}]/,
'<': /[<>]/, '>': /[<>]/})[symb];
var openSym = ({
'(': '(', ')': '(',
'[': '[', ']': '[',
'{': '{', '}': '{',
'<': '<', '>': '<'})[symb];
var curChar = cm.getLine(cur.line).charAt(cur.ch);
// Due to the behavior of scanForBracket, we need to add an offset if the
// cursor is on a matching open bracket.
var offset = curChar === openSym ? 1 : 0;
start = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});
end = cm.scanForBracket(new Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});
if (!start || !end) {
return { start: cur, end: cur };
}
start = start.pos;
end = end.pos;
if ((start.line == end.line && start.ch > end.ch)
|| (start.line > end.line)) {
var tmp = start;
start = end;
end = tmp;
}
if (inclusive) {
end.ch += 1;
} else {
start.ch += 1;
}
return { start: start, end: end };
}
// Takes in a symbol and a cursor and tries to simulate text objects that
// have identical opening and closing symbols
// TODO support across multiple lines
function findBeginningAndEnd(cm, head, symb, inclusive) {
var cur = copyCursor(head);
var line = cm.getLine(cur.line);
var chars = line.split('');
var start, end, i, len;
var firstIndex = chars.indexOf(symb);
// the decision tree is to always look backwards for the beginning first,
// but if the cursor is in front of the first instance of the symb,
// then move the cursor forward
if (cur.ch < firstIndex) {
cur.ch = firstIndex;
// Why is this line even here???
// cm.setCursor(cur.line, firstIndex+1);
}
// otherwise if the cursor is currently on the closing symbol
else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
end = cur.ch; // assign end to the current cursor
--cur.ch; // make sure to look backwards
}
// if we're currently on the symbol, we've got a start
if (chars[cur.ch] == symb && !end) {
start = cur.ch + 1; // assign start to ahead of the cursor
} else {
// go backwards to find the start
for (i = cur.ch; i > -1 && !start; i--) {
if (chars[i] == symb) {
start = i + 1;
}
}
}
// look forwards for the end symbol
if (start && !end) {
for (i = start, len = chars.length; i < len && !end; i++) {
if (chars[i] == symb) {
end = i;
}
}
}
// nothing found
if (!start || !end) {
return { start: cur, end: cur };
}
// include the symbols
if (inclusive) {
--start; ++end;
}
return {
start: new Pos(cur.line, start),
end: new Pos(cur.line, end)
};
}
// Search functions
defineOption('pcre', true, 'boolean');
function SearchState() {}
SearchState.prototype = {
getQuery: function() {
return vimGlobalState.query;
},
setQuery: function(query) {
vimGlobalState.query = query;
},
getOverlay: function() {
return this.searchOverlay;
},
setOverlay: function(overlay) {
this.searchOverlay = overlay;
},
isReversed: function() {
return vimGlobalState.isReversed;
},
setReversed: function(reversed) {
vimGlobalState.isReversed = reversed;
},
getScrollbarAnnotate: function() {
return this.annotate;
},
setScrollbarAnnotate: function(annotate) {
this.annotate = annotate;
}
};
function getSearchState(cm) {
var vim = cm.state.vim;
return vim.searchState_ || (vim.searchState_ = new SearchState());
}
function splitBySlash(argString) {
return splitBySeparator(argString, '/');
}
function findUnescapedSlashes(argString) {
return findUnescapedSeparators(argString, '/');
}
function splitBySeparator(argString, separator) {
var slashes = findUnescapedSeparators(argString, separator) || [];
if (!slashes.length) return [];
var tokens = [];
// in case of strings like foo/bar
if (slashes[0] !== 0) return;
for (var i = 0; i < slashes.length; i++) {
if (typeof slashes[i] == 'number')
tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
}
return tokens;
}
function findUnescapedSeparators(str, separator) {
if (!separator)
separator = '/';
var escapeNextChar = false;
var slashes = [];
for (var i = 0; i < str.length; i++) {
var c = str.charAt(i);
if (!escapeNextChar && c == separator) {
slashes.push(i);
}
escapeNextChar = !escapeNextChar && (c == '\\');
}
return slashes;
}
// Translates a search string from ex (vim) syntax into javascript form.
function translateRegex(str) {
// When these match, add a '\' if unescaped or remove one if escaped.
var specials = '|(){';
// Remove, but never add, a '\' for these.
var unescape = '}';
var escapeNextChar = false;
var out = [];
for (var i = -1; i < str.length; i++) {
var c = str.charAt(i) || '';
var n = str.charAt(i+1) || '';
var specialComesNext = (n && specials.indexOf(n) != -1);
if (escapeNextChar) {
if (c !== '\\' || !specialComesNext) {
out.push(c);
}
escapeNextChar = false;
} else {
if (c === '\\') {
escapeNextChar = true;
// Treat the unescape list as special for removing, but not adding '\'.
if (n && unescape.indexOf(n) != -1) {
specialComesNext = true;
}
// Not passing this test means removing a '\'.
if (!specialComesNext || n === '\\') {
out.push(c);
}
} else {
out.push(c);
if (specialComesNext && n !== '\\') {
out.push('\\');
}
}
}
}
return out.join('');
}
// Translates the replace part of a search and replace from ex (vim) syntax into
// javascript form. Similar to translateRegex, but additionally fixes back references
// (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
function translateRegexReplace(str) {
var escapeNextChar = false;
var out = [];
for (var i = -1; i < str.length; i++) {
var c = str.charAt(i) || '';
var n = str.charAt(i+1) || '';
if (charUnescapes[c + n]) {
out.push(charUnescapes[c+n]);
i++;
} else if (escapeNextChar) {
// At any point in the loop, escapeNextChar is true if the previous
// character was a '\' and was not escaped.
out.push(c);
escapeNextChar = false;
} else {
if (c === '\\') {
escapeNextChar = true;
if ((isNumber(n) || n === '$')) {
out.push('$');
} else if (n !== '/' && n !== '\\') {
out.push('\\');
}
} else {
if (c === '$') {
out.push('$');
}
out.push(c);
if (n === '/') {
out.push('\\');
}
}
}
}
return out.join('');
}
// Unescape \ and / in the replace part, for PCRE mode.
var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t', '\\&':'&'};
function unescapeRegexReplace(str) {
var stream = new CodeMirror.StringStream(str);
var output = [];
while (!stream.eol()) {
// Search for \.
while (stream.peek() && stream.peek() != '\\') {
output.push(stream.next());
}
var matched = false;
for (var matcher in unescapes) {
if (stream.match(matcher, true)) {
matched = true;
output.push(unescapes[matcher]);
break;
}
}
if (!matched) {
// Don't change anything
output.push(stream.next());
}
}
return output.join('');
}
/**
* Extract the regular expression from the query and return a Regexp object.
* Returns null if the query is blank.
* If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
* If smartCase is passed in, and the query contains upper case letters,
* then ignoreCase is overridden, and the 'i' flag will not be set.
* If the query contains the /i in the flag part of the regular expression,
* then both ignoreCase and smartCase are ignored, and 'i' will be passed
* through to the Regex object.
*/
function parseQuery(query, ignoreCase, smartCase) {
// First update the last search register
var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
lastSearchRegister.setText(query);
// Check if the query is already a regex.
if (query instanceof RegExp) { return query; }
// First try to extract regex + flags from the input. If no flags found,
// extract just the regex. IE does not accept flags directly defined in
// the regex string in the form /regex/flags
var slashes = findUnescapedSlashes(query);
var regexPart;
var forceIgnoreCase;
if (!slashes.length) {
// Query looks like 'regexp'
regexPart = query;
} else {
// Query looks like 'regexp/...'
regexPart = query.substring(0, slashes[0]);
var flagsPart = query.substring(slashes[0]);
forceIgnoreCase = (flagsPart.indexOf('i') != -1);
}
if (!regexPart) {
return null;
}
if (!getOption('pcre')) {
regexPart = translateRegex(regexPart);
}
if (smartCase) {
ignoreCase = (/^[^A-Z]*$/).test(regexPart);
}
var regexp = new RegExp(regexPart,
(ignoreCase || forceIgnoreCase) ? 'im' : 'm');
return regexp;
}
/**
* dom - Document Object Manipulator
* Usage:
* dom('<tag>'|<node>[, ...{<attributes>|<$styles>}|<child-node>|'<text>'])
* Examples:
* dom('div', {id:'xyz'}, dom('p', 'CM rocks!', {$color:'red'}))
* dom(document.head, dom('script', 'alert("hello!")'))
* Not supported:
* dom('p', ['arrays are objects'], Error('objects specify attributes'))
*/
function dom(n) {
if (typeof n === 'string') n = document.createElement(n);
for (var a, i = 1; i < arguments.length; i++) {
if (!(a = arguments[i])) continue;
if (typeof a !== 'object') a = document.createTextNode(a);
if (a.nodeType) n.appendChild(a);
else for (var key in a) {
if (!Object.prototype.hasOwnProperty.call(a, key)) continue;
if (key[0] === '$') n.style[key.slice(1)] = a[key];
else n.setAttribute(key, a[key]);
}
}
return n;
}
function showConfirm(cm, template) {
var pre = dom('pre', {$color: 'red', class: 'cm-vim-message'}, template);
if (cm.openNotification) {
cm.openNotification(pre, {bottom: true, duration: 5000});
} else {
alert(pre.innerText);
}
}
function makePrompt(prefix, desc) {
return dom(document.createDocumentFragment(),
dom('span', {$fontFamily: 'monospace', $whiteSpace: 'pre'},
prefix,
dom('input', {type: 'text', autocorrect: 'off',
autocapitalize: 'off', spellcheck: 'false'})),
desc && dom('span', {$color: '#888'}, desc));
}
function showPrompt(cm, options) {
var template = makePrompt(options.prefix, options.desc);
if (cm.openDialog) {
cm.openDialog(template, options.onClose, {
onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
bottom: true, selectValueOnOpen: false, value: options.value
});
}
else {
var shortText = '';
if (typeof options.prefix != "string" && options.prefix) shortText += options.prefix.textContent;
if (options.desc) shortText += " " + options.desc;
options.onClose(prompt(shortText, ''));
}
}
function regexEqual(r1, r2) {
if (r1 instanceof RegExp && r2 instanceof RegExp) {
var props = ['global', 'multiline', 'ignoreCase', 'source'];
for (var i = 0; i < props.length; i++) {
var prop = props[i];
if (r1[prop] !== r2[prop]) {
return false;
}
}
return true;
}
return false;
}
// Returns true if the query is valid.
function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
if (!rawQuery) {
return;
}
var state = getSearchState(cm);
var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
if (!query) {
return;
}
highlightSearchMatches(cm, query);
if (regexEqual(query, state.getQuery())) {
return query;
}
state.setQuery(query);
return query;
}
function searchOverlay(query) {
if (query.source.charAt(0) == '^') {
var matchSol = true;
}
return {
token: function(stream) {
if (matchSol && !stream.sol()) {
stream.skipToEnd();
return;
}
var match = stream.match(query, false);
if (match) {
if (match[0].length == 0) {
// Matched empty string, skip to next.
stream.next();
return 'searching';
}
if (!stream.sol()) {
// Backtrack 1 to match \b
stream.backUp(1);
if (!query.exec(stream.next() + match[0])) {
stream.next();
return null;
}
}
stream.match(query);
return 'searching';
}
while (!stream.eol()) {
stream.next();
if (stream.match(query, false)) break;
}
},
query: query
};
}
var highlightTimeout = 0;
function highlightSearchMatches(cm, query) {
clearTimeout(highlightTimeout);
highlightTimeout = setTimeout(function() {
if (!cm.state.vim) return;
var searchState = getSearchState(cm);
var overlay = searchState.getOverlay();
if (!overlay || query != overlay.query) {
if (overlay) {
cm.removeOverlay(overlay);
}
overlay = searchOverlay(query);
cm.addOverlay(overlay);
if (cm.showMatchesOnScrollbar) {
if (searchState.getScrollbarAnnotate()) {
searchState.getScrollbarAnnotate().clear();
}
searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
}
searchState.setOverlay(overlay);
}
}, 50);
}
function findNext(cm, prev, query, repeat) {
if (repeat === undefined) { repeat = 1; }
return cm.operation(function() {
var pos = cm.getCursor();
var cursor = cm.getSearchCursor(query, pos);
for (var i = 0; i < repeat; i++) {
var found = cursor.find(prev);
if (i == 0 && found && cursorEqual(cursor.from(), pos)) {
var lastEndPos = prev ? cursor.from() : cursor.to();
found = cursor.find(prev);
if (found && !found[0] && cursorEqual(cursor.from(), lastEndPos)) {
if (cm.getLine(lastEndPos.line).length == lastEndPos.ch)
found = cursor.find(prev);
}
}
if (!found) {
// SearchCursor may have returned null because it hit EOF, wrap
// around and try again.
cursor = cm.getSearchCursor(query,
(prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
if (!cursor.find(prev)) {
return;
}
}
}
return cursor.from();
});
}
/**
* Pretty much the same as `findNext`, except for the following differences:
*
* 1. Before starting the search, move to the previous search. This way if our cursor is
* already inside a match, we should return the current match.
* 2. Rather than only returning the cursor's from, we return the cursor's from and to as a tuple.
*/
function findNextFromAndToInclusive(cm, prev, query, repeat, vim) {
if (repeat === undefined) { repeat = 1; }
return cm.operation(function() {
var pos = cm.getCursor();
var cursor = cm.getSearchCursor(query, pos);
// Go back one result to ensure that if the cursor is currently a match, we keep it.
var found = cursor.find(!prev);
// If we haven't moved, go back one more (similar to if i==0 logic in findNext).
if (!vim.visualMode && found && cursorEqual(cursor.from(), pos)) {
cursor.find(!prev);
}
for (var i = 0; i < repeat; i++) {
found = cursor.find(prev);
if (!found) {
// SearchCursor may have returned null because it hit EOF, wrap
// around and try again.
cursor = cm.getSearchCursor(query,
(prev) ? new Pos(cm.lastLine()) : new Pos(cm.firstLine(), 0) );
if (!cursor.find(prev)) {
return;
}
}
}
return [cursor.from(), cursor.to()];
});
}
function clearSearchHighlight(cm) {
var state = getSearchState(cm);
cm.removeOverlay(getSearchState(cm).getOverlay());
state.setOverlay(null);
if (state.getScrollbarAnnotate()) {
state.getScrollbarAnnotate().clear();
state.setScrollbarAnnotate(null);
}
}
/**
* Check if pos is in the specified range, INCLUSIVE.
* Range can be specified with 1 or 2 arguments.
* If the first range argument is an array, treat it as an array of line
* numbers. Match pos against any of the lines.
* If the first range argument is a number,
* if there is only 1 range argument, check if pos has the same line
* number
* if there are 2 range arguments, then check if pos is in between the two
* range arguments.
*/
function isInRange(pos, start, end) {
if (typeof pos != 'number') {
// Assume it is a cursor position. Get the line number.
pos = pos.line;
}
if (start instanceof Array) {
return inArray(pos, start);
} else {
if (typeof end == 'number') {
return (pos >= start && pos <= end);
} else {
return pos == start;
}
}
}
function getUserVisibleLines(cm) {
var scrollInfo = cm.getScrollInfo();
var occludeToleranceTop = 6;
var occludeToleranceBottom = 10;
var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
var to = cm.coordsChar({left:0, top: bottomY}, 'local');
return {top: from.line, bottom: to.line};
}
function getMarkPos(cm, vim, markName) {
if (markName == '\'' || markName == '`') {
return vimGlobalState.jumpList.find(cm, -1) || new Pos(0, 0);
} else if (markName == '.') {
return getLastEditPos(cm);
}
var mark = vim.marks[markName];
return mark && mark.find();
}
function getLastEditPos(cm) {
var done = cm.doc.history.done;
for (var i = done.length; i--;) {
if (done[i].changes) {
return copyCursor(done[i].changes[0].to);
}
}
}
var ExCommandDispatcher = function() {
this.buildCommandMap_();
};
ExCommandDispatcher.prototype = {
processCommand: function(cm, input, opt_params) {
var that = this;
cm.operation(function () {
cm.curOp.isVimOp = true;
that._processCommand(cm, input, opt_params);
});
},
_processCommand: function(cm, input, opt_params) {
var vim = cm.state.vim;
var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
var previousCommand = commandHistoryRegister.toString();
if (vim.visualMode) {
exitVisualMode(cm);
}
var inputStream = new CodeMirror.StringStream(input);
// update ": with the latest command whether valid or invalid
commandHistoryRegister.setText(input);
var params = opt_params || {};
params.input = input;
try {
this.parseInput_(cm, inputStream, params);
} catch(e) {
showConfirm(cm, e.toString());
throw e;
}
var command;
var commandName;
if (!params.commandName) {
// If only a line range is defined, move to the line.
if (params.line !== undefined) {
commandName = 'move';
}
} else {
command = this.matchCommand_(params.commandName);
if (command) {
commandName = command.name;
if (command.excludeFromCommandHistory) {
commandHistoryRegister.setText(previousCommand);
}
this.parseCommandArgs_(inputStream, params, command);
if (command.type == 'exToKey') {
// Handle Ex to Key mapping.
for (var i = 0; i < command.toKeys.length; i++) {
vimApi.handleKey(cm, command.toKeys[i], 'mapping');
}
return;
} else if (command.type == 'exToEx') {
// Handle Ex to Ex mapping.
this.processCommand(cm, command.toInput);
return;
}
}
}
if (!commandName) {
showConfirm(cm, 'Not an editor command ":' + input + '"');
return;
}
try {
exCommands[commandName](cm, params);
// Possibly asynchronous commands (e.g. substitute, which might have a
// user confirmation), are responsible for calling the callback when
// done. All others have it taken care of for them here.
if ((!command || !command.possiblyAsync) && params.callback) {
params.callback();
}
} catch(e) {
showConfirm(cm, e.toString());
throw e;
}
},
parseInput_: function(cm, inputStream, result) {
inputStream.eatWhile(':');
// Parse range.
if (inputStream.eat('%')) {
result.line = cm.firstLine();
result.lineEnd = cm.lastLine();
} else {
result.line = this.parseLineSpec_(cm, inputStream);
if (result.line !== undefined && inputStream.eat(',')) {
result.lineEnd = this.parseLineSpec_(cm, inputStream);
}
}
// Parse command name.
var commandMatch = inputStream.match(/^(\w+|!!|@@|[!#&*<=>@~])/);
if (commandMatch) {
result.commandName = commandMatch[1];
} else {
result.commandName = inputStream.match(/.*/)[0];
}
return result;
},
parseLineSpec_: function(cm, inputStream) {
var numberMatch = inputStream.match(/^(\d+)/);
if (numberMatch) {
// Absolute line number plus offset (N+M or N-M) is probably a typo,
// not something the user actually wanted. (NB: vim does allow this.)
return parseInt(numberMatch[1], 10) - 1;
}
switch (inputStream.next()) {
case '.':
return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
case '$':
return this.parseLineSpecOffset_(inputStream, cm.lastLine());
case '\'':
var markName = inputStream.next();
var markPos = getMarkPos(cm, cm.state.vim, markName);
if (!markPos) throw new Error('Mark not set');
return this.parseLineSpecOffset_(inputStream, markPos.line);
case '-':
case '+':
inputStream.backUp(1);
// Offset is relative to current line if not otherwise specified.
return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
default:
inputStream.backUp(1);
return undefined;
}
},
parseLineSpecOffset_: function(inputStream, line) {
var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
if (offsetMatch) {
var offset = parseInt(offsetMatch[2], 10);
if (offsetMatch[1] == "-") {
line -= offset;
} else {
line += offset;
}
}
return line;
},
parseCommandArgs_: function(inputStream, params, command) {
if (inputStream.eol()) {
return;
}
params.argString = inputStream.match(/.*/)[0];
// Parse command-line arguments
var delim = command.argDelimiter || /\s+/;
var args = trim(params.argString).split(delim);
if (args.length && args[0]) {
params.args = args;
}
},
matchCommand_: function(commandName) {
// Return the command in the command map that matches the shortest
// prefix of the passed in command name. The match is guaranteed to be
// unambiguous if the defaultExCommandMap's shortNames are set up
// correctly. (see @code{defaultExCommandMap}).
for (var i = commandName.length; i > 0; i--) {
var prefix = commandName.substring(0, i);
if (this.commandMap_[prefix]) {
var command = this.commandMap_[prefix];
if (command.name.indexOf(commandName) === 0) {
return command;
}
}
}
return null;
},
buildCommandMap_: function() {
this.commandMap_ = {};
for (var i = 0; i < defaultExCommandMap.length; i++) {
var command = defaultExCommandMap[i];
var key = command.shortName || command.name;
this.commandMap_[key] = command;
}
},
map: function(lhs, rhs, ctx) {
if (lhs != ':' && lhs.charAt(0) == ':') {
if (ctx) { throw Error('Mode not supported for ex mappings'); }
var commandName = lhs.substring(1);
if (rhs != ':' && rhs.charAt(0) == ':') {
// Ex to Ex mapping
this.commandMap_[commandName] = {
name: commandName,
type: 'exToEx',
toInput: rhs.substring(1),
user: true
};
} else {
// Ex to key mapping
this.commandMap_[commandName] = {
name: commandName,
type: 'exToKey',
toKeys: rhs,
user: true
};
}
} else {
if (rhs != ':' && rhs.charAt(0) == ':') {
// Key to Ex mapping.
var mapping = {
keys: lhs,
type: 'keyToEx',
exArgs: { input: rhs.substring(1) }
};
if (ctx) { mapping.context = ctx; }
defaultKeymap.unshift(mapping);
} else {
// Key to key mapping
var mapping = {
keys: lhs,
type: 'keyToKey',
toKeys: rhs
};
if (ctx) { mapping.context = ctx; }
defaultKeymap.unshift(mapping);
}
}
},
unmap: function(lhs, ctx) {
if (lhs != ':' && lhs.charAt(0) == ':') {
// Ex to Ex or Ex to key mapping
if (ctx) { throw Error('Mode not supported for ex mappings'); }
var commandName = lhs.substring(1);
if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
delete this.commandMap_[commandName];
return true;
}
} else {
// Key to Ex or key to key mapping
var keys = lhs;
for (var i = 0; i < defaultKeymap.length; i++) {
if (keys == defaultKeymap[i].keys
&& defaultKeymap[i].context === ctx) {
defaultKeymap.splice(i, 1);
return true;
}
}
}
}
};
var exCommands = {
colorscheme: function(cm, params) {
if (!params.args || params.args.length < 1) {
showConfirm(cm, cm.getOption('theme'));
return;
}
cm.setOption('theme', params.args[0]);
},
map: function(cm, params, ctx) {
var mapArgs = params.args;
if (!mapArgs || mapArgs.length < 2) {
if (cm) {
showConfirm(cm, 'Invalid mapping: ' + params.input);
}
return;
}
exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
},
imap: function(cm, params) { this.map(cm, params, 'insert'); },
nmap: function(cm, params) { this.map(cm, params, 'normal'); },
vmap: function(cm, params) { this.map(cm, params, 'visual'); },
unmap: function(cm, params, ctx) {
var mapArgs = params.args;
if (!mapArgs || mapArgs.length < 1 || !exCommandDispatcher.unmap(mapArgs[0], ctx)) {
if (cm) {
showConfirm(cm, 'No such mapping: ' + params.input);
}
}
},
move: function(cm, params) {
commandDispatcher.processCommand(cm, cm.state.vim, {
type: 'motion',
motion: 'moveToLineOrEdgeOfDocument',
motionArgs: { forward: false, explicitRepeat: true,
linewise: true },
repeatOverride: params.line+1});
},
set: function(cm, params) {
var setArgs = params.args;
// Options passed through to the setOption/getOption calls. May be passed in by the
// local/global versions of the set command
var setCfg = params.setCfg || {};
if (!setArgs || setArgs.length < 1) {
if (cm) {
showConfirm(cm, 'Invalid mapping: ' + params.input);
}
return;
}
var expr = setArgs[0].split('=');
var optionName = expr[0];
var value = expr[1];
var forceGet = false;
if (optionName.charAt(optionName.length - 1) == '?') {
// If post-fixed with ?, then the set is actually a get.
if (value) { throw Error('Trailing characters: ' + params.argString); }
optionName = optionName.substring(0, optionName.length - 1);
forceGet = true;
}
if (value === undefined && optionName.substring(0, 2) == 'no') {
// To set boolean options to false, the option name is prefixed with
// 'no'.
optionName = optionName.substring(2);
value = false;
}
var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
if (optionIsBoolean && value == undefined) {
// Calling set with a boolean option sets it to true.
value = true;
}
// If no value is provided, then we assume this is a get.
if (!optionIsBoolean && value === undefined || forceGet) {
var oldValue = getOption(optionName, cm, setCfg);
if (oldValue instanceof Error) {
showConfirm(cm, oldValue.message);
} else if (oldValue === true || oldValue === false) {
showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
} else {
showConfirm(cm, ' ' + optionName + '=' + oldValue);
}
} else {
var setOptionReturn = setOption(optionName, value, cm, setCfg);
if (setOptionReturn instanceof Error) {
showConfirm(cm, setOptionReturn.message);
}
}
},
setlocal: function (cm, params) {
// setCfg is passed through to setOption
params.setCfg = {scope: 'local'};
this.set(cm, params);
},
setglobal: function (cm, params) {
// setCfg is passed through to setOption
params.setCfg = {scope: 'global'};
this.set(cm, params);
},
registers: function(cm, params) {
var regArgs = params.args;
var registers = vimGlobalState.registerController.registers;
var regInfo = '----------Registers----------\n\n';
if (!regArgs) {
for (var registerName in registers) {
var text = registers[registerName].toString();
if (text.length) {
regInfo += '"' + registerName + ' ' + text + '\n'
}
}
} else {
var registerName;
regArgs = regArgs.join('');
for (var i = 0; i < regArgs.length; i++) {
registerName = regArgs.charAt(i);
if (!vimGlobalState.registerController.isValidRegister(registerName)) {
continue;
}
var register = registers[registerName] || new Register();
regInfo += '"' + registerName + ' ' + register.toString() + '\n'
}
}
showConfirm(cm, regInfo);
},
sort: function(cm, params) {
var reverse, ignoreCase, unique, number, pattern;
function parseArgs() {
if (params.argString) {
var args = new CodeMirror.StringStream(params.argString);
if (args.eat('!')) { reverse = true; }
if (args.eol()) { return; }
if (!args.eatSpace()) { return 'Invalid arguments'; }
var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
if (!opts && !args.eol()) { return 'Invalid arguments'; }
if (opts[1]) {
ignoreCase = opts[1].indexOf('i') != -1;
unique = opts[1].indexOf('u') != -1;
var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;
var hex = opts[1].indexOf('x') != -1 && 1;
var octal = opts[1].indexOf('o') != -1 && 1;
if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
}
if (opts[2]) {
pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
}
}
}
var err = parseArgs();
if (err) {
showConfirm(cm, err + ': ' + params.argString);
return;
}
var lineStart = params.line || cm.firstLine();
var lineEnd = params.lineEnd || params.line || cm.lastLine();
if (lineStart == lineEnd) { return; }
var curStart = new Pos(lineStart, 0);
var curEnd = new Pos(lineEnd, lineLength(cm, lineEnd));
var text = cm.getRange(curStart, curEnd).split('\n');
var numberRegex = pattern ? pattern :
(number == 'decimal') ? /(-?)([\d]+)/ :
(number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
(number == 'octal') ? /([0-7]+)/ : null;
var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
var numPart = [], textPart = [];
if (number || pattern) {
for (var i = 0; i < text.length; i++) {
var matchPart = pattern ? text[i].match(pattern) : null;
if (matchPart && matchPart[0] != '') {
numPart.push(matchPart);
} else if (!pattern && numberRegex.exec(text[i])) {
numPart.push(text[i]);
} else {
textPart.push(text[i]);
}
}
} else {
textPart = text;
}
function compareFn(a, b) {
if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
var anum = number && numberRegex.exec(a);
var bnum = number && numberRegex.exec(b);
if (!anum) { return a < b ? -1 : 1; }
anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
return anum - bnum;
}
function comparePatternFn(a, b) {
if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }
return (a[0] < b[0]) ? -1 : 1;
}
numPart.sort(pattern ? comparePatternFn : compareFn);
if (pattern) {
for (var i = 0; i < numPart.length; i++) {
numPart[i] = numPart[i].input;
}
} else if (!number) { textPart.sort(compareFn); }
text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
if (unique) { // Remove duplicate lines
var textOld = text;
var lastLine;
text = [];
for (var i = 0; i < textOld.length; i++) {
if (textOld[i] != lastLine) {
text.push(textOld[i]);
}
lastLine = textOld[i];
}
}
cm.replaceRange(text.join('\n'), curStart, curEnd);
},
vglobal: function(cm, params) {
// global inspects params.commandName
this.global(cm, params);
},
global: function(cm, params) {
// a global command is of the form
// :[range]g/pattern/[cmd]
// argString holds the string /pattern/[cmd]
var argString = params.argString;
if (!argString) {
showConfirm(cm, 'Regular Expression missing from global');
return;
}
var inverted = params.commandName[0] === 'v';
// range is specified here
var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
var lineEnd = params.lineEnd || params.line || cm.lastLine();
// get the tokens from argString
var tokens = splitBySlash(argString);
var regexPart = argString, cmd;
if (tokens.length) {
regexPart = tokens[0];
cmd = tokens.slice(1, tokens.length).join('/');
}
if (regexPart) {
// If regex part is empty, then use the previous query. Otherwise
// use the regex part as the new query.
try {
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
true /** smartCase */);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + regexPart);
return;
}
}
// now that we have the regexPart, search for regex matches in the
// specified range of lines
var query = getSearchState(cm).getQuery();
var matchedLines = [];
for (var i = lineStart; i <= lineEnd; i++) {
var line = cm.getLineHandle(i);
var matched = query.test(line.text);
if (matched !== inverted) {
matchedLines.push(cmd ? line : line.text);
}
}
// if there is no [cmd], just display the list of matched lines
if (!cmd) {
showConfirm(cm, matchedLines.join('\n'));
return;
}
var index = 0;
var nextCommand = function() {
if (index < matchedLines.length) {
var line = matchedLines[index++];
var lineNum = cm.getLineNumber(line);
if (lineNum == null) {
nextCommand();
return;
}
var command = (lineNum + 1) + cmd;
exCommandDispatcher.processCommand(cm, command, {
callback: nextCommand
});
}
};
nextCommand();
},
substitute: function(cm, params) {
if (!cm.getSearchCursor) {
throw new Error('Search feature not available. Requires searchcursor.js or ' +
'any other getSearchCursor implementation.');
}
var argString = params.argString;
var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
var regexPart, replacePart = '', trailing, flagsPart, count;
var confirm = false; // Whether to confirm each replace.
var global = false; // True to replace all instances on a line, false to replace only 1.
if (tokens.length) {
regexPart = tokens[0];
if (getOption('pcre') && regexPart !== '') {
regexPart = new RegExp(regexPart).source; //normalize not escaped characters
}
replacePart = tokens[1];
if (replacePart !== undefined) {
if (getOption('pcre')) {
replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g,"$1$$&"));
} else {
replacePart = translateRegexReplace(replacePart);
}
vimGlobalState.lastSubstituteReplacePart = replacePart;
}
trailing = tokens[2] ? tokens[2].split(' ') : [];
} else {
// either the argString is empty or its of the form ' hello/world'
// actually splitBySlash returns a list of tokens
// only if the string starts with a '/'
if (argString && argString.length) {
showConfirm(cm, 'Substitutions should be of the form ' +
':s/pattern/replace/');
return;
}
}
// After the 3rd slash, we can have flags followed by a space followed
// by count.
if (trailing) {
flagsPart = trailing[0];
count = parseInt(trailing[1]);
if (flagsPart) {
if (flagsPart.indexOf('c') != -1) {
confirm = true;
}
if (flagsPart.indexOf('g') != -1) {
global = true;
}
if (getOption('pcre')) {
regexPart = regexPart + '/' + flagsPart;
} else {
regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
}
}
}
if (regexPart) {
// If regex part is empty, then use the previous query. Otherwise use
// the regex part as the new query.
try {
updateSearchQuery(cm, regexPart, true /** ignoreCase */,
true /** smartCase */);
} catch (e) {
showConfirm(cm, 'Invalid regex: ' + regexPart);
return;
}
}
replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
if (replacePart === undefined) {
showConfirm(cm, 'No previous substitute regular expression');
return;
}
var state = getSearchState(cm);
var query = state.getQuery();
var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
var lineEnd = params.lineEnd || lineStart;
if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
lineEnd = Infinity;
}
if (count) {
lineStart = lineEnd;
lineEnd = lineStart + count - 1;
}
var startPos = clipCursorToContent(cm, new Pos(lineStart, 0));
var cursor = cm.getSearchCursor(query, startPos);
doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
},
redo: CodeMirror.commands.redo,
undo: CodeMirror.commands.undo,
write: function(cm) {
if (CodeMirror.commands.save) {
// If a save command is defined, call it.
CodeMirror.commands.save(cm);
} else if (cm.save) {
// Saves to text area if no save command is defined and cm.save() is available.
cm.save();
}
},
nohlsearch: function(cm) {
clearSearchHighlight(cm);
},
yank: function (cm) {
var cur = copyCursor(cm.getCursor());
var line = cur.line;
var lineText = cm.getLine(line);
vimGlobalState.registerController.pushText(
'0', 'yank', lineText, true, true);
},
delmarks: function(cm, params) {
if (!params.argString || !trim(params.argString)) {
showConfirm(cm, 'Argument required');
return;
}
var state = cm.state.vim;
var stream = new CodeMirror.StringStream(trim(params.argString));
while (!stream.eol()) {
stream.eatSpace();
// Record the streams position at the beginning of the loop for use
// in error messages.
var count = stream.pos;
if (!stream.match(/[a-zA-Z]/, false)) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
var sym = stream.next();
// Check if this symbol is part of a range
if (stream.match('-', true)) {
// This symbol is part of a range.
// The range must terminate at an alphabetic character.
if (!stream.match(/[a-zA-Z]/, false)) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
var startMark = sym;
var finishMark = stream.next();
// The range must terminate at an alphabetic character which
// shares the same case as the start of the range.
if (isLowerCase(startMark) && isLowerCase(finishMark) ||
isUpperCase(startMark) && isUpperCase(finishMark)) {
var start = startMark.charCodeAt(0);
var finish = finishMark.charCodeAt(0);
if (start >= finish) {
showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
return;
}
// Because marks are always ASCII values, and we have
// determined that they are the same case, we can use
// their char codes to iterate through the defined range.
for (var j = 0; j <= finish - start; j++) {
var mark = String.fromCharCode(start + j);
delete state.marks[mark];
}
} else {
showConfirm(cm, 'Invalid argument: ' + startMark + '-');
return;
}
} else {
// This symbol is a valid mark, and is not part of a range.
delete state.marks[sym];
}
}
}
};
var exCommandDispatcher = new ExCommandDispatcher();
/**
* @param {CodeMirror} cm CodeMirror instance we are in.
* @param {boolean} confirm Whether to confirm each replace.
* @param {Cursor} lineStart Line to start replacing from.
* @param {Cursor} lineEnd Line to stop replacing at.
* @param {RegExp} query Query for performing matches with.
* @param {string} replaceWith Text to replace matches with. May contain $1,
* $2, etc for replacing captured groups using JavaScript replace.
* @param {function()} callback A callback for when the replace is done.
*/
function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
replaceWith, callback) {
// Set up all the functions.
cm.state.vim.exMode = true;
var done = false;
var lastPos, modifiedLineNumber, joined;
function replaceAll() {
cm.operation(function() {
while (!done) {
replace();
next();
}
stop();
});
}
function replace() {
var text = cm.getRange(searchCursor.from(), searchCursor.to());
var newText = text.replace(query, replaceWith);
var unmodifiedLineNumber = searchCursor.to().line;
searchCursor.replace(newText);
modifiedLineNumber = searchCursor.to().line;
lineEnd += modifiedLineNumber - unmodifiedLineNumber;
joined = modifiedLineNumber < unmodifiedLineNumber;
}
function findNextValidMatch() {
var lastMatchTo = lastPos && copyCursor(searchCursor.to());
var match = searchCursor.findNext();
if (match && !match[0] && lastMatchTo && cursorEqual(searchCursor.from(), lastMatchTo)) {
match = searchCursor.findNext();
}
return match;
}
function next() {
// The below only loops to skip over multiple occurrences on the same
// line when 'global' is not true.
while(findNextValidMatch() &&
isInRange(searchCursor.from(), lineStart, lineEnd)) {
if (!global && searchCursor.from().line == modifiedLineNumber && !joined) {
continue;
}
cm.scrollIntoView(searchCursor.from(), 30);
cm.setSelection(searchCursor.from(), searchCursor.to());
lastPos = searchCursor.from();
done = false;
return;
}
done = true;
}
function stop(close) {
if (close) { close(); }
cm.focus();
if (lastPos) {
cm.setCursor(lastPos);
var vim = cm.state.vim;
vim.exMode = false;
vim.lastHPos = vim.lastHSPos = lastPos.ch;
}
if (callback) { callback(); }
}
function onPromptKeyDown(e, _value, close) {
// Swallow all keys.
CodeMirror.e_stop(e);
var keyName = CodeMirror.keyName(e);
switch (keyName) {
case 'Y':
replace(); next(); break;
case 'N':
next(); break;
case 'A':
// replaceAll contains a call to close of its own. We don't want it
// to fire too early or multiple times.
var savedCallback = callback;
callback = undefined;
cm.operation(replaceAll);
callback = savedCallback;
break;
case 'L':
replace();
// fall through and exit.
case 'Q':
case 'Esc':
case 'Ctrl-C':
case 'Ctrl-[':
stop(close);
break;
}
if (done) { stop(close); }
return true;
}
// Actually do replace.
next();
if (done) {
showConfirm(cm, 'No matches for ' + query.source);
return;
}
if (!confirm) {
replaceAll();
if (callback) { callback(); }
return;
}
showPrompt(cm, {
prefix: dom('span', 'replace with ', dom('strong', replaceWith), ' (y/n/a/q/l)'),
onKeyDown: onPromptKeyDown
});
}
CodeMirror.keyMap.vim = {
attach: attachVimMap,
detach: detachVimMap,
call: cmKey
};
function exitInsertMode(cm) {
var vim = cm.state.vim;
var macroModeState = vimGlobalState.macroModeState;
var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
var isPlaying = macroModeState.isPlaying;
var lastChange = macroModeState.lastInsertModeChanges;
if (!isPlaying) {
cm.off('change', onChange);
CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
}
if (!isPlaying && vim.insertModeRepeat > 1) {
// Perform insert mode repeat for commands like 3,a and 3,o.
repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
true /** repeatForInsert */);
vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
}
delete vim.insertModeRepeat;
vim.insertMode = false;
cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
cm.setOption('keyMap', 'vim');
cm.setOption('disableInput', true);
cm.toggleOverwrite(false); // exit replace mode if we were in it.
// update the ". register before exiting insert mode
insertModeChangeRegister.setText(lastChange.changes.join(''));
CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
if (macroModeState.isRecording) {
logInsertModeChange(macroModeState);
}
}
function _mapCommand(command) {
defaultKeymap.unshift(command);
}
function mapCommand(keys, type, name, args, extra) {
var command = {keys: keys, type: type};
command[type] = name;
command[type + "Args"] = args;
for (var key in extra)
command[key] = extra[key];
_mapCommand(command);
}
// The timeout in milliseconds for the two-character ESC keymap should be
// adjusted according to your typing speed to prevent false positives.
defineOption('insertModeEscKeysTimeout', 200, 'number');
CodeMirror.keyMap['vim-insert'] = {
// TODO: override navigation keys so that Esc will cancel automatic
// indentation from o, O, i_<CR>
fallthrough: ['default'],
attach: attachVimMap,
detach: detachVimMap,
call: cmKey
};
CodeMirror.keyMap['vim-replace'] = {
'Backspace': 'goCharLeft',
fallthrough: ['vim-insert'],
attach: attachVimMap,
detach: detachVimMap,
call: cmKey
};
function executeMacroRegister(cm, vim, macroModeState, registerName) {
var register = vimGlobalState.registerController.getRegister(registerName);
if (registerName == ':') {
// Read-only register containing last Ex command.
if (register.keyBuffer[0]) {
exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
}
macroModeState.isPlaying = false;
return;
}
var keyBuffer = register.keyBuffer;
var imc = 0;
macroModeState.isPlaying = true;
macroModeState.replaySearchQueries = register.searchQueries.slice(0);
for (var i = 0; i < keyBuffer.length; i++) {
var text = keyBuffer[i];
var match, key;
while (text) {
// Pull off one command key, which is either a single character
// or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
match = (/<\w+-.+?>|<\w+>|./).exec(text);
key = match[0];
text = text.substring(match.index + key.length);
vimApi.handleKey(cm, key, 'macro');
if (vim.insertMode) {
var changes = register.insertModeChanges[imc++].changes;
vimGlobalState.macroModeState.lastInsertModeChanges.changes =
changes;
repeatInsertModeChanges(cm, changes, 1);
exitInsertMode(cm);
}
}
}
macroModeState.isPlaying = false;
}
function logKey(macroModeState, key) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register) {
register.pushText(key);
}
}
function logInsertModeChange(macroModeState) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register && register.pushInsertModeChanges) {
register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
}
}
function logSearchQuery(macroModeState, query) {
if (macroModeState.isPlaying) { return; }
var registerName = macroModeState.latestRegister;
var register = vimGlobalState.registerController.getRegister(registerName);
if (register && register.pushSearchQuery) {
register.pushSearchQuery(query);
}
}
/**
* Listens for changes made in insert mode.
* Should only be active in insert mode.
*/
function onChange(cm, changeObj) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
if (!macroModeState.isPlaying) {
while(changeObj) {
lastChange.expectCursorActivityForChange = true;
if (lastChange.ignoreCount > 1) {
lastChange.ignoreCount--;
} else if (changeObj.origin == '+input' || changeObj.origin == 'paste'
|| changeObj.origin === undefined /* only in testing */) {
var selectionCount = cm.listSelections().length;
if (selectionCount > 1)
lastChange.ignoreCount = selectionCount;
var text = changeObj.text.join('\n');
if (lastChange.maybeReset) {
lastChange.changes = [];
lastChange.maybeReset = false;
}
if (text) {
if (cm.state.overwrite && !/\n/.test(text)) {
lastChange.changes.push([text]);
} else {
lastChange.changes.push(text);
}
}
}
// Change objects may be chained with next.
changeObj = changeObj.next;
}
}
}
/**
* Listens for any kind of cursor activity on CodeMirror.
*/
function onCursorActivity(cm) {
var vim = cm.state.vim;
if (vim.insertMode) {
// Tracking cursor activity in insert mode (for macro support).
var macroModeState = vimGlobalState.macroModeState;
if (macroModeState.isPlaying) { return; }
var lastChange = macroModeState.lastInsertModeChanges;
if (lastChange.expectCursorActivityForChange) {
lastChange.expectCursorActivityForChange = false;
} else {
// Cursor moved outside the context of an edit. Reset the change.
lastChange.maybeReset = true;
}
} else if (!cm.curOp.isVimOp) {
handleExternalSelection(cm, vim);
}
}
function handleExternalSelection(cm, vim) {
var anchor = cm.getCursor('anchor');
var head = cm.getCursor('head');
// Enter or exit visual mode to match mouse selection.
if (vim.visualMode && !cm.somethingSelected()) {
exitVisualMode(cm, false);
} else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
vim.visualMode = true;
vim.visualLine = false;
CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
}
if (vim.visualMode) {
// Bind CodeMirror selection model to vim selection model.
// Mouse selections are considered visual characterwise.
var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
head = offsetCursor(head, 0, headOffset);
anchor = offsetCursor(anchor, 0, anchorOffset);
vim.sel = {
anchor: anchor,
head: head
};
updateMark(cm, vim, '<', cursorMin(head, anchor));
updateMark(cm, vim, '>', cursorMax(head, anchor));
} else if (!vim.insertMode) {
// Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
vim.lastHPos = cm.getCursor().ch;
}
}
/** Wrapper for special keys pressed in insert mode */
function InsertModeKey(keyName) {
this.keyName = keyName;
}
/**
* Handles raw key down events from the text area.
* - Should only be active in insert mode.
* - For recording deletes in insert mode.
*/
function onKeyEventTargetKeyDown(e) {
var macroModeState = vimGlobalState.macroModeState;
var lastChange = macroModeState.lastInsertModeChanges;
var keyName = CodeMirror.keyName(e);
if (!keyName) { return; }
function onKeyFound() {
if (lastChange.maybeReset) {
lastChange.changes = [];
lastChange.maybeReset = false;
}
lastChange.changes.push(new InsertModeKey(keyName));
return true;
}
if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
}
}
/**
* Repeats the last edit, which includes exactly 1 command and at most 1
* insert. Operator and motion commands are read from lastEditInputState,
* while action commands are read from lastEditActionCommand.
*
* If repeatForInsert is true, then the function was called by
* exitInsertMode to repeat the insert mode changes the user just made. The
* corresponding enterInsertMode call was made with a count.
*/
function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
var macroModeState = vimGlobalState.macroModeState;
macroModeState.isPlaying = true;
var isAction = !!vim.lastEditActionCommand;
var cachedInputState = vim.inputState;
function repeatCommand() {
if (isAction) {
commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
} else {
commandDispatcher.evalInput(cm, vim);
}
}
function repeatInsert(repeat) {
if (macroModeState.lastInsertModeChanges.changes.length > 0) {
// For some reason, repeat cw in desktop VIM does not repeat
// insert mode changes. Will conform to that behavior.
repeat = !vim.lastEditActionCommand ? 1 : repeat;
var changeObject = macroModeState.lastInsertModeChanges;
repeatInsertModeChanges(cm, changeObject.changes, repeat);
}
}
vim.inputState = vim.lastEditInputState;
if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
// o and O repeat have to be interlaced with insert repeats so that the
// insertions appear on separate lines instead of the last line.
for (var i = 0; i < repeat; i++) {
repeatCommand();
repeatInsert(1);
}
} else {
if (!repeatForInsert) {
// Hack to get the cursor to end up at the right place. If I is
// repeated in insert mode repeat, cursor will be 1 insert
// change set left of where it should be.
repeatCommand();
}
repeatInsert(repeat);
}
vim.inputState = cachedInputState;
if (vim.insertMode && !repeatForInsert) {
// Don't exit insert mode twice. If repeatForInsert is set, then we
// were called by an exitInsertMode call lower on the stack.
exitInsertMode(cm);
}
macroModeState.isPlaying = false;
}
function repeatInsertModeChanges(cm, changes, repeat) {
function keyHandler(binding) {
if (typeof binding == 'string') {
CodeMirror.commands[binding](cm);
} else {
binding(cm);
}
return true;
}
var head = cm.getCursor('head');
var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
if (visualBlock) {
// Set up block selection again for repeating the changes.
selectForInsert(cm, head, visualBlock + 1);
repeat = cm.listSelections().length;
cm.setCursor(head);
}
for (var i = 0; i < repeat; i++) {
if (visualBlock) {
cm.setCursor(offsetCursor(head, i, 0));
}
for (var j = 0; j < changes.length; j++) {
var change = changes[j];
if (change instanceof InsertModeKey) {
CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
} else if (typeof change == "string") {
cm.replaceSelection(change);
} else {
var start = cm.getCursor();
var end = offsetCursor(start, 0, change[0].length);
cm.replaceRange(change[0], start, end);
cm.setCursor(end);
}
}
}
if (visualBlock) {
cm.setCursor(offsetCursor(head, 0, 1));
}
}
resetVimGlobalState();
return vimApi;
};
// Initialize Vim and make it available as an API.
CodeMirror.Vim = Vim();
});
|
294coder/Efficient-MIF
| 7,300 |
utils/sailency/BackProp.py
|
import numpy as np
import torch
import cv2
from .utils import grad_norm, IG_baseline, interpolation, isotropic_gaussian_kernel
def _add_batch_one(tensor):
"""
Return a tensor with size (1, ) + tensor.size
:param tensor: 2D or 3D tensor
:return: 3D or 4D tensor
"""
return tensor.view((1, ) + tensor.size())
def attribution_objective(attr_func, h, w, window=16):
def calculate_objective(image):
return attr_func(image, h, w, window=window)
return calculate_objective
def saliency_map_gradient(numpy_image, model, attr_func):
img_tensor = torch.from_numpy(numpy_image)
img_tensor.requires_grad_(True)
result = model(_add_batch_one(img_tensor))
target = attr_func(result)
target.backward()
return img_tensor.grad.numpy(), result
def I_gradient(numpy_image, baseline_image, model, attr_objective, fold, interp='linear'):
interpolated = interpolation(numpy_image, baseline_image, fold, mode=interp).astype(np.float32)
grad_list = np.zeros_like(interpolated, dtype=np.float32)
result_list = []
for i in range(fold):
img_tensor = torch.from_numpy(interpolated[i])
img_tensor.requires_grad_(True)
result = model(_add_batch_one(img_tensor))
target = attr_objective(result)
target.backward()
grad = img_tensor.grad.numpy()
grad_list[i] = grad
result_list.append(result)
results_numpy = np.asarray(result_list)
return grad_list, results_numpy, interpolated
def GaussianBlurPath(sigma, fold, l=5):
def path_interpolation_func(cv_numpy_image):
h, w, c = cv_numpy_image.shape
kernel_interpolation = np.zeros((fold + 1, l, l))
image_interpolation = np.zeros((fold, h, w, c))
lambda_derivative_interpolation = np.zeros((fold, h, w, c))
sigma_interpolation = np.linspace(sigma, 0, fold + 1)
for i in range(fold + 1):
kernel_interpolation[i] = isotropic_gaussian_kernel(l, sigma_interpolation[i])
for i in range(fold):
image_interpolation[i] = cv2.filter2D(cv_numpy_image, -1, kernel_interpolation[i + 1])
lambda_derivative_interpolation[i] = cv2.filter2D(cv_numpy_image, -1, (kernel_interpolation[i + 1] - kernel_interpolation[i]) * fold)
return np.moveaxis(image_interpolation, 3, 1).astype(np.float32), \
np.moveaxis(lambda_derivative_interpolation, 3, 1).astype(np.float32)
return path_interpolation_func
def GaussianLinearPath(sigma, fold, l=5):
def path_interpolation_func(cv_numpy_image):
kernel = isotropic_gaussian_kernel(l, sigma)
baseline_image = cv2.filter2D(cv_numpy_image, -1, kernel)
image_interpolation = interpolation(cv_numpy_image, baseline_image, fold, mode='linear').astype(np.float32)
lambda_derivative_interpolation = np.repeat(np.expand_dims(cv_numpy_image - baseline_image, axis=0), fold, axis=0)
return np.moveaxis(image_interpolation, 3, 1).astype(np.float32), \
np.moveaxis(lambda_derivative_interpolation, 3, 1).astype(np.float32)
return path_interpolation_func
def LinearPath(fold):
def path_interpolation_func(cv_numpy_image):
baseline_image = np.zeros_like(cv_numpy_image)
image_interpolation = interpolation(cv_numpy_image, baseline_image, fold, mode='linear').astype(np.float32)
lambda_derivative_interpolation = np.repeat(np.expand_dims(cv_numpy_image - baseline_image, axis=0), fold, axis=0)
return np.moveaxis(image_interpolation, 3, 1).astype(np.float32), \
np.moveaxis(lambda_derivative_interpolation, 3, 1).astype(np.float32)
return path_interpolation_func
def Path_gradient(torch_image, model, attr_objective, path_interpolation_func, cuda=False):
"""
:param path_interpolation_func:
return \lambda(\alpha) and d\lambda(\alpha)/d\alpha, for \alpha\in[0, 1]
This function return pil_numpy_images
:return:
"""
# if cuda:
# model = model.cuda()
cv_numpy_image = [img[0].numpy().transpose([1, 2, 0]) for img in torch_image]
# cv_numpy_image = np.moveaxis(numpy_image, 0, 2)
image_interpolation_list = []
lambda_derivative_interpolation_list = []
for img in cv_numpy_image:
image_interpolation, lambda_derivative_interpolation = path_interpolation_func(img)
image_interpolation_list.append(image_interpolation)
lambda_derivative_interpolation_list.append(lambda_derivative_interpolation)
lambda_derivative_interpolation = np.concatenate([lambda_derivative_interpolation_list[0], lambda_derivative_interpolation_list[2]], axis=1)
grad_accumulate_list = np.zeros_like(lambda_derivative_interpolation)
result_list = []
for i in range(image_interpolation.shape[0]):
# lms, ms, rgb = torch.from_numpy(cv_numpy_image[0]), torch.from_numpy(cv_numpy_image[1]), torch.from_numpy(cv_numpy_image[2])
# lms, ms, rgb = image_interpolation[i] #torch_image
lms, ms, rgb = image_interpolation_list
lms, ms, rgb = torch.from_numpy(lms[i, None]), torch.from_numpy(ms[i, None]), torch.from_numpy(rgb[i, None])
lms.requires_grad_(True)
ms.requires_grad_(True)
rgb.requires_grad_(True)
print(f'processing interpolated image {i} / {image_interpolation.shape[0]}')
if cuda:
result = model.val_step(ms.cuda(), lms.cuda(), rgb.cuda())
target = attr_objective(result)
target.backward()
lms_grad = lms.grad.cpu().numpy()
rgb_grad = rgb.grad.cpu().numpy()
grad = np.concatenate([lms_grad, rgb_grad], axis=1)
if np.any(np.isnan(grad)):
grad[np.isnan(grad)] = 0.0
else:
result = model(_add_batch_one(img_tensor))
target = attr_objective(result)
target.backward()
grad = img_tensor.grad.numpy()
if np.any(np.isnan(grad)):
grad[np.isnan(grad)] = 0.0
grad_accumulate_list[i] = grad * lambda_derivative_interpolation[i]
result_list.append(result.detach().cpu().numpy())
results_numpy = np.asarray(result_list)
return grad_accumulate_list, results_numpy, image_interpolation
def saliency_map_PG(grad_list, result_list):
final_grad = grad_list.mean(axis=0)
return final_grad, result_list[-1]
def saliency_map_P_gradient(
numpy_image, model, attr_objective, path_interpolation_func):
grad_list, result_list, _ = Path_gradient(numpy_image, model, attr_objective, path_interpolation_func)
final_grad = grad_list.mean(axis=0)
return final_grad, result_list[-1]
def saliency_map_I_gradient(
numpy_image, model, attr_objective, baseline='gaus', fold=10, interp='linear'):
"""
:param numpy_image: RGB C x H x W
:param model:
:param attr_func:
:param h:
:param w:
:param window:
:param baseline:
:return:
"""
numpy_baseline = np.moveaxis(IG_baseline(np.moveaxis(numpy_image, 0, 2) * 255., mode=baseline) / 255., 2, 0)
grad_list, result_list, _ = I_gradient(numpy_image, numpy_baseline, model, attr_objective, fold, interp='linear')
final_grad = grad_list.mean(axis=0) * (numpy_image - numpy_baseline)
return final_grad, result_list[-1]
|
281677160/openwrt-package
| 12,976 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_live_relay_simple.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_live_relay.h"
#include "ngx_rtmp_dynamic.h"
#include "ngx_dynamic_resolver.h"
static ngx_live_push_pt next_push;
static ngx_live_pull_pt next_pull;
static ngx_live_push_close_pt next_push_close;
static void *ngx_live_relay_simple_create_app_conf(ngx_conf_t *cf);
static char *ngx_live_relay_simple_merge_app_conf(ngx_conf_t *cf,
void *parent, void *child);
static ngx_int_t ngx_live_relay_simple_postconfiguration(ngx_conf_t *cf);
static char *ngx_live_relay_push(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char *ngx_live_relay_pull(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
typedef struct {
ngx_live_relay_t pull;
ngx_array_t pushes; /* ngx_live_relay_t */
} ngx_live_relay_simple_app_conf_t;
typedef struct {
ngx_live_relay_t *relay;
} ngx_live_relay_simple_ctx_t;
static ngx_command_t ngx_live_relay_simple_commands[] = {
{ ngx_string("push"),
NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_live_relay_push,
NGX_RTMP_APP_CONF_OFFSET,
0,
NULL },
{ ngx_string("pull"),
NGX_RTMP_APP_CONF|NGX_CONF_1MORE,
ngx_live_relay_pull,
NGX_RTMP_APP_CONF_OFFSET,
0,
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_live_relay_simple_module_ctx = {
NULL, /* preconfiguration */
ngx_live_relay_simple_postconfiguration,/* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_live_relay_simple_create_app_conf, /* create app configuration */
ngx_live_relay_simple_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_live_relay_simple_module = {
NGX_MODULE_V1,
&ngx_live_relay_simple_module_ctx, /* module context */
ngx_live_relay_simple_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_live_relay_simple_create_app_conf(ngx_conf_t *cf)
{
ngx_live_relay_simple_app_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_live_relay_simple_app_conf_t));
if (conf == NULL) {
return NULL;
}
if (ngx_array_init(&conf->pushes, cf->pool, 8, sizeof(ngx_live_relay_t))
!= NGX_OK)
{
return NULL;
}
return conf;
}
static char *
ngx_live_relay_simple_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
return NGX_CONF_OK;
}
static void
ngx_live_relay_simple_handler(ngx_event_t *ev)
{
ngx_rtmp_session_t *s;
ngx_live_relay_app_conf_t *lracf;
ngx_live_relay_ctx_t *ctx;
ngx_live_relay_simple_ctx_t *sctx;
ngx_live_relay_t *relay;
s = ev->data;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (!ctx->failed_delay && ev->timedout) { // connect timeout
ngx_log_error(NGX_LOG_ERR, s->log, NGX_ETIMEDOUT,
"simple relay, relay timeout");
s->finalize_reason = NGX_LIVE_RELAY_TIMEOUT;
ngx_rtmp_finalize_session(s);
return;
}
// relay pull, no player or relay push no publisher
if ((s->publishing && s->live_stream->play_ctx == NULL)
|| (!s->publishing && s->live_stream->publish_ctx == NULL))
{
return;
}
lracf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_module);
ngx_add_timer(&ctx->reconnect, lracf->relay_reconnect);
sctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_simple_module);
relay = sctx->relay;
ngx_live_relay_create(s, relay);
}
static ngx_int_t
ngx_live_relay_simple_relay(ngx_rtmp_session_t *s, ngx_live_relay_t *relay,
unsigned publishing)
{
ngx_rtmp_session_t *rs;
ngx_live_relay_ctx_t *ctx, *pctx;
ngx_live_relay_app_conf_t *lracf;
ngx_live_relay_simple_ctx_t *sctx;
rs = ngx_rtmp_create_relay_session(s, &ngx_live_relay_simple_module);
if (rs == NULL) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"relay simple, create relay session failed");
return NGX_DECLINED;
}
rs->publishing = publishing;
rs->live_stream = s->live_stream;
ngx_live_create_ctx(rs, publishing);
sctx = ngx_pcalloc(rs->pool, sizeof(ngx_live_relay_simple_ctx_t));
if (sctx == NULL) {
ngx_log_error(NGX_LOG_ERR, rs->log, 0,
"relay simple, create simple relay ctx failed");
ngx_rtmp_finalize_session(rs);
return NGX_OK;
}
ngx_rtmp_set_ctx(rs, sctx, ngx_live_relay_simple_module);
sctx->relay = relay;
ctx = ngx_rtmp_get_module_ctx(rs, ngx_live_relay_module);
ctx->reconnect.log = rs->log;
ctx->reconnect.data = rs;
ctx->reconnect.handler = ngx_live_relay_simple_handler;
if (s->publishing != rs->publishing) {
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
// normal publisher close, need to trigger pull
if (s->publishing && !s->relay) {
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
// reconnect
pctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (pctx->successd) { // prev relay successd
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
ctx->idx = pctx->idx;
ctx->failed_reconnect = pctx->failed_reconnect;
if (ctx->idx < relay->urls.nelts) { // retry backup url immediately
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
lracf = ngx_rtmp_get_module_app_conf(rs, ngx_live_relay_module);
if (!pctx->reconnect.timer_set) { // prev relay timeout
ctx->failed_reconnect = ngx_min(pctx->failed_reconnect * 2,
lracf->relay_reconnect);
ngx_post_event(&ctx->reconnect, &ngx_posted_events);
return NGX_OK;
}
if (pctx->failed_reconnect) {
ctx->failed_reconnect = ngx_min(pctx->failed_reconnect * 2,
lracf->relay_reconnect);
} else {
ctx->failed_reconnect = lracf->failed_reconnect;
}
ctx->failed_delay = 1;
ngx_add_timer(&ctx->reconnect, ctx->failed_reconnect);
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_simple_push(ngx_rtmp_session_t *s)
{
ngx_live_relay_simple_app_conf_t *rsacf;
ngx_live_relay_t *relay;
ngx_uint_t i;
rsacf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_simple_module);
if (rsacf->pushes.nelts == 0) { // not configured
goto next;
}
if (s->relay && s->static_pull == 0) {
goto next;
}
relay = rsacf->pushes.elts;
for (i = 0; i < rsacf->pushes.nelts; ++i, ++relay) {
ngx_live_relay_simple_relay(s, relay, 0);
}
next:
return next_push(s);
}
static ngx_int_t
ngx_live_relay_simple_pull(ngx_rtmp_session_t *s)
{
ngx_live_relay_simple_app_conf_t *rsacf;
ngx_live_relay_t *relay;
rsacf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_simple_module);
if (rsacf->pull.urls.nelts == 0) { // not configured
goto next;
}
if (!s->publishing && s->relay) { // relay push
goto next;
}
if (s->live_stream->publish_ctx) { // already has publisher
goto next;
}
relay = &rsacf->pull;
if (ngx_live_relay_simple_relay(s, relay, 1) == NGX_OK) {
return NGX_OK;
}
next:
return next_pull(s);
}
static ngx_int_t
ngx_live_relay_simple_push_close(ngx_rtmp_session_t *s)
{
ngx_live_relay_ctx_t *ctx;
ngx_live_relay_simple_ctx_t *sctx;
ngx_live_relay_t *relay;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx->tag != &ngx_live_relay_simple_module) {
goto next;
}
// relay push and has publisher in stream
if (!ctx->giveup && s->live_stream->publish_ctx) {
sctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_simple_module);
relay = sctx->relay;
ngx_live_relay_simple_relay(s, relay, 0);
}
next:
return next_push_close(s);
}
static char *
ngx_live_relay_push_pull(ngx_conf_t *cf, ngx_live_relay_t *relay)
{
ngx_live_relay_url_t *url;
ngx_str_t *value, n, v;
ngx_uint_t i;
u_char *p;
relay->tag = &ngx_live_relay_simple_module;
if (ngx_array_init(&relay->urls, cf->pool, 8, sizeof(ngx_live_relay_url_t))
!= NGX_OK)
{
return NGX_CONF_ERROR;
}
value = cf->args->elts;
++value;
for (i = 1; i < cf->args->nelts; ++i, ++value) {
if (ngx_strncasecmp(value->data, (u_char *) "rtmp://", 7) == 0
|| ngx_strncasecmp(value->data, (u_char *) "http://", 7) == 0)
{
url = ngx_array_push(&relay->urls);
if (url == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(url, sizeof(ngx_live_relay_url_t));
if (value->data[0] == 'h') {
url->relay_type = NGX_LIVE_RELAY_HTTPFLV;
} else {
url->relay_type = NGX_LIVE_RELAY_RTMP;
}
if (ngx_parse_request_url(&url->url, value) != NGX_OK) {
return NGX_CONF_ERROR;
}
url->port = ngx_request_port(&url->url.scheme, &url->url.port);
if (url->port == 0) {
return "invalid port";
}
ngx_dynamic_resolver_add_domain(&url->url.host, cf->cycle);
continue;
}
p = ngx_strlchr(value->data, value->data + value->len, '=');
if (p == NULL) {
return "unsupported parameter format";
} else {
n.data = value->data;
n.len = p - value->data;
v.data = p + 1;
v.len = value->data + value->len - v.data;
}
#define NGX_LIVE_RELAY_STR_PAR(name, var) \
if (n.len == sizeof(name) - 1 \
&& ngx_strncasecmp(n.data, (u_char *) name, n.len) == 0) \
{ \
relay->var = v; \
continue; \
}
NGX_LIVE_RELAY_STR_PAR("domain", domain);
NGX_LIVE_RELAY_STR_PAR("app", app);
NGX_LIVE_RELAY_STR_PAR("name", name);
NGX_LIVE_RELAY_STR_PAR("pargs", pargs);
NGX_LIVE_RELAY_STR_PAR("referer", referer);
NGX_LIVE_RELAY_STR_PAR("user_agent", user_agent);
#undef NGX_LIVE_RELAY_STR_PAR
return "unsupported parameter";
}
return NGX_CONF_OK;
}
static char *
ngx_live_relay_push(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_live_relay_simple_app_conf_t *rsacf;
ngx_live_relay_t *relay;
char *rc;
rsacf = conf;
relay = ngx_array_push(&rsacf->pushes);
if (relay == NULL) {
return NGX_CONF_ERROR;
}
ngx_memzero(relay, sizeof(ngx_live_relay_t));
rc = ngx_live_relay_push_pull(cf, relay);
if (rc != NGX_CONF_OK) {
return rc;
}
return NGX_CONF_OK;
}
static char *
ngx_live_relay_pull(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_live_relay_simple_app_conf_t *rsacf;
rsacf = conf;
if (rsacf->pull.urls.nelts) {
return "is duplicate";
}
return ngx_live_relay_push_pull(cf, &rsacf->pull);
}
static ngx_int_t
ngx_live_relay_simple_postconfiguration(ngx_conf_t *cf)
{
/* chain handlers */
next_push = ngx_live_push;
ngx_live_push = ngx_live_relay_simple_push;
next_pull = ngx_live_pull;
ngx_live_pull = ngx_live_relay_simple_pull;
next_push_close = ngx_live_push_close;
ngx_live_push_close = ngx_live_relay_simple_push_close;
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 16,334 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/keymap/emacs.js
|
// 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 cmds = CodeMirror.commands;
var Pos = CodeMirror.Pos;
function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
// Kill 'ring'
var killRing = [];
function addToRing(str) {
killRing.push(str);
if (killRing.length > 50) killRing.shift();
}
function growRingTop(str) {
if (!killRing.length) return addToRing(str);
killRing[killRing.length - 1] += str;
}
function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
var lastKill = null;
// Internal generic kill function, used by several mapped kill "family" functions.
function _kill(cm, from, to, ring, text) {
if (text == null) text = cm.getRange(from, to);
if (ring == "grow" && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
growRingTop(text);
else if (ring !== false)
addToRing(text);
cm.replaceRange("", from, to, "+delete");
if (ring == "grow") lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
else lastKill = null;
}
// Boundaries of various units
function byChar(cm, pos, dir) {
return cm.findPosH(pos, dir, "char", true);
}
function byWord(cm, pos, dir) {
return cm.findPosH(pos, dir, "word", true);
}
function byLine(cm, pos, dir) {
return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
}
function byPage(cm, pos, dir) {
return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
}
function byParagraph(cm, pos, dir) {
var no = pos.line, line = cm.getLine(no);
var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
var fst = cm.firstLine(), lst = cm.lastLine();
for (;;) {
no += dir;
if (no < fst || no > lst)
return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
line = cm.getLine(no);
var hasText = /\S/.test(line);
if (hasText) sawText = true;
else if (sawText) return Pos(no, 0);
}
}
function bySentence(cm, pos, dir) {
var line = pos.line, ch = pos.ch;
var text = cm.getLine(pos.line), sawWord = false;
for (;;) {
var next = text.charAt(ch + (dir < 0 ? -1 : 0));
if (!next) { // End/beginning of line reached
if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
text = cm.getLine(line + dir);
if (!/\S/.test(text)) return Pos(line, ch);
line += dir;
ch = dir < 0 ? text.length : 0;
continue;
}
if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
if (!sawWord) sawWord = /\w/.test(next);
ch += dir;
}
}
function byExpr(cm, pos, dir) {
var wrap;
if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, {strict: true}))
&& wrap.match && (wrap.forward ? 1 : -1) == dir)
return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
for (var first = true;; first = false) {
var token = cm.getTokenAt(pos);
var after = Pos(pos.line, dir < 0 ? token.start : token.end);
if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
var newPos = cm.findPosH(after, dir, "char");
if (posEq(after, newPos)) return pos;
else pos = newPos;
} else {
return after;
}
}
}
// Prefixes (only crudely supported)
function getPrefix(cm, precise) {
var digits = cm.state.emacsPrefix;
if (!digits) return precise ? null : 1;
clearPrefix(cm);
return digits == "-" ? -1 : Number(digits);
}
function repeated(cmd) {
var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
return function(cm) {
var prefix = getPrefix(cm);
f(cm);
for (var i = 1; i < prefix; ++i) f(cm);
};
}
function findEnd(cm, pos, by, dir) {
var prefix = getPrefix(cm);
if (prefix < 0) { dir = -dir; prefix = -prefix; }
for (var i = 0; i < prefix; ++i) {
var newPos = by(cm, pos, dir);
if (posEq(newPos, pos)) break;
pos = newPos;
}
return pos;
}
function move(by, dir) {
var f = function(cm) {
cm.extendSelection(findEnd(cm, cm.getCursor(), by, dir));
};
f.motion = true;
return f;
}
function killTo(cm, by, dir, ring) {
var selections = cm.listSelections(), cursor;
var i = selections.length;
while (i--) {
cursor = selections[i].head;
_kill(cm, cursor, findEnd(cm, cursor, by, dir), ring);
}
}
function _killRegion(cm, ring) {
if (cm.somethingSelected()) {
var selections = cm.listSelections(), selection;
var i = selections.length;
while (i--) {
selection = selections[i];
_kill(cm, selection.anchor, selection.head, ring);
}
return true;
}
}
function addPrefix(cm, digit) {
if (cm.state.emacsPrefix) {
if (digit != "-") cm.state.emacsPrefix += digit;
return;
}
// Not active yet
cm.state.emacsPrefix = digit;
cm.on("keyHandled", maybeClearPrefix);
cm.on("inputRead", maybeDuplicateInput);
}
var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
function maybeClearPrefix(cm, arg) {
if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
clearPrefix(cm);
}
function clearPrefix(cm) {
cm.state.emacsPrefix = null;
cm.off("keyHandled", maybeClearPrefix);
cm.off("inputRead", maybeDuplicateInput);
}
function maybeDuplicateInput(cm, event) {
var dup = getPrefix(cm);
if (dup > 1 && event.origin == "+input") {
var one = event.text.join("\n"), txt = "";
for (var i = 1; i < dup; ++i) txt += one;
cm.replaceSelection(txt);
}
}
function maybeRemovePrefixMap(cm, arg) {
if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
cm.removeKeyMap(prefixMap);
cm.state.emacsPrefixMap = false;
cm.off("keyHandled", maybeRemovePrefixMap);
cm.off("inputRead", maybeRemovePrefixMap);
}
// Utilities
cmds.setMark = function (cm) {
cm.setCursor(cm.getCursor());
cm.setExtending(!cm.getExtending());
cm.on("change", function() { cm.setExtending(false); });
}
function clearMark(cm) {
cm.setExtending(false);
cm.setCursor(cm.getCursor());
}
function makePrompt(msg) {
var fragment = document.createDocumentFragment();
var input = document.createElement("input");
input.setAttribute("type", "text");
input.style.width = "10em";
fragment.appendChild(document.createTextNode(msg + ": "));
fragment.appendChild(input);
return fragment;
}
function getInput(cm, msg, f) {
if (cm.openDialog)
cm.openDialog(makePrompt(msg), f, {bottom: true});
else
f(prompt(msg, ""));
}
function operateOnWord(cm, op) {
var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
cm.replaceRange(op(cm.getRange(start, end)), start, end);
cm.setCursor(end);
}
function toEnclosingExpr(cm) {
var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
var stack = [];
while (line >= cm.firstLine()) {
var text = cm.getLine(line);
for (var i = ch == null ? text.length : ch; i > 0;) {
var ch = text.charAt(--i);
if (ch == ")")
stack.push("(");
else if (ch == "]")
stack.push("[");
else if (ch == "}")
stack.push("{");
else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
return cm.extendSelection(Pos(line, i));
}
--line; ch = null;
}
}
// Commands. Names should match emacs function names (albeit in camelCase)
// except where emacs function names collide with code mirror core commands.
cmds.killRegion = function(cm) {
_kill(cm, cm.getCursor("start"), cm.getCursor("end"), true);
};
// Maps to emacs kill-line
cmds.killLineEmacs = repeated(function(cm) {
var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
var text = cm.getRange(start, end);
if (!/\S/.test(text)) {
text += "\n";
end = Pos(start.line + 1, 0);
}
_kill(cm, start, end, "grow", text);
});
cmds.killRingSave = function(cm) {
addToRing(cm.getSelection());
clearMark(cm);
};
cmds.yank = function(cm) {
var start = cm.getCursor();
cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
cm.setSelection(start, cm.getCursor());
};
cmds.yankPop = function(cm) {
cm.replaceSelection(popFromRing(), "around", "paste");
};
cmds.forwardChar = move(byChar, 1);
cmds.backwardChar = move(byChar, -1)
cmds.deleteChar = function(cm) { killTo(cm, byChar, 1, false); };
cmds.deleteForwardChar = function(cm) {
_killRegion(cm, false) || killTo(cm, byChar, 1, false);
};
cmds.deleteBackwardChar = function(cm) {
_killRegion(cm, false) || killTo(cm, byChar, -1, false);
};
cmds.forwardWord = move(byWord, 1);
cmds.backwardWord = move(byWord, -1);
cmds.killWord = function(cm) { killTo(cm, byWord, 1, "grow"); };
cmds.backwardKillWord = function(cm) { killTo(cm, byWord, -1, "grow"); };
cmds.nextLine = move(byLine, 1);
cmds.previousLine = move(byLine, -1);
cmds.scrollDownCommand = move(byPage, -1);
cmds.scrollUpCommand = move(byPage, 1);
cmds.backwardParagraph = move(byParagraph, -1);
cmds.forwardParagraph = move(byParagraph, 1);
cmds.backwardSentence = move(bySentence, -1);
cmds.forwardSentence = move(bySentence, 1);
cmds.killSentence = function(cm) { killTo(cm, bySentence, 1, "grow"); };
cmds.backwardKillSentence = function(cm) {
_kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), "grow");
};
cmds.killSexp = function(cm) { killTo(cm, byExpr, 1, "grow"); };
cmds.backwardKillSexp = function(cm) { killTo(cm, byExpr, -1, "grow"); };
cmds.forwardSexp = move(byExpr, 1);
cmds.backwardSexp = move(byExpr, -1);
cmds.markSexp = function(cm) {
var cursor = cm.getCursor();
cm.setSelection(findEnd(cm, cursor, byExpr, 1), cursor);
};
cmds.transposeSexps = function(cm) {
var leftStart = byExpr(cm, cm.getCursor(), -1);
var leftEnd = byExpr(cm, leftStart, 1);
var rightEnd = byExpr(cm, leftEnd, 1);
var rightStart = byExpr(cm, rightEnd, -1);
cm.replaceRange(cm.getRange(rightStart, rightEnd) +
cm.getRange(leftEnd, rightStart) +
cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
};
cmds.backwardUpList = repeated(toEnclosingExpr);
cmds.justOneSpace = function(cm) {
var pos = cm.getCursor(), from = pos.ch;
var to = pos.ch, text = cm.getLine(pos.line);
while (from && /\s/.test(text.charAt(from - 1))) --from;
while (to < text.length && /\s/.test(text.charAt(to))) ++to;
cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
};
cmds.openLine = repeated(function(cm) {
cm.replaceSelection("\n", "start");
});
// maps to emacs 'transpose-chars'
cmds.transposeCharsRepeatable = repeated(function(cm) {
cm.execCommand("transposeChars");
});
cmds.capitalizeWord = repeated(function(cm) {
operateOnWord(cm, function(w) {
var letter = w.search(/\w/);
if (letter == -1) return w;
return w.slice(0, letter) + w.charAt(letter).toUpperCase() +
w.slice(letter + 1).toLowerCase();
});
});
cmds.upcaseWord = repeated(function(cm) {
operateOnWord(cm, function(w) { return w.toUpperCase(); });
});
cmds.downcaseWord = repeated(function(cm) {
operateOnWord(cm, function(w) { return w.toLowerCase(); });
});
// maps to emacs 'undo'
cmds.undoRepeatable = repeated("undo");
cmds.keyboardQuit = function(cm) {
cm.execCommand("clearSearch");
clearMark(cm);
}
cmds.newline = repeated(function(cm) { cm.replaceSelection("\n", "end"); });
cmds.gotoLine = function(cm) {
var prefix = getPrefix(cm, true);
if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
getInput(cm, "Goto line", function(str) {
var num;
if (str && !isNaN(num = Number(str)) && num == (num|0) && num > 0)
cm.setCursor(num - 1);
});
};
cmds.indentRigidly = function(cm) {
cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
};
cmds.exchangePointAndMark = function(cm) {
cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
};
cmds.quotedInsertTab = repeated("insertTab");
cmds.universalArgument = function addPrefixMap(cm) {
cm.state.emacsPrefixMap = true;
cm.addKeyMap(prefixMap);
cm.on("keyHandled", maybeRemovePrefixMap);
cm.on("inputRead", maybeRemovePrefixMap);
};
CodeMirror.emacs = {kill: _kill, killRegion: _killRegion, repeated: repeated};
// Actual keymap
var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({
"Ctrl-W": "killRegion",
"Ctrl-K": "killLineEmacs",
"Alt-W": "killRingSave",
"Ctrl-Y": "yank",
"Alt-Y": "yankPop",
"Ctrl-Space": "setMark",
"Ctrl-Shift-2": "setMark",
"Ctrl-F": "forwardChar",
"Ctrl-B": "backwardChar",
"Right": "forwardChar",
"Left": "backwardChar",
"Ctrl-D": "deleteChar",
"Delete": "deleteForwardChar",
"Ctrl-H": "deleteBackwardChar",
"Backspace": "deleteBackwardChar",
"Alt-F": "forwardWord",
"Alt-B": "backwardWord",
"Alt-Right": "forwardWord",
"Alt-Left": "backwardWord",
"Alt-D": "killWord",
"Alt-Backspace": "backwardKillWord",
"Ctrl-N": "nextLine",
"Ctrl-P": "previousLine",
"Down": "nextLine",
"Up": "previousLine",
"Ctrl-A": "goLineStart",
"Ctrl-E": "goLineEnd",
"End": "goLineEnd",
"Home": "goLineStart",
"Alt-V": "scrollDownCommand",
"Ctrl-V": "scrollUpCommand",
"PageUp": "scrollDownCommand",
"PageDown": "scrollUpCommand",
"Ctrl-Up": "backwardParagraph",
"Ctrl-Down": "forwardParagraph",
"Alt-{": "backwardParagraph",
"Alt-}": "forwardParagraph",
"Alt-A": "backwardSentence",
"Alt-E": "forwardSentence",
"Alt-K": "killSentence",
"Ctrl-X Delete": "backwardKillSentence",
"Ctrl-Alt-K": "killSexp",
"Ctrl-Alt-Backspace": "backwardKillSexp",
"Ctrl-Alt-F": "forwardSexp",
"Ctrl-Alt-B": "backwardSexp",
"Shift-Ctrl-Alt-2": "markSexp",
"Ctrl-Alt-T": "transposeSexps",
"Ctrl-Alt-U": "backwardUpList",
"Alt-Space": "justOneSpace",
"Ctrl-O": "openLine",
"Ctrl-T": "transposeCharsRepeatable",
"Alt-C": "capitalizeWord",
"Alt-U": "upcaseWord",
"Alt-L": "downcaseWord",
"Alt-;": "toggleComment",
"Ctrl-/": "undoRepeatable",
"Shift-Ctrl--": "undoRepeatable",
"Ctrl-Z": "undoRepeatable",
"Cmd-Z": "undoRepeatable",
"Ctrl-X U": "undoRepeatable",
"Shift-Ctrl-Z": "redo",
"Shift-Alt-,": "goDocStart",
"Shift-Alt-.": "goDocEnd",
"Ctrl-S": "findPersistentNext",
"Ctrl-R": "findPersistentPrev",
"Ctrl-G": "keyboardQuit",
"Shift-Alt-5": "replace",
"Alt-/": "autocomplete",
"Enter": "newlineAndIndent",
"Ctrl-J": "newline",
"Tab": "indentAuto",
"Alt-G G": "gotoLine",
"Ctrl-X Tab": "indentRigidly",
"Ctrl-X Ctrl-X": "exchangePointAndMark",
"Ctrl-X Ctrl-S": "save",
"Ctrl-X Ctrl-W": "save",
"Ctrl-X S": "saveAll",
"Ctrl-X F": "open",
"Ctrl-X K": "close",
"Ctrl-X H": "selectAll",
"Ctrl-Q Tab": "quotedInsertTab",
"Ctrl-U": "universalArgument",
"fallthrough": "default"
});
var prefixMap = {"Ctrl-G": clearPrefix};
function regPrefix(d) {
prefixMap[d] = function(cm) { addPrefix(cm, d); };
keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
prefixPreservingKeys["Ctrl-" + d] = true;
}
for (var i = 0; i < 10; ++i) regPrefix(String(i));
regPrefix("-");
});
|
294coder/Efficient-MIF
| 8,074 |
utils/sailency/utils.py
|
import numpy as np
import cv2
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib as mpl
from PIL import Image
import cv2
import torchvision
def PIL2Tensor(pil_image):
return torchvision.transforms.functional.to_tensor(pil_image)
def Tensor2PIL(tensor_image, mode="RGB"):
if len(tensor_image.size()) == 4 and tensor_image.size()[0] == 1:
tensor_image = tensor_image.view(tensor_image.size()[1:])
return torchvision.transforms.functional.to_pil_image(
tensor_image.detach(), mode=mode
)
def cv2_to_pil(img):
image = Image.fromarray(cv2.cvtColor(img.astype(np.uint8), cv2.COLOR_BGR2RGB))
return image
def pil_to_cv2(img):
image = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
return image
def make_pil_grid(pil_image_list):
sizex, sizey = pil_image_list[0].size
for img in pil_image_list:
assert sizex == img.size[0] and sizey == img.size[1], "check image size"
target = Image.new("RGB", (sizex * len(pil_image_list), sizey))
left = 0
right = sizex
for i in range(len(pil_image_list)):
target.paste(pil_image_list[i], (left, 0, right, sizey))
left += sizex
right += sizex
return target
def blend_input(map, input):
return Image.blend(map, input, 0.4)
def count_saliency_pixels(map, threshold=0.95):
sum_threshold = map.reshape(-1).sum() * threshold
cum_sum = -np.cumsum(np.sort(-map.reshape(-1)))
return len(cum_sum[cum_sum < sum_threshold])
def plot_diff_of_attrs_kde(A, B, zoomin=4, blend=0.5):
grad_flat = A.reshape((-1))
datapoint_y, datapoint_x = np.mgrid[0 : A.shape[0] : 1, 0 : A.shape[1] : 1]
Y, X = np.mgrid[0 : A.shape[0] : 1, 0 : A.shape[1] : 1]
positions = np.vstack([X.ravel(), Y.ravel()])
pixels = np.vstack([datapoint_x.ravel(), datapoint_y.ravel()])
kernel = stats.gaussian_kde(pixels, weights=grad_flat)
Za = np.reshape(kernel(positions).T, A.shape)
Za = Za / Za.max()
grad_flat = B.reshape((-1))
datapoint_y, datapoint_x = np.mgrid[0 : B.shape[0] : 1, 0 : B.shape[1] : 1]
Y, X = np.mgrid[0 : B.shape[0] : 1, 0 : B.shape[1] : 1]
positions = np.vstack([X.ravel(), Y.ravel()])
pixels = np.vstack([datapoint_x.ravel(), datapoint_y.ravel()])
kernel = stats.gaussian_kde(pixels, weights=grad_flat)
Zb = np.reshape(kernel(positions).T, B.shape)
Zb = Zb / Zb.max()
diff = Za - Zb
diff_norm = diff / diff.max()
vis = Zb - blend * diff_norm
cmap = plt.get_cmap("seismic")
# cmap = plt.get_cmap('Purples')
map_color = (255 * cmap(vis * 0.5 + 0.5)).astype(np.uint8)
# map_color = (255 * cmap(Z)).astype(np.uint8)
Img = Image.fromarray(map_color)
s1, s2 = Img.size
return Img.resize((s1 * zoomin, s2 * zoomin), Image.BICUBIC)
def vis_saliency_kde(map, zoomin=4):
grad_flat = map.reshape((-1))
datapoint_y, datapoint_x = np.mgrid[0 : map.shape[0] : 1, 0 : map.shape[1] : 1]
Y, X = np.mgrid[0 : map.shape[0] : 1, 0 : map.shape[1] : 1]
positions = np.vstack([X.ravel(), Y.ravel()])
pixels = np.vstack([datapoint_x.ravel(), datapoint_y.ravel()])
kernel = stats.gaussian_kde(pixels, weights=grad_flat)
Z = np.reshape(kernel(positions).T, map.shape)
Z = Z / Z.max()
cmap = plt.get_cmap("seismic")
# cmap = plt.get_cmap('Purples')
map_color = (255 * cmap(Z * 0.5 + 0.5)).astype(np.uint8)
# map_color = (255 * cmap(Z)).astype(np.uint8)
Img = Image.fromarray(map_color)
s1, s2 = Img.size
return Img.resize((s1 * zoomin, s2 * zoomin), Image.BICUBIC)
def vis_saliency(map, zoomin=4):
"""
:param map: the saliency map, 2D, norm to [0, 1]
:param zoomin: the resize factor, nn upsample
:return:
"""
cmap = plt.get_cmap("seismic")
# cmap = plt.get_cmap('Purples')
map_color = (255 * cmap(map * 0.5 + 0.5)).astype(np.uint8)
# map_color = (255 * cmap(map)).astype(np.uint8)
Img = Image.fromarray(map_color)
s1, s2 = Img.size
Img = Img.resize((s1 * zoomin, s2 * zoomin), Image.NEAREST)
return Img.convert("RGB")
def click_select_position(pil_img, window_size=16):
"""
:param pil_img:
:param window_size:
:return: w, h
"""
cv2_img = pil_to_cv2(pil_img)
position = [-1, -1]
def mouse(event, x, y, flags, param):
""""""
if event == cv2.EVENT_LBUTTONDOWN:
xy = "%d, %d" % (x, y)
position[0] = x
position[1] = y
draw_img = cv2_img.copy()
cv2.rectangle(
draw_img, (x, y), (x + window_size, y + window_size), (0, 0, 255), 2
)
cv2.putText(
draw_img,
xy,
(x, y),
cv2.FONT_HERSHEY_PLAIN,
1.0,
(255, 255, 255),
thickness=1,
)
cv2.imshow("image", draw_img)
cv2.namedWindow("image")
cv2.imshow("image", cv2_img)
cv2.resizeWindow("image", 800, 600)
cv2.setMouseCallback("image", mouse)
cv2.waitKey(0)
cv2.destroyAllWindows()
return_img = cv2_img.copy()
cv2.rectangle(
return_img,
(position[0], position[1]),
(position[0] + window_size, position[1] + window_size),
(0, 0, 255),
2,
)
return position[0], position[1], cv2_to_pil(return_img)
def prepare_images(hr_path, scale=4):
hr_pil = Image.open(hr_path)
sizex, sizey = hr_pil.size
hr_pil = hr_pil.crop((0, 0, sizex - sizex % scale, sizey - sizey % scale))
sizex, sizey = hr_pil.size
lr_pil = hr_pil.resize((sizex // scale, sizey // scale), Image.BICUBIC)
return lr_pil, hr_pil
def grad_abs_norm(grad):
"""
:param grad: numpy array
:return:
"""
grad_2d = np.abs(grad.sum(axis=0))
grad_max = grad_2d.max()
grad_norm = grad_2d / grad_max
return grad_norm
def grad_norm(grad):
"""
:param grad: numpy array
:return:
"""
grad_2d = grad.sum(axis=0)
grad_max = max(grad_2d.max(), abs(grad_2d.min()))
grad_norm = grad_2d / grad_max
return grad_norm
def grad_abs_norm_singlechannel(grad):
"""
:param grad: numpy array
:return:
"""
grad_2d = np.abs(grad)
grad_max = grad_2d.max()
grad_norm = grad_2d / grad_max
return grad_norm
def IG_baseline(numpy_image, mode="gaus"):
"""
:param numpy_image: cv2 image
:param mode:
:return:
"""
if mode == "l1":
raise NotImplementedError()
elif mode == "gaus":
ablated = cv2.GaussianBlur(numpy_image, (7, 7), 0)
elif mode == "bif":
ablated = cv2.bilateralFilter(numpy_image, 15, 90, 90)
elif mode == "mean":
ablated = cv2.medianBlur(numpy_image, 5)
else:
ablated = cv2.GaussianBlur(numpy_image, (7, 7), 0)
return ablated
def interpolation(x, x_prime, fold, mode="linear"):
diff = x - x_prime
l = np.linspace(0, 1, fold).reshape((fold, 1, 1, 1))
interp_list = l * diff + x_prime
return interp_list
def isotropic_gaussian_kernel(l, sigma, epsilon=1e-5):
ax = np.arange(-l // 2 + 1.0, l // 2 + 1.0)
xx, yy = np.meshgrid(ax, ax)
kernel = np.exp(-(xx ** 2 + yy ** 2) / (2.0 * (sigma + epsilon) ** 2))
return kernel / np.sum(kernel)
def gini(array):
"""Calculate the Gini coefficient of a numpy array."""
# based on bottom eq:
# http://www.statsdirect.com/help/generatedimages/equations/equation154.svg
# from:
# http://www.statsdirect.com/help/default.htm#nonparametric_methods/gini.htm
# All values are treated equally, arrays must be 1d:
array = array.flatten()
if np.amin(array) < 0:
# Values cannot be negative:
array -= np.amin(array)
# Values cannot be 0:
array += 0.0000001
# Values must be sorted:
array = np.sort(array)
# Index per array element:
index = np.arange(1, array.shape[0] + 1)
# Number of array elements:
n = array.shape[0]
# Gini coefficient:
return (np.sum((2 * index - n - 1) * array)) / (n * np.sum(array))
|
281677160/openwrt-package
| 11,439 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_receive.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp.h"
#include "ngx_rtmp_amf.h"
#include "ngx_rtmp_cmd_module.h"
#include <string.h>
ngx_int_t
ngx_rtmp_protocol_message_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in)
{
ngx_buf_t *b;
u_char *p;
uint32_t val;
uint8_t limit;
b = in->buf;
if (b->last - b->pos < 4) {
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"too small buffer for %d message: %d",
(int)h->type, b->last - b->pos);
return NGX_OK;
}
p = (u_char*)&val;
p[0] = b->pos[3];
p[1] = b->pos[2];
p[2] = b->pos[1];
p[3] = b->pos[0];
switch(h->type) {
case NGX_RTMP_MSG_CHUNK_SIZE:
/* set chunk size =val */
ngx_rtmp_set_chunk_size(s, val);
break;
case NGX_RTMP_MSG_ABORT:
/* abort chunk stream =val */
break;
case NGX_RTMP_MSG_ACK:
/* receive ack with sequence number =val */
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive ack seq=%uD", val);
break;
case NGX_RTMP_MSG_ACK_SIZE:
/* receive window size =val */
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive ack_size=%uD", val);
s->ack_size = val;
break;
case NGX_RTMP_MSG_BANDWIDTH:
if (b->last - b->pos >= 5) {
limit = *(uint8_t*)&b->pos[4];
(void)val;
(void)limit;
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive bandwidth=%uD limit=%d",
val, (int)limit);
/* receive window size =val
* && limit */
}
break;
default:
return NGX_ERROR;
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_user_message_handler(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_buf_t *b;
u_char *p;
uint16_t evt;
uint32_t val;
b = in->buf;
if (b->last - b->pos < 6) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"too small buffer for user message: %d",
b->last - b->pos);
return NGX_OK;
}
p = (u_char*)&evt;
p[0] = b->pos[1];
p[1] = b->pos[0];
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP recv user evt %s (%i)",
ngx_rtmp_user_message_type(evt), (ngx_int_t) evt);
p = (u_char *) &val;
p[0] = b->pos[5];
p[1] = b->pos[4];
p[2] = b->pos[3];
p[3] = b->pos[2];
switch(evt) {
case NGX_RTMP_USER_STREAM_BEGIN:
{
ngx_rtmp_stream_begin_t v;
v.msid = val;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive: stream_begin msid=%uD", v.msid);
return ngx_rtmp_stream_begin(s, &v);
}
case NGX_RTMP_USER_STREAM_EOF:
{
ngx_rtmp_stream_eof_t v;
v.msid = val;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive: stream_eof msid=%uD", v.msid);
return ngx_rtmp_stream_eof(s, &v);
}
case NGX_RTMP_USER_STREAM_DRY:
{
ngx_rtmp_stream_dry_t v;
v.msid = val;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive: stream_dry msid=%uD", v.msid);
return ngx_rtmp_stream_dry(s, &v);
}
case NGX_RTMP_USER_SET_BUFLEN:
{
ngx_rtmp_set_buflen_t v;
v.msid = val;
if (b->last - b->pos < 10) {
return NGX_OK;
}
p = (u_char *) &v.buflen;
p[0] = b->pos[9];
p[1] = b->pos[8];
p[2] = b->pos[7];
p[3] = b->pos[6];
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive: set_buflen msid=%uD buflen=%uD",
v.msid, v.buflen);
/*TODO: move this to play module */
s->buflen = v.buflen;
return ngx_rtmp_set_buflen(s, &v);
}
case NGX_RTMP_USER_RECORDED:
{
ngx_rtmp_recorded_t v;
v.msid = val;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"receive: recorded msid=%uD", v.msid);
return ngx_rtmp_recorded(s, &v);
}
case NGX_RTMP_USER_PING_REQUEST:
return ngx_rtmp_send_ping_response(s, val);
case NGX_RTMP_USER_PING_RESPONSE:
/* val = incoming timestamp */
ngx_rtmp_reset_ping(s);
return NGX_OK;
default:
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"unexpected user event: %i", (ngx_int_t) evt);
return NGX_OK;
}
}
static ngx_int_t
ngx_rtmp_fetch(ngx_chain_t **in, u_char *ret)
{
while (*in && (*in)->buf->pos >= (*in)->buf->last) {
*in = (*in)->next;
}
if (*in == NULL) {
return NGX_DONE;
}
*ret = *(*in)->buf->pos++;
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_fetch_uint8(ngx_chain_t **in, uint8_t *ret)
{
return ngx_rtmp_fetch(in, (u_char *) ret);
}
static ngx_int_t
ngx_rtmp_fetch_uint32(ngx_chain_t **in, uint32_t *ret, ngx_int_t n)
{
u_char *r = (u_char *) ret;
ngx_int_t rc;
*ret = 0;
while (--n >= 0) {
rc = ngx_rtmp_fetch(in, &r[n]);
if (rc != NGX_OK) {
return rc;
}
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_aggregate_message_handler(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
uint32_t base_time, timestamp, prev_size;
size_t len;
ngx_int_t first;
u_char *last;
ngx_int_t rc;
ngx_buf_t *b;
ngx_chain_t *cl, *next;
ngx_rtmp_header_t ch;
ch = *h;
first = 1;
base_time = 0;
while (in) {
if (ngx_rtmp_fetch_uint8(&in, &ch.type) != NGX_OK) {
return NGX_OK;
}
if (ngx_rtmp_fetch_uint32(&in, &ch.mlen, 3) != NGX_OK) {
return NGX_ERROR;
}
if (ngx_rtmp_fetch_uint32(&in, ×tamp, 3) != NGX_OK) {
return NGX_ERROR;
}
if (ngx_rtmp_fetch_uint8(&in, (uint8_t *) ×tamp + 3) != NGX_OK)
{
return NGX_ERROR;
}
if (ngx_rtmp_fetch_uint32(&in, &ch.msid, 3) != NGX_OK)
{
return NGX_ERROR;
}
if (first) {
base_time = timestamp;
first = 0;
}
ngx_log_debug6(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP aggregate %s (%d) len=%uD time=%uD (+%D) msid=%uD",
ngx_rtmp_message_type(ch.type),
(ngx_int_t) ch.type, ch.mlen, ch.timestamp,
timestamp - base_time, ch.msid);
/* limit chain */
len = 0;
cl = in;
while (cl) {
b = cl->buf;
len += (b->last - b->pos);
if (len > ch.mlen) {
break;
}
cl = cl->next;
}
if (cl == NULL) {
ngx_log_error(NGX_LOG_INFO, s->log, 0,
"RTMP error parsing aggregate");
return NGX_ERROR;
}
next = cl->next;
cl->next = NULL;
b = cl->buf;
last = b->last;
b->last -= (len - ch.mlen);
/* handle aggregated message */
ch.timestamp = h->timestamp + timestamp - base_time;
rc = ngx_rtmp_receive_message(s, &ch, in);
/* restore chain before checking the result */
in = cl;
in->next = next;
b->pos = b->last;
b->last = last;
if (rc != NGX_OK) {
return rc;
}
/* read 32-bit previous tag size */
if (ngx_rtmp_fetch_uint32(&in, &prev_size, 4) != NGX_OK) {
return NGX_OK;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP aggregate prev_size=%uD", prev_size);
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_amf_message_handler(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in)
{
ngx_rtmp_amf_ctx_t act;
ngx_rtmp_core_main_conf_t *cmcf;
ngx_array_t *ch;
ngx_rtmp_handler_pt *ph;
size_t len, n;
static u_char func[128];
static ngx_rtmp_amf_elt_t elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
func, sizeof(func) },
};
/* AMF command names come with string type, but shared object names
* come without type */
if (h->type == NGX_RTMP_MSG_AMF_SHARED ||
h->type == NGX_RTMP_MSG_AMF3_SHARED)
{
elts[0].type |= NGX_RTMP_AMF_TYPELESS;
} else {
elts[0].type &= ~NGX_RTMP_AMF_TYPELESS;
}
if ((h->type == NGX_RTMP_MSG_AMF3_SHARED ||
h->type == NGX_RTMP_MSG_AMF3_META ||
h->type == NGX_RTMP_MSG_AMF3_CMD)
&& in->buf->last > in->buf->pos)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"AMF3 prefix: %ui", (ngx_int_t)*in->buf->pos);
++in->buf->pos;
}
cmcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_core_module);
/* read AMF func name & transaction id */
ngx_memzero(&act, sizeof(act));
act.link = in;
act.log = s->log;
memset(func, 0, sizeof(func));
if (ngx_rtmp_amf_read(&act, elts,
sizeof(elts) / sizeof(elts[0])) != NGX_OK)
{
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"AMF cmd failed");
return NGX_ERROR;
}
/* skip name */
in = act.link;
in->buf->pos += act.offset;
len = ngx_strlen(func);
ch = ngx_hash_find(&cmcf->amf_hash,
ngx_hash_strlow(func, func, len), func, len);
if (ch && ch->nelts) {
ph = ch->elts;
for (n = 0; n < ch->nelts; ++n, ++ph) {
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"AMF func '%s' passed to handler %d/%d",
func, n, ch->nelts);
switch ((*ph)(s, h, in)) {
case NGX_ERROR:
return NGX_ERROR;
case NGX_DONE:
return NGX_OK;
}
}
} else {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"AMF cmd '%s' no handler", func);
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_receive_amf(ngx_rtmp_session_t *s, ngx_chain_t *in,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
ngx_rtmp_amf_ctx_t act;
ngx_memzero(&act, sizeof(act));
act.link = in;
act.log = s->log;
return ngx_rtmp_amf_read(&act, elts, nelts);
}
|
281677160/openwrt-package
| 8,576 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/config
|
ngx_addon_name="ngx_rtmp_module"
RTMP_CORE_MODULES=" \
ngx_live_module \
ngx_rtmp_module \
ngx_rtmp_dynamic_module \
ngx_rtmp_dynamic_core_module \
ngx_rtmp_core_module \
ngx_rtmp_cmd_module \
ngx_rtmp_codec_module \
ngx_rtmp_access_module \
ngx_rtmp_live_module \
ngx_live_record_module \
ngx_live_relay_module \
ngx_live_relay_rtmp_module \
ngx_live_relay_static_module \
ngx_live_relay_simple_module \
ngx_rtmp_exec_module \
ngx_rtmp_notify_module \
ngx_live_relay_inner_module \
ngx_rtmp_log_module \
ngx_rtmp_limit_module \
ngx_rtmp_hls_module \
ngx_rtmp_dash_module \
ngx_rtmp_shared_module \
ngx_rtmp_record_module \
ngx_rtmp_gop_module \
ngx_rtmp_monitor_module \
ngx_mpegts_live_module \
ngx_mpegts_gop_module \
ngx_hls_live_module \
"
RTMP_HTTP_MODULES=" \
ngx_rtmp_stat_module \
ngx_rtmp_sys_stat_module \
ngx_rtmp_control_module \
ngx_http_flv_live_module \
ngx_hls_http_module \
ngx_mpegts_http_module \
"
RTMP_DEPS=" \
$ngx_addon_dir/ngx_netcall.h \
$ngx_addon_dir/ngx_rtmp_amf.h \
$ngx_addon_dir/ngx_rtmp_bandwidth.h \
$ngx_addon_dir/ngx_rtmp_cmd_module.h \
$ngx_addon_dir/ngx_rtmp_codec_module.h \
$ngx_addon_dir/ngx_rtmp_eval.h \
$ngx_addon_dir/ngx_rtmp.h \
$ngx_addon_dir/ngx_rtmp_version.h \
$ngx_addon_dir/ngx_rtmp_live_module.h \
$ngx_addon_dir/ngx_rtmp_notify_module.h \
$ngx_addon_dir/ngx_rtmp_streams.h \
$ngx_addon_dir/ngx_rtmp_bitop.h \
$ngx_addon_dir/ngx_rtmp_proxy_protocol.h \
$ngx_addon_dir/ngx_rtmp_monitor_module.h \
$ngx_addon_dir/hls/ngx_rtmp_mpegts.h \
$ngx_addon_dir/dash/ngx_rtmp_mp4.h \
$ngx_addon_dir/http/ngx_http_set_header.h \
$ngx_addon_dir/ngx_live.h \
$ngx_addon_dir/ngx_live_relay.h \
$ngx_addon_dir/ngx_live_record.h \
$ngx_addon_dir/ngx_rtmp_dynamic.h \
$ngx_addon_dir/ngx_rtmp_variables.h \
$ngx_addon_dir/ngx_rtmp_record_module.h \
$ngx_addon_dir/mpegts/ngx_mpegts_live_module.h \
$ngx_addon_dir/mpegts/ngx_hls_live_module.h \
$ngx_addon_dir/mpegts/ngx_mpegts_gop_module.h \
"
RTMP_CORE_SRCS=" \
$ngx_addon_dir/ngx_netcall.c \
$ngx_addon_dir/ngx_rtmp.c \
$ngx_addon_dir/ngx_rtmp_init.c \
$ngx_addon_dir/ngx_rtmp_handshake.c \
$ngx_addon_dir/ngx_rtmp_handler.c \
$ngx_addon_dir/ngx_rtmp_amf.c \
$ngx_addon_dir/ngx_rtmp_send.c \
$ngx_addon_dir/ngx_rtmp_eval.c \
$ngx_addon_dir/ngx_rtmp_receive.c \
$ngx_addon_dir/ngx_rtmp_core_module.c \
$ngx_addon_dir/ngx_rtmp_cmd_module.c \
$ngx_addon_dir/ngx_rtmp_codec_module.c \
$ngx_addon_dir/ngx_rtmp_access_module.c \
$ngx_addon_dir/ngx_rtmp_live_module.c \
$ngx_addon_dir/ngx_rtmp_bandwidth.c \
$ngx_addon_dir/ngx_rtmp_exec_module.c \
$ngx_addon_dir/ngx_rtmp_notify_module.c \
$ngx_addon_dir/ngx_rtmp_log_module.c \
$ngx_addon_dir/ngx_rtmp_limit_module.c \
$ngx_addon_dir/ngx_rtmp_bitop.c \
$ngx_addon_dir/ngx_rtmp_proxy_protocol.c \
$ngx_addon_dir/hls/ngx_rtmp_hls_module.c \
$ngx_addon_dir/dash/ngx_rtmp_dash_module.c \
$ngx_addon_dir/hls/ngx_rtmp_mpegts.c \
$ngx_addon_dir/dash/ngx_rtmp_mp4.c \
$ngx_addon_dir/ngx_live.c \
$ngx_addon_dir/ngx_live_relay.c \
$ngx_addon_dir/ngx_live_relay_httpflv.c \
$ngx_addon_dir/ngx_live_relay_rtmp.c \
$ngx_addon_dir/ngx_live_relay_inner.c \
$ngx_addon_dir/ngx_live_relay_simple.c \
$ngx_addon_dir/ngx_live_relay_static.c \
$ngx_addon_dir/ngx_live_record.c \
$ngx_addon_dir/ngx_rtmp_shared_module.c \
$ngx_addon_dir/ngx_rtmp_gop_module.c \
$ngx_addon_dir/ngx_rtmp_monitor_module.c \
$ngx_addon_dir/ngx_rtmp_dynamic.c \
$ngx_addon_dir/ngx_rtmp_variables.c \
$ngx_addon_dir/ngx_rtmp_record_module.c \
$ngx_addon_dir/mpegts/ngx_mpegts_live_module.c \
$ngx_addon_dir/mpegts/ngx_hls_live_module.c \
$ngx_addon_dir/mpegts/ngx_mpegts_gop_module.c \
"
RTMP_HTTP_SRCS=" \
$ngx_addon_dir/ngx_rtmp_sys_stat_module.c \
$ngx_addon_dir/ngx_rtmp_stat_module.c \
$ngx_addon_dir/ngx_rtmp_control_module.c \
$ngx_addon_dir/http/ngx_http_flv_live_module.c \
$ngx_addon_dir/http/ngx_http_set_header.c \
$ngx_addon_dir/mpegts/ngx_hls_http_module.c \
$ngx_addon_dir/mpegts/ngx_mpegts_http_module.c \
"
if [ -f auto/module ] ; then
ngx_module_incs=$ngx_addon_dir
ngx_module_deps=$RTMP_DEPS
if [ $ngx_module_link = DYNAMIC ] ; then
ngx_module_name="$RTMP_CORE_MODULES $RTMP_HTTP_MODULES"
ngx_module_srcs="$RTMP_CORE_SRCS $RTMP_HTTP_SRCS"
. auto/module
else
ngx_module_type=CORE
ngx_module_name=$RTMP_CORE_MODULES
ngx_module_srcs=$RTMP_CORE_SRCS
. auto/module
ngx_module_type=HTTP
ngx_module_name=$RTMP_HTTP_MODULES
ngx_module_incs="$ngx_addon_dir $ngx_addon_dir/http $ngx_addon_dir/hls $ngx_addon_dir/mpegts"
ngx_module_deps=
ngx_module_srcs=$RTMP_HTTP_SRCS
. auto/module
fi
else
CORE_MODULES="$CORE_MODULES $RTMP_CORE_MODULES"
HTTP_MODULES="$HTTP_MODULES $RTMP_HTTP_MODULES"
NGX_ADDON_DEPS="$NGX_ADDON_DEPS $RTMP_DEPS"
NGX_ADDON_SRCS="$NGX_ADDON_SRCS $RTMP_CORE_SRCS $RTMP_HTTP_SRCS"
CFLAGS="$CFLAGS -I$ngx_addon_dir -I$ngx_addon_dir/http -I$ngx_addon_dir/hls -I$ngx_addon_dir/mpegts"
fi
USE_OPENSSL=YES
|
294coder/Efficient-MIF
| 11,595 |
utils/loss_landscape/cifar10/main.py
|
from __future__ import print_function
import os
import random
import numpy as np
import argparse
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torch.nn.parallel
import model_loader
import dataloader
def init_params(net):
for m in net.modules():
if isinstance(m, nn.Conv2d) or isinstance(m, nn.ConvTranspose2d):
init.kaiming_normal_(m.weight, mode='fan_in')
if m.bias is not None:
init.constant_(m.bias, 0)
elif isinstance(m, nn.BatchNorm2d):
init.constant_(m.weight, 1)
init.constant_(m.bias, 0)
elif isinstance(m, nn.Linear):
init.normal_(m.weight, std=1e-3)
if m.bias is not None:
init.constant_(m.bias, 0)
# Training
def train(trainloader, net, criterion, optimizer, use_cuda=True):
net.train()
train_loss = 0
correct = 0
total = 0
if isinstance(criterion, nn.CrossEntropyLoss):
for batch_idx, (inputs, targets) in enumerate(trainloader):
batch_size = inputs.size(0)
total += batch_size
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
optimizer.zero_grad()
inputs, targets = Variable(inputs), Variable(targets)
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
train_loss += loss.item()*batch_size
_, predicted = torch.max(outputs.data, 1)
correct += predicted.eq(targets.data).cpu().sum().item()
elif isinstance(criterion, nn.MSELoss):
for batch_idx, (inputs, targets) in enumerate(trainloader):
batch_size = inputs.size(0)
total += batch_size
one_hot_targets = torch.FloatTensor(batch_size, 10).zero_()
one_hot_targets = one_hot_targets.scatter_(1, targets.view(batch_size, 1), 1.0)
one_hot_targets = one_hot_targets.float()
if use_cuda:
inputs, one_hot_targets = inputs.cuda(), one_hot_targets.cuda()
inputs, one_hot_targets = Variable(inputs), Variable(one_hot_targets)
outputs = F.softmax(net(inputs))
loss = criterion(outputs, one_hot_targets)
loss.backward()
optimizer.step()
train_loss += loss.item()*batch_size
_, predicted = torch.max(outputs.data, 1)
correct += predicted.cpu().eq(targets).cpu().sum().item()
return train_loss/total, 100 - 100.*correct/total
def test(testloader, net, criterion, use_cuda=True):
net.eval()
test_loss = 0
correct = 0
total = 0
if isinstance(criterion, nn.CrossEntropyLoss):
for batch_idx, (inputs, targets) in enumerate(testloader):
batch_size = inputs.size(0)
total += batch_size
if use_cuda:
inputs, targets = inputs.cuda(), targets.cuda()
inputs, targets = Variable(inputs), Variable(targets)
outputs = net(inputs)
loss = criterion(outputs, targets)
test_loss += loss.item()*batch_size
_, predicted = torch.max(outputs.data, 1)
correct += predicted.eq(targets.data).cpu().sum().item()
elif isinstance(criterion, nn.MSELoss):
for batch_idx, (inputs, targets) in enumerate(testloader):
batch_size = inputs.size(0)
total += batch_size
one_hot_targets = torch.FloatTensor(batch_size, 10).zero_()
one_hot_targets = one_hot_targets.scatter_(1, targets.view(batch_size, 1), 1.0)
one_hot_targets = one_hot_targets.float()
if use_cuda:
inputs, one_hot_targets = inputs.cuda(), one_hot_targets.cuda()
inputs, one_hot_targets = Variable(inputs), Variable(one_hot_targets)
outputs = F.softmax(net(inputs))
loss = criterion(outputs, one_hot_targets)
test_loss += loss.item()*batch_size
_, predicted = torch.max(outputs.data, 1)
correct += predicted.cpu().eq(targets).cpu().sum().item()
return test_loss/total, 100 - 100.*correct/total
def name_save_folder(args):
save_folder = args.model + '_' + str(args.optimizer) + '_lr=' + str(args.lr)
if args.lr_decay != 0.1:
save_folder += '_lr_decay=' + str(args.lr_decay)
save_folder += '_bs=' + str(args.batch_size)
save_folder += '_wd=' + str(args.weight_decay)
save_folder += '_mom=' + str(args.momentum)
save_folder += '_save_epoch=' + str(args.save_epoch)
if args.loss_name != 'crossentropy':
save_folder += '_loss=' + str(args.loss_name)
if args.noaug:
save_folder += '_noaug'
if args.raw_data:
save_folder += '_rawdata'
if args.label_corrupt_prob > 0:
save_folder += '_randlabel=' + str(args.label_corrupt_prob)
if args.ngpu > 1:
save_folder += '_ngpu=' + str(args.ngpu)
if args.idx:
save_folder += '_idx=' + str(args.idx)
return save_folder
if __name__ == '__main__':
# Training options
parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Training')
parser.add_argument('--batch_size', default=128, type=int)
parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--lr_decay', default=0.1, type=float, help='learning rate decay rate')
parser.add_argument('--optimizer', default='sgd', help='optimizer: sgd | adam')
parser.add_argument('--weight_decay', default=0.0005, type=float)
parser.add_argument('--momentum', default=0.9, type=float)
parser.add_argument('--epochs', default=300, type=int, metavar='N', help='number of total epochs to run')
parser.add_argument('--save', default='trained_nets',help='path to save trained nets')
parser.add_argument('--save_epoch', default=10, type=int, help='save every save_epochs')
parser.add_argument('--ngpu', type=int, default=1, help='number of GPUs to use')
parser.add_argument('--rand_seed', default=0, type=int, help='seed for random num generator')
parser.add_argument('--resume_model', default='', help='resume model from checkpoint')
parser.add_argument('--resume_opt', default='', help='resume optimizer from checkpoint')
# model parameters
parser.add_argument('--model', '-m', default='vgg9')
parser.add_argument('--loss_name', '-l', default='crossentropy', help='loss functions: crossentropy | mse')
# data parameters
parser.add_argument('--raw_data', action='store_true', default=False, help='do not normalize data')
parser.add_argument('--noaug', default=False, action='store_true', help='no data augmentation')
parser.add_argument('--label_corrupt_prob', type=float, default=0.0)
parser.add_argument('--trainloader', default='', help='path to the dataloader with random labels')
parser.add_argument('--testloader', default='', help='path to the testloader with random labels')
parser.add_argument('--idx', default=0, type=int, help='the index for the repeated experiment')
args = parser.parse_args()
print('\nLearning Rate: %f' % args.lr)
print('\nDecay Rate: %f' % args.lr_decay)
use_cuda = torch.cuda.is_available()
print('Current devices: ' + str(torch.cuda.current_device()))
print('Device count: ' + str(torch.cuda.device_count()))
# Set the seed for reproducing the results
random.seed(args.rand_seed)
np.random.seed(args.rand_seed)
torch.manual_seed(args.rand_seed)
if use_cuda:
torch.cuda.manual_seed_all(args.rand_seed)
cudnn.benchmark = True
lr = args.lr # current learning rate
start_epoch = 1 # start from epoch 1 or last checkpoint epoch
if not os.path.isdir(args.save):
os.mkdir(args.save)
save_folder = name_save_folder(args)
if not os.path.exists('trained_nets/' + save_folder):
os.makedirs('trained_nets/' + save_folder)
f = open('trained_nets/' + save_folder + '/log.out', 'a', 0)
trainloader, testloader = dataloader.get_data_loaders(args)
if args.label_corrupt_prob and not args.resume_model:
torch.save(trainloader, 'trained_nets/' + save_folder + '/trainloader.dat')
torch.save(testloader, 'trained_nets/' + save_folder + '/testloader.dat')
# Model
if args.resume_model:
# Load checkpoint.
print('==> Resuming from checkpoint..')
checkpoint = torch.load(args.resume_model)
net = model_loader.load(args.model)
net.load_state_dict(checkpoint['state_dict'])
start_epoch = checkpoint['epoch'] + 1
else:
net = model_loader.load(args.model)
print(net)
init_params(net)
if args.ngpu > 1:
net = torch.nn.DataParallel(net)
criterion = nn.CrossEntropyLoss()
if args.loss_name == 'mse':
criterion = nn.MSELoss()
if use_cuda:
net.cuda()
criterion = criterion.cuda()
# Optimizer
if args.optimizer == 'sgd':
optimizer = optim.SGD(net.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay, nesterov=True)
else:
optimizer = optim.Adam(net.parameters(), lr=args.lr, weight_decay=args.weight_decay)
if args.resume_opt:
checkpoint_opt = torch.load(args.resume_opt)
optimizer.load_state_dict(checkpoint_opt['optimizer'])
# record the performance of initial model
if not args.resume_model:
train_loss, train_err = test(trainloader, net, criterion, use_cuda)
test_loss, test_err = test(testloader, net, criterion, use_cuda)
status = 'e: %d loss: %.5f train_err: %.3f test_top1: %.3f test_loss %.5f \n' % (0, train_loss, train_err, test_err, test_loss)
print(status)
f.write(status)
state = {
'acc': 100 - test_err,
'epoch': 0,
'state_dict': net.module.state_dict() if args.ngpu > 1 else net.state_dict()
}
opt_state = {
'optimizer': optimizer.state_dict()
}
torch.save(state, 'trained_nets/' + save_folder + '/model_0.t7')
torch.save(opt_state, 'trained_nets/' + save_folder + '/opt_state_0.t7')
for epoch in range(start_epoch, args.epochs + 1):
loss, train_err = train(trainloader, net, criterion, optimizer, use_cuda)
test_loss, test_err = test(testloader, net, criterion, use_cuda)
status = 'e: %d loss: %.5f train_err: %.3f test_top1: %.3f test_loss %.5f \n' % (epoch, loss, train_err, test_err, test_loss)
print(status)
f.write(status)
# Save checkpoint.
acc = 100 - test_err
if epoch == 1 or epoch % args.save_epoch == 0 or epoch == 150:
state = {
'acc': acc,
'epoch': epoch,
'state_dict': net.module.state_dict() if args.ngpu > 1 else net.state_dict(),
}
opt_state = {
'optimizer': optimizer.state_dict()
}
torch.save(state, 'trained_nets/' + save_folder + '/model_' + str(epoch) + '.t7')
torch.save(opt_state, 'trained_nets/' + save_folder + '/opt_state_' + str(epoch) + '.t7')
if int(epoch) == 150 or int(epoch) == 225 or int(epoch) == 275:
lr *= args.lr_decay
for param_group in optimizer.param_groups:
param_group['lr'] *= args.lr_decay
f.close()
|
2881099/FreeSql.AdminLTE
| 26,692 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/keymap/sublime.js
|
// CodeMirror, copyright (c) by Marijn Haverbeke and others
// Distributed under an MIT license: https://codemirror.net/LICENSE
// A rough approximation of Sublime Text's keybindings
// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("../lib/codemirror"), require("../addon/search/searchcursor"), require("../addon/edit/matchbrackets"));
else if (typeof define == "function" && define.amd) // AMD
define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var cmds = CodeMirror.commands;
var Pos = CodeMirror.Pos;
// This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
function findPosSubword(doc, start, dir) {
if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
var line = doc.getLine(start.line);
if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
var state = "start", type, startPos = start.ch;
for (var pos = startPos, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
var next = line.charAt(dir < 0 ? pos - 1 : pos);
var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
if (cat == "w" && next.toUpperCase() == next) cat = "W";
if (state == "start") {
if (cat != "o") { state = "in"; type = cat; }
else startPos = pos + dir
} else if (state == "in") {
if (type != cat) {
if (type == "w" && cat == "W" && dir < 0) pos--;
if (type == "W" && cat == "w" && dir > 0) { // From uppercase to lowercase
if (pos == startPos + 1) { type = "w"; continue; }
else pos--;
}
break;
}
}
}
return Pos(start.line, pos);
}
function moveSubword(cm, dir) {
cm.extendSelectionsBy(function(range) {
if (cm.display.shift || cm.doc.extend || range.empty())
return findPosSubword(cm.doc, range.head, dir);
else
return dir < 0 ? range.from() : range.to();
});
}
cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); };
cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); };
cmds.scrollLineUp = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
if (cm.getCursor().line >= visibleBottomLine)
cm.execCommand("goLineUp");
}
cm.scrollTo(null, info.top - cm.defaultTextHeight());
};
cmds.scrollLineDown = function(cm) {
var info = cm.getScrollInfo();
if (!cm.somethingSelected()) {
var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
if (cm.getCursor().line <= visibleTopLine)
cm.execCommand("goLineDown");
}
cm.scrollTo(null, info.top + cm.defaultTextHeight());
};
cmds.splitSelectionByLine = function(cm) {
var ranges = cm.listSelections(), lineRanges = [];
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
for (var line = from.line; line <= to.line; ++line)
if (!(to.line > from.line && line == to.line && to.ch == 0))
lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
head: line == to.line ? to : Pos(line)});
}
cm.setSelections(lineRanges, 0);
};
cmds.singleSelectionTop = function(cm) {
var range = cm.listSelections()[0];
cm.setSelection(range.anchor, range.head, {scroll: false});
};
cmds.selectLine = function(cm) {
var ranges = cm.listSelections(), extended = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
extended.push({anchor: Pos(range.from().line, 0),
head: Pos(range.to().line + 1, 0)});
}
cm.setSelections(extended);
};
function insertLine(cm, above) {
if (cm.isReadOnly()) return CodeMirror.Pass
cm.operation(function() {
var len = cm.listSelections().length, newSelection = [], last = -1;
for (var i = 0; i < len; i++) {
var head = cm.listSelections()[i].head;
if (head.line <= last) continue;
var at = Pos(head.line + (above ? 0 : 1), 0);
cm.replaceRange("\n", at, null, "+insertLine");
cm.indentLine(at.line, null, true);
newSelection.push({head: at, anchor: at});
last = head.line + 1;
}
cm.setSelections(newSelection);
});
cm.execCommand("indentAuto");
}
cmds.insertLineAfter = function(cm) { return insertLine(cm, false); };
cmds.insertLineBefore = function(cm) { return insertLine(cm, true); };
function wordAt(cm, pos) {
var start = pos.ch, end = start, line = cm.getLine(pos.line);
while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
}
cmds.selectNextOccurrence = function(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
cm.setSelection(word.from, word.to);
fullWord = true;
} else {
var text = cm.getRange(from, to);
var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
var cur = cm.getSearchCursor(query, to);
var found = cur.findNext();
if (!found) {
cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
found = cur.findNext();
}
if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to())) return
cm.addSelection(cur.from(), cur.to());
}
if (fullWord)
cm.state.sublimeFindFullWord = cm.doc.sel;
};
cmds.skipAndSelectNextOccurrence = function(cm) {
var prevAnchor = cm.getCursor("anchor"), prevHead = cm.getCursor("head");
cmds.selectNextOccurrence(cm);
if (CodeMirror.cmpPos(prevAnchor, prevHead) != 0) {
cm.doc.setSelections(cm.doc.listSelections()
.filter(function (sel) {
return sel.anchor != prevAnchor || sel.head != prevHead;
}));
}
}
function addCursorToSelection(cm, dir) {
var ranges = cm.listSelections(), newRanges = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
var newAnchor = cm.findPosV(
range.anchor, dir, "line", range.anchor.goalColumn);
var newHead = cm.findPosV(
range.head, dir, "line", range.head.goalColumn);
newAnchor.goalColumn = range.anchor.goalColumn != null ?
range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left;
newHead.goalColumn = range.head.goalColumn != null ?
range.head.goalColumn : cm.cursorCoords(range.head, "div").left;
var newRange = {anchor: newAnchor, head: newHead};
newRanges.push(range);
newRanges.push(newRange);
}
cm.setSelections(newRanges);
}
cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); };
cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); };
function isSelectedRange(ranges, from, to) {
for (var i = 0; i < ranges.length; i++)
if (CodeMirror.cmpPos(ranges[i].from(), from) == 0 &&
CodeMirror.cmpPos(ranges[i].to(), to) == 0) return true
return false
}
var mirror = "(){}[]";
function selectBetweenBrackets(cm) {
var ranges = cm.listSelections(), newRanges = []
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
if (!opening) return false;
for (;;) {
var closing = cm.scanForBracket(pos, 1);
if (!closing) return false;
if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
var startPos = Pos(opening.pos.line, opening.pos.ch + 1);
if (CodeMirror.cmpPos(startPos, range.from()) == 0 &&
CodeMirror.cmpPos(closing.pos, range.to()) == 0) {
opening = cm.scanForBracket(opening.pos, -1);
if (!opening) return false;
} else {
newRanges.push({anchor: startPos, head: closing.pos});
break;
}
}
pos = Pos(closing.pos.line, closing.pos.ch + 1);
}
}
cm.setSelections(newRanges);
return true;
}
cmds.selectScope = function(cm) {
selectBetweenBrackets(cm) || cm.execCommand("selectAll");
};
cmds.selectBetweenBrackets = function(cm) {
if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
};
function puncType(type) {
return !type ? null : /\bpunctuation\b/.test(type) ? type : undefined
}
cmds.goToBracket = function(cm) {
cm.extendSelectionsBy(function(range) {
var next = cm.scanForBracket(range.head, 1, puncType(cm.getTokenTypeAt(range.head)));
if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
var prev = cm.scanForBracket(range.head, -1, puncType(cm.getTokenTypeAt(Pos(range.head.line, range.head.ch + 1))));
return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
});
};
cmds.swapLineUp = function(cm) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from().line - 1, to = range.to().line;
newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
head: Pos(range.head.line - 1, range.head.ch)});
if (range.to().ch == 0 && !range.empty()) --to;
if (from > at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = 0; i < linesToMove.length; i += 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
if (to > cm.lastLine())
cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
else
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.setSelections(newSels);
cm.scrollIntoView();
});
};
cmds.swapLineDown = function(cm) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
for (var i = ranges.length - 1; i >= 0; i--) {
var range = ranges[i], from = range.to().line + 1, to = range.from().line;
if (range.to().ch == 0 && !range.empty()) from--;
if (from < at) linesToMove.push(from, to);
else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
at = to;
}
cm.operation(function() {
for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
var from = linesToMove[i], to = linesToMove[i + 1];
var line = cm.getLine(from);
if (from == cm.lastLine())
cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
else
cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
}
cm.scrollIntoView();
});
};
cmds.toggleCommentIndented = function(cm) {
cm.toggleComment({ indent: true });
}
cmds.joinLines = function(cm) {
var ranges = cm.listSelections(), joined = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i], from = range.from();
var start = from.line, end = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
end = ranges[++i].to().line;
joined.push({start: start, end: end, anchor: !range.empty() && from});
}
cm.operation(function() {
var offset = 0, ranges = [];
for (var i = 0; i < joined.length; i++) {
var obj = joined[i];
var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
for (var line = obj.start; line <= obj.end; line++) {
var actual = line - offset;
if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
if (actual < cm.lastLine()) {
cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
++offset;
}
}
ranges.push({anchor: anchor || head, head: head});
}
cm.setSelections(ranges, 0);
});
};
cmds.duplicateLine = function(cm) {
cm.operation(function() {
var rangeCount = cm.listSelections().length;
for (var i = 0; i < rangeCount; i++) {
var range = cm.listSelections()[i];
if (range.empty())
cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
else
cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
}
cm.scrollIntoView();
});
};
function sortLines(cm, caseSensitive, direction) {
if (cm.isReadOnly()) return CodeMirror.Pass
var ranges = cm.listSelections(), toSort = [], selected;
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) continue;
var from = range.from().line, to = range.to().line;
while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
to = ranges[++i].to().line;
if (!ranges[i].to().ch) to--;
toSort.push(from, to);
}
if (toSort.length) selected = true;
else toSort.push(cm.firstLine(), cm.lastLine());
cm.operation(function() {
var ranges = [];
for (var i = 0; i < toSort.length; i += 2) {
var from = toSort[i], to = toSort[i + 1];
var start = Pos(from, 0), end = Pos(to);
var lines = cm.getRange(start, end, false);
if (caseSensitive)
lines.sort(function(a, b) { return a < b ? -direction : a == b ? 0 : direction; });
else
lines.sort(function(a, b) {
var au = a.toUpperCase(), bu = b.toUpperCase();
if (au != bu) { a = au; b = bu; }
return a < b ? -direction : a == b ? 0 : direction;
});
cm.replaceRange(lines, start, end);
if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
}
if (selected) cm.setSelections(ranges, 0);
});
}
cmds.sortLines = function(cm) { sortLines(cm, true, 1); };
cmds.reverseSortLines = function(cm) { sortLines(cm, true, -1); };
cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false, 1); };
cmds.reverseSortLinesInsensitive = function(cm) { sortLines(cm, false, -1); };
cmds.nextBookmark = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
var current = marks.shift();
var found = current.find();
if (found) {
marks.push(current);
return cm.setSelection(found.from, found.to);
}
}
};
cmds.prevBookmark = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) while (marks.length) {
marks.unshift(marks.pop());
var found = marks[marks.length - 1].find();
if (!found)
marks.pop();
else
return cm.setSelection(found.from, found.to);
}
};
cmds.toggleBookmark = function(cm) {
var ranges = cm.listSelections();
var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
for (var i = 0; i < ranges.length; i++) {
var from = ranges[i].from(), to = ranges[i].to();
var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to);
for (var j = 0; j < found.length; j++) {
if (found[j].sublimeBookmark) {
found[j].clear();
for (var k = 0; k < marks.length; k++)
if (marks[k] == found[j])
marks.splice(k--, 1);
break;
}
}
if (j == found.length)
marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
}
};
cmds.clearBookmarks = function(cm) {
var marks = cm.state.sublimeBookmarks;
if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
marks.length = 0;
};
cmds.selectBookmarks = function(cm) {
var marks = cm.state.sublimeBookmarks, ranges = [];
if (marks) for (var i = 0; i < marks.length; i++) {
var found = marks[i].find();
if (!found)
marks.splice(i--, 0);
else
ranges.push({anchor: found.from, head: found.to});
}
if (ranges.length)
cm.setSelections(ranges, 0);
};
function modifyWordOrSelection(cm, mod) {
cm.operation(function() {
var ranges = cm.listSelections(), indices = [], replacements = [];
for (var i = 0; i < ranges.length; i++) {
var range = ranges[i];
if (range.empty()) { indices.push(i); replacements.push(""); }
else replacements.push(mod(cm.getRange(range.from(), range.to())));
}
cm.replaceSelections(replacements, "around", "case");
for (var i = indices.length - 1, at; i >= 0; i--) {
var range = ranges[indices[i]];
if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
var word = wordAt(cm, range.head);
at = word.from;
cm.replaceRange(mod(word.word), word.from, word.to);
}
});
}
cmds.smartBackspace = function(cm) {
if (cm.somethingSelected()) return CodeMirror.Pass;
cm.operation(function() {
var cursors = cm.listSelections();
var indentUnit = cm.getOption("indentUnit");
for (var i = cursors.length - 1; i >= 0; i--) {
var cursor = cursors[i].head;
var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));
// Delete by one character by default
var deletePos = cm.findPosH(cursor, -1, "char", false);
if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
var prevIndent = new Pos(cursor.line,
CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));
// Smart delete only if we found a valid prevIndent location
if (prevIndent.ch != cursor.ch) deletePos = prevIndent;
}
cm.replaceRange("", deletePos, cursor, "+delete");
}
});
};
cmds.delLineRight = function(cm) {
cm.operation(function() {
var ranges = cm.listSelections();
for (var i = ranges.length - 1; i >= 0; i--)
cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
cm.scrollIntoView();
});
};
cmds.upcaseAtCursor = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
};
cmds.downcaseAtCursor = function(cm) {
modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
};
cmds.setSublimeMark = function(cm) {
if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
};
cmds.selectToSublimeMark = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) cm.setSelection(cm.getCursor(), found);
};
cmds.deleteToSublimeMark = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
var from = cm.getCursor(), to = found;
if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
cm.state.sublimeKilled = cm.getRange(from, to);
cm.replaceRange("", from, to);
}
};
cmds.swapWithSublimeMark = function(cm) {
var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
if (found) {
cm.state.sublimeMark.clear();
cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
cm.setCursor(found);
}
};
cmds.sublimeYank = function(cm) {
if (cm.state.sublimeKilled != null)
cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
};
cmds.showInCenter = function(cm) {
var pos = cm.cursorCoords(null, "local");
cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
};
function getTarget(cm) {
var from = cm.getCursor("from"), to = cm.getCursor("to");
if (CodeMirror.cmpPos(from, to) == 0) {
var word = wordAt(cm, from);
if (!word.word) return;
from = word.from;
to = word.to;
}
return {from: from, to: to, query: cm.getRange(from, to), word: word};
}
function findAndGoTo(cm, forward) {
var target = getTarget(cm);
if (!target) return;
var query = target.query;
var cur = cm.getSearchCursor(query, forward ? target.to : target.from);
if (forward ? cur.findNext() : cur.findPrevious()) {
cm.setSelection(cur.from(), cur.to());
} else {
cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
: cm.clipPos(Pos(cm.lastLine())));
if (forward ? cur.findNext() : cur.findPrevious())
cm.setSelection(cur.from(), cur.to());
else if (target.word)
cm.setSelection(target.from, target.to);
}
};
cmds.findUnder = function(cm) { findAndGoTo(cm, true); };
cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); };
cmds.findAllUnder = function(cm) {
var target = getTarget(cm);
if (!target) return;
var cur = cm.getSearchCursor(target.query);
var matches = [];
var primaryIndex = -1;
while (cur.findNext()) {
matches.push({anchor: cur.from(), head: cur.to()});
if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
primaryIndex++;
}
cm.setSelections(matches, primaryIndex);
};
var keyMap = CodeMirror.keyMap;
keyMap.macSublime = {
"Cmd-Left": "goLineStartSmart",
"Shift-Tab": "indentLess",
"Shift-Ctrl-K": "deleteLine",
"Alt-Q": "wrapLines",
"Ctrl-Left": "goSubwordLeft",
"Ctrl-Right": "goSubwordRight",
"Ctrl-Alt-Up": "scrollLineUp",
"Ctrl-Alt-Down": "scrollLineDown",
"Cmd-L": "selectLine",
"Shift-Cmd-L": "splitSelectionByLine",
"Esc": "singleSelectionTop",
"Cmd-Enter": "insertLineAfter",
"Shift-Cmd-Enter": "insertLineBefore",
"Cmd-D": "selectNextOccurrence",
"Shift-Cmd-Space": "selectScope",
"Shift-Cmd-M": "selectBetweenBrackets",
"Cmd-M": "goToBracket",
"Cmd-Ctrl-Up": "swapLineUp",
"Cmd-Ctrl-Down": "swapLineDown",
"Cmd-/": "toggleCommentIndented",
"Cmd-J": "joinLines",
"Shift-Cmd-D": "duplicateLine",
"F5": "sortLines",
"Shift-F5": "reverseSortLines",
"Cmd-F5": "sortLinesInsensitive",
"Shift-Cmd-F5": "reverseSortLinesInsensitive",
"F2": "nextBookmark",
"Shift-F2": "prevBookmark",
"Cmd-F2": "toggleBookmark",
"Shift-Cmd-F2": "clearBookmarks",
"Alt-F2": "selectBookmarks",
"Backspace": "smartBackspace",
"Cmd-K Cmd-D": "skipAndSelectNextOccurrence",
"Cmd-K Cmd-K": "delLineRight",
"Cmd-K Cmd-U": "upcaseAtCursor",
"Cmd-K Cmd-L": "downcaseAtCursor",
"Cmd-K Cmd-Space": "setSublimeMark",
"Cmd-K Cmd-A": "selectToSublimeMark",
"Cmd-K Cmd-W": "deleteToSublimeMark",
"Cmd-K Cmd-X": "swapWithSublimeMark",
"Cmd-K Cmd-Y": "sublimeYank",
"Cmd-K Cmd-C": "showInCenter",
"Cmd-K Cmd-G": "clearBookmarks",
"Cmd-K Cmd-Backspace": "delLineLeft",
"Cmd-K Cmd-1": "foldAll",
"Cmd-K Cmd-0": "unfoldAll",
"Cmd-K Cmd-J": "unfoldAll",
"Ctrl-Shift-Up": "addCursorToPrevLine",
"Ctrl-Shift-Down": "addCursorToNextLine",
"Cmd-F3": "findUnder",
"Shift-Cmd-F3": "findUnderPrevious",
"Alt-F3": "findAllUnder",
"Shift-Cmd-[": "fold",
"Shift-Cmd-]": "unfold",
"Cmd-I": "findIncremental",
"Shift-Cmd-I": "findIncrementalReverse",
"Cmd-H": "replace",
"F3": "findNext",
"Shift-F3": "findPrev",
"fallthrough": "macDefault"
};
CodeMirror.normalizeKeyMap(keyMap.macSublime);
keyMap.pcSublime = {
"Shift-Tab": "indentLess",
"Shift-Ctrl-K": "deleteLine",
"Alt-Q": "wrapLines",
"Ctrl-T": "transposeChars",
"Alt-Left": "goSubwordLeft",
"Alt-Right": "goSubwordRight",
"Ctrl-Up": "scrollLineUp",
"Ctrl-Down": "scrollLineDown",
"Ctrl-L": "selectLine",
"Shift-Ctrl-L": "splitSelectionByLine",
"Esc": "singleSelectionTop",
"Ctrl-Enter": "insertLineAfter",
"Shift-Ctrl-Enter": "insertLineBefore",
"Ctrl-D": "selectNextOccurrence",
"Shift-Ctrl-Space": "selectScope",
"Shift-Ctrl-M": "selectBetweenBrackets",
"Ctrl-M": "goToBracket",
"Shift-Ctrl-Up": "swapLineUp",
"Shift-Ctrl-Down": "swapLineDown",
"Ctrl-/": "toggleCommentIndented",
"Ctrl-J": "joinLines",
"Shift-Ctrl-D": "duplicateLine",
"F9": "sortLines",
"Shift-F9": "reverseSortLines",
"Ctrl-F9": "sortLinesInsensitive",
"Shift-Ctrl-F9": "reverseSortLinesInsensitive",
"F2": "nextBookmark",
"Shift-F2": "prevBookmark",
"Ctrl-F2": "toggleBookmark",
"Shift-Ctrl-F2": "clearBookmarks",
"Alt-F2": "selectBookmarks",
"Backspace": "smartBackspace",
"Ctrl-K Ctrl-D": "skipAndSelectNextOccurrence",
"Ctrl-K Ctrl-K": "delLineRight",
"Ctrl-K Ctrl-U": "upcaseAtCursor",
"Ctrl-K Ctrl-L": "downcaseAtCursor",
"Ctrl-K Ctrl-Space": "setSublimeMark",
"Ctrl-K Ctrl-A": "selectToSublimeMark",
"Ctrl-K Ctrl-W": "deleteToSublimeMark",
"Ctrl-K Ctrl-X": "swapWithSublimeMark",
"Ctrl-K Ctrl-Y": "sublimeYank",
"Ctrl-K Ctrl-C": "showInCenter",
"Ctrl-K Ctrl-G": "clearBookmarks",
"Ctrl-K Ctrl-Backspace": "delLineLeft",
"Ctrl-K Ctrl-1": "foldAll",
"Ctrl-K Ctrl-0": "unfoldAll",
"Ctrl-K Ctrl-J": "unfoldAll",
"Ctrl-Alt-Up": "addCursorToPrevLine",
"Ctrl-Alt-Down": "addCursorToNextLine",
"Ctrl-F3": "findUnder",
"Shift-Ctrl-F3": "findUnderPrevious",
"Alt-F3": "findAllUnder",
"Shift-Ctrl-[": "fold",
"Shift-Ctrl-]": "unfold",
"Ctrl-I": "findIncremental",
"Shift-Ctrl-I": "findIncrementalReverse",
"Ctrl-H": "replace",
"F3": "findNext",
"Shift-F3": "findPrev",
"fallthrough": "pcDefault"
};
CodeMirror.normalizeKeyMap(keyMap.pcSublime);
var mac = keyMap.default == keyMap.macDefault;
keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime;
});
|
294coder/Efficient-MIF
| 2,057 |
utils/loss_landscape/cifar10/dataloader.py
|
import os
import torch
import torchvision
import torchvision.transforms as transforms
def get_data_loaders(args):
if args.trainloader and args.testloader:
assert os.path.exists(args.trainloader), 'trainloader does not exist'
assert os.path.exists(args.testloader), 'testloader does not exist'
trainloader = torch.load(args.trainloader)
testloader = torch.load(args.testloader)
return trainloader, testloader
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
std=[x/255.0 for x in [63.0, 62.1, 66.7]])
if args.raw_data:
transform_train = transforms.Compose([
transforms.ToTensor(),
])
else:
if not args.noaug:
# with data augmentation
transform_train = transforms.Compose([
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
normalize,
])
else:
# no data agumentation
transform_train = transforms.Compose([
transforms.ToTensor(),
normalize,
])
transform_test = transforms.Compose([
transforms.ToTensor(),
normalize,
])
kwargs = {'num_workers': 2, 'pin_memory': True} if args.ngpu else {}
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True,
transform=transform_train)
testset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True,
transform=transform_test)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=args.batch_size,
shuffle=True, **kwargs)
testloader = torch.utils.data.DataLoader(testset, batch_size=args.batch_size,
shuffle=False, **kwargs)
return trainloader, testloader
|
294coder/Efficient-MIF
| 2,350 |
utils/loss_landscape/cifar10/model_loader.py
|
import os
import torch, torchvision
import cifar10.models.vgg as vgg
import cifar10.models.resnet as resnet
import cifar10.models.densenet as densenet
# map between model name and function
models = {
'vgg9' : vgg.VGG9,
'densenet121' : densenet.DenseNet121,
'resnet18' : resnet.ResNet18,
'resnet18_noshort' : resnet.ResNet18_noshort,
'resnet34' : resnet.ResNet34,
'resnet34_noshort' : resnet.ResNet34_noshort,
'resnet50' : resnet.ResNet50,
'resnet50_noshort' : resnet.ResNet50_noshort,
'resnet101' : resnet.ResNet101,
'resnet101_noshort' : resnet.ResNet101_noshort,
'resnet152' : resnet.ResNet152,
'resnet152_noshort' : resnet.ResNet152_noshort,
'resnet20' : resnet.ResNet20,
'resnet20_noshort' : resnet.ResNet20_noshort,
'resnet32_noshort' : resnet.ResNet32_noshort,
'resnet44_noshort' : resnet.ResNet44_noshort,
'resnet50_16_noshort' : resnet.ResNet50_16_noshort,
'resnet56' : resnet.ResNet56,
'resnet56_noshort' : resnet.ResNet56_noshort,
'resnet110' : resnet.ResNet110,
'resnet110_noshort' : resnet.ResNet110_noshort,
'wrn56_2' : resnet.WRN56_2,
'wrn56_2_noshort' : resnet.WRN56_2_noshort,
'wrn56_4' : resnet.WRN56_4,
'wrn56_4_noshort' : resnet.WRN56_4_noshort,
'wrn56_8' : resnet.WRN56_8,
'wrn56_8_noshort' : resnet.WRN56_8_noshort,
'wrn110_2_noshort' : resnet.WRN110_2_noshort,
'wrn110_4_noshort' : resnet.WRN110_4_noshort,
}
def load(model_name, model_file=None, data_parallel=False):
net = models[model_name]()
if data_parallel: # the model is saved in data paralle mode
net = torch.nn.DataParallel(net)
if model_file:
assert os.path.exists(model_file), model_file + " does not exist."
stored = torch.load(model_file, map_location=lambda storage, loc: storage)
if 'state_dict' in stored.keys():
net.load_state_dict(stored['state_dict'])
else:
net.load_state_dict(stored)
if data_parallel: # convert the model back to the single GPU version
net = net.module
net.eval()
return net
|
281677160/openwrt-package
| 11,182 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_live.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_live.h"
static void *ngx_live_create_conf(ngx_cycle_t *cf);
static char *ngx_live_init_conf(ngx_cycle_t *cycle, void *conf);
static ngx_command_t ngx_live_commands[] = {
{ ngx_string("stream_buckets"),
NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
0,
offsetof(ngx_live_conf_t, stream_buckets),
NULL },
{ ngx_string("server_buckets"),
NGX_MAIN_CONF|NGX_DIRECT_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
0,
offsetof(ngx_live_conf_t, server_buckets),
NULL },
ngx_null_command
};
static ngx_core_module_t ngx_live_module_ctx = {
ngx_string("live"),
ngx_live_create_conf, /* create conf */
ngx_live_init_conf /* init conf */
};
ngx_module_t ngx_live_module = {
NGX_MODULE_V1,
&ngx_live_module_ctx, /* module context */
ngx_live_commands, /* module directives */
NGX_CORE_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_live_create_conf(ngx_cycle_t *cycle)
{
ngx_live_conf_t *lcf;
lcf = ngx_pcalloc(cycle->pool, sizeof(ngx_live_conf_t));
if (lcf == NULL) {
return NULL;
}
lcf->stream_buckets = NGX_CONF_UNSET_SIZE;
lcf->server_buckets = NGX_CONF_UNSET_SIZE;
return lcf;
}
static char *
ngx_live_init_conf(ngx_cycle_t *cycle, void *conf)
{
ngx_live_conf_t *lcf = conf;
lcf->pool = ngx_create_pool(4096, cycle->log);
if (lcf->pool == NULL) {
return NGX_CONF_ERROR;
}
ngx_conf_init_size_value(lcf->stream_buckets, 10007);
ngx_conf_init_size_value(lcf->server_buckets, 1031);
lcf->servers = ngx_pcalloc(lcf->pool,
sizeof(ngx_live_server_t *) * lcf->server_buckets);
if (lcf->servers == NULL) {
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static ngx_live_server_t **
ngx_live_find_server(ngx_str_t *serverid)
{
ngx_live_conf_t *lcf;
ngx_live_server_t **psrv;
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
psrv = &lcf->servers[ngx_hash_key(serverid->data, serverid->len)
% lcf->server_buckets];
for (; *psrv; psrv = &(*psrv)->next) {
if (ngx_strlen((*psrv)->serverid) == serverid->len &&
ngx_memcmp((*psrv)->serverid, serverid->data, serverid->len) == 0)
{
break;
}
}
return psrv;
}
static ngx_live_server_t *
ngx_live_get_server(ngx_str_t *serverid)
{
ngx_live_conf_t *lcf;
ngx_live_server_t *srv;
if (serverid->len > NGX_LIVE_SERVERID_LEN - 1) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"serverid too long: %ui", serverid->len);
return NULL;
}
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
srv = lcf->free_server;
if (srv == NULL) {
srv = ngx_pcalloc(lcf->pool, sizeof(ngx_live_server_t));
if (srv == NULL) {
return NULL;
}
srv->streams = ngx_pcalloc(lcf->pool,
sizeof(ngx_live_stream_t *) * lcf->stream_buckets);
if (srv->streams == NULL) {
return NULL;
}
++lcf->alloc_server_count;
} else {
lcf->free_server = srv->next;
--lcf->free_server_count;
}
*ngx_cpymem(srv->serverid, serverid->data, serverid->len) = 0;
srv->deleted = 0;
srv->n_stream = 0;
return srv;
}
static void
ngx_live_put_server(ngx_live_server_t *server)
{
ngx_live_conf_t *lcf;
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
server->next = lcf->free_server;
lcf->free_server = server;
++lcf->free_server_count;
}
static ngx_live_stream_t **
ngx_live_find_stream(ngx_live_server_t *server, ngx_str_t *stream)
{
ngx_live_conf_t *lcf;
ngx_live_stream_t **pst;
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
pst = &server->streams[ngx_hash_key(stream->data, stream->len)
% lcf->stream_buckets];
for (; *pst; pst = &(*pst)->next) {
if (ngx_strlen((*pst)->name) == stream->len &&
ngx_memcmp((*pst)->name, stream->data, stream->len) == 0)
{
break;
}
}
return pst;
}
static ngx_live_stream_t *
ngx_live_get_stream(ngx_str_t *stream)
{
ngx_live_conf_t *lcf;
ngx_live_stream_t *st;
if (stream->len > NGX_LIVE_STREAM_LEN - 1) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"stream too long: %ui", stream->len);
return NULL;
}
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
st = lcf->free_stream;
if (st == NULL) {
st = ngx_pcalloc(lcf->pool, sizeof(ngx_live_stream_t));
++lcf->alloc_stream_count;
} else {
lcf->free_stream = st->next;
--lcf->free_stream_count;
ngx_memzero(st, sizeof(ngx_live_stream_t));
}
*ngx_cpymem(st->name, stream->data, stream->len) = 0;
st->pslot = -1;
st->epoch = ngx_current_msec;
ngx_map_init(&st->pubctx, ngx_map_hash_int, ngx_cmp_int);
return st;
}
static void
ngx_live_put_stream(ngx_live_stream_t *st)
{
ngx_live_conf_t *lcf;
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
st->next = lcf->free_stream;
lcf->free_stream = st;
++lcf->free_stream_count;
}
ngx_live_server_t *
ngx_live_create_server(ngx_str_t *serverid)
{
ngx_live_server_t **psrv;
psrv = ngx_live_find_server(serverid);
if (*psrv) {
(*psrv)->deleted = 0;
return *psrv;
}
*psrv = ngx_live_get_server(serverid);
return *psrv;
}
ngx_live_server_t *
ngx_live_fetch_server(ngx_str_t *serverid)
{
ngx_live_server_t **psrv;
psrv = ngx_live_find_server(serverid);
return *psrv;
}
void
ngx_live_delete_server(ngx_str_t *serverid)
{
ngx_live_server_t **psrv, *srv;
psrv = ngx_live_find_server(serverid);
if (*psrv == NULL) {
return;
}
if ((*psrv)->n_stream != 0) {
(*psrv)->deleted = 1;
}
if ((*psrv)->n_stream == 0) {
srv = *psrv;
*psrv = srv->next;
ngx_live_put_server(srv);
}
}
ngx_live_stream_t *
ngx_live_create_stream(ngx_str_t *serverid, ngx_str_t *stream)
{
ngx_live_server_t **psrv;
ngx_live_stream_t **pst;
psrv = ngx_live_find_server(serverid);
if (*psrv == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"server %V does not exist when create stream", serverid);
return NULL;
}
pst = ngx_live_find_stream(*psrv, stream);
if (*pst) {
return *pst;
}
*pst = ngx_live_get_stream(stream);
++(*psrv)->n_stream;
return *pst;
}
ngx_live_stream_t *
ngx_live_fetch_stream(ngx_str_t *serverid, ngx_str_t *stream)
{
ngx_live_server_t **psrv;
ngx_live_stream_t **pst;
psrv = ngx_live_find_server(serverid);
if (*psrv == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"server %V does not exist when fetch stream", serverid);
return NULL;
}
pst = ngx_live_find_stream(*psrv, stream);
return *pst;
}
void
ngx_live_delete_stream(ngx_str_t *serverid, ngx_str_t *stream)
{
ngx_live_server_t **psrv;
ngx_live_stream_t **pst, *st;
psrv = ngx_live_find_server(serverid);
if (*psrv == NULL) {
ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0,
"server %V does not exist when delete stream", serverid);
return;
}
pst = ngx_live_find_stream(*psrv, stream);
if (*pst == NULL) {
return;
}
st = *pst;
*pst = st->next;
ngx_live_put_stream(st);
--(*psrv)->n_stream;
if ((*psrv)->deleted && (*psrv)->n_stream == 0) {
ngx_live_delete_server(serverid);
}
}
void
ngx_live_create_ctx(ngx_rtmp_session_t *s, unsigned publishing)
{
ngx_rtmp_core_ctx_t *ctx, **pctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_core_module);
if (ctx == NULL) {
ctx = ngx_pcalloc(s->pool, sizeof(ngx_rtmp_core_ctx_t));
if (ctx == NULL) {
return;
}
ngx_rtmp_set_ctx(s, ctx, ngx_rtmp_core_module);
}
ctx->publishing = publishing;
ctx->session = s;
if (publishing) {
pctx = &s->live_stream->publish_ctx;
} else {
pctx = &s->live_stream->play_ctx;
}
ctx->next = (*pctx);
*pctx = ctx;
}
void
ngx_live_delete_ctx(ngx_rtmp_session_t *s)
{
ngx_rtmp_core_ctx_t *ctx, **pctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_rtmp_core_module);
if (ctx == NULL) {
return;
}
if (ctx->publishing) {
pctx = &s->live_stream->publish_ctx;
} else {
pctx = &s->live_stream->play_ctx;
}
for (/* void */; *pctx; pctx = &(*pctx)->next) {
if (*pctx == ctx) {
*pctx = ctx->next;
return;
}
}
}
ngx_chain_t *
ngx_live_state(ngx_http_request_t *r)
{
ngx_live_conf_t *lcf;
ngx_chain_t *cl;
ngx_buf_t *b;
size_t len;
lcf = (ngx_live_conf_t *) ngx_get_conf(ngx_cycle->conf_ctx,
ngx_live_module);
len = sizeof("##########ngx live state##########\n") - 1
+ sizeof("ngx_live nalloc server: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_live nfree server: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_live nalloc stream: \n") - 1 + NGX_OFF_T_LEN
+ sizeof("ngx_live nfree stream: \n") - 1 + NGX_OFF_T_LEN;
cl = ngx_alloc_chain_link(r->pool);
if (cl == NULL) {
return NULL;
}
cl->next = NULL;
b = ngx_create_temp_buf(r->pool, len);
if (b == NULL) {
return NULL;
}
cl->buf = b;
b->last = ngx_snprintf(b->last, len,
"##########ngx live state##########\n"
"ngx_live nalloc server: %ui\nngx_live nfree server: %ui\n"
"ngx_live nalloc stream: %ui\nngx_live nfree stream: %ui\n",
lcf->alloc_server_count, lcf->free_server_count,
lcf->alloc_stream_count, lcf->free_stream_count);
return cl;
}
|
2881099/FreeSql.AdminLTE
| 2,614 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/duotone-dark.css
|
/*
Name: DuoTone-Dark
Author: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes)
CodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/)
*/
.cm-s-duotone-dark.CodeMirror { background: #2a2734; color: #6c6783; }
.cm-s-duotone-dark div.CodeMirror-selected { background: #545167!important; }
.cm-s-duotone-dark .CodeMirror-gutters { background: #2a2734; border-right: 0px; }
.cm-s-duotone-dark .CodeMirror-linenumber { color: #545167; }
/* begin cursor */
.cm-s-duotone-dark .CodeMirror-cursor { border-left: 1px solid #ffad5c; /* border-left: 1px solid #ffad5c80; */ border-right: .5em solid #ffad5c; /* border-right: .5em solid #ffad5c80; */ opacity: .5; }
.cm-s-duotone-dark .CodeMirror-activeline-background { background: #363342; /* background: #36334280; */ opacity: .5;}
.cm-s-duotone-dark .cm-fat-cursor .CodeMirror-cursor { background: #ffad5c; /* background: #ffad5c80; */ opacity: .5;}
/* end cursor */
.cm-s-duotone-dark span.cm-atom, .cm-s-duotone-dark span.cm-number, .cm-s-duotone-dark span.cm-keyword, .cm-s-duotone-dark span.cm-variable, .cm-s-duotone-dark span.cm-attribute, .cm-s-duotone-dark span.cm-quote, .cm-s-duotone-dark span.cm-hr, .cm-s-duotone-dark span.cm-link { color: #ffcc99; }
.cm-s-duotone-dark span.cm-property { color: #9a86fd; }
.cm-s-duotone-dark span.cm-punctuation, .cm-s-duotone-dark span.cm-unit, .cm-s-duotone-dark span.cm-negative { color: #e09142; }
.cm-s-duotone-dark span.cm-string { color: #ffb870; }
.cm-s-duotone-dark span.cm-operator { color: #ffad5c; }
.cm-s-duotone-dark span.cm-positive { color: #6a51e6; }
.cm-s-duotone-dark span.cm-variable-2, .cm-s-duotone-dark span.cm-variable-3, .cm-s-duotone-dark span.cm-type, .cm-s-duotone-dark span.cm-string-2, .cm-s-duotone-dark span.cm-url { color: #7a63ee; }
.cm-s-duotone-dark span.cm-def, .cm-s-duotone-dark span.cm-tag, .cm-s-duotone-dark span.cm-builtin, .cm-s-duotone-dark span.cm-qualifier, .cm-s-duotone-dark span.cm-header, .cm-s-duotone-dark span.cm-em { color: #eeebff; }
.cm-s-duotone-dark span.cm-bracket, .cm-s-duotone-dark span.cm-comment { color: #6c6783; }
/* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */
.cm-s-duotone-dark span.cm-error, .cm-s-duotone-dark span.cm-invalidchar { color: #f00; }
.cm-s-duotone-dark span.cm-header { font-weight: normal; }
.cm-s-duotone-dark .CodeMirror-matchingbracket { text-decoration: underline; color: #eeebff !important; }
|
2881099/FreeSql.AdminLTE
| 2,719 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/duotone-light.css
|
/*
Name: DuoTone-Light
Author: by Bram de Haan, adapted from DuoTone themes by Simurai (http://simurai.com/projects/2016/01/01/duotone-themes)
CodeMirror template by Jan T. Sott (https://github.com/idleberg), adapted by Bram de Haan (https://github.com/atelierbram/)
*/
.cm-s-duotone-light.CodeMirror { background: #faf8f5; color: #b29762; }
.cm-s-duotone-light div.CodeMirror-selected { background: #e3dcce !important; }
.cm-s-duotone-light .CodeMirror-gutters { background: #faf8f5; border-right: 0px; }
.cm-s-duotone-light .CodeMirror-linenumber { color: #cdc4b1; }
/* begin cursor */
.cm-s-duotone-light .CodeMirror-cursor { border-left: 1px solid #93abdc; /* border-left: 1px solid #93abdc80; */ border-right: .5em solid #93abdc; /* border-right: .5em solid #93abdc80; */ opacity: .5; }
.cm-s-duotone-light .CodeMirror-activeline-background { background: #e3dcce; /* background: #e3dcce80; */ opacity: .5; }
.cm-s-duotone-light .cm-fat-cursor .CodeMirror-cursor { background: #93abdc; /* #93abdc80; */ opacity: .5; }
/* end cursor */
.cm-s-duotone-light span.cm-atom, .cm-s-duotone-light span.cm-number, .cm-s-duotone-light span.cm-keyword, .cm-s-duotone-light span.cm-variable, .cm-s-duotone-light span.cm-attribute, .cm-s-duotone-light span.cm-quote, .cm-s-duotone-light-light span.cm-hr, .cm-s-duotone-light-light span.cm-link { color: #063289; }
.cm-s-duotone-light span.cm-property { color: #b29762; }
.cm-s-duotone-light span.cm-punctuation, .cm-s-duotone-light span.cm-unit, .cm-s-duotone-light span.cm-negative { color: #063289; }
.cm-s-duotone-light span.cm-string, .cm-s-duotone-light span.cm-operator { color: #1659df; }
.cm-s-duotone-light span.cm-positive { color: #896724; }
.cm-s-duotone-light span.cm-variable-2, .cm-s-duotone-light span.cm-variable-3, .cm-s-duotone-light span.cm-type, .cm-s-duotone-light span.cm-string-2, .cm-s-duotone-light span.cm-url { color: #896724; }
.cm-s-duotone-light span.cm-def, .cm-s-duotone-light span.cm-tag, .cm-s-duotone-light span.cm-builtin, .cm-s-duotone-light span.cm-qualifier, .cm-s-duotone-light span.cm-header, .cm-s-duotone-light span.cm-em { color: #2d2006; }
.cm-s-duotone-light span.cm-bracket, .cm-s-duotone-light span.cm-comment { color: #b6ad9a; }
/* using #f00 red for errors, don't think any of the colorscheme variables will stand out enough, ... maybe by giving it a background-color ... */
/* .cm-s-duotone-light span.cm-error { background: #896724; color: #728fcb; } */
.cm-s-duotone-light span.cm-error, .cm-s-duotone-light span.cm-invalidchar { color: #f00; }
.cm-s-duotone-light span.cm-header { font-weight: normal; }
.cm-s-duotone-light .CodeMirror-matchingbracket { text-decoration: underline; color: #faf8f5 !important; }
|
2881099/FreeSql.AdminLTE
| 2,009 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/seti.css
|
/*
Name: seti
Author: Michael Kaminsky (http://github.com/mkaminsky11)
Original seti color scheme by Jesse Weed (https://github.com/jesseweed/seti-syntax)
*/
.cm-s-seti.CodeMirror {
background-color: #151718 !important;
color: #CFD2D1 !important;
border: none;
}
.cm-s-seti .CodeMirror-gutters {
color: #404b53;
background-color: #0E1112;
border: none;
}
.cm-s-seti .CodeMirror-cursor { border-left: solid thin #f8f8f0; }
.cm-s-seti .CodeMirror-linenumber { color: #6D8A88; }
.cm-s-seti.CodeMirror-focused div.CodeMirror-selected { background: rgba(255, 255, 255, 0.10); }
.cm-s-seti .CodeMirror-line::selection, .cm-s-seti .CodeMirror-line > span::selection, .cm-s-seti .CodeMirror-line > span > span::selection { background: rgba(255, 255, 255, 0.10); }
.cm-s-seti .CodeMirror-line::-moz-selection, .cm-s-seti .CodeMirror-line > span::-moz-selection, .cm-s-seti .CodeMirror-line > span > span::-moz-selection { background: rgba(255, 255, 255, 0.10); }
.cm-s-seti span.cm-comment { color: #41535b; }
.cm-s-seti span.cm-string, .cm-s-seti span.cm-string-2 { color: #55b5db; }
.cm-s-seti span.cm-number { color: #cd3f45; }
.cm-s-seti span.cm-variable { color: #55b5db; }
.cm-s-seti span.cm-variable-2 { color: #a074c4; }
.cm-s-seti span.cm-def { color: #55b5db; }
.cm-s-seti span.cm-keyword { color: #ff79c6; }
.cm-s-seti span.cm-operator { color: #9fca56; }
.cm-s-seti span.cm-keyword { color: #e6cd69; }
.cm-s-seti span.cm-atom { color: #cd3f45; }
.cm-s-seti span.cm-meta { color: #55b5db; }
.cm-s-seti span.cm-tag { color: #55b5db; }
.cm-s-seti span.cm-attribute { color: #9fca56; }
.cm-s-seti span.cm-qualifier { color: #9fca56; }
.cm-s-seti span.cm-property { color: #a074c4; }
.cm-s-seti span.cm-variable-3, .cm-s-seti span.cm-type { color: #9fca56; }
.cm-s-seti span.cm-builtin { color: #9fca56; }
.cm-s-seti .CodeMirror-activeline-background { background: #101213; }
.cm-s-seti .CodeMirror-matchingbracket { text-decoration: underline; color: white !important; }
|
2881099/FreeSql.AdminLTE
| 2,767 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/material-ocean.css
|
/*
Name: material
Author: Mattia Astorino (http://github.com/equinusocio)
Website: https://material-theme.site/
*/
.cm-s-material-ocean.CodeMirror {
background-color: #0F111A;
color: #8F93A2;
}
.cm-s-material-ocean .CodeMirror-gutters {
background: #0F111A;
color: #464B5D;
border: none;
}
.cm-s-material-ocean .CodeMirror-guttermarker,
.cm-s-material-ocean .CodeMirror-guttermarker-subtle,
.cm-s-material-ocean .CodeMirror-linenumber {
color: #464B5D;
}
.cm-s-material-ocean .CodeMirror-cursor {
border-left: 1px solid #FFCC00;
}
.cm-s-material-ocean.cm-fat-cursor .CodeMirror-cursor {
background-color: #a2a8a175 !important;
}
.cm-s-material-ocean .cm-animate-fat-cursor {
background-color: #a2a8a175 !important;
}
.cm-s-material-ocean div.CodeMirror-selected {
background: rgba(113, 124, 180, 0.2);
}
.cm-s-material-ocean.CodeMirror-focused div.CodeMirror-selected {
background: rgba(113, 124, 180, 0.2);
}
.cm-s-material-ocean .CodeMirror-line::selection,
.cm-s-material-ocean .CodeMirror-line>span::selection,
.cm-s-material-ocean .CodeMirror-line>span>span::selection {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material-ocean .CodeMirror-line::-moz-selection,
.cm-s-material-ocean .CodeMirror-line>span::-moz-selection,
.cm-s-material-ocean .CodeMirror-line>span>span::-moz-selection {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-material-ocean .CodeMirror-activeline-background {
background: rgba(0, 0, 0, 0.5);
}
.cm-s-material-ocean .cm-keyword {
color: #C792EA;
}
.cm-s-material-ocean .cm-operator {
color: #89DDFF;
}
.cm-s-material-ocean .cm-variable-2 {
color: #EEFFFF;
}
.cm-s-material-ocean .cm-variable-3,
.cm-s-material-ocean .cm-type {
color: #f07178;
}
.cm-s-material-ocean .cm-builtin {
color: #FFCB6B;
}
.cm-s-material-ocean .cm-atom {
color: #F78C6C;
}
.cm-s-material-ocean .cm-number {
color: #FF5370;
}
.cm-s-material-ocean .cm-def {
color: #82AAFF;
}
.cm-s-material-ocean .cm-string {
color: #C3E88D;
}
.cm-s-material-ocean .cm-string-2 {
color: #f07178;
}
.cm-s-material-ocean .cm-comment {
color: #464B5D;
}
.cm-s-material-ocean .cm-variable {
color: #f07178;
}
.cm-s-material-ocean .cm-tag {
color: #FF5370;
}
.cm-s-material-ocean .cm-meta {
color: #FFCB6B;
}
.cm-s-material-ocean .cm-attribute {
color: #C792EA;
}
.cm-s-material-ocean .cm-property {
color: #C792EA;
}
.cm-s-material-ocean .cm-qualifier {
color: #DECB6B;
}
.cm-s-material-ocean .cm-variable-3,
.cm-s-material-ocean .cm-type {
color: #DECB6B;
}
.cm-s-material-ocean .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #FF5370;
}
.cm-s-material-ocean .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
|
294coder/Efficient-MIF
| 2,548 |
utils/loss_landscape/script/2d_contour_vgg9.sh
|
# ===========================================================
# 2d loss contours for VGG-9
# ===========================================================
# ------------------------------------------------------------
# SGD
#------------------------------------------------------------
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
# ------------------------------------------------------------
# Adam
#------------------------------------------------------------
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=8192_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=8192_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
|
281677160/openwrt-package
| 22,756 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_live_relay_rtmp.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_live_relay.h"
#include "ngx_poold.h"
#include "ngx_toolkit_misc.h"
#include "ngx_dynamic_resolver.h"
static ngx_int_t ngx_live_relay_rtmp_postconfiguration(ngx_conf_t *cf);
static void *ngx_live_relay_rtmp_create_app_conf(ngx_conf_t *cf);
static char *ngx_live_relay_rtmp_merge_app_conf(ngx_conf_t *cf, void *parent,
void *child);
typedef struct {
ngx_msec_t buflen;
} ngx_live_relay_rtmp_app_conf_t;
typedef struct {
char *code;
ngx_uint_t status;
ngx_flag_t finalize;
} ngx_rtmp_status_code_t;
static ngx_rtmp_status_code_t ngx_rtmp_relay_status_error_code[] = {
{ "NetStream.Publish.BadName", 400, 1 },
{ "NetStream.Stream.Forbidden", 403, 1 },
{ "NetStream.Play.StreamNotFound", 404, 1 },
{ "NetStream.Relay.ServerError", 500, 1 },
{ NULL, 0, 0 }
};
#define NGX_RTMP_RELAY_CONNECT_TRANS 1
#define NGX_RTMP_RELAY_CREATE_STREAM_TRANS 2
#define NGX_RTMP_RELAY_CSID_AMF_INI 3
#define NGX_RTMP_RELAY_CSID_AMF 5
#define NGX_RTMP_RELAY_MSID 1
static ngx_command_t ngx_live_relay_rtmp_commands[] = {
{ ngx_string("relay_buffer"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_live_relay_rtmp_app_conf_t, buflen),
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_live_relay_rtmp_module_ctx = {
NULL, /* preconfiguration */
ngx_live_relay_rtmp_postconfiguration, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_live_relay_rtmp_create_app_conf, /* create app configuration */
ngx_live_relay_rtmp_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_live_relay_rtmp_module = {
NGX_MODULE_V1,
&ngx_live_relay_rtmp_module_ctx, /* module context */
ngx_live_relay_rtmp_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_live_relay_rtmp_create_app_conf(ngx_conf_t *cf)
{
ngx_live_relay_rtmp_app_conf_t *racf;
racf = ngx_pcalloc(cf->pool, sizeof(ngx_live_relay_rtmp_app_conf_t));
if (racf == NULL) {
return NULL;
}
racf->buflen = NGX_CONF_UNSET_MSEC;
return racf;
}
static char *
ngx_live_relay_rtmp_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_live_relay_rtmp_app_conf_t *prev = parent;
ngx_live_relay_rtmp_app_conf_t *conf = child;
ngx_conf_merge_msec_value(conf->buflen, prev->buflen, 5000);
return NGX_CONF_OK;
}
static ngx_int_t
ngx_live_relay_rtmp_send_connect(ngx_rtmp_session_t *s)
{
ngx_str_t app, tcurl;
double acodecs = 3575, vcodecs = 252;
static double trans = NGX_RTMP_RELAY_CONNECT_TRANS;
static ngx_rtmp_amf_elt_t out_cmd[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("app"),
NULL, 0 }, /* <-- fill */
{ NGX_RTMP_AMF_STRING,
ngx_string("tcUrl"),
NULL, 0 }, /* <-- fill */
{ NGX_RTMP_AMF_STRING,
ngx_string("pageUrl"),
NULL, 0 }, /* <-- fill */
{ NGX_RTMP_AMF_STRING,
ngx_string("swfUrl"),
NULL, 0 }, /* <-- fill */
{ NGX_RTMP_AMF_STRING,
ngx_string("flashVer"),
NULL, 0 }, /* <-- fill */
{ NGX_RTMP_AMF_NUMBER,
ngx_string("audioCodecs"),
NULL, 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_string("videoCodecs"),
NULL, 0 }
};
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"connect", 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&trans, 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
out_cmd, sizeof(out_cmd) }
};
ngx_rtmp_core_app_conf_t *cacf;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_live_relay_ctx_t *ctx;
ngx_rtmp_header_t h;
cacf = ngx_rtmp_get_module_app_conf(s, ngx_rtmp_core_module);
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (cacf == NULL || ctx == NULL) {
return NGX_ERROR;
}
/* app */
if (ctx->args.len) {
app.len = ctx->app.len + 1 + ctx->args.len;
app.data = ngx_pcalloc(s->pool, app.len);
if (app.data == NULL) {
return NGX_ERROR;
}
ngx_snprintf(app.data, app.len, "%V?%V", &ctx->app, &ctx->args);
} else {
app = ctx->app;
}
out_cmd[0].data = app.data;
out_cmd[0].len = app.len;
/* tcUrl */
tcurl.len = sizeof("rtmp://") - 1 + ctx->domain.len + 1 + ctx->app.len;
tcurl.data = ngx_palloc(s->pool, tcurl.len);
if (tcurl.data == NULL) {
return NGX_ERROR;
}
ngx_snprintf(tcurl.data, tcurl.len, "rtmp://%V/%V",
&ctx->domain, &ctx->app);
out_cmd[1].data = tcurl.data;
out_cmd[1].len = tcurl.len;
/* pageUrl */
out_cmd[2].data = ctx->referer.data;
out_cmd[2].len = ctx->referer.len;
/* swfUrl */
out_cmd[3].data = ctx->swf_url.data;
out_cmd[3].len = ctx->swf_url.len;
/* flashVer */
out_cmd[4].data = ctx->user_agent.data;
out_cmd[4].len = ctx->user_agent.len;
if (ctx->acodecs != 0) {
acodecs = (double) ctx->acodecs;
}
out_cmd[5].data = &acodecs;
if (ctx->vcodecs != 0) {
vcodecs = (double) ctx->vcodecs;
}
out_cmd[6].data = &vcodecs;
ngx_memzero(&h, sizeof(h));
h.csid = NGX_RTMP_RELAY_CSID_AMF_INI;
h.type = NGX_RTMP_MSG_AMF_CMD;
s->status = NGX_LIVE_CONNECT;
s->connect_time = ngx_current_msec;
return ngx_rtmp_send_chunk_size(s, cscf->chunk_size) != NGX_OK
|| ngx_rtmp_send_ack_size(s, cscf->ack_window) != NGX_OK
|| ngx_rtmp_send_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0])) != NGX_OK
? NGX_ERROR
: NGX_OK;
}
static ngx_int_t
ngx_live_relay_rtmp_send_create_stream(ngx_rtmp_session_t *s)
{
static double trans = NGX_RTMP_RELAY_CREATE_STREAM_TRANS;
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"createStream", 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 }
};
ngx_rtmp_header_t h;
ngx_memzero(&h, sizeof(h));
h.csid = NGX_RTMP_RELAY_CSID_AMF_INI;
h.type = NGX_RTMP_MSG_AMF_CMD;
s->stage = NGX_LIVE_CREATE_STREAM;
s->create_stream_time = ngx_current_msec;
return ngx_rtmp_send_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0]));
}
static ngx_int_t
ngx_live_relay_rtmp_send_publish(ngx_rtmp_session_t *s)
{
ngx_str_t name;
static double trans;
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"publish", 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
NULL, 0 }, /* <- to fill */
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"live", 0 }
};
ngx_rtmp_header_t h;
ngx_live_relay_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
return NGX_ERROR;
}
if (ctx->pargs.len) {
name.len = ctx->name.len + 1 + ctx->pargs.len;
name.data = ngx_pcalloc(s->pool, name.len);
if (name.data == NULL) {
return NGX_ERROR;
}
ngx_snprintf(name.data, name.len, "%V?%V", &ctx->name, &ctx->pargs);
} else {
name = ctx->name;
}
out_elts[3].data = name.data;
out_elts[3].len = name.len;
ngx_memzero(&h, sizeof(h));
h.csid = NGX_RTMP_RELAY_CSID_AMF;
h.msid = NGX_RTMP_RELAY_MSID;
h.type = NGX_RTMP_MSG_AMF_CMD;
s->stage = NGX_LIVE_PUBLISH;
s->ptime = ngx_current_msec;
return ngx_rtmp_send_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0]));
}
static ngx_int_t
ngx_live_relay_rtmp_send_play(ngx_rtmp_session_t *s)
{
ngx_str_t name;
static double trans;
static double start, duration;
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"play", 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
NULL, 0 }, /* <- fill */
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&start, 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&duration, 0 },
};
ngx_rtmp_header_t h;
ngx_live_relay_ctx_t *ctx;
ngx_live_relay_rtmp_app_conf_t *racf;
racf = ngx_rtmp_get_module_app_conf(s, ngx_live_relay_rtmp_module);
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (racf == NULL) {
return NGX_ERROR;
}
if (ctx->pargs.len) {
name.len = ctx->name.len + 1 + ctx->pargs.len;
name.data = ngx_pcalloc(s->pool, name.len);
if (name.data == NULL) {
return NGX_ERROR;
}
ngx_snprintf(name.data, name.len, "%V?%V", &ctx->name, &ctx->pargs);
} else {
name = ctx->name;
}
out_elts[3].data = name.data;
out_elts[3].len = name.len;
start = -1000;
duration = -1000;
ngx_memzero(&h, sizeof(h));
h.csid = NGX_RTMP_RELAY_CSID_AMF;
h.msid = NGX_RTMP_RELAY_MSID;
h.type = NGX_RTMP_MSG_AMF_CMD;
s->stage = NGX_LIVE_PLAY;
s->ptime = ngx_current_msec;
return ngx_rtmp_send_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0])) != NGX_OK
|| ngx_rtmp_send_set_buflen(s, NGX_RTMP_RELAY_MSID,
racf->buflen) != NGX_OK
? NGX_ERROR
: NGX_OK;
}
static ngx_int_t
ngx_live_relay_rtmp_status_error(ngx_rtmp_session_t *s, char *type, char *code,
char *level, char *desc)
{
ngx_rtmp_core_ctx_t *cctx;
size_t i;
ngx_flag_t status = 0;
if (ngx_strcmp(type, "onStatus") == 0) {
status = 1;
}
for (i = 0; ngx_rtmp_relay_status_error_code[i].code; ++i) {
if (ngx_strcmp(ngx_rtmp_relay_status_error_code[i].code, code)
!= 0)
{
continue;
}
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"relay transit, %s: level='%s' code='%s' description='%s'",
type, level, code, desc);
if (s->publishing) {
cctx = s->live_stream->play_ctx;
} else {
cctx = s->live_stream->publish_ctx;
}
for (; cctx; cctx = cctx->next) {
cctx->session->status = ngx_rtmp_relay_status_error_code[i].status;
status ? ngx_rtmp_send_status(cctx->session, code, level, desc)
: ngx_rtmp_send_error(cctx->session, code, level, desc);
if (ngx_rtmp_relay_status_error_code[i].finalize
&& !cctx->session->static_pull)
{
cctx->session->finalize_reason = NGX_LIVE_RELAY_TRANSIT;
ngx_rtmp_finalize_session(cctx->session);
}
}
}
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_rtmp_on_result(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_live_relay_ctx_t *ctx;
static struct {
double trans;
u_char level[32];
u_char code[128];
u_char desc[1024];
} v;
static ngx_rtmp_amf_elt_t in_inf[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("level"),
&v.level, sizeof(v.level) },
{ NGX_RTMP_AMF_STRING,
ngx_string("code"),
&v.code, sizeof(v.code) },
{ NGX_RTMP_AMF_STRING,
ngx_string("description"),
&v.desc, sizeof(v.desc) },
};
static ngx_rtmp_amf_elt_t in_elts[] = {
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&v.trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
in_inf, sizeof(in_inf) },
};
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
return NGX_OK;
}
ngx_memzero(&v, sizeof(v));
if (ngx_rtmp_receive_amf(s, in, in_elts,
sizeof(in_elts) / sizeof(in_elts[0])))
{
return NGX_ERROR;
}
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"relay: _result: level='%s' code='%s' description='%s'",
v.level, v.code, v.desc);
switch ((ngx_int_t)v.trans) {
case NGX_RTMP_RELAY_CONNECT_TRANS:
return ngx_live_relay_rtmp_send_create_stream(s);
case NGX_RTMP_RELAY_CREATE_STREAM_TRANS:
if (s->publishing == 0) {
if (ngx_live_relay_rtmp_send_publish(s) != NGX_OK) {
return NGX_ERROR;
}
return ngx_live_relay_play_local(s);
} else {
if (ngx_live_relay_rtmp_send_play(s) != NGX_OK) {
return NGX_ERROR;
}
return ngx_live_relay_publish_local(s);
}
default:
return NGX_OK;
}
}
static ngx_int_t
ngx_live_relay_rtmp_on_error(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_live_relay_ctx_t *ctx;
static struct {
double trans;
u_char level[32];
u_char code[128];
u_char desc[1024];
} v;
static ngx_rtmp_amf_elt_t in_inf[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("level"),
&v.level, sizeof(v.level) },
{ NGX_RTMP_AMF_STRING,
ngx_string("code"),
&v.code, sizeof(v.code) },
{ NGX_RTMP_AMF_STRING,
ngx_string("description"),
&v.desc, sizeof(v.desc) },
};
static ngx_rtmp_amf_elt_t in_elts[] = {
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&v.trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
in_inf, sizeof(in_inf) },
};
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
return NGX_OK;
}
ngx_memzero(&v, sizeof(v));
if (ngx_rtmp_receive_amf(s, in, in_elts,
sizeof(in_elts) / sizeof(in_elts[0])))
{
return NGX_ERROR;
}
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"relay: _error: level='%s' code='%s' description='%s'",
v.level, v.code, v.desc);
ngx_live_relay_rtmp_status_error(s, "_error", (char *) v.code,
(char *) v.level, (char *) v.desc);
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_rtmp_on_status(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_live_relay_ctx_t *ctx;
static struct {
double trans;
u_char level[32];
u_char code[128];
u_char desc[1024];
} v;
static ngx_rtmp_amf_elt_t in_inf[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("level"),
&v.level, sizeof(v.level) },
{ NGX_RTMP_AMF_STRING,
ngx_string("code"),
&v.code, sizeof(v.code) },
{ NGX_RTMP_AMF_STRING,
ngx_string("description"),
&v.desc, sizeof(v.desc) },
};
static ngx_rtmp_amf_elt_t in_elts[] = {
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&v.trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
in_inf, sizeof(in_inf) },
};
static ngx_rtmp_amf_elt_t in_elts_meta[] = {
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
in_inf, sizeof(in_inf) },
};
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
return NGX_OK;
}
ngx_memzero(&v, sizeof(v));
if (h->type == NGX_RTMP_MSG_AMF_META) {
ngx_rtmp_receive_amf(s, in, in_elts_meta,
sizeof(in_elts_meta) / sizeof(in_elts_meta[0]));
} else {
ngx_rtmp_receive_amf(s, in, in_elts,
sizeof(in_elts) / sizeof(in_elts[0]));
}
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"relay: onStatus: level='%s' code='%s' description='%s'",
v.level, v.code, v.desc);
ngx_live_relay_rtmp_status_error(s, "onStatus", (char *) v.code,
(char *) v.level, (char *) v.desc);
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_rtmp_handshake_done(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_chain_t *in)
{
ngx_live_relay_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
return NGX_OK;
}
return ngx_live_relay_rtmp_send_connect(s);
}
static ngx_int_t
ngx_live_relay_rtmp_get_peer(ngx_peer_connection_t *pc, void *data)
{
return NGX_OK;
}
static void
ngx_live_relay_rtmp_free_peer(ngx_peer_connection_t *pc, void *data,
ngx_uint_t state)
{
}
ngx_int_t
ngx_live_relay_create_rtmp(ngx_rtmp_session_t *s, ngx_live_relay_t *relay,
ngx_live_relay_url_t *url)
{
ngx_live_relay_ctx_t *rctx;
ngx_pool_t *pool;
ngx_peer_connection_t *pc;
ngx_connection_t *c;
ngx_int_t rc;
ngx_str_t name;
u_char text[NGX_SOCKADDRLEN];
// must use ngx_sockaddr_t, because sizeof(struct sockaddr)
// is not long enouph, content will be covered by other var
ngx_sockaddr_t nsa;
struct sockaddr *sa;
socklen_t len;
rctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (rctx == NULL) {
return NGX_ERROR;
}
pool = ngx_create_pool(4096, ngx_cycle->log);
if (pool == NULL) {
goto destroy;
}
#define NGX_LIVE_RELAY_CTX(para) \
if (ngx_copy_str(s->pool, &rctx->para, &relay->para) != NGX_OK) { \
goto destroy; \
}
NGX_LIVE_RELAY_CTX(domain);
NGX_LIVE_RELAY_CTX(app);
NGX_LIVE_RELAY_CTX(name);
NGX_LIVE_RELAY_CTX(pargs);
NGX_LIVE_RELAY_CTX(referer);
NGX_LIVE_RELAY_CTX(user_agent);
#undef NGX_LIVE_RELAY_CTX
rctx->tag = relay->tag;
// connect server
pc = ngx_pcalloc(s->pool, sizeof(ngx_peer_connection_t));
if (pc == NULL) {
goto destroy;
}
pc->log = s->log;
// get address
sa = (struct sockaddr *) &nsa;
len = ngx_dynamic_resolver_gethostbyname(&url->url.host, sa);
if (len == 0) {
ngx_log_error(NGX_LOG_ERR, s->log, 0,
"relay rtmp: gethostbyname failed %V", &url->url.host);
goto destroy;
}
if (url->port != 0) {
ngx_inet_set_port(sa, url->port);
}
ngx_memzero(text, sizeof(text));
name.len = ngx_sock_ntop(sa, len, text, NGX_SOCKADDRLEN, 1);
name.data = text;
/* copy log to keep shared log unchanged */
pc->get = ngx_live_relay_rtmp_get_peer;
pc->free = ngx_live_relay_rtmp_free_peer;
pc->name = &name;
pc->socklen = len;
pc->sockaddr = sa;
rc = ngx_event_connect_peer(pc);
if (rc != NGX_OK && rc != NGX_AGAIN ) {
ngx_log_error(NGX_LOG_ERR, s->log, 0, "relay: connection failed");
goto destroy;
}
c = pc->connection;
if (ngx_copy_str(pool, &c->addr_text, &url->url.host_with_port) != NGX_OK) {
goto destroy;
}
ngx_rtmp_init_session(s, c);
c->pool = pool;
#if (NGX_STAT_STUB)
(void) ngx_atomic_fetch_add(ngx_stat_active, 1);
#endif
ngx_rtmp_client_handshake(s, 1);
return NGX_OK;
destroy:
if (pool) {
ngx_destroy_pool(pool);
}
ngx_rtmp_finalize_session(s);
return NGX_ERROR;
}
static ngx_int_t
ngx_live_relay_rtmp_postconfiguration(ngx_conf_t *cf)
{
ngx_rtmp_core_main_conf_t *cmcf;
ngx_rtmp_handler_pt *h;
ngx_rtmp_amf_handler_t *ch;
cmcf = ngx_rtmp_conf_get_module_main_conf(cf, ngx_rtmp_core_module);
h = ngx_array_push(&cmcf->events[NGX_RTMP_HANDSHAKE_DONE]);
*h = ngx_live_relay_rtmp_handshake_done;
ch = ngx_array_push(&cmcf->amf);
ngx_str_set(&ch->name, "_result");
ch->handler = ngx_live_relay_rtmp_on_result;
ch = ngx_array_push(&cmcf->amf);
ngx_str_set(&ch->name, "_error");
ch->handler = ngx_live_relay_rtmp_on_error;
ch = ngx_array_push(&cmcf->amf);
ngx_str_set(&ch->name, "onStatus");
ch->handler = ngx_live_relay_rtmp_on_status;
return NGX_OK;
}
|
294coder/Efficient-MIF
| 1,938 |
utils/loss_landscape/script/1d_loss_curve_vgg9.sh
|
# ===========================================================
# 1d normalized surface for VGG-9
# ===========================================================
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=8192_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model vgg9 \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=8192_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xnorm filter --xignore biasbn
|
2881099/FreeSql.AdminLTE
| 1,987 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/3024-day.css
|
/*
Name: 3024 day
Author: Jan T. Sott (http://github.com/idleberg)
CodeMirror template by Jan T. Sott (https://github.com/idleberg/base16-codemirror)
Original Base16 color scheme by Chris Kempson (https://github.com/chriskempson/base16)
*/
.cm-s-3024-day.CodeMirror { background: #f7f7f7; color: #3a3432; }
.cm-s-3024-day div.CodeMirror-selected { background: #d6d5d4; }
.cm-s-3024-day .CodeMirror-line::selection, .cm-s-3024-day .CodeMirror-line > span::selection, .cm-s-3024-day .CodeMirror-line > span > span::selection { background: #d6d5d4; }
.cm-s-3024-day .CodeMirror-line::-moz-selection, .cm-s-3024-day .CodeMirror-line > span::-moz-selection, .cm-s-3024-day .CodeMirror-line > span > span::selection { background: #d9d9d9; }
.cm-s-3024-day .CodeMirror-gutters { background: #f7f7f7; border-right: 0px; }
.cm-s-3024-day .CodeMirror-guttermarker { color: #db2d20; }
.cm-s-3024-day .CodeMirror-guttermarker-subtle { color: #807d7c; }
.cm-s-3024-day .CodeMirror-linenumber { color: #807d7c; }
.cm-s-3024-day .CodeMirror-cursor { border-left: 1px solid #5c5855; }
.cm-s-3024-day span.cm-comment { color: #cdab53; }
.cm-s-3024-day span.cm-atom { color: #a16a94; }
.cm-s-3024-day span.cm-number { color: #a16a94; }
.cm-s-3024-day span.cm-property, .cm-s-3024-day span.cm-attribute { color: #01a252; }
.cm-s-3024-day span.cm-keyword { color: #db2d20; }
.cm-s-3024-day span.cm-string { color: #fded02; }
.cm-s-3024-day span.cm-variable { color: #01a252; }
.cm-s-3024-day span.cm-variable-2 { color: #01a0e4; }
.cm-s-3024-day span.cm-def { color: #e8bbd0; }
.cm-s-3024-day span.cm-bracket { color: #3a3432; }
.cm-s-3024-day span.cm-tag { color: #db2d20; }
.cm-s-3024-day span.cm-link { color: #a16a94; }
.cm-s-3024-day span.cm-error { background: #db2d20; color: #5c5855; }
.cm-s-3024-day .CodeMirror-activeline-background { background: #e8f2ff; }
.cm-s-3024-day .CodeMirror-matchingbracket { text-decoration: underline; color: #a16a94 !important; }
|
281677160/openwrt-package
| 6,577 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_eval.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp_eval.h"
#define NGX_RTMP_EVAL_BUFLEN 16
static void
ngx_rtmp_eval_session_str(void *ctx, ngx_rtmp_eval_t *e, ngx_str_t *ret)
{
*ret = *(ngx_str_t *) ((u_char *) ctx + e->offset);
}
static void
ngx_rtmp_eval_connection_str(void *ctx, ngx_rtmp_eval_t *e, ngx_str_t *ret)
{
ngx_rtmp_session_t *s = ctx;
*ret = *(ngx_str_t *) ((u_char *) s->connection + e->offset);
}
ngx_rtmp_eval_t ngx_rtmp_eval_session[] = {
{ ngx_string("app"),
ngx_rtmp_eval_session_str,
offsetof(ngx_rtmp_session_t, app) },
{ ngx_string("flashver"),
ngx_rtmp_eval_session_str,
offsetof(ngx_rtmp_session_t, flashver) },
{ ngx_string("swfurl"),
ngx_rtmp_eval_session_str,
offsetof(ngx_rtmp_session_t, swf_url) },
{ ngx_string("tcurl"),
ngx_rtmp_eval_session_str,
offsetof(ngx_rtmp_session_t, tc_url) },
{ ngx_string("pageurl"),
ngx_rtmp_eval_session_str,
offsetof(ngx_rtmp_session_t, page_url) },
{ ngx_string("addr"),
ngx_rtmp_eval_connection_str,
offsetof(ngx_connection_t, addr_text) },
ngx_rtmp_null_eval
};
static void
ngx_rtmp_eval_append(ngx_buf_t *b, void *data, size_t len, ngx_log_t *log)
{
size_t buf_len;
if (b->last + len > b->end) {
buf_len = 2 * (b->last - b->pos) + len;
b->start = ngx_alloc(buf_len, log);
if (b->start == NULL) {
return;
}
b->last = ngx_cpymem(b->start, b->pos, b->last - b->pos);
b->pos = b->start;
b->end = b->start + buf_len;
}
b->last = ngx_cpymem(b->last, data, len);
}
static void
ngx_rtmp_eval_append_var(void *ctx, ngx_buf_t *b, ngx_rtmp_eval_t **e,
ngx_str_t *name, ngx_log_t *log)
{
ngx_uint_t k;
ngx_str_t v;
ngx_rtmp_eval_t *ee;
for (; *e; ++e) {
for (k = 0, ee = *e; ee->handler; ++k, ++ee) {
if (ee->name.len == name->len &&
ngx_memcmp(ee->name.data, name->data, name->len) == 0)
{
ee->handler(ctx, ee, &v);
ngx_rtmp_eval_append(b, v.data, v.len, log);
}
}
}
}
ngx_int_t
ngx_rtmp_eval(void *ctx, ngx_str_t *in, ngx_rtmp_eval_t **e, ngx_str_t *out,
ngx_log_t *log)
{
u_char c, *p;
ngx_str_t name;
ngx_buf_t b;
ngx_uint_t n;
enum {
NORMAL,
ESCAPE,
NAME,
SNAME
} state = NORMAL;
b.pos = b.last = b.start = ngx_alloc(NGX_RTMP_EVAL_BUFLEN, log);
if (b.pos == NULL) {
return NGX_ERROR;
}
b.end = b.pos + NGX_RTMP_EVAL_BUFLEN;
name.data = NULL;
for (n = 0; n < in->len; ++n) {
p = &in->data[n];
c = *p;
switch (state) {
case SNAME:
if (c != '}') {
continue;
}
name.len = p - name.data;
ngx_rtmp_eval_append_var(ctx, &b, e, &name, log);
state = NORMAL;
continue;
case NAME:
if (c == '{' && name.data == p) {
++name.data;
state = SNAME;
continue;
}
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
continue;
}
name.len = p - name.data;
ngx_rtmp_eval_append_var(ctx, &b, e, &name, log);
switch (c) {
case '$':
name.data = p + 1;
state = NAME;
continue;
case '\\':
state = ESCAPE;
continue;
}
ngx_rtmp_eval_append(&b, &c, 1, log);
state = NORMAL;
break;
case NORMAL:
switch (c) {
case '$':
name.data = p + 1;
state = NAME;
continue;
case '\\':
state = ESCAPE;
continue;
}
ngx_rtmp_eval_append(&b, &c, 1, log);
state = NORMAL;
break;
case ESCAPE:
ngx_rtmp_eval_append(&b, &c, 1, log);
state = NORMAL;
break;
}
}
if (state == NAME) {
p = &in->data[n];
name.len = p - name.data;
ngx_rtmp_eval_append_var(ctx, &b, e, &name, log);
}
c = 0;
ngx_rtmp_eval_append(&b, &c, 1, log);
out->data = b.pos;
out->len = b.last - b.pos - 1;
return NGX_OK;
}
ngx_int_t
ngx_rtmp_eval_streams(ngx_str_t *in)
{
#if !(NGX_WIN32)
ngx_int_t mode, create, v, close_src;
ngx_fd_t dst, src;
u_char *path;
path = in->data;
while (*path >= '0' && *path <= '9') {
path++;
}
switch ((char) *path) {
case '>':
v = (path == in->data ? 1 : ngx_atoi(in->data, path - in->data));
if (v == NGX_ERROR) {
return NGX_ERROR;
}
dst = (ngx_fd_t) v;
mode = NGX_FILE_WRONLY;
create = NGX_FILE_TRUNCATE;
path++;
if (*path == (u_char) '>') {
mode = NGX_FILE_APPEND;
create = NGX_FILE_CREATE_OR_OPEN;
path++;
}
break;
case '<':
v = (path == in->data ? 0 : ngx_atoi(in->data, path - in->data));
if (v == NGX_ERROR) {
return NGX_ERROR;
}
dst = (ngx_fd_t) v;
mode = NGX_FILE_RDONLY;
create = NGX_FILE_OPEN;
path++;
break;
default:
return NGX_DONE;
}
if (*path == (u_char) '&') {
path++;
v = ngx_atoi(path, in->data + in->len - path);
if (v == NGX_ERROR) {
return NGX_ERROR;
}
src = (ngx_fd_t) v;
close_src = 0;
} else {
src = ngx_open_file(path, mode, create, NGX_FILE_DEFAULT_ACCESS);
if (src == NGX_INVALID_FILE) {
return NGX_ERROR;
}
close_src = 1;
}
if (src == dst) {
return NGX_OK;
}
dup2(src, dst);
if (close_src) {
ngx_close_file(src);
}
return NGX_OK;
#else
return NGX_DONE;
#endif
}
|
281677160/openwrt-package
| 10,974 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_live_relay.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_live_relay.h"
#include "ngx_rtmp_cmd_module.h"
#include "ngx_toolkit_misc.h"
static ngx_rtmp_publish_pt next_publish;
static ngx_rtmp_play_pt next_play;
static ngx_rtmp_close_stream_pt next_close_stream;
static ngx_int_t ngx_live_relay_postconfiguration(ngx_conf_t *cf);
static void *ngx_live_relay_create_app_conf(ngx_conf_t *cf);
static char *ngx_live_relay_merge_app_conf(ngx_conf_t *cf, void *parent,
void *child);
ngx_live_push_pt ngx_live_push;
ngx_live_pull_pt ngx_live_pull;
ngx_live_push_close_pt ngx_live_push_close;
ngx_live_pull_close_pt ngx_live_pull_close;
typedef ngx_int_t (* relay_create_pt)(ngx_rtmp_session_t *rs,
ngx_live_relay_t *relay,
ngx_live_relay_url_t *url);
static relay_create_pt create_relay[] = {
ngx_live_relay_create_httpflv,
ngx_live_relay_create_rtmp
};
static const char *relay_protocol[] = {
"httpflv",
"rtmp"
};
static const char *relay_type[] = {
"push",
"pull"
};
static ngx_command_t ngx_live_relay_commands[] = {
{ ngx_string("failed_reconnect"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_live_relay_app_conf_t, failed_reconnect),
NULL },
{ ngx_string("relay_reconnect"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_live_relay_app_conf_t, relay_reconnect),
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_live_relay_module_ctx = {
NULL, /* preconfiguration */
ngx_live_relay_postconfiguration, /* postconfiguration */
NULL, /* create main configuration */
NULL, /* init main configuration */
NULL, /* create server configuration */
NULL, /* merge server configuration */
ngx_live_relay_create_app_conf, /* create app configuration */
ngx_live_relay_merge_app_conf /* merge app configuration */
};
ngx_module_t ngx_live_relay_module = {
NGX_MODULE_V1,
&ngx_live_relay_module_ctx, /* module context */
ngx_live_relay_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
NGX_MODULE_V1_PADDING
};
static void *
ngx_live_relay_create_app_conf(ngx_conf_t *cf)
{
ngx_live_relay_app_conf_t *racf;
racf = ngx_pcalloc(cf->pool, sizeof(ngx_live_relay_app_conf_t));
if (racf == NULL) {
return NULL;
}
racf->failed_reconnect = NGX_CONF_UNSET_MSEC;
racf->relay_reconnect = NGX_CONF_UNSET_MSEC;
return racf;
}
static char *
ngx_live_relay_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_live_relay_app_conf_t *prev = parent;
ngx_live_relay_app_conf_t *conf = child;
ngx_conf_merge_msec_value(conf->failed_reconnect, prev->failed_reconnect,
50);
ngx_conf_merge_msec_value(conf->relay_reconnect, prev->relay_reconnect,
3000);
return NGX_CONF_OK;
}
ngx_int_t
ngx_live_relay_create(ngx_rtmp_session_t *rs, ngx_live_relay_t *relay)
{
ngx_live_relay_ctx_t *ctx;
ngx_live_relay_url_t *url;
relay_create_pt create;
ctx = ngx_rtmp_get_module_ctx(rs, ngx_live_relay_module);
if (ctx->idx >= relay->urls.nelts) {
ctx->idx = 0;
}
ctx->failed_delay = 0;
url = relay->urls.elts;
url += ctx->idx;
if (url->relay_type >= NGX_LIVE_RELAY_MAXTYPE) {
ngx_log_error(NGX_LOG_ERR, rs->log, 0, "unsupported relay type %ui",
url->relay_type);
return NGX_ERROR;
}
create = create_relay[url->relay_type];
ngx_log_error(NGX_LOG_INFO, rs->log, 0,
"create %s relay %s to %V:%d, domain='%V' app='%V' name='%V' "
"pargs='%V' referer='%V' user_agent='%V'",
relay_protocol[url->relay_type], relay_type[rs->publishing],
&url->url.host, url->port, &relay->domain, &relay->app,
&relay->name, &relay->pargs, &relay->referer, &relay->user_agent);
++ctx->idx;
return create(rs, relay, url);
}
ngx_int_t
ngx_live_relay_play_local(ngx_rtmp_session_t *rs)
{
ngx_rtmp_play_t v;
ngx_memzero(&v, sizeof(ngx_rtmp_play_t));
v.silent = 1;
*(ngx_cpymem(v.name, rs->name.data, ngx_min(sizeof(v.name) - 1,
rs->name.len))) = 0;
if (rs->pargs.len) {
*(ngx_cpymem(v.args, rs->pargs.data, ngx_min(sizeof(v.args) - 1,
rs->pargs.len))) = 0;
}
return ngx_rtmp_play_filter(rs, &v);
}
ngx_int_t
ngx_live_relay_publish_local(ngx_rtmp_session_t *rs)
{
ngx_rtmp_publish_t v;
ngx_memzero(&v, sizeof(ngx_rtmp_publish_t));
v.silent = 1;
*(ngx_cpymem(v.name, rs->name.data, ngx_min(sizeof(v.name) - 1,
rs->name.len))) = 0;
if (rs->pargs.len) {
*(ngx_cpymem(v.args, rs->pargs.data, ngx_min(sizeof(v.args) - 1,
rs->pargs.len))) = 0;
}
return ngx_rtmp_publish_filter(rs, &v);
}
static ngx_int_t
ngx_live_relay_publish(ngx_rtmp_session_t *s, ngx_rtmp_publish_t *v)
{
ngx_live_relay_ctx_t *ctx;
// second publish will not trigger push
if (s->live_stream->publish_ctx->next != NULL) {
goto next;
}
if (ngx_live_push(s) != NGX_OK) {
return NGX_ERROR;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
goto next;
}
if (ctx->reconnect.timer_set) {
ngx_del_timer(&ctx->reconnect);
}
if (ctx->reconnect.posted) {
ngx_delete_posted_event(&ctx->reconnect);
}
ctx->successd = 1;
ctx->failed_reconnect = 0;
ctx->idx = 0;
next:
return next_publish(s, v);
}
static ngx_int_t
ngx_live_relay_play(ngx_rtmp_session_t *s, ngx_rtmp_play_t *v)
{
ngx_live_relay_ctx_t *ctx;
if (ngx_live_pull(s) != NGX_OK) {
return NGX_ERROR;
}
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx == NULL) {
goto next;
}
if (ctx->reconnect.timer_set) {
ngx_del_timer(&ctx->reconnect);
}
if (ctx->reconnect.posted) {
ngx_delete_posted_event(&ctx->reconnect);
}
ctx->successd = 1;
ctx->failed_reconnect = 0;
ctx->idx = 0;
next:
return next_play(s, v);
}
static ngx_int_t
ngx_live_relay_close_stream(ngx_rtmp_session_t *s, ngx_rtmp_close_stream_t *v)
{
ngx_rtmp_core_ctx_t *ctx;
ngx_live_relay_ctx_t *rctx;
if (s->live_stream == NULL) {
goto next;
}
if (s->publishing) {
/*
* normal publisher close or relay puller close
* need to trigger ngx_live_pull_close
*/
ngx_live_pull_close(s);
// all publishers close, close push (play + relay)
if (s->live_stream->publish_ctx == NULL) {
for (ctx = s->live_stream->play_ctx; ctx; ctx = ctx->next) {
if (ctx->session->relay) {
ctx->session->finalize_reason = NGX_LIVE_RELAY_CLOSE;
ngx_rtmp_finalize_session(ctx->session);
}
}
}
} else {
rctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (rctx) {
// push close will trigger relay push reconnect in relay modules
ngx_live_push_close(s);
}
// all players close, close pull (publish + relay)
if (s->live_stream->play_ctx == NULL) {
for (ctx = s->live_stream->publish_ctx; ctx; ctx = ctx->next) {
if (ctx->session->relay) {
ctx->session->finalize_reason = NGX_LIVE_RELAY_CLOSE;
ngx_rtmp_finalize_session(ctx->session);
}
}
}
}
next:
return next_close_stream(s, v);
}
static ngx_int_t
ngx_live_relay_push(ngx_rtmp_session_t *s)
{
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_pull(ngx_rtmp_session_t *s)
{
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_push_close(ngx_rtmp_session_t *s)
{
ngx_live_relay_ctx_t *ctx;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
if (ctx && ctx->reconnect.timer_set) {
ngx_del_timer(&ctx->reconnect);
}
if (ctx && ctx->reconnect.posted) {
ngx_delete_posted_event(&ctx->reconnect);
}
return NGX_OK;
}
/*
* pull reconnect need to trigger ngx_live_pull chain
*/
static ngx_int_t
ngx_live_relay_pull_close(ngx_rtmp_session_t *s)
{
ngx_live_relay_ctx_t *ctx;
ngx_flag_t has_player;
ngx_rtmp_core_ctx_t *cctx;;
ctx = ngx_rtmp_get_module_ctx(s, ngx_live_relay_module);
has_player = 0;
if (s->static_pull == 0) {
for (cctx = s->live_stream->play_ctx; cctx; cctx = cctx->next) {
if (cctx->session->relay == 0) { // has pure player, not relay push
has_player = 1;
break;
}
}
}
if (has_player || s->static_pull) { // has player in stream
// ctx is NULL, s is a normal publisher
// ctx is not NULL, s is a puller, if giveup flag set
// no need to create pull reconnect
if (ctx == NULL || !ctx->giveup) {
ngx_live_pull(s);
}
}
if (ctx && ctx->reconnect.timer_set) {
ngx_del_timer(&ctx->reconnect);
}
if (ctx && ctx->reconnect.posted) {
ngx_delete_posted_event(&ctx->reconnect);
}
return NGX_OK;
}
static ngx_int_t
ngx_live_relay_postconfiguration(ngx_conf_t *cf)
{
next_publish = ngx_rtmp_publish;
ngx_rtmp_publish = ngx_live_relay_publish;
next_play = ngx_rtmp_play;
ngx_rtmp_play = ngx_live_relay_play;
next_close_stream = ngx_rtmp_close_stream;
ngx_rtmp_close_stream = ngx_live_relay_close_stream;
ngx_live_pull = ngx_live_relay_pull;
ngx_live_push = ngx_live_relay_push;
ngx_live_pull_close = ngx_live_relay_pull_close;
ngx_live_push_close = ngx_live_relay_push_close;
return NGX_OK;
}
|
2881099/FreeSql.AdminLTE
| 2,001 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/zenburn.css
|
/**
* "
* Using Zenburn color palette from the Emacs Zenburn Theme
* https://github.com/bbatsov/zenburn-emacs/blob/master/zenburn-theme.el
*
* Also using parts of https://github.com/xavi/coderay-lighttable-theme
* "
* From: https://github.com/wisenomad/zenburn-lighttable-theme/blob/master/zenburn.css
*/
.cm-s-zenburn .CodeMirror-gutters { background: #3f3f3f !important; }
.cm-s-zenburn .CodeMirror-foldgutter-open, .CodeMirror-foldgutter-folded { color: #999; }
.cm-s-zenburn .CodeMirror-cursor { border-left: 1px solid white; }
.cm-s-zenburn.CodeMirror { background-color: #3f3f3f; color: #dcdccc; }
.cm-s-zenburn span.cm-builtin { color: #dcdccc; font-weight: bold; }
.cm-s-zenburn span.cm-comment { color: #7f9f7f; }
.cm-s-zenburn span.cm-keyword { color: #f0dfaf; font-weight: bold; }
.cm-s-zenburn span.cm-atom { color: #bfebbf; }
.cm-s-zenburn span.cm-def { color: #dcdccc; }
.cm-s-zenburn span.cm-variable { color: #dfaf8f; }
.cm-s-zenburn span.cm-variable-2 { color: #dcdccc; }
.cm-s-zenburn span.cm-string { color: #cc9393; }
.cm-s-zenburn span.cm-string-2 { color: #cc9393; }
.cm-s-zenburn span.cm-number { color: #dcdccc; }
.cm-s-zenburn span.cm-tag { color: #93e0e3; }
.cm-s-zenburn span.cm-property { color: #dfaf8f; }
.cm-s-zenburn span.cm-attribute { color: #dfaf8f; }
.cm-s-zenburn span.cm-qualifier { color: #7cb8bb; }
.cm-s-zenburn span.cm-meta { color: #f0dfaf; }
.cm-s-zenburn span.cm-header { color: #f0efd0; }
.cm-s-zenburn span.cm-operator { color: #f0efd0; }
.cm-s-zenburn span.CodeMirror-matchingbracket { box-sizing: border-box; background: transparent; border-bottom: 1px solid; }
.cm-s-zenburn span.CodeMirror-nonmatchingbracket { border-bottom: 1px solid; background: none; }
.cm-s-zenburn .CodeMirror-activeline { background: #000000; }
.cm-s-zenburn .CodeMirror-activeline-background { background: #000000; }
.cm-s-zenburn div.CodeMirror-selected { background: #545454; }
.cm-s-zenburn .CodeMirror-focused div.CodeMirror-selected { background: #4f4f4f; }
|
294coder/Efficient-MIF
| 1,998 |
utils/loss_landscape/script/1d_loss_curve_resnet56.sh
|
# ===========================================================
# 1d normalized surface for ResNet-56
# ===========================================================
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=4096_wd=0.0_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=4096_wd=0.0005_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=4096_wd=0.0_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
mpirun -n 4 python plot_surface.py --x=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=4096_wd=0.0005_save_epoch=1/model_300.t7 \
--cuda --mpi --dir_type states --xnorm filter --xignore biasbn
|
281677160/openwrt-package
| 33,393 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_core_module.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include <ngx_event.h>
#include <nginx.h>
#include "ngx_rtmp.h"
#include "ngx_dynamic_conf.h"
#include "ngx_rtmp_dynamic.h"
#include "ngx_rtmp_variables.h"
static ngx_int_t ngx_rtmp_core_preconfiguration(ngx_conf_t *cf);
static void *ngx_rtmp_core_create_main_conf(ngx_conf_t *cf);
static char *ngx_rtmp_core_init_main_conf(ngx_conf_t *cf, void *conf);
static void *ngx_rtmp_core_create_srv_conf(ngx_conf_t *cf);
static char *ngx_rtmp_core_merge_srv_conf(ngx_conf_t *cf, void *parent,
void *child);
static void *ngx_rtmp_core_create_app_conf(ngx_conf_t *cf);
static char *ngx_rtmp_core_merge_app_conf(ngx_conf_t *cf, void *parent,
void *child);
static char *ngx_rtmp_core_server(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char *ngx_rtmp_core_listen(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char *ngx_rtmp_core_server_name(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static char *ngx_rtmp_core_application(ngx_conf_t *cf, ngx_command_t *cmd,
void *conf);
static void *ngx_rtmp_core_create_srv_dconf(ngx_conf_t *cf);
static char *ngx_rtmp_core_init_srv_dconf(ngx_conf_t *cf, void *conf);
static char *ngx_rtmp_merge_frame(ngx_conf_t *cf, void *post, void *data);
static ngx_conf_post_handler_pt ngx_rtmp_merge_frame_p =
ngx_rtmp_merge_frame;
ngx_rtmp_core_main_conf_t *ngx_rtmp_core_main_conf;
static ngx_conf_deprecated_t ngx_conf_deprecated_so_keepalive = {
ngx_conf_deprecated, "so_keepalive",
"so_keepalive\" parameter of the \"listen"
};
static ngx_command_t ngx_rtmp_core_commands[] = {
{ ngx_string("server_names_hash_max_size"),
NGX_RTMP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_MAIN_CONF_OFFSET,
offsetof(ngx_rtmp_core_main_conf_t, server_names_hash_max_size),
NULL },
{ ngx_string("server_names_hash_bucket_size"),
NGX_RTMP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_MAIN_CONF_OFFSET,
offsetof(ngx_rtmp_core_main_conf_t, server_names_hash_bucket_size),
NULL },
{ ngx_string("fast_reload"),
NGX_RTMP_MAIN_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_MAIN_CONF_OFFSET,
offsetof(ngx_rtmp_core_main_conf_t, fast_reload),
NULL },
{ ngx_string("server"),
NGX_RTMP_MAIN_CONF|NGX_CONF_BLOCK|NGX_CONF_NOARGS,
ngx_rtmp_core_server,
0,
0,
NULL },
{ ngx_string("listen"),
NGX_RTMP_SRV_CONF|NGX_CONF_TAKE12,
ngx_rtmp_core_listen,
NGX_RTMP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("server_name"),
NGX_RTMP_SRV_CONF|NGX_CONF_1MORE,
ngx_rtmp_core_server_name,
NGX_RTMP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("application"),
NGX_RTMP_SRV_CONF|NGX_CONF_BLOCK|NGX_CONF_TAKE1,
ngx_rtmp_core_application,
NGX_RTMP_SRV_CONF_OFFSET,
0,
NULL },
{ ngx_string("so_keepalive"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, so_keepalive),
&ngx_conf_deprecated_so_keepalive },
{ ngx_string("timeout"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, timeout),
NULL },
{ ngx_string("ping"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, ping),
NULL },
{ ngx_string("ping_timeout"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, ping_timeout),
NULL },
{ ngx_string("max_streams"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, max_streams),
NULL },
{ ngx_string("ack_window"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, ack_window),
NULL },
{ ngx_string("chunk_size"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, chunk_size),
NULL },
{ ngx_string("max_message"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, max_message),
NULL },
{ ngx_string("out_queue"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, out_queue),
NULL },
{ ngx_string("merge_frame"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_core_app_conf_t, merge_frame),
&ngx_rtmp_merge_frame_p },
{ ngx_string("tcp_nodelay"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_FLAG,
ngx_conf_set_flag_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_core_app_conf_t, tcp_nodelay),
NULL },
{ ngx_string("out_cork"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_size_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, out_cork),
NULL },
{ ngx_string("busy"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, busy),
NULL },
/* time fixes are needed for flash clients */
{ ngx_string("play_time_fix"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, play_time_fix),
NULL },
{ ngx_string("publish_time_fix"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_flag_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, publish_time_fix),
NULL },
{ ngx_string("buflen"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_msec_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, buflen),
NULL },
{ ngx_string("serverid"),
NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_conf_t, serverid),
NULL },
{ ngx_string("hevc_codecid"),
NGX_RTMP_MAIN_CONF|NGX_RTMP_SRV_CONF|NGX_RTMP_APP_CONF|NGX_CONF_TAKE1,
ngx_conf_set_num_slot,
NGX_RTMP_APP_CONF_OFFSET,
offsetof(ngx_rtmp_core_app_conf_t, hevc_codec),
NULL },
ngx_null_command
};
static ngx_rtmp_module_t ngx_rtmp_core_module_ctx = {
ngx_rtmp_core_preconfiguration, /* preconfiguration */
NULL, /* postconfiguration */
ngx_rtmp_core_create_main_conf, /* create main configuration */
ngx_rtmp_core_init_main_conf, /* init main configuration */
ngx_rtmp_core_create_srv_conf, /* create server configuration */
ngx_rtmp_core_merge_srv_conf, /* merge server configuration */
ngx_rtmp_core_create_app_conf, /* create app configuration */
ngx_rtmp_core_merge_app_conf /* merge app configuration */
};
/* nginx rtmp dynamic */
static ngx_command_t ngx_rtmp_core_dcommands[] = {
{ ngx_string("serverid"),
NGX_RTMP_SRV_CONF|NGX_CONF_TAKE1,
ngx_conf_set_str_slot,
NGX_RTMP_SRV_CONF_OFFSET,
offsetof(ngx_rtmp_core_srv_dconf_t, serverid),
NULL },
ngx_null_command
};
static ngx_rtmp_dynamic_module_t ngx_rtmp_core_module_dctx = {
NULL, /* create main configuration */
NULL, /* init main configuration */
ngx_rtmp_core_create_srv_dconf, /* create server configuration */
ngx_rtmp_core_init_srv_dconf, /* merge server configuration */
NULL, /* create app configuration */
NULL /* merge app configuration */
};
ngx_module_t ngx_rtmp_core_module = {
NGX_MODULE_V1,
&ngx_rtmp_core_module_ctx, /* module context */
ngx_rtmp_core_commands, /* module directives */
NGX_RTMP_MODULE, /* module type */
NULL, /* init master */
NULL, /* init module */
NULL, /* init process */
NULL, /* init thread */
NULL, /* exit thread */
NULL, /* exit process */
NULL, /* exit master */
(uintptr_t) &ngx_rtmp_core_module_dctx, /* module dynamic context */
(uintptr_t) ngx_rtmp_core_dcommands, /* module dynamic directives */
NGX_MODULE_V1_DYNAMIC_PADDING
};
static void *
ngx_rtmp_core_create_main_conf(ngx_conf_t *cf)
{
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_core_main_conf_t));
if (cmcf == NULL) {
return NULL;
}
ngx_rtmp_core_main_conf = cmcf;
if (ngx_array_init(&cmcf->servers, cf->pool, 4,
sizeof(ngx_rtmp_core_srv_conf_t *))
!= NGX_OK)
{
return NULL;
}
cmcf->server_names_hash_max_size = NGX_CONF_UNSET_UINT;
cmcf->server_names_hash_bucket_size = NGX_CONF_UNSET_UINT;
cmcf->fast_reload = NGX_CONF_UNSET;
cmcf->variables_hash_max_size = 1024;
cmcf->variables_hash_bucket_size = 64;
return cmcf;
}
static char *
ngx_rtmp_core_init_main_conf(ngx_conf_t *cf, void *conf)
{
ngx_rtmp_core_main_conf_t *cmcf;
cmcf = conf;
ngx_conf_init_uint_value(cmcf->server_names_hash_max_size, 512);
ngx_conf_init_uint_value(cmcf->server_names_hash_bucket_size,
ngx_cacheline_size);
ngx_conf_init_value(cmcf->fast_reload, 0);
return NGX_CONF_OK;
}
static void *
ngx_rtmp_core_create_srv_conf(ngx_conf_t *cf)
{
ngx_rtmp_core_srv_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_core_srv_conf_t));
if (conf == NULL) {
return NULL;
}
if (ngx_array_init(&conf->applications, cf->pool, 4,
sizeof(ngx_rtmp_core_app_conf_t *))
!= NGX_OK)
{
return NULL;
}
if (ngx_array_init(&conf->server_names, cf->temp_pool, 4,
sizeof(ngx_rtmp_server_name_t))
!= NGX_OK)
{
return NULL;
}
conf->timeout = NGX_CONF_UNSET_MSEC;
conf->ping = NGX_CONF_UNSET_MSEC;
conf->ping_timeout = NGX_CONF_UNSET_MSEC;
conf->so_keepalive = NGX_CONF_UNSET;
conf->max_streams = NGX_CONF_UNSET;
conf->chunk_size = NGX_CONF_UNSET;
conf->ack_window = NGX_CONF_UNSET_UINT;
conf->max_message = NGX_CONF_UNSET_SIZE;
conf->out_queue = NGX_CONF_UNSET_SIZE;
conf->out_cork = NGX_CONF_UNSET_SIZE;
conf->play_time_fix = NGX_CONF_UNSET;
conf->publish_time_fix = NGX_CONF_UNSET;
conf->buflen = NGX_CONF_UNSET_MSEC;
conf->busy = NGX_CONF_UNSET;
return conf;
}
static char *
ngx_rtmp_core_merge_srv_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_core_srv_conf_t *prev = parent;
ngx_rtmp_core_srv_conf_t *conf = child;
ngx_str_t name;
ngx_rtmp_server_name_t *sn;
ngx_conf_merge_msec_value(conf->timeout, prev->timeout, 60000);
ngx_conf_merge_msec_value(conf->ping, prev->ping, 60000);
ngx_conf_merge_msec_value(conf->ping_timeout, prev->ping_timeout, 30000);
ngx_conf_merge_value(conf->so_keepalive, prev->so_keepalive, 0);
ngx_conf_merge_value(conf->max_streams, prev->max_streams, 32);
ngx_conf_merge_value(conf->chunk_size, prev->chunk_size, 4096);
ngx_conf_merge_uint_value(conf->ack_window, prev->ack_window, 5000000);
ngx_conf_merge_size_value(conf->max_message, prev->max_message,
1 * 1024 * 1024);
ngx_conf_merge_size_value(conf->out_queue, prev->out_queue, 2048);
ngx_conf_merge_size_value(conf->out_cork, prev->out_cork,
conf->out_queue / 8);
ngx_conf_merge_value(conf->play_time_fix, prev->play_time_fix, 1);
ngx_conf_merge_value(conf->publish_time_fix, prev->publish_time_fix, 1);
ngx_conf_merge_msec_value(conf->buflen, prev->buflen, 1000);
ngx_conf_merge_value(conf->busy, prev->busy, 0);
ngx_conf_merge_str_value(conf->serverid, prev->serverid, "default");
if (prev->pool == NULL) {
prev->pool = ngx_create_pool(4096, &cf->cycle->new_log);
if (prev->pool == NULL) {
return NGX_CONF_ERROR;
}
}
conf->pool = prev->pool;
if (conf->server_names.nelts == 0) {
sn = ngx_array_push(&conf->server_names);
#if (NGX_PCRE)
sn->regex = NULL;
#endif
sn->server = conf;
ngx_str_set(&sn->name, "");
}
sn = conf->server_names.elts;
name = sn[0].name;
#if (NGX_PCRE)
if (sn->regex) {
name.len++;
name.data--;
} else
#endif
if (name.data[0] == '.') {
name.len--;
name.data++;
}
conf->server_name.len = name.len;
conf->server_name.data = ngx_pstrdup(cf->pool, &name);
if (conf->server_name.data == NULL) {
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static void *
ngx_rtmp_core_create_app_conf(ngx_conf_t *cf)
{
ngx_rtmp_core_app_conf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_core_app_conf_t));
if (conf == NULL) {
return NULL;
}
if (ngx_array_init(&conf->applications, cf->pool, 1,
sizeof(ngx_rtmp_core_app_conf_t *))
!= NGX_OK)
{
return NULL;
}
conf->hevc_codec = NGX_CONF_UNSET_UINT;
conf->merge_frame = NGX_CONF_UNSET_UINT;
conf->tcp_nodelay = NGX_CONF_UNSET;
return conf;
}
static char *
ngx_rtmp_core_merge_app_conf(ngx_conf_t *cf, void *parent, void *child)
{
ngx_rtmp_core_app_conf_t *prev = parent;
ngx_rtmp_core_app_conf_t *conf = child;
ngx_conf_merge_uint_value(conf->hevc_codec, prev->hevc_codec, 12);
ngx_conf_merge_uint_value(conf->merge_frame, prev->merge_frame, 32);
ngx_conf_merge_value(conf->tcp_nodelay, prev->tcp_nodelay, 1);
NGX_RTMP_HEVC_CODEC_ID = conf->hevc_codec;
return NGX_CONF_OK;
}
/* nginx rtmp dynamic */
static void *
ngx_rtmp_core_create_srv_dconf(ngx_conf_t *cf)
{
ngx_rtmp_core_srv_dconf_t *conf;
conf = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_core_srv_dconf_t));
if (conf == NULL) {
return NULL;
}
return conf;
}
static char *
ngx_rtmp_core_init_srv_dconf(ngx_conf_t *cf, void *conf)
{
return NGX_CONF_OK;
}
static char *
ngx_rtmp_merge_frame(ngx_conf_t *cf, void *post, void *data)
{
ngx_uint_t *mfp;
mfp = data;
if (*mfp > NGX_RTMP_MAX_MERGE_FRAME) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"the merge_frame must be no larger than %ui",
NGX_RTMP_MAX_MERGE_FRAME);
return NGX_CONF_ERROR;
}
return NGX_CONF_OK;
}
static char *
ngx_rtmp_core_server(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *rv;
void *mconf;
ngx_uint_t m;
ngx_conf_t pcf;
ngx_module_t **modules;
ngx_rtmp_module_t *module;
struct sockaddr_in *sin;
ngx_rtmp_conf_ctx_t *ctx, *rtmp_ctx;
ngx_rtmp_listen_opt_t lsopt;
ngx_rtmp_core_srv_conf_t *cscf, **cscfp;
ngx_rtmp_core_main_conf_t *cmcf;
ctx = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_conf_ctx_t));
if (ctx == NULL) {
return NGX_CONF_ERROR;
}
rtmp_ctx = cf->ctx;
ctx->main_conf = rtmp_ctx->main_conf;
/* the server{}'s srv_conf */
ctx->srv_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->srv_conf == NULL) {
return NGX_CONF_ERROR;
}
ctx->app_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->app_conf == NULL) {
return NGX_CONF_ERROR;
}
#if (nginx_version >= 1009011)
modules = cf->cycle->modules;
#else
modules = ngx_modules;
#endif
for (m = 0; modules[m]; m++) {
if (modules[m]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[m]->ctx;
if (module->create_srv_conf) {
mconf = module->create_srv_conf(cf);
if (mconf == NULL) {
return NGX_CONF_ERROR;
}
ctx->srv_conf[modules[m]->ctx_index] = mconf;
}
if (module->create_app_conf) {
mconf = module->create_app_conf(cf);
if (mconf == NULL) {
return NGX_CONF_ERROR;
}
ctx->app_conf[modules[m]->ctx_index] = mconf;
}
}
/* the server configuration context */
cscf = ctx->srv_conf[ngx_rtmp_core_module.ctx_index];
cscf->ctx = ctx;
cmcf = ctx->main_conf[ngx_rtmp_core_module.ctx_index];
cscfp = ngx_array_push(&cmcf->servers);
if (cscfp == NULL) {
return NGX_CONF_ERROR;
}
*cscfp = cscf;
/* parse inside server{} */
pcf = *cf;
cf->ctx = ctx;
cf->cmd_type = NGX_RTMP_SRV_CONF;
rv = ngx_conf_parse(cf, NULL);
*cf = pcf;
if (rv == NGX_CONF_OK && !cscf->listen) {
/* if listen not configured, set 1935 as default */
ngx_memzero(&lsopt, sizeof(ngx_rtmp_listen_opt_t));
lsopt.sockaddr = ngx_pcalloc(cf->pool, NGX_SOCKADDR_STRLEN);
if (lsopt.sockaddr == NULL) {
return NGX_CONF_ERROR;
}
sin = (struct sockaddr_in *) lsopt.sockaddr;
sin->sin_family = AF_INET;
sin->sin_port = htons(1935);
sin->sin_addr.s_addr = INADDR_ANY;
lsopt.socklen = sizeof(struct sockaddr_in);
lsopt.wildcard = 1;
(void) ngx_sock_ntop(lsopt.sockaddr, lsopt.socklen, lsopt.addr,
NGX_SOCKADDR_STRLEN, 1);
if (ngx_rtmp_add_listen(cf, cscf, &lsopt) != NGX_OK) {
return NGX_CONF_ERROR;
}
}
return rv;
}
static char *
ngx_rtmp_core_application(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
char *rv;
ngx_int_t i;
ngx_str_t *value;
ngx_conf_t save;
ngx_module_t **modules;
ngx_rtmp_module_t *module;
ngx_rtmp_conf_ctx_t *ctx, *pctx;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_rtmp_core_app_conf_t *cacf, **cacfp;
ctx = ngx_pcalloc(cf->pool, sizeof(ngx_rtmp_conf_ctx_t));
if (ctx == NULL) {
return NGX_CONF_ERROR;
}
pctx = cf->ctx;
ctx->main_conf = pctx->main_conf;
ctx->srv_conf = pctx->srv_conf;
ctx->app_conf = ngx_pcalloc(cf->pool, sizeof(void *) * ngx_rtmp_max_module);
if (ctx->app_conf == NULL) {
return NGX_CONF_ERROR;
}
#if (nginx_version >= 1009011)
modules = cf->cycle->modules;
#else
modules = ngx_modules;
#endif
for (i = 0; modules[i]; i++) {
if (modules[i]->type != NGX_RTMP_MODULE) {
continue;
}
module = modules[i]->ctx;
if (module->create_app_conf) {
ctx->app_conf[modules[i]->ctx_index] = module->create_app_conf(cf);
if (ctx->app_conf[modules[i]->ctx_index] == NULL) {
return NGX_CONF_ERROR;
}
}
}
cacf = ctx->app_conf[ngx_rtmp_core_module.ctx_index];
cacf->app_conf = ctx->app_conf;
value = cf->args->elts;
cacf->name = value[1];
cscf = pctx->srv_conf[ngx_rtmp_core_module.ctx_index];
if (cacf->name.len == 1 && cacf->name.data[0] == '*') { /* default_app */
cscf->default_app = cacf;
}
cacfp = ngx_array_push(&cscf->applications);
if (cacfp == NULL) {
return NGX_CONF_ERROR;
}
*cacfp = cacf;
save = *cf;
cf->ctx = ctx;
cf->cmd_type = NGX_RTMP_APP_CONF;
rv = ngx_conf_parse(cf, NULL);
*cf= save;
return rv;
}
static char *
ngx_rtmp_core_listen(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_rtmp_core_srv_conf_t *cscf = conf;
ngx_str_t *value;
ngx_url_t u;
ngx_uint_t i;
ngx_rtmp_listen_opt_t lsopt;
cscf->listen = 1;
value = cf->args->elts;
ngx_memzero(&u, sizeof(ngx_url_t));
u.url = value[1];
u.listen = 1;
u.default_port = 1935;
if (ngx_parse_url(cf->pool, &u) != NGX_OK) {
if (u.err) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"%s in \"%V\" of the \"listen\" directive",
u.err, &u.url);
}
return NGX_CONF_ERROR;
}
ngx_memzero(&lsopt, sizeof(ngx_rtmp_listen_opt_t));
lsopt.sockaddr = ngx_pcalloc(cf->pool, NGX_SOCKADDR_STRLEN);
if (lsopt.sockaddr == NULL) {
return NGX_CONF_ERROR;
}
ngx_memcpy(lsopt.sockaddr, (u_char *) &u.sockaddr, u.socklen);
lsopt.socklen = u.socklen;
lsopt.wildcard = u.wildcard;
(void) ngx_sock_ntop(lsopt.sockaddr, lsopt.socklen, lsopt.addr,
NGX_SOCKADDR_STRLEN, 1);
for (i = 2; i < cf->args->nelts; i++) {
if (ngx_strcmp(value[i].data, "default_server") == 0
|| ngx_strcmp(value[i].data, "default") == 0)
{
lsopt.default_server = 1;
continue;
}
if (ngx_strcmp(value[i].data, "bind") == 0) {
lsopt.bind = 1;
continue;
}
if (ngx_strncmp(value[i].data, "ipv6only=o", 10) == 0) {
#if (NGX_HAVE_INET6 && defined IPV6_V6ONLY)
struct sockaddr *sa;
sa = lsopt.sockaddr;
if (sa->sa_family == AF_INET6) {
if (ngx_strcmp(&value[i].data[10], "n") == 0) {
lsopt.ipv6only = 1;
} else if (ngx_strcmp(&value[i].data[10], "ff") == 0) {
lsopt.ipv6only = 0;
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"invalid ipv6only flags \"%s\"",
&value[i].data[9]);
return NGX_CONF_ERROR;
}
lsopt.bind = 1;
} else {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"ipv6only is not supported "
"on addr \"%s\", ignored", lsopt.addr);
}
continue;
#else
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"bind ipv6only is not supported "
"on this platform");
return NGX_CONF_ERROR;
#endif
}
if (ngx_strcmp(value[i].data, "reuseport") == 0) {
#if (NGX_HAVE_REUSEPORT)
lsopt.reuseport = 1;
lsopt.set = 1;
lsopt.bind = 1;
#else
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"reuseport is not supported "
"on this platform, ignored");
#endif
continue;
}
if (ngx_strncmp(value[i].data, "so_keepalive=", 13) == 0) {
if (ngx_strcmp(&value[i].data[13], "on") == 0) {
lsopt.so_keepalive = 1;
} else if (ngx_strcmp(&value[i].data[13], "off") == 0) {
lsopt.so_keepalive = 2;
} else {
#if (NGX_HAVE_KEEPALIVE_TUNABLE)
u_char *p, *end;
ngx_str_t s;
end = value[i].data + value[i].len;
s.data = value[i].data + 13;
p = ngx_strlchr(s.data, end, ':');
if (p == NULL) {
p = end;
}
if (p > s.data) {
s.len = p - s.data;
lsopt.tcp_keepidle = ngx_parse_time(&s, 1);
if (lsopt.tcp_keepidle == (time_t) NGX_ERROR) {
goto invalid_so_keepalive;
}
}
s.data = (p < end) ? (p + 1) : end;
p = ngx_strlchr(s.data, end, ':');
if (p == NULL) {
p = end;
}
if (p > s.data) {
s.len = p - s.data;
lsopt.tcp_keepintvl = ngx_parse_time(&s, 1);
if (lsopt.tcp_keepintvl == (time_t) NGX_ERROR) {
goto invalid_so_keepalive;
}
}
s.data = (p < end) ? (p + 1) : end;
if (s.data < end) {
s.len = end - s.data;
lsopt.tcp_keepcnt = ngx_atoi(s.data, s.len);
if (lsopt.tcp_keepcnt == NGX_ERROR) {
goto invalid_so_keepalive;
}
}
if (lsopt.tcp_keepidle == 0 && lsopt.tcp_keepintvl == 0
&& lsopt.tcp_keepcnt == 0)
{
goto invalid_so_keepalive;
}
lsopt.so_keepalive = 1;
#else
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"the \"so_keepalive\" parameter accepts "
"only \"on\" or \"off\" on this platform");
return NGX_CONF_ERROR;
#endif
}
lsopt.bind = 1;
continue;
#if (NGX_HAVE_KEEPALIVE_TUNABLE)
invalid_so_keepalive:
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"invalid so_keepalive value: \"%s\"",
&value[i].data[13]);
return NGX_CONF_ERROR;
#endif
}
if (ngx_strcmp(value[i].data, "proxy_protocol") == 0) {
lsopt.proxy_protocol = 1;
continue;
}
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"the invalid \"%V\" parameter", &value[i]);
return NGX_CONF_ERROR;
}
if (ngx_rtmp_add_listen(cf, cscf, &lsopt) == NGX_OK) {
return NGX_CONF_OK;
}
return NGX_CONF_ERROR;
}
static char *
ngx_rtmp_core_server_name(ngx_conf_t *cf, ngx_command_t *cmd, void *conf)
{
ngx_rtmp_core_srv_conf_t *cscf = conf;
u_char ch;
ngx_str_t *value;
ngx_uint_t i;
ngx_rtmp_server_name_t *sn;
value = cf->args->elts;
for (i = 1; i < cf->args->nelts; i++) {
ch = value[i].data[0];
if ((ch == '*' && (value[i].len < 3 || value[i].data[1] != '.'))
|| (ch == '.' && value[i].len < 2))
{
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"server name \"%V\" is invalid", &value[i]);
return NGX_CONF_ERROR;
}
if (ngx_strchr(value[i].data, '/')) {
ngx_conf_log_error(NGX_LOG_WARN, cf, 0,
"server name \"%V\" has suspicious symbols",
&value[i]);
}
sn = ngx_array_push(&cscf->server_names);
if (sn == NULL) {
return NGX_CONF_ERROR;
}
#if (NGX_PCRE)
sn->regex = NULL;
#endif
sn->server = cscf;
if (ngx_strcasecmp(value[i].data, (u_char *) "$hostname") == 0) {
sn->name = cf->cycle->hostname;
} else {
sn->name = value[i];
}
if (value[i].data[0] != '~') {
ngx_strlow(sn->name.data, sn->name.data, sn->name.len);
continue;
}
#if (NGX_PCRE)
{
u_char *p;
ngx_regex_compile_t rc;
u_char errstr[NGX_MAX_CONF_ERRSTR];
if (value[i].len == 1) {
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"empty regex in server name \"%V\"", &value[i]);
return NGX_CONF_ERROR;
}
value[i].len--;
value[i].data++;
ngx_memzero(&rc, sizeof(ngx_regex_compile_t));
rc.pattern = value[i];
rc.err.len = NGX_MAX_CONF_ERRSTR;
rc.err.data = errstr;
for (p = value[i].data; p < value[i].data + value[i].len; p++) {
if (*p >= 'A' && *p <= 'Z') {
rc.options = NGX_REGEX_CASELESS;
break;
}
}
sn->regex = ngx_rtmp_regex_compile(cf, &rc);
if (sn->regex == NULL) {
return NGX_CONF_ERROR;
}
sn->name = value[i];
cscf->captures = (rc.captures > 0);
}
#else
ngx_conf_log_error(NGX_LOG_EMERG, cf, 0,
"using regex \"%V\" "
"requires PCRE library", &value[i]);
return NGX_CONF_ERROR;
#endif
}
return NGX_CONF_OK;
}
static ngx_rtmp_addr_conf_t *
ngx_rtmp_get_addr_conf(ngx_listening_t *ls, struct sockaddr *sa, socklen_t len)
{
ngx_uint_t i;
ngx_rtmp_addr_conf_t *addr_conf;
ngx_rtmp_port_t *port;
struct sockaddr_in *sin;
ngx_rtmp_in_addr_t *addr;
#if (NGX_HAVE_INET6)
struct sockaddr_in6 *sin6;
ngx_rtmp_in6_addr_t *addr6;
#endif
port = ls->servers;
addr_conf = NULL;
if (port->naddrs > 1) {
switch (sa->sa_family) {
#if (NGX_HAVE_INET6)
case AF_INET6:
sin6 = (struct sockaddr_in6 *) sa;
addr6 = port->addrs;
/* the last address is "*" */
for (i = 0; i < port->naddrs - 1; ++i) {
if (ngx_memcmp(&addr6[i].addr6, &sin6->sin6_addr, 16) == 0) {
break;
}
}
addr_conf = &addr6[i].conf;
break;
#endif
default:
sin = (struct sockaddr_in *) sa;
addr = port->addrs;
/* the last address is "*" */
for (i = 0; i < port->naddrs - 1; ++i) {
if (addr[i].addr == sin->sin_addr.s_addr) {
break;
}
}
addr_conf = &addr[i].conf;
break;
}
} else {
switch (sa->sa_family) {
#if (NGX_HAVE_INET6)
case AF_INET6:
addr6 = port->addrs;
addr_conf = &addr6[0].conf;
break;
#endif
default:
addr = port->addrs;
addr_conf = &addr[0].conf;
break;
}
}
return addr_conf;
}
ngx_rtmp_addr_conf_t *
ngx_rtmp_find_related_addr_conf(ngx_cycle_t *cycle, ngx_str_t *addr)
{
ngx_url_t u;
ngx_listening_t *ls;
ngx_uint_t i;
ngx_memzero(&u, sizeof(ngx_url_t));
u.url = *addr;
u.listen = 1;
u.default_port = 0;
if (ngx_parse_url(cycle->pool, &u) != NGX_OK) {
if (u.err) {
ngx_log_error(NGX_LOG_EMERG, cycle->log, 0,
"Relation port err: %V", addr);
}
return NULL;
}
ls = cycle->listening.elts;
for (i = 0; i < cycle->listening.nelts; ++i, ++ls) {
if (ls->handler == ngx_rtmp_init_connection
&& ls->socklen == u.socklen
&& ngx_memcmp(ls->sockaddr, (u_char *) &u.sockaddr,
u.socklen) == 0)
{
return ngx_rtmp_get_addr_conf(ls, &u.sockaddr.sockaddr, u.socklen);
}
}
ngx_log_error(NGX_LOG_EMERG, cycle->log, 0,
"Can not find relation port: %V", addr);
return NULL;
}
ngx_int_t
ngx_rtmp_arg(ngx_rtmp_session_t *s, u_char *name, size_t len, ngx_str_t *value)
{
u_char *p, *last;
if (s->pargs.len == 0) {
return NGX_DECLINED;
}
p = s->pargs.data;
last = p + s->pargs.len;
for ( /* void */ ; p < last; p++) {
/* we need '=' after name, so drop one char from last */
p = ngx_strlcasestrn(p, last - 1, name, len - 1);
if (p == NULL) {
return NGX_DECLINED;
}
if ((p == s->pargs.data || *(p - 1) == '&') && *(p + len) == '=') {
value->data = p + len + 1;
p = ngx_strlchr(p, last, '&');
if (p == NULL) {
p = s->pargs.data + s->pargs.len;
}
value->len = p - value->data;
return NGX_OK;
}
}
return NGX_DECLINED;
}
static ngx_int_t
ngx_rtmp_core_preconfiguration(ngx_conf_t *cf)
{
return ngx_rtmp_variables_add_core_vars(cf);
}
|
294coder/Efficient-MIF
| 2,627 |
utils/loss_landscape/script/2d_contour_resnet56.sh
|
# ===========================================================
# 2d loss contours for ResNet-56
# ===========================================================
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=4096_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=4096_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=4096_wd=0.0_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
mpirun -n 4 python plot_surface.py --x=-1:1:51 --y=-1:1:51 --model resnet56 \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=4096_wd=0.0005_save_epoch=1/model_300.t7 \
--mpi --cuda --dir_type weights --xignore biasbn --xnorm filter --yignore biasbn --ynorm filter
|
2881099/FreeSql.AdminLTE
| 2,369 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/moxer.css
|
/*
Name: Moxer Theme
Author: Mattia Astorino (http://github.com/equinusocio)
Website: https://github.com/moxer-theme/moxer-code
*/
.cm-s-moxer.CodeMirror {
background-color: #090A0F;
color: #8E95B4;
line-height: 1.8;
}
.cm-s-moxer .CodeMirror-gutters {
background: #090A0F;
color: #35394B;
border: none;
}
.cm-s-moxer .CodeMirror-guttermarker,
.cm-s-moxer .CodeMirror-guttermarker-subtle,
.cm-s-moxer .CodeMirror-linenumber {
color: #35394B;
}
.cm-s-moxer .CodeMirror-cursor {
border-left: 1px solid #FFCC00;
}
.cm-s-moxer div.CodeMirror-selected {
background: rgba(128, 203, 196, 0.2);
}
.cm-s-moxer.CodeMirror-focused div.CodeMirror-selected {
background: #212431;
}
.cm-s-moxer .CodeMirror-line::selection,
.cm-s-moxer .CodeMirror-line>span::selection,
.cm-s-moxer .CodeMirror-line>span>span::selection {
background: #212431;
}
.cm-s-moxer .CodeMirror-line::-moz-selection,
.cm-s-moxer .CodeMirror-line>span::-moz-selection,
.cm-s-moxer .CodeMirror-line>span>span::-moz-selection {
background: #212431;
}
.cm-s-moxer .CodeMirror-activeline-background,
.cm-s-moxer .CodeMirror-activeline-gutter .CodeMirror-linenumber {
background: rgba(33, 36, 49, 0.5);
}
.cm-s-moxer .cm-keyword {
color: #D46C6C;
}
.cm-s-moxer .cm-operator {
color: #D46C6C;
}
.cm-s-moxer .cm-variable-2 {
color: #81C5DA;
}
.cm-s-moxer .cm-variable-3,
.cm-s-moxer .cm-type {
color: #f07178;
}
.cm-s-moxer .cm-builtin {
color: #FFCB6B;
}
.cm-s-moxer .cm-atom {
color: #A99BE2;
}
.cm-s-moxer .cm-number {
color: #7CA4C0;
}
.cm-s-moxer .cm-def {
color: #F5DFA5;
}
.cm-s-moxer .CodeMirror-line .cm-def ~ .cm-def {
color: #81C5DA;
}
.cm-s-moxer .cm-string {
color: #B2E4AE;
}
.cm-s-moxer .cm-string-2 {
color: #f07178;
}
.cm-s-moxer .cm-comment {
color: #3F445A;
}
.cm-s-moxer .cm-variable {
color: #8E95B4;
}
.cm-s-moxer .cm-tag {
color: #FF5370;
}
.cm-s-moxer .cm-meta {
color: #FFCB6B;
}
.cm-s-moxer .cm-attribute {
color: #C792EA;
}
.cm-s-moxer .cm-property {
color: #81C5DA;
}
.cm-s-moxer .cm-qualifier {
color: #DECB6B;
}
.cm-s-moxer .cm-variable-3,
.cm-s-moxer .cm-type {
color: #DECB6B;
}
.cm-s-moxer .cm-error {
color: rgba(255, 255, 255, 1.0);
background-color: #FF5370;
}
.cm-s-moxer .CodeMirror-matchingbracket {
text-decoration: underline;
color: white !important;
}
|
281677160/openwrt-package
| 17,145 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_send.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp.h"
#include "ngx_rtmp_amf.h"
#include "ngx_rtmp_streams.h"
#include "ngx_rbuf.h"
#define NGX_RTMP_USER_START(s, tp) \
ngx_chain_t *__l; \
ngx_buf_t *__b; \
ngx_rtmp_core_srv_conf_t *__cscf; \
ngx_rtmp_frame_t *__f; \
\
__cscf = ngx_rtmp_get_module_srv_conf( \
s, ngx_rtmp_core_module); \
\
__f = ngx_rtmp_shared_alloc_frame(__cscf->chunk_size, NULL, 1); \
__f->hdr.type = tp; \
__f->hdr.csid = 2; \
__l = __f->chain; \
if (__l == NULL) { \
return NULL; \
} \
__b = __l->buf;
#define NGX_RTMP_UCTL_START(s, type, utype) \
NGX_RTMP_USER_START(s, type); \
*(__b->last++) = (u_char)((utype) >> 8); \
*(__b->last++) = (u_char)(utype);
#define NGX_RTMP_USER_OUT1(v) \
*(__b->last++) = ((u_char*)&v)[0];
#define NGX_RTMP_USER_OUT4(v) \
*(__b->last++) = ((u_char*)&v)[3]; \
*(__b->last++) = ((u_char*)&v)[2]; \
*(__b->last++) = ((u_char*)&v)[1]; \
*(__b->last++) = ((u_char*)&v)[0];
#define NGX_RTMP_USER_END(s) \
return __f;
static ngx_int_t
ngx_rtmp_send_shared_packet(ngx_rtmp_session_t *s, ngx_rtmp_frame_t *frame)
{
ngx_int_t rc;
if (frame == NULL) {
return NGX_ERROR;
}
rc = ngx_rtmp_send_message(s, frame, 0);
ngx_rtmp_shared_free_frame(frame);
return rc;
}
/* Protocol control messages */
ngx_rtmp_frame_t *
ngx_rtmp_create_chunk_size(ngx_rtmp_session_t *s, uint32_t chunk_size)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"chunk_size=%uD", chunk_size);
{
NGX_RTMP_USER_START(s, NGX_RTMP_MSG_CHUNK_SIZE);
NGX_RTMP_USER_OUT4(chunk_size);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_chunk_size(ngx_rtmp_session_t *s, uint32_t chunk_size)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_chunk_size(s, chunk_size));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_abort(ngx_rtmp_session_t *s, uint32_t csid)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: abort csid=%uD", csid);
{
NGX_RTMP_USER_START(s, NGX_RTMP_MSG_CHUNK_SIZE);
NGX_RTMP_USER_OUT4(csid);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_abort(ngx_rtmp_session_t *s, uint32_t csid)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_abort(s, csid));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_ack(ngx_rtmp_session_t *s, uint32_t seq)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: ack seq=%uD", seq);
{
NGX_RTMP_USER_START(s, NGX_RTMP_MSG_ACK);
NGX_RTMP_USER_OUT4(seq);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_ack(ngx_rtmp_session_t *s, uint32_t seq)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_ack(s, seq));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_ack_size(ngx_rtmp_session_t *s, uint32_t ack_size)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: ack_size=%uD", ack_size);
{
NGX_RTMP_USER_START(s, NGX_RTMP_MSG_ACK_SIZE);
NGX_RTMP_USER_OUT4(ack_size);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_ack_size(ngx_rtmp_session_t *s, uint32_t ack_size)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_ack_size(s, ack_size));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_bandwidth(ngx_rtmp_session_t *s, uint32_t ack_size,
uint8_t limit_type)
{
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: bandwidth ack_size=%uD limit=%d",
ack_size, (int)limit_type);
{
NGX_RTMP_USER_START(s, NGX_RTMP_MSG_BANDWIDTH);
NGX_RTMP_USER_OUT4(ack_size);
NGX_RTMP_USER_OUT1(limit_type);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_bandwidth(ngx_rtmp_session_t *s, uint32_t ack_size,
uint8_t limit_type)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_bandwidth(s, ack_size, limit_type));
}
/* User control messages */
ngx_rtmp_frame_t *
ngx_rtmp_create_stream_begin(ngx_rtmp_session_t *s, uint32_t msid)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: stream_begin msid=%uD", msid);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_STREAM_BEGIN);
NGX_RTMP_USER_OUT4(msid);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_stream_begin(ngx_rtmp_session_t *s, uint32_t msid)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_stream_begin(s, msid));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_stream_eof(ngx_rtmp_session_t *s, uint32_t msid)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: stream_end msid=%uD", msid);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_STREAM_EOF);
NGX_RTMP_USER_OUT4(msid);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_stream_eof(ngx_rtmp_session_t *s, uint32_t msid)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_stream_eof(s, msid));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_stream_dry(ngx_rtmp_session_t *s, uint32_t msid)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: stream_dry msid=%uD", msid);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_STREAM_DRY);
NGX_RTMP_USER_OUT4(msid);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_stream_dry(ngx_rtmp_session_t *s, uint32_t msid)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_stream_dry(s, msid));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_set_buflen(ngx_rtmp_session_t *s, uint32_t msid,
uint32_t buflen_msec)
{
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: set_buflen msid=%uD buflen=%uD",
msid, buflen_msec);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_SET_BUFLEN);
NGX_RTMP_USER_OUT4(msid);
NGX_RTMP_USER_OUT4(buflen_msec);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_set_buflen(ngx_rtmp_session_t *s, uint32_t msid,
uint32_t buflen_msec)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_set_buflen(s, msid, buflen_msec));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_recorded(ngx_rtmp_session_t *s, uint32_t msid)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: recorded msid=%uD", msid);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_RECORDED);
NGX_RTMP_USER_OUT4(msid);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_recorded(ngx_rtmp_session_t *s, uint32_t msid)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_recorded(s, msid));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_ping_request(ngx_rtmp_session_t *s, uint32_t timestamp)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: ping_request timestamp=%uD", timestamp);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_PING_REQUEST);
NGX_RTMP_USER_OUT4(timestamp);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_ping_request(ngx_rtmp_session_t *s, uint32_t timestamp)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_ping_request(s, timestamp));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_ping_response(ngx_rtmp_session_t *s, uint32_t timestamp)
{
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: ping_response timestamp=%uD", timestamp);
{
NGX_RTMP_UCTL_START(s, NGX_RTMP_MSG_USER, NGX_RTMP_USER_PING_RESPONSE);
NGX_RTMP_USER_OUT4(timestamp);
NGX_RTMP_USER_END(s);
}
}
ngx_int_t
ngx_rtmp_send_ping_response(ngx_rtmp_session_t *s, uint32_t timestamp)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_ping_response(s, timestamp));
}
static ngx_chain_t *
ngx_rtmp_alloc_amf_buf(void *arg)
{
return ngx_get_chainbuf(((ngx_rtmp_core_srv_conf_t *)arg)->chunk_size, 1);
}
/* AMF sender */
/* NOTE: this function does not free shared bufs on error */
ngx_int_t
ngx_rtmp_append_amf(ngx_rtmp_session_t *s,
ngx_chain_t **first, ngx_chain_t **last,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
ngx_rtmp_amf_ctx_t act;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_int_t rc;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
memset(&act, 0, sizeof(act));
act.arg = cscf;
act.alloc = ngx_rtmp_alloc_amf_buf;
act.log = s->log;
if (first) {
act.first = *first;
}
if (last) {
act.link = *last;
}
rc = ngx_rtmp_amf_write(&act, elts, nelts);
if (first) {
*first = act.first;
}
if (last) {
*last = act.link;
}
return rc;
}
ngx_rtmp_frame_t *
ngx_rtmp_create_amf(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
ngx_int_t rc;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_rtmp_frame_t *frame;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: amf nelts=%ui", nelts);
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
frame = ngx_rtmp_shared_alloc_frame(cscf->chunk_size, NULL, 1);
frame->hdr = *h;
rc = ngx_rtmp_append_amf(s, &frame->chain, &frame->chain, elts, nelts);
if (rc != NGX_OK) {
ngx_rtmp_shared_free_frame(frame);
return NULL;
}
return frame;
}
ngx_int_t
ngx_rtmp_send_amf(ngx_rtmp_session_t *s, ngx_rtmp_header_t *h,
ngx_rtmp_amf_elt_t *elts, size_t nelts)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_amf(s, h, elts, nelts));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_error(ngx_rtmp_session_t *s, char *code, char* level,
char *desc)
{
ngx_rtmp_header_t h;
static double trans;
static ngx_rtmp_amf_elt_t out_inf[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("level"),
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_string("code"),
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_string("description"),
NULL, 0 },
};
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"_error", 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
out_inf,
sizeof(out_inf) },
};
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: error code='%s' level='%s' desc='%s'",
code, level, desc);
out_inf[0].data = level;
out_inf[1].data = code;
out_inf[2].data = desc;
memset(&h, 0, sizeof(h));
h.type = NGX_RTMP_MSG_AMF_CMD;
h.csid = NGX_RTMP_CSID_AMF;
h.msid = NGX_RTMP_MSID;
return ngx_rtmp_create_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0]));
}
ngx_int_t
ngx_rtmp_send_error(ngx_rtmp_session_t *s, char *code, char* level, char *desc)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_error(s, code, level, desc));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_status(ngx_rtmp_session_t *s, char *code, char* level,
char *desc)
{
ngx_rtmp_header_t h;
static double trans;
static ngx_rtmp_amf_elt_t out_inf[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("level"),
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_string("code"),
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_string("description"),
NULL, 0 },
};
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"onStatus", 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_null_string,
&trans, 0 },
{ NGX_RTMP_AMF_NULL,
ngx_null_string,
NULL, 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
out_inf,
sizeof(out_inf) },
};
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: status code='%s' level='%s' desc='%s'",
code, level, desc);
out_inf[0].data = level;
out_inf[1].data = code;
out_inf[2].data = desc;
memset(&h, 0, sizeof(h));
h.type = NGX_RTMP_MSG_AMF_CMD;
h.csid = NGX_RTMP_CSID_AMF;
h.msid = NGX_RTMP_MSID;
return ngx_rtmp_create_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0]));
}
ngx_int_t
ngx_rtmp_send_status(ngx_rtmp_session_t *s, char *code, char* level, char *desc)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_status(s, code, level, desc));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_play_status(ngx_rtmp_session_t *s, char *code, char* level,
ngx_uint_t duration, ngx_uint_t bytes)
{
ngx_rtmp_header_t h;
static double dduration;
static double dbytes;
static ngx_rtmp_amf_elt_t out_inf[] = {
{ NGX_RTMP_AMF_STRING,
ngx_string("code"),
NULL, 0 },
{ NGX_RTMP_AMF_STRING,
ngx_string("level"),
NULL, 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_string("duration"),
&dduration, 0 },
{ NGX_RTMP_AMF_NUMBER,
ngx_string("bytes"),
&dbytes, 0 },
};
static ngx_rtmp_amf_elt_t out_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"onPlayStatus", 0 },
{ NGX_RTMP_AMF_OBJECT,
ngx_null_string,
out_inf,
sizeof(out_inf) },
};
ngx_log_debug4(NGX_LOG_DEBUG_RTMP, s->log, 0,
"create: play_status code='%s' level='%s' "
"duration=%ui bytes=%ui",
code, level, duration, bytes);
out_inf[0].data = code;
out_inf[1].data = level;
dduration = duration;
dbytes = bytes;
memset(&h, 0, sizeof(h));
h.type = NGX_RTMP_MSG_AMF_META;
h.csid = NGX_RTMP_CSID_AMF;
h.msid = NGX_RTMP_MSID;
h.timestamp = duration;
return ngx_rtmp_create_amf(s, &h, out_elts,
sizeof(out_elts) / sizeof(out_elts[0]));
}
ngx_int_t
ngx_rtmp_send_play_status(ngx_rtmp_session_t *s, char *code, char* level,
ngx_uint_t duration, ngx_uint_t bytes)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_play_status(s, code, level, duration, bytes));
}
ngx_rtmp_frame_t *
ngx_rtmp_create_sample_access(ngx_rtmp_session_t *s)
{
ngx_rtmp_header_t h;
static int access = 1;
static ngx_rtmp_amf_elt_t access_elts[] = {
{ NGX_RTMP_AMF_STRING,
ngx_null_string,
"|RtmpSampleAccess", 0 },
{ NGX_RTMP_AMF_BOOLEAN,
ngx_null_string,
&access, 0 },
{ NGX_RTMP_AMF_BOOLEAN,
ngx_null_string,
&access, 0 },
};
memset(&h, 0, sizeof(h));
h.type = NGX_RTMP_MSG_AMF_META;
h.csid = NGX_RTMP_CSID_AMF;
h.msid = NGX_RTMP_MSID;
return ngx_rtmp_create_amf(s, &h, access_elts,
sizeof(access_elts) / sizeof(access_elts[0]));
}
ngx_int_t
ngx_rtmp_send_sample_access(ngx_rtmp_session_t *s)
{
return ngx_rtmp_send_shared_packet(s,
ngx_rtmp_create_sample_access(s));
}
|
294coder/Efficient-MIF
| 1,359 |
utils/loss_landscape/script/1d_linear_interpolation_vgg9.sh
|
# =============================================================================
# 1d linear interpolation for VGG-9
# =============================================================================
mpirun -n 3 python plot_surface.py --x=-0.5:1.5:401 --model vgg9 --dir_type states --mpi --cuda \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0_save_epoch=1/model_300.t7 \
mpirun -n 3 python plot_surface.py --x=-0.5:1.5:401 --model vgg9 --dir_type states --mpi --cuda \
--model_file cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/vgg9_sgd_lr=0.1_bs=8192_wd=0.0005_save_epoch=1/model_300.t7 \
mpirun -n 3 python plot_surface.py --x=-0.5:1.5:401 --model vgg9 --dir_type states --mpi --cuda \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/vgg9_adam_lr=0.001_bs=8192_wd=0.0_save_epoch=1/model_300.t7 \
mpirun -n 3 python plot_surface.py --x=-0.5:1.5:401 --model vgg9 --dir_type states --mpi --cuda \
--model_file cifar10/trained_nets/vgg9_adam_lr=0.001_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/vgg9_adam_lr=0.001_bs=8192_wd=0.0005_save_epoch=1/model_300.t7 \
|
2881099/FreeSql.AdminLTE
| 2,142 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/vibrant-ink.css
|
/* Taken from the popular Visual Studio Vibrant Ink Schema */
.cm-s-vibrant-ink.CodeMirror { background: black; color: white; }
.cm-s-vibrant-ink div.CodeMirror-selected { background: #35493c; }
.cm-s-vibrant-ink .CodeMirror-line::selection, .cm-s-vibrant-ink .CodeMirror-line > span::selection, .cm-s-vibrant-ink .CodeMirror-line > span > span::selection { background: rgba(53, 73, 60, 0.99); }
.cm-s-vibrant-ink .CodeMirror-line::-moz-selection, .cm-s-vibrant-ink .CodeMirror-line > span::-moz-selection, .cm-s-vibrant-ink .CodeMirror-line > span > span::-moz-selection { background: rgba(53, 73, 60, 0.99); }
.cm-s-vibrant-ink .CodeMirror-gutters { background: #002240; border-right: 1px solid #aaa; }
.cm-s-vibrant-ink .CodeMirror-guttermarker { color: white; }
.cm-s-vibrant-ink .CodeMirror-guttermarker-subtle { color: #d0d0d0; }
.cm-s-vibrant-ink .CodeMirror-linenumber { color: #d0d0d0; }
.cm-s-vibrant-ink .CodeMirror-cursor { border-left: 1px solid white; }
.cm-s-vibrant-ink .cm-keyword { color: #CC7832; }
.cm-s-vibrant-ink .cm-atom { color: #FC0; }
.cm-s-vibrant-ink .cm-number { color: #FFEE98; }
.cm-s-vibrant-ink .cm-def { color: #8DA6CE; }
.cm-s-vibrant-ink span.cm-variable-2, .cm-s-vibrant span.cm-tag { color: #FFC66D; }
.cm-s-vibrant-ink span.cm-variable-3, .cm-s-vibrant span.cm-def, .cm-s-vibrant span.cm-type { color: #FFC66D; }
.cm-s-vibrant-ink .cm-operator { color: #888; }
.cm-s-vibrant-ink .cm-comment { color: gray; font-weight: bold; }
.cm-s-vibrant-ink .cm-string { color: #A5C25C; }
.cm-s-vibrant-ink .cm-string-2 { color: red; }
.cm-s-vibrant-ink .cm-meta { color: #D8FA3C; }
.cm-s-vibrant-ink .cm-builtin { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-tag { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-attribute { color: #8DA6CE; }
.cm-s-vibrant-ink .cm-header { color: #FF6400; }
.cm-s-vibrant-ink .cm-hr { color: #AEAEAE; }
.cm-s-vibrant-ink .cm-link { color: #5656F3; }
.cm-s-vibrant-ink .cm-error { border-bottom: 1px solid red; }
.cm-s-vibrant-ink .CodeMirror-activeline-background { background: #27282E; }
.cm-s-vibrant-ink .CodeMirror-matchingbracket { outline:1px solid grey; color:white !important; }
|
294coder/Efficient-MIF
| 1,367 |
utils/loss_landscape/script/1d_linear_interpolation_resnet56.sh
|
# ===========================================================
# 1d linear interpolation for ResNet-56
# ===========================================================
mpirun -n 4 python plot_surface.py --cuda --mpi --x=-0.5:1.5:401 --model resnet56 --dir_type states \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=4096_wd=0.0_save_epoch=1/model_300.t7
mpirun -n 4 python plot_surface.py --cuda --mpi --x=-0.5:1.5:401 --model resnet56 --dir_type states \
--model_file cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/resnet56_sgd_lr=0.1_bs=4096_wd=0.0005_save_epoch=1/model_300.t7
mpirun -n 4 python plot_surface.py --cuda --mpi --x=-0.5:1.5:401 --model resnet56 --dir_type states \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=128_wd=0.0_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/resnet56_adam_lr=0.001_bs=4096_wd=0.0_save_epoch=1/model_300.t7
mpirun -n 4 python plot_surface.py --cuda --mpi --x=-0.5:1.5:401 --model resnet56 --dir_type states \
--model_file cifar10/trained_nets/resnet56_adam_lr=0.001_bs=128_wd=0.0005_save_epoch=1/model_300.t7 \
--model_file2 cifar10/trained_nets/resnet56_adam_lr=0.001_bs=4096_wd=0.0005_save_epoch=1/model_300.t7
|
281677160/openwrt-package
| 1,162 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_bitop.h
|
/*
* Copyright (C) Roman Arutyunyan
*/
#ifndef _NGX_RTMP_BITOP_H_INCLUDED_
#define _NGX_RTMP_BITOP_H_INCLUDED_
#include <ngx_config.h>
#include <ngx_core.h>
typedef struct {
u_char *pos;
u_char *last;
ngx_uint_t offs;
ngx_uint_t err;
} ngx_rtmp_bit_reader_t;
void ngx_rtmp_bit_init_reader(ngx_rtmp_bit_reader_t *br, u_char *pos,
u_char *last);
uint64_t ngx_rtmp_bit_read(ngx_rtmp_bit_reader_t *br, ngx_uint_t n);
uint64_t ngx_rtmp_bit_read_golomb(ngx_rtmp_bit_reader_t *br);
#define ngx_rtmp_bit_read_err(br) ((br)->err)
#define ngx_rtmp_bit_read_eof(br) ((br)->pos == (br)->last)
#define ngx_rtmp_bit_read_8(br) \
((uint8_t) ngx_rtmp_bit_read(br, 8))
#define ngx_rtmp_bit_read_16(br) \
((uint16_t) ngx_rtmp_bit_read(br, 16))
#define ngx_rtmp_bit_read_32(br) \
((uint32_t) ngx_rtmp_bit_read(br, 32))
#define ngx_rtmp_bit_read_64(br) \
((uint64_t) ngx_rtmp_read(br, 64))
#endif /* _NGX_RTMP_BITOP_H_INCLUDED_ */
|
2881099/FreeSql.AdminLTE
| 2,112 |
Examples/net80_blazor/wwwroot/AdminLTE-3.2.0/plugins/codemirror/theme/mbo.css
|
/****************************************************************/
/* Based on mbonaci's Brackets mbo theme */
/* https://github.com/mbonaci/global/blob/master/Mbo.tmTheme */
/* Create your own: http://tmtheme-editor.herokuapp.com */
/****************************************************************/
.cm-s-mbo.CodeMirror { background: #2c2c2c; color: #ffffec; }
.cm-s-mbo div.CodeMirror-selected { background: #716C62; }
.cm-s-mbo .CodeMirror-line::selection, .cm-s-mbo .CodeMirror-line > span::selection, .cm-s-mbo .CodeMirror-line > span > span::selection { background: rgba(113, 108, 98, .99); }
.cm-s-mbo .CodeMirror-line::-moz-selection, .cm-s-mbo .CodeMirror-line > span::-moz-selection, .cm-s-mbo .CodeMirror-line > span > span::-moz-selection { background: rgba(113, 108, 98, .99); }
.cm-s-mbo .CodeMirror-gutters { background: #4e4e4e; border-right: 0px; }
.cm-s-mbo .CodeMirror-guttermarker { color: white; }
.cm-s-mbo .CodeMirror-guttermarker-subtle { color: grey; }
.cm-s-mbo .CodeMirror-linenumber { color: #dadada; }
.cm-s-mbo .CodeMirror-cursor { border-left: 1px solid #ffffec; }
.cm-s-mbo span.cm-comment { color: #95958a; }
.cm-s-mbo span.cm-atom { color: #00a8c6; }
.cm-s-mbo span.cm-number { color: #00a8c6; }
.cm-s-mbo span.cm-property, .cm-s-mbo span.cm-attribute { color: #9ddfe9; }
.cm-s-mbo span.cm-keyword { color: #ffb928; }
.cm-s-mbo span.cm-string { color: #ffcf6c; }
.cm-s-mbo span.cm-string.cm-property { color: #ffffec; }
.cm-s-mbo span.cm-variable { color: #ffffec; }
.cm-s-mbo span.cm-variable-2 { color: #00a8c6; }
.cm-s-mbo span.cm-def { color: #ffffec; }
.cm-s-mbo span.cm-bracket { color: #fffffc; font-weight: bold; }
.cm-s-mbo span.cm-tag { color: #9ddfe9; }
.cm-s-mbo span.cm-link { color: #f54b07; }
.cm-s-mbo span.cm-error { border-bottom: #636363; color: #ffffec; }
.cm-s-mbo span.cm-qualifier { color: #ffffec; }
.cm-s-mbo .CodeMirror-activeline-background { background: #494b41; }
.cm-s-mbo .CodeMirror-matchingbracket { color: #ffb928 !important; }
.cm-s-mbo .CodeMirror-matchingtag { background: rgba(255, 255, 255, .37); }
|
294coder/Efficient-MIF
| 9,883 |
utils/loss_landscape/cifar10/models/resnet.py
|
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion*planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(self.expansion*planes)
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
out += self.shortcut(x)
out = F.relu(out)
return out
class BasicBlock_noshortcut(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(BasicBlock_noshortcut, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
out = F.relu(out)
return out
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(self.expansion*planes)
self.shortcut = nn.Sequential()
if stride != 1 or in_planes != self.expansion*planes:
self.shortcut = nn.Sequential(
nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(self.expansion*planes)
)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = F.relu(self.bn2(self.conv2(out)))
out = self.bn3(self.conv3(out))
out += self.shortcut(x)
out = F.relu(out)
return out
class Bottleneck_noshortcut(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(Bottleneck_noshortcut, self).__init__()
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
self.conv3 = nn.Conv2d(planes, self.expansion*planes, kernel_size=1, bias=False)
self.bn3 = nn.BatchNorm2d(self.expansion*planes)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = F.relu(self.bn2(self.conv2(out)))
out = self.bn3(self.conv3(out))
return out
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
self.linear = nn.Linear(512*block.expansion, num_classes)
def _make_layer(self, block, planes, num_blocks, stride):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, stride))
self.in_planes = planes * block.expansion
return nn.Sequential(*layers)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = self.layer4(out)
out = F.avg_pool2d(out, 4)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
class ResNet_cifar(nn.Module):
def __init__(self, block, num_blocks, num_classes=10):
super(ResNet_cifar, self).__init__()
self.in_planes = 16
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(16)
self.layer1 = self._make_layer(block, 16, num_blocks[0], stride=1)
self.layer2 = self._make_layer(block, 32, num_blocks[1], stride=2)
self.layer3 = self._make_layer(block, 64, num_blocks[2], stride=2)
self.linear = nn.Linear(64*block.expansion, num_classes)
def _make_layer(self, block, planes, num_blocks, stride):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, stride))
self.in_planes = planes * block.expansion
return nn.Sequential(*layers)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = F.avg_pool2d(out, 8)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
class WResNet_cifar(nn.Module):
def __init__(self, block, num_blocks, k, num_classes=10):
super(WResNet_cifar, self).__init__()
self.in_planes = 16*k
self.conv1 = nn.Conv2d(3, 16*k, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(16*k)
self.layer1 = self._make_layer(block, 16*k, num_blocks[0], stride=1)
self.layer2 = self._make_layer(block, 32*k, num_blocks[1], stride=2)
self.layer3 = self._make_layer(block, 64*k, num_blocks[2], stride=2)
self.linear = nn.Linear(64*k*block.expansion, num_classes)
def _make_layer(self, block, planes, num_blocks, stride):
strides = [stride] + [1]*(num_blocks-1)
layers = []
for stride in strides:
layers.append(block(self.in_planes, planes, stride))
self.in_planes = planes * block.expansion
return nn.Sequential(*layers)
def forward(self, x):
out = F.relu(self.bn1(self.conv1(x)))
out = self.layer1(out)
out = self.layer2(out)
out = self.layer3(out)
out = F.avg_pool2d(out, 8)
out = out.view(out.size(0), -1)
out = self.linear(out)
return out
# ImageNet models
def ResNet18():
return ResNet(BasicBlock, [2,2,2,2])
def ResNet18_noshort():
return ResNet(BasicBlock_noshortcut, [2,2,2,2])
def ResNet34():
return ResNet(BasicBlock, [3,4,6,3])
def ResNet34_noshort():
return ResNet(BasicBlock_noshortcut, [3,4,6,3])
def ResNet50():
return ResNet(Bottleneck, [3,4,6,3])
def ResNet50_noshort():
return ResNet(Bottleneck_noshortcut, [3,4,6,3])
def ResNet101():
return ResNet(Bottleneck, [3,4,23,3])
def ResNet101_noshort():
return ResNet(Bottleneck_noshortcut, [3,4,23,3])
def ResNet152():
return ResNet(Bottleneck, [3,8,36,3])
def ResNet152_noshort():
return ResNet(Bottleneck_noshortcut, [3,8,36,3])
# CIFAR-10 models
def ResNet20():
depth = 20
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock, [n,n,n])
def ResNet20_noshort():
depth = 20
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock_noshortcut, [n,n,n])
def ResNet32_noshort():
depth = 32
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock_noshortcut, [n,n,n])
def ResNet44_noshort():
depth = 44
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock_noshortcut, [n,n,n])
def ResNet50_16_noshort():
depth = 50
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock_noshortcut, [n,n,n])
def ResNet56():
depth = 56
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock, [n,n,n])
def ResNet56_noshort():
depth = 56
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock_noshortcut, [n,n,n])
def ResNet110():
depth = 110
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock, [n,n,n])
def ResNet110_noshort():
depth = 110
n = (depth - 2) // 6
return ResNet_cifar(BasicBlock_noshortcut, [n,n,n])
def WRN56_2():
depth = 56
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock, [n,n,n], 2)
def WRN56_4():
depth = 56
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock, [n,n,n], 4)
def WRN56_8():
depth = 56
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock, [n,n,n], 8)
def WRN56_2_noshort():
depth = 56
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock_noshortcut, [n,n,n], 2)
def WRN56_4_noshort():
depth = 56
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock_noshortcut, [n,n,n], 4)
def WRN56_8_noshort():
depth = 56
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock_noshortcut, [n,n,n], 8)
def WRN110_2_noshort():
depth = 110
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock_noshortcut, [n,n,n], 2)
def WRN110_4_noshort():
depth = 110
n = (depth - 2) // 6
return WResNet_cifar(BasicBlock_noshortcut, [n,n,n], 4)
|
281677160/openwrt-package
| 4,429 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_netcall.c
|
/*
* Copyright (C) AlexWoo(Wu Jie) [email protected]
*/
#include "ngx_netcall.h"
#include "ngx_poold.h"
// cleanup only be called when connect failed(exclusive timeout)
static void
ngx_netcall_cleanup(void *data)
{
ngx_netcall_ctx_t *nctx;
nctx = data;
if (nctx->ev.timer_set) {
ngx_del_timer(&nctx->ev);
}
if (nctx->ev.posted) {
ngx_delete_posted_event(&nctx->ev);
}
if (nctx->hcr) {
ngx_http_client_detach(nctx->hcr);
nctx->handler(nctx, NGX_ERROR);
nctx->hcr = NULL;
}
}
// netcall timeout
static void
ngx_netcall_timeout(ngx_event_t *ev)
{
ngx_netcall_ctx_t *nctx;
nctx = ev->data;
if (nctx->ev.timer_set) {
ngx_del_timer(&nctx->ev);
}
if (nctx->ev.posted) {
ngx_delete_posted_event(&nctx->ev);
}
if (nctx->hcr) {
ngx_http_client_detach(nctx->hcr);
nctx->handler(nctx, NGX_ERROR);
nctx->hcr = NULL;
}
}
static void
ngx_netcall_handler(void *data, ngx_http_request_t *hcr)
{
ngx_netcall_ctx_t *nctx;
ngx_int_t code;
nctx = data;
if (nctx->ev.timer_set) {
ngx_del_timer(&nctx->ev);
}
if (nctx->ev.posted) {
ngx_delete_posted_event(&nctx->ev);
}
code = ngx_http_client_status_code(hcr);
if (nctx->hcr) {
ngx_http_client_detach(nctx->hcr);
nctx->handler(nctx, code);
nctx->hcr = NULL;
}
}
static void
ngx_netcall_destroy_handler(ngx_event_t *ev)
{
ngx_netcall_ctx_t *nctx;
nctx = ev->data;
NGX_DESTROY_POOL(nctx->pool);
}
ngx_netcall_ctx_t *
ngx_netcall_create_ctx(ngx_uint_t type, ngx_str_t *groupid, ngx_uint_t stage,
ngx_msec_t timeout, ngx_msec_t update, ngx_uint_t idx)
{
ngx_netcall_ctx_t *ctx;
ngx_pool_t *pool;
pool = NGX_CREATE_POOL(4096, ngx_cycle->log);
if (pool == NULL) {
return NULL;
}
ctx = ngx_pcalloc(pool, sizeof(ngx_netcall_ctx_t));
if (ctx == NULL) {
NGX_DESTROY_POOL(pool);
return NULL;
}
ctx->url.data = ngx_pcalloc(pool, NGX_NETCALL_MAX_URL_LEN);
if (ctx->url.data == NULL) {
NGX_DESTROY_POOL(pool);
return NULL;
}
ctx->pool = pool;
ctx->idx = idx;
ctx->type = type;
ctx->groupid.len = groupid->len;
ctx->groupid.data = ngx_pcalloc(pool, ctx->groupid.len);
if (ctx->groupid.data == NULL) {
NGX_DESTROY_POOL(pool);
return NULL;
}
ngx_memcpy(ctx->groupid.data, groupid->data, groupid->len);
ctx->ev.log = ngx_cycle->log;
ctx->ev.data = ctx;
ctx->stage = stage;
ctx->timeout = timeout;
ctx->update = update;
return ctx;
}
void
ngx_netcall_create(ngx_netcall_ctx_t *nctx, ngx_log_t *log)
{
ngx_http_request_t *hcr;
ngx_http_cleanup_t *cln;
hcr = ngx_http_client_get(log, &nctx->url, NULL, nctx);
if (hcr == NULL) {
return;
}
ngx_http_client_set_read_handler(hcr, ngx_netcall_handler);
cln = ngx_http_client_cleanup_add(hcr, 0);
if (cln == NULL) {
ngx_log_error(NGX_LOG_ERR, log, 0,
"netcall create add cleanup failed");
return;
}
cln->handler = ngx_netcall_cleanup;
cln->data = nctx;
// detach old http client request
if (nctx->hcr) {
ngx_http_client_detach(nctx->hcr);
}
nctx->hcr = hcr;
nctx->ev.log = log;
nctx->ev.handler = ngx_netcall_timeout;
ngx_add_timer(&nctx->ev, nctx->timeout);
}
void
ngx_netcall_destroy(ngx_netcall_ctx_t *nctx)
{
if (nctx->ev.timer_set) {
ngx_del_timer(&nctx->ev);
}
if (nctx->ev.posted) {
ngx_delete_posted_event(&nctx->ev);
}
if (nctx->hcr) { // use detach will keep client connection alive
ngx_http_client_detach(nctx->hcr);
nctx->hcr = NULL;
}
// destroy may called in nctx->handler
// destroy pool may cause memory error
// so we destroy nctx pool asynchronous
nctx->ev.handler = ngx_netcall_destroy_handler;
// reset ev log, use rtmp session log may be destroy
nctx->ev.log = ngx_cycle->log;
ngx_post_event(&nctx->ev, &ngx_posted_events);
}
ngx_str_t *
ngx_netcall_header(ngx_netcall_ctx_t *nctx, ngx_str_t *key)
{
ngx_http_request_t *hcr;
hcr = nctx->hcr;
return ngx_http_client_header_in(hcr, key);
}
|
294coder/Efficient-MIF
| 1,730 |
utils/loss_landscape/cifar10/models/vgg.py
|
import torch
import torch.nn as nn
cfg = {
'VGG9': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M'],
'VGG16': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'VGG19': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
}
class VGG(nn.Module):
def __init__(self, vgg_name):
super(VGG, self).__init__()
self.input_size = 32
self.features = self._make_layers(cfg[vgg_name])
self.n_maps = cfg[vgg_name][-2]
self.fc = self._make_fc_layers()
self.classifier = nn.Linear(self.n_maps, 10)
def forward(self, x):
out = self.features(x)
out = out.view(out.size(0), -1)
out = self.fc(out)
out = self.classifier(out)
return out
def _make_fc_layers(self):
layers = []
layers += [nn.Linear(self.n_maps*self.input_size*self.input_size, self.n_maps),
nn.BatchNorm1d(self.n_maps),
nn.ReLU(inplace=True)]
return nn.Sequential(*layers)
def _make_layers(self, cfg):
layers = []
in_channels = 3
for x in cfg:
if x == 'M':
layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]
self.input_size = self.input_size // 2
else:
layers += [nn.Conv2d(in_channels, x, kernel_size=3, padding=1),
nn.BatchNorm2d(x),
nn.ReLU(inplace=True)]
in_channels = x
return nn.Sequential(*layers)
def VGG9():
return VGG('VGG9')
def VGG16():
return VGG('VGG16')
def VGG19():
return VGG('VGG19')
|
281677160/openwrt-package
| 25,057 |
luci-app-nginx-pingos/modules/nginx-rtmp-module/ngx_rtmp_handler.c
|
/*
* Copyright (C) Roman Arutyunyan
*/
#include <ngx_config.h>
#include <ngx_core.h>
#include "ngx_rtmp.h"
#include "ngx_rtmp_amf.h"
#include "ngx_rbuf.h"
#include "ngx_poold.h"
#include "ngx_rtmp_monitor_module.h"
static void ngx_rtmp_recv(ngx_event_t *rev);
static void ngx_rtmp_send(ngx_event_t *rev);
static void ngx_rtmp_ping(ngx_event_t *rev);
static ngx_int_t ngx_rtmp_finalize_set_chunk_size(ngx_rtmp_session_t *s);
ngx_uint_t ngx_rtmp_naccepted;
ngx_rtmp_bandwidth_t ngx_rtmp_bw_out;
ngx_rtmp_bandwidth_t ngx_rtmp_bw_in;
#ifdef NGX_DEBUG
char*
ngx_rtmp_message_type(uint8_t type)
{
static char* types[] = {
"?",
"chunk_size",
"abort",
"ack",
"user",
"ack_size",
"bandwidth",
"edge",
"audio",
"video",
"?",
"?",
"?",
"?",
"?",
"amf3_meta",
"amf3_shared",
"amf3_cmd",
"amf_meta",
"amf_shared",
"amf_cmd",
"?",
"aggregate"
};
return type < sizeof(types) / sizeof(types[0])
? types[type]
: "?";
}
char*
ngx_rtmp_user_message_type(uint16_t evt)
{
static char* evts[] = {
"stream_begin",
"stream_eof",
"stream dry",
"set_buflen",
"recorded",
"",
"ping_request",
"ping_response",
};
return evt < sizeof(evts) / sizeof(evts[0])
? evts[evt]
: "?";
}
#endif
void
ngx_rtmp_cycle(ngx_rtmp_session_t *s)
{
ngx_connection_t *c;
c = s->connection;
c->read->handler = ngx_rtmp_recv;
c->write->handler = ngx_rtmp_send;
s->ping_evt.data = c;
s->ping_evt.log = s->log;
s->ping_evt.handler = ngx_rtmp_ping;
ngx_rtmp_reset_ping(s);
ngx_rtmp_recv(c->read);
}
static ngx_chain_t *
ngx_rtmp_alloc_in_buf(ngx_rtmp_session_t *s)
{
ngx_chain_t *cl;
ngx_buf_t *b;
size_t size;
if ((cl = ngx_alloc_chain_link(s->in_pool)) == NULL
|| (cl->buf = ngx_calloc_buf(s->in_pool)) == NULL)
{
return NULL;
}
cl->next = NULL;
b = cl->buf;
size = s->in_chunk_size + NGX_RTMP_MAX_CHUNK_HEADER;
b->start = b->last = b->pos = ngx_palloc(s->in_pool, size);
if (b->start == NULL) {
return NULL;
}
b->end = b->start + size;
return cl;
}
void
ngx_rtmp_reset_ping(ngx_rtmp_session_t *s)
{
ngx_rtmp_core_srv_conf_t *cscf;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
if (cscf->ping == 0) {
return;
}
s->ping_active = 0;
s->ping_reset = 0;
ngx_add_timer(&s->ping_evt, cscf->ping);
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"ping: wait %Mms", cscf->ping);
}
static void
ngx_rtmp_ping(ngx_event_t *pev)
{
ngx_connection_t *c;
ngx_rtmp_session_t *s;
ngx_rtmp_core_srv_conf_t *cscf;
c = pev->data;
s = c->data;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
/* i/o event has happened; no need to ping */
if (s->ping_reset) {
ngx_rtmp_reset_ping(s);
return;
}
if (s->ping_active) {
ngx_log_error(NGX_LOG_INFO, s->log, 0, "ping: unresponded");
ngx_rtmp_finalize_session(s);
return;
}
if (cscf->busy) {
ngx_log_error(NGX_LOG_INFO, s->log, 0, "ping: not busy between pings");
ngx_rtmp_finalize_session(s);
return;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"ping: schedule %Mms", cscf->ping_timeout);
if (ngx_rtmp_send_ping_request(s, (uint32_t)ngx_current_msec) != NGX_OK) {
ngx_rtmp_finalize_session(s);
return;
}
s->ping_active = 1;
ngx_add_timer(pev, cscf->ping_timeout);
}
static void
ngx_rtmp_recv(ngx_event_t *rev)
{
ngx_int_t n;
ngx_connection_t *c;
ngx_rtmp_session_t *s;
ngx_rtmp_core_srv_conf_t *cscf;
ngx_rtmp_header_t *h;
ngx_rtmp_stream_t *st, *st0;
ngx_chain_t *in, *head;
ngx_buf_t *b;
u_char *p, *pp, *old_pos;
size_t size, fsize, old_size;
uint8_t fmt, ext;
uint32_t csid, timestamp;
c = rev->data;
s = c->data;
b = NULL;
old_pos = NULL;
old_size = 0;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
if (c->destroyed) {
return;
}
if (ngx_rtmp_core_main_conf->fast_reload && (ngx_exiting || ngx_terminate)) {
s->finalize_reason = NGX_LIVE_PROCESS_EXIT;
ngx_rtmp_finalize_session(s);
return;
}
for( ;; ) {
st = &s->in_streams[s->in_csid];
/* allocate new buffer */
if (st->in == NULL) {
st->in = ngx_rtmp_alloc_in_buf(s);
if (st->in == NULL) {
ngx_log_error(NGX_LOG_INFO, s->log, 0, "in buf alloc failed");
ngx_rtmp_finalize_session(s);
return;
}
}
h = &st->hdr;
in = st->in;
b = in->buf;
if (old_size) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"reusing formerly read data: %d", old_size);
b->pos = b->start;
b->last = ngx_movemem(b->pos, old_pos, old_size);
if (s->in_chunk_size_changing) {
ngx_rtmp_finalize_set_chunk_size(s);
}
} else {
if (old_pos) {
b->pos = b->last = b->start;
}
n = c->recv(c, b->last, b->end - b->last);
if (n == NGX_ERROR || n == 0) {
s->finalize_reason = n == 0? NGX_LIVE_NORMAL_CLOSE:
NGX_LIVE_RTMP_RECV_ERR;
ngx_rtmp_finalize_session(s);
return;
}
if (n == NGX_AGAIN) {
if (ngx_handle_read_event(c->read, 0) != NGX_OK) {
ngx_rtmp_finalize_session(s);
}
return;
}
s->ping_reset = 1;
ngx_rtmp_update_bandwidth(&ngx_rtmp_bw_in, n);
b->last += n;
s->in_bytes += n;
if (s->in_bytes >= 0xf0000000) {
ngx_log_debug0(NGX_LOG_DEBUG_RTMP, s->log, 0,
"resetting byte counter");
s->in_bytes = 0;
s->in_last_ack = 0;
}
if (s->ack_size && s->in_bytes - s->in_last_ack >= s->ack_size) {
s->in_last_ack = s->in_bytes;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"sending RTMP ACK(%uD)", s->in_bytes);
if (ngx_rtmp_send_ack(s, s->in_bytes)) {
ngx_rtmp_finalize_session(s);
return;
}
}
}
old_pos = NULL;
old_size = 0;
/* parse headers */
if (b->pos == b->start) {
p = b->pos;
/* chunk basic header */
fmt = (*p >> 6) & 0x03;
csid = *p++ & 0x3f;
if (csid == 0) {
if (b->last - p < 1)
continue;
csid = 64;
csid += *(uint8_t*)p++;
} else if (csid == 1) {
if (b->last - p < 2)
continue;
csid = 64;
csid += *(uint8_t*)p++;
csid += (uint32_t)256 * (*(uint8_t*)p++);
}
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP bheader fmt=%d csid=%D",
(int)fmt, csid);
if (csid >= (uint32_t)cscf->max_streams) {
ngx_log_error(NGX_LOG_INFO, s->log, 0,
"RTMP in chunk stream too big: %D >= %D",
csid, cscf->max_streams);
ngx_rtmp_finalize_session(s);
return;
}
/* link orphan */
if (s->in_csid == 0) {
/* unlink from stream #0 */
st->in = st->in->next;
/* link to new stream */
s->in_csid = csid;
st = &s->in_streams[csid];
if (st->in == NULL) {
in->next = in;
} else {
in->next = st->in->next;
st->in->next = in;
}
st->in = in;
h = &st->hdr;
h->csid = csid;
}
ext = st->ext;
timestamp = st->dtime;
if (fmt <= 2 ) {
if (b->last - p < 3)
continue;
/* timestamp:
* big-endian 3b -> little-endian 4b */
pp = (u_char*)×tamp;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
pp[3] = 0;
ext = (timestamp == 0x00ffffff);
if (fmt <= 1) {
if (b->last - p < 4)
continue;
/* size:
* big-endian 3b -> little-endian 4b
* type:
* 1b -> 1b*/
pp = (u_char*)&h->mlen;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
pp[3] = 0;
h->type = *(uint8_t*)p++;
if (fmt == 0) {
if (b->last - p < 4)
continue;
/* stream:
* little-endian 4b -> little-endian 4b */
pp = (u_char*)&h->msid;
pp[0] = *p++;
pp[1] = *p++;
pp[2] = *p++;
pp[3] = *p++;
}
}
}
/* extended header */
if (ext) {
if (b->last - p < 4)
continue;
pp = (u_char*)×tamp;
pp[3] = *p++;
pp[2] = *p++;
pp[1] = *p++;
pp[0] = *p++;
}
if (st->len == 0) {
/* Messages with type=3 should
* never have ext timestamp field
* according to standard.
* However that's not always the case
* in real life */
st->ext = (ext && cscf->publish_time_fix);
if (fmt) {
st->dtime = timestamp;
} else {
h->timestamp = timestamp;
st->dtime = 0;
}
}
ngx_log_debug8(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP mheader fmt=%d %s (%d) "
"time=%uD+%uD mlen=%D len=%D msid=%D",
(int)fmt, ngx_rtmp_message_type(h->type), (int)h->type,
h->timestamp, st->dtime, h->mlen, st->len, h->msid);
/* header done */
b->pos = p;
if (h->mlen > cscf->max_message) {
ngx_log_error(NGX_LOG_INFO, s->log, 0,
"too big message: %uz", cscf->max_message);
ngx_rtmp_finalize_session(s);
return;
}
}
size = b->last - b->pos;
fsize = h->mlen - st->len;
if (size < ngx_min(fsize, s->in_chunk_size))
continue;
/* buffer is ready */
if (fsize > s->in_chunk_size) {
/* collect fragmented chunks */
st->len += s->in_chunk_size;
b->last = b->pos + s->in_chunk_size;
old_pos = b->last;
old_size = size - s->in_chunk_size;
} else {
/* handle! */
head = st->in->next;
st->in->next = NULL;
b->last = b->pos + fsize;
old_pos = b->last;
old_size = size - fsize;
st->len = 0;
h->timestamp += st->dtime;
if (ngx_rtmp_receive_message(s, h, head) != NGX_OK) {
ngx_rtmp_finalize_session(s);
return;
}
if (s->in_chunk_size_changing) {
/* copy old data to a new buffer */
if (!old_size) {
ngx_rtmp_finalize_set_chunk_size(s);
}
} else {
/* add used bufs to stream #0 */
st0 = &s->in_streams[0];
st->in->next = st0->in;
st0->in = head;
st->in = NULL;
}
}
s->in_csid = 0;
}
}
static ngx_flag_t
ngx_rtmp_relative_timestamp(ngx_rtmp_session_t *s, ngx_rtmp_header_t *lh)
{
return 0;
}
static ngx_chain_t *
ngx_rtmp_prepare_out_chain(ngx_rtmp_session_t *s)
{
ngx_rtmp_core_srv_conf_t *cscf;
ngx_rtmp_frame_t *frame;
ngx_chain_t *head, *l, **ll;
uint32_t mlen, timestamp, ext_timestamp;
uint8_t fmt, hsize, thsize;
static uint8_t hdrsize[] = { 12, 8, 4, 1 };
ngx_flag_t relative;
ngx_rtmp_header_t lh;
u_char th[7], *p, *pp;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
frame = s->out[s->out_pos];
head = NULL;
if (frame->hdr.csid >= (uint32_t)cscf->max_streams) {
ngx_log_error(NGX_LOG_INFO, s->log, 0,
"RTMP out chunk stream too big: %D >= %D",
frame->hdr.csid, cscf->max_streams);
goto failed;
}
mlen = 0;
fmt = 0;
relative = ngx_rtmp_relative_timestamp(s, &lh);
for (l = frame->chain; l; l = l->next) {
mlen += ngx_buf_size(l->buf);
}
if (relative && lh.csid && frame->hdr.msid == lh.msid) {
++fmt;
if (frame->hdr.type == lh.type && mlen && mlen == lh.mlen) {
++fmt;
if (frame->hdr.timestamp == lh.timestamp) {
++fmt;
}
}
timestamp = frame->hdr.timestamp - lh.timestamp;
} else {
timestamp = frame->hdr.timestamp;
}
hsize = hdrsize[fmt];
ngx_log_debug7(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP prep %s (%d) fmt=%d csid=%uD timestamp=%uD mlen=%uD msid=%uD",
ngx_rtmp_message_type(frame->hdr.type), (int)frame->hdr.type,
(int)fmt, frame->hdr.csid, timestamp, mlen, frame->hdr.msid);
ext_timestamp = 0;
if (timestamp >= 0x00ffffff) {
ext_timestamp = timestamp;
timestamp = 0x00ffffff;
hsize += 4;
}
if (frame->hdr.csid >= 64) {
++hsize;
if (frame->hdr.csid >= 320) {
++hsize;
}
}
/* fill initial header */
head = ngx_get_chainbuf(NGX_RTMP_MAX_CHUNK_HEADER, 1);
if (head == NULL) {
goto failed;
}
p = head->buf->pos;
/* basic header */
*p = (fmt << 6);
if (frame->hdr.csid >= 2 && frame->hdr.csid <= 63) {
*p++ |= (((uint8_t)frame->hdr.csid) & 0x3f);
} else if (frame->hdr.csid >= 64 && frame->hdr.csid < 320) {
++p;
*p++ = (uint8_t)(frame->hdr.csid - 64);
} else {
*p++ |= 1;
*p++ = (uint8_t)(frame->hdr.csid - 64);
*p++ = (uint8_t)((frame->hdr.csid - 64) >> 8);
}
/* create fmt3 header for successive fragments */
thsize = p - head->buf->pos;
ngx_memcpy(th, head->buf->pos, thsize);
th[0] |= 0xc0;
/* message header */
if (fmt <= 2) {
pp = (u_char *)×tamp;
*p++ = pp[2];
*p++ = pp[1];
*p++ = pp[0];
if (fmt <= 1) {
pp = (u_char *)&mlen;
*p++ = pp[2];
*p++ = pp[1];
*p++ = pp[0];
*p++ = frame->hdr.type;
if (fmt == 0) {
pp = (u_char *)&frame->hdr.msid;
*p++ = pp[0];
*p++ = pp[1];
*p++ = pp[2];
*p++ = pp[3];
}
}
}
/* extended timestamp */
if (ext_timestamp) {
pp = (u_char *)&ext_timestamp;
*p++ = pp[3];
*p++ = pp[2];
*p++ = pp[1];
*p++ = pp[0];
/* This CONTRADICTS the standard
* but that's the way flash client
* wants data to be encoded;
* ffmpeg complains */
if (cscf->play_time_fix) {
ngx_memcpy(&th[thsize], p - 4, 4);
thsize += 4;
}
}
head->buf->last = p;
/* append headers to successive fragments */
ll = &head->next;
l = frame->chain;
while (l && l->buf->pos == l->buf->last) {
l = l->next;
}
if (l == NULL) {
return head;
}
*ll = ngx_get_chainbuf(0, 0);
(*ll)->buf->pos = l->buf->pos;
(*ll)->buf->last = l->buf->last;
for (l = l->next; l; l = l->next) {
/* chunk header */
ll = &(*ll)->next;
*ll = ngx_get_chainbuf(NGX_RTMP_MAX_CHUNK_HEADER, 1);
(*ll)->buf->last = ngx_cpymem((*ll)->buf->last, th, thsize);
/* payload */
ll = &(*ll)->next;
*ll = ngx_get_chainbuf(0, 0);
(*ll)->buf->pos = l->buf->pos;
(*ll)->buf->last = l->buf->last;
}
ngx_rtmp_monitor_frame(s, &frame->hdr, NULL, frame->av_header, 0);
return head;
failed:
ngx_put_chainbufs(head);
ngx_rtmp_finalize_session(s);
return NULL;
}
static void
ngx_rtmp_send(ngx_event_t *wev)
{
ngx_connection_t *c;
ngx_rtmp_session_t *s;
ngx_int_t n;
ngx_chain_t *chain, *cl;
off_t sent;
c = wev->data;
s = c->data;
if (c->destroyed) {
return;
}
if (wev->timedout) {
ngx_log_error(NGX_LOG_INFO, s->log, NGX_ETIMEDOUT, "client timed out");
c->timedout = 1;
s->finalize_reason = NGX_LIVE_RTMP_SEND_TIMEOUT;
ngx_rtmp_finalize_session(s);
return;
}
if (wev->timer_set) {
ngx_del_timer(wev);
}
if (s->prepare_handler == NULL) {
s->prepare_handler = ngx_rtmp_prepare_out_chain;
}
if (ngx_rtmp_core_main_conf->fast_reload && (ngx_exiting || ngx_terminate)) {
s->finalize_reason = NGX_LIVE_PROCESS_EXIT;
ngx_rtmp_finalize_session(s);
return;
}
if (ngx_rtmp_prepare_merge_frame(s) == NGX_ERROR) {
ngx_rtmp_finalize_session(s);
return;
}
while (s->out_chain) {
sent = c->sent;
chain = c->send_chain(c, s->out_chain, 0);
n = c->sent - sent;
if (chain == NGX_CHAIN_ERROR) { /* NGX_ERROR */
c->error = 1;
s->finalize_reason = NGX_LIVE_RTMP_SEND_ERR;
ngx_rtmp_finalize_session(s);
return;
}
for (cl = s->out_chain; cl != chain;) {
s->out_chain = cl->next;
ngx_free_chain(s->pool, cl);
cl = s->out_chain;
}
if (chain) { /* NGX_AGAIN */
ngx_add_timer(c->write, s->timeout);
if (ngx_handle_write_event(c->write, 0) != NGX_OK) {
ngx_rtmp_finalize_session(s);
}
return;
}
s->out_bytes += n;
s->ping_reset = 1;
ngx_rtmp_update_bandwidth(&ngx_rtmp_bw_out, n);
if (ngx_rtmp_prepare_merge_frame(s) == NGX_ERROR) {
ngx_rtmp_finalize_session(s);
return;
}
}
if (wev->active) {
ngx_del_event(wev, NGX_WRITE_EVENT, 0);
}
ngx_event_process_posted((ngx_cycle_t *) ngx_cycle, &s->posted_dry_events);
}
ngx_int_t
ngx_rtmp_send_message(ngx_rtmp_session_t *s, ngx_rtmp_frame_t *out,
ngx_uint_t priority)
{
ngx_uint_t nmsg;
if (out == NULL) {
goto send;
}
nmsg = (s->out_last - s->out_pos) % s->out_queue + 1;
if (priority > 3) {
priority = 3;
}
/* drop packet?
* Note we always leave 1 slot free */
if (nmsg + priority * s->out_queue / 4 >= s->out_queue) {
ngx_log_debug2(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP drop message bufs=%ui, priority=%ui",
nmsg, priority);
return NGX_AGAIN;
}
s->out[s->out_last++] = out;
s->out_last %= s->out_queue;
ngx_rtmp_shared_acquire_frame(out);
ngx_log_debug3(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP send nmsg=%ui, priority=%ui #%ui",
nmsg, priority, s->out_last);
if (priority && s->out_buffer && nmsg < s->out_cork) {
return NGX_OK;
}
send:
if (!s->connection->write->active) {
ngx_post_event(s->connection->write, &ngx_posted_events);
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_receive_message(ngx_rtmp_session_t *s,
ngx_rtmp_header_t *h, ngx_chain_t *in)
{
ngx_rtmp_core_main_conf_t *cmcf;
ngx_array_t *evhs;
size_t n;
ngx_rtmp_handler_pt *evh;
cmcf = ngx_rtmp_get_module_main_conf(s, ngx_rtmp_core_module);
#ifdef NGX_DEBUG
{
int nbufs;
ngx_chain_t *ch;
for(nbufs = 1, ch = in;
ch->next;
ch = ch->next, ++nbufs);
ngx_log_debug7(NGX_LOG_DEBUG_RTMP, s->log, 0,
"RTMP recv %s (%d) csid=%D timestamp=%D "
"mlen=%D msid=%D nbufs=%d",
ngx_rtmp_message_type(h->type), (int)h->type,
h->csid, h->timestamp, h->mlen, h->msid, nbufs);
}
#endif
if (h->type > NGX_RTMP_MSG_MAX) {
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"unexpected RTMP message type: %d", (int)h->type);
return NGX_OK;
}
evhs = &cmcf->events[h->type];
evh = evhs->elts;
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0, "nhandlers: %d", evhs->nelts);
for(n = 0; n < evhs->nelts; ++n, ++evh) {
if (!evh) {
continue;
}
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0, "calling handler %d", n);
switch ((*evh)(s, h, in)) {
case NGX_ERROR:
ngx_log_debug1(NGX_LOG_DEBUG_RTMP, s->log, 0,
"handler %d failed", n);
return NGX_ERROR;
case NGX_DONE:
return NGX_OK;
}
}
return NGX_OK;
}
ngx_int_t
ngx_rtmp_set_chunk_size(ngx_rtmp_session_t *s, ngx_uint_t size)
{
ngx_rtmp_core_srv_conf_t *cscf;
ngx_chain_t *li, *fli, *lo, *flo;
ngx_buf_t *bi, *bo;
ngx_int_t n;
cscf = ngx_rtmp_get_module_srv_conf(s, ngx_rtmp_core_module);
s->in_old_pool = s->in_pool;
s->in_chunk_size = size;
s->in_pool = NGX_CREATE_POOL(4096, ngx_cycle->log);
/* copy existing chunk data */
if (s->in_old_pool) {
s->in_chunk_size_changing = 1;
s->in_streams[0].in = NULL;
for(n = 1; n < cscf->max_streams; ++n) {
/* stream buffer is circular
* for all streams except for the current one
* (which caused this chunk size change);
* we can simply ignore it */
li = s->in_streams[n].in;
if (li == NULL || li->next == NULL) {
s->in_streams[n].in = NULL;
continue;
}
/* move from last to the first */
li = li->next;
fli = li;
lo = ngx_rtmp_alloc_in_buf(s);
if (lo == NULL) {
return NGX_ERROR;
}
flo = lo;
for ( ;; ) {
bi = li->buf;
bo = lo->buf;
if (bo->end - bo->last >= bi->last - bi->pos) {
bo->last = ngx_cpymem(bo->last, bi->pos,
bi->last - bi->pos);
li = li->next;
if (li == fli) {
lo->next = flo;
s->in_streams[n].in = lo;
break;
}
continue;
}
bi->pos += (ngx_cpymem(bo->last, bi->pos,
bo->end - bo->last) - bo->last);
lo->next = ngx_rtmp_alloc_in_buf(s);
lo = lo->next;
if (lo == NULL) {
return NGX_ERROR;
}
}
}
}
return NGX_OK;
}
static ngx_int_t
ngx_rtmp_finalize_set_chunk_size(ngx_rtmp_session_t *s)
{
if (s->in_chunk_size_changing && s->in_old_pool) {
NGX_DESTROY_POOL(s->in_old_pool);
s->in_old_pool = NULL;
s->in_chunk_size_changing = 0;
}
return NGX_OK;
}
|
Subsets and Splits
GitHub Repos with WiFiClientSecure
Finds specific file paths in repositories that contain particular code snippets related to WiFiClientSecure and ChatGPT, providing basic filtering of relevant files.