#!/usr/bin/env /usr/bin/pythonw

# pythonw -c 'import gensuitemodule; gensuitemodule.main()' --output Safari /Applications/Safari.app

import time
import Safari
import aetools                          # for aetools.Error trapping
import MacOS				# for MacOS.Error trapping

# icon support
import AppKit
app = AppKit.NSApplication.sharedApplication()
ipath = __file__.replace(".py","") + ".icns"
img = AppKit.NSImage.alloc().initWithContentsOfFile_(ipath)
if img:
    app.setApplicationIconImage_(img)
# end icon support

s = Safari.Safari()

items = Safari.items(1)

knowndocs = {}

slog = open("safari_log", "a")
print >> slog, "*", time.time()

lostdocs = {}
while 1:
    try:
        ndocs = s.count(items, each=Safari.document)
    except MacOS.Error, e:
        if e[0] == -1712:
            print "timeout, retrying"
            time.sleep(10)
            continue
        raise
    nowdocs = {}
    newdocs = []
    # we sometimes lose one doc, temporarily
    # it isn't just a scan, it may be due to new windows at just the
    # right time, kicking something off the end?
    t_scan_start = time.time()
    for docnum in range(ndocs):
        try:
            url = s.get(Safari.documents(docnum+1).URL)
        except aetools.Error, e:
            print "oops:", e
            continue
        except MacOS.Error, e:
            if e[0] == -1712:
                print "timeout, retrying"
                continue
            print "oops", e
            continue
        if url not in knowndocs:
            # appeared
            newdocs.append(url)
            knowndocs[url] = 1
        nowdocs[url] = 1
    t_scan = time.time() - t_scan_start
    for url in knowndocs.keys():
        if url not in nowdocs:
            if url in lostdocs:
                print >> slog, "-", time.time(), url
                del knowndocs[url]
                del lostdocs[url]
            else: # not visible, but only just lost:
                lostdocs[url] = 1
        elif url in lostdocs: # visible but we though we lost it:
            del lostdocs[url] # "nevermind"
    # do newdocs after purge, looks cleaner for the url-jump case
    # though the addition of the lostdocs case kind of breaks this...
    for url in newdocs:
        print >> slog, "+", time.time(), url
    slog.flush()
    # print t_scan
    time.sleep((7+t_scan)/2)


# s.do_JavaScript("getSelection()", in_=Safari.documents(1))

## - 1084845111.0 http://www.sdss.org/iotw/iotw.html
## Traceback (most recent call last):
##   File "./monitor_safari.py", line 22, in ?
##     ndocs = s.count(items, each=Safari.document)
##   File "/Users/eichin/thok/intranet/python/mac/Safari/Standard_Suite.py", line 64, in count
##     raise aetools.Error, aetools.decodeerror(_arguments)
## aetools.Error: (-1708, 'the AppleEvent was not handled by any handler', None)
##     69884.55 real      1824.98 user       130.13 sys
## 
##  -- this was from scanning with a quicktime save-menu up, I think...