//=================================================================================================================================////DESCRIPTION: A tool for relinking files across one or more InDesign documents// Jeremy Howard -- www.jeremyhoward.me//=================================================================================================================================////--icon for the "folderPicker" buttonvar myIcon = ScriptUI.newImage("\u0089PNG\r\n\x1A\n\x00\x00\x00\rIHDR\x00\x00\x00\x1C\x00\x00\x00\x0F\b\x06\x00\x00\x00\u00F7O\u00AF\u00A1\x00\x00\x01KiTXtXML:com.adobe.xmp\x00\x00\x00\x00\x00<?xpacket begin=\"\u00EF\u00BB\u00BF\" id=\"W5M0MpCehiHzreSzNTczkc9d\"?>\n<x:xmpmeta xmlns:x=\"adobe:ns:meta/\" x:xmptk=\"Adobe XMP Core 5.6-c140 79.160451, 2017/05/06-01:08:21        \">\n <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n  <rdf:Description rdf:about=\"\"/>\n </rdf:RDF>\n</x:xmpmeta>\n<?xpacket end=\"r\"?>-CD\u00B7\x00\x00\x02lIDAT8\u008D\u00B5\u0094KHTQ\x18\u00C7\x7F\u00F7\u00DEy\u00DCqfrf|\u00E5 \u0094\u00F9\x06\u00B5)\b\u0089\u00842R{X\u00B4\u00AA\u00A0\u00A2V\u0081TT\x0B]\u00D6\u00C2U\x10=h\x11\x15\u00BD$\u00C8\x16=\x16\u00C1d\u00F4\\H\u008B\x1ECH\x0B+S\u00D1\x1CG\x1D_\u00E3<\x1C\u00BDsZ\x14\u00A5\u0088\u00E3u\u00E1\x1F\x0E\u009Cs\u00F8>~\u00FF\u00EF;\u0087O\u00BA\u00F7\u00FC\u00C3\u00A9Go}\u0097\u00D7\u00ACtD{\u0087C\u0096Mey\x17\u00CF\u00EC\u00DB\u00DC\u00C8r\u00E9@\u00C35\x7Fd<(\u0084\x16\x15BD\u00C5\u00E1\u00D3W\u00C5;_\u00D7*!\u0084\u00B2\x1C\u00CB\u0090\u009D\u00ED2\u00A9\u00AA\u0099\u00C0\u00D0\x18Y\u0099\x0E\u008A\u00CBWs\u00AE\u00B9\u00F5z\u00CD\u00D7\u0082`$:\u00A5.dT\x02\u00C5?\x16\u00B2o\u00F1\x14\u00DE>\u00B8\u00CD\u00D3\u00A2\u00B7@C\\@8:\u0085\u00D9\u00A8\u0080\u0090i<\u00B4\u009D\u00FD\u00FD\u00C3\u00B5\u00B1\u00A98\u008A\u00A2 \x01\u00E2?\u00E4\u00DF^\u0091%\u00AC\u00AA\u0091\u0086\u009B/\u00B7\u00BA]\u00A9?\u00AA\u00D6\u00E7~\u00D4\x05\x14\x02l6\x13\u00FE\u00A0\u00C6\u0085\u00BB\u00EFQ\u0099\u00C0a\u00B3\u00A2%D\u00D2D!\x04\x19iv\u00D4\u00E9\x18M\u00B7\u00BCM=\u00E3U-;\u00D6\u00E5z\u00B3\x1C\u00EA`R\u00A0,\x01\u008A\u008D\u00F3\x0F\u009E\u00E0\u00F27Q[\x06\u00A1\u00F0\u0082\u009D\u009CSo\u00BC{\u009A\u00E3\x1E\x17Nu\u00B4\u00FA\u00BE\u00B7\u00B9\u00FA\u00E8\u00D3#\u0097\u00BCW\u00EA\x1B\u0092\x02\u00ED)f\u00DA\u00BFOb\x19x\u00C1\u00D9\u00FA\x19\u0088\u00B9A$\u00AFn\u009E2\u00CC\x14\r\u00D8\u00F9\x15\u00CC\x19],\u00D4\u00E0\\a\u00E1[w\u0080\u0082\u00F4>\x10\u00E9h\x13\u00C6?\u008F\u00A5S2 i\u00E3\u00F8z\u008A\u00C2u\u00BB*[\x17\u008D\x17\u00B2\u0099\u00A1\u00A1nJ2\x03\x101-\t\x06 \x195~vF\u00C1\u00BE\u00B6\u00AD\u00AE\u00C2\u00F9iQ`g Nl\u00B4\u0083\u00F2\u00DC\x04\u00C4\u0094\u00A5\u00D1\x00l\x1A\u009F;\u00CD\u00B8\u00DC\u00A5\u00AF\u00F4\u0084\u00CB\u00CF|\x01L\u00F1\x0E\u00AC\u00D9)h\tyi0\x01HQz's)\u00CE\u00CF\x7F\u00AD\x0B\u00D8\u00DF\u00E5'\u00CF\u00D1\x07\u00B2yi0@\u0091A\x04\u00C3L\x18K\u00BBvW8|zr\f\x059a6\u00E4\u0087 b@\u0096\x12\u00C9\u00BC\u00CD\u00BF\u00B2\u00CE\u00F0\u00A5=\u00C2\u008C\u00A5\u00A4M\u00AFIC\u00A5k0\u00E1r\u00FBa\u00DA\u0089\u00A4\u00F2\u00FF\u00D3\u0088\u00BFse\u00CEy\u0096\x14\x19\u00ACc<|c\u00C2]S\u00AE\u00AB\u009D\x00\u0086\u00D2\u008D;\x1F\u009F\u00B8\x11?\u0096\u00E6H\x1D\x11\u00C8\u0089\u00D9\u00E3\x0BXp\u00B4\u00C9h\u00CAH(\u00EA\u00B0x\u00F6\u00DC9\u00B9\u00B7\u00B0Y/\u00F07&\u008F\x1C\\\u00C8\u00D5\x1F\u00E0\x00\x00\x00\x00IEND\u00AEB`\u0082");var scriptArgs =[];//=================================================================================================================================////-- Build the "introDialog" - the dialog that allows a user to configure the scriptvar introDialog = new Window('dialog {text: "InDesign Relinker", orientation: "column", alignChildren: ["left","top"], spacing: 10}');//=================================================================================================================================////=================================================================================================================================////--Scope Definition Radio Button Group - Allows the user to choose to run the script in the current document or across all open documentsvar scopeSpecGroup = introDialog.add('panel {text:"Relink Files In:", orientation:"column", alignment:["left","top"], alignChildren:["left","top"], spacing:2, margins:[12,15,10,8],preferredSize: [350,undefined]}');var thisDocScope = scopeSpecGroup.add('radiobutton {text:"Current document"}');var allDocsScope = scopeSpecGroup.add('radiobutton {text:"All open documents"}');thisDocScope.value = true;//=================================================================================================================================////=================================================================================================================================////-- Choose Folder User Input Group - This is where the user specifies which folder contains the images to link tovar folderChoiceGroup = introDialog.add('panel {text:"Search for links in:", orientation:"row", alignment:["left","top"], alignChildren:["fill","top"], margins:[12,13,10,10], preferredSize: [350,undefined]}');var folderPathInput = folderChoiceGroup.add('edittext', undefined, undefined);folderPathInput.preferredSize.width = 275;var folderPicker = folderChoiceGroup.add('iconbutton',undefined,myIcon);folderPicker.preferredSize.height = 22;//-- Include subfolders option - when ticked, the search walks the chosen folder and every folder inside it.var subfolderGroup = introDialog.add('group {orientation:"row", alignment:["left","top"], margins:[13,0,0,2]}');var searchSubfolders = subfolderGroup.add('checkbox', undefined, "Include subfolders");searchSubfolders.value = false;//=================================================================================================================================////=================================================================================================================================////-- File Format Checkboxes Group - Allows the user to specify which file formats should be updated or relinked by the scriptvar fileFormatGroup = introDialog.add('panel {text:"Link File Formats:", orientation:"row", margins:[13,17,0,7],preferredSize: [350,undefined]}');var formatColOne = fileFormatGroup.add('group {orientation:"column", alignment:["left","top"], alignChildren:["left","top"], spacing:2, preferredSize: [120,undefined]}');var formatColTwo = fileFormatGroup.add('group {orientation:"column", alignment:["left","top"], alignChildren:["left","top"], spacing:2, preferredSize: [100,undefined]}');var formatColThree = fileFormatGroup.add('group {orientation:"column", alignment:["left","top"], alignChildren:["left","top"], spacing:2, preferredSize: [80,undefined]}');//-- fill the fileFormatGroup columns with checkboxes for formatsvar formatLists = [["jpg, jpeg", "png", "tif, tiff","gif","bmp"], ["ai","eps", "pdf","psd","indd"], ["txt", "rtf", "doc, docx","xls, xlsx"]]for(formatListNum=0;formatListNum<formatLists.length;formatListNum++){    var currentList = formatLists[formatListNum];    var currentGroup = fileFormatGroup.children[formatListNum];    for(colBoxNum=0;colBoxNum<currentList.length;colBoxNum++){        var addThis = currentGroup.add('checkbox', undefined, currentList[colBoxNum]);        addThis.value = true;     }}//=================================================================================================================================////=================================================================================================================================////-- Relink link type Checkboxes Group - Allows the user to dictate the method that should be used when processing found links.var linkTypeGroup = introDialog.add('panel {text: "Relink links that are:", orientation: "row", margins:[13,15,0,7], preferredSize: [350,undefined]}');var missingLink = linkTypeGroup.add('checkbox', undefined, "Missing");missingLink.preferredSize.width = 120;missingLink.value = true; var modifiedLink = linkTypeGroup.add('checkbox', undefined, "Modified");modifiedLink.preferredSize.width = 100;modifiedLink.value = true;var allLinks = linkTypeGroup.add('checkbox', undefined, "Relink all");allLinks.preferredSize.width = 80;//=================================================================================================================================////=================================================================================================================================////-- Buttons Group - Launch or cancel the scriptvar myButtonGroup = introDialog.add('group {alignment:["right","top"], alignChildren:["right","top"], margins: [0,10,5,10]}');var cancelButton = myButtonGroup.add('button', undefined, "Cancel",{name: "Cancel"});var proceedButton = myButtonGroup.add ('button', undefined, "Continue",{name: "proceedButton"});//=================================================================================================================================////=================================================================================================================================////-- When the "folderPicker" button is clicked...folderPicker.onClick = function(){    var folderPath = String(Folder.selectDialog("Select a folder with InDesign documents")).replace(/%20/g,' ')    folderPathInput.text = folderPath;}//=================================================================================================================================////=================================================================================================================================////-- When the "Cancel" button is clicked...cancelButton.onClick = function(){exit(0);}//=================================================================================================================================////=================================================================================================================================////-- When the "Continue" button is clicked...proceedButton.onClick = function() {    var extensionsArray = [];    var relinkMethodArray = [];        //--gather info about which extension check boxes are selected and build the extensionsArray    for(thisChild=0;thisChild<fileFormatGroup.children.length;thisChild++){        var subGroup = fileFormatGroup.children[thisChild];        var checkBoxes = subGroup.children;        for(thisBox = 0;thisBox < checkBoxes.length;thisBox++){            if (checkBoxes[thisBox].value == true) {                var thisExtension = checkBoxes[thisBox].text.replace(/, /g,',');                extensionsArray.push(thisExtension);            }        }    }    //-- Store the selected relinking methods in the relinkMethodArray    if(allLinks.value == true){relinkMethodArray.push("allLinks");}    if(modifiedLink.value == true && allLinks.value == false){relinkMethodArray.push("modified");}    if(missingLink.value == true && allLinks.value == false){relinkMethodArray.push("missing");}    //--prep variables for insertion into the "scriptArgs" array    scriptArgs.push(folderPathInput.text);    scriptArgs.push(extensionsArray.join(","));    scriptArgs.push(String(thisDocScope.value));    scriptArgs.push(relinkMethodArray.join(","));    scriptArgs.push(String(searchSubfolders.value));        introDialog.close(1);}var dialogResult = introDialog.show();if(dialogResult == 1){    app.doScript(relinkFiles, ScriptLanguage.JAVASCRIPT, scriptArgs, UndoModes.ENTIRE_SCRIPT, "Relink Files");}else if (dialogResult== 2){    exit(0);}//=================================================================================================================================////=================================================================================================================================////-- The main relinking function...function relinkFiles(args){    //-- Parse the input arguments array into variables for this function    var folderPath = String(args[0]);    var extensionsArray = args[1].split(",");    var docScope = args[2];    var relinkMethod = args[3];    var searchSubfolders = args[4];    var linkCount_pBar = 0;    //-- Build the list of folders to search once, up front. If subfolders are off this is just the chosen folder,    //-- so behaviour is identical to before. If on, it's the chosen folder plus every folder nested inside it,    //-- root-first, so shallower matches take precedence.    var rootFolder = Folder(folderPath);    var searchFolders = (searchSubfolders == "true") ? collectFolders(rootFolder) : [rootFolder];        if(docScope == "true"){        var allDocs = [app.activeDocument];    }else{        var allDocs = app.documents;    }    //-- Get number of links across entire scope of the relinking routine. This allows us to create an accurate progress bar.    for(aDoc=0;aDoc<allDocs.length;aDoc++){        var linkCount_pBar = linkCount_pBar + allDocs[aDoc].links.length;    }    //-- Create the progress bar    var pBarWin = new Window ('palette {text: "Relinking Files..."}');    var pBar = pBarWin.add ('progressbar', undefined, 0, linkCount_pBar);    pBar.preferredSize.width = 300;    var pBarStatus = pBarWin.add("statictext", undefined, "Processing...");    pBarStatus.preferredSize.width = 300;    pBarStatus.alignment = 'left';    pBarWin.show();        //define tracking variables for the message displayed at the script's end.    var missingCount = 0;    var modifiedCount = 0;    var notFoundCount = 0;    var totalLinkCount = 0;    for(aDoc=0;aDoc<allDocs.length;aDoc++){        var currentDoc = allDocs[aDoc];        var docLinks = currentDoc.links;        var totalLinkCount = totalLinkCount + docLinks.length;                for(aLink=0;aLink<docLinks.length;aLink++){            var currentLink = docLinks[aLink];                        //-- If the currentLink is a modified link...            if(currentLink.status == LinkStatus.linkOutOfDate && relinkMethod.split("modified").length>1){                var modifiedCount = modifiedCount + 1;                currentLink.update();            }            //--Update the progress bar            pBarStatus.text = "Processing link " + (Number(aLink) + 1) + " of " + docLinks.length + " in document " + (Number(aDoc) + 1);                       //-- If the currentLink is a missing link... Will also relink everything if the "Relink All" option has been selected.           if((currentLink.status == LinkStatus.LINK_MISSING && relinkMethod.split("missing").length>1) || relinkMethod.split("allLinks").length>1){                var missingCount = missingCount + 1;                if(extensionsArray.length == 18){                    var imgFolder = findInFolders(searchFolders, currentLink.name+".*")                    try{                        currentLink.relink(imgFolder[0]);                    }catch(e){                        var notFoundCount = notFoundCount + 1;                    }                }else{                    var foundLink = false;                    var loopCount = 0;                    while(foundLink == false && loopCount < extensionsArray.length){                        var baseFileName = GetFileName(currentLink.name)                        var imgName = String(baseFileName + "." + extensionsArray[loopCount]);                        var imgFolder = findInFolders(searchFolders, imgName);                        try{                            currentLink.relink(imgFolder[0]);                            var foundLink = true;                        }catch(e){};                        var loopCount = loopCount + 1;                    }//end while (to find extension specific files)                                    if(foundLink == false){                        var notFoundCount = notFoundCount + 1;                    }//end if foundLink is false                }//end if all extensions are selected            }//end check link status        pBar.value = aLink + 1;        }//end link loop        //-- update the progress bar    }//end document loop    //-- Close the progress bar    pBarWin.close();      //-------------------------------------------------------------------------------------------------------//    //-- Build the end-of-script message to display to the user...    if(missingCount==0){        var missingMsg = "";    }else if(missingCount>0 && relinkMethod.split("allLinks").length==1){        var successfulRelinksCount = missingCount - notFoundCount;        var missingMsg = String("\r" + successfulRelinksCount + " missing links were found and replaced.\r");    }else if(missingCount>0 && relinkMethod.split("allLinks").length>1){        var successfulRelinksCount = missingCount - notFoundCount;        var missingMsg = String("\r" + successfulRelinksCount + " links were relinked to the new directory.\r");    }    if(modifiedCount==0){        var modifiedMsg = ""    }else if(modifiedCount>0){        var modifiedMsg = String("\r" + modifiedCount + " modified links were found and updated.");    }        if(notFoundCount == 0){        var notFoundMsg = "\r\rAll missing links have been resolved."    }else{        var notFoundMsg = "\rUnable to find new links for " + notFoundCount + " files.\r\rRerun the InDesign Relinker script if you would like to look for these links in a different folder"    }    if(missingCount == 0 && notFoundCount == 0 && modifiedCount == 0 && relinkMethod.split("allLinks").length>1){        alert("Workflow Complete!\r\r" + totalLinkCount + " links were replaced.");    }else if(missingCount == 0 && notFoundCount == 0 && modifiedCount == 0){        alert("Workflow Complete!\r\rNo missing or modified links were found.");    }else{        alert("Workflow Complete!" + missingMsg + modifiedMsg+ notFoundMsg + "\r" );    }    //-------------------------------------------------------------------------------------------------------//}//end main relinking function//=================================================================================================================================//function GetFileName(fileName){    var str = "";    var res = fileName.lastIndexOf(".");    if (res == -1) {str = fileName;}else {str = fileName.substr(0, res);}    return str;}//-- Return the given folder followed by every folder nested inside it, root-first (shallow before deep).//-- Walks the tree once so the per-link search doesn't have to re-enumerate the directory structure.function collectFolders(folder){    var folders = [folder];    var entries = folder.getFiles();    for(var i=0;i<entries.length;i++){        if(entries[i] instanceof Folder){            folders = folders.concat(collectFolders(entries[i]));        }    }    return folders;}//-- Run the same native getFiles(mask) across every folder in the list and gather the matches.//-- Matching semantics are unchanged from the original single-folder call - only the number of folders differs.function findInFolders(folders, mask){    var results = [];    for(var i=0;i<folders.length;i++){        results = results.concat(folders[i].getFiles(mask));    }    return results;}