FQCrop Batch: Difference between revisions

From FetishQuest Wiki
Jump to navigation Jump to search
JasX (talk | contribs)
No edit summary
JasX (talk | contribs)
No edit summary
 
(5 intermediate revisions by the same user not shown)
Line 6: Line 6:


<pre>
<pre>
// This is a helper script for all ASSET editors
/*
import Window from '../WindowManager.js';
Note: This is similar to the fqcrop.jsx file except it exports all layers one at a time.
import Condition from '../../classes/Condition.js';
Usage: See fqcrop.jsx for more info. Things you need to keep in mind in this implementation:
import Generic from '../../classes/helpers/Generic.js';
- Each art layer can only consist of ONE photoshop layer
import Audio from '../../classes/Audio.js';
- All layers must begin with <layerNr>_ ex 30_bikini_light_ub to use layer 30 (upper body base)
import * as EditorPlayerIconState from './EditorPlayerIconState.js';
- A JSON metadata file named the same as the original file will be created or updated. It's going to need a bit of editing, but you can use it to quickly upload a full character.
import PlayerIconState from '../../classes/PlayerIconState.js';
- Layers and groups starting with # are ignored.
- If a JSON file exists, it's loaded and updated. Missing layers aren't deleted from it. So if you remove layers you have to remove them from the JSON file or delete the JSON file to generate a new one.
- The following values are overwritten into the JSON file, using the photoshop settings:
- icon
- x
- y
- blendMode (only normal, multiply, overlay are supported)
- opacity
*/
var startRulesUnits = preferences.rulerUnits;
var doc = activeDocument;
var docW = doc.width;
var docH = doc.height;
var allLayers = [];
var dirJson = decodeURI(doc.path.fsName)+"/";
var jsonName = doc.name.split(".");
jsonName.pop();
var fName = jsonName.join('_')
var dir = dirJson+fName+"/";
jsonName = jsonName.join(".")+".json";
var pics = [];
var url = '';
var bgName = "";
var bgLayer;
Array.prototype.indexOf = function ( item ) {


export default{
  var index = 0, length = this.length;


PAGINATION_LENGTH : 250,
  for ( ; index < length; index++ ) {
TEST_AUDIO : null,


// Automatically binds all inputs, textareas, and selects with the class saveable and a name attribute indicating the field to to save
if ( this[index] === item )
// win is a windowmanager object
// Autobind ADDS an event, so you can use el.eventType = fn before calling autobind if you want
// List is the name of the array in mod.<array> that the asset is stored in
// Also binds JSON
autoBind( win, asset, list, onChange ){


const dom = win.dom,
  return index;
dev = window.mod
;


const updateExact = (el, val) => {
  }
if( el )
el.innerText = '('+(val <= 0 && el.classList.contains("zeroParent") ? 'PASS' : val)+')';
};


const handleChange = event => {
  return -1;


const targ = event.currentTarget,
  };
name = targ.name
;


var condMap = {
    '26_sling_heavy' : ['targetWearsSlingBikini','targetLowerBodyHard'],
    '25_sling_heavy' : ['targetWearsSlingBikini','targetLowerBodyHard'],
    '26_sling_med' : ['targetWearsSlingBikini','targetLowerBodyLeather'],
    '25_sling_med' : ['targetWearsSlingBikini','targetLowerBodyLeather'],
    '26_sling_cloth' : ['targetWearsSlingBikini'],
    '25_sling_cloth' : ['targetWearsSlingBikini'],
    '26_bodysuit_leather' : ['targetBodysuit', 'targetLowerBodyLeather'],
    '25_bodysuit_leather' : ['targetBodysuit', 'targetLowerBodyLeather'],
    '26_bodysuit_cloth' : ['targetBodysuit'],
    '25_bodysuit_cloth' : ['targetBodysuit'],
   
    '36_heavy_ub' : ['targetUpperBodyHard', 'targetNoBodysuit'],
    '35_heavy_ub' : ['targetUpperBodyHard', 'targetNoBodysuit'],
   
    '26_heavy_lb' : ['targetLowerBodyHard'],
    '25_heavy_lb' : ['targetLowerBodyHard'],
   
    '36_bikini_leather_ub' : ['targetUpperBodyBikini', 'targetUpperBodyLeather', 'targetNoBodysuit'],
    '35_bikini_leather_ub' : ['targetUpperBodyBikini', 'targetUpperBodyLeather', 'targetNoBodysuit'],
    '26_bikini_leather_lb' : ['targetWearsThong', 'targetLowerBodyLeather'],
    '25_bikini_leather_lb' : ['targetWearsThong', 'targetLowerBodyLeather'],
   
    '36_bikini_cloth_ub' : ['targetUpperBodyBikini', 'targetNoBodysuit'],
    '35_bikini_cloth_ub' : ['targetUpperBodyBikini', 'targetNoBodysuit'],
    '26_bikini_cloth_lb' : ['targetWearsThong'],
    '25_bikini_cloth_lb' : ['targetWearsThong'],
   
    '36_cloth_ub' : ['targetWearsUpperBody', 'targetNoBodysuit'],
    '35_cloth_ub' : ['targetWearsUpperBody', 'targetNoBodysuit'],
    '26_cloth_lb' : ['targetWearsLowerBody'],
    '25_cloth_lb' : ['targetWearsLowerBody'],
   
    '15_aroused_heavy' : ['metaVeryArousing'],
    '15_pain_heavy' : ['metaVeryPainful'],
    '10_aroused' : ['metaArousing'],
    '10_pain' : ['metaPainful'],
    '5_orgasm' : ['targetHasOrgasm'],
};


let val = targ.value.trim();
function exec(){
preferences.rulerUnits = Units.PIXELS;
fetchLayers(doc);


if( targ.classList.contains('bitwise') ){


let v = 0;
// Fetch JSON if possible
const all = [...dom.querySelectorAll('input[name="'+name+'"]')];
var jsonFile = new File(dir+jsonName);
for( let sub of all ){
jsonFile.encoding = 'UTF8';
if( sub.checked && parseInt(sub.value) )
if( jsonFile.exists ){
v = v|parseInt(sub.value);
}
jsonFile.open("r");
val = v;
        var parsed = JSON.parse(jsonFile.read());
 
        url = parsed.url || '';
}
bgName = parsed.base || "";
// Try to auto typecast
pics = parsed.layers;
else if( targ.dataset.type === 'smart' ){
jsonFile.close();
 
if( val.toLowerCase() === 'true' )
}
val = true;
else if( val.toLowerCase() === 'false' )
var pngOpts = new PNGSaveOptions();
val = false;
pngOpts.method = stringIDToTypeID("thorough");
else if( !isNaN(val) )
pngOpts.compression = 1;
val = +val;
 
var missingFromMap = [];
}
for( var i = 0; i < allLayers.length; ++i ){
else if( targ.dataset.type === 'int' ){
val = parseInt(val) || 0;
var l = allLayers[i];
}
l.visible = true;
else if( targ.dataset.type === 'float' ){
if( i )
val = +val || 0;
allLayers[i-1].visible = false;
}
else if( targ.tagName === 'INPUT' ){
 
const type = targ.type;
if( type === 'range' || type === 'number' )
val = +val;
if( type === 'checkbox' )
val = Boolean(targ.checked);
 
}
 
let path = name.split('::');
let base = asset;
while( path.length > 1 ){
base = base[path.shift()];
if( base === undefined ){
console.error("Path find failed for ", name, "in", asset);
throw "Unable to find path, see above";
}
}
path = path.shift();
 
// Soft = here because type isn't important
if( val != base[path] ){
 
// Label change must update the window
if( name === "label" || name === "id" ){
 
val = val.trim();
if( !val )
throw 'Label/id cannot be empty';
 
win.id = val;
win.updateTitle();
dev.mod.updateChildLabels(base, win.type, base[path], val); // Make sure any child objects notice the label change
 
}
else if( name === "name" ){
win.name = val;
win.updateTitle();
}
base[path] = val;
dev.setDirty(true);
if( list )
this.rebuildAssetLists(list);
 
this.propagateChange(win);
if( typeof onChange === "function" )
onChange(name, val);
 
}
 
updateExact(targ._valExact, val);
 
};
 
// Binds simple inputs
dom.querySelectorAll(".saveable[name]").forEach(el => {
 
// Cache any exact val span
el._valExact = el.parentElement.querySelector('span.valueExact');
if( el.parentElement.tagName !== 'LABEL' )
delete el._valExact;
updateExact( el._valExact, el.value );
el.addEventListener('change', handleChange);
 
});
 
this.bindJson( win, asset, list );
this.bindArrayPickers(win, asset, list);
 
},
 
// Automatically binds JSON fields. Needs to be a textarea with class json and name being the field you want to put the data in
bindJson( win, asset, list ){
 
const dev = window.mod;
 
const updateData = (textarea, checkChange = true) => {
 
try{
textarea.value = textarea.value.trim();
if( !textarea.value )
textarea.value = '{}';
 
let data = JSON.parse(textarea.value);
textarea.value = JSON.stringify(data, undefined, 2); // Auto format
 
// Check if it has changed
if( JSON.stringify(data) !== JSON.stringify(asset.data) && checkChange ){
asset[textarea.name] = data;
dev.setDirty(true);
this.rebuildAssetLists(list);
this.propagateChange(win);
 
}
 
}catch(err){
alert("JSON Syntax error: "+(err.message || err));
let e = String(err).split(' ');
let pos = parseInt(e.pop());
textarea.focus();
textarea.setSelectionRange(pos, pos);
return false;
}
 
return true;
 
};
 
win.dom.querySelectorAll('textarea.json[name]').forEach(el => {
 
updateData(el, false);
el.addEventListener('change', event => {
if( !updateData(el) )
event.stopImmediatePropagation();
});
 
});
 
},
 
// Automatically binds arrayPickers (arrays of checkboxes). Needs to be a div with class arrayPicker and name being the field to put the resulting array in
bindArrayPickers( win, asset, list ){
 
const dev = window.mod;
 
 
const updateData = div => {
 
const out = [], pre = JSON.stringify(asset[div.getAttribute("name")] || []);
div.querySelectorAll('input[type=checkbox]:checked').forEach(el => {
out.push(el.value);
});
 
if( JSON.stringify(out) !== pre  ){
asset[div.getAttribute("name")] = out;
dev.setDirty(true);
this.rebuildAssetLists(list);
this.propagateChange(win);
}
 
};
 
const picker = win.dom.querySelectorAll('div.arrayPicker[name]');
picker.forEach(pickerEl => {
 
pickerEl.querySelectorAll('input[type=checkbox]').forEach(el => el.addEventListener("change", () => {
updateData(pickerEl);
}));
 
updateData(pickerEl);
});
},
var baseOpacity = l.opacity
 
// Tries to convert an object, array etc to something that can be put into a table, and escaped
makeReadable( val ){
 
if( Array.isArray(val) ){
val = val.map(el => this.makeReadable(el)).join(', ');
}
else if( val === null ){
val = '{}';
}
else if( typeof val === "object" ){ // NULL is technically an object
 
if( val.label )
val = val.label;
else if( val.id )
val = val.id;
else
val = JSON.stringify(val);
 
}
return String(val);
 
},
 
// Takes a var and library name and turns it into an object (unless it's already one)
modEntryToObject( v, lib ){
if( typeof v === "string" )
v = this.getAssetById( lib, v );
return v;
},
 
// Creates a table inside an asset to show other assets. Such as a table of conditions tied to a text asset
// Returns a DOM table with events bound on it
// Asset is a mod asset
/*
win is the Window object that should act as the parent for the asset to link
asset is the parent asset
key is the key in the asset to modify
if parented, it sets the _mParent : {type:(str)type, label:(str)label} parameter on any new assets created, and only shows assets with the same _mParent set
if parented is === 2, it sets _h instead to hide it. Used only in sub assets of dungeon room assets to save memory
if single is === -1, then it hides all inputs
columns can also contain functions, they'll be run with the asset as an argument
ignoreAsset doesn't put the asset into the list. Used by EditorQuestReward where you have multiple fields mapping the same key to different types of objects
windowData is passed to the new window
*/
linkedTable( win, asset, key, constructor = Condition, targetLibrary = 'conditions', columns = ['id', 'label', 'desc'], single = false, parented = false, ignoreAsset = false, windowData = '', ignoreLibrary = false, allowUnique = true ){
 
const fullKey = key;
let k = key.split('::');
let entries = asset;
while( k.length > 1 ){
entries = entries[k.shift()];
}
key = k.shift();
const allEntries = toArray(entries[key]);
var bounds = l.bounds;
// Needed because :: may need to set '' as a value in order to work
var left = bounds[0];
if( single && single !== -1 && allEntries[0] === '' )
var right = docW-bounds[2];
allEntries.splice(0);
var top = bounds[1];
 
var bottom = docH - bounds[3];
const EDITOR = window.mod, MOD = EDITOR.mod;
var layerName = l.name;
 
var layerNr = parseInt(layerName);
let table = document.createElement("table");
var blendMode = 'source-over';
table.classList.add("linkedTable", "selectable");
if( l.blendMode == BlendMode.MULTIPLY )
blendMode = 'multiply';
else if( l.blendMode == BlendMode.OVERLAY )
blendMode = 'overlay';
var opacity = baseOpacity/100;
if( !ignoreAsset ){ // Used in EditorQuestReward where there are multiple inputs all corresponding to the same field
if( isNaN(layerNr) )
 
alert("Layer "+layerName+" needs to start with the FQ art layer number. Use # if you don't want to save this layer.");
//console.log(key, targetLibrary, allEntries);
else if( right < 1 || bottom < 1 ){
 
alert("Layer "+layerName+" invalid dimensions "+left + " "+ right +" :: "+top+" "+bottom);
let n = 0;
for( let entry of allEntries ){
 
 
const base = this.modEntryToObject(entry, targetLibrary),
asset = new constructor(base)
;
 
 
if( !base ){
console.error("Base not found, trying to find", entry, "in", targetLibrary, "asset was", asset, "all assets", allEntries);
}
 
 
const tr = document.createElement('tr');
table.appendChild(tr);
tr.classList.add("asset");
tr.dataset.id = asset.label || asset.id;
tr.dataset.index = n;
 
if( base && typeof entry !== 'object' && (base.__MOD || base._e) ){
 
if( base.__MOD ){
tr.dataset.mod = base.__MOD;
}
if( base._e ){
tr.dataset.ext = base._e;
}
 
}
 
// prefer label before id
for( let column of columns ){
 
const td = document.createElement('td');
tr.appendChild(td);
td.innerText = this.makeReadable(typeof column === 'function' ? column(asset) : asset[column]);
 
}
let td = document.createElement("td");
tr.appendChild(td);
 
if( !base )
td.innerText = 'MISSING_ASSET';
else
td.innerText = (base.__MOD ? base.__MOD : 'THIS');
 
// order buttons
if( !single ){
 
td = document.createElement("td");
tr.appendChild(td);
td.classList.add("order");
if( n )
td.innerHTML += '<input type="button" class="small up" value="&#9650;" />';
if( n !== allEntries.length-1 )
td.innerHTML += '<input type="button" class="small down" value="&#9660;" />';
 
}
 
++n;
}
}
}
 
else{
// Stores a created asset in this asset's key
// a is the new asset
const storeAsset = (a, pa) => {
 
console.log("Storing asset", a, pa);
let template = new constructor();
let text = (asset.label||asset.id)+'>>'+targetLibrary.substr(0, 3)+'_'+Generic.generateUUID().substr(0,4)
if( template.hasOwnProperty("label") )
a.label = text;
else
a.id = text;
 
// There's no target library, this should be stored as an object
if( !mod.mod[targetLibrary] ){
 
console.log("Note: Stored asset as object (may be unwanted)", a, "in", asset);
 
if( single )
entries[key] = a;
else{
 
if( !Array.isArray(entries[key]) )
entries[key] = [];
 
entries[key].push(a);
}
 
}
else if( single )
entries[key] = a.label || a.id; // Store only the ID
else{
 
if( !Array.isArray(entries[key]) )
entries[key] = [];
 
entries[key].push(a.label || a.id);
 
}
 
if( pa ){
 
if( pa === 2 )
a._h = 1;
else{
a._mParent = {
type : win.type,
label : win.id,
};
}
 
}
 
var file = layerName+".png";
};
 
 
// Parented single asset can only add if one is missing. Otherwise they have to edit by clicking. This works because parented can only belong to the same mod.
const hasButton = (!single || !parented || !entries[key]) && single !== -1;
if( hasButton ){
 
const tr = document.createElement("tr");
table.appendChild(tr);
tr.classList.add("noselect");
 
//console.log("targetLibrary", targetLibrary, "ignore", ignoreLibrary);
tr.innerHTML = '<td class="center" colspan="'+(columns.length+1+(!single))+'">'+
(window.mod.hasDB(targetLibrary) && !ignoreLibrary ? '<input type="button" class="small addNew library" value="Library" />' : '')+
(allowUnique ? '<input type="button" class="small addNew" value="Unique" />' : '')+
'</td>';
 
table.querySelectorAll("input.addNew")?.forEach(el => el.onclick = event => {
var folder = Folder(dir);
 
if( !folder.exists )
const fromLibrary = event.target.classList.contains('library');
folder.create();
 
// If parented, insert a new asset immediately, as there's no point in listing assets that are only viable for this parent
// Holding shift key for a non-parent by default creates a parented one
if( !fromLibrary ){
 
let a = new constructor();
a = constructor.saveThis(a, "mod");
storeAsset(a, parented || true); // Must be either 2 or true when clicking the unique button, default to mParent
 
// Insert handles other window refreshers
this.insertAsset(targetLibrary, a, win, undefined, windowData);
 
// But we still need to refresh this
win.rebuild();
 
this.propagateChange(win);
 
}
else
window.mod.buildAssetLinker( win, asset, fullKey, targetLibrary, single );
 
});
}
 
const clickListener = event => {
 
const index = parseInt(event.currentTarget.dataset.index);
const entry = single ? entries[key] : entries[key][index];
const id = event.currentTarget.dataset.id;
 
 
let asset = this.getAssetById(targetLibrary, id);
 
// Ctrl deletes
if( event.ctrlKey || event.metaKey ){
 
// Remove an extension
if( event.currentTarget.dataset.ext ){
MOD.deleteAsset(targetLibrary, entry);
}
// Remove the actual thing
else{
 
// Don't need to store this param in the mod anymore
if( single )
delete entries[key];
// Remove from the array
else
entries[key].splice(index, 1); // Remove this
 
// Assets in lists are always strings, only the official mod can use objects because it's hardcoded
// If this table has a parenting relationship (see Mod.js), gotta remove it from the DB too
if( asset && (asset._h || asset._mParent) )
MOD.deleteAsset(targetLibrary, entry, true);
 
}
 
win.rebuild();
EDITOR.setDirty(true);
this.rebuildAssetLists(win.type);
this.propagateChange(win);
 
return;
}
else{
 
// Fetch from library
if( !asset ){
throw 'Linked asset not found, '+id+" in "+targetLibrary;
}
 
if( typeof asset !== "object" )
throw 'Linked asset is not an object';
 
if( event.altKey && !single ){
 
const a = new constructor(asset);
const inserted = this.insertCloneAsset(targetLibrary, a, constructor, win);
// Add it to the list
storeAsset(inserted, parented);
this.rebuildAssetLists(targetLibrary);
this.propagateChange(win);
win.rebuild();
return;
}
 
 
// This is just for legacy reasons, makes sure it has an ID, which the window manager wants
if( !asset.label && !asset.id && typeof entry === "object" )
entry.id = Generic.generateUUID();
 
// prefer editing by string since that can be put into save state, but custom assets can be edited via object for legacy reasons
EDITOR.buildAssetEditor( targetLibrary, entry, undefined, win, windowData );
}
 
 
};
 
const onArrowClick = event => {
 
const up = event.currentTarget.classList.contains("up"),
index = parseInt(event.currentTarget.parentNode.parentNode.dataset.index)
;
if( up ){
l.opacity = 100;
let pre = entries[key][index-1];
entries[key][index-1] = entries[key][index];
entries[key][index] = pre;
}
else{
 
let pre = entries[key][index+1];
entries[key][index+1] = entries[key][index];
entries[key][index] = pre;
 
}
 
win.rebuild();
EDITOR.setDirty(true);
this.propagateChange(win);
};
//alert("Image cropped x:"+left+" y:"+top)
var workLayer = doc.duplicate();


table.querySelectorAll("tr.asset").forEach(el => {
workLayer.crop(bounds);
el.onclick = clickListener;
el.linkedTableListener = clickListener; // Stores the listener in the TR in case you want to override it
});
var fileOut = new File(dir+file)
 
workLayer.saveAs(fileOut, pngOpts, true);
// Prevents default action when clicking one the td contining the arrows
workLayer.close(SaveOptions.DONOTSAVECHANGES);
table.querySelectorAll('td.order').forEach(el => {
el.onclick = event => event.stopImmediatePropagation();
l.opacity = baseOpacity;
});
 
var duration = 0;
table.querySelectorAll('td.order > input').forEach(el => el.onclick = onArrowClick);
if( layerNr < 20 && layerNr >= 10 )
 
duration = 3000; // Facial expressions generally.
// Todo: Need some way to refresh the window if one of the linked assets are changed
var slots = {
s26 : 'lowerBody',
return table;
s31 : 'hands',
 
s36 : 'upperBody',
},
s41 : 'jewelleryCosmetic',
 
s46 : 'lowerBodyCosmetic',
 
s51 : 'upperBodyCosmetic',
 
};
// Because list and linker use the same function, this can be used to check which it is
windowIsLinker( win ){
var cm = condMap[layerName] || [];
 
if( !cm.length )
return win.type === 'linker';
missingFromMap.push(layerName);
 
},
 
 
 
// Tries to automatically build a selectable list of assets and return the HTML
// Fields is an array of {field:true/func} If you use a non function, it'll try to auto generate the value based on the type,  
// otherwise the function will be executed using win as parent and supply the var as an argument
// If a field name starts with * it counts as essential
// Nonfunction is auto escaped, function needs manual escaping
// Fields should contain an id or label field (or both), it will be used for tracking the TR and prefer label if it exists
// Constructor is the asset constructor (used for default values)
buildList( win, library, constr, fields, start ){
 
let fulldb = window.mod.mod[library].slice().reverse(),
isLinker = this.windowIsLinker(win)
;
 
// Parent mod assets
fulldb.push(...window.mod.parentMod[library].slice().reverse());
// Filter out parented and extensions
fulldb = fulldb.filter(el =>
(!el._mParent && !el._e && !el._h) ||
window.mod.showParented
);
 
const fieldIsEssential = field => field.startsWith('*');
const getFieldName = field => {
if( fieldIsEssential(field) )
updatePic(makePic({
return field.slice(1);
icon : file,
return field;
layer : layerNr,
 
duration : duration,
};
x : parseInt(left),
 
y : parseInt(top),
// Used to stringify a key from fields that should exist in asset
slot : slots['s'+layerNr] || '',
const stringifyVal = (field, custom, asset) => {
blendMode : blendMode,
 
opacity : opacity,
if( typeof custom === "function" )
                conditions : condMap[layerName] || [],
return custom.call(win, asset);
}));
 
const val = asset[getFieldName(field)];
if( typeof val === "boolean" )
return val ? 'YES' : '';
return this.makeReadable(val);
}
 
};
 
if( !start )
}
start = parseInt(win.custom._page) || 0;
if( missingFromMap.length )
if( start === -1 )
alert("The following layers are missing auto condition definitions, check your spelling etc: "+missingFromMap.join(", "));
start = fulldb.length;
win.custom._page = start;
// Save BG as nude layer
 
if( bgLayer ){
if( allLayers.length )
allLayers[i-1].visible = false;
bgLayer.visible = true;
var jpegOpts = new JPEGSaveOptions();
jpegOpts.quality = 9;
var fn = fName+"_n.jpg";
doc.saveAs(new File(dir+fn), jpegOpts, true);
bgName = fn;
}
var keys = [];
for( var i in condMap ){
keys.push(i);
}
pics.sort(function(a, b){
var aln = a.icon.split(".")[0];
var bln = b.icon.split(".")[0];
var aPos = keys.indexOf(aln);
var bPos = keys.indexOf(bln);
if( aPos == bPos )
return 0;
if( aPos == -1 )
return 1;
if( bPos == -1 )
return -1;
return aPos < bPos ? -1 : 1;
if( win._search ){
});


let searchTerms = {}; // Object where key * searches all fields, otherwise 'key' : 'search'
var dump = JSON.stringify({
try{
base : bgName,
searchTerms = JSON.parse(win._search);
        url : url,
}catch(err){
        layers : pics
searchTerms = {'*' : win._search};
    }, null, 4);
}
jsonFile.open("w");
jsonFile.write(dump);
jsonFile.close();


for( let term in searchTerms )
preferences.rulerUnits = startRulesUnits;
searchTerms[term] = String(searchTerms[term]).toLowerCase();


// Use cached search results
}
if( win._searchResults )
fulldb = win._searchResults;


else{


// Returns true if the term validated
const findTermInEntry = (terms, entry) => {


terms = toArray(terms);
// Validates all terms
for( let searchTerm of terms ){


let inverse = false;
if( searchTerm.startsWith("!") ){


inverse = true;
searchTerm = searchTerm.substr(1);


}


let found = entry.includes(searchTerm);
if( found === inverse )
return false;


}
return true;


};


// Find out how many fields we need, * is only counted if it's the only field
let minTerms = Object.keys(searchTerms).length;
if( minTerms > 1 && searchTerms['*'] )
--minTerms;


fulldb = win._searchResults = fulldb.filter(el => {


let fieldsFound = 0;
for( let i in fields ){
let fieldName = i;
if( fieldName.charAt(0) === '*' )
fieldName = fieldName.substring(1);
let texts = [];
if( searchTerms['*'] )
texts.push(searchTerms['*']);
if( searchTerms[fieldName] )
texts.push(searchTerms[fieldName]);
// no search terms for this field
if( !texts.length )
continue;
// Ignore this field
if( window.mod.essentialOnly && !fieldIsEssential(i) )
continue;
let data = stringifyVal(fieldName, fields[i], el);
const text = typeof data === 'string' ? data.toLowerCase() : String(data);
// Wildcard found
if( findTermInEntry( texts, text ) ){
++fieldsFound;
// Found enough fields
if( fieldsFound >= minTerms )
return true;
continue;
}
/// {"chat":1,"conditions":"eventisbattlestarted"}
}
return false;
});
}


// Accept data from makePic
function updatePic( picData ){
for( var i = 0; i < pics.length; ++i ){
var p = pics[i];
if( p.icon == picData.icon ){
p.layer = picData.layer;
p.x = picData.x;
p.y = picData.y;
p.blendMode = picData.blendMode;
p.opacity = picData.opacity;
return;
}
}
}
pics.push(picData);
}


let lastPageStarts = Math.floor(fulldb.length/this.PAGINATION_LENGTH);
if( fulldb.length%this.PAGINATION_LENGTH === 0 && fulldb.length )
lastPageStarts -= 1;
lastPageStarts *= this.PAGINATION_LENGTH;
if( win.custom._page > lastPageStarts )
win.custom._page = lastPageStarts;
let db = fulldb.slice(win.custom._page, win.custom._page+this.PAGINATION_LENGTH);


// Fetches all viable art layers
function fetchLayers( parentLayer, ignore ){
for( var i = 0; i < parentLayer.layers.length; ++i ){
var l = parentLayer.layers[i];
var ign = ignore;
var isBg = l.name == "Background";
if( !ignore )
ign = ( l.name.substring(0,1) == "#" || isBg );
if( isBg )
bgLayer = l;


// Create the element to return
l.visible = (l.typename == "LayerSet");
const container = document.createElement('template');
 
let el = document.createElement('div');
el.innerText = 'To search specific fields use a JSON object {"fieldName":"searchTerm", "*":"globalSearchTerm"}. You can use ! at the start of a search term to inverse.';
container.appendChild(el);
 
// "new" button
el = document.createElement('input');
container.appendChild(el);
el.classList.add('new');
el.type = 'button';
el.value = 'New';
 
// Search bar
el = document.createElement('input');
container.appendChild(el);
el.classList.add('search');
el.type = 'text';
el.placeholder = 'Search';
 
// Batch operation span
el = document.createElement('span');
container.appendChild(el);
el.classList.add('hidden', 'batch');
 
// Batch delete
let elSub = document.createElement('input');
el.appendChild(elSub);
elSub.classList.add('deleteSelected');
elSub.type = 'button';
elSub.value = 'Delete Selected';
 
elSub = document.createElement('input');
el.appendChild(elSub);
elSub.classList.add('exportSelected');
elSub.type = 'button';
elSub.value = 'Export Selected';
 
const table = document.createElement('table');
container.appendChild(table);
table.classList.add('dblist', 'selectable', 'autosize');
 
 
let tr = document.createElement('tr');
table.appendChild(tr);
// Add checkbox placeholder
if( !isLinker ){
 
let th = document.createElement('th');
tr.appendChild(th);
th.classList.add("essential");
let checkbox = document.createElement('input');
th.appendChild(checkbox);
checkbox.classList.add('checkAll');
checkbox.type = 'checkbox';


if( l.typename == "LayerSet" ){
fetchLayers(l, ign);
continue;
}
}
for( let i in fields ){
if( !ign )
allLayers.push(l);
}
}


let th = document.createElement('th');
function makePic( data ){
tr.appendChild(th);
if( fieldIsEssential(i) )
if( typeof data != "object" )
th.classList.add('essential');
data = {};
th.innerText = getFieldName(i);
var out = {};
out.icon = data.icon;
out.conditions = data.conditions || [];
out.layer = data.layer || 0;
out.duration = parseInt(data.duration) || 0;
out.x = data.x || 0;
out.y = data.y || 0;
out.slot = data.slot || '';
out.blendMode = data.blendMode || 'source-over';
out.opacity = 1.0;
if( !isNaN(data.opacity) )
out.opacity = data.opacity;
    out.conditions = data.conditions;
return out;
}


}


// mod shows up in linker
if( isLinker ){


let th = document.createElement('th');
function save_as_png(doc, file, copy, comp, filter, none){
tr.appendChild(th);
th.innerText = "MOD";


}
    try {


for( let asset of db ){
        if (copy == undefined) copy = true;


const a = constr.loadThis(asset);
        if (comp == undefined) comp = 9;
let tr = document.createElement('tr');
table.appendChild(tr);
tr.dataset.id = asset.label || asset.id || a.label || a.id;
let ext = a;


// This asset is not from this mod
        if (none == undefined) none = true;
if( asset.__MOD ){
tr.dataset.mod = asset.__MOD;
}


ext = window.mod.parentMod.getAssetById(library, asset.label || asset.id, true) || a;
        if (filter == undefined) filter = "PNGFilterAdaptive";
if( (ext.id && ext.id !== a.id) || (ext.label && ext.label !== a.label) ) // This is an extension on the base mod
tr.dataset.ext = ext.id || ext.label;
if( !isLinker ){


let td = document.createElement('td');
        var doc0 = app.activeDocument;
tr.appendChild(td);
td.classList.add('essential');
td.innerHTML = '<input type="checkbox" class="marker" />';


}
        app.activeDocument = doc;
for( let field in fields ){


const essential = fieldIsEssential(field);
        var d = new ActionDescriptor();
let val = stringifyVal(field, fields[field], ext);


const td = document.createElement('td');
        var d1 = new ActionDescriptor();
tr.appendChild(td);
if( essential )
td.classList.add("essential");
td.innerText = val;
}


// Linker should also show the mod
        d1.putEnumerated(stringIDToTypeID("method"), stringIDToTypeID("PNGMethod"), stringIDToTypeID("quick"));
if( isLinker ){


const td = document.createElement('td');
        if (none)
tr.appendChild(td);
td.innerText = asset.__MOD ? asset.__MOD : 'THIS';


}
            d1.putEnumerated(stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceNone"));


}
        else


            d1.putEnumerated(stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceAdam7"));


container.appendChild(table);
        d1.putEnumerated(stringIDToTypeID("PNGFilter"), stringIDToTypeID("PNGFilter"), stringIDToTypeID(filter));


if( start > 0 ){
        d1.putInteger(stringIDToTypeID("compression"), comp);


let back = document.createElement('input');
        d.putObject(stringIDToTypeID("as"), stringIDToTypeID("PNGFormat"), d1);
back.type = 'button';
back.className = 'backFull';
back.value = '<<<<';
container.appendChild(back);


back = document.createElement('input');
        d.putPath(stringIDToTypeID("in"), file);
back.type = 'button';
back.className = 'back';
back.value = '<<';
container.appendChild(back);


}
        d.putBoolean(stringIDToTypeID("copy"), copy);


if( fulldb.length > this.PAGINATION_LENGTH ){
        executeAction(stringIDToTypeID("save"), d, DialogModes.NO);


const paginate = document.createElement('span');
        app.activeDocument = doc0;
paginate.innerText = ' '+(win.custom._page/this.PAGINATION_LENGTH)+'/'+Math.floor(Math.max(0,fulldb.length-1)/this.PAGINATION_LENGTH)+' ';
container.append(paginate);


}
        return true;


if( fulldb.length > win.custom._page+this.PAGINATION_LENGTH ){
        }


let next = document.createElement('input');
    catch (e) { alert(e); return false; }
next.type = 'button';
next.className = 'next';
next.value = '>>';
container.append(next);


next = document.createElement('input');
}
next.type = 'button';
next.className = 'last';
next.value = '>>>>';
container.append(next);
}


return container;


},


// Binds a window listing. This is used for the window types: database, linker
// Type is the name of the array of the asset in mod the list fetches elements from
// baseObject is the object to insert when pressing "new"
bindList( win, type, baseObject ){
const DEV = window.mod, MOD = DEV.mod;
const isLinker = this.windowIsLinker(win),
single = isLinker && win.asset && win.asset.single, // This is a linker for only ONE object, otherwise it's an array
batchDiv = win.dom.querySelector('span.batch'),
rows = win.dom.querySelectorAll('tr[data-id]'), // TRs in the table
nextButton = win.dom.querySelector('input.next'),
lastButton = win.dom.querySelector('input.last'),
backButton = win.dom.querySelector('input.back'),
backFullButton = win.dom.querySelector('input.backFull')
;


nextButton?.addEventListener('click', () => {
win.custom._page += this.PAGINATION_LENGTH;
win.rebuild();
});
lastButton?.addEventListener('click', () => {
win.custom._page = -1;
win.rebuild();
});


if( backButton )
//  json2.js
backButton.addEventListener('click', () => {
//  2023-05-10
//  Public Domain.
//  NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.


win.custom._page -= this.PAGINATION_LENGTH;
//  USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
win.rebuild();
//  NOT CONTROL.
});


if( backFullButton )
//  This file creates a global JSON object containing two methods: stringify
backFullButton.addEventListener('click', () => {
//  and parse. This file provides the ES5 JSON capability to ES3 systems.
//  If a project might run on IE8 or earlier, then this file should be included.
//  This file does nothing on ES5 systems.


win.custom._page = 0;
//      JSON.stringify(value, replacer, space)
win.rebuild();
//          value      any JavaScript value, usually an object or array.
});
//          replacer    an optional parameter that determines how object
//                      values are stringified for objects. It can be a
//                      function or an array of strings.
//          space      an optional parameter that specifies the indentation
//                      of nested structures. If it is omitted, the text will
//                      be packed without extra whitespace. If it is a number,
//                      it will specify the number of spaces to indent at each
//                      level. If it is a string (such as "\t" or "&nbsp;"),
//                      it contains the characters used to indent at each level.
//          This method produces a JSON text from a JavaScript value.
//          When an object value is found, if the object contains a toJSON
//          method, its toJSON method will be called and the result will be
//          stringified. A toJSON method does not serialize: it returns the
//          value represented by the name/value pair that should be serialized,
//          or undefined if nothing should be serialized. The toJSON method
//          will be passed the key associated with the value, and this will be
//          bound to the value.


const parentWindow = win.parent;
//          For example, this would serialize Dates as ISO strings.
if( parentWindow ){


// Parent is the same type as this, such as adding subconditions. You need to remove the parent from the list to prevent recursion.
//             Date.prototype.toJSON = function (key) {
if( type === parentWindow.type ){
//                  function f(n) {
//                      // Format integers to have at least two digits.
const el = win.dom.querySelector('tr[data-id="'+parentWindow.id+'"]');
//                      return (n < 10)
if( el )
//                          ? "0" + n
el.remove();
//                          : n;
//                  }
}
//                  return this.getUTCFullYear()  + "-" +
//                      f(this.getUTCMonth() + 1) + "-" +
//                      f(this.getUTCDate())      + "T" +
//                      f(this.getUTCHours())    + ":" +
//                      f(this.getUTCMinutes())   + ":" +
//                      f(this.getUTCSeconds())  + "Z";
//              };


//          You can provide an optional replacer method. It will be passed the
//          key and value of each member, with this bound to the containing
//          object. The value that is returned from your method will be
//          serialized. If your method returns undefined, then the member will
//          be excluded from the serialization.


}
//          If the replacer parameter is an array of strings, then it will be
//          used to select the members to be serialized. It filters the results
//          such that only members with keys listed in the replacer array are
//          stringified.


// Checks if any of the checkboxes are checked
//         Values that do not have JSON representations, such as undefined or
const markers = [...win.dom.querySelectorAll("input.marker")]; // Checkboxes
//          functions, will not be serialized. Such values in objects will be
const checkBatchSelections = () => {
//         dropped; in arrays they will be replaced with null. You can use
//          a replacer function to replace those with JSON values.
let checked = false;
for( let marker of markers ){
if( marker.checked ){
checked = true;
break;
}
}
batchDiv.classList.toggle("hidden", !checked);


};
//          JSON.stringify(undefined) returns undefined.


// Delete asset
//         The optional space parameter produces a stringification of the
const del = elId => {
//          value that is filled with line breaks and indentation to make it
if( MOD.deleteAsset(type, elId) ){
//          easier to read.


DEV.closeAssetEditors(type, elId);
//         If the space parameter is a non-empty string, then that string will
DEV.setDirty(true);
//          be used for indentation. If the space parameter is a number, then
 
//          the indentation will be that many spaces.
}
};
 
// If not linker, handle the batch selectors
if( !isLinker ){
checkBatchSelections();
batchDiv.querySelector('input.deleteSelected').onclick = event => {
const checkedLabels = [];
const markers = win.dom.querySelectorAll("input.marker:checked").values();
for( let marker of markers )
checkedLabels.push(marker.parentElement.parentElement.dataset.id);
if( !checkedLabels.length )
return;
 
if( confirm("Really delete "+checkedLabels.length+" items?") ){
 
for( let label of checkedLabels )
del(label);
 
win.rebuild();
this.rebuildAssetLists(type);
 
}
};
batchDiv.querySelector('input.exportSelected').onclick = event => {
const checkedLabels = [];
const markers = win.dom.querySelectorAll("input.marker:checked").values();
for( let marker of markers )
checkedLabels.push(marker.parentElement.parentElement.dataset.id);
if( !checkedLabels.length )
return;


let data = MOD.getExportData(baseObject.constructor, type, checkedLabels);
//          Example:
Window.create('export'+Generic.generateUUID(), 'jsonExport', 'Export Data - '+type, 'files', function(){
this.setDom('<textarea style="width:100%; height:100%; min-height:10vh">'+esc(JSON.stringify(data, undefined, 2), true)+'</textarea>');
}, undefined, undefined, data);
};


const checkAll = win.dom.querySelector('input.checkAll');
//          text = JSON.stringify(["e", {pluribus: "unum"}]);
checkAll.onchange = event => {
//          // text is '["e",{"pluribus":"unum"}]'
for( let el of markers ){
if( !el.parentNode.parentNode.dataset.mod )
el.checked = !el.parentElement.parentElement.classList.contains("hidden") && checkAll.checked;
}
checkBatchSelections();


};
//          text = JSON.stringify(["e", {pluribus: "unum"}], null, "\t");
//          // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'


}
//          text = JSON.stringify([new Date()], function (key, value) {
//              return this[key] instanceof Date
rows.forEach(el => {
//                  ? "Date(" + this[key] + ")"
//                  : value;
//          });
//          // text is '["Date(---current time---)"]'


// Library view
//     JSON.parse(text, reviver)
if( !isLinker ){
//          This method parses a JSON text to produce an object or array.
//          It can throw a SyntaxError exception.
const base = el.querySelector("input[type=checkbox].marker");
base.parentElement.onclick = event => {
event.stopImmediatePropagation();


if( event.target === event.currentTarget )
//          The optional reviver parameter is a function that can filter and
base.checked = !base.checked;
//          transform the results. It receives each of the keys and values,
checkBatchSelections();
//          and its return value is used instead of the original value.
};
//          If it returns what it received, then the structure is not modified.
//          If it returns undefined then the member is deleted.


}
//          Example:


// Linker view
//         // Parse the text. Values that look like ISO date strings will
// Bind click on row
//         // be converted to Date objects.
el.addEventListener('click', event => {


const elId = event.currentTarget.dataset.id,
//          myData = JSON.parse(text, function (key, value) {
mod = event.currentTarget.dataset.mod,
//              var a;
ext = event.currentTarget.dataset.ext // This is an extend of another asset
//              if (typeof value === "string") {
;
//                  a =
//  /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
//                  if (a) {
//                      return new Date(Date.UTC(
//                        +a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]
//                      ));
//                  }
//                  return value;
//             }
//          });


//          myData = JSON.parse(
//              "[\"Date(09/09/2001)\"]",
//              function (key, value) {
//                  var d;
//                  if (
//                      typeof value === "string"
//                      && value.slice(0, 5) === "Date("
//                      && value.slice(-1) === ")"
//                  ) {
//                      d = new Date(value.slice(5, -1));
//                      if (d) {
//                          return d;
//                      }
//                  }
//                  return value;
//              }
//          );


// Ctrl deletes unless it's a linker
// This is a reference implementation. You are free to copy, modify, or
if( (!mod || ext) && !isLinker && (event.ctrlKey || event.metaKey) && confirm("Really delete?") ){
//  redistribute.


del(ext ? ext : elId);
/*jslint
win.rebuild();
    eval, for, this
this.rebuildAssetLists(type);
*/


}
/*property
    JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
// If it's a linker you can use shift to bring up an editor
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
else if( event.shiftKey && (isLinker && mod)  ){
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
DEV.buildAssetEditor(type, elId);
    test, toJSON, toString, valueOf
}
*/
// Alt clones
else if( event.altKey ){


const asset = DEV.getAssetById(type, elId);
if( !asset )
throw 'Asset not found', type, elId;


// Create a JSON object only if one does not already exist. We create the
this.insertCloneAsset(type, asset, baseObject.constructor, win, true);
// methods in a closure to avoid creating global variables.


}
var JSON = {};
// Unmodified non linker click opens
else if( !isLinker ){


DEV.buildAssetEditor(type, elId);


}
(function () {
    "use strict";


// This is a linker, we need to tie it to the parent
    var rx_one = /^[\],:{}\s]*$/;
else{
    var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
    var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
    var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
    var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;


if( !parentWindow )
    function f(n) {
throw 'Parent window missing';
        // Format integers to have at least two digits.
        return (n < 10)
            ? "0" + n
            : n;
    }


    function this_value() {
        return this.valueOf();
    }


// Get the asset we need to modify
    if (typeof Date.prototype.toJSON !== "function") {
// Linker expects the parent window to be an asset editor unles parentWindow.asset.asset is set
let baseAsset = parentWindow.asset.asset || MOD.getAssetById(parentWindow.type, parentWindow.id), // Window id is the asset ID for asset editors. Can only edit our mod, so get from that
targAsset = this.getAssetById(type, elId) // Target can be from a parent mod, so we'll need to include that in this search, which is why we use this instead of MOD
;


        Date.prototype.toJSON = function () {
if( !baseAsset ){
console.error("Type", type, "parentWindow", parentWindow);
throw 'Base asset not found';
}
if( !targAsset )
throw 'Target asset not found';


// Handle subsets. This is pretty much just used for Collection type assets since they don't have their own database
            return isFinite(this.valueOf())
let targ = win.id.split('::');
                ? (
while( targ.length > 1 )
                    this.getUTCFullYear()
baseAsset = baseAsset[targ.shift()];
                    + "-"
                    + f(this.getUTCMonth() + 1)
                    + "-"
                    + f(this.getUTCDate())
                    + "T"
                    + f(this.getUTCHours())
                    + ":"
                    + f(this.getUTCMinutes())
                    + ":"
                    + f(this.getUTCSeconds())
                    + "Z"
                )
                : null;
        };


const key = targ.shift();
        Boolean.prototype.toJSON = this_value;
        Number.prototype.toJSON = this_value;
        String.prototype.toJSON = this_value;
    }


// win.id contains the field you're looking to link to
    var gap;
let label = targAsset.label || targAsset.id;
    var indent;
if( targAsset._e )
    var meta;
label = targAsset._e;
    var rep;


// Single assigns directly to the key
if( single ){
baseAsset[key] = label;
}
// Nonsingle appends to array
else{


if( !Array.isArray(baseAsset[key]) )
    function quote(string) {
baseAsset[key] = [];
baseAsset[key].push(label);


}
// If the string contains no control characters, no quote characters, and no
win.close();
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.


parentWindow.rebuild();
        rx_escapable.lastIndex = 0;
DEV.setDirty(true);
        return rx_escapable.test(string)
this.rebuildAssetLists(parentWindow.type);
            ? "\"" + string.replace(rx_escapable, function (a) {
this.propagateChange(win);
                var c = meta[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            }) + "\""
            : "\"" + string + "\"";
    }


}
}, {
passive : true
});


});
    function str(key, holder) {
win.dom.querySelector('input.new').onclick = event => {
const obj = baseObject.constructor.saveThis(baseObject, "mod");
this.insertAsset(type, obj, win);
};


// Produce a string from holder[key].


// Search filter
        var i;          // The loop counter.
const searchInput = win.dom.querySelector('input.search');
        var k;          // The member key.
const performSearch = () => {
        var v;          // The member value.
        var length;
        var mind = gap;
        var partial;
        var value = holder[key];


delete win._searchResults;
// If the value has a toJSON method, call it to obtain a replacement value.
let searchTerm = searchInput.value.toLowerCase();
if( win._search !== searchTerm )
win.custom._page = 0;
win._search = searchTerm;


win.rebuild();
        if (
            value
            && typeof value === "object"
            && typeof value.toJSON === "function"
        ) {
            value = value.toJSON(key);
        }


};
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.


if( win._search )
        if (typeof rep === "function") {
searchInput.value = win._search;
            value = rep.call(holder, key, value);
        }


let searchTimeout;
// What happens next depends on the value's type.
searchInput.onchange = event => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
performSearch();
}, 250);


};
        switch (typeof value) {
searchInput.onkeypress = event => {
        case "string":
            return quote(value);


if( event.key === 'Enter' ){
        case "number":
clearTimeout(searchTimeout);
performSearch();
}


};
// JSON numbers must be finite. Encode non-finite numbers as null.


setTimeout(() => {
            return (isFinite(value))
if( win === Window.front)
                ? String(value)
searchInput.focus();
                : "null";
}, 10)


},
        case "boolean":
        case "null":


// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce "null". The case is included here in
// the remote chance that this gets fixed someday.


// Takes an asset and tries to clone it, returns the cloned object
            return String(value);
// Type: table in the mod, such as dungeonTemplate
// Asset: Asset to clone such as a DungeonTemplate
insertCloneAsset( type, asset, constructor, parentWindow, openEditor = true ){


const out = mod.mod.deepCloneAsset(type, constructor, asset);
// If the type is "object", we might be dealing with an object or an array or
// Cloning adds the whole object to our mod
// null.


delete out._e;
        case "object":
delete out._ext;


this.onInsertAsset(type, out, parentWindow, openEditor);
// Due to a specification blunder in ECMAScript, typeof null is "object",
return out;
// so watch out for that case.


},
            if (!value) {
                return "null";
            }


// Make an array to hold the partial results of stringifying this object value.


// mParent should be an object if supplied (see Mod.js for info about parented assets)
            gap += indent;
/*
            partial = [];
type is the window type (needs to be listed in Modtools2.js
asset is the asset to insert
win is the parent window
openEditor is if you should open the editor immediately
windowData is custom data stored on the window. AVOID OBJECTS
*/
insertAsset( type, asset = {}, win, openEditor = true, windowData = '' ){
mod.mod[type].push(asset);
this.onInsertAsset(type, asset, win, openEditor, windowData);
},


onInsertAsset( type, asset, win, openEditor = true, windowData = '' ){
// Is the value an array?


if( win?.editorOnCreate )
            if (Object.prototype.toString.apply(value) === "[object Array]") {
win.editorOnCreate(win, asset);


mod.setDirty(true);
// The value is an array. Stringify every element. Use null as a placeholder
if( openEditor )
// for non-JSON values.
mod.buildAssetEditor(type, asset.label || asset.id, undefined, win, windowData);
this.rebuildAssetLists(type);


},
                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || "null";
                }


// Rebuilds all listings by type
// Join all of the elements together, separated with commas, and wrap them in
rebuildAssetLists( type ){
// brackets.


for( let win of Window.pages.values() ){
                v = partial.length === 0
                    ? "[]"
                    : gap
                        ? (
                            "[\n"
                            + gap
                            + partial.join(",\n" + gap)
                            + "\n"
                            + mind
                            + "]"
                        )
                        : "[" + partial.join(",") + "]";
                gap = mind;
                return v;
            }


if(
// If the replacer is an array, use it to select the members to be stringified.
(win.type === "Database" && win.id === type) || // This is a database listing of this type
(win.type === "linker" && win.asset && win.asset.targetType === type)
){


win.rebuild();
            if (rep && typeof rep === "object") {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === "string") {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                (gap)
                                    ? ": "
                                    : ":"
                            ) + v);
                        }
                    }
                }
            } else {


}
// Otherwise, iterate through all of the keys in the object.


}
                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                (gap)
                                    ? ": "
                                    : ":"
                            ) + v);
                        }
                    }
                }
            }


},
// Join all of the member texts together, separated with commas,
// and wrap them in braces.


            v = partial.length === 0
                ? "{}"
                : gap
                    ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}"
                    : "{" + partial.join(",") + "}";
            gap = mind;
            return v;
        }
    }


