Detecting if a module already exists in a pactch

I have a new module I’ve been working on that ideally I only want one instance of in any patch. I know there’s no way to stop users adding another one from the browser, so is there any way to detect if a module already exists in a patch? If so, is there a way to have one module remove the other instance when it’s added to the patch? Alternatively, is there a way to make the new module unload itself if it detects another instance in the patch when it is added? Is this even a good idea?

afaik this is not supported.

For example I’ve used

for (widget::Widget* w : APP->scene->rack->moduleContainer->children)

to loop through module widgets inside a patch. But the global APP have been said to change or disappear with future versions of rack.

But you could also define some global inside your plugin and check for that? Maybe just render the second created module with a text that the user shouldn’t create more, instead of searching the patch and dealing with removing it. Not sure if this would be good enough for you.

I’m curious though, why you want to do this. I also have a wip module that can set the theme for all of my modules and I’d like it to behave the same.

Here is a previous discussion on this subject:

1 Like

thanks! it even comes from the same reason as my interest in this.

skimming through it, singleton in plugin is ok, but deleting or preventing creation of second instance shouldn’t be done.

I’ve implemented a singleton in the Arcane family (to avoid unnecessary network connections) and UnDuLaR (to avoid both fighting for control), and nobody has reported any issue.

Thanks that looks like it’s got some good info in it. Strange it come up in any of my searches.

The submarine WM-101 only allows one instance to be active. So it uses a global variable to track the current instance. All other instances are disabled and show a message to say so. But if you close the active instance, one other instance will take over automatically.

2 Likes

If you want to make sure that you only have one “active” module per process, use

struct MyModule;

static MyModule* myModuleSingleton = NULL;

struct MyModule : Module {
	~MyModule() {
		if (myModuleSingleton == this) {
			myModuleSingleton = NULL;
		}
	}
	...
	void process(whatever) {
		if (myModuleSingleton == NULL) {
			myModuleSingleton = this;
		}
		if (myModuleSingleton != this) {
			return;
		}

		// do DSP stuff
	}
};

This will also make sure that only one module is added in the DAW process across all Rack for DAWs instances.

If it’s okay to have multiple instances per process but you want only one instance per rack, let me know.

1 Like

Thanks Andrew, that seems to work nicely.