Where should a Gtk.Application parse command line arguments

I am developing a Gtk.Application that should handle these scenarios:

  1. Launch the primary instance:
    $ my_app
  2. Launch a remote instance:
    $ my_app -p default

when a remote instance is launched, it should communicate the given parameter “default” to the primary instance so that the primary instance could open a new application window for this parameter.

Following these guidelines, my first attempt is

  1. connect to handle-local-options
  2. Call activate_action on my application when I see the parameter “-p”

This results in the error that the application is not yet registered.

My second attempt was to follow this advice and to register the application before activating my action. I was wondering if I should register the app within the handle-local-options callback but gemini suggested that it was a really bad idea. Instead, Gemini suggested using G_APPLICATION_HANDLES_COMMAND_LINE and use the command-line signal but the Gnome tutorial suggests that it is probably not the recommended way.

So, what is the recommended way to accomplish this task?

There is the command-line signal that gets emitted in the primary instance. See Gio.ApplicationCommandLine and the notes on Gio.Application::handle-local-options.

Thanks, Sergey! This is the path I am following at the moment:

app = Gtk.Application(
	application_id = APPLICATION_ID,
	flags = Gio.ApplicationFlags.HANDLES_COMMAND_LINE,
)

app.connect('command-line', on_command_line)

...

def on_command_line(
	application: Gtk.Application,
	cmd_line: Gio.ApplicationCommandLine
) -> int:
	options = cmd_line.get_options_dict()
	# My logic to handle the command line options
	...
	return 0

My concern is that section “Using G_APPLICATION_HANDLES_COMMAND_LINE" of “Using GtkApplication” says

G_APPLICATION_HANDLES_COMMAND_LINE allows for a more complex interaction between the two sides. If in doubt, you should not use G_APPLICATION_HANDLES_COMMAND_LINE

None of the cases in this section seem to match. I guess I could stretch this case to my scenario:

your application needs to print data from the primary instance to the stdout/stderr of the terminal of the remote instance

In the sense that when the parameter is incorrect I may decide to report the error on the remote instance side.