#!/usr/bin/env python
# -*- coding: utf-8 -*-

#================================================
#
#    daemon_wallpapoz.py - Wallpapoz 
#    Copyright (C) 2005 Akbar <akbarhome@gmail.com>
#
#================================================
#
#    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
#
#================================================

## daemon_wallpapoz.py
#
# This file will check desktop continously and change wallpaper 
# with preferences from configuration file

import sys
sys.path.insert(0, '/usr/share/wallpapoz')
from xml_processing import XMLProcessing
import os
import array
import time
import threading
import random

## number -- global variable
#
# this is index of wallpaper list of workspaces
# for example: number[0] is index of wallpaper list in first workspace
number = array.array('i')

## delay -- global variable, how many time will wallpaper list thread
#
# has to wait before it manipulate its index
delay = 1.0

## random -- global variable, is wallpaper list thread randomize its index
randomvar = 0

## System -- class for knowing current desktop and change wallpaper
#
# with calling external program
class System:
    ## class method to know what workspace we are in now
    def current_desktop(self):
	desktop = os.popen('xprop -root _NET_CURRENT_DESKTOP').read()
	return int(desktop[33] + desktop[34])

    ## class method
    def change_wallpaper(self, wallpaper):
	os.system('gconftool-2 -t string -s /desktop/gnome/background/picture_filename ' + "\"" + wallpaper + "\"")

## AsyncIndex -- class for making thread that manipulating index wallpaper list
class AsyncIndex(threading.Thread):
    ## constructor
    def __init__(self, index):
	threading.Thread.__init__(self)
	self.index = index

    ## the function that thread will execute
    def run(self):
	if randomvar == 1:
	    number[self.index] = 0
	    size = len(worklist[self.index])
	    while True:
		number[self.index] = int(random.random() * size)
		time.sleep(delay)
	else:
	    while True:
		number[self.index] = 0
		for i in worklist[self.index]:
		    time.sleep(delay)
		    number[self.index] = number[self.index] + 1

## the main program
if __name__ == "__main__":

    # generate seed for random number
    random.seed()

    # the configuration file
    file = os.environ['HOME'] + "/.wallpapoz/wallpapoz.xml"

    # call the xmlprocessing class to read it
    wallpapozxml = XMLProcessing(file)

    # fill the workspace list
    worklist = wallpapozxml.fill_list()
    
    # cleansing
    for iter in worklist:
	iter.pop(0)

    # how many workspace we use
    total_workspace = wallpapozxml.get_workspace_num()

    # create the index for wallpaper list thread
    number.fromlist( range( total_workspace ) )

    # create the system class ( to change wallpaper and read current desktop )
    # by calling external program
    system = System()

    # previous workspace
    previous_desktop = -1

    # previous wallpaper list index
    previous_index = -1

    # get the delay time and random preferences
    delay = 60 * float(wallpapozxml.delay())
    randomvar = int(wallpapozxml.is_random())

    # create the thread
    wallpaper_list = []
    for i in range(total_workspace):
	wallpaper_list.append(AsyncIndex(i))
	wallpaper_list[i].start()

    # the daemon that works forever
    while True:
	try:
	    # don't get rush
	    time.sleep(1)

	    # what workspace we are in now?
	    cur_desk = system.current_desktop()

	    # requirement for changing wallpaper
	    # 1. we change workspace
	    # 2. index of wallpaper list change
	    if previous_desktop != cur_desk or previous_index != number[cur_desk]:
		# if we move to workspace that we don't use, just ignore
		if cur_desk >= total_workspace:
		    continue

		# command to change wallpaper
		system.change_wallpaper(worklist[cur_desk][number[cur_desk]])

		# our previous workspace and index of wallpaper list
		previous_desktop = cur_desk
		previous_index = number[cur_desk]

	# ok, we stop this daemon
	except KeyboardInterrupt:
	    # now it's time for the main thread to exit
	    os._exit(0)
