Generic Script to Save / Reload Window Parameters

Photoshop Script Snippets - Note: Full Scripts go in the Photoshop Scripts Forum

Moderators: Tom, Kukurykus

Andrew

Generic Script to Save / Reload Window Parameters

Post by Andrew »

I've been meaning to do this for a long time - I finally got round to it.

The following code / script provides a generalised method for saving and reloading Extend Script Window variables. It is independent of the structure and namespace of your window, the use of Panel or Group structures etc. It should be usable on any ES window for CS and CS2.

Run with default settings it will save (and reload to your window on the next run) all the window.controlObject.text and window.controlObject.value properties from your UI window's latest run eg myedittext.text, myradiobutton.value, myslider.value etc.

Alternatively you can target specific types of control object, and, if you wish, specific properties of that control object:


Code: Select allwTAr.push(['checkbox']); // returns the default 'value' property for all checkboxs

wTAr.push(['edittext','text','bounds']); //return the text and bounds properties for all edittext variables

Alternatively you can target control objects by variable name - in which case you must specify the required property / properties:

Code: Select allwTAr.push(['fsSelCb','value']);
wTAr.push(['fsSelCb','value','enabled']);

Sometimes I find I want to save all my checkbox's except for say 'delete source image', which I always want set to unticked to start with. For this there is the Exclude array wXAr. Unlike the other array parameters, this is string based, see the difference in the second example.

Code: Select allwXAr.push('.fsFolEt.');
wXAr.push('.fsFolEt.text');

The following does the actual work:

Code: Select all// w = window variable as in w = new Window () or w = new Window (myresourcestring)
// wTAr the array of window properties you want to save, if undefined default properties value and text will be collected
// getType: if 'c' assumes wTAr only contains control elements eg checkboxs, edittext, slider etc
// getType: if 's' assumes wTAr contains specific control element names eg zipCb
// if getType is undefined it will be derived from the script individually for every member of wTAr
// which means wTAr can be a mix of 'c' and 's' types.
// heritage is an internal variable for the script, do not specify in the initial call to getWProps
function getWProps (w, wTAr, getType, heritage){
   var tGetType;
   if (wTAr == undefined || wTAr.length == 0) {
      wTAr = [['checkbox'],['radiobutton'],['slider'],['scrollbar'],['edittext']];
      getType = 'c';
   }
   if (getType != undefined) tGetType = getType;
   if (heritage == undefined) heritage = '';
   if (w.tProps == undefined) w.tProps = '';
   var x = eval('w' + heritage);
   for (var p in x) {
      if (p == 'parent' || p == 'children' || p == 'reflection') continue;
      if (x[p] != null && typeof x[p] == 'object') {
         if ( x[p].type == 'panel'  || x[p].type == 'group' ) {
            getWProps (w, wTAr, getType, heritage + '.' + p);
            continue;
         }
         for (var i = 0; i < wTAr.length; i++) {
            if (getType == undefined) tGetType = fWGetType (wTAr[0]);
            if ((tGetType == 'c' && x[p].type == wTAr[0]) || (tGetType == 's' && p == wTAr[0])) {
               if (wTAr.length == 1) wTAr[1] = windowPropertiesDefaults(wTAr[0]);
               for (var j = 1; j < wTAr.length;j++) {
                  var ty = typeof eval('x[p].' + wTAr[j]);
                  if (ty == 'boolean' || ty == 'number') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[j] + '= ' + eval('x[p].' + wTAr[j]) + ';';}
                  else if (ty == 'string') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= "' + eval('x[p].' + wTAr[i][j]) + '";';}
                  else if (ty == 'object') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= ' + eval('x[p].' + wTAr[i][j]).toSource() + ';';}
}   }   }   }   }   }

function xWSProps (str, wXAr) {
   for (var i = 0; i < wXAr.length; i++) {
      var re = RegExp ('(;|^)[^;]*' + wXAr[i].replace(/\./g,'[.]') + '[^;]*;','g');
      str = str.replace(re,'$1');
   }
   return str;
}

function windowPropertiesDefaults(control) {
   if ('checkbox,radiobutton,slider,scrollbar'.indexOf(control) != -1) return 'value';
   else if ('statictext,edittext,button'.indexOf(control) != -1) return 'text';
}

function fWGetType (target) {
   if ('checkbox,radiobutton,slider,scrollbar,statictext,edittext,button'.indexOf(target) != -1) return 'c';
   return 's';
}


function saveWSettings (d, str)
{
   if (!d.sF.exists) if (!d.sF.create()) {alert('Failed to Create\n' + d.sF.fsName);return;}
   if (!d.sDatF.exists) if (!d.sDatF.create()) {alert('Failed to Create\n' + d.sDatF.fsName);return;}
   if (d.datF.open('w')) {
      if (d.datF.write(str)) d.datF.close();
      else throw ("Error saving your settings\n" + d.datF);
   }
   else throw ('Error, Settings File Not Opened\n' + d.datF);
}

function loadWSettings (d, w)
{
   if (d.datF.exists){
   if (d.datF.open('r')) {
         try {eval(d.datF.read());}
         catch (e) {return;}
      }
      else throw('Failed to Load Settings \n' + f);
   }
}

To test it out use the following example script which includes a fairly complex sample window. Then try saving different combinations of control parameters.


Code: Select alltestTheScript ();

function testTheScript () {
   var d = {}; // data file object
   var w = {}; // window object
   var wTAr = []; // window Target Params array
   var wXAr = []; // window Exclude Params array
   // *********************************** SET SAVE PARAMS HERE **************************************
   d.sF =    new Folder(app.path + '/Presets/ScriptsData');
   d.sDatF =    new Folder(d.sF + '/AndrewHallScriptData');
   d.datF =    new File(d.sDatF + '/test.dat');
//   wTAr.push(['checkbox']); // target all checkbox's, get default 'value' property
//   wTAr.push(['edittext','text','bounds']); // target edittext, get 'text' string property AND 'bounds' object property
//   wTAr.push(['slider']); // target all sliders, get default 'value' property - in this case type 'number'
//   wTAr.push(['fsSelCb','value']); // target a window control element by name, you must also specify the property required
//   wXAr.push('.fsFolEt.'); // exclude a window element by name - as specific or as general as you wish eg 'fsSelCb.value' but use string not array
   // *********************************** END SET SAVE PARAMS **************************************
   w = createDialog();
   loadWSettings(d,w); // loads settings from last run
   initialiseWindow(w);
   var result = w.show();
   getWProps (w, wTAr); // get the widow properties
   if (wXAr.length != 0)w.tProps = xWSProps (w.tProps, wXAr);   // exclude specified control variables
   saveWSettings(d,w.tProps); // saves settings
   if (result != 2) sampleProcessResult(w.tProps);
}

function getWProps (w, wName, wTAr, getType, heritage){
   var tGetType;
   if (wTAr == undefined || wTAr.length == 0) {
      wTAr = [['checkbox'],['radiobutton'],['slider'],['scrollbar'],['edittext']];
      getType = 'c';
   }
   if (getType != undefined) tGetType = getType;
   if (heritage == undefined) heritage = '';
   if (w.tProps == undefined) w.tProps = '';
   var x = eval('w' + heritage);
   for (var p in x) {
      if (p == 'parent' || p == 'children' || p == 'reflection') continue;
      if (x[p] != null && typeof x[p] == 'object') {
         if ( x[p].type == 'panel'  || x[p].type == 'group' ) {
            getWProps (w, wTAr, getType, heritage + '.' + p);
            continue;
         }
         for (var i = 0; i < wTAr.length; i++) {
            if (getType == undefined) tGetType = fWGetType (wTAr[i][0]);
            if ((tGetType == 'c' && x[p].type == wTAr[i][0]) || (tGetType == 's' && p == wTAr[i][0])) {
               if (wTAr[i].length == 1) wTAr[i][1] = windowPropertiesDefaults(wTAr[i][0]);
               for (var j = 1; j < wTAr[i].length;j++) {
                  var ty = typeof eval('x[p].' + wTAr[i][j]);
                  if (ty == 'boolean' || ty == 'number') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= ' + eval('x[p].' + wTAr[i][j]) + ';';}
                  else if (ty == 'string') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= "' + eval('x[p].' + wTAr[i][j]) + '";';}
                  else if (ty == 'object') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= ' + eval('x[p].' + wTAr[i][j]).toSource() + ';';}
}   }   }   }   }   }

function xWSProps (str, wXAr) {
   for (var i = 0; i < wXAr.length; i++) {
      var re = RegExp ('(;|^)[^;]*' + wXAr[i].replace(/\./g,'[.]') + '[^;]*;','g');
      str = str.replace(re,'$1');
   }
   return str;
}

function windowPropertiesDefaults(control) {
   if ('checkbox,radiobutton,slider,scrollbar'.indexOf(control) != -1) return 'value';
   else if ('statictext,edittext,button'.indexOf(control) != -1) return 'text';
}

function fWGetType (target) {
   if ('checkbox,radiobutton,slider,scrollbar,statictext,edittext,button'.indexOf(target) != -1) return 'c';
   return 's';
}


function saveWSettings (d, str)
{
   if (!d.sF.exists) if (!d.sF.create()) {alert('Failed to Create\n' + d.sF.fsName);return;}
   if (!d.sDatF.exists) if (!d.sDatF.create()) {alert('Failed to Create\n' + d.sDatF.fsName);return;}
   if (d.datF.open('w')) {
      if (d.datF.write(str)) d.datF.close();
      else throw ("Error saving your settings\n" + d.datF);
   }
   else throw ('Error, Settings File Not Opened\n' + d.datF);
}

function loadWSettings (d, w)
{
   if (d.datF.exists){
      if (d.datF.open('r')) {
         try {eval(d.datF.read());}
         catch (e) {return;}
         }
      else throw('Failed to Load Settings \n' + f);
   }

}

function initialiseWindow (w) {
   with (w.sourcePnl){
      fsSfxSt.enabled = fsSfxEt.enabled = fsExtSt.enabled = fsExcSt.enabled = fsExcEt.enabled = fsExtEt.enabled = fsCritCb.value;
      fsCritCb.onClick = function () {
         fsSfxSt.enabled = fsSfxEt.enabled = fsExtSt.enabled = fsExcSt.enabled = fsExcEt.enabled = fsExtEt.enabled = fsCritCb.value;}
      }
}


function createDialog()
{
   var renameResource;
   renameResource =
      "dialog { text: 'AH - Batch with Stop: Set Params', bounds:[140,50,650,520], \
         execPnl: Panel { text: 'Process', bounds:[405,0,505,465], \
            runBtn: Button { text:'OK', bounds:[7, 20, 93, 40]}, \
            cancelBtn: Button { text:'Cancel', bounds:[7, 60, 93, 80]}, \
            loadBtn: Button { text:'Load', bounds:[7, 100, 93, 120]}, \
            saveBtn: Button { text:'Save', bounds:[7, 140, 93, 160]}, \
            resetBtn: Button { text:'ReSet', bounds:[7, 180, 93, 200]}, \
            webBtn: Button { text:'Support', bounds:[7, 215, 93, 235]} \
         }, \
         sourcePnl: Panel { text: 'File Source', bounds:[7,0,400,140], \
            fsSelCb: Checkbox { text:'Selected', value:true, bounds:[7,20,105,40]}, \
            fsFolEt: EditText { text:'<source folder>', bounds:[110,20,300,40]}, \
            fsFolBtn: Button { text:'Browse', bounds:[305, 20, 385, 40]}, \
            fsCritCb: Checkbox { text:'Filter', bounds:[7,50,65,70]}, \
            fsSfxSt: StaticText { text:'Name', justify:'right',bounds:[68,52,105,70]}, \
            fsSfxEt: EditText { text:'search name', bounds:[110,50,255,70]}, \
            fsExtSt: StaticText { text:'Extension', bounds:[265,57,365,75]}, \
            fsExcSt: StaticText { text:'Exclude', justify:'right', bounds:[40,82,105,105]}, \
            fsExcEt: EditText { text:'exclude', bounds:[110,80,255,100]}, \
            fsExtEt: EditText { text:'jpg+tif', bounds:[265,80,385,100]}, \
            fsSubfolderCb: Checkbox { text:'SubFolder', bounds:[7,105,105,125]}, \
            advCb: Checkbox { text:'Advanced', bounds:[110,105,310,125]} \
         }, \
         destPnl: Panel { text: 'File Destination', bounds:[7,145,400,225], \
            fsDesCb: Checkbox { text:'Same', value:true, bounds:[7,20,105,40]}, \
            fsDesEt: EditText { text:'<destination folder>', bounds:[110,20,300,40]}, \
            fsDesBtn: Button { text:'Browse', bounds:[305, 20, 385, 40]}, \
            fsAutoCb: Checkbox { text:'Auto SubF', bounds:[7,50,105,70]}, \
            fsAutoEt: EditText { text:'AH NEW', bounds:[110,50,190,70]}, \
            noOver: Checkbox { text:'No Overwrite', bounds:[220,50,320,70]} \
         }, \
         processPnl: Panel { text: 'Output Options', bounds:[7,230,400,340], \
            oFileTypeCb1:Checkbox { text:'tif', value:'true', bounds:[7,15,55,35] }, \
            oFileTypeCb2:Checkbox { text:'psd', bounds:[60,15,105,35] }, \
            oFileTypeCb3:Checkbox { text:'jpg', bounds:[110,15,170,35] }, \
            delActiveCb:Checkbox {text:'Delete ActiveDoc', bounds:[180,15,305,35] }, \
            tifS: StaticText { text:'Tif Options', bounds:[7, 45, 100, 65]}, \
            lzwCb:Checkbox { text:'tif-lzw', bounds:[110,45,170,65] }, \
            zipCb:Checkbox { text:'tif-zip', bounds:[180,45,240,65] }, \
            ticcCb:Checkbox {text:'ICC', value:'true', bounds:[242,45,310,65] }, \
            jpgS: StaticText { text:'JPG Options', bounds:[7,75, 100, 95]}, \
            sRgb: Checkbox { text:'sRGB', value:true, bounds:[110,75, 170,95]}, \
            jpgQ: EditText { text:'8', bounds:[180,75, 200,95]}, \
            jpgQS: StaticText { text:'Qual', bounds:[205,75, 245,95]}, \
            jiccCb:Checkbox {text:'ICC', value:'true', bounds:[242,75,310,95] }, \
         }, \
         renamePnl: Panel { text: 'File Rename Panel', bounds:[7,345,400,465], \
            renameSt: StaticText { text:'Rename Params - see Help', bounds:[15,15,160,35]}, \
            nameEt: EditText { text:'<crdate+crtime+origname+orignum3+autonum100+mytext>', bounds:[15,37,300,57]}, \
            tPnl: Panel { text: 'File Source', bounds:[10,62,380,105], \
               fTESTCb: Slider { value:40, bounds:[200,10,360,30]} \
            } \
         } \
   }";
   return new Window(renameResource);
}

function sampleProcessResult(str) {
   alertAr(str.split(';'));
}

function alertAr (array1) {
   var arrayStr,i;
   arrayStr = '';
   for (i = 0; i < array1.length; i++) {arrayStr += array1[i] + '\n';}
   alert(arrayStr);   
}


Andrew
Recury

Generic Script to Save / Reload Window Parameters

Post by Recury »

This was exactly what I was looking for and it saved me a TON of time. Thanks!
Andrew

