/* 
 * OroboROX Window Manager
 * 
 * Copyright (C) 2004 Guido Schimmels
 *
 * code of this module mostly from Metacity
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  
 */

#include "config.h"
#include <stdio.h>
#include <glib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/cursorfont.h>
#include <X11/Xmd.h>
#include <ft2build.h>
#include <X11/Xft/Xft.h>

#include "xerror.h"
#include "main.h"
#include "hints.h"
#include "client.h"
#include "stacking.h"
#include "keyboard.h"
#include "pixmap.h"
#include "mouse.h"
#include "settings.h"
#include "ping.h"

#define PING_TIMEOUT_DELAY 2250

//static guint32 current_time;

static gboolean ping_timeout(gpointer data)
{
	Client *c = data;
	c->ping_timeout_id = 0;
	c->ping_moribund = True;
	XDefineCursor(dpy, c->buttons[CLOSE_BUTTON], kill_cursor);

	dbg("Ping %lu on window %s timed out\n", c->ping_time, c->class.res_name);
		
	return FALSE;
}

void ping_timeout_remove(Client *c)
{
	if (c->ping_timeout_id != 0)
		g_source_remove(c->ping_timeout_id);
	c->ping_moribund = False;
	
	if (button_cursors)
		XDefineCursor(dpy, c->buttons[CLOSE_BUTTON], button_cursor[CLOSE_BUTTON]);
	else
		XUndefineCursor(dpy, c->buttons[CLOSE_BUTTON]);
}


void net_wm_ping(Client * c, Time timestamp)
{
	if (timestamp == CurrentTime)
	{
		g_warning("Tried to ping a window with CurrentTime! Not allowed.");
		return;
	}

	c->ping_time = timestamp;
	c->ping_timeout_id = g_timeout_add(PING_TIMEOUT_DELAY, ping_timeout, c);

	dbg("Sending ping with timestamp %lu to window %s\n", timestamp, c->class.res_name);
		
	send_icccm_message(c->window, intern_atoms[NET_WM_PING], timestamp);
}



/* process the pong from our ping */
void process_pong_message(XEvent * event)
{
	GList *l;

	dbg("Received a pong with timestamp %lu\n", (Time) event->xclient.data.l[1]);

	for (l = clients; l != NULL; l = l->next)
	{
		Client *c = (Client *) l->data;
	
		if ((Time) event->xclient.data.l[1] == c->ping_time)
		{
			dbg("Matching ping found for pong %lu\n", c->ping_time);

			ping_timeout_remove(c);
			break;
		}
	}
}


