#!/usr/bin/env python

"""
osd_acpi.py:

  hack to display xosd progress bar on an acpi-enabled linux machine.

  NOTE: by default uses battery 0.
        no support for more than one battery, but this should be easy to add.

  to use you'll need:

  xosd  - http://www.ignavus.net/software.html
  pyosd - http://repose.cx/pyosd/
"""

"""
Copyright (c) 2006, Weston Andros Adamson <dros@monkey.org>
All rights reserved.

Redistribution and use in source and binary forms, with or without 
modification, are permitted provided that the following conditions 
are met:

    * Redistributions of source code must retain the above copyright 
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright 
      notice, this list of conditions and the following disclaimer in 
      the documentation and/or other materials provided with the distribution.
    * Neither the name of monkey.org nor the names of its contributors 
      may be used to endorse or promote products derived from this software 
      without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
THE POSSIBILITY OF SUCH DAMAGE.
"""

import pyosd
import os
import time
import getopt
import sys

# simple print debugging
_DEBUG=False

# states
ACPI_STATE_UNKNOWN   = 0
ACPI_STATE_DISCHARGING = 1
ACPI_STATE_CHARGING  = 2

acpi_state2str = {
ACPI_STATE_UNKNOWN:    "<unknown>",
ACPI_STATE_DISCHARGING:  "discharging",
ACPI_STATE_CHARGING:   "charging",
}

def file2map(filepath):
    """very simple way to parse linux's /proc files describing batteries
       reads the file as <key>:<value> on each line, returns a dict
    """
    lines = file(filepath).readlines()

    rmap = {}

    for l in lines:
        s = l.split(':')
        key = s[0].strip()
        try:
            val = "".join([x.strip() for x in s[1:]])
        except:
            val = ''

        rmap[key] = val

    return rmap


class OsdAcpi(object):
    """mantains state and displays acpi staus via osd"""
    def __init__(self, path='/proc/acpi/battery/BAT0/', 
                       position='bottom',
                       align='left',
                       font='-misc-fixed-bold-*-*-*-*-130-*-*-*-*-*-*',
                       length=100):
        """set up stats and display object
        
           path     - path to battery directory.  
                      defaults to '/proc/acpi/battery/BAT0/'
                  
           position - 'top', 'bottom'
           align    - 'left', 'center', 'right'
           font     - unix font line
           length   - length of bar in chars
        """
        self.path = path
        self.info_path = os.path.join(path, 'info')
        self.state_path = os.path.join(path, 'state')
        self.state = ACPI_STATE_UNKNOWN
        self.charge = 0.0
        self.load()

        # set OSD defaults
        self.osd = pyosd.osd(lines=1)

        if position == 'top':
            self.osd.set_pos(pyosd.POS_TOP)
        elif position == 'bottom':
            self.osd.set_pos(pyosd.POS_BOT)
        else:
            raise Exception("Invalid position: %s" % (position))


        if align == 'left':
            self.osd.set_align(pyosd.ALIGN_LEFT)
        elif align == 'middle':
            self.osd.set_align(pyosd.ALIGN_CENTER)
        elif align == 'right':
            self.osd.set_align(pyosd.ALIGN_RIGHT)

        self.osd.set_font(font)
        self.osd.set_bar_length(long(length))

    def load(self):
        imap = file2map(self.info_path)
        smap = file2map(self.state_path)

        if (smap['charging state'] == 'charging' or
            smap['charging state'] == 'charged'):
            self.state = ACPI_STATE_CHARGING
        elif smap['charging state'] == 'discharging':
            self.state = ACPI_STATE_DISCHARGING
        else:
            raise Exception("cannot determine state for %s" % self.path)

        remain = float(smap['remaining capacity'].split(' ')[0])
        total = float(imap['last full capacity'].split(' ')[0])

        if total <= 0.0 or remain < 0.0 or remain > total:
            raise Exception("error parsing charge for %s" % self.path)

        self.charge = (remain / total)
        if _DEBUG:
            print "load - state:%s  charge:%s" % (acpi_state2str[self.state], self.charge)

    def show(self):
        if _DEBUG:
            print "display"
        if self.state == ACPI_STATE_CHARGING:
            self.osd.set_colour("#0000ff")
        elif self.state == ACPI_STATE_DISCHARGING:
            self.osd.set_colour("#ff0000")

        if _DEBUG:
            print "charge: %s" % self.charge

        pct = long(self.charge * 100.0) 

        if _DEBUG:
            print "pct: %s" % pct

        if pct < 0:
            pct = 0
        elif pct > 100:
            pct = 100

        self.osd.display(pct, type=pyosd.TYPE_SLIDER)

    def run(self, update, sleep):
        self.osd.set_timeout(long(sleep) + 1)
        sleepsper = float(update) / float(sleep)
        if sleepsper <= 0.0:
            sleepsper = 1
        else:
            sleepsper = long(sleepsper)

        while True:
            self.load()
            for i in range(sleepsper):
                self.show()
                if _DEBUG:
                    print "sleep %f" % sleep
                time.sleep(sleep)

def usage():
    sys.stderr.write("%s [options]\n" % sys.argv[0])
    sys.stderr.write("\t-d\tacpi battery directory\n")
    sys.stderr.write("\t-p\tposition, 'top' or 'bottom'\n")
    sys.stderr.write("\t-a\talign, 'left', 'center' or 'bottom'\n")
    sys.stderr.write("\t-f\tfont\n")
    sys.stderr.write("\t-l\tlength of bar\n")
    sys.exit(1)

if __name__ == '__main__':
    path='/proc/acpi/battery/BAT0/'
    position='bottom'
    align='left'
    font='-misc-fixed-bold-*-*-*-*-130-*-*-*-*-*-*'
    length=100

    try:
        opts, args = getopt.getopt(sys.argv[1:], "d:f:l:p:a:")

        for a, v in opts:
            if a == '-d':
                path = v
            elif a == '-f':
                font = v
            elif a == '-l':
                length = long(v)
            elif a == '-p':
                position = v
            elif a == '-a':
                align = v
            else:
                print "%s" % a
                raise
    except:
        usage()

    if args:
        print "ARGS = %s" % args
        usage()

    OsdAcpi(path=path, position=position, align=align, font=font, 
            length=length).run(5, 1)
