#target photoshop
if (app.documents.length > 0) {
var doc = app.activeDocument;
var theLayer = doc.activeLayer;
var lbRef = theLayer.bounds;
if (getSelectedLayersIdx().length != 1) {
alert("Mission Impossible! Select one layer and repeat")
} else {
if (theLayer.kind != "LayerKind.SMARTOBJECT") {
alert("Selected layer is not a smart object")
} else {
if ($.os.search(/windows/i) != -1) {
var theFiles = File.openDialog("please select files", "*.*", true)
} else {
var theFiles = File.openDialog("please select files", getFiles, true)
};
if (theFiles) {
replacedLayer = newFile_and_relinkToFile()
dX = lbRef[0].value - replacedLayer.bounds[0].value
dY = lbRef[3].value - replacedLayer.bounds[3].value
replacedLayer.translate( dX, dY );
theLayer.remove();
};
};
};
};
function getFiles(theFile) {
if (theFile.name.match(/\.(psd|tif|jpg|ai|pdf)$/i) != null || theFile.constructor.name == "Folder") {
return true
};
};
function relinkToFile(newFile) {
var idplacedLayerReplaceContents = stringIDToTypeID("placedLayerRelinkToFile");
var desc3 = new ActionDescriptor();
var idnull = charIDToTypeID("null");
desc3.putPath(idnull, new File(newFile));
var idPgNm = charIDToTypeID("PgNm");
desc3.putInteger(idPgNm, 1);
executeAction(idplacedLayerReplaceContents, desc3, DialogModes.NO);
};
function newFile_and_relinkToFile() {
app.activeDocument.selection.copy();
newDoc = documents.add(doc.width, doc.height, doc.resolution);
newDoc.paste();
relinkToFile(theFiles);
app.activeDocument.selection.copy();
newDoc.close(SaveOptions.DONOTSAVECHANGES);
app.activeDocument = doc;
doc.paste();
return app.activeDocument.activeLayer;
};
function getSelectedLayersIdx(){
var selectedLayers = new Array;
var ref = new ActionReference();
ref.putEnumerated( charIDToTypeID('Dcmn'), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
var desc = executeActionGet(ref);
if( desc.hasKey( stringIDToTypeID( 'targetLayers' ) ) ){
desc = desc.getList( stringIDToTypeID( 'targetLayers' ));
var c = desc.count;
var selectedLayers = new Array();
for(var i=0;i<c;i++){
try{
activeDocument.backgroundLayer;
selectedLayers.push( desc.getReference( i ).getIndex() );
}catch(e){
selectedLayers.push( desc.getReference( i ).getIndex()+1 );
};
};
}else{
var ref = new ActionReference();
ref.putProperty( charIDToTypeID('Prpr') , charIDToTypeID( 'ItmI' ));
ref.putEnumerated( charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt') );
try{
activeDocument.backgroundLayer;
selectedLayers.push( executeActionGet(ref).getInteger(charIDToTypeID( 'ItmI' ))-1);
}catch(e){
selectedLayers.push( executeActionGet(ref).getInteger(charIDToTypeID( 'ItmI' )));
};
};
return selectedLayers;
};