Generic Script to Save / Reload Window Parameters

Post by Andrew »

This is a revised version of getWProps that also collects dropdownlist settings. I imagine adding listbox and slider type controls (which are currently not covered) would not be a particularly difficult or different. I know this is fairly complex but if you use dialogs a lot it can save you a LOT of time once you know how to set it up right.

Code: Select allfunction getWProps (w, wTAr, getType, heritage){
   var tGetType;
   if (wTAr == undefined || wTAr.length == 0) {
      wTAr = [['checkbox'],['radiobutton'],['slider'],['scrollbar'],['edittext']];
      getType = 'c';
   }
   if (getType != undefined) tGetType = getType;
   if (heritage == undefined) heritage = '';
   if (w.tProps == undefined) w.tProps = '';
   var x = eval('w' + heritage);
   for (var p in x) {
      if (p == 'parent' || p == 'children' || p == 'reflection') continue;
      if (x[p] != null && typeof x[p] == 'object') {
         if ( x[p].type == 'panel'  || x[p].type == 'group' ) {
            getWProps (w, wTAr, getType, heritage + '.' + p);
            continue;
         }
         if ( x[p].type == 'dropdownlist' ) {
            if (eval('w' + heritage + '.' + p + '.selection') != null) {w.tProps += 'w' + heritage + '.' + p + '.find("' + eval('w' + heritage + '.' + p + '.selection.text' ) + '").selected' + '= true;';}
            continue;
         }
         for (var i = 0; i < wTAr.length; i++) {
            if (getType == undefined) tGetType = fWGetType (wTAr[0]);
            if ((tGetType == 'c' && x[p].type == wTAr[0]) || (tGetType == 's' && p == wTAr[0])) {
               if (wTAr.length == 1) wTAr[1] = windowPropertiesDefaults(wTAr[0]);
               for (var j = 1; j < wTAr.length;j++) {
                  var ty = typeof eval('x[p].' + wTAr[j]);
                  if (ty == 'boolean' || ty == 'number') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[j] + '= ' + eval('x[p].' + wTAr[j]) + ';';}
                  else if (ty == 'string') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= "' + eval('x[p].' + wTAr[i][j]) + '";';}
                  else if (ty == 'object') {
                     w.tProps += 'w' + heritage + '.' + p + '.' + wTAr[i][j] + '= ' + eval('x[p].' + wTAr[i][j]).toSource() + ';';}
}   }   }   }   }   }

function xWSProps (str, wXAr) {
   for (var i = 0; i < wXAr.length; i++) {
      var re = RegExp ('(;|^)[^;]*' + wXAr[i].replace(/\./g,'[.]') + '[^;]*;','g');
      str = str.replace(re,'$1');
   }
   return str;
}



This is a live example of it being used (it won't work since the rest of the script is missing but it demonstrates structure):


Code: Select all   myData.wTAr = [['checkbox'],['radiobutton'],['edittext'],['dropdownlist']];
   myData.getType = 'c';

   try {         
      app.displayDialogs = DialogModes.NO;

      w = actionCmdDialog();

      if (initACDlg(w,myData) == -1) return;
      
      if (myData.settingsFile.exists)  {loadWSettings(myData.settingsFile, w); refreshDlg(w,myData);}

      dlg = w.show();
      
      getWProps (w, myData.wTAr, myData.getType);

      saveWSettings (myData.settingsFile, w.tProps); // save this runs settings
}
catch (e) {}

function saveWSettings (d, str)
{
   if (d.open('w')) {
      if (d.write(str)) d.close();
      else throw ("Error saving your settings\n" + d.fsName);
   }
   else throw ('Error, Settings File Not Opened\n' + d.fsName);
}

function loadWSettings (d, w)
{
   if (d.exists){
      if (d.open('r')) {
         try {eval(d.read());}
         catch(e) {d.open('w');return;}
      }
      else throw('Failed to Load Settings \n' + d.fsName);
   }
}

Andrew