• Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
    Dedicated community for Japanese speakers
  • 한국 커뮤니티
    Dedicated community for Korean speakers

Duplicate layer on the top of layers on all open documents

Engaged ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

I tried to duplicate some layer with a script to all open documents and put that layer on the top (with script listed below), but problem occures when on another document, active layer have cliped layers, this script unclipe layer. Does anyone now how to improve this?

 

Screen Shot 2022-09-30 at 12.40.25.png

if( app.documents.length > 0 ){
    duplicateToAll();
}
function duplicateToAll(){
    docs = app.documents;
    curDoc = app.activeDocument;
    for(var i = 0; i < docs.length; i++){
        if(curDoc != docs[i]){
        var curLayer;
        try { curLayer = docs[i].activeLayer; } catch(e) {}
        curDoc.activeLayer.duplicate(docs[i],ElementPlacement.PLACEATBEGINNING);
        }
        app.activeDocument = curDoc;
    }
}
TOPICS
Actions and scripting

Views

118

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

Community Expert , Sep 30, 2022 Sep 30, 2022

 

@milevic 

 

The following code will select the top layer on all open files without changing their original visibility. The active doc is presumed to be the file that you will dupe the layer group from. After selecting the top layer of all open docs the script will return to the original doc.

 

You should be able to add your code after this code.

 

/*
The active doc should be the source doc containing the layer or group to be duplicated to all other open docs
*/

// Set the original doc
var ori
...

Likes

Translate

Translate
Community Expert ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

You would need to add a routine to check for a clipped layer, then if there is a grouped layer select both the active layer and the clipped layer and duplicate them both. 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

Sorry for missunderstanding, this image represent destination document.  It s not problem when it is on source document,  main problem is when i have selected layer on destination doc. Is it possible to improve code for example to select top layer on each open document before i duplicate or any other idea?

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

I had a script that did this. I'll have to see if I can find it.

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

That will be great...

 

 

 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

Well I found the script, but it's actually a plugin and I'm not sure now how to install it. I'll post the jsx part of it, which is the meat. Basically, the script checks for clipped layers, and copies them both, keeps track of what was clipped and reclips them in another document. But it might take some figuring out how to get it to run as a normal script.

 

var doc = tDoc = null
var selLayIdx = []
var selLayId = []
var selLayers = []
var selClip = []
var useLayers = []
var useIdx =[]
var useClip = []
var targetLayer = []
var moveBg = false
var moveAfterBg = false
var hasBg = false
var hasGroup = false
var LayDown 
var bgChange = true;
var clipped = []

/*
//remove==================
btn_click ('get', true)

app.activeDocument = app.documents[1]
btn_click ('dupe', true)
//=========================
*/

