#!/usr/bin/python

# simple python utility to enable next available display with aticonfig
# this is for people using fglrx and docking/undocking laptops
# bind this to some hotkey (I use alt-f5 and the instructions at
# http://www.captain.at/howto-gnome-custom-hotkey-keyboard-shortcut.php )

# 2007, Charl P. Botha - http://cpbotha.net/

import os

# we need the DISPLAY=:0 (or somesuch); if xgl is running, we have a new
# display over the original one, aticonfig needs to know about this.
ATICONFIG_CMD = "DISPLAY=:0 aticonfig"

# first find out which are the connected and enabled monitors
######################################################################

put,get = os.popen4("%s --query-monitor" % (ATICONFIG_CMD,))

connected = []
enabled = []
for l in get.readlines():
    if l.find('Connected') >= 0:
        connected = l.split(':')[1].split(',')
        connected = [i.strip() for i in connected]

    elif l.find('Enabled') >= 0:
        enabled = l.split(':')[1].split(',')
        enabled = [i.strip() for i in enabled]
        
put.close()
get.close()

# then select the NEXT available display and activate it
######################################################################

if len(connected) == 1:
    # only one connected monitor, enable it.
    os.system('%s --enable-monitor=%s' % (ATICONFIG_CMD, connected[0]))

else:
    # choose NEXT monitor in connected list
    print connected
    print enabled
    new_idx = connected.index(enabled[0]) + 1
    if new_idx >= len(connected):
        new_idx = 0

    os.system('%s --enable-monitor=%s' % (ATICONFIG_CMD, connected[new_idx]))
    
