#!/usr/bin/env python
import time, win32gui

'''
Monitor how much time you spend on each application.
Works only on Windows.

License: http://www.opensource.org/licenses/bsd-license.php
URL: http://www.swaroopch.info/archives/2007/04/10/big-brother/
'''


total_counter = 0
counter = {}
_tick = 5 # Note which app is running, every `_tick` seconds
_refresh = 30 # Write out the file, every `_refresh` seconds

def title_to_application(title):
    '''If the title name is something like 'Adobe Flex - Mozilla Firefox',
    then we need only the part after the last dash.'''

## Enable this if you want to track all DOS windows as one application,
## all cygwin windows as one application, etc.
#     apps = ['cmd.exe', 'cygdrive']
#     for a in apps:
#         if title.find(a) > -1:
#             return a

    return title.split('-')[-1].strip()

def write_times_to_file(counter):
    '''Write the time spent on each application to a file.'''
    f = open('BigBrotherSays.txt', 'w')
    output = ','.join(['%s=%s' % (app, counter[app]) for app in counter.keys()])
    f.write(output)
    f.close()


while True:
    time.sleep(_tick)
    app = title_to_application(win32gui.GetWindowText(win32gui.GetForegroundWindow()))
    if app not in counter:
        counter[app] = 0
    counter[app] += _tick
    total_counter += 1
    if total_counter % (_refresh/_tick) == 0:
        write_times_to_file(counter)
        print counter # debug, remove if distracting