// Checks for an onChildChange method on win and any parents, and calls it
// If the JSON object does not yet have a stringify method, give it one.
propagateChange( win ){


Window.getByType('Node Editor').forEach(el => el.onDbAssetChange(win.type, win.id));
    if (typeof JSON.stringify !== "function") {
        meta = {    // table of character substitutions
            "\b": "\\b",
            "\t": "\\t",
            "\n": "\\n",
            "\f": "\\f",
            "\r": "\\r",
            "\"": "\\\"",
            "\\": "\\\\"
        };
        JSON.stringify = function (value, replacer, space) {


let p = win;
// The stringify method takes a value and an optional replacer, and an optional
while( true ){
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.


if( typeof p.onChange === "function" )
            var i;
p.onChange(win);
            gap = "";
p = p.parent;
            indent = "";


if( !p )
// If the space parameter is a number, make an indent string containing that
return;
// many spaces.


}
            if (typeof space === "number") {
                for (i = 0; i < space; i += 1) {
                    indent += " ";
                }


},
// If the space parameter is a string, it will be used as the indent string.


// Tries to get an asset from our mod or a parent mod, tries to find id in label or actual id
            } else if (typeof space === "string") {
getAssetById( type, id ){
                indent = space;
            }


let out = window.mod.mod.getAssetById(type, id);
// If there is a replacer, it must be a function or an array.
if( out )
// Otherwise, throw an error.
return out;
return window.mod.parentMod.getAssetById(type, id);


},
            rep = replacer;
            if (replacer && typeof replacer !== "function" && (
                typeof replacer !== "object"
                || typeof replacer.length !== "number"
            )) {
                throw new Error("JSON.stringify");
            }


// Shared between editorDungeon and editorDungeonRoom
// Make a fake root object containing our value under the key of "".
bindTestReverb( typeEl, wetEl, lowpassEl, buttonEl ){
// Return the result of stringifying the value.


buttonEl.onclick = async () => {
            return str("", {"": value});
        };
    }


if( !this.TEST_AUDIO ){
await Audio.begin();
this.TEST_AUDIO = new Audio('test');
}
let wet = +wetEl.value || 1.0;
let lp = +lowpassEl.value || 1.0;


await this.TEST_AUDIO.setReverb(typeEl.value);
// If the JSON object does not yet have a parse method, give it one.
this.TEST_AUDIO.setWet(wet);
this.TEST_AUDIO.setLowpass(lp);
const sounds = ["trap_trigger", "tickle", "slap", "pinch", "chest_open"];
const audio = await this.TEST_AUDIO.play('/media/audio/'+randElem(sounds)+'.ogg');


};
    if (typeof JSON.parse !== "function") {
        JSON.parse = function (text, reviver) {


},
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.


helpLinkedList : 'This is a linked list. Click an item to edit it (provided it belongs to this mod), ctrl+click to remove an item. Use the arrows to move it up/down.',
            var j;


            function walk(holder, key) {


// Player/PlayerTemplate JSON file parser
// The walk method is used to recursively walk the resulting structure so
bindAdvancedArtLayers( win, asset, DB ){
// that modifications can be made.


win.dom.querySelector("div.istates").appendChild(EditorPlayerIconState.assetTable(win, asset, "istates"));
                var k;
win.dom.querySelector("input.importAdvancedIcons").onchange = event => {
                var v;
                var value = holder[key];
                if (value && typeof value === "object") {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


if( !event.target.files.length )
return;
const reader = new FileReader();
reader.onload = rEvt => {
event.target.value = "";
const json = JSON.parse(rEvt.target.result);
const data = json.layers;
const url = json.url || "";


// Parsing happens in four stages. In the first stage, we replace certain
if( !Array.isArray(data) )
// Unicode characters with escape sequences. JavaScript handles many characters
throw 'Invalid JSON data. Not an array.';
// incorrectly, either silently deleting them, or treating them as line endings.
if( win.dom.querySelector("input.replaceAll").checked ){
for( let istate of asset.istates ) {
window.mod.mod.deleteAsset('playerIconStates', istate);
}
asset.istates = [];
}
if( !Array.isArray(asset.istates) )
asset.istates = [];
const replaceIntoIstates = istate => {
if( !isNaN(istate.opacity) )
istate.opacity = Math.round(istate.opacity*100)/100;
const out = istate.save("mod");
out._mParent = {type : DB, label : asset.label};
window.mod.mod.mergeAsset("playerIconStates", out);
if( !asset.istates.includes(istate.id) )
asset.istates.push(istate.id);
window.mod.setDirty(true);
}
for( let istate of data ){
let icon = istate.icon;
if( url )
icon = url + (url.endsWith('/') || icon.startsWith('/') ? '' : '/') + icon;
istate.icon = icon;
replaceIntoIstates(new PlayerIconState(istate));
}


win.dom.querySelector("div.istates").replaceChildren(EditorPlayerIconState.assetTable(win, asset, "istates"));
            text = String(text);
            rx_dangerous.lastIndex = 0;
            if (rx_dangerous.test(text)) {
                text = text.replace(rx_dangerous, function (a) {
                    return (
                        "\\u"
                        + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
                    );
                });
            }


};
// In the second stage, we run the text against regular expressions that look
reader.readAsText(event.target.files[0]);
// for non-JSON patterns. We are especially concerned with "()" and "new"
// because they can cause invocation, and "=" because it can cause mutation.
};
// But just to be safe, we want to reject all unexpected forms.
win.dom.querySelector("input.exportAdvancedIcons").onclick = () => {
if( !Array.isArray(asset.istates) || !asset.istates.length )
return;


let outData = {
// We split the second stage into 4 regexp operations in order to work around
url : '',
// crippling inefficiencies in IE's and Safari's regexp engines. First we
layers : [],
// replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
};
// replace all simple value tokens with "]" characters. Third, we delete all
const out = asset.istates.map(el => mod.mod.getAssetById('playerIconStates', el)).filter(el => Boolean(el));
// open brackets that follow a colon or comma or that begin the text. Finally,
// See if there's a common URL
// we look to see that the remaining characters are only whitespace or "]" or
for( let asset of out ){
// "," or ":" or "{" or "}". If that is so, then the text is safe for eval.
// First element checks for a common URL
if( !outData.url ){
let url = asset.icon.split('/');
url.pop();
outData.url = url.join('/')+'/';
if( !outData.url )
break; // If there's no URL we can disregard this entirely.
continue;


}
            if (
// Now try to disprove that all start with the same URL
                rx_one.test(
if( !asset.icon.startsWith(outData.url) ){
                    text
outData.url = '';
                        .replace(rx_two, "@")
break;
                        .replace(rx_three, "]")
}
                        .replace(rx_four, "")
                )
            ) {


}
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The "{" operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.


if( outData.url ){
                j = eval("(" + text + ")");
out.map(el => el.icon = el.icon.substring(outData.url.length)); // remove the URL frmo the icons
}
outData.layers = out;


const blob = new Blob([JSON.stringify(outData, null, 4)], { type: "text/json" });
// In the optional fourth stage, we recursively walk the new structure, passing
const link = document.createElement("a");
// each name/value pair to a reviver function for possible transformation.
link.download = asset.label+".json";
link.href = window.URL.createObjectURL(blob);
link.dataset.downloadurl = ["text/json", link.download, link.href].join(":");
const evt = new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true,
});
link.dispatchEvent(evt);
link.remove();
};


},
                return (typeof reviver === "function")
                    ? walk({"": j}, "")
                    : j;
            }


getAdvancedArtLayersForm(){
// If the text is not JSON parseable, then a SyntaxError is thrown.
return 'Advanced icon states: <div class="istates"></div>'+
'<div class="labelFlex">'+
'<label>Import JSON <input type="file" class="importAdvancedIcons" accept=".json" /> Replace ALL: <input type="checkbox" checked class="replaceAll" /></label>'+
'<label><input type="button" value="Export JSON" class="exportAdvancedIcons" /></label>'+
'</div>';
},


};
            throw new SyntaxError("JSON.parse");
        };
    }
}());


