#include <glib.h>
#include <gtk/gtk.h>
#include <gdk/gdkx.h>

static urgent_cb (GtkWindow *window)
{
  XWMHints *wm_hints;
  GdkDisplay *display;
  GdkScreen *screen;
  Display *xdisplay;
  Window xid;

  screen = gtk_widget_get_screen (GTK_WIDGET (window));
  display = gdk_screen_get_display (screen);
  xdisplay = gdk_x11_display_get_xdisplay (display);
  xid = GDK_WINDOW_XWINDOW (GTK_WIDGET (window)->window);

  wm_hints = XGetWMHints (xdisplay, xid);
  if (!wm_hints) {
    wm_hints = XAllocWMHints ();
    wm_hints->flags |= XUrgencyHint;
  } else 
    wm_hints->flags ^= XUrgencyHint;
  XSetWMHints (xdisplay, xid, wm_hints);
  XFree (wm_hints);

  return FALSE;
}

gboolean
time_to_quit (GtkWidget *widget, GdkEvent *event, gpointer data)
{
  XWMHints *wm_hints;
  GdkDisplay *display;
  GdkScreen *screen;
  Display *xdisplay;
  Window xid;
  gboolean is_urgent;

  screen = gtk_widget_get_screen (GTK_WIDGET (widget));
  display = gdk_screen_get_display (screen);
  xdisplay = gdk_x11_display_get_xdisplay (display);
  xid = GDK_WINDOW_XWINDOW (GTK_WIDGET (widget)->window);

  wm_hints = XGetWMHints (xdisplay, xid);

  is_urgent = FALSE;
  if (wm_hints)
    {
      if (wm_hints->flags & XUrgencyHint)
        is_urgent = TRUE;
      XFree (wm_hints);
    }

  if (is_urgent)
    printf("Urgency flag was set when the program exited.\n");
  else
    printf("Urgency flag was NOT set when the program exited.\n");

  gtk_main_quit();

  return TRUE;
}

int main(int argc, char **argv)
{
  GtkWidget *window, *button;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  button = gtk_button_new_with_label ("Toggle Urgency");
  g_signal_connect_swapped (button, "clicked", G_CALLBACK (urgent_cb), window);
  gtk_container_add (GTK_CONTAINER (window), button);

  gtk_window_move (GTK_WINDOW (window), 300, 400);

  gtk_widget_show_all (window);

  g_signal_connect (window, "delete-event", G_CALLBACK (time_to_quit), NULL);

  gtk_main ();

  return 0;
}
