executeAsModal when refreshing UI?

My understanding is that checking a document’s state shouldn’t require a modal context.

In this case I want to keep my panel’s interface up to date, so I’ve got a setInterval going every 500ms while the panel is open - if a modal context takes full control of Photoshop and stops anything else from happening it seems potentially a bad idea to be doing that twice a second.

However… I’m using this method to check whether we’re in a mask, and occasionally at random (usually when Photoshop is saving/flattening/opening) it brings up an error window: “The command ‘Get’ is not currently available.”

async function getTargetChannels() {
  
  const app = require("photoshop").app;
  const doc = app.activeDocument;
  const layer = doc.activeLayers && doc.activeLayers.length > 0 ? doc.activeLayers\[0\] : null;
  
  if (!layer) {
        console.log("No active layer.");
        return null;
   }

  return await executeAsModal(async () => {
    const result = await batchPlay(
      [{
      _obj: "get",
      _target: [
                          { _ref: "layer", _id: layer.id }
      ],
      options: { dialogOptions: "dontDisplay" }
                  }],
                  {}
            );
  *// The targetChannels property should be in result[0]*
  return result[0].targetChannels || null;
      }, { commandName: "Check Mask State" });
}

I’m guessing that the intermittent errors are because something has changed and the layer I was trying to get is no longer available. Presumably executeAsModal could stop this from happening, but is it a bad idea to do it so frequently, when the user isn’t necessarily even using the plugin?

What’s the right way to go about this?

You can listen to “idle” event. It also happens freuqently but not if PS is doing something.

Alternatively you could also run get action only when there is no modal state. But not only yours plugin can start modal state and it is not easy to find out. Built-in method does not work as expected.

For my own plugin I made executeAsModal Scheduler to make sure not running any of those twice at the same time and then workaround to check if e.g. user opened some dialog window meaning PS is in modal state.