import gtk, sys, random, shutil, os, time
from dogtail.tree import root

pdf = sys.argv[1]
# copy pdf to /tmp
pdfcopyname = "pdf.%s.pdf" % random.random()
pdfcopy = "/tmp/" + pdfcopyname
shutil.copy(pdf, pdfcopy)

# start two evinces
os.system("evince --presentation --page-label=1 %s &" % pdf)
os.system("evince %s &" % pdfcopy)

# find them with dogtail
time.sleep(2)
from dogtail.tree import root
evince = root.application("evince")
pdfw = evince.window(os.path.split(pdf)[1])
pdfcopyw = evince.window(pdfcopyname)
halfpages = int(pdfw.child(roleName="tool bar").child(roleName="label").text.split()[1]) / 2
pdfpageel = pdfw.child(roleName="tool bar").child(roleName="text")
pdfcopypageel = pdfcopyw.child(roleName="tool bar").child(roleName="text")

def ping():
  global pdfw, pdfcopyw, halfpages, pdfpageel, pdfcopypageel
  try:
    pdfpage = int(pdfpageel.text)
    pdfcopypage = int(pdfcopypageel.text)
  except ValueError:
    # pdf window has been destroyed, probably
    raise "die"
  if (pdfpage + halfpages) != pdfcopypage:
    pdfcopypage = pdfpage + halfpages
    pdfcopypageel.text = str(pdfcopypage)
    pdfcopypageel.doAction("activate")
  
  return True
  

pingobj = gtk.timeout_add(500, ping)
try:
  gtk.main()
except:
  os.unlink(pdfcopy)


