#!/usr/bin/env python
# ClipManip v.5
# added hnb insertion for -n (still makes a 'notes.txt'; hope to ditch that one)
# Sat Jul 21 14:15:21 PDT 2001  <pevans@catholic.org>

#######################################################
#                                                     #
# Requires xsel to grab the clipboard contents        #
# http://v.iki.fi/~vherva/xsel/ by Ville Herva        #
# Clipboard, in this case is the 'Primary Selection'  #
# i.e. whatever is presently highlighted by the mouse #
#                                                     #
#######################################################

# args are one of: sort -s, add -a, notes -n, or comment -c
# -s 'sorted' will sort the primary selection in place, just middle click to paste
# -a 'added' will attempt to do a sum of any numbers it finds. Any 'word' will be evaluated
#    and summed with other 'words'. e.g.: "2 mixed 2 text 2 so what 2*5 10/2" will put 21.0 in the clipboard.
#    with '----' above it. Multiple lines are fine too.
# -c 'commented' will make hash style comments from the current mouse selection as you see above.
# -n 'noted' will append a ~/notes.txt file with window title, date and clipboard contents
#     Now it also does an insert to hnb "Hierarchical Notebook" by yvind Kols



#from wxPython.wx import wxTheClipboard, wxTextDataObject #xsel is much lower overhead
from sys import argv
import string, os, sys

######################
# read the clipboard #
######################
#wxTheClipboard.UsePrimarySelection(1) # which clipbuffer to use: in the clipboard or the primary (selected text)
#wxTheClipboard.Open()
#data = wxTextDataObject();wxTheClipboard.GetData(data)
#contents = data.GetText()
#wxTheClipboard.Close()
f = os.popen('xsel -p', 'r')
contents = f.read()
f.close

def sorted(contents):
    contentslist = string.split(contents,'\n')
    contentslist.sort()
    contents = string.join(contentslist, '\n')

    f = os.popen('xsel -c', 'w')
    f.write(contents)
    f.close()

def added(contents):
    #sum the clipboard
    orig = contents
    contentslist = string.split(contents)
    sum = 0
    for i in contentslist:
        if string.find(i,'/') > 0 and string.find(i,'.') < 1:
            i = i + '.0' #force floating if division in i
        try:
            sum = sum + float(eval(i))
        except:
            continue
    contents = '============\n' + str(sum) + '\n'
    print contents
    f = os.popen('xsel -c', 'w')
    f.write(contents)
    f.close()

def get_title():
    # How to get the active window from the command line:
    # xwininfo -id $(xprop -root | grep '_NET_ACTIVE_WINDOW(WINDOW)' | cut -d ' ' -f 5) | grep wininfo | cut -d ' ' -f 5
    f = os.popen('xprop -root | grep _NET_ACTIVE_WINDOW\\(WINDOW\\)', 'r')
    winid = f.read().split().pop() #split into list of words and pop the last word
    f.close
    f = os.popen('xwininfo -id ' + winid +'| grep xwininfo', 'r')
    wintitle = f.read().split('"')[1] #split at " and take the second item
    f.close
    return wintitle

def noted(contents):
    #add clipboard to notes with date stamp and wininfo
    import getpass
    user = getpass.getuser()
    if user == 'root':
        HOMEDIR = '/root'
    else:
        HOMEDIR = '/home/' + user
    
    try:
        f = open(HOMEDIR + "/notes.txt", 'r')
        orig = f.read()
        f.close()
    except IOError:
        orig = ""

    import time
    #add timestamp to date title, so we have a unique one
    wintitle = get_title() + time.strftime('-%X',time.localtime(time.time() ) )
    stamp = time.strftime('%a-%d-%b-%Y-%X',time.localtime(time.time() ) )
    sep = '\n' +  '='*30 + '\n\n'
    outstr = wintitle + '\n' + stamp + contents + sep + orig
    f = open(HOMEDIR + "/notes.txt", 'w')
    f.write(outstr)
    f.close()

    # this one is just too much fun!
    # uses http://hnb.sourceforge.net/ hnb - hierarchical notebook
    # which is an excellent outliner
    wintitle = string.replace(wintitle, ' ', '_')
    wintitle = string.replace(wintitle, '/', '~')
    stamp = string.replace(stamp, ' ', '-')
    lines = string.split(string.expandtabs(contents, 8), '\n')

    i, o, e = os.popen3('hnb -ui cli')
    f = os.popen('grep -c OnlineNotes ' + HOMEDIR + '/.hnb')
    grepres = f.read(1)
    f.close()
    if grepres == '0':
        i.write('add OnlineNotes\n')

    i.write('addc OnlineNotes' + '\n')
    i.write('cd OnlineNotes\n')
    i.write('add ' + wintitle + '\n')

    i.write('addc ' + wintitle + '\n')
    i.write('cd ' + wintitle + '\n')

    lines.insert(0,stamp)
    for x in lines:
        i.write('add ' + x + '\n')
    i.write('save\n')
    i.write('quit\n')
    i.close()
    o.close()
    e.close()

def comment(contents):
    #Comment the clipboard with hash marks
    contentslist = string.split(contents,'\n')
    global longest #yes, I know about max() now, wrote this part early on..
    longest = 0
    for i in contentslist:
         if len(i) > longest:
             longest = len(i)
    x = '#'*(longest+4)
    x2 = '#' + ' '*(longest+2) + '#'
    newlist = map(padhash, contentslist)
    newlist.insert(0, x2) #leading blank. just delete if you don't like them.
    newlist.insert(0, x)
    newlist.append(x2)
    newlist.append(x)     #trailing blank. just delete if you don't like them.
    contents = string.join(newlist, '\n')
    f = os.popen('xsel -c', 'w')
    f.write(contents)
    f.close()

def padhash(line):
    global longest
    spaces = ' ' * (longest - len(line))
    padded = "%s%s%s%s" % ('# ', line, spaces, ' #')
    return(padded)

if argv[1] == '-s':
    sorted(contents)
elif argv[1] == '-a':
    added(contents)
elif argv[1] == '-n':
    noted(contents)
elif argv[1] == '-c':
    comment(contents)
else:
    pass