exec();


</pre>
</pre>


[[Category:Modding]]
[[Category:Modding]]

Latest revision as of 15:51, 20 February 2025

The following is a script you can use along with the Creating Advanced Art Layers Guide to speed up connecting your advanced art layers to your FQ mod.

To use it, simply copy the content into a new text file and name it fqcrop_batch.jsx

You can either put this in your Phothoshop/Presets/Scripts folder and restart photoshop to use it from file > scripts. Or you can go to file > scripts > browse.

/*
	Note: This is similar to the fqcrop.jsx file except it exports all layers one at a time.
	Usage: See fqcrop.jsx for more info. Things you need to keep in mind in this implementation:
	- Each art layer can only consist of ONE photoshop layer
	- All layers must begin with <layerNr>_ ex 30_bikini_light_ub to use layer 30 (upper body base)
	- A JSON metadata file named the same as the original file will be created or updated. It's going to need a bit of editing, but you can use it to quickly upload a full character.
	- Layers and groups starting with # are ignored.
	- If a JSON file exists, it's loaded and updated. Missing layers aren't deleted from it. So if you remove layers you have to remove them from the JSON file or delete the JSON file to generate a new one.
	- The following values are overwritten into the JSON file, using the photoshop settings:
		- icon
		- x
		- y
		- blendMode (only normal, multiply, overlay are supported)
		- opacity
*/
var startRulesUnits = preferences.rulerUnits;
var doc = activeDocument;
var docW = doc.width;
var docH = doc.height;
var allLayers = [];
var dirJson = decodeURI(doc.path.fsName)+"/";
var jsonName = doc.name.split(".");
jsonName.pop();
var fName = jsonName.join('_')
var dir = dirJson+fName+"/";
jsonName = jsonName.join(".")+".json";
var pics = [];
var url = '';
var bgName = "";
var bgLayer;
Array.prototype.indexOf = function ( item ) {

	  var index = 0, length = this.length;

	  for ( ; index < length; index++ ) {

				if ( this[index] === item )

						  return index;

	  }

	  return -1;

  };

