VivoQuant 6.5.0
Loading...
Searching...
No Matches
Script Settings with SettingsTab.vqs

SettingsTab.vqs is installed with VivoQuant, so a script can use it with #include "SettingsTab.vqs". It builds a ScriptPanel tab from a table of settings, and reads, checks and writes the settings file.

Example

#include "SettingsTab.vqs"
// Automated tests (VQ_TEST_MODE) keep the settings file in their own run folder rather than
// next to the script, and don't remember it in ~/.vqsconfig
var isTest = VQ.isTestMode();
var runFolder = String(VQ.getCache()).replace(/\\/g, '/').replace(/\/+$/, '');
runFolder = runFolder.substring(0, runFolder.lastIndexOf('/') + 1);
//---------------------------------------------------------
// Settings example: the SettingsTab.vqs step of the Script Panel Tutorial workflow
// (script-panel.md). Run it from the tutorial, or with Script > Open VivoScript.
//
// SettingsTab.vqs (installed with VivoQuant) gives a script settings that are kept in a
// file, and a "Settings" tab on the script panel to check and edit them before the script
// runs. Describe the settings in a table; run() does the rest:
// - opens the file used last time (or defaultFile, or asks for one)
// - shows it on the tab, and checks each value as the user types
// - waits until the user presses Run with valid settings
// - saves them if anything changed, and returns them
// The file is plain text, one "key = value" per line, so it can also be edited by hand or
// kept with a study. The full list of options is at the top of SettingsTab.vqs.
//---------------------------------------------------------
// The panel keeps its contents between scripts: start empty. Removing the default tab
// leaves just the Settings tab, until the script places something on another tab.
var panel = VQ.scriptPanel();
panel.clear();
panel.removeTab('');
var settings = new SettingsTab({
// First line of the comment at the top of the file
title: 'Settings for settings-example.vqs',
// Where the settings are kept: next to the script, unless the path is absolute
defaultFile: isTest ? runFolder + 'settings-example.txt' : 'settings-example-settings.txt',
// Remember the file used last time in ~/.vqsconfig, under this key (leave out to always
// start with defaultFile)
configKey: isTest ? undefined : 'settingsTabExample',
// Each group is a section of the tab, and a heading in the file
groups: [
{ id: 'data', label: 'Data' },
{ id: 'output', label: 'Output' }
],
// One entry per setting. 'help' is the tooltip, and a comment in the file.
settings: [
{ key: 'server', group: 'data', label: 'Server', type: 'text', required: true,
default: 'ipacss://example.org/', help: 'iPACS server URL',
check: function (v) { return /\/$/.test(v) ? '' : "must end with '/'"; } },
{ key: 'dateStart', group: 'data', label: 'Studies from', type: 'date', required: true, default: '20260101' },
{ key: 'dateEnd', group: 'data', label: 'Studies to', type: 'date', required: true, default: '20261231' },
{ key: 'modality', group: 'data', label: 'Modality', type: 'item', items: ['CT', 'PT', 'SPECT'] },
{ key: 'rois', group: 'data', label: 'ROIs', type: 'list', default: ['Liver', 'Kidney'],
help: 'ROIs to measure' },
{ key: 'repeats', group: 'output', label: 'Repeats', type: 'int', min: 1, max: 10, default: 3 },
{ key: 'threshold', group: 'output', label: 'Threshold', type: 'double', min: 0, max: 1,
decimals: 3, default: 0.25 },
{ key: 'upload', group: 'output', label: 'Upload results', type: 'bool', default: true }
],
// Checks that involve several settings; run on every edit and on Run
validate: function (v) {
var dates = SettingsFile.validDate(v.dateStart) && SettingsFile.validDate(v.dateEnd);
return dates && v.dateStart > v.dateEnd ? ['Studies from is after Studies to'] : [];
}
});
// Shows the Settings tab and waits for Run. Returns { server: ..., dateStart: ..., ... }.
// settings.file is then the file used.
var params = settings.run();
VQ.debug("Settings: " + JSON.stringify(params));
// From here the Settings tab is a read-only record of the settings in use. The script can
// add its own tabs and fields; keep their names from starting with 'set_', the tab's prefix.
params.rois.forEach(function (roi, i) {
panel.setValue('progress_' + roi, 'Measured', 'Progress');
// ... the real work for each ROI goes here ...
});
panel.setCurrentTab('Progress');
// A script that only reads its settings, without letting the user change them, can call
// settings.view() instead of run(): it shows the file read-only and returns
// { file, values, problems, warnings, isNew } without waiting.
// Automated tests close VivoQuant here
if (isTest) {
VQ.quit();
}

Reference

The options, setting types and file format are described at the top of the library:

/*
* SettingsTab.vqs - a script's settings: a settings file defined by a table, and a
* script panel tab to check and edit it before the script runs.
*
* #include it at the top of the script: the constructors below are set up when this
* file runs, so they can't be used before the #include line.
*
* Quick start:
*
* #include "SettingsTab.vqs"
*
* var settings = new SettingsTab({
* title: 'My tool settings', // first line of the file's header comment
* defaultFile: 'MyToolSettings.txt', // next to the script, unless absolute
* configKey: 'myToolSettings', // remember the last file in ~/.vqsconfig
* groups: [ { id: 'data', label: 'Data' } ],
* settings: [
* { key: 'url', group: 'data', label: 'Server', type: 'text', required: true,
* help: 'iPACS server URL' },
* { key: 'mode', group: 'data', label: 'Mode', type: 'item', items: ['Fast', 'Full'] }
* ]
* });
* var params = settings.run(); // { url: ..., mode: ... }
*
* run() picks the file (the one used last time, else defaultFile, else asks), shows it
* on the tab, waits until the user presses Run with valid settings, saves them to the
* file if anything changed and returns the values. The file used is then settings.file.
* The tab then stays as a read-only record of the settings in use, with a note (also in
* the status line) that they are for reference and that changing them means running the
* script again.
*
* A script that only reads its settings can call view() instead of run(): it shows the same
* file the same way run() leaves the tab (read-only, with a note), without waiting, and
* returns the values and any problems. It never changes the file.
*
* While waiting, the tab has "Use another file", which picks an existing file. When the file
* shown isn't defaultFile (for example a file remembered from another folder), it also has
* "Use the default file": it opens defaultFile, or if that doesn't exist yet, switches to it
* keeping the settings shown, so Run creates it with them.
*
* Groups: each entry of options.groups is { id, label }, a section of the tab, in order
* id used by the settings' group: letters, digits and _, not starting with a digit
* label title of the section, and heading in the file (default: id)
* A group with no settings isn't shown.
*
* Settings: each entry of options.settings, shown in order within its group
* key name in the file and in the returned values (case-sensitive): letters,
* digits and _, not starting with a digit, e.g. dateStart
* group id of one of options.groups: the section of the tab it is shown in
* label text on the tab (default: key)
* type 'text' (default), 'item', 'bool', 'date' (YYYYMMDD), 'list' (of text),
* 'int' or 'double'
* items for 'item': the allowed values; editable: true also allows other text
* min, max for 'int' and 'double': the allowed range
* decimals for 'double': decimals shown on the tab, 0 to 15 (default: as many as the
* value needs, at least 2). The tab rounds what is typed to these decimals.
* required for text, item, date: must not be empty
* default value when the file doesn't set it (default: empty, false, [] or 0, or the
* nearest number in the range; for a non-editable item, its first item). It
* must suit the type: a string, true or false, an array of strings, or a number
* in the range; an item that is one of the items; a date as YYYYMMDD or ''.
* help tooltip on the tab, and comment above the key in the file
* check optional function (value) returning a problem ('' or nothing when fine),
* e.g. "must end with '/'". Not called for an empty, optional value.
*
* The definitions are checked strictly when the SettingsFile or SettingsTab is made: an
* unknown property, or one the type doesn't use (e.g. 'items' on a text setting, or a
* misspelt 'requird'), an unknown type or group, a duplicate key, or a default that doesn't
* suit the type throws an Error naming the setting.
*
* Settings file format. Files are read leniently where it is safe, and are rewritten in
* this form when the user changes anything, or when the file has problems:
* - one "key = value" per line; lines starting with // or # are comments
* - only the defined keys, each at most once; others are reported, then dropped on save
* - text, item and date values in quotes: url = 'ipacss://...' (quotes optional when read)
* - item values are matched without regard to case when read: mode = fast
* - bool: true or false (1 and 0 are accepted when read)
* - list: ['Liver', 'Kidney'], or [] for none; an entry in quotes may contain commas.
* On the tab a list is typed the same way without the [ ]: Liver, 'Kidney, left'
* - int and double: plain numbers
*
* Other options:
* validate function (values) returning an array of problems that involve several
* settings, e.g. a start date after an end date; checked on every edit and Run
* tab name of the panel tab (default 'Settings')
* prefix start of the tab's field names (default 'set_'): a setting's field is
* prefix + key, and the tab's own controls are prefix + '-' + something,
* so neither can clash with the other; keep the script's own field names
* from starting with the prefix
* runButton text of the button (default 'Run')
* dialogTitle title of the file dialog (default 'Select the settings file')
* dialogDir folder the file dialog starts in (default: the script's folder)
* configFile where configKey is kept (default ~/.vqsconfig)
* panel the script panel (default VQ.scriptPanel())
*
* The file layer works without a panel, e.g. to check a file in a batch run:
* var file = new SettingsFile(options); // the same options
* var read = file.read(path); // { values, problems, unusable, failedChecks, isNew }
* var all = file.problems(read.values); // what run() would refuse, by label
*
* The Script Panel Tutorial in the Workflow Assistant has a complete script using it
* (workflows/script-panel/settings-example.vqs).
*/
/* ---------------------------------------------------------------------------------
* SettingsFile: the definitions, and reading, checking and writing settings files
* --------------------------------------------------------------------------------- */
function SettingsFile(options) {
if (!options || !(options.settings instanceof Array) || !(options.groups instanceof Array)) {
throw new Error('SettingsFile: options.settings and options.groups must be arrays');
}
this.options = options;
this.groups = options.groups;
this.settings = options.settings;
var groupIds = [];
this.groups.forEach(function (g) {
if (!SettingsFile.isName(g.id)) {
throw new Error("SettingsFile: group id '" + g.id + "' is not allowed; " + SettingsFile.NAME_RULES);
}
if (groupIds.indexOf(g.id) >= 0) throw new Error("SettingsFile: group '" + g.id + "' is defined twice");
for (var p in g) {
if (p !== 'id' && p !== 'label') {
throw new Error("SettingsFile: group '" + g.id + "' has unknown property '" + p + "'");
}
}
g.label = g.label || g.id;
groupIds.push(g.id);
});
var seen = Object.create(null);
this.settings.forEach(function (d) {
if (!d.key) throw new Error('SettingsFile: a setting has no key');
if (!SettingsFile.isName(d.key)) {
throw new Error("SettingsFile: key '" + d.key + "' is not allowed; " + SettingsFile.NAME_RULES);
}
if (seen[d.key]) throw new Error("SettingsFile: setting '" + d.key + "' is defined twice");
seen[d.key] = true;
if (groupIds.indexOf(d.group) < 0) {
throw new Error("SettingsFile: setting '" + d.key + "' has unknown group '" + d.group + "'");
}
d.type = d.type || 'text';
if (SettingsFile.TYPES.indexOf(d.type) < 0) {
throw new Error("SettingsFile: setting '" + d.key + "' has unknown type '" + d.type + "'");
}
// Strict, as the script panel is: a misspelt property is an error, not silently ignored
var allowed = SettingsFile.COMMON_PROPERTIES.concat(SettingsFile.TYPE_PROPERTIES[d.type]);
for (var p in d) {
if (allowed.indexOf(p) < 0) {
throw new Error("SettingsFile: setting '" + d.key + "' has unknown property '" + p +
"' for type '" + d.type + "'");
}
}
if (d.type === 'item' && !(d.items instanceof Array && d.items.length &&
d.items.every(function (x) { return typeof x === 'string'; }))) {
throw new Error("SettingsFile: item setting '" + d.key + "' needs items");
}
['min', 'max'].forEach(function (p) {
if (d[p] !== undefined && !(typeof d[p] === 'number' && isFinite(d[p]))) {
throw new Error("SettingsFile: setting '" + d.key + "': '" + p + "' must be a number");
}
});
if (d.min !== undefined && d.max !== undefined && d.min > d.max) {
throw new Error("SettingsFile: setting '" + d.key + "': 'min' is more than 'max'");
}
if (d.decimals !== undefined && !(typeof d.decimals === 'number' && Math.floor(d.decimals) === d.decimals &&
d.decimals >= 0 && d.decimals <= 15)) {
throw new Error("SettingsFile: setting '" + d.key + "': 'decimals' must be a whole number from 0 to 15");
}
if (d.check !== undefined && typeof d.check !== 'function') {
throw new Error("SettingsFile: setting '" + d.key + "': 'check' must be a function");
}
d.label = d.label || d.key;
d.help = d.help || '';
if (d.default !== undefined) {
var problem = SettingsFile.defaultProblem(d);
if (problem) throw new Error("SettingsFile: setting '" + d.key + "': default " + problem);
}
});
}
SettingsFile.TYPES = ['text', 'item', 'bool', 'date', 'list', 'int', 'double'];
// The properties a setting may have: these, and those of its type
SettingsFile.COMMON_PROPERTIES = ['key', 'group', 'label', 'type', 'default', 'help', 'check'];
SettingsFile.TYPE_PROPERTIES = {
text: ['required'],
item: ['required', 'items', 'editable'],
date: ['required'],
bool: [],
list: [],
int: ['min', 'max'],
double: ['min', 'max', 'decimals']
};
// What is wrong with d.default for d's type, or ''. The setting's own check isn't run on it:
// a default may be a placeholder the user must change, such as an empty required setting.
SettingsFile.defaultProblem = function (d) {
var v = d.default;
switch (d.type) {
case 'bool':
return typeof v === 'boolean' ? '' : 'must be true or false';
case 'list':
return v instanceof Array && v.every(function (x) { return typeof x === 'string'; })
? '' : 'must be an array of strings';
case 'int':
case 'double':
if (typeof v !== 'number' || !isFinite(v)) return 'must be a number';
if (d.type === 'int' && Math.floor(v) !== v) return 'must be a whole number';
if ((d.min !== undefined && v < d.min) || (d.max !== undefined && v > d.max)) {
return 'must be from ' + (d.min !== undefined ? d.min : '-') + ' to ' + (d.max !== undefined ? d.max : '-');
}
return '';
default: // text, item, date
if (typeof v !== 'string') return 'must be a string';
if (d.type === 'item' && !d.editable && d.items.indexOf(v) < 0) {
return "'" + v + "' is not one of: " + d.items.join(', ');
}
if (d.type === 'date' && v !== '' && !SettingsFile.validDate(v)) return "'" + v + "' is not a date as YYYYMMDD";
return '';
}
};
/**
* Decimals a double field needs to show v exactly: d.decimals if the setting sets it, else
* as many as v needs, at least 2. The field rounds its value to its decimals, so too few
* would silently change a value read from the file.
*/
SettingsFile.decimalsFor = function (d, v) {
if (d.decimals !== undefined) return d.decimals;
for (var n = 2; n < 15; n++) {
if (Number(v.toFixed(n)) === v) return n;
}
return 15;
};
// Setting keys and group ids. A '-' can't start one, which keeps the tab's own controls
// (prefix + '-...') apart from the settings (prefix + key).
SettingsFile.NAME_RULES = "use letters, digits and _, not starting with a digit, and not '__proto__'";
SettingsFile.isName = function (s) {
return typeof s === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(s) && s !== '__proto__';
};
SettingsFile.unquote = function (s) {
var q = s.charAt(0);
if (s.length >= 2 && (q === "'" || q === '"') && s.charAt(s.length - 1) === q) {
return s.substring(1, s.length - 1);
}
return s;
};
// Values are written in quotes, so a value can't contain both kinds
SettingsFile.quote = function (s) {
return s.indexOf("'") >= 0 ? '"' + s + '"' : "'" + s + "'";
};
/**
* Reads a list of entries separated by commas, as in the file (between the [ ]) and on the
* tab: "a, 'b, c', \"d'e\"" -> ['a', 'b, c', "d'e"]. An entry in quotes, ' or ", keeps
* everything between them, commas and spaces included; any other entry is trimmed and ends
* at the next comma. Empty entries are dropped. Returns { items }, or { error } for an
* entry whose quote isn't closed or is followed by more text.
*/
SettingsFile.parseList = function (s) {
var items = [], i = 0, n = s.length, entry = 0;
var skipSpace = function () { while (i < n && /\s/.test(s.charAt(i))) i++; };
while (true) {
skipSpace();
entry++;
var item, q = s.charAt(i);
if (i < n && (q === "'" || q === '"')) {
var end = s.indexOf(q, i + 1);
if (end < 0) return { error: 'entry ' + entry + ' has no closing ' + q };
item = s.substring(i + 1, end);
i = end + 1;
skipSpace();
if (i < n && s.charAt(i) !== ',') return { error: 'entry ' + entry + ' has more text after its closing ' + q };
} else {
var comma = s.indexOf(',', i);
if (comma < 0) comma = n;
item = s.substring(i, comma).trim();
i = comma;
}
if (item !== '') items.push(item);
if (i >= n) break;
i++; // past the comma
}
return { items: items };
};
/**
* A list as the tab shows it, in the form parseList reads back to the same entries. An
* entry is quoted only when it has to be: it contains a comma, starts or ends with a space,
* or starts with a quote. So everyday lists read naturally: Liver, O'Brien.
*/
SettingsFile.listText = function (items) {
return items.map(function (x) {
var plain = x.indexOf(',') < 0 && x === x.trim() && x.charAt(0) !== "'" && x.charAt(0) !== '"';
return plain ? x : SettingsFile.quote(x);
}).join(', ');
};
SettingsFile.validDate = function (s) {
if (!/^\d{8}$/.test(s)) return false;
var year = parseInt(s.substr(0, 4), 10);
var month = parseInt(s.substr(4, 2), 10), day = parseInt(s.substr(6, 2), 10);
var leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
var days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return year >= 1 && month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1];
};
SettingsFile.prototype.def = function (key) {
for (var i = 0; i < this.settings.length; i++) {
if (this.settings[i].key === key) return this.settings[i];
}
return null;
};
/** Value of every setting before a file is read: its default, or empty. */
SettingsFile.prototype.defaults = function () {
var values = {};
this.settings.forEach(function (d) {
if (d.default !== undefined) {
values[d.key] = (d.default instanceof Array) ? d.default.slice() : d.default;
} else if (d.type === 'bool') {
values[d.key] = false;
} else if (d.type === 'list') {
values[d.key] = [];
} else if (d.type === 'int' || d.type === 'double') {
// 0, or the nearest number in the range
var n = 0;
if (d.min !== undefined && n < d.min) n = d.min;
if (d.max !== undefined && n > d.max) n = d.max;
if (d.type === 'int' && Math.floor(n) !== n) n = Math.ceil(n); // a fractional min
values[d.key] = n;
} else if (d.type === 'item' && !d.editable) {
values[d.key] = d.items[0]; // the panel can only show one of the items
} else {
values[d.key] = '';
}
});
return values;
};
/** What is wrong with value v of setting d, or '' if nothing. */
SettingsFile.prototype.check = function (d, v) {
var bothQuotes = function (s) { return s.indexOf("'") >= 0 && s.indexOf('"') >= 0; };
var problem = '';
switch (d.type) {
case 'bool':
break;
case 'list':
if (v.some(bothQuotes)) problem = 'entries can\'t contain both \' and "';
break;
case 'int':
case 'double':
if (typeof v !== 'number' || !isFinite(v)) problem = 'needs a number';
else if (d.type === 'int' && Math.floor(v) !== v) problem = 'needs a whole number';
else if (d.min !== undefined && v < d.min) problem = 'must be at least ' + d.min;
else if (d.max !== undefined && v > d.max) problem = 'must be at most ' + d.max;
break;
default: // text, item, date
if (v === '') {
problem = d.required ? 'needs a value' : '';
} else if (bothQuotes(v)) {
problem = 'can\'t contain both \' and "';
} else if (d.type === 'date' && !SettingsFile.validDate(v)) {
problem = "'" + v + "' is not a date as YYYYMMDD";
} else if (d.type === 'item' && !d.editable && d.items.indexOf(v) < 0) {
problem = "'" + v + "' is not one of: " + d.items.join(', ');
}
}
if (!problem && d.check && !(v === '' && !d.required)) {
problem = d.check(v) || '';
}
return problem;
};
/**
* What is wrong with values: each setting, labelled, then options.validate. An array of
* problems, empty if there are none.
*/
SettingsFile.prototype.problems = function (values) {
var self = this, problems = [];
this.settings.forEach(function (d) {
var p = self.check(d, values[d.key]);
if (p) problems.push(d.label + ' (' + d.key + ') ' + p);
});
if (this.options.validate) {
problems = problems.concat(this.options.validate(values) || []);
}
return problems;
};
// Parses the text after '=' for setting d. Returns { value } or { error, value }:
// value is what to show on the tab, if there is anything usable.
SettingsFile.prototype.parse = function (d, raw) {
var v;
switch (d.type) {
case 'bool':
var b = raw.toLowerCase();
if (b === 'true' || b === '1') return { value: true };
if (b === 'false' || b === '0') return { value: false };
return { error: "'" + raw + "' is not true or false" };
case 'list':
if (raw.charAt(0) !== '[' || raw.charAt(raw.length - 1) !== ']') {
return { error: "'" + raw + "' is not a list like ['a', 'b'] or []" };
}
var list = SettingsFile.parseList(raw.substring(1, raw.length - 1));
if (list.error) return { error: list.error };
v = list.items;
break;
case 'int':
case 'double':
var text = SettingsFile.unquote(raw);
v = text === '' ? NaN : Number(text);
if (!isFinite(v)) return { error: "'" + raw + "' is not a number" };
break;
case 'item':
v = SettingsFile.unquote(raw);
for (var i = 0; i < d.items.length; i++) {
if (d.items[i].toLowerCase() === v.toLowerCase()) v = d.items[i];
}
break;
default:
v = SettingsFile.unquote(raw);
}
var problem = this.check(d, v);
return problem ? { error: problem, value: v } : { value: v };
};
/**
* Reads a settings file. Returns { values, problems, unusable, failedChecks, isNew }: a value
* for every setting (the default where the file has none or an unusable one), what is wrong
* with the file, and whether the file doesn't exist yet (then values are all defaults).
* unusable: the problems where the file asks for something the values don't have, because
* the default was used instead (a value that can't be read, a line without '=', a key in
* the wrong case, a missing required setting with a default). These are also in problems.
* failedChecks: the problems with values that were read and kept but fail a check (or a
* missing required setting left empty). They are also in problems, and problems() reports
* them again, by label, for as long as the value isn't fixed; so the tab shows them once.
*/
SettingsFile.prototype.read = function (path) {
var values = this.defaults(), problems = [], unusable = [], failedChecks = [], setOnLine = Object.create(null);
var self = this;
if (!VQ.fileExists(path)) {
return { values: values, problems: [], unusable: [], failedChecks: [], isNew: true };
}
var lines = VQ.readFile(path);
for (var i = 0; i < lines.length; i++) {
var line = String(lines[i]).trim();
if (line === '' || line.indexOf('//') === 0 || line.charAt(0) === '#') continue;
var where = 'line ' + (i + 1);
var eq = line.indexOf('=');
if (eq < 0) {
// Can't tell which setting it meant to set, so it may be one the values miss
problems.push(where + ": expected 'key = value'");
unusable.push(problems[problems.length - 1]);
continue;
}
var key = line.substring(0, eq).trim();
var raw = line.substring(eq + 1).trim().replace(/;$/, '').trim();
var d = this.def(key);
if (!d) {
var meant = this.settings.filter(function (s) { return s.key.toLowerCase() === key.toLowerCase(); })[0];
if (meant) {
// Almost certainly that setting, which then keeps its default
problems.push(where + ": unknown setting '" + key + "'; keys are case-sensitive, did you mean " + meant.key + '?');
unusable.push(problems[problems.length - 1]);
} else {
problems.push(where + ": unknown setting '" + key + "' (keys are case-sensitive); it is dropped when saved");
}
continue;
}
if (setOnLine[key]) {
problems.push(where + ': ' + key + ' is also set on line ' + setOnLine[key] + '; using this one');
}
setOnLine[key] = i + 1;
var r = this.parse(d, raw);
// An item that isn't one of the items can't be shown, so it keeps the default
if (r.value !== undefined && !(r.error && d.type === 'item' && !d.editable)) {
values[key] = r.value;
if (r.error) {
problems.push(where + ': ' + key + ' ' + r.error); // problems() reports it too
failedChecks.push(problems[problems.length - 1]);
}
} else if (r.error) {
problems.push(where + ': ' + key + ' ' + r.error + "; this value isn't used");
unusable.push(problems[problems.length - 1]);
}
}
this.settings.forEach(function (d) {
if (d.required && !setOnLine[d.key]) {
problems.push(d.key + ' is missing');
// With an empty default, problems() reports it anyway ("needs a value")
if (!self.check(d, values[d.key])) unusable.push(problems[problems.length - 1]);
else failedChecks.push(problems[problems.length - 1]);
}
});
// options.validate isn't run here: problems() runs it on the values, wherever they came from
return { values: values, problems: problems, unusable: unusable, failedChecks: failedChecks, isNew: false };
};
SettingsFile.prototype.formatValue = function (d, v) {
if (d.type === 'bool') return v ? 'true' : 'false';
if (d.type === 'list') return '[' + v.map(SettingsFile.quote).join(', ') + ']';
if (d.type === 'int' || d.type === 'double') return String(v);
return SettingsFile.quote(v);
};
/** The settings file for values, in the standard form, with each setting's help as a comment. */
SettingsFile.prototype.format = function (values) {
var self = this;
var out = [];
if (this.options.title) out.push('// ' + this.options.title);
out.push("// One 'key = value' per line; lines starting with // are comments.",
"// Text in quotes, true or false, dates as 'YYYYMMDD', lists as ['a', 'b'] or [].");
this.groups.forEach(function (g) {
out.push('', '// ' + g.label.toUpperCase());
self.settings.forEach(function (d) {
if (d.group !== g.id) return;
var choices = d.type === 'item' ? '(' + d.items.join(', ') + (d.editable ? ', or another' : '') + ')' : '';
var comment = [d.help, choices].filter(function (x) { return x; }).join(' ');
if (comment) out.push('// ' + comment);
out.push(d.key + ' = ' + self.formatValue(d, values[d.key]));
});
});
return out.join('\n') + '\n';
};
/** Writes values to path, in the standard form. Throws an Error if the file can't be written. */
SettingsFile.prototype.write = function (path, values) {
if (!VQ.writeFile(path, this.format(values))) {
throw new Error('Could not write the settings file ' + path);
}
};
/* ---------------------------------------------------------------------------------
* SettingsTab: the settings file on a script panel tab
* --------------------------------------------------------------------------------- */
function SettingsTab(options) {
this.options = options;
this.settingsFile = new SettingsFile(options);
this.panel = options.panel || VQ.scriptPanel();
this.tab = options.tab || 'Settings';
this.prefix = options.prefix || 'set_';
this.file = ''; // the file shown on the tab
this.loaded = null; // what was read from it: settingsFile.read()
var self = this;
this.onChanged = function (name, value) { self.changed(name, value); }; // for disconnect
}
// Folder of a file path, with a trailing '/'
SettingsTab.folderOf = function (path) {
var p = String(path).replace(/\\/g, '/');
return p.substring(0, p.lastIndexOf('/') + 1);
};
// ~/.vqsconfig
SettingsTab.defaultConfigFile = function () {
var home = VQ.getEnv('USERPROFILE');
if (home == '') home = VQ.getEnv('HOME');
return String(home).replace(/\\/g, '/') + '/.vqsconfig';
};
/** Value of key in configFile (default ~/.vqsconfig), or ''. */
SettingsTab.readConfig = function (key, configFile) {
var path = configFile || SettingsTab.defaultConfigFile();
if (!VQ.fileExists(path)) return '';
var lines = VQ.readFile(path);
for (var i = 0; i < lines.length; i++) {
var line = String(lines[i]), eq = line.indexOf('=');
if (eq > 0 && line.substring(0, eq).trim() === key) return line.substring(eq + 1).trim();
}
return '';
};
/** Sets key in configFile (default ~/.vqsconfig), leaving its other lines as they are. */
SettingsTab.writeConfig = function (key, value, configFile) {
var path = configFile || SettingsTab.defaultConfigFile();
var lines = VQ.fileExists(path) ? VQ.readFile(path).map(String) : [];
var entry = key + ' = ' + value, found = false;
for (var i = 0; i < lines.length; i++) {
var eq = lines[i].indexOf('=');
if (eq > 0 && lines[i].substring(0, eq).trim() === key) {
lines[i] = entry;
found = true;
}
}
if (!found) lines.push(entry);
return VQ.writeFile(path, lines.join('\n') + '\n'); // remembering the file is a convenience: no error
};
// Whether paths a and b name the same file, ignoring / or \ and letter case
SettingsTab.samePath = function (a, b) {
var norm = function (p) { return String(p).replace(/\\/g, '/').toLowerCase(); };
return norm(a) === norm(b);
};
/** defaultFile as a path: as given if absolute, else next to the script. '' if there is none. */
SettingsTab.prototype.defaultPath = function () {
var o = this.options;
if (!o.defaultFile) return '';
var f = String(o.defaultFile).replace(/\\/g, '/');
if (/^([A-Za-z]:)?\//.test(f)) return f; // absolute
var scriptDir = SettingsTab.folderOf(VQ.getScriptPath());
return scriptDir !== '' ? scriptDir + f : '';
};
/** The file to start with: the one used last time, else defaultFile, else asks. */
SettingsTab.prototype.startFile = function () {
var o = this.options;
if (o.configKey) {
var last = SettingsTab.readConfig(o.configKey, o.configFile);
if (last !== '' && VQ.fileExists(last)) return last;
}
var def = this.defaultPath();
if (def !== '') return def;
return this.pick(o.dialogDir || SettingsTab.folderOf(VQ.getScriptPath()));
};
/** Asks for a settings file, starting in dir. Returns its path, or '' if none was picked. */
SettingsTab.prototype.pick = function (dir) {
var files = VQ.getLocalFiles(this.options.dialogTitle || 'Select the settings file', dir);
if (!files || files.length === 0 || files == '') return '';
var path = String(files[0]);
if (/\.(vqs|js)$/i.test(path)) {
VQ.showMessage('That is a script, not a settings file:\n' + path + '\n\nPick the settings file.');
return '';
}
return path;
};
// One field on the tab
SettingsTab.prototype.field = function (d, value) {
var f = { name: this.prefix + d.key, label: d.label,
tooltip: (d.help ? d.help + ' ' : '') + '[' + d.key + ' in the file]' };
switch (d.type) {
case 'bool':
f.type = 'bool';
f.value = !!value;
break;
case 'list':
f.type = 'text';
f.value = SettingsFile.listText(value);
f.tooltip = (d.help ? d.help + '. ' : '') + 'Separate entries with commas; put an entry in quotes if it ' +
'contains a comma. [' + d.key + ' in the file]';
break;
case 'item':
f.type = 'item';
f.items = d.items;
if (d.editable) f.editable = true; // then any text is a valid value
f.value = value;
break;
case 'int':
case 'double':
f.type = d.type;
if (d.min !== undefined) f.min = d.min;
if (d.max !== undefined) f.max = d.max;
f.value = d.type === 'int' && Math.floor(value) !== value
? this.settingsFile.defaults()[d.key] : value;
if (d.type === 'double') f.decimals = SettingsFile.decimalsFor(d, f.value);
break;
default: // text, date
f.type = 'text';
f.value = value;
}
return f;
};
// The tab's entries for values. With a note (after run()), the note replaces "Use another file".
SettingsTab.prototype.fields = function (values, note) {
var self = this;
var fileEntries = [ { name: this.own('file'), label: 'File', type: 'label', value: this.file } ];
if (note) {
fileEntries.push({ name: self.own('note'), label: '', type: 'label', value: note });
} else {
fileEntries.push({ name: self.own('changeFile'), label: 'Use another file', type: 'bool', value: false,
tooltip: 'Pick a different settings file; changes made here are not kept' });
var def = this.defaultPath();
if (def !== '' && !SettingsTab.samePath(def, this.file)) {
fileEntries.push({ name: self.own('useDefault'), label: 'Use the default file', type: 'bool', value: false,
tooltip: def + '\n' + (VQ.fileExists(def)
? 'Open it; changes made here are not kept'
: 'It doesn\'t exist yet: switch to it, keeping the settings shown here, ' +
'and create it when you press ' + this.runButton()) });
}
}
var fields = [ { type: 'section', name: this.own('fileSection'), label: 'Settings file', children: fileEntries } ];
this.settingsFile.groups.forEach(function (g) {
var children = self.settingsFile.settings
.filter(function (d) { return d.group === g.id; })
.map(function (d) { return self.field(d, values[d.key]); });
if (children.length) { // a section needs at least one entry
fields.push({ type: 'section', name: self.own('group-' + g.id), label: g.label, columns: 2,
children: children });
}
});
return fields;
};
SettingsTab.REFERENCE_NOTE = 'For reference only: these are the settings this run of the script uses. ' +
'To change them, run the script again.';
SettingsTab.VIEW_NOTE = 'For reference only: these are the settings this script uses. It only reads them.';
/** Reads path and shows it on the tab, replacing what was there. */
SettingsTab.prototype.show = function (path) {
var loaded = this.settingsFile.read(path);
var previousFile = this.file;
this.file = path;
try {
this.panel.setFields(this.fields(loaded.values), this.tab);
} catch (e) {
this.file = previousFile;
throw e;
}
this.loaded = loaded;
loaded.replaced = this.replacedValues();
this.panel.setCurrentTab(this.tab);
// A new file is all blanks: don't greet it with a list of errors
this.showStatus(this.loaded.isNew ? null : this.values().problems);
};
/** The settings as the tab shows them: { values, problems }. */
SettingsTab.prototype.values = function () {
var self = this, values = {}, listProblems = [];
this.settingsFile.settings.forEach(function (d) {
var v = self.panel.value(self.prefix + d.key);
if (d.type === 'bool') {
v = !!v;
} else if (d.type === 'list') {
var list = SettingsFile.parseList(String(v));
if (list.error) listProblems.push(d.label + ' (' + d.key + ') ' + list.error);
v = list.error ? [] : list.items;
} else if (d.type === 'int' || d.type === 'double') {
v = Number(v);
} else {
v = String(v).trim();
}
values[d.key] = v;
});
return { values: values, problems: listProblems.concat(this.settingsFile.problems(values)) };
};
// The panel's status line, by the Run button. current: what stops Run (red); problems
// found in the file are orange.
SettingsTab.prototype.showStatus = function (current) {
var loaded = this.loaded, parts = [], kind = 'info';
if (current && current.length) {
parts.push('Can\'t run yet:\n- ' + current.join('\n- '));
kind = 'error';
}
if (loaded.isNew && loaded.carried) {
parts.push('This settings file doesn\'t exist yet. It is created with the settings shown when you press ' +
this.runButton() + '.');
} else if (loaded.isNew) {
parts.push('This settings file doesn\'t exist yet. Fill in the settings, then press ' +
this.runButton() + ' to create it.');
} else if (this.fileWarnings().length) {
parts.push('Found in the file (saving fixes it):\n- ' + this.fileWarnings().join('\n- '));
if (kind === 'info') kind = 'warning';
} else if (kind === 'info') {
parts.push('Check the settings, then press ' + this.runButton() + '. Changes are saved to the settings file.');
}
this.panel.setStatus(parts.join('\n\n'), kind);
};
// What was found in the file, less the values that fail a check: problems() reports those, by
// label, until they are fixed, so the status line lists each problem once. Plus the values the
// tab couldn't show as they are (see replacedValues()), which problems() doesn't report.
SettingsTab.prototype.fileWarnings = function () {
var failed = this.loaded.failedChecks || [];
return this.loaded.problems.filter(function (p) { return failed.indexOf(p) < 0; })
.concat(this.loaded.replaced || []);
};
// The numbers in the file that the tab shows differently: a whole number field can't show 2.5,
// and a number field shows values within its range, to its decimals. The tab shows another
// value, which Run saves, and which may pass every check; so each is listed, with the reason.
SettingsTab.prototype.replacedValues = function () {
var self = this, read = this.loaded.values, shown = this.values().values, list = [];
this.settingsFile.settings.forEach(function (d) {
if (d.type !== 'int' && d.type !== 'double') return;
var was = read[d.key], now = shown[d.key];
// Allow for the last binary digit of a double the field rounded to the same decimals
if (was === now || Math.abs(was - now) <= 1e-12 * Math.max(Math.abs(was), Math.abs(now))) return;
var why = self.settingsFile.check(d, was);
list.push(d.key + ' = ' + was + " can't be shown" + (why ? ' (' + why + ')' : '') +
', so the tab shows ' + now);
});
return list;
};
// Name of one of the tab's own controls. Settings are prefix + key and a key can't start
// with '-', so these never clash with a setting, whatever the keys and group ids are.
SettingsTab.prototype.own = function (what) {
return this.prefix + '-' + what;
};
SettingsTab.prototype.runButton = function () {
return this.options.runButton || 'Run';
};
// While waiting: "Use another file" works like a button, and any other edit rechecks the
// settings, so a problem shows as soon as it is typed.
SettingsTab.prototype.changed = function (name, value) {
var p = this.prefix;
if (name.indexOf(p) !== 0 || name === this.own('file')) return;
if (name === this.own('useDefault')) {
if (value) this.useDefault();
return;
}
if (name !== this.own('changeFile')) {
this.showStatus(this.values().problems);
return;
}
if (!value) return;
try {
var path = this.pick(SettingsTab.folderOf(this.file));
if (path == '') {
this.panel.setValue(this.own('changeFile'), false);
return;
}
this.show(path); // replaces the tab, this check box included
} catch (e) {
this.panel.setValue(this.own('changeFile'), false);
this.panel.setStatus('Could not open that file: ' + e, 'error');
}
};
// The tab as a read-only record of values, with note in place of "Use another file"
SettingsTab.prototype.showRecord = function (values, note) {
var self = this;
this.panel.setFields(this.fields(values, note), this.tab);
this.panel.setReadOnly(this.own('fileSection'), true);
this.settingsFile.groups.forEach(function (g) {
if (self.panel.hasField(self.own('group-' + g.id))) {
self.panel.setReadOnly(self.own('group-' + g.id), true);
}
});
};
/**
* For a script that only reads its settings: shows the file run() would start with on the
* tab, read-only with note (default VIEW_NOTE), without waiting, and returns
* { file, values, problems, warnings, isNew }
* problems: what makes the values unusable, as run() would refuse them (a file that doesn't
* exist yet is one), and what in the file couldn't be used, so the values differ from what it
* asks for (e.g. skipROI = not-a-list gives skipROI = []). warnings: what was found in the
* file but doesn't affect the values, such as an unknown setting. Both are also shown in the
* status line. The file is never changed, and settings.file is set as after run().
*/
SettingsTab.prototype.view = function (note) {
var path = this.startFile();
if (path == '') {
VQ.showMessage('No settings file selected!');
VQ.abort();
}
var loaded = this.settingsFile.read(path);
this.file = path;
this.loaded = loaded;
note = note || SettingsTab.VIEW_NOTE;
this.showRecord(loaded.values, note);
loaded.replaced = this.replacedValues();
var problems = loaded.isNew ? ['The settings file doesn\'t exist yet: ' + path]
: loaded.unusable.concat(this.settingsFile.problems(loaded.values));
// problems() already reports the values that fail a check
var warnings = loaded.isNew ? [] : this.fileWarnings().filter(function (p) {
return loaded.unusable.indexOf(p) < 0;
});
this.panel.setCurrentTab(this.tab);
this.panel.showPanel();
var parts = [];
if (problems.length) parts.push('Problems with these settings:\n- ' + problems.join('\n- '));
if (warnings.length) parts.push('Found in the file:\n- ' + warnings.join('\n- '));
if (!parts.length) parts.push(note);
this.panel.setStatus(parts.join('\n\n'), problems.length ? 'error' : warnings.length ? 'warning' : 'info');
return { file: path, values: loaded.values, problems: problems, warnings: warnings, isNew: loaded.isNew };
};
/**
* "Use the default file": opens defaultFile, or if it doesn't exist yet, shows it as a new file
* with the settings currently on the tab, so Run creates it with them.
*/
SettingsTab.prototype.useDefault = function () {
var path = this.defaultPath();
try {
if (VQ.fileExists(path)) {
this.show(path); // replaces the tab, this check box included
return;
}
var values = this.values().values;
var previousFile = this.file;
this.file = path;
try {
this.panel.setFields(this.fields(values), this.tab);
} catch (e) {
this.file = previousFile;
throw e;
}
this.loaded = { values: values, problems: [], unusable: [], failedChecks: [], isNew: true, carried: true };
this.panel.setCurrentTab(this.tab);
this.showStatus(this.values().problems);
} catch (e) {
if (this.panel.hasField(this.own('useDefault'))) this.panel.setValue(this.own('useDefault'), false);
this.panel.setStatus('Could not use the default file: ' + e, 'error');
}
};
/**
* Shows the settings, waits until the user presses Run with valid settings, saves them
* if anything changed, and leaves the tab as a read-only record of them (see
* REFERENCE_NOTE). Returns the values; settings.file is the file used. Aborts the script
* if it is stopped while waiting.
*/
SettingsTab.prototype.run = function () {
var start = this.startFile();
if (start == '') {
VQ.showMessage('No settings file selected!');
VQ.abort();
}
this.show(start);
this.panel.showPanel();
this.panel.valueChanged.connect(this.onChanged);
// In test mode (VQ_TEST_DIALOGS) wait() returns at once, so a refusal would repeat forever
var testMode = VQ.getEnv('VQ_TEST_DIALOGS') != '';
var run;
while (true) {
if (!this.panel.wait(this.runButton())) {
VQ.abort(); // the script was stopped
}
run = this.values();
if (!run.problems.length) break;
this.showStatus(run.problems);
this.panel.setCurrentTab(this.tab);
if (testMode) {
this.panel.valueChanged.disconnect(this.onChanged);
throw new Error('SettingsTab: invalid settings in ' + this.file + ':\n- ' + run.problems.join('\n- '));
}
VQ.showMessage('Can\'t run yet:\n- ' + run.problems.join('\n- ') +
'\n\nFix these on the ' + this.tab + ' tab, then press ' + this.runButton() + ' again.');
}
this.panel.valueChanged.disconnect(this.onChanged);
// Save when the file is new, the user changed something, or the file needs fixing
var loaded = this.loaded;
var save = loaded.isNew || loaded.problems.length > 0 ||
JSON.stringify(run.values) !== JSON.stringify(loaded.values);
var saveError = '';
if (save) {
try {
this.settingsFile.write(this.file, run.values);
} catch (e) {
saveError = e.message; // run with the settings anyway; they are valid
}
}
if (this.options.configKey && !saveError) {
SettingsTab.writeConfig(this.options.configKey, this.file, this.options.configFile);
}
// From here on the tab is only a record of the settings in use: shown again read-only,
// with a note in place of "Use another file". The status line says so too, though the
// script may replace it; the note on the tab stays.
this.showRecord(run.values, SettingsTab.REFERENCE_NOTE);
if (saveError) {
this.panel.setStatus(saveError + '; these settings were not saved.\n\n' + SettingsTab.REFERENCE_NOTE, 'warning');
if (!testMode) VQ.showMessage(saveError + '.\n\nRunning with the settings on the ' + this.tab +
' tab; they were not saved.');
} else {
this.panel.setStatus((save ? 'Saved to the settings file.\n\n' : '') + SettingsTab.REFERENCE_NOTE);
}
return run.values;
};