#!/usr/bin/perl

################################################################################
#
# focus_watch -- by greenfly <greenfly@greenfly.org>
# 
# this script takes the name of a window as an argument 
# (eesh -ewait 'window_list' will show all the window names)
# and watches that window for focus.  When it has focus it is unshaded, and when
# it is unfocused it shades the window again
#
################################################################################

use Time::HiRes qw(usleep);	# lets us sleep in microseconds

use strict;

my $window_id;
my $focus;
my $shade;
my $window_name = shift;
my $sleep = 100000;	# number of microseconds to sleep


# find the window matching $window_name and grab the window_id
open WINDOWLIST, "eesh -ewait 'window_list'|";

while(<WINDOWLIST>)
{
   if(/(\w+).:.$window_name/)
   {
      $window_id = $1;
   }
}
close WINDOWLIST;

# now watch for this window to get focus
while(1)
{
   open FOCUS, "eesh -ewait \"win_op $window_id focus ?\"|";
   $focus = <FOCUS>;
   close FOCUS;

   open SHADE, "eesh -ewait \"win_op $window_id shade ?\" |";
   $shade = <SHADE>;
   close SHADE;

   chomp($focus);
   chomp($shade);

# if it's focused and shaded, unshade it
   if(($focus eq "focused: yes") && ($shade eq "window shaded: yes"))
   {
      system("eesh -e \"win_op $window_id shade\"");
   }
# if it's unfocused and unshaded, shade it
   elsif(($focus eq "focused: no") && ($shade eq "window shaded: no"))
   {
      system("eesh -e \"win_op $window_id shade\"");
   }
# die if the window can't be found
   elsif($focus eq "Error: no such window:  $window_id")
   {
      die "Can't find window $focus\n";
   }

   usleep($sleep);
}
      