var condMap = {
    '26_sling_heavy' : ['targetWearsSlingBikini','targetLowerBodyHard'],
    '25_sling_heavy' : ['targetWearsSlingBikini','targetLowerBodyHard'],
    '26_sling_med' : ['targetWearsSlingBikini','targetLowerBodyLeather'],
    '25_sling_med' : ['targetWearsSlingBikini','targetLowerBodyLeather'],
    '26_sling_cloth' : ['targetWearsSlingBikini'],
    '25_sling_cloth' : ['targetWearsSlingBikini'],
    '26_bodysuit_leather' : ['targetBodysuit', 'targetLowerBodyLeather'],
    '25_bodysuit_leather' : ['targetBodysuit', 'targetLowerBodyLeather'],
    '26_bodysuit_cloth' : ['targetBodysuit'],
    '25_bodysuit_cloth' : ['targetBodysuit'],
    
    '36_heavy_ub' : ['targetUpperBodyHard', 'targetNoBodysuit'],
    '35_heavy_ub' : ['targetUpperBodyHard', 'targetNoBodysuit'],
    
    '26_heavy_lb' : ['targetLowerBodyHard'],
    '25_heavy_lb' : ['targetLowerBodyHard'],
    
    '36_bikini_leather_ub' : ['targetUpperBodyBikini', 'targetUpperBodyLeather', 'targetNoBodysuit'],
    '35_bikini_leather_ub' : ['targetUpperBodyBikini', 'targetUpperBodyLeather', 'targetNoBodysuit'],
    '26_bikini_leather_lb' : ['targetWearsThong', 'targetLowerBodyLeather'],
    '25_bikini_leather_lb' : ['targetWearsThong', 'targetLowerBodyLeather'],
    
    '36_bikini_cloth_ub' : ['targetUpperBodyBikini', 'targetNoBodysuit'],
    '35_bikini_cloth_ub' : ['targetUpperBodyBikini', 'targetNoBodysuit'],
    '26_bikini_cloth_lb' : ['targetWearsThong'],
    '25_bikini_cloth_lb' : ['targetWearsThong'],
    
    '36_cloth_ub' : ['targetWearsUpperBody', 'targetNoBodysuit'],
    '35_cloth_ub' : ['targetWearsUpperBody', 'targetNoBodysuit'],
    '26_cloth_lb' : ['targetWearsLowerBody'],
    '25_cloth_lb' : ['targetWearsLowerBody'],
    
    '15_aroused_heavy' : ['metaVeryArousing'],
    '15_pain_heavy' : ['metaVeryPainful'],
    '10_aroused' : ['metaArousing'],
    '10_pain' : ['metaPainful'],
    '5_orgasm' : ['targetHasOrgasm'], 
};

