Launch A Program

Mar 23, 2024 at 3:50am
I'm working on my GUI game framework (SDL, Linux Machine). I have a keyboard shortcut that sends things into edit mode, and I want to have an edit option attached to all GUI objects that auto launches Krita for editing the source images.

I know that system calls are frowned upon, but what would you do or what is the preferred program launch method (especially on Linux) in this situation?

Side quest: Is there a way to confirm that a program exists on a system before or after calling it? [I'd like to offer the user a chance to specify another image editor if Krita is not installed.]
Last edited on Mar 23, 2024 at 4:40am
Mar 23, 2024 at 4:15am
The correct way is to fork() and exec*()...

but to make life simple just use system(). It is exactly what it is for.

You could also use popen(), but that blocks by default, and since you are running a GUI, don’t. Fixing the blocking and setting up a wait signal requires more deep magic that you don’t want to deal with. (Probably.)

Just use system().
Last edited on Mar 23, 2024 at 4:15am
Mar 23, 2024 at 4:50am
Oh, as for the side quest: just have an option for your program indicating which program you would like to run. Then, when the user selects to open in an image editor, either for the first time or because Krita failed to execute, have a little dialog box ready to pop up and ask the user to select a default application.

Depending on how much work you want to do, you can make the list pretty by looking through /usr/share/applications/defaults.list for .desktop files to examine. (The listing will start with the word “image/” as the very first thing on the line.)

Also look for any .desktop files you find laying around in ~/.local/share/applications/. You should probably do that first, heh.

In any case, once you have a .desktop file name, open it and look for the “GenericName” tag (with no language tag or with an “[en]” tag) reading “Image Editor”.

Those’ll be the applications the user has installed to edit image files. To start it, you’ll either need to parse out more of the file or just use gtk-launch.

1
2
3
4
5
6
7
8
9
10
11
12
  std::filesystem::path desktop_filename;
  // This is the value you got from your work above. It might be something like:
  //   "/usr/share/applications/krita.desktop"

  std::string cmd = "gtk-launch ";
  cmd += desktop_filename.stem();
  cmd += " ";
  cmd += image_filename_to_edit;
  // (I don’t think you need to add an "&" for this particular use case)

  int status = system( cmd.c_str() );
  if (status != 0) complain();

This is but one way to do things.

Good luck!
Mar 23, 2024 at 4:59am
That's great, thank you.
Topic archived. No new replies allowed.