function btn_click(mov,pos){
    bgChange = true;
    hasBg = hasBackground ()
    if(app.documents.length>0){
        if(mov=='get'){
            hasGroup = false;
            clipped = []
            targetLayer = []
            useLayers = []
            useIdx = []
            useClip = []
            selLayIdx = []
            selLayId = []
            selLayers = []
            selClip = []//clear all arrays
            doc=app.activeDocument
            }
        else {
            if(selLayIdx.length>0){
                tDoc=app.activeDocument;
                
                if(tDoc.activeLayer.isBackgroundLayer && !pos){
                    var tarBgConfirm = confirm ("You can't move a layer under a background Layer.\nDo you want to convert it to a normal Layer?", true);
                    if(tarBgConfirm){
                        tDoc.activeLayer.isBackgroundLayer = false
                        hasBg = false;
                        }
                    else{
                        bgChange = false
                        return 'reset'
                        }
                    }
                
                targetLayer[0] = tDoc.activeLayer;
                
                if(hasBg && pos){targetLayer[1] = Number(getSelectedLayersIdx ()[0])+1}
                else if(hasBg && !pos){targetLayer[1] = Number(getSelectedLayersIdx ()[0])}
                else if(!hasBg && pos){targetLayer[1] = Number(getSelectedLayersIdx ()[0])}
                else if(!hasBg && !pos){targetLayer[1] = Number(getSelectedLayersIdx ()[0])-1}
                
                app.activeDocument = doc;
                multiSelectByIDs (selLayId)
                }
            else{alert('No layers were selected to move or duplicate')};
            };
        
        if(mov=='move' && selLayIdx.length>0 && doc!=tDoc){mov='dupe'}
        
        switch(mov){
            case 'get':
                moveBg = false
                selLayIdx = getSelectedLayersIdx ()
                selLayId = getSelectedLayersIds ()
                if(selLayIdx[0]==0){                   
                    var bg = confirm('one of the selected layers is a background.\nDo you want to change it to a normal layer?',false) 
                    if(bg){
                        try{                          
                        doc.layers[doc.layers.length-1].isBackgroundLayer = false;
                        doc.activeLayer = doc.layers[doc.layers.length-1];
                        selLayId[0] = getSelectedLayersIds ()[0];                      
                        multiSelectByIDs (selLayId);
                        }
                    catch(e){alert(e)}
                        }
                    else{
                        selLayIdx = [];
                        selLayId = [];
                        bgChange = false;
                        break;
                        }
                    }
                selLayIdx = getSelectedLayersIdx ();
                if(app.documents.length>1){
                    makeActiveByIndex (selLayIdx, true);
                    //setSelectionArrays(selLayIdx)                  
                    multiSelectByIDs(selLayId);
                    
                    }
                break;
            case 'move':
                moveAM('move',targetLayer[1])
                break;
            case 'dupe':    
 //           try{
                if(doc==tDoc){
                    moveAM('dupe',targetLayer[1]);
                }
                else{
                    var dupeLayers = [];
                    var hasParent = false;
                    clipped = [];
                    useLayers = [];
                    app.activeDocument = doc;
                    multiSelectByIDs (selLayId);
                    
                    for(var i=0;i<selLayId.length;i++){
                        layDown = false;
                        if(selClip[i]){
                            var singleId = [selLayId[i]];
                            multiSelectByIDs (singleId);
                            
                            nextLayerDown ()
                            layDown = doc.activeLayer
                            
                            try{if(layDown!=selLayers[i-1]){selClip[i] = false}}
                            catch(e){selClip[i] = false}
                            
                            }
                        hasParent = false
                    
                        for(var j=0;j<selLayers.length;j++){
                            if(selLayers[i].parent==selLayers[j]||selLayers[i].parent.parent==selLayers[j]||selLayers[i].parent.parent.parent==selLayers[j]){
                                 hasParent = true
                                }
                            }//end second for loop
                            if(!hasParent){
                                useLayers.push(selLayers[i])
                                useClip.push(selClip[i])             
                                }//end if                        
                        };//end first loop
                            singleId = [selLayId[0]];//for some reason you have to set a single layer or you will get duplicate layers.
                            multiSelectByIDs (singleId);
                            
                        for(var i= 0; i<useLayers.length;i++){

                           if(pos && i==0){useLayers[i].duplicate(targetLayer[0],ElementPlacement.PLACEBEFORE)}
                           else if(!pos && i==0){useLayers[i].duplicate(targetLayer[0],ElementPlacement.PLACEAFTER)}
                           else{useLayers[i].duplicate(dupeLayers[i-1],ElementPlacement.PLACEBEFORE)}
                           dupeLayers.push(tDoc.activeLayer)
                                                    
                           };//end loop for getting ids and grouped layers
                        
                        multiSelectByIDs (selLayId)
                        var dupeId = []
                       
                        app.activeDocument = tDoc;
                      
                        for(var i=0;i<dupeLayers.length;i++){
                            tDoc.activeLayer = dupeLayers[i];                            
                            dupeId.push(getSelectedLayersIds()[0]);
                            var aL = tDoc.activeLayer
                            if(useClip[i] && !aL.grouped){aL.grouped = true}
                            else if(!useClip[i] && aL.grouped){aL.grouped = false}
                            };//end loop for grouping layers.

                        multiSelectByIDs (dupeId) ;
                    };//end else for dupe to different doc
                
 //               }//end try
 //           catch(e){alert('In dupe switch '+e)}
                
                break;
            };//end switch
        if(mov!='get'){
            hasGroup = false;
            clipped = []
            targetLayer = []
            useLayers = []
            useIdx = []
            useClip = []
            selLayIdx = []
            selLayId = []
            selLayers = []
            selClip = []//clear all arrays
            return 'done'
            }
        else if(bgChange){return 'sel'}
        else{return 'reset'}
        }//end if for two open layers
    else{alert('thre are no open files')}
    };

function moveAM(mov,targetIdx){//use index
    var idmove = charIDToTypeID( "move" );
        var desc8 = new ActionDescriptor();
        var idnull = charIDToTypeID( "null" );
            var ref8 = new ActionReference();
            var idLyr = charIDToTypeID( "Lyr " );
            var idOrdn = charIDToTypeID( "Ordn" );
            var idTrgt = charIDToTypeID( "Trgt" );
            ref8.putEnumerated( idLyr, idOrdn, idTrgt );
        desc8.putReference( idnull, ref8 );
        var idT = charIDToTypeID( "T   " );
            var ref9 = new ActionReference();
            var idLyr = charIDToTypeID( "Lyr " );
            ref9.putIndex( idLyr, Number(targetIdx) );
        desc8.putReference( idT, ref9 );
        
        if(mov=='dupe'){
            var idDplc = charIDToTypeID( "Dplc" );
            desc8.putBoolean( idDplc, true );            
            }
        var idAdjs = charIDToTypeID( "Adjs" );
        desc8.putBoolean( idAdjs, false );
        var idVrsn = charIDToTypeID( "Vrsn" );
        desc8.putInteger( idVrsn, 5 );
    executeAction( idmove, desc8, DialogModes.NO );
}

 function getSelectedLayersIds(){// get the selected layers identifiers
      //( these id's are unique and they will not change if the layer name is changed or it's position in the layers editor will change)
       var idxs = getSelectedLayersIdx();// first get the indexes
       var selectedLayersIds = [];
      //for each index get the layer id
      
       for( var i=0;i<idxs.length;i++){
          selectedLayersIds.push(getIdfromIdx(idxs[i]));
       }
       return selectedLayersIds;
    }
    function hasBackground(){// function to check if there is a background layer
        var res = undefined;
        try{
            var ref = new ActionReference();
            ref.putProperty( charIDToTypeID("Prpr") , charIDToTypeID("Nm  "));
            ref.putIndex( charIDToTypeID("Lyr "), 0 );
            executeActionGet(ref).getString(charIDToTypeID("Nm  ") );
            res = true;
        }catch(e){ res = false}
        hasBg=res
        return res;
    }
    function getIdfromIdx( idx ){// get the id from index
       var ref = new ActionReference();
       ref.putIndex(charIDToTypeID('Lyr '), idx);
        var desc = executeActionGet(ref);
           desc = desc.getInteger(charIDToTypeID("LyrI"));
           return desc;
    }

    function getSelectedLayersIdx(){// get the selected layers index( positon in layer editor)
         var selectedLayers = new Array;
         var ref = new ActionReference();
         ref.putEnumerated( charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
         var desc = executeActionGet(ref);
         var add = 1;
         if(hasBackground()){//alert('hBck');
             add = 0}
         if( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){
              desc = desc.getList( stringIDToTypeID( 'targetLayers' ));
              var c = desc.count
              var selectedLayers = [];
              for(var i=0;i<c;i++){
                   selectedLayers.push(  (desc.getReference( i ).getIndex()) + add);
              }
         }else{
              var ref = new ActionReference();
              ref.putProperty( charIDToTypeID('Prpr') , charIDToTypeID( 'ItmI' ));
              ref.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
              srs = hasBackground()?executeActionGet(ref).getInteger(charIDToTypeID( 'ItmI' ))-1:executeActionGet(ref).getInteger(charIDToTypeID( 'ItmI' ));
              selectedLayers.push( srs);
         }
         return selectedLayers;
    }

    function doesIdExists( id ){// function to check if the id exists
       var res = true;
       var ref = new ActionReference();
       ref.putIdentifier(charIDToTypeID('Lyr '), Number(id));
        try{var desc = executeActionGet(ref)}catch(err){res = false};
        return res;
    }
    function multiSelectByIDs(ids) {     
      if( ids.constructor != Array ) ids = [ ids ];
        var layers = [];
        var id54 = charIDToTypeID( "slct" );
        var desc12 = new ActionDescriptor();
        var id55 = charIDToTypeID( "null" );
        var ref9 = new ActionReference();
        for (var i = 0; i < ids.length; i++) {
           if(doesIdExists(ids[i]) == true){// a check to see if the id stil exists
               layers[i] = charIDToTypeID( "Lyr " );
               ref9.putIdentifier(layers[i], Number(ids[i]));
           }
        }
        desc12.putReference( id55, ref9 );
        var id58 = charIDToTypeID( "MkVs" );
        desc12.putBoolean( id58, false );
        executeAction( id54, desc12, DialogModes.NO );
    }

function makeActiveByIndex(idx, pushLay) {    
      var layUp, layDown
try{
      for (var i = 0; i < idx.length; i++) {
            var desc = new ActionDescriptor();
            var ref = new ActionReference();
            ref.putIndex(charIDToTypeID("Lyr "), Number(idx[i]))
            desc.putReference(charIDToTypeID("null"), ref);
            if (i > 0) {
                  var idselectionModifier = stringIDToTypeID("selectionModifier");
                  var idselectionModifierType = stringIDToTypeID("selectionModifierType");
                  var idaddToSelection = stringIDToTypeID("addToSelection");
                  desc.putEnumerated(idselectionModifier, idselectionModifierType, idaddToSelection);
            }
            desc.putBoolean(charIDToTypeID("MkVs"), true);
            executeAction(charIDToTypeID("slct"), desc, DialogModes.NO);

            if(pushLay){
                 if(doc.activeLayer.typename == 'LayerSet'){hasGroup = true};
                 
                  selLayers.push(doc.activeLayer);
                  selClip.push(Boolean (doc.activeLayer.grouped));
                  if(selClip[i] && idx[i]-1!=idx[i-1]){selClip[i]=false};
                  if(doc.activeLayer.typename == 'LayerSet'){selClip[i]=false};
                  }//end if for pushlay
              
      }//end loop
    }//end try

    catch(e){}
};// end makeActiveByIndex

function makeSingleActiveByIndex(idx) {

            var desc = new ActionDescriptor();
            var ref = new ActionReference();
            ref.putIndex(charIDToTypeID("Lyr "), idx)
            desc.putReference(charIDToTypeID("null"), ref);

            desc.putBoolean(charIDToTypeID("MkVs"), true);
            executeAction(charIDToTypeID("slct"), desc, DialogModes.NO);

};//end makeSingleActiveByIndex    

function setSelectionArrays(idxA){

    for(var i=0;i<idxA.length;i++){    
        var idx = Number(idxA[i]);
        var desc = new ActionDescriptor();
        var ref = new ActionReference();
        ref.putIndex(charIDToTypeID("Lyr "), idx)
        desc.putReference(charIDToTypeID("null"), ref);

        desc.putBoolean(charIDToTypeID("MkVs"), true);
        executeAction(charIDToTypeID("slct"), desc, DialogModes.NO);
        
         if(doc.activeLayer.typename == 'LayerSet'){hasGroup = true};
         
          selLayers.push(doc.activeLayer);
          selClip.push(Boolean (doc.activeLayer.grouped));
          if(selClip[i] && idx-1!=idx-1){selClip[i]=false};
          if(doc.activeLayer.typename == 'LayerSet'){selClip[i]=false};                
        };//end for loop

    }

function MyWriteln(inMessage) {
     // comment this out for production code
     if ( ! BridgeTalk.isRunning( "estoolkit" ) )
         BridgeTalk.launch( "estoolkit" );

     if ( BridgeTalk.isRunning( "estoolkit" ) ) {
         if ( app.name == "ExtendScript Toolkit" ) {
             $.writeln("help me " + inMessage);
       } else {
             var bt = new BridgeTalk;
             bt.body = "$.writeln('help me : " + inMessage + "');";
             bt.target = "estoolkit";
       bt.send();
       }
     }
}

function nextLayerDown(){
    var idslct = charIDToTypeID( "slct" );
        var desc5 = new ActionDescriptor();
        var idnull = charIDToTypeID( "null" );
            var ref5 = new ActionReference();
            var idLyr = charIDToTypeID( "Lyr " );
            var idOrdn = charIDToTypeID( "Ordn" );
            var idBckw = charIDToTypeID( "Bckw" );
            ref5.putEnumerated( idLyr, idOrdn, idBckw );
        desc5.putReference( idnull, ref5 );
        var idMkVs = charIDToTypeID( "MkVs" );
        desc5.putBoolean( idMkVs, false );
    executeAction( idslct, desc5, DialogModes.NO );    
    }

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Sep 30, 2022 Sep 30, 2022

Copy link to clipboard

Copied

 

@milevic 

 

The following code will select the top layer on all open files without changing their original visibility. The active doc is presumed to be the file that you will dupe the layer group from. After selecting the top layer of all open docs the script will return to the original doc.

 

You should be able to add your code after this code.

 

/*
The active doc should be the source doc containing the layer or group to be duplicated to all other open docs
*/

// Set the original doc
var origDoc = activeDocument;

// Loop over all open docs
for (var i = 0; i < app.documents.length; i++) {
    app.activeDocument = app.documents[i];
    
    // Ignore the original doc
    if (activeDocument !== origDoc) {
        
        // Select the top/front layer without changing visibility
        if (activeDocument.layers[0].visible === false) {
            activeDocument.activeLayer = activeDocument.layers[0];
            activeDocument.activeLayer.visible = false;
        } else {
            activeDocument.activeLayer = activeDocument.layers[0];
        }
    }
}

// Return to the original doc
activeDocument = origDoc;

 

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Engaged ,
Oct 02, 2022 Oct 02, 2022

Copy link to clipboard

Copied

This is great. I combine this code with this one from queston and that works perfectly. Thanks

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines
Community Expert ,
Oct 02, 2022 Oct 02, 2022

Copy link to clipboard

Copied

LATEST

You're welcome!

Likes

Translate

Translate

Report

Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines