Dragon8oy
Dragon8oy

Reputation: 25

Add buttons to libnotify notifications that run functions

I need to add buttons to the bottom of a libnotify notification that run functions when clicked. I can make the buttons appear, but they don't run the functions when clicked. It gives no error message at all.

The program is called with ./notifications "Title" "Body" "pathtoicon"

Code:

#include <libnotify/notify.h>
#include <iostream>

void callback_mute(NotifyNotification* n, char* action, gpointer user_data) {
  std::cout << "Muting Program" << std::endl;
  system("pkexec kernel-notify -am");
}

int main(int argc, char * argv[] ) {
    GError *error = NULL;
    notify_init("Basics");
    NotifyNotification* n = notify_notification_new (argv[1],
                                 argv[2],
                                 argv[3]);

    notify_notification_add_action (n,
      "action_click",
      "Mute",
       NOTIFY_ACTION_CALLBACK(callback_mute),
       NULL,
       NULL);


    notify_notification_set_timeout(n, 10000);
    if (!notify_notification_show(n, 0)) {
        std::cerr << "Notification failed" << std::endl;
        return 1;
    }
    return 0;
}

Any help would be greatly appreciated, thanks!

Upvotes: 1

Views: 615

Answers (1)

user12082191
user12082191

Reputation:

You have to use GMainLoop, a "main event loop" in order for the callback function to work. libnotify uses this loop in order to handle its actions, without it, it simply doesn't call the callback function you expected as there's nothing handling it.

Basically in your main function, just add a GMainLoop *loop in the beginning then loop = g_main_loop_new(nullptr, FALSE); to initialize it after that, then in the end just add g_main_loop_run(loop);. Your program should run just like as before but the callback function working now. So basically:

int main(int argc, char **argv)
{
  GMainLoop *loop;
  loop = g_main_loop_new(nullptr, FALSE);
  // ... do your stuff
  g_main_loop_run(loop);
  return 0;
}

You can read more about it at: The Main Event Loop: GLib Reference Manual

You don't have to include glib.h as libnotify includes it anyway.

Upvotes: 0

Related Questions