function exec(){
	
	preferences.rulerUnits = Units.PIXELS;
	
	fetchLayers(doc);


	// Fetch JSON if possible
	var jsonFile = new File(dir+jsonName);
	jsonFile.encoding = 'UTF8';
	if( jsonFile.exists ){
		
		jsonFile.open("r");
        var parsed = JSON.parse(jsonFile.read());
        url = parsed.url || '';
		bgName = parsed.base || "";
		pics = parsed.layers;
		jsonFile.close();
		
	}
	
	var pngOpts = new PNGSaveOptions();
	pngOpts.method = stringIDToTypeID("thorough");
	pngOpts.compression = 1;
	
	var missingFromMap = [];
	for( var i = 0; i < allLayers.length; ++i ){
		
		var l = allLayers[i];
		l.visible = true;
		if( i )
			allLayers[i-1].visible = false;
		
		var baseOpacity = l.opacity
		
		var bounds = l.bounds;
		var left = bounds[0];
		var right = docW-bounds[2];
		var top = bounds[1];
		var bottom = docH - bounds[3];
		var layerName = l.name;
		var layerNr = parseInt(layerName);
		var blendMode = 'source-over';
		if( l.blendMode == BlendMode.MULTIPLY )
			blendMode = 'multiply';
		else if( l.blendMode == BlendMode.OVERLAY )
			blendMode = 'overlay';
		var opacity = baseOpacity/100;
		
		if( isNaN(layerNr) )
			alert("Layer "+layerName+" needs to start with the FQ art layer number. Use # if you don't want to save this layer.");
		else if( right < 1 || bottom < 1 ){
			alert("Layer "+layerName+" invalid dimensions "+left + " "+ right +" :: "+top+" "+bottom);
		}
		else{
			
			var file = layerName+".png";
			
			var folder = Folder(dir);
			if( !folder.exists )
				folder.create();
			
			l.opacity = 100;
						
			//alert("Image cropped x:"+left+" y:"+top)
			var workLayer = doc.duplicate();

			workLayer.crop(bounds);
			
			
			var fileOut = new File(dir+file)
			workLayer.saveAs(fileOut, pngOpts, true);	
			workLayer.close(SaveOptions.DONOTSAVECHANGES);
			
			l.opacity = baseOpacity;
			
			var duration = 0;
			if( layerNr < 20 && layerNr >= 10 )
				duration = 3000; // Facial expressions generally.
			var slots = {
				s26 : 'lowerBody',
				s31 : 'hands',
				s36 : 'upperBody',
				s41 : 'jewelleryCosmetic',
				s46 : 'lowerBodyCosmetic',
				s51 : 'upperBodyCosmetic',
			};
			
			var cm = condMap[layerName] || [];
			if( !cm.length )
				missingFromMap.push(layerName);
			
			updatePic(makePic({
				icon : file,
				layer : layerNr,
				duration : duration,
				x : parseInt(left),
				y : parseInt(top),
				slot : slots['s'+layerNr] || '',
				blendMode : blendMode,
				opacity : opacity,
                conditions : condMap[layerName] || [],
			}));
			
		}
		
		
		
	}
	if( missingFromMap.length )
		alert("The following layers are missing auto condition definitions, check your spelling etc: "+missingFromMap.join(", "));
		
	// Save BG as nude layer
	if( bgLayer ){
		
		if( allLayers.length )
			allLayers[i-1].visible = false;
		bgLayer.visible = true;
		var jpegOpts = new JPEGSaveOptions();
		jpegOpts.quality = 9;
		var fn = fName+"_n.jpg";
		doc.saveAs(new File(dir+fn), jpegOpts, true);
		bgName = fn;
		
	
	}
	
	var keys = [];
	for( var i in condMap ){
		keys.push(i);
	}
	
	pics.sort(function(a, b){
		var aln = a.icon.split(".")[0];
		var bln = b.icon.split(".")[0];
		var aPos = keys.indexOf(aln);
		var bPos = keys.indexOf(bln);
		if( aPos == bPos )
			return 0;
		if( aPos == -1 )
			return 1;
		if( bPos == -1 )
			return -1;
		return aPos < bPos ? -1 : 1;
		
	});
	

	var dump = JSON.stringify({
		base : bgName,
        url : url,
        layers : pics
    }, null, 4);
	jsonFile.open("w");
	jsonFile.write(dump);
	jsonFile.close();

	preferences.rulerUnits = startRulesUnits;

}













