home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2011 November
/
CHIP_2011_11.iso
/
Programy
/
Narzedzia
/
AIMP2
/
aimp_2.61.583.exe
/
$TEMP
/
YandexPackSetup.msi
/
filCE527DEABCC69D5FF44711863445D162
< prev
next >
Wrap
Text File
|
2010-07-12
|
41KB
|
1,228 lines
XB._functions = {};
XB._functions.CN_assign = XB._calcNodes.ProcNode.extend({
$name: "CN_assign",
expectedArgNames: ["name", "value"],
_proc: function Fassign_proc(eventInfo) {
var refName = this._argManager.getValByName("name", "String");
var refNode = this._parentWidget.findVariable(refName);
if (!refNode)
refNode = this._parentWidget.findSetting(refName);
if (!refNode)
throw new Error(XB._base.consts.ERR_DATA_UNDEFINED + " (" + refName + ")");
var newValue = this._argManager.getValByName("value");
refNode.setValue(newValue);
}
});
XB._functions.CN_cast = XB._calcNodes.FuncNode.extend({
$name: "CN_cast",
expectedArgNames: ["type", "value"],
_calculate: function Fcast_calculate(changedArgs) {
let preferedType = this._argManager.getValByName("type", "String");
let value = this._argManager.getValByName("value");
switch(preferedType) {
case "empty":
return XB.types.empty;
case "bool":
return XB._base.runtime.xToBool(value);
case "number":
return XB._base.runtime.xToNumber(value);
case "string":
return XB._base.runtime.xToString(value);
default:
throw new Error("Unknown cast type: " + preferedType);
}
}
});
XB._functions.RegEx = XB._calcNodes.FuncNode.extend({
$name: "RegEx",
_calculate: function FRegex_calculate(changedArgs) {
if (!this._compiledRegExp || this._argManager.argInArray("expression", changedArgs))
this._compiledRegExp = new RegExp(this._argManager.getValByName("expression", "String"), "m");
},
_compiledRegExp: null
});
XB._functions["CN_regex-test"] = XB._functions.RegEx.extend({
$name: "CN_regex-test",
expectedArgNames: ["expression", "value"],
_calculate: function FRegexTest_calculate(changedArgs) {
this.base(changedArgs);
let string = this._argManager.getValByName("value", "String");
return this._compiledRegExp.test(string);
}
});
XB._functions["CN_regex-search"] = XB._functions.RegEx.extend({
$name: "CN_regex-search",
expectedArgNames: ["expression", "value"],
_calculate: function FRegexSearch_calculate(changedArgs) {
this.base(changedArgs);
let string = this._argManager.getValByName("value", "String");
let match = string.match(this._compiledRegExp);
if (!match)
return XB.types.empty;
return match.length > 1 ? match[1] : match[0];
}
});
XB._functions["CN_regex-escape"] = XB._functions.RegEx.extend({
$name: "CN_regex-escape",
expectedArgNames: ["value"],
_calculate: function FRegexEscape_calculate(changedArgs) {
let string = this._argManager.getValByName("value", "String");
return sysutils.RegExp.escape(string);
}
});
XB._functions.Arithmetical = XB._calcNodes.FuncNode.extend({
$name: "Arithmetical",
_calculate: function FArithmetical_calculate(changedArgs) {
return Number( this._applyOp(this._operation).toFixed(XB._functions.Arithmetical.PRECISION) );
},
_applyOp: function FArithmetical_applyOp(op) {
var result = undefined;
for (let valIndex = 0, len = this._argManager.argsCount; valIndex < len; valIndex++) {
var num = this._argManager.getValByIndex(valIndex, "Number");
if (result == undefined)
result = num;
else
result = op(result, num);
}
return result;
}
});
XB._functions.Arithmetical.PRECISION = 6;
XB._functions.CN_add = XB._functions.Arithmetical.extend({
$name: "CN_add",
_operation: function Fadd_operation(p1, p2) {
return p1 + p2;
}
});
XB._functions.CN_sub = XB._functions.Arithmetical.extend({
$name: "CN_sub",
_operation: function Fsub_operation(p1, p2) {
return p1 - p2;
}
});
XB._functions.CN_mul = XB._functions.Arithmetical.extend({
$name: "CN_mul",
_operation: function Fmul_operation(p1, p2) {
return p1 * p2;
}
});
XB._functions.CN_div = XB._functions.Arithmetical.extend({
$name: "CN_div",
_operation: function Fdiv_operation(p1, p2) {
if (p2 == 0)
throw new Error("Division by zero");
return p1 / p2;
}
});
XB._functions.CN_mod = XB._functions.Arithmetical.extend({
$name: "CN_mod",
_operation: function Fmod_operation(p1, p2) {
if (p2 == 0)
throw new Error("Division by zero");
return p1 % p2;
}
});
XB._functions["CN_format-number"] = XB._calcNodes.FuncNode.extend({
$name: "CN_format-number",
expectedArgNames: ["value", "precision", "separate-groups", "positive-sign"],
_calculate: function FFormatNumber_calculate(changedArgs) {
var num = this._argManager.getValByName("value", "Number");
var precision = this._argManager.getValByNameDef("precision", "Number", undefined);
if (precision !== undefined) {
precision = parseInt(precision, 10);
if (precision < 0)
throw new RangeError("Precision must be positive");
}
var posSign = this._argManager.getValByNameDef("positive-sign", "Bool", false);
var sign = "";
if (num < 0)
sign = "-";
else {
if (posSign && (num > 0))
sign = "+";
}
var result;
if (precision == undefined) {
result = sign + Math.abs(num).toLocaleString();
} else {
var order = Math.pow(10, precision);
var rounded = Math.round(Math.abs(num) * order);
result = sign + parseInt(rounded / order, 10).toLocaleString();
if (precision > 0) {
var fracStr = rounded.toString().substr(-precision);
fracStr = sysutils.strdup("0", precision - fracStr.length) + fracStr;
result += XB._base.consts.STR_LOCALE_DECIMAL_SEPARATOR + fracStr;
}
}
if (!this._argManager.getValByNameDef("separate-groups", "Bool", true)) {
result = result.replace(/\s+/g, "");
}
return result;
}
});
XB._functions.Periodic = XB._calcNodes.FuncNode.extend({
$name: "Periodic",
expectedArgNames: ["interval"],
constructor: function FPeriodic_constructor() {
this.base.apply(this, arguments);
this._timer = XB._Cc["@mozilla.org/timer;1"].createInstance(XB._Ci.nsITimer);
},
_resetTimer: function FPeriodic_resetTimer() {
var expireTime = this._argManager.getValByNameDef(this.expectedArgNames[0], "Number", Number.POSITIVE_INFINITY);
if (expireTime == Number.POSITIVE_INFINITY) {
this._timerSet = true;
return;
}
if (expireTime <= 0)
throw new RangeError(this._consts.ERR_INVALID_INTERVAL);
expireTime = Math.max(expireTime, XB._functions.Periodic.MIN_INTERVAL);
this._timer.initWithCallback(this, expireTime * 1000, this._timer.TYPE_REPEATING_SLACK);
this._timerSet = true;
this._timerInterval = expireTime;
},
_cancelTimer: function FPeriodic_cancelTimer() {
this._timer.cancel();
this._timerSet = false;
},
_calculate: function FPeriodic_calculate(changedArgs) {
if (this._hasSubscribers() &&
(!this._timerSet || this._argManager.argInArray(this.expectedArgNames[0], changedArgs))) {
this._resetTimer();
}
else {
this._cancelTimer();
}
return this._storedValue;
},
_notNeeded: function FPeriodic_notNeeded() {
this._cancelTimer();
},
_timer: null,
_timerInterval: undefined,
_timerSet: false
}, {
MIN_INTERVAL: 1
});
XB._functions.CN_timestamp = XB._functions.Periodic.extend({
$name: "CN_timestamp",
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsITimerCallback]),
notify: function Ftimestamp_notify() {
try {
this._setNewVal( parseInt(Date.now() / 1000, 10) );
this._notifyDeps();
}
catch (e) {
this._parentWidget.logger.error("CN_timestamp.notify() failed. " + e.message);
}
},
_calculate: function Ftimestamp_calculate(changedArgs) {
this.base(changedArgs);
return parseInt(Date.now() / 1000, 10);
}
});
XB._functions.CN_meander = XB._functions.Periodic.extend({
$name: "CN_meander",
notify: function Fmeander_notify() {
try {
this._setNewVal(!this._storedValue);
this._notifyDeps();
}
catch (e) {
this._parentWidget.logger.error("CN_meander.notify() failed. " + e.message);
}
}
});
XB._functions["CN_time-arrived"] = XB._calcNodes.FuncNode.extend({
$name: "CN_time-arrived",
expectedArgNames: ["time"],
constructor: function Ftimearrived_constructor() {
this.base.apply(this, arguments);
this._timer = XB._Cc["@mozilla.org/timer;1"].createInstance(XB._Ci.nsITimer);
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsITimerCallback]),
notify: function Fwait_notify() {
try {
if (this._setNewVal(true))
this._notifyDeps();
}
catch (e) {
this._parentWidget.logger.error("CN_time-arrived.notify() failed. " + e.message);
}
},
_timer: null,
_calculate: function Ftimearrived_calculate(changedArgs) {
var moreToWait = this._argManager.getValByName("time", "Number") - parseInt(Date.now() / 1000, 10);
if (moreToWait > 0)
this._timer.initWithCallback(this, moreToWait * 1000, this._timer.TYPE_ONE_SHOT);
return moreToWait <= 0;
}
});
XB._functions["CN_format-time"] = XB._calcNodes.FuncNode.extend({
$name: "CN_format-time",
expectedArgNames: ["value", "format"],
_calculate: function FFormatTime_calculate(changedArgs) {
return this._formatTimestamp(this._argManager.getValByName("value", "Number") * 1000,
this._argManager.getValByName("format", "String"));
},
_formatTimestamp: function format(timestamp, format) {
var date = new Date(timestamp);
if (date == "Invalid Date")
throw new RangeError("Invalid date timestamp (" + timestamp + ")");
var components = [];
function leadZero(str) {
return str.length > 1 ? str : "0" + str;
}
function formatCode(code) {
switch (code) {
case "d":
return date.getDate();
case "D":
return leadZero("" + date.getDate());
case "m":
return date.getMonth() + 1;
case "M":
return leadZero("" + (date.getMonth() + 1));
case "y":
return ("" + date.getFullYear()).substr(2, 2);
case "Y":
return date.getFullYear();
case "h":
return date.getHours();
case "H":
return leadZero("" + date.getHours());
case "n":
return date.getMinutes();
case "N":
return leadZero("" + date.getMinutes());
case "s":
return date.getSeconds();
case "S":
return leadZero("" + date.getSeconds());
default:
throw new SyntaxError("Unknown format code " + code);
}
}
function makeComponents(str, start, accum) {
var occur = str.indexOf("%", start);
if (occur == -1) {
accum.push(str.substring(start));
return;
}
accum.push(str.substring(start, occur));
accum.push(formatCode(str.substr(occur + 1, 1)));
makeComponents(str, occur + 2, accum);
}
makeComponents(format, 0, components);
return components.join("");
}
});
XB._functions.CN_if = XB._calcNodes.FuncNode.extend({
$name: "CN_if",
expectedArgNames: ["condition", "ontrue", "onfalse"],
_calculate: function Fif_calculate(changedArgs) {
if ( this._argManager.getValByName("condition", "Bool") )
return this._argManager.getValByNameDef("ontrue", undefined, XB.types.empty);
return this._argManager.getValByNameDef("onfalse", undefined, XB.types.empty);
}
});
XB._functions.CN_concat = XB._calcNodes.FuncNode.extend({
$name: "CN_concat",
_calculate: function Fconcat_calculate(changedArgs) {
var numArgs = this._argManager.argsCount;
if (numArgs > 0)
return XB._functions.CN_concat.concatArgs(this, 0, numArgs - 1);
return XB.types.empty;
}
});
// Practically an alias with another class name for debugging purpose
XB._functions.Data = XB._functions.CN_concat.extend({
$name: "Data"
});
XB._functions.CN_concat.concatArgs = function ConcatArgs (funcNode, start, end) {
if (end - start < 1)
return funcNode._argManager.getValByIndex(start);
var resultIsXML = false;
var argXValues = [];
for (; start <= end; start++) {
var xv = funcNode._argManager.getValByIndex(start);
argXValues.push(xv);
resultIsXML = resultIsXML || XB._base.runtime.isXML(xv);
}
return XB._functions.CN_concat.glue(argXValues, resultIsXML);
};
XB._functions.CN_concat.glue = function ConcatGlue (valuesArray, xmlOutput) {
if (!xmlOutput) {
var result = "";
for each (let value in valuesArray) {
result += XB._base.runtime.xToString(value);
}
return result;
}
else {
var result = new XB.types.XML();
for each (let value in valuesArray) {
if (XB._base.runtime.isXML(value))
result.append(value);
else {
var node = XB._base.runtime.tempXMLDoc.createTextNode(XB._base.runtime.xToString(value));
result.append(node);
}
}
return result;
}
};
XB._functions.CN_xpath = XB._calcNodes.FuncNode.extend({
$name: "CN_xpath",
expectedArgNames: ["expression", "source"],
_calculate: function Fxpath_calculate(changedArgs) {
var expr = this._argManager.getValByName("expression", "String");
var src = this._argManager.getValByName("source");
if (!XB._base.runtime.isXML(src))
return new XB.types.Exception(this._getHumanReadableID(), XB.types.Exception.types.E_TYPE,
"Not XML, " + XB._base.runtime.describeValue(src));
return src.query(expr);
}
});
XB._functions.CN_xslt = XB._calcNodes.FuncNode.extend({
$name: "CN_xslt",
expectedArgNames: ["stylesheet", "source"],
_calculate: function Fxslt_calculate(changedArgs) {
var stylesheetPath = this._argManager.getValByName("stylesheet", "String");
var stylesheetFile = this._parentWidget.prototype.unit.unitPackage.findFile(stylesheetPath);
if (!stylesheetFile)
throw new Error("File no found: " + stylesheetPath);
var stylesheet = sysutils.xmlDocFromFile(stylesheetFile);
var src = this._argManager.getValByName("source");
if (!XB._base.runtime.isXML(src))
return new XB.types.Exception(this._getHumanReadableID(), XB.types.Exception.types.E_TYPE,
"Not XML, " + XB._base.runtime.describeValue(src));
return src.transform(stylesheet);
}
});
XB._functions.CN_attribute = XB._calcNodes.FuncNode.extend({
$name: "CN_attribute",
expectedArgNames: ["name", "value"],
_calculate: function FAttribute_calculate(changedArgs) {
var name = this._argManager.getValByName(this.expectedArgNames[0], "String");
var value = this._argManager.getValByName(this.expectedArgNames[1], "String");
var result = new XB.types.XML();
result.addAttribute("", name, value);
return result;
}
});
XB._functions["CN_serialize-xml"] = XB._calcNodes.FuncNode.extend({
$name: "CN_serialize-xml",
expectedArgNames: ["source"],
_calculate: function FSerializeXml_calculate(changedArgs) {
var src = this._argManager.getValByName("source");
if (!XB._base.runtime.isXML(src))
return new XB.types.Exception(this._getHumanReadableID(), XB.types.Exception.types.E_TYPE,
"Not XML, " + XB._base.runtime.describeValue(src));
return src.serialize();
}
});
XB._functions["CN_value-of"] = XB._calcNodes.FuncNode.extend({
$name: "CN_value-of",
expectedArgNames: ["name"],
_calculate: function Fvalueof_calculate(changedArgs) {
if (!this._refNode || this._argManager.argInArray("name", changedArgs))
this._findRefNode();
return this._refNode.getValue(this._hasSubscribers()? this: null);
},
_notNeeded: function Fvalueof__notNeeded() {
if (this._refNode) {
this._refNode.unsubscribe(this);
this._refNode = null;
}
},
_findRefNode: function Fvalueof_findRefNode() {
var refName = this._argManager.getValByName("name", "String");
var refNode = this._parentWidget.findData(refName);
if (!refNode)
refNode = this._parentWidget.findVariable(refName);
if (!refNode)
refNode = this._parentWidget.findSetting(refName);
if (!refNode)
throw new Error(XB._base.consts.ERR_DATA_UNDEFINED + " (" + refName + ")");
if (this._refNode != refNode) {
if (this._refNode)
this._refNode.unsubscribe(this);
this._refNode = refNode;
}
},
_refNode: null
});
XB._functions["CN_is-empty"] = XB._calcNodes.FuncNode.extend({
$name: "CN_is-empty",
expectedArgNames: ["value", "mode"],
_calculate: function Fisempty_calculate(changedArgs) {
var what = this._argManager.getValByName("value");
var modeStr = this._argManager.getValByNameDef("mode", "String", "default");
var strict = false;
switch (modeStr) {
case "strict":
strict = true;
break;
case "default":
strict = false;
break;
default:
throw new SyntaxError("Unknown mode \"" + modeStr + "\"");
}
return XB._functions["CN_is-empty"].test(what, strict);
}
});
XB._functions["CN_is-empty"].test = function EmptyTest(what, strict) {
if (strict)
return what === XB.types.empty;
return ( sysutils.strcmp(XB._base.runtime.xToString(what), "") == 0 )
};
XB._functions.Comparision = XB._calcNodes.FuncNode.extend({
$name: "Comparision",
expectedArgNames: ["left", "right", "mode"],
_calculate: function FComparision_calculate(changedArgs) {
var mode = this._argManager.getValByNameDef("mode", "String", "default");
var cmpMode;
switch (mode) {
case "strict":
cmpMode = XB._base.runtime.cmpModes.CMP_STRICT;
break;
case "default":
cmpMode = XB._base.runtime.cmpModes.CMP_FREE;
break;
default:
throw new Error("Unknown mode \"" + mode + "\"");
}
var left = this._argManager.getValByName("left");
var right = this._argManager.getValByName("right");
return this._op( XB._base.runtime.compareValues(left, right, cmpMode) );
}
});
XB._functions.CN_eq = XB._functions.Comparision.extend({
$name: "CN_eq",
_op: function Feq_op(compResult) {
return compResult == 0;
}
});
XB._functions.CN_equal = XB._functions.CN_eq;
XB._functions.CN_neq = XB._functions.CN_eq.extend({
$name: "CN_neq",
_op: function Fneq_op(compResult) {
return !this.base(compResult);
}
});
XB._functions["CN_not-equal"] = XB._functions.CN_neq;
XB._functions.Relation = XB._calcNodes.FuncNode.extend({
$name: "Relation",
expectedArgNames: ["left", "right", "mode"],
_calculate: function FRelation_calculate(changedArgs) {
var convType = undefined;
var mode = this._argManager.getValByNameDef("mode", "String", "number");
switch (mode) {
case "number":
convType = "Number";
break;
case "string":
convType = "String";
break;
case "smart":
break;
default:
throw new Error("Unknown mode \"" + mode + "\"");
}
var left = this._argManager.getValByName("left", convType);
var right = this._argManager.getValByName("right", convType);
var cmpMode = XB._base.runtime.cmpModes[!!convType ? "CMP_STRICT" : "CMP_SMART"];
return this._op( XB._base.runtime.compareValues(left, right, cmpMode) );
}
});
XB._functions.CN_lt = XB._functions.Relation.extend({
$name: "CN_lt",
_op: function Flt_op(compResult) {
return compResult < 0;
}
});
XB._functions.CN_lte = XB._functions.Relation.extend({
$name: "CN_lte",
_op: function Flte_op(compResult) {
return compResult <= 0;
}
});
XB._functions.CN_gt = XB._functions.Relation.extend({
$name: "CN_gt",
_op: function Fgt_op(compResult) {
return compResult > 0;
}
});
XB._functions.CN_gte = XB._functions.Relation.extend({
$name: "CN_gte",
_op: function Fgte_op(compResult) {
return compResult >= 0;
}
});
XB._functions.CN_not = XB._calcNodes.FuncNode.extend({
$name: "CN_not",
_calculate: function Fnot_calculate(changedArgs) {
return !(this._argManager.getValByIndex(0, "Bool"));
}
});
XB._functions.CN_or = XB._calcNodes.FuncNode.extend({
$name: "CN_or",
_calculate: function For_calculate(changedArgs) {
if (this._argManager.argsCount < 1)
throw new Error("No arguments");
for (let i = 0, len = this._argManager.argsCount; i < len; i++) {
var val = this._argManager.getValByIndex(i);
if (XB._base.runtime.xToBool(val))
return true;
}
return false;
}
});
XB._functions.CN_coalesce = XB._calcNodes.FuncNode.extend({
$name: "CN_coalesce",
_calculate: function Fcoalesce_calculate(changedArgs) {
let strictMode = false;
var modeStr = this._argManager.getValByNameDef("mode", "String", "default");
switch (modeStr) {
case "default":
strictMode = false;
break;
case "strict":
strictMode = true;
break;
default:
throw new SyntacError("Unknown mode \"" + modeStr + "\"");
}
for each (let argName in this._argManager.argsNames) {
if (argName == "mode")
continue;
var val = this._argManager.getValByName(argName);
if (!XB._functions["CN_is-empty"].test(val, strictMode))
return val;
}
return XB.types.empty;
}
});
XB._functions.CN_and = XB._calcNodes.FuncNode.extend({
$name: "CN_and",
_calculate: function Fand_calculate(changedArgs) {
if (this._argManager.argsCount < 1)
throw new Error("No arguments");
for (let i = 0, len = this._argManager.argsCount; i < len; i++) {
let val = this._argManager.getValByIndex(i);
let asBool = XB._base.runtime.xToBool(val);
if (!asBool)
return false;
}
return true;
}
});
XB._functions.CN_try = XB._calcNodes.FuncNode.extend({
$name: "CN_try",
expectedArgNames: ["expression", "..."],
_calculate: function Ftry_calculate(changedArgs) {
try {
return this._argManager.getValByName(this.expectedArgNames[0]);
}
catch (origException) {
if (!(origException instanceof XB.types.Exception))
throw origException;
if (origException.type == XB.types.Exception.types.E_RETHROW) {
origException = new XB.types.Exception(origException.srcNodeUid, XB.types.Exception.types.E_GENERIC, origException.message);
}
if (this._debugMode)
this._parentWidget.logger.debug(this._getHumanReadableID() + " cought exception: " + origException.toString());
this._findHandler(origException.type);
if (this._usedHandler) {
var handlerVal = this._usedHandler.getValue(this._hasSubscribers()? this: null);
if (handlerVal instanceof XB.types.Exception) {
if (this._debugMode)
this._parentWidget.logger.debug(this._getHumanReadableID() + " exception rethrown with type " + handlerVal.type);
switch (handlerVal.type) {
case XB.types.Exception.types.E_RETHROW:
handlerVal = origException;
break;
case XB.types.Exception.types.E_LASTVALUE:
handlerVal = this._storedValue;
break;
}
}
if (this._debugMode)
this._parentWidget.logger.debug(this._getHumanReadableID() + " exception handler returned " + handlerVal);
return handlerVal;
}
return origException;
}
},
_findHandler: function (exceptionType) {
var handler = this._argManager.findNodeByName(exceptionType) ||
this._argManager.findNodeByName(this._consts.STR_ALL_EXCEPTIONS);
if (this._usedHandler != handler) {
if (this._usedHandler)
this._usedHandler.unsubscribe(this);
this._usedHandler = handler;
}
},
_notNeeded: function Ftry__notNeeded() {
if (this._usedHandler) {
this._usedHandler.unsubscribe(this);
this._usedHandler = null;
}
},
_usedHandler: null,
_consts: {
STR_ALL_EXCEPTIONS: "..."
}
});
XB._functions.CN_throw = XB._calcNodes.FuncNode.extend({
$name: "CN_throw",
expectedArgNames: ["type"],
_calculate: function Fthrow_calculate(changedArgs) {
var eType = this._argManager.getValByNameDef("type", "String", XB.types.Exception.types.E_RETHROW);
var Exception = new XB.types.Exception(this._getHumanReadableID(), eType, "XBTHROW");
var excPropVal;
var excPropsNames = this._argManager.argsNames;
for each (let propName in excPropsNames) {
if (propName == "type")
continue;
excPropVal = this._argManager.getValByName(propName);
Exception[propName] = excPropVal;
}
return Exception;
}
});
XB._functions.CN_lastvalue = XB._calcNodes.FuncNode.extend({
$name: "CN_lastvalue",
_calculate: function Flastvalue_calculate(changedArgs) {
var lastValException = new XB.types.Exception(this._getHumanReadableID(), XB.types.Exception.types.E_LASTVALUE,
"XBLASTVAL");
return lastValException;
}
});
XB._functions.CN_optional = XB._calcNodes.FuncNode.extend({
$name: "CN_optional",
expectedArgNames: ["condition"],
_calculate: function Foptional_calculate(changedArgs) {
var numArgs = this._argManager.argsCount;
if (numArgs > 1 && this._argManager.getValByName("condition", "Bool") ) {
return XB._functions.CN_concat.concatArgs(this, 1, numArgs - 1);
}
return XB.types.empty;
}
});
XB._functions.CN_cookie = XB._calcNodes.FuncNode.extend({
$name: "CN_cookie",
expectedArgNames: ["url", "name"],
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupports, Ci.nsIObserver, Ci.nsITimerCallback]),
observe: function Fcookie_observe(subject, topic, data) {
switch (topic) {
case "cookie-changed":
this._timer = XB._Cc["@mozilla.org/timer;1"].createInstance(XB._Ci.nsITimer);
this._timer.initWithCallback(this, 10, this._timer.TYPE_ONE_SHOT);
break;
default:
break;
}
},
notify: function () {
try {
if (this._setNewVal(this._cookie()))
this._notifyDeps();
}
catch (e) {
this._parentWidget.logger.error("CN_cookie.notify() failed. " + e.message);
}
finally {
this._timer = null;
}
},
_ioService: Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService),
_cookieService: Cc["@mozilla.org/cookieService;1"].getService().QueryInterface(Ci.nsICookieService),
_observerService: Cc["@mozilla.org/observer-service;1"].getService(Ci.nsIObserverService),
_observing: false,
_url: undefined,
_cookieName: undefined,
_timer: null,
_cookie: function Fcookie__cookie() {
var uri = this._ioService.newURI(this._url, null, null);
var cookieString = this._cookieService.getCookieString(uri, null);
if (!cookieString)
return XB.types.empty;
var cookies = cookieString.split(";");
for each (let cookie in cookies) {
let separatorPos = cookie.indexOf("=");
if (separatorPos == -1)
continue;
let cookieName = sysutils.trimAllSpaces( cookie.substring(0, separatorPos) );
if (cookieName == this._cookieName)
return unescape( cookie.substring(separatorPos + 1) );
}
return XB.types.empty;
},
_calculate: function Fcookie__calculate(changedArgs) {
if (this._argManager.argInArray("url", changedArgs) || this._url == undefined)
this._url = this._argManager.getValByName("url", "String");
if (this._argManager.argInArray("name", changedArgs) || !this._cookiePattern) {
this._cookieName = this._argManager.getValByName("name", "String");
}
if (!this._observing) {
this._observerService.addObserver(this, "cookie-changed", false);
this._observing = true;
}
return this._cookie();
},
_notNeeded: function Fcookie__notNeeded() {
if (this._observing) {
this._observerService.removeObserver(this, "cookie-changed");
this._observing = false;
}
}
});
XB._functions.CN_request = XB._calcNodes.FuncNode.extend({
$name: "CN_request",
expectedArgNames: ["url", "update", "expire", "format", "valid-status", "valid-xpath"],
_calculate: function Frequest_calculate(changedArgs) {
var format;
var formatStr = this._argManager.getValByNameDef("format", "String", "xml");
switch (formatStr) {
case "text":
format = XB.types.RequestData.Format.FMT_TEXT;
break;
case "xml":
format = XB.types.RequestData.Format.FMT_XML;
break;
case "json":
format = XB.types.RequestData.Format.FMT_JSON;
break;
default:
throw new Error("Unknown format specification: " + formatStr);
}
var validStatusRange = {start: 100, end: 399};
var statusesExpr = this._argManager.getValByNameDef("valid-status", "String", "");
if (statusesExpr) {
var matches = statusesExpr.match(/^(\d+)?\.\.(\d+)?$/);
if (matches != null) {
validStatusRange.start = matches[1]? parseInt(matches[1], 10) : 100;
validStatusRange.end = matches[2]? parseInt(matches[2], 10) : 399;
}
else {
this._parentWidget.logger.warn("Could not parse request status validation expression (" + statusesExpr + ")");
}
}
var updateInterval = this._argManager.getValByNameDef("update", "Number", 0)
|| Number.POSITIVE_INFINITY;
var reqData = new XB.types.RequestData(this._argManager.getValByName("url", "String"),
"GET",
updateInterval,
this._argManager.getValByNameDef("expire", "Number", 0),
format,
validStatusRange,
this._argManager.getValByNameDef("valid-xpath", "String"));
return reqData;
}
});
XB._functions.NetworkData = XB._calcNodes.FuncNode.extend({
$name: "NetworkData",
expectedArgNames: ["request"],
update: function FNetworkData_update(netResource, netData) {
if (netResource !== this._resource) {
this._parentWidget.logger.warn("Update notification from a martian network resource! " + this._getHumanReadableID());
return;
}
if (this._setNewVal(this._processResData(netData)))
this._notifyDeps();
},
_calculate: function FNetworkData_calculate(changedArgs) {
var reqData = this._argManager.getValByName("request", "RequestData");
var netResource = XB.network.getResource(reqData);
if (this._resource != netResource) {
if (this._resource)
try {
this._resource.unsubscribe(this, this._dataType);
}
catch (e) {
this._parentWidget.logger.error("Could not unsubscribe from a network resource. " +
misc.formatError(e));
this._parentWidget.logger.debug(e.stack);
}
this._resource = netResource;
}
var rawData = this._resource.requestData(this, this._dataType);
this._parentWidget.logger.trace("FNetworkData_calculate raw data is " + rawData);
return this._processResData(rawData) || XB.types.empty;
},
_resource: null,
_notNeeded: function FNetworkData_notNeeded() {
if (this._resource) {
this._resource.unsubscribe(this, this._dataType);
delete this._resource;
}
}
});
XB._functions.CN_content = XB._functions.NetworkData.extend({
$name: "CN_content",
_dataType: XB.network.ResourceDataType.NRDT_CONTENT,
_processResData: function Fcontent_processResData(content) {
if (!content)
return XB.types.empty;
if (content instanceof XB._Ci.nsIDOMDocument) {
return new XB.types.XML(content);
}
if (!sysutils.isString(content))
throw new TypeError("Network resource sent not an XML document, nor a String");
return content;
}
});
XB._functions.CN_header = XB._functions.NetworkData.extend({
$name: "CN_header",
expectedArgNames: ["request", "name"],
_dataType: XB.network.ResourceDataType.NRDT_HEADERS,
_calculate: function Fheader_calculate(changedArgs) {
if (this._argManager.argInArray("name", changedArgs) || !this._headerName) {
this._headerName = this._argManager.getValByName("name", "String");
}
return this.base(changedArgs);
},
_processResData: function Fheader_processResData(resHeaders) {
if (resHeaders)
return resHeaders[this._headerName];
},
_headerName: undefined
});
XB._functions.CN_finished = XB._calcNodes.FuncNode.extend({
$name: "CN_finished",
expectedArgNames: ["try-id"],
onRequestFinished: function Ffinished_onRequestFinished(requestID) {
if (this._requestID == requestID)
if (this._setNewVal(true))
this._notifyDeps();
this._requestID = undefined;
},
_calculate: function Ffinished_calculate(changedArgs) {
var requestID = this._argManager.getValByName(this.expectedArgNames[0], "Number");
if (XB.network.requestFinished(requestID)) return true;
XB.network.subscribeToRequestFinish(requestID, this);
this._requestID = requestID;
return false;
},
_requestID: undefined
});
XB._functions.CN_update = XB._calcNodes.ProcNode.extend({
$name: "CN_update",
expectedArgNames: ["request"],
_proc: function Fupdate_proc(eventInfo) {
var requestData = this._argManager.getValByName("request", "RequestData");
var netResource = XB.network.getResource(requestData);
return netResource.update(true);
}
});
XB._functions.CN_file = XB._calcNodes.FuncNode.extend({
$name: "CN_file",
expectedArgNames: ["path", "type"],
_calculate: function Ffile_calculate(changedArgs) {
var path = this._argManager.getValByName("path", "String");
var type = this._argManager.getValByNameDef("type", "String", "text");
var file = this._parentWidget.prototype.unit.unitPackage.findFile(path);
switch (type) {
case "xml":
return new XB.types.XML( sysutils.xmlDocFromFile(file) );
case "text":
return sysutils.readTextFile(file);
default:
throw new Error("Unsupported file output type");
}
}
});
XB._functions["CN_copy-to-clipboard"] = XB._calcNodes.ProcNode.extend({
$name: "CN_copy-to-clipboard",
constructor: function FCopyToClipboard_constructor() {
this.base.apply(this, arguments);
this._helper = XB._Cc["@mozilla.org/widget/clipboardhelper;1"].getService(XB._Ci.nsIClipboardHelper);
},
_helper: null,
_proc: function FcopyToClipboard_proc(eventInfo) {
this._helper.copyString(this._argManager.getValByIndex(0, "String"));
}
});
XB._functions.CN_navigate = XB._calcNodes.ProcNode.extend({
$name: "CN_navigate",
expectedArgNames: ["url", "target"],
_proc: function Fnavigate_proc(eventInfo) {
var url = this._argManager.getValByName("url", "String");
var target = this._argManager.getValByNameDef("target", "String", "");
if (eventInfo.keys.ctrl || eventInfo.keys.meta || eventInfo.mouse.button == 1)
target = "new tab";
else if (eventInfo.keys.shift)
target = "new window";
var yandexAction = this._argManager.getValByNameDef("action", "String", "");
var windowWidth = this._argManager.getValByNameDef("width", "Number", 50);
var windowHeight = this._argManager.getValByNameDef("height", "Number", 50);
this._parentWidget.host.navigate(url, target, windowWidth, windowHeight, yandexAction,
this._parentWidget.prototype);
}
});
XB._functions["CN_setup-widget"] = XB._calcNodes.ProcNode.extend({
$name: "CN_setup-widget",
_proc: function FSetupWidget_proc(eventInfo) {
this._parentWidget.host.setupWidget(this._parentWidget);
}
});
XB._functions["CN_add-widget"] = XB._calcNodes.ProcNode.extend({
$name: "CN_add-widget",
_proc: function FAddWidget_proc(eventInfo) {
if (this._parentWidget.prototype.isUnique)
throw new Error("This widget is unique!");
this._parentWidget.host.addWidget(this._parentWidget.prototype.id, undefined, this._parentWidget, true);
}
});
XB._functions["CN_remove-widget"] = XB._calcNodes.ProcNode.extend({
$name: "CN_remove-widget",
_proc: function FRemoveWidget_proc(eventInfo) {
this._parentWidget.host.removeWidget(this._parentWidget.id);
}
});