#!/usr/bin/python
#eMonitor by Kranu
#modified by DarkTrick
#Version 2 (9-1-2011)

#Tested on Windows 7 x64, Python 2.7.2, wxPython 2.8
#For more information, see: h://goo.gl/rJoLp

#BEGIN SETUP

#HTTP Server
port=8080              #port of http server (http://127.0.0.1:8000/)

#capture region
#l,t=(1680,1050-800)
l,t=(10,120)              #left and right offset from primary monitor
#w,h=(595,701)          #width and height of capture region
w,h=(701,595)          #width and height of capture region

# "ss" = screenshot
ssX = l
ssY = t
ssWidth  = w
ssHeight = h

#fn ='shot.jpg'         #file name of screenshot
fn ='shot.png'         #file name of screenshot

#//END SETUP

import socket
# run with python2
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer

#run with python3
#from http.server import BaseHTTPRequestHandler, HTTPServer

import gtk.gdk
import time

def convertGetVarToArray ( url ):
  startPos = url.find("?") + 1

  # stop, if no vars
  if(startPos == 0):
    return {}

  vars_flat = url[startPos:]
  
  # stop, if empty
  if("" == vars_flat):
    return {}
  #else:  # debug
  #  print("OK ( " + vars_flat + ")")

  # split by "&"
  vars_assigns = vars_flat.split("&")

  associativeArray = {}
  for assignment in vars_assigns:
    key, value = "",""
    if( "=" in assignment ):
      key, value = assignment.split("=",1)
    else:
      key = assignment
    associativeArray[key] =  value

  return associativeArray

def test_convertGetVarToArray():
  convertGetVarToArray("/shot.png?a=1")     == {"a": "1"}
  convertGetVarToArray("/shot.png?a=1&b=2") == {"a": "1", "b": "2"}
  convertGetVarToArray("/shot.png")         == {}
  convertGetVarToArray("/shot.png?")        == {}
  convertGetVarToArray("/shot.png?a=")      == {"a": ""}
  convertGetVarToArray("//shot.png?a")      == {"a": ""}

# testing
#test_convertGetVarToArray()
#exit()

def gtkScreenshot (moveX = 0, moveY = 0):

  global ssX,ssY

  ssX += moveX * (ssWidth/2)  # 80
  ssY += moveY * (ssHeight/2) #40

  print ("x: " + str(ssX) + " y: " + str(ssY))

  w = gtk.gdk.get_default_root_window()
  #ssWidth,ssHeight = w.get_size()
  #print "The size of the window is %d x %d" % sz
  
  pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,ssWidth,ssHeight)
  pb = pb.get_from_drawable(w,w.get_colormap(),ssX,ssY,0,0,ssWidth,ssHeight)

  pb = pb.rotate_simple(90)

  #pb = gtk.gdk.pixbuf_get_from_window(window, ssX, ssY, ssWidth, ssHeight)

  ts = time.time()
  filename = fn

  if (pb != None):
      pb.save(filename,"png")
      #print "Screenshot saved to "+filename
  else:
      print("Unable to get the screenshot.")

class serv(BaseHTTPRequestHandler):

  def deliverSite (self):
    #print("deliverSite()")
    
    self.send_header('Content-type','text/html')
    self.end_headers()
    
    # reloadFunction = 'function() {'\
    #   '  document.getElementById("pic").src="'+fn+'?"+(new Date()).getTime();'\
    #   '}'
    
    # website = """
    #   <!doctype html>
    #   <html lang="en">
    #     <head>
    #       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    #       <title>eMonitor by Kranu</title>
    #     </head>
    #     <body id="bod" style="margin:0px;">
    #       <img id="pic" src='shot.png' >
    #       <script type="text/javascript">
    #           document.getElementById("pic").onclick="""+reloadFunction+"""
    #       </script>

    #     </body>
    #   </html>"""
  
    website = """
        
      <!doctype html>
      <html lang="en">
        <head>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <title>eMonitor by Kranu</title>
          <style>
            div{
              position:absolute;
              background-color: #00000000;
              }
          </style>
          <script type="text/javascript">
            function renew(additionalParams) {
              //alert('"""+fn+"""?' + additionalParams);
              //we need the time to make the browser really renew
              document.getElementById("pic").src='"""+fn+"""?' + (new Date()).getTime() + '&' +additionalParams;
            }
            function moveVisibleArea(x,y){
                renew("movex=" + x + "&movey=" + y);
            }
          </script>
        </head>
        <body id="bod" style="margin:0px;">
          <!-- up -->
          <div onclick="javascript:moveVisibleArea(0,-1);" style="width:20%;height:80%;"></div>
          <!-- down -->
          <div onclick="javascript:moveVisibleArea(0, 1);" style="width:20%;height:80%;left:80%;"></div>
          <!-- right -->
          <div onclick="javascript:moveVisibleArea( 1,0);" style="width:100%;height:20%;top:0px;"></div>
          <!-- left -->
          <div onclick="javascript:moveVisibleArea(-1,0);" style="width:100%;height:20%;top:80%;"></div>
          
          <img id="pic" src='"""+fn+"""' onclick='javascript:renew("")'  />

        </body>
      </html>
    """
    with open("debug_website.html","w") as file:
      file.write(website)
      
    self.wfile.write(website)

  def updateImage (self):    

      #get all variables
      vars = convertGetVarToArray(self.path)
      moveX = 0
      moveY = 0
      if( "movex" in vars ):
        moveX = int(vars["movex"])
      if( "movey" in vars ):
        moveY = int(vars["movey"])

      print("deliverImage()")
        
      self.send_header('Content-type','image/jpeg')
      self.end_headers()
  
      gtkScreenshot(moveX,moveY)

      with open(fn,'rb') as f:
          self.wfile.write(f.read())

  def do_GET (self):
    self.send_response(200)

    #check, if the request was about the image
    if self.path.startswith('/'+fn): 
      self.updateImage()  
    else:
      self.deliverSite()
      
try: 
  print( 'eMonitor by Kranu')

  #Amazon's website is used here for its reliablity. Feel free to change it.
  s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  s.connect(("amazon.com",80))

  print ('Starting.. ')
  server=HTTPServer(('',port),serv)
  print ('Press Ctrl+C to stop')
  print ("")

  print ('On your Kindle, visit http://'+s.getsockname()[0]+':'+str(port)+'/')
  
  # take initial screenshot
  gtkScreenshot()
    
    
  server.serve_forever()
except KeyboardInterrupt:
  print ('Stopping.. '),
  server.socket.close()