// Accept data from makePic
function updatePic( picData ){
	for( var i = 0; i < pics.length; ++i ){
		
		var p = pics[i];
		if( p.icon == picData.icon ){
			
			p.layer = picData.layer;
			p.x = picData.x;
			p.y = picData.y;
			p.blendMode = picData.blendMode;
			p.opacity = picData.opacity;
			
			return;
		}
		
	}
	
	pics.push(picData);
	
}


// Fetches all viable art layers
function fetchLayers( parentLayer, ignore ){
	
	for( var i = 0; i < parentLayer.layers.length; ++i ){
		
		var l = parentLayer.layers[i];
		
		var ign = ignore;
		var isBg = l.name == "Background";
		if( !ignore )
			ign = ( l.name.substring(0,1) == "#" || isBg );
		if( isBg )
			bgLayer = l;

		l.visible = (l.typename == "LayerSet");

		if( l.typename == "LayerSet" ){
			fetchLayers(l, ign);
			continue;
		}
		
		if( !ign )
			allLayers.push(l);
		
	}
	
}

function makePic( data ){
	
	if( typeof data != "object" )
		data = {};
	
	var out = {};
	out.icon = data.icon;
	out.conditions = data.conditions || [];
	out.layer = data.layer || 0;
	out.duration = parseInt(data.duration) || 0;
	out.x = data.x || 0;
	out.y = data.y || 0;
	out.slot = data.slot || '';
	out.blendMode = data.blendMode || 'source-over';
	out.opacity = 1.0;
	if( !isNaN(data.opacity) )
		out.opacity = data.opacity;
    out.conditions = data.conditions;
	return out;
	
}



