/* -*- c-basic-offset: 2 -*- */
/*
 *   cc `pkg-config --cflags --libs gtk+-2.0` metaerror.c -o metaerror
 */
#include <gtk/gtk.h>
#include <gdk/gdkx.h>

GdkFilterReturn wm_protocols_filter (GdkXEvent *xev,
				     GdkEvent  *event,
				     gpointer   data);
int
main (int argc, char *argv[])
{
  GtkWidget *window;

  gtk_init (&argc, &argv);

  window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

  gdk_add_client_message_filter (gdk_atom_intern ("WM_PROTOCOLS", FALSE),
				 wm_protocols_filter, NULL);

  gtk_widget_show_all (window);

  gtk_main ();

  return 0;
}

GdkFilterReturn
wm_protocols_filter (GdkXEvent *xev, GdkEvent  *event, gpointer no_data)
{
  XEvent     *xevent;
  GdkWindow  *win;
  GdkDisplay *display;
  Atom        message;

  xevent = (XEvent *)xev;
  win = event->any.window;
  display = gdk_drawable_get_display (GDK_DRAWABLE (win));
  message = (Atom) xevent->xclient.data.l[0];

  if (message == gdk_x11_get_xatom_by_name_for_display (display, "WM_DELETE_WINDOW")) {
    event->any.type = GDK_DELETE;
    return GDK_FILTER_TRANSLATE;
  } else if (message == gdk_x11_get_xatom_by_name_for_display (display, "WM_TAKE_FOCUS")) {
    GtkWidget *widget;
    guint32    take_focus_time;
    widget = gtk_widget_get_toplevel (gtk_get_event_widget (event));
    take_focus_time = xevent->xclient.data.l[1];
    XSetInputFocus (GDK_WINDOW_XDISPLAY (widget->window),
		    GDK_WINDOW_XID (widget->window),
		    RevertToParent,
		    take_focus_time);
    g_message ("Take focus at %d", take_focus_time);
  } else if (message == gdk_x11_get_xatom_by_name_for_display (display, "_NET_WM_PING")
	     && !_gdk_x11_display_is_root_window (display, xevent->xclient.window)) {
    XEvent xev = *xevent;
    xev.xclient.window = GDK_ROOT_WINDOW ();
    XSendEvent (GDK_WINDOW_XDISPLAY (win),
		xev.xclient.window,
		False,
		SubstructureRedirectMask | SubstructureNotifyMask,
		&xev);
  }
  return GDK_FILTER_REMOVE;
}
