/* xidle.c
 * Grab XScreenSaver Extension Idle information
 * Idea ripped from GAIM
 * by Spirilis
 * + output modifications by f0rked
 * 2005-04-26, 2006-11-09
 *
 * Distributed under the terms of the GNU General Public License version 2 or later:
 * (original GAIM copyright notice follows)
 * Gaim is the legal property of its developers, whose names are too numerous
 * to list here.  Please refer to the COPYRIGHT file distributed with this
 * source distribution.
 *
 * 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 of the License, 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

 */

/* NOTE
 * Compile using: gcc -o xidle xidle.c `gtk-config --cflags` `gtk-config --libs` -lXss
 */
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/scrnsaver.h>
#include <gdk/gdkx.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    static XScreenSaverInfo *mit_info = NULL;
    int event_base, error_base;
    float seconds;

    char *dpyvar = getenv("DISPLAY");
    if (dpyvar == NULL) {
        fprintf(stderr,"Error: No display\n");
        exit(1);
    }

    /* Redirect stdout temporarily so any errors created by gtk_init()
       will not affect our program output */
    FILE *old_stdout = stdout;
    if ((stdout = fopen("/dev/null","w")) == NULL) {
        fprintf(stderr,"Failed to redirect stdout temporarily\n");
        exit(1);
    }
    gtk_init(&argc, &argv);
    fclose(stdout);
    stdout = old_stdout;

    if (XScreenSaverQueryExtension(GDK_DISPLAY(), &event_base, &error_base)) {
        if (mit_info == NULL) {
            mit_info = XScreenSaverAllocInfo();
        }
        XScreenSaverQueryInfo(GDK_DISPLAY(), GDK_ROOT_WINDOW(), mit_info);
        
        seconds = (float)mit_info->idle/1000;
        printf("%f\n",seconds);
        exit(0);
    } 
    else {
        fprintf(stderr,"Error: XScreenSaver Extension not present\n");
        exit(1);
    }
}