function save_as_png(doc, file, copy, comp, filter, none){

    try {

        if (copy == undefined) copy = true;

        if (comp == undefined) comp = 9;

        if (none == undefined) none = true;

        if (filter == undefined) filter = "PNGFilterAdaptive";

        var doc0 = app.activeDocument;

        app.activeDocument = doc;

        var d = new ActionDescriptor();

        var d1 = new ActionDescriptor();

        d1.putEnumerated(stringIDToTypeID("method"), stringIDToTypeID("PNGMethod"), stringIDToTypeID("quick"));

        if (none)

            d1.putEnumerated(stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceNone"));

        else

            d1.putEnumerated(stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceType"), stringIDToTypeID("PNGInterlaceAdam7"));

        d1.putEnumerated(stringIDToTypeID("PNGFilter"), stringIDToTypeID("PNGFilter"), stringIDToTypeID(filter));

        d1.putInteger(stringIDToTypeID("compression"), comp);

        d.putObject(stringIDToTypeID("as"), stringIDToTypeID("PNGFormat"), d1);

        d.putPath(stringIDToTypeID("in"), file);

        d.putBoolean(stringIDToTypeID("copy"), copy);

        executeAction(stringIDToTypeID("save"), d, DialogModes.NO);

        app.activeDocument = doc0;

        return true;

        }

    catch (e) { alert(e); return false; }

}





//  json2.js
//  2023-05-10
//  Public Domain.
//  NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.

//  USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
//  NOT CONTROL.

//  This file creates a global JSON object containing two methods: stringify
//  and parse. This file provides the ES5 JSON capability to ES3 systems.
//  If a project might run on IE8 or earlier, then this file should be included.
//  This file does nothing on ES5 systems.

//      JSON.stringify(value, replacer, space)
//          value       any JavaScript value, usually an object or array.
//          replacer    an optional parameter that determines how object
//                      values are stringified for objects. It can be a
//                      function or an array of strings.
//          space       an optional parameter that specifies the indentation
//                      of nested structures. If it is omitted, the text will
//                      be packed without extra whitespace. If it is a number,
//                      it will specify the number of spaces to indent at each
//                      level. If it is a string (such as "\t" or " "),
//                      it contains the characters used to indent at each level.
//          This method produces a JSON text from a JavaScript value.
//          When an object value is found, if the object contains a toJSON
//          method, its toJSON method will be called and the result will be
//          stringified. A toJSON method does not serialize: it returns the
//          value represented by the name/value pair that should be serialized,
//          or undefined if nothing should be serialized. The toJSON method
//          will be passed the key associated with the value, and this will be
//          bound to the value.

//          For example, this would serialize Dates as ISO strings.

//              Date.prototype.toJSON = function (key) {
//                  function f(n) {
//                      // Format integers to have at least two digits.
//                      return (n < 10)
//                          ? "0" + n
//                          : n;
//                  }
//                  return this.getUTCFullYear()   + "-" +
//                       f(this.getUTCMonth() + 1) + "-" +
//                       f(this.getUTCDate())      + "T" +
//                       f(this.getUTCHours())     + ":" +
//                       f(this.getUTCMinutes())   + ":" +
//                       f(this.getUTCSeconds())   + "Z";
//              };

//          You can provide an optional replacer method. It will be passed the
//          key and value of each member, with this bound to the containing
//          object. The value that is returned from your method will be
//          serialized. If your method returns undefined, then the member will
//          be excluded from the serialization.

//          If the replacer parameter is an array of strings, then it will be
//          used to select the members to be serialized. It filters the results
//          such that only members with keys listed in the replacer array are
//          stringified.

//          Values that do not have JSON representations, such as undefined or
//          functions, will not be serialized. Such values in objects will be
//          dropped; in arrays they will be replaced with null. You can use
//          a replacer function to replace those with JSON values.

//          JSON.stringify(undefined) returns undefined.

//          The optional space parameter produces a stringification of the
//          value that is filled with line breaks and indentation to make it
//          easier to read.

//          If the space parameter is a non-empty string, then that string will
//          be used for indentation. If the space parameter is a number, then
//          the indentation will be that many spaces.

//          Example:

//          text = JSON.stringify(["e", {pluribus: "unum"}]);
//          // text is '["e",{"pluribus":"unum"}]'

//          text = JSON.stringify(["e", {pluribus: "unum"}], null, "\t");
//          // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'

//          text = JSON.stringify([new Date()], function (key, value) {
//              return this[key] instanceof Date
//                  ? "Date(" + this[key] + ")"
//                  : value;
//          });
//          // text is '["Date(---current time---)"]'

//      JSON.parse(text, reviver)
//          This method parses a JSON text to produce an object or array.
//          It can throw a SyntaxError exception.

//          The optional reviver parameter is a function that can filter and
//          transform the results. It receives each of the keys and values,
//          and its return value is used instead of the original value.
//          If it returns what it received, then the structure is not modified.
//          If it returns undefined then the member is deleted.

//          Example:

//          // Parse the text. Values that look like ISO date strings will
//          // be converted to Date objects.

//          myData = JSON.parse(text, function (key, value) {
//              var a;
//              if (typeof value === "string") {
//                  a =
//   /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
//                  if (a) {
//                      return new Date(Date.UTC(
//                         +a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]
//                      ));
//                  }
//                  return value;
//              }
//          });

//          myData = JSON.parse(
//              "[\"Date(09/09/2001)\"]",
//              function (key, value) {
//                  var d;
//                  if (
//                      typeof value === "string"
//                      && value.slice(0, 5) === "Date("
//                      && value.slice(-1) === ")"
//                  ) {
//                      d = new Date(value.slice(5, -1));
//                      if (d) {
//                          return d;
//                      }
//                  }
//                  return value;
//              }
//          );

//  This is a reference implementation. You are free to copy, modify, or
//  redistribute.

/*jslint
    eval, for, this
*/

/*property
    JSON, apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
    getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
    lastIndex, length, parse, prototype, push, replace, slice, stringify,
    test, toJSON, toString, valueOf
*/


// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.

var JSON = {};


(function () {
    "use strict";

    var rx_one = /^[\],:{}\s]*$/;
    var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
    var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
    var rx_four = /(?:^|:|,)(?:\s*\[)+/g;
    var rx_escapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
    var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;

    function f(n) {
        // Format integers to have at least two digits.
        return (n < 10)
            ? "0" + n
            : n;
    }

    function this_value() {
        return this.valueOf();
    }

    if (typeof Date.prototype.toJSON !== "function") {

        Date.prototype.toJSON = function () {

            return isFinite(this.valueOf())
                ? (
                    this.getUTCFullYear()
                    + "-"
                    + f(this.getUTCMonth() + 1)
                    + "-"
                    + f(this.getUTCDate())
                    + "T"
                    + f(this.getUTCHours())
                    + ":"
                    + f(this.getUTCMinutes())
                    + ":"
                    + f(this.getUTCSeconds())
                    + "Z"
                )
                : null;
        };

        Boolean.prototype.toJSON = this_value;
        Number.prototype.toJSON = this_value;
        String.prototype.toJSON = this_value;
    }

    var gap;
    var indent;
    var meta;
    var rep;


    function quote(string) {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.

        rx_escapable.lastIndex = 0;
        return rx_escapable.test(string)
            ? "\"" + string.replace(rx_escapable, function (a) {
                var c = meta[a];
                return typeof c === "string"
                    ? c
                    : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4);
            }) + "\""
            : "\"" + string + "\"";
    }


    function str(key, holder) {

// Produce a string from holder[key].

        var i;          // The loop counter.
        var k;          // The member key.
        var v;          // The member value.
        var length;
        var mind = gap;
        var partial;
        var value = holder[key];

// If the value has a toJSON method, call it to obtain a replacement value.

        if (
            value
            && typeof value === "object"
            && typeof value.toJSON === "function"
        ) {
            value = value.toJSON(key);
        }

// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.

        if (typeof rep === "function") {
            value = rep.call(holder, key, value);
        }

// What happens next depends on the value's type.

        switch (typeof value) {
        case "string":
            return quote(value);

        case "number":

// JSON numbers must be finite. Encode non-finite numbers as null.

            return (isFinite(value))
                ? String(value)
                : "null";

        case "boolean":
        case "null":

// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce "null". The case is included here in
// the remote chance that this gets fixed someday.

            return String(value);

// If the type is "object", we might be dealing with an object or an array or
// null.

        case "object":

// Due to a specification blunder in ECMAScript, typeof null is "object",
// so watch out for that case.

            if (!value) {
                return "null";
            }

// Make an array to hold the partial results of stringifying this object value.

            gap += indent;
            partial = [];

// Is the value an array?

            if (Object.prototype.toString.apply(value) === "[object Array]") {

// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.

                length = value.length;
                for (i = 0; i < length; i += 1) {
                    partial[i] = str(i, value) || "null";
                }

// Join all of the elements together, separated with commas, and wrap them in
// brackets.

                v = partial.length === 0
                    ? "[]"
                    : gap
                        ? (
                            "[\n"
                            + gap
                            + partial.join(",\n" + gap)
                            + "\n"
                            + mind
                            + "]"
                        )
                        : "[" + partial.join(",") + "]";
                gap = mind;
                return v;
            }

// If the replacer is an array, use it to select the members to be stringified.

            if (rep && typeof rep === "object") {
                length = rep.length;
                for (i = 0; i < length; i += 1) {
                    if (typeof rep[i] === "string") {
                        k = rep[i];
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                (gap)
                                    ? ": "
                                    : ":"
                            ) + v);
                        }
                    }
                }
            } else {

// Otherwise, iterate through all of the keys in the object.

                for (k in value) {
                    if (Object.prototype.hasOwnProperty.call(value, k)) {
                        v = str(k, value);
                        if (v) {
                            partial.push(quote(k) + (
                                (gap)
                                    ? ": "
                                    : ":"
                            ) + v);
                        }
                    }
                }
            }

// Join all of the member texts together, separated with commas,
// and wrap them in braces.

            v = partial.length === 0
                ? "{}"
                : gap
                    ? "{\n" + gap + partial.join(",\n" + gap) + "\n" + mind + "}"
                    : "{" + partial.join(",") + "}";
            gap = mind;
            return v;
        }
    }

