Skip to main content
Mohamed Hameed21513110
Inspiring
December 27, 2021
Answered

Code to transfer layers from a document to specific documents

  • December 27, 2021
  • 3 replies
  • 1274 views
Hello all professionals and collaborators...
I have a code that transfers layers from one document to all other documents open in Photoshop
But I want to make a Dialog that shows the open files and I choose the files to be transferred to
by checkbox
-
thanks for your cooperation
 
This topic has been closed for replies.
Correct answer JJMack

@Mike Bro

Really you are great
It was already done and implemented as I wanted
Thank you for your effort and interest


You should have been able to modify the hack I gave you to do that with Check Boxes to support up to a limited number of open documents.  The Script you accepted as your solution  hangs on my  machine when I select just some of the open documents to be copied to. Like  doc 3 5 and 9.  I have to use the Windows Task Manager to Kill Photoshop.  I do not have an issue like that when I modify the Hack I gave you. CopySelectedtoSelected.jsx

 

// JJMack
#target photoshop
var s2t = stringIDToTypeID;
var selectedDocs = new Array;  // Gloable array for selected open Documents to copy to

function main() {
	try {
		var myDoc = app.activeDocument;
		var selectedLayerID = new Array;
		selectedLayerID = get_selected_layers_id();
		if (selectedLayerID=="") {alert("No Selected Layers"); return;}

		// the maximum number of Open Documents to display
		var maxFiles = 30;
		// get only existing Open Documents
		var OpenDocuments = [];
		for (var i = 0; i<app.documents.length; i++) {
			if (app.documents[i]==myDoc) continue;  // omit the current document
			OpenDocuments.push(app.documents[i]);
			if (OpenDocuments.length == maxFiles) {
				break;
			}
		}
		len = OpenDocuments.length;
		if (!len) {
			alert('No Open Documents found.', 'No Open Documents', false);
			return;
		}

		// update maxFiles
		maxFiles = Math.min(maxFiles, len);

		// show Open Documents dialog
		var rfDialog = openDocumentsDialog(OpenDocuments, maxFiles);
		rfDialog.show();
	
		for (var s = 0; s < selectedDocs.length; s++) {
				copyToDoc(selectedLayerID[0], selectedDocs[s].name);
		}
	
	}
	catch(e) { alert(e + ': on line ' + e.line, 'Photoshop Error', true); }  
}

///////////////////////////////////////////////////////////////////////////////
// openDocumentsDialog - create the Open Documents dialog
///////////////////////////////////////////////////////////////////////////////
function openDocumentsDialog(OpenDocuments, maxFiles) {

	// dialog window
	var dlg = new Window('dialog');
	dlg.text = 'Open Documents';
	dlg.orientation = 'row';
	dlg.alignChildren = 'top';

	// recent items panel	
	var panel = dlg.add('panel');
	panel.text = 'Open Documents';
	panel.alignChildren = 'left';

	// recent items checkboxes
	var cb, rf;
	var checkboxes = [];
	for (var i = 0; i < maxFiles; i++) {
		rf = OpenDocuments[i];
		cb = panel.add('checkbox');
		cb.text = ' ' + decodeURI(rf.name);
		cb.helpTip = rf.fsName;
		checkboxes.push(cb);
	}

	// buttons
	var buttons = dlg.add('group');
	buttons.orientation = 'column';
	buttons.alignChildren = 'fill';

	// 'check all' button
	var checkAll = buttons.add('button');
	checkAll.text = 'Check All';
	checkAll.onClick = function() {
		toggleCheckBoxes(true);
	};

	// 'check none' button
	var checkNone = buttons.add('button');
	checkNone.text = 'Check None';
	checkNone.onClick = function() {
		toggleCheckBoxes(false);
	};

	// spacer
	var spacer = buttons.add('group');
	spacer.preferredSize.height = 10;

	// ok button
	var okBtn = buttons.add('button');
	okBtn.text = 'OK';
	okBtn.onClick = function() {
		dlg.close(1);
		copytoCheckedItems();
	};

	// cancel button
	var cancelBtn = buttons.add('button');
	cancelBtn.text = 'Cancel';
	cancelBtn.onClick = function() {
		dlg.close(2);
	};

	// dialog properties
	dlg.defaultElement = okBtn;
	dlg.cancelElement = cancelBtn;
	return dlg;

	// toggle checkboxes on/off
	function toggleCheckBoxes(enabled) {
		for (var i = 0; i < checkboxes.length; i++) {
			checkboxes[i].value = enabled;
		}
	}

	// Copy Layers to checked files
	function copytoCheckedItems() {
		for (var i = 0; i < checkboxes.length; i++) {
			if (checkboxes[i].value) {
			selectedDocs.push(OpenDocuments[i]);	//global array
			}
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
// openFile - open the selected file
///////////////////////////////////////////////////////////////////////////////
function openFile(file) {
	try {
		open(file);
	}
	catch(e) {
		alert('Unable to open file:\r' + file.fsName, 'File Open Error', true);
	}
}

///////////////////////////////////////////////////////////////////////////////
// isCorrectVersion - check for Adobe Photoshop CS3 (v10) or higher
///////////////////////////////////////////////////////////////////////////////
function isCorrectVersion() {
	if (parseInt(version, 10) >= 10) {
		return true;
	}
	else {
		alert('This script requires Adobe Photoshop CS3 or higher.', 'Wrong Version', false);
		return false;
	}
}

///////////////////////////////////////////////////////////////////////////////
// showError - display error message if something goes wrong
///////////////////////////////////////////////////////////////////////////////
function showError(err) {
	if (confirm('An unknown error has occurred.\n' +
		'Would you like to see more information?', true, 'Unknown Error')) {
			alert(err + ': on line ' + err.line, 'Script Error', true);
	}
}

// test initial conditions prior to running main function
if (isCorrectVersion()) {
	try {
		main();
	}
	// don't report error on user cancel
	catch(e) {
		if (e.number != 8007) {
			showError(e);
		}
	}
}

function copyToDoc(layerId,toDoc) { // seems to copy all Selected Layers
	var descriptor = new ActionDescriptor();
	var list = new ActionList();
	var reference = new ActionReference();
	var reference2 = new ActionReference();
	reference.putEnumerated( stringIDToTypeID( "layer" ), stringIDToTypeID( "ordinal" ), stringIDToTypeID( "targetEnum" ));
	descriptor.putReference( charIDToTypeID( "null" ), reference );
	reference2.putName( stringIDToTypeID( "document" ), toDoc );
	descriptor.putReference( stringIDToTypeID( "to" ), reference2 );
	descriptor.putInteger( stringIDToTypeID( "version" ), layerId );
	list.putInteger( 8 );
	descriptor.putList( stringIDToTypeID( "ID" ), list );
	executeAction( stringIDToTypeID( "duplicate" ), descriptor, DialogModes.NO );
}

function get_selected_layers_id() {  
	try {  
		var r = new ActionReference();      
		r.putProperty(charIDToTypeID("Prpr"), stringIDToTypeID("targetLayers"));      
		r.putEnumerated(charIDToTypeID("Dcmn"), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));  
		var d = executeActionGet(r);  
		if (!d.hasKey(stringIDToTypeID("targetLayers"))) {  
			var r = new ActionReference();  
			r.putProperty(charIDToTypeID("Prpr"), stringIDToTypeID("layerID"));      
			r.putEnumerated(charIDToTypeID("Lyr "), charIDToTypeID("Ordn"), charIDToTypeID("Trgt"));  
			return [ executeActionGet(r).getInteger(stringIDToTypeID("layerID")) ];  
        }  
		var list = d.getList(stringIDToTypeID("targetLayers"));  
		if (!list) return null;  
		var n = 0;  
		try { activeDocument.backgroundLayer } catch (e) { n = 1; }  
		var len = list.count;  
		var selected_layers = new Array();  
		for (var i = 0; i < len; i++) {  
			try {  
				var r = new ActionReference();  
				r.putProperty(charIDToTypeID("Prpr"), stringIDToTypeID("layerID"));      
				r.putIndex( charIDToTypeID("Lyr "), list.getReference(i).getIndex() + n);  
				selected_layers.push(executeActionGet(r).getInteger(stringIDToTypeID("layerID")));  
			}  
			catch (e) { _alert(e); return null; }  
		}  
		return selected_layers;  
	}  
	catch (e) { alert(e); return null; }  
}   

// based on code by mike hale, via paul riggott;
function selectLayerByID(id,add){
	add = undefined ? add = false:add
	var ref = new ActionReference();
    ref.putIdentifier(charIDToTypeID("Lyr "), id);
    var desc = new ActionDescriptor();
    desc.putReference(charIDToTypeID("null"), ref );
	if(add) desc.putEnumerated( stringIDToTypeID( "selectionModifier" ), stringIDToTypeID( "selectionModifierType" ), stringIDToTypeID( "addToSelection" ) );
	desc.putBoolean( charIDToTypeID( "MkVs" ), false );
	try{ executeAction(charIDToTypeID("slct"), desc, DialogModes.NO ); }
	catch(e){ alert(e.message); }
};

  

3 replies

Stephen Marsh
Community Expert
Community Expert
December 28, 2021

Before the GUI, the first hurdle would appear to be the lack of a native property for the names of open documents.

 

https://theiviaxx.github.io/photoshop-docs/Photoshop/Documents.html#documents

 

So some sort of loop through open docs that stores the names of each doc into an array would appear to be in order?

 

Mohamed Hameed21513110
Inspiring
December 28, 2021

Stephen_A_Marsh

Well, I will look for solutions.
But will there be any problems if I modify the code and add a dialoug that contains a checkbox to choose the documents I want to send the layers to

JJMack
Community Expert
Community Expert
December 28, 2021

Here is a quick hack however I have no Idea as the where the layers you want to copy are located or where in the selected open documents layers stacks you want the layers copied to..  CopytoSelected.jsx I do not know ScriptUI I just reused Trevor's dialog.....  Set a limit of 20 open documents and changed the code to process open Document instead of recent files that still exists.

 

If you add the copy function it should  use try catch.  Not all document can have layers added.  You  need to catch and log errors....

 

 

// Quick Hacked for a Copy layer to selected open documents  
// No actual Copy done for I have no idea where the layer to be copied are 
// or have any idea as the where the selected documents layer stack  layers should be added.
// Hacker JJMack

// Author: Trevor Morris (trevor@morris-photographics.com)

// enable double-clicking from Mac Finder or Windows Explorer
#target photoshop

// bring application forward for double-click events
app.bringToFront();

///////////////////////////////////////////////////////////////////////////////
// main - main function
///////////////////////////////////////////////////////////////////////////////
function main() {

	// the maximum number of Open Documents to display
	var maxFiles = 20;

	// get only existing Open Documents
	var OpenDocuments = [];
	for (var i = 0; i<app.documents.length; i++) {
		OpenDocuments.push(app.documents[i]);
		if (OpenDocuments.length == maxFiles) {
			break;
		}
	}


	len = OpenDocuments.length;
	if (!len) {
		alert('No Open Documents found.', 'No Open Documents', false);
		return;
	}

	// update maxFiles
	maxFiles = Math.min(maxFiles, len);

	// show Open Documents dialog
	var rfDialog = openDocumentsDialog(OpenDocuments, maxFiles);
	rfDialog.show();
}

///////////////////////////////////////////////////////////////////////////////
// openDocumentsDialog - create the Open Documents dialog
///////////////////////////////////////////////////////////////////////////////
function openDocumentsDialog(OpenDocuments, maxFiles) {

	// dialog window
	var dlg = new Window('dialog');
	dlg.text = 'Open Documents';
	dlg.orientation = 'row';
	dlg.alignChildren = 'top';

	// recent items panel	
	var panel = dlg.add('panel');
	panel.text = 'Open Documents';
	panel.alignChildren = 'left';

	// recent items checkboxes
	var cb, rf;
	var checkboxes = [];
	for (var i = 0; i < maxFiles; i++) {
		rf = OpenDocuments[i];
		cb = panel.add('checkbox');
		cb.text = ' ' + decodeURI(rf.name);
		cb.helpTip = rf.fsName;
		checkboxes.push(cb);
	}

	// buttons
	var buttons = dlg.add('group');
	buttons.orientation = 'column';
	buttons.alignChildren = 'fill';

	// 'check all' button
	var checkAll = buttons.add('button');
	checkAll.text = 'Check All';
	checkAll.onClick = function() {
		toggleCheckBoxes(true);
	};

	// 'check none' button
	var checkNone = buttons.add('button');
	checkNone.text = 'Check None';
	checkNone.onClick = function() {
		toggleCheckBoxes(false);
	};

	// spacer
	var spacer = buttons.add('group');
	spacer.preferredSize.height = 10;

	// ok button
	var okBtn = buttons.add('button');
	okBtn.text = 'OK';
	okBtn.onClick = function() {
		dlg.close(1);
		copytoCheckedItems();
	};

	// cancel button
	var cancelBtn = buttons.add('button');
	cancelBtn.text = 'Cancel';
	cancelBtn.onClick = function() {
		dlg.close(2);
	};

	// dialog properties
	dlg.defaultElement = okBtn;
	dlg.cancelElement = cancelBtn;
	return dlg;

	// toggle checkboxes on/off
	function toggleCheckBoxes(enabled) {
		for (var i = 0; i < checkboxes.length; i++) {
			checkboxes[i].value = enabled;
		}
	}

	// Copy Layers to checked files
	function copytoCheckedItems() {
		for (var i = 0; i < checkboxes.length; i++) {
			if (checkboxes[i].value) {
				alert("Copy Layers to "  + OpenDocuments[i]);
			}
		}
	}
}

///////////////////////////////////////////////////////////////////////////////
// openFile - open the selected file
///////////////////////////////////////////////////////////////////////////////
function openFile(file) {
	try {
		open(file);
	}
	catch(e) {
		alert('Unable to open file:\r' + file.fsName, 'File Open Error', true);
	}
}

///////////////////////////////////////////////////////////////////////////////
// isCorrectVersion - check for Adobe Photoshop CS3 (v10) or higher
///////////////////////////////////////////////////////////////////////////////
function isCorrectVersion() {
	if (parseInt(version, 10) >= 10) {
		return true;
	}
	else {
		alert('This script requires Adobe Photoshop CS3 or higher.', 'Wrong Version', false);
		return false;
	}
}

///////////////////////////////////////////////////////////////////////////////
// showError - display error message if something goes wrong
///////////////////////////////////////////////////////////////////////////////
function showError(err) {
	if (confirm('An unknown error has occurred.\n' +
		'Would you like to see more information?', true, 'Unknown Error')) {
			alert(err + ': on line ' + err.line, 'Script Error', true);
	}
}

// test initial conditions prior to running main function
if (isCorrectVersion()) {
	try {
		main();
	}
	// don't report error on user cancel
	catch(e) {
		if (e.number != 8007) {
			showError(e);
		}
	}
}

 

 

 

 

 

 

 

 

 

JJMack
Legend
December 27, 2021

Hello @Mohamed Hameed21513110,

 

Can you post the code that transfers layers from one document to all other documents open in Photoshop so we can build off that to add the dialog.

 

Regards,

Mike

JJMack
Community Expert
Community Expert
December 28, 2021

You can duplucate layers betweem documents several ways.  Copy and Paste  duplicate layer or layer group into a new document or some other open document. Standard Photoshop steps. Cut Past to transfer etc 

JJMack
Stephen Marsh
Community Expert
Community Expert
December 28, 2021
quote

You can duplucate layers betweem documents several ways.  Copy and Paste  duplicate layer or layer group into a new document or some other open document. Standard Photoshop steps. Cut Past to transfer etc 


By @JJMack

 

Indeed, or using the Layer menu > Duplicate Layer... option. And that is the point, it would seem appropriate for the OP to provide the existing code that the GUI request is based around. Creating a GUI always seems like x10 the work of creating the original script!

JJMack
Community Expert
Community Expert
December 27, 2021

You should be able to use the Open document list to create the ScriptUI dialog.  You could have many open documents in photoshop your list may need to be scrollable or have columns,  Document path and name may be quite long.  There have been scripts posted that had dialogs the displayed  file list you can select from like the recent open files list. Look at its code. Search for that script.

JJMack