from Tkinter import *
import tkFileDialog
import threading

global NCLine 

NCLine = 1

def sendstring():
    history.insert(END, e.get()+'\n')
    limitHistory()

def loadNCfile():
    fname = tkFileDialog.askopenfilename(filetypes=(("NC files", "*.nc"),("All files", "*.*") ))
    if fname:
       try:
          with open(fname) as f:
	    NCfile.delete(1.0, END)
	    NCfile.insert(END, f.read())
	    f.close()
	    
       except:                     # <- naked except is a bad idea
          showerror("Open Source File", "Something went wrong, I don't know what.\n'%s'" % fname)
       return

def limitHistory():
  count = int(history.index('end-1c').split('.')[0])
  if (count > 14):
    history.delete(1.0, 2.0)

def sendLine():
  global NCLine
  threading.Timer(2.0, sendLine).start()
  history.insert(END, NCfile.get( str(NCLine)+'.0', str(NCLine+1)+'.0').strip()+"\n")
  limitHistory()
  NCLine += 1



mainwin = Tk()
mainwin.title("Text Input")
mainwin.wm_iconbitmap('@icon.xbm') 

fo = Button(mainwin, text="Open", width=4, command=loadNCfile)
fo.grid(row=0, column=0, sticky=W)

start = Button(mainwin, text="Send", width=4, command=sendLine)
start.grid(row=0, column=0, sticky=E)

NCfile = Text(mainwin, width=50, height=15, wrap=NONE)
NCfile.grid(row=1,column=0, rowspan=2, columnspan=2, sticky=N+E+S+W)
NCfile.insert(END, "NC FILE GOES HERE.\n")

NCscroll = Scrollbar(mainwin, command=NCfile.yview, width=10)
NCfile['yscrollcommand'] = NCscroll.set
NCscroll.grid(row=1,column=1, rowspan=2, sticky=N+E+S)

history = Text(mainwin, width=50, height=15, foreground="#10FF10", background="#020202" )
history.grid(row=1,column=2, columnspan=2, sticky=N+E+S+W)
history.insert(END, "   -- MACHINE HISTORY. --\n")
history.bind("<Key>", lambda e: "break")

e = Entry(mainwin)
e.grid(row=2,column=2, sticky=E+W)
e.bind("<Return>",(lambda event: sendstring()))
e.focus_set()

b = Button(mainwin, text="Send", width=4, command=sendstring).grid(row=2, column=3)

mainloop()