// If the JSON object does not yet have a stringify method, give it one.

    if (typeof JSON.stringify !== "function") {
        meta = {    // table of character substitutions
            "\b": "\\b",
            "\t": "\\t",
            "\n": "\\n",
            "\f": "\\f",
            "\r": "\\r",
            "\"": "\\\"",
            "\\": "\\\\"
        };
        JSON.stringify = function (value, replacer, space) {

// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.

            var i;
            gap = "";
            indent = "";

// If the space parameter is a number, make an indent string containing that
// many spaces.

            if (typeof space === "number") {
                for (i = 0; i < space; i += 1) {
                    indent += " ";
                }

// If the space parameter is a string, it will be used as the indent string.

            } else if (typeof space === "string") {
                indent = space;
            }

// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.

            rep = replacer;
            if (replacer && typeof replacer !== "function" && (
                typeof replacer !== "object"
                || typeof replacer.length !== "number"
            )) {
                throw new Error("JSON.stringify");
            }

// Make a fake root object containing our value under the key of "".
// Return the result of stringifying the value.

            return str("", {"": value});
        };
    }


// If the JSON object does not yet have a parse method, give it one.

    if (typeof JSON.parse !== "function") {
        JSON.parse = function (text, reviver) {

// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.

            var j;

            function walk(holder, key) {

// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.

                var k;
                var v;
                var value = holder[key];
                if (value && typeof value === "object") {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }


// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.

            text = String(text);
            rx_dangerous.lastIndex = 0;
            if (rx_dangerous.test(text)) {
                text = text.replace(rx_dangerous, function (a) {
                    return (
                        "\\u"
                        + ("0000" + a.charCodeAt(0).toString(16)).slice(-4)
                    );
                });
            }

// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with "()" and "new"
// because they can cause invocation, and "=" because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with "@" (a non-JSON character). Second, we
// replace all simple value tokens with "]" characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or "]" or
// "," or ":" or "{" or "}". If that is so, then the text is safe for eval.

            if (
                rx_one.test(
                    text
                        .replace(rx_two, "@")
                        .replace(rx_three, "]")
                        .replace(rx_four, "")
                )
            ) {

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The "{" operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval("(" + text + ")");

// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.

                return (typeof reviver === "function")
                    ? walk({"": j}, "")
                    : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError("JSON.parse");
        };
    }
}());

exec();