#!/usr/bin/perl

#   Display a slide show on the root window (to be used with xscreensaver)
#
# Note: chbg (http://chbg.sourceforge.net/) does a better job probably.
#
# Usage: slideshow -p imagedir -w wait
# See below for explanation of options.
#
# The images are displayed in random order.
# Each image is displayed only once.
#
# In order to save the 'find' every time this screensaver is started,
# it tries to write the list of images into imagedir.
# If that fails, it will try to write that list into /tmp.
# 
# How to make it run under KDE (as of KDE2):
#   Manually:
#     find the process named 'kdesktop' and kill it;
#     start xscreensaver-demo and close it again;
#     put the following line into your ~/.xscreensaver
#         "My Art Images Slide Show"  slideshow -p /raphael/art -w 30 \n\
#     under the section "programs:";
#     run xscreensaver-demo again and test it;
#     (maybe you have to start the demon under the File menu).
#   Automatically:
#     First, perform the above steps manually;
#     Create a file 'xscreensaver' in ~/.kde/Autostart/ with the following lines
#  		#!/bin/sh
#  		killall kdesktop
#  		xscreensaver
#     chmod a+x ~/.kde/Autostart/xscreensaver;
#
# Problem:
#   The currently displayed image is echo'd on stdout, 
#   but xscreensaver seems to do a newline every time, which makes the print
#   scroll off the screen after a while ...
#
# Prerequisites:
#   xv & perl.
#
# Gabriel Zachmann (gabriel.zachmann@gmx.net), June 2002.
#

require 'getopts.pl';

#use diagnostics;
use English;
use FileHandle;

Getopts('p:w:h');
if ( $opt_h )
{
	print "slideshow -p imagedir -w wait\n";
	print "  -p imagedir  root directory of all images\n";
	print "  -w wait      wait that many seconds until next image\n";
	print "  -h       this help\n";
	exit 0;
}

if ( ! $opt_p )
{
	print "slideshow: No image directory specified!\n";
	exit 1;
}
if ( ! $opt_w )
{
	$opt_w = 30;
}

$imagedir = $opt_p;
$wait = $opt_w;

unless ( open LIST, "$imagedir/imagelist" )
{
	chdir $imagedir;

	if ( -w "$imagedir" )
	{
		$listdir = ".";
	}
	else
	{
		$listdir = "/tmp";
	}

	`find . -type f -iname '*.jpg' -o -iname '*.png' -o \\
			-iname '*.tif' -o -iname '*.tiff' -o -iname '*.gif' | \\
			grep -v -e \\.small -e '/t-' > $listdir/imagelist`;
	# the 'grep' tries to filter out thumbnails

	unless ( open LIST, "$listdir/imagelist" )
	{
		die "slideshow: could not create image list $listdir/imagelist";
	}
}

@images = <LIST>;
$nimages = @images;

srand;

while ( $nimages )
{
	$i = int rand $nimages;

	if ( -z "$imagedir/$images[$i]" )
	{
		next;
	}

	print "$images[$i]";
	`xv -root -smooth -maxpect -quit -rmode 5 $imagedir/$images[$i] >/dev/null 2>/dev/null`;

	sleep $wait;

	$images[$i] = $images[$nimages-1];
	$nimages -= 1;
}

