Gio single instance logic

I’m struggling to achieve the single instance behavior in my gtk4 app. When I run it subsequently from gnome-shell’s terminal, it always opens a new window and when I tried to count the windows associated with the GtkApplication (before app activation) it returns 0.

int main (int argc, char **argv) {
  GtkApplication *app;
  int status;
  
  printf("%s\n", g_application_id_is_valid("com.example") ? "valid" : "not valid");
  
  app = gtk_application_new ("com.example", G_APPLICATION_FLAGS_NONE);
  
  printf("%d\n", g_list_length(gtk_application_get_windows(app)));
  
  g_signal_connect (app, "activate", G_CALLBACK (gpcst_activate), NULL);
  status = g_application_run (G_APPLICATION (app), argc, argv);
  g_object_unref (app);

  return status;
}

Thank you for your help.

It seems you’re operating under the impression that gtk_application_get_windows() will return the list of windows of a running application. That’s not, and has never been, the case.

The way single instances work is:

  • the first instance will claim a token on a shared global resource when calling g_application_run(); on Linux, this is a name on the session bus associated to the user on a machine; that name is the application id
  • any other instance launched will call g_application_run(), see that there’s already a running instance, call the Activate D-Bus method on that instance, and will immediately return from the g_application_run()

For more information, see the documentation of the GApplication class.

Thank you so much!

I’ve read the doc, but somehow overlooked this:

“If the application is not the primary instance then a signal is sent to the primary instance and g_application_run() promptly returns.”

Sorry, just one more question, how do I avoid to call the activate signal in this case? So that no new window creation happens.

You cannot avoid it: it’s how the whole thing works.

Let’s back up a bit: what are you actually trying to achieve?

Ah, I see. All works now, I moved the window counter logic inside the activate callback, so now I have only one window despite invoking the app many times.

Thank you for all :slight_smile:

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.