#!/usr/bin/python2
# -*- coding: utf-8 -*-

__author__ = "James Meyer"
__date__   = "August 23rd 2012"


from subprocess import Popen, PIPE
import re

class available_display_res():
    def __init__(self):

        self.mode_list=[]
        self.videocard = self.find_video_card()

        if self.videocard == "nvidia":
            self.parse_modeline_nvidia()
        else:
            self.sizes_xrandr()
        #elif self.videocard == "intel":
            #self.sizes_xrandr()
        #elif self.videocard == "vmware":
            #self.sizes_xrandr()
        #elif self.videocard == "vesa":
            #self.sizes_parse_log()


    def getlist(self):
        return self.mode_list

    def getvc(self):
        return self.videocard

    def find_video_card(self):
        videocard=""
        conf_file="/etc/X11/xorg.conf.d/20-automv.conf"
        lines=[]
        try:
            f=open(conf_file,'r')
            lines=f.readlines()
            f.close()
        except:
            print "    find_video_card: couldn't read in %s" %conf_file
            videocard = "unknown"

        for line in lines:
            parsed=line.split()
            if parsed[0].strip() == "Driver":
                videocard = parsed[1].strip('''"''')
                break

        return  videocard

    def parse_modeline_nvidia(self):
        self.mode_list=[]
        conf_file="/var/log/Xorg.0.log"
        lines=[]
        try:
            f=open(conf_file,'r')
            lines=f.readlines()
            f.close()
        except:
            print "    parse_modeline_nvidia: couldn't read in %s" %conf_file
            self.mode_list=["Auto"]
        #now parse the list looking for modelines
        search="Modes in ModePool"
        searchindex=[]
        for line in lines:
            if line.find(search) > 4 :
                searchindex.append(lines.index(line))
                search="End of ModePool"

            if len(searchindex) == 2:
                break
        #extract the modelines
        #[    29.858] (II) NVIDIA(GPU-0): "nvidia-auto-select" : 2560 x 1600 @  59.9 Hz  (from: EDID)
        try:
            modelines =  lines[searchindex[0]+1:searchindex[1]-1]
            for i in modelines:
                self.mode_list.append(i.split('''"''')[1])
        except:
            self.mode_list=["nvidia-auto-select"]


    def sizes_parse_log(self):
        self.mode_list=["parse_log_list"]

    def sizes_xrandr(self):
        """List all sizes detected by xrandr,
        ordered by the next resolution to cycle to"""
        size_re = re.compile("^   ([0-9]*x[0-9]*)\W*[0-9]*\.[0-9]*(\*)?")
        p1 = Popen(['xrandr'], stdout=PIPE)
        sizes = []
        current_size_index = 0
        for line in  p1.communicate()[0].split("\n"):
            m = size_re.match(line)
            if m:
                sizes.append(m.group(1))
                if m.group(2) == "*":
                    current_size_index = len(sizes) - 1
        #return sizes[current_size_index+1:] + sizes[:current_size_index+1]
        self.mode_list = sizes[current_size_index+1:] + sizes[:current_size_index+1]

def go():
    mode = available_display_res()
    vc = mode.getvc()
    modelist = mode.getlist()
    print vc

    for i in modelist:
        print i
    conf_file="/tmp/modelines"
    try:
        f=open(conf_file,'w')
        for i in modelist:
            f.write(i)
            f.write("\n")
        f.close()
    except:
        print "    print_xorg_res: couldn't write modelines to  %s" %conf_file




if __name__ == '__main__':
    go()

