Skip to main content
Inspiring
February 8, 2020
Answered

Help Searching Layers For Name Script

  • February 8, 2020
  • 4 replies
  • 2403 views

Can someone help me with a script which will search all layers in Active Documnet for a specific name and if found make that the active Layer or Return an Alert if not found.

 

Thanks

Ian

This topic has been closed for replies.
Correct answer pixxxelschubser

Reading your posting again:

try {
(ref1 = new ActionReference()).putName(stringIDToTypeID('layer'), "Canvas" ); // replace Canvas with your layer name
(desc1 = new ActionDescriptor()).putReference(stringIDToTypeID('null'), ref1)
executeAction(stringIDToTypeID('select'), desc1, DialogModes.NO);
} catch (e) {
    alert("Sorry, this layername does not exists");
}

4 replies

pixxxelschubser
Community Expert
Community Expert
February 8, 2020

Did you tried your own code in documents with layer sets?

IanBarberAuthor
Inspiring
February 8, 2020

Ah...

 

Just tried my own code with Layer Sets and it Failed 😞

JJMack
Community Expert
Community Expert
February 8, 2020

To process all layers names with DOM code you would need to use recursion. In that Process you could break when you find the first layer with the name or continue the process counting the number of layer or creating an array of layers with the name. A count of 0 = not found . The Action manage code is select layer Name.  Which will  select the layer with the name closest to the bottom of the layer stack.  If there no such layer the Active layer would  not be changed from what it was. 

 

There are some differences between Action manager Layer kinds and  DOM Layer Kind.   For example all shape layers are fill layers  but all fill layers are not shape layers.   DOM has no Layer Kind Shape where Action Manager has a Shape kind.    Many Scripts need to use some action manager code to script some thing Adobe DOM does not cover all of Photoshop  features.

 

Here is a LayerStack.jsx that views layers from both kind of view don't try the script on a document with more the 20 layers.

// 2019, use it at your own risk;

	//Action Manager layerKind seems to be like this. 
 	var Doclayerkind = [
	"Pixel", 
	"Adjustment", 
	"Text",
	"Shape",
	"Smartobject",
	"6",
	"Layerset",
	"3Dlayer",
	"Gradientfill",
	"Patternfill",
	"Colorfill",
	"12",
	"13",
	"14",
	"15",
	"16",
	"17",
	"18",
	"19",
	"20",
	"21",
	"22",
	"23",
	"24"
	]

var theLayers = collectLayers ();
alert("Layer Stack Height " + theLayers.length + "\n" + theLayers.join("\n") );

