It’s strange. Your new example on my Photoshop 21.1.1 works just like the first one - the selection is created only if the layer is pre-activated on the palette. If no layer is selected, or a background layer is selected, then I get an error. What is your version of Photoshop? In the example above, I activated the layer only in one case - if there were no selected layers on the palette. In other cases, the state of the active layer did not change. I changed my code a bit - now it works in almost all cases: getSelectionFromLayerMask(2)
function getSelectionFromLayerMask(idx) {
s2t = stringIDToTypeID;
(docRef = new ActionReference()).putProperty(s2t("property"), s2t("targetLayers"))
docRef.putEnumerated(s2t("document"), s2t("ordinal"), s2t("targetEnum"))
var targetLayers = executeActionGet(docRef).hasKey(s2t("targetLayers"));
(docRef = new ActionReference()).putProperty(s2t("property"), s2t("numberOfLayers"))
docRef.putEnumerated(s2t("document"), s2t("ordinal"), s2t("targetEnum"))
var numberOfLayers = executeActionGet(docRef).getInteger(s2t("numberOfLayers"));
(lrRef = new ActionReference()).putProperty(s2t("property"), s2t("background"))
lrRef.putEnumerated(s2t("layer"), s2t("ordinal"), s2t("targetEnum"))
var background = executeActionGet(lrRef).getBoolean(s2t("background"));
if (numberOfLayers == 1 && background) return;
(lrRef = new ActionReference()).putProperty(s2t("property"), s2t("hasUserMask"))
lrRef.putIndex(s2t("layer"), idx)
if (!executeActionGet(lrRef).getBoolean(s2t("hasUserMask"))) return;
if (!targetLayers || background) {
(ref = new ActionReference()).putIndex(s2t("layer"), 1);
(desc = new ActionDescriptor()).putReference(s2t("null"), ref);
executeAction(s2t("select"), desc, DialogModes.NO)
}
makeSelectionFromLayerMask(idx)
if (!targetLayers) {
(ref = new ActionReference()).putEnumerated(s2t("layer"), s2t("ordinal"), s2t("targetEnum"));
(desc = new ActionDescriptor()).putReference(s2t("null"), ref);
executeAction(s2t("selectNoLayers"), desc, DialogModes.NO)
}
if (background) {
(ref = new ActionReference()).putIndex(s2t("layer"), 0);
(desc = new ActionDescriptor()).putReference(s2t("null"), ref);
executeAction(s2t("select"), desc, DialogModes.NO)
}
function makeSelectionFromLayerMask(idx) {
var desc = new ActionDescriptor();
var ref = new ActionReference();
ref.putProperty(charIDToTypeID("Chnl"), charIDToTypeID("fsel"));
desc.putReference(charIDToTypeID("null"), ref);
var ref1 = new ActionReference();
ref1.putEnumerated(charIDToTypeID("Chnl"), charIDToTypeID("Chnl"), charIDToTypeID("Msk "));
ref1.putIndex(charIDToTypeID("Lyr "), idx);
desc.putReference(charIDToTypeID("T "), ref1);
executeAction(charIDToTypeID("setd"), desc, DialogModes.NO)
}
} The most time-consuming operation is directly creating a selection. The time to get the layer attributes is practically zero and can be neglected (especially since if you do not take care of additional checks, this will lead to an error).
... View more