1 Reply Latest reply on Jul 20, 2017 12:22 AM by Silly-V

    Creating global variable

    Silly-V Adobe Community Professional

      Hello!

       

      How are the worlds of scripting different among these applications!

      In my case I'd like to put some variables into the global scope intentionally to be data-holders between photoshop script runs. I'd rather not write these pieces of data to a text file, because the data I choose for such storage is mostly trivial: last dialog button clicked, etc.

      With Illustrator it's really easy to pollute the global scope with any variable which doesn't have the 'var' keyword in front of it. However, PS always starts from scratch and no amount of "#targetengine main" will help break the variables out of the running script instance.

       

      Anyone know how one can create their custom engine for such a purpose?

      I posed the question to some Italians, but it's 10 pm in USA and 5 am in Italy - so I don't expect they hear my pleas just yet

       

      * So I read this thread with Mr. Bob Stucky commenting that you "can't create your own persistent engine in PS, but there's a persistent engine for BridgeTalk.." <-- I'd like to know more about what this means, if there are any workarounds, etc.

       

      ** getting closer: Working with putCustomOptions and getCustomOptions

        • 1. Re: Creating global variable
          Silly-V Adobe Community Professional

          Okay, I was over-thinking it, but I put the CustomOptions to use and here is a test snippet:

           

          #target photoshop

          "object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(t){return 10>t?"0"+t:t}function quote(t){

            return escapable.lastIndex=0,escapable.test(t)?'"'+t.replace(escapable,function(t){var e=meta[t];

              return"string"==typeof e?e:"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+t+'"'}

            function str(t,e){var n,r,o,f,u,i=gap,p=e[t];switch(p&&"object"==typeof p&&"function"==typeof p.toJSON&&(p=p.toJSON(t)),

              "function"==typeof rep&&(p=rep.call(e,t,p)),typeof p){case"string":return quote(p);case"number":return isFinite(p)?String(p):"null";

            case"boolean":case"null":return String(p);case"object":if(!p)return"null";if(gap+=indent,u=[],"[object Array]"===Object.prototype.toString.apply(p)){

              for(f=p.length,n=0;f>n;n+=1)u[n]=str(n,p)||"null";return o=0===u.length?"[]":gap?"[\n"+gap+u.join(",\n"+gap)+"\n"+i+"]":"["+u.join(",")+"]",gap=i, o}

                if(rep&&"object"==typeof rep)for(f=rep.length,n=0;f>n;n+=1)"string"==typeof rep[n]&&(r=rep[n],o=str(r,p),o&&u.push(quote(r)+(gap?": ":":")+o));

              else for(r in p)Object.prototype.hasOwnProperty.call(p,r)&&(o=str(r,p),o&&u.push(quote(r)+(gap?": ":":")+o));return o=0===u.length?"{}":gap?"{\n"+gap+

              u.join(",\n"+gap)+"\n"+i+"}":"{"+u.join(",")+"}",gap=i,o}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){

                return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.get UTCDate())+"T"+f(this.getUTCHours())+":"+

                f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Num ber.prototype.toJSON=Boolean.prototype.toJSON=function(){

                  return this.valueOf()});var cx,escapable,gap,indent,meta,rep;"function"!=typeof JSON.stringify&&

              (escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u20 28-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,

                meta={"\b":"\\b","  ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(t ,e,n){var r;

                  if(gap="",indent="","number"==typeof n)for(r=0;n>r;r+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=e,

                    e&&"function"!=typeof e&&("object"!=typeof e||"number"!=typeof e.length))throw new Error("JSON.stringify");return str("",{"":t})}),

              "function"!=typeof JSON.parse&&(cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u 2060-\u206f\ufeff\ufff0-\uffff]/g,

                JSON.parse=function(text,reviver){function walk(t,e){var n,r,o=t[e];if(o&&"object"==typeof o)for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&

                (r=walk(o,n),void 0!==r?o[n]=r:delete o[n]);return reviver.call(t,e,o)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&

                  (text=text.replace(cx,function(t){return"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice (-4)})),

                  /^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@")

                    .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]")

                    .replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;

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

           

          function test() {

           

            var psPersistenceManager = new(function() {

              this.store = function(keyStringObj, obj) {

                this.remove(keyStringObj);

                var container = new ActionDescriptor();

                container.putString(0, JSON.stringify(obj));

                app.putCustomOptions(keyStringObj, container, true);

              };

              this.get = function(keyStringObj) {

                try {

                  return JSON.parse(app.getCustomOptions(keyStringObj).getString(0));

                } catch (e) {

                  return null;

                }

              };

              this.remove = function(keyStringObj) {

                try {

                  app.eraseCustomOptions(keyStringObj);

                  return true;

                } catch (e) {

                  return false;

                }

              };

              this.getOrCreate = function(keyStringObj, obj) {

                var foundObj = this.get(keyStringObj);

                if (foundObj) {

                  for (var all in foundObj) {

                    obj[all] = foundObj[all];

                  }

                } else {

                  this.store(obj, keyStringObj);

                }

                return obj;

              }

            });

           

            function removeProperty(obj, propName) {

              var newObj = {};

              for (var all in obj) {

                if (all != propName) {

                  newObj[all] = obj[all];

                }

              }

              return newObj;

            };

           

            var MY_SETTINGS_TEST_Object = {

              prop_a: 'abc',

              prop_b: 'def',

              prop_c: '123'

            };

           

            psPersistenceManager.getOrCreate("MY_SETTINGS_TEST_Object", MY_SETTINGS_TEST_Object);

           

            var UIWindow = (function() {

              function getUpdatedListItems(listBox) {

                listBox.removeAll();

                var newItem;

                for (var all in MY_SETTINGS_TEST_Object) {

                  newItem = listBox.add("item");

                  newItem.text = "MY_SETTINGS_TEST_Object." + all + "\t\t|\t\t" + MY_SETTINGS_TEST_Object[all];

                }

              };

              var w = new Window("dialog", "Test");

              var g1 = w.add("panel", undefined, "Current state of 'MY_SETTINGS_TEST_Object'");

           

              var list_objectDisplay = g1.add("listbox", undefined, []); // multi column listboxes do not work in PS  >:(

              list_objectDisplay.size = [500, 250];

           

              var g2 = w.add("group");

              var btn_remove = g2.add("button", undefined, "Remove");

              var btn_add = g2.add("button", undefined, "Add");

              var btn_ok = g2.add("button", undefined, "Ok");

           

              btn_add.onClick = function() {

                if (!MY_SETTINGS_TEST_Object.hasOwnProperty("prop_d")) {

                  MY_SETTINGS_TEST_Object.prop_d = "456";

                  psPersistenceManager.store("MY_SETTINGS_TEST_Object", MY_SETTINGS_TEST_Object);

                  getUpdatedListItems(list_objectDisplay);

                } else {

                  alert("This button only adds 'prop_d' and does nothing else.");

                }

              };

           

              btn_remove.onClick = function() {

                if (list_objectDisplay.selection == null) {

                  return;

                }

                MY_SETTINGS_TEST_Object = removeProperty(MY_SETTINGS_TEST_Object, list_objectDisplay.selection.text.split("\t\t|\t\t")[0].split(".")[1]);

                psPersistenceManager.store("MY_SETTINGS_TEST_Object", MY_SETTINGS_TEST_Object);

                getUpdatedListItems(list_objectDisplay);

              }

           

              w.onShow = function() {

                getUpdatedListItems(list_objectDisplay);

              };

              w.show();

           

            })();

           

           

          }

          test();