////// collect layers //////
function collectLayers () {
	// the file;
	var myDocument = app.activeDocument;
	// get number of layers;
	var ref = new ActionReference();
	ref.putEnumerated( charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt") );
	var applicationDesc = executeActionGet(ref);
	var theNumber = applicationDesc.getInteger(stringIDToTypeID("numberOfLayers"));
	// process the layers;	
	var theLayers = new Array;
	for (var m = 0; m <= theNumber; m++) {
		try {
			var ref = new ActionReference();
			ref.putIndex( charIDToTypeID( "Lyr " ), m);
			var layerDesc = executeActionGet(ref);
			//alert(actionDescriptor(layerDesc));
			//if (m==1) alert(actionDescriptor(layerDesc));
			var layerSet = typeIDToStringID(layerDesc.getEnumerationValue(stringIDToTypeID("layerSection")));
			var isBackground = layerDesc.getBoolean(stringIDToTypeID("background"));
			// if group collect values;
			//if (layerSet != "layerSectionEnd" && layerSet != "layerSectionStart" ) {
			//if (layerSet != "layerSectionEnd" && layerSet != "layerSectionStart" && isBackground != true) {
				var theName = layerDesc.getString(stringIDToTypeID('name'));
				var theKind = layerDesc.getInteger(stringIDToTypeID('layerKind'));
				var theID = layerDesc.getInteger(stringIDToTypeID('layerID'));
				var theBounds = layerDesc.getObjectValue(stringIDToTypeID("bounds"));
				var theseBounds = [theBounds.getUnitDoubleValue(stringIDToTypeID("left")), theBounds.getUnitDoubleValue(stringIDToTypeID("top")), theBounds.getUnitDoubleValue(stringIDToTypeID("right")), theBounds.getUnitDoubleValue(stringIDToTypeID("bottom"))];
				layer = get_layer_by_id(theID);
				var theBlend = layer.blendMode; 
				var theOpacity = layer.opacity; 
				var theVisible = layer.visible; 
				var theType = layer.typename; 	
				var theParent = layer.parent;
				
				if (layer!=null) {theRealkind = layer.kind;}
				else {theRealkind = "";}
				if (theRealkind==undefined) {theRealkind = "LayerKind.UNDEFINED"}	
				// Action Manager layerKnd Shape
				//alert(Doclayerkind[theKind-1]);
				if (Doclayerkind[theKind-1]=="Shape") {
					//alert(actionDescriptor(layerDesc));
					var theFill= layerDesc.getBoolean(stringIDToTypeID("fillEnabled"));
					var theStrokewidth="";
					var theStrokenabled=false; 
					try {					
						var theStrokewidth = layerDesc.getObjectValue(stringIDToTypeID("AGMStrokeStyleInfo")).getUnitDoubleValue(stringIDToTypeID("strokeStyleLineWidth"));
						var theStrokenabled = layerDesc.getObjectValue(stringIDToTypeID("AGMStrokeStyleInfo")).getBoolean(stringIDToTypeID("strokeEnabled"));
					}
					//catch(e) {alert(e + ': on line ' + e.line, 'Script Error', true); }
					catch(e) { }					
					theLayers.push([theName, "ID " + theID, Doclayerkind[theKind-1], theType, theParent, theBlend, "Opacity " + theOpacity, "Visible " + theVisible, "Bounds " + theseBounds, "stroke " + theStrokewidth + " " + theStrokenabled, "fill " + theFill, theRealkind]);				
				}
				// Action Manager layerKind Adjustments		
				else if (Doclayerkind[theKind-1]=="Adjustment") {
					//alert(actionDescriptor(layerDesc));					
					theLayers.push([theName, "ID " + theID, Doclayerkind[theKind-1], theType, theParent, theBlend, "Opacity " + theOpacity, "Visible " + theVisible, "Bounds " + theseBounds, theRealkind]);
				}
				// Action Manager layerKind Smartobjects			
				else if (Doclayerkind[theKind-1]=="Smartobject") {
					//alert(actionDescriptor(layerDesc));					
					// get Smart Object info
					//alert(obj_to_str(layer));
					/*
					alert(["allLocke " +  layer.allLocked,
					      "\nblendMode " +  layer.blendMode,
					      "\nbound " +  layer.bounds,
					      "\nboundsNoEffect " +  layer.boundsNoEffects,
					      "\nid " +  layer.id,
					      "\nitemIndex " +  layer.itemIndex,					
					      "\nlinkedLayer " +  layer.linkedLayers,						
					      "\nname " +  layer.name,	
					      "\nopacity " +  layer.opacity,	
					      "\nparent " +  layer.parent,	
					      "\ntypename " +  layer.typename,	
					      "\nvisible " +  layer.visible,						
					      "\nxmpMetadata " +  layer.xmpMetadata]);						
					*/
					theLayers.push([theName, "ID " + theID, Doclayerkind[theKind-1], theType, theParent, theBlend, "Opacity " + theOpacity, "Visible " + theVisible, "Bounds " + theseBounds, theRealkind]);
				}	
				// Action Manager layerKind Text					
				else if (Doclayerkind[theKind-1]=="Text") {
					//alert(actionDescriptor(layerDesc));					
					// get text info
					//alert(obj_to_str(layer));
					/*
					alert(["allLocke " +  layer.allLocked,
					      "\nblendMode " +  layer.blendMode,
					      "\nbound " +  layer.bounds,
					      "\nboundsNoEffect " +  layer.boundsNoEffects,
					      "\nid " +  layer.id,
					      "\nitemIndex " +  layer.itemIndex,					
					      "\nlinkedLayer " +  layer.linkedLayers,						
					      "\nname " +  layer.name,	
					      "\nopacity " +  layer.opacity,	
					      "\nparent " +  layer.parent,	
					      "\ntypename " +  layer.typename,	
					      "\nvisible " +  layer.visible,						
					      "\nxmpMetadata " +  layer.xmpMetadata,					
					      "\nkind " + layer.kind,
					      "\ncolor " + layer.textItem.color,
					      "\ntextkind " + layer.textItem.kind, 
					      "\nfont " + layer.textItem.font, 
					      "\nblend " + layer.blendMode, 
					      "\nantiAliasMethod " + layer.textItem.antiAliasMethod,
					      "\nsize " + layer.textItem.size, 
						  "\nposition " + layer.textItem.position,
					      "\ncontents " + layer.textItem.contents, 					  
						  ]);
					*/
					theLayers.push([theName, "ID " + theID, Doclayerkind[theKind-1], theType, theParent, theBlend, "Opacity " + theOpacity, "Visible " + theVisible, "Bounds " + theseBounds, layer.textItem.font, layer.textItem.size, theRealkind ]);
				}	
				// Action Manager layerKind	Pixel
				// Action Manager layerKind	Layerset
				// Action Manager layerKind	Gradientfill
				// Action Manager layerKind	Patternfill
				// Action Manager layerKind	Colorfill
				// Action Manager layerKind other
				else {
					//alert(theName + "," + Doclayerkind[theKind-1]);
					//alert(actionDescriptor(layerDesc));						
					theLayers.push([theName, "ID " + theID, Doclayerkind[theKind-1], theType, theParent, theBlend, "Opacity " + theOpacity, "Visible " + theVisible, "Bounds " + theseBounds, theRealkind]);
				}
			//};
		}
		catch (e) {};
	};
	return theLayers
};


// DOM Layer items
function layerInfo(layer) {
	alert("LayerName='" + layer.name + "'" 
	+ "\nLayerID='" + layer.id  + "'"
	+ "\nLayerKind='" + layer.kind + "'"
	+ "\nallLocked='" + layer.allLocked + "'"
	+ "\nblendMode='" + layer.blendMode + "'"
	+ "\nbounds='" + layer.bounds + "'"
	+ "\nboundsNoEffects='" + layer.boundsNoEffects + "'"
    + "\nitemIndex='" + layer.itemIndex + "'" 
    + "\nlinkedLayers='" + layer.linkedLayers + "'"
	+ "\nopacity='" + layer.opacity + "'"
	+ "\nparent='" + layer.parent + "'"	
	+ "\ntypename='" + layer.typename + "'"	
	+ "\nvisible='" + layer.visible + "'"	
	+ "\nxmpMetadata='" + layer.xmpMetadata + "'"	
	
	);	
}

// Thanks to SuperMerlin
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function actionDescriptor(desc){  
	if(desc.typename == 'ActionDescriptor'){  
		var c = desc.count;  
		var msg= "Action Descriptor Item Count = " + c;
		for(var i=0;i<c;i++){ //enumerate descriptor's keys  
			//$.writeln('AD '+zeroPad( i+1, 2 )+' = '+IDTz(desc.getKey(i)) +' : '+desc.getType(desc.getKey(i)));   
			msg =  msg + "\n" + 'AD '+zeroPad( i+1, 2 )+' = '+IDTz(desc.getKey(i)) +' : '+desc.getType(desc.getKey(i)) ; 
		} 
    return msg; 
	}  
	function IDTz(id){  
		try {  
			var res = typeIDToStringID( id );  
			if(res == '' ){  
				var res = typeIDToCharID( id );  
			}  
		}
		catch(e){}  
		return res;  
	}  
	function zTID( s ){  
		if( s.length == 4 ) var res = charIDToTypeID( s );  
		if( s.length > 4 ) var res = stringIDToTypeID( s );  
		return res;  
	}  
	function zeroPad(num,pad) {  
		var z = Math.pow(10,Number(pad))  
		return num <= z ? ((Number( num) + z).toString().substr(1)): num  
	}  
}; 

//Thanks to r-bin
function obj_to_str(obj){var str = ""; for (var p in obj) if(obj.hasOwnProperty(p))try{str+=p+"::"+obj[p]+"\n";}catch(e){};return str;}  

// Thanks to
function get_layer_by_id(id, doc_id) {    
	try {    
		var doc;  
		if (doc_id == undefined) doc = activeDocument;  
		else { 
			for (var i = 0; i < documents.length; i++) {  
				if (documents[i].id == doc_id) {  
					doc = documents[i];  
					break;  
                }  
            }
		}
		if (doc == undefined) { alert("Bad document " + doc_id); return null; }  
		var r = new ActionReference();      
		r.putProperty(charIDToTypeID("Prpr"), stringIDToTypeID("json"));   
		if (doc_id == undefined) r.putEnumerated(charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));  
		else                     r.putIdentifier(charIDToTypeID("Dcmn"), doc_id);  
		eval("var json = " + executeActionGet(r).getString(stringIDToTypeID("json")));    
		if (json == undefined) return null;    
		var set = new Array();  
		function search_id(layers, id) {    
			for (var i = 0; i < layers.length; i++) {  
				if (layers[i].id == id) { set.push(i); return true; }  
            }  
			for (var i = 0; i < layers.length; i++) {  
				if (layers[i].layers) {    
					if (search_id(layers[i].layers, id)) { set.push(i); return true; }   
				}  
			}  
		}     
		if (search_id(json.layers, id)) {  
			var ret = doc.layers;  
			for (var i = set.length-1; i > 0; i--) { ret = ret[set[i]].layers;}  
			return ret[set[0]];  
		}  
		return null;  
	}    
	catch (e) { alert(e); }    
} 

 

JJMack
pixxxelschubser
Community Expert
pixxxelschubserCommunity ExpertCorrect answer
Community Expert
February 8, 2020

Reading your posting again:

try {
(ref1 = new ActionReference()).putName(stringIDToTypeID('layer'), "Canvas" ); // replace Canvas with your layer name
(desc1 = new ActionDescriptor()).putReference(stringIDToTypeID('null'), ref1)
executeAction(stringIDToTypeID('select'), desc1, DialogModes.NO);
} catch (e) {
    alert("Sorry, this layername does not exists");
}
IanBarberAuthor
Inspiring
February 8, 2020

Thank You

 

This also seems to work having read a bit deeper into the Scripting Manual

 

try {
  app.activeDocument.activeLayer = app.activeDocument.artLayers.getByName("Master Layer");
  }
catch (e) {
  alert("Not Found");
  }

Guess its just a personal Preference as to which way to do it

pixxxelschubser
Community Expert
Community Expert
February 8, 2020

Hi @ian-barber,

you could try:

 

 

(ref1 = new ActionReference()).putName(stringIDToTypeID('layer'), "Canvas" ); // replace Canvas with your layer name
(desc1 = new ActionDescriptor()).putReference(stringIDToTypeID('null'), ref1)
executeAction(stringIDToTypeID('select'), desc1, DialogModes.NO);

 

 

 

If that works for you

have fun

😉

JJMack
Community Expert
Community Expert
February 8, 2020

If the script finds layers with the name would you also want the nuuber of layers with the name or knowing that there is at least one is all you need to know.  getByName

JJMack
IanBarberAuthor
Inspiring
February 8, 2020

knowing that there is at least one would probably be sufficient