Search code examples
javascriptphotoshop-script

Problem with counter in script Photoshop CS6 ver 13 64 bit


I have script that
PSD (activeDocument) in "3.Working folder
saves jpg
in draft folders in directory "../UserNameJobName/4.WIP/"

The problem is that everything works fine until I want to to create third draft folder (draft003).
Then it saved again activeDocument in the same jpg file in draft002, instead of creating new folder draft003 and saving there respectivly.

It seams that var draftCounter can't be higher than 2 value. I'm not sure where is a bug. What I know in photoshop CC it works without any problems.

[Link to folder structure zip]
https://www.dropbox.com/s/kbalzsubs2477jy/191130_WARGAMES_LUKKAR.zip?dl=0

Main file directory pic
Draft directory pic


code

#target photoshop;

var wipCounter = 1;
var fileNotFound = true;
main();

function main(){
    //Get file information
    var doc = app.activeDocument;
    var docName = doc.name;
    var docPath = doc.path;

    //Get the percentage to scale by
    var scaleValue = prompt("Enter the WIP JPEG scale percentage", "100");

    //Figure out the location of the WIP folder
    var savePath = docPath.toString();
    savePath = savePath.slice(0,-10);
    savePath = savePath + "/4.WIP/";
    var currDoc = docName.toString();
    currDoc = currDoc.slice(0,-4);

    //global variables are defined here

    //Look at the WIP folder and run a search for anything containing the word "draft"
    //Define the location of the WIP folder 
    var inWIPFolder = new Folder(savePath);
    //Look in each folder and create an array containing all of the information
    var fileList = inWIPFolder.getFiles();
    // Look at each array and sort the info out 
    for(var a=0; a<fileList.length; a++) {
            //Exclude anything that is not a folder
            if(fileList[a] instanceof Folder) {
                //convert each foldername to string for editing
                var fileName = fileList[a].toString();
                var draftSearch = fileName.search("draft");
                if(draftSearch > -1) {
                    var draftCounter  = fileName.slice(draftSearch);
                    if(fileNotFound == true) {
                        searchDraftFolder(draftCounter, savePath, currDoc);
                        }
                }
            }
        }


        //Formatting the numbers
        if(wipCounter < 10){
            wipCounter = "00" + wipCounter.toString();
         }else if(wipCounter >= 10 && wipCounter < 100) {
             wipCounter = "0" + wipCounter.toString();  
         }

        //Define the path of the draft folders
        savePath = Folder(savePath +"/draft" + wipCounter);
        //Check to see if the draft folders exists. If not, make one
        if(!savePath.exists){
            savePath.create();
            }

        //Define the WIP file name with the incremental counter
        var wipFileName =savePath + "/" + currDoc + "_WIP" + wipCounter + ".jpg";

        //Resize the file
        doc.selection.selectAll();
        var blankLayer = doc.artLayers.add();
        blankLayer.name = "blankLayer";
        doc.selection.copy(true);
        doc.layers.getByName("blankLayer").remove();

        //Make new doc to paste into
        app.preferences.rulerUnits = Units.PIXELS;
        //arguments are: Width, Height, resolution, filename, colourspce, documentfill
        app.documents.add(UnitValue(doc.width, "PX"), UnitValue(doc.height, "PX"), doc.resolution, wipFileName, NewDocumentMode.RGB, DocumentFill.TRANSPARENT,1);
        app.activeDocument.paste();
        app.activeDocument.resizeImage(UnitValue(scaleValue, "PERCENT"), null, null, ResampleMethod.BICUBICSHARPER);
        //Save a RGBJpeg
        jpegFileSaver(app.activeDocument, new File(wipFileName), 10);
        //Close the new document down
        app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
        //Deselect
        doc.selection.deselect();
        alert(currDoc + "WIP" + wipCounter + " saved.");
}


function searchDraftFolder(draftCounter, savePath, currDoc){
   var fileSearch = -1;
   //Define the location of each draft folder  
   var internalFolder = new Folder(savePath + "/" + draftCounter);
   //Look in each folder and create an array containing all of the information
   var internalFileList = internalFolder.getFiles();
   // Look at each array and sort the info out 
   for(var a=0; a<internalFileList.length; a++) {
        //Exclude anything that is not a file
       if(internalFileList[a] instanceof File) {
           // convert each filename to string for editing
            var fileName = internalFileList[a].toString();
            //Searching the current document name and replacing spaces with %20
            var currDocStripped = currDoc.replace(/ /g, '%20');
            //Checking files until a result greater than 0 appears
            if(fileSearch === -1){
                //search for the current file name
                fileSearch = fileName.search(currDocStripped);
            }
           }
       }
   //if the filesearch does not return a result:
    if(fileSearch === -1){
        fileNotFound = true;
     //if it does return a result:
    } else {
        //Slice the number off the draft folder
        draftCounter = draftCounter.slice(-3);
        //convert the string into an integer
        draftCounter = parseInt(Number(draftCounter));
        //increment the number up
        wipCounter++;
        //terminate the main loop
        fileNotFound = false;
        }   
    }


//A resuable JPEG save script
function jpegFileSaver(doc, saveFile, quality){
    //define the save options
    var saveOptions = new JPEGSaveOptions();
    saveOptions.embedColorProfile = true;
    saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
    saveOptions.quality = quality;
    //save the files
    doc.saveAs(saveFile, saveOptions, true);
    }

Thanks in advance.
Additional credits to code author http://jamesmcdonald3d.com/


Solution

  • The issue is with searchDraftFolder(). When it finds the already saved Great Map_wip in draft001, fileNotFound is set to false and your loop on line 39 terminates. That's why wipCounter is stuck on 2: it increments ones and that's it.

    Here I rewrote this function a little bit, trying to make it simpler: all necessary loops are inside the function and I think it's easier to understand.

    p.s. there was also an issue at least on CC: app.documents.add() was showing interface. That's because you were using a full path as a new document name and you can't use \-symbol in it, so Photoshop was suggesting a different name and showing it. I added a separate variable for document name without a path (line 49) to use in .add()

    main();
    
    function main()
    {
      //Get file information
      var doc = app.activeDocument;
      var docName = doc.name;
      var docPath = doc.path;
      var wipCounter;
    
      //Get the percentage to scale by
      var scaleValue = prompt("Enter the WIP JPEG scale percentage", "100");
    
      //Figure out the location of the WIP folder
      var savePath = docPath.toString();
      savePath = savePath.slice(0, -10);
      savePath = savePath + "/4.WIP/";
      var currDoc = docName.toString();
      currDoc = currDoc.slice(0, -4);
    
      //global variables are defined here
    
      //Look at the WIP folder and run a search for anything containing the word "draft"
      //Define the location of the WIP folder 
      var inWIPFolder = new Folder(savePath);
    
      // !! modifications
      wipCounter = searchDraftFolder(inWIPFolder, currDoc)
    
      //Formatting the numbers
      if (wipCounter < 10)
      {
        wipCounter = "00" + wipCounter.toString();
      }
      else if (wipCounter >= 10 && wipCounter < 100)
      {
        wipCounter = "0" + wipCounter.toString();
      }
    
      //Define the path of the draft folders
      savePath = Folder(savePath + "/draft" + wipCounter);
      //Check to see if the draft folders exists. If not, make one
      if (!savePath.exists)
      {
        savePath.create();
      }
    
      //Define the WIP file name with the incremental counter
      var wipFileName = currDoc + "_WIP" + wipCounter + ".jpg";
      var wipFilePath = savePath + "/" + wipFileName;
    
      //Resize the file
      doc.selection.selectAll();
      var blankLayer = doc.artLayers.add();
      blankLayer.name = "blankLayer";
      doc.selection.copy(true);
      doc.layers.getByName("blankLayer").remove();
    
      //Make new doc to paste into
      app.preferences.rulerUnits = Units.PIXELS;
      //arguments are: Width, Height, resolution, filename, colourspce, documentfill
      app.documents.add(UnitValue(doc.width, "PX"), UnitValue(doc.height, "PX"), doc.resolution, wipFileName, NewDocumentMode.RGB, DocumentFill.TRANSPARENT, 1);
      app.activeDocument.paste();
      app.activeDocument.resizeImage(UnitValue(scaleValue, "PERCENT"), null, null, ResampleMethod.BICUBICSHARPER);
      //Save a RGBJpeg
      jpegFileSaver(app.activeDocument, new File(wipFilePath), 10);
      //Close the new document down
      app.activeDocument.close(SaveOptions.DONOTSAVECHANGES);
      //Deselect
      doc.selection.deselect();
      alert(currDoc + "_WIP" + wipCounter + " saved.");
    }
    
    // p is WIP path
    // n is a name of the active doc without extension
    function searchDraftFolder(p, n)
    {
      var fileList = p.getFiles(); // folders in wip folder
      var counter = 1;
      var drafts, fileName, i, k;
    
      // for all the files found..
      for (i = 0; i < fileList.length; i++)
      {
        //if a folder is found and its name has 'draft' in it
        if (fileList[i] instanceof Folder && fileList[i].name.indexOf('draft') != -1)
        {
    
          //get files inside this draft folder
          drafts = fileList[i].getFiles();
    
          // for all files inside
          for (k = 0; k < drafts.length; k++)
          {
            //'.name' gives us a URI-name, so replacing %20 with ' '. Probably should add more special symbols here if you use them
            fileName = drafts[k].name.replace(/%20/g, ' ');
    
            // if there's a file that starts with active doc name counter is incremented
            if (fileName.indexOf(n) != -1)
            {
              counter++
            }
          }
        }
      }
    
      return counter;
    }
    
    
    //A resuable JPEG save script
    function jpegFileSaver(doc, saveFile, quality)
    {
      //define the save options
      var saveOptions = new JPEGSaveOptions();
      saveOptions.embedColorProfile = true;
      saveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
      saveOptions.quality = quality;
      //save the files
      doc.saveAs(saveFile, saveOptions, true);
    }