#!/usr/bin/env /home/beams/BCDA/bin/python
import tkFileDialog
import sys
import os
import string
from Tkinter import *

user = os.getenv("USER")

pv1 = user + ':scan1'
pv2 = user + ':scan2'
editor = "/usr/dt/bin/dtpad -v "         # set default viewer/editor

class ascii:

    def badfile(self,fname):
	t1 = Toplevel(root)
	t1.title('File Error')
	for st in ["","Error: Bad file picked!!","",fname]:
		Label(t1,text=st).pack(anchor=W,padx=10)
        Button(t1,text='Close',command=t1.destroy).pack(pady=10)
		

    def help(self):
	t1 = Toplevel(root)
	t1.title('Help on Yviewer')
	for st in ["                **  Help on yviewer/asciiRpt  **",
		"",
		"This python tk program allows the user to view any scanSee/catcher",
		"data file through using the application written in extended yorick",
		"program yca. (Yorick is a unlicensed efficient interpreter graphic language.)",
		"It also allows the user flexiblely to generate ascii report for any",
		"scanSee/catcher file.",
		"File Menu:",
		"      Viewer...  - to access the scanSee/catcher visual dialog",
		"                   if any of scanSee or catcher 1D/2D file picked.",  
		"      Yca...    - to access the interpreter yca, yca term is normally",
		"                  terminated by the 'quit' command.",
		"      Quit       - to stop this program",
		"CatcherScan Menu:",
		"      Setup...     - set the scan1 and scan2 database scan record name",
		"      Save New...  - start catcher_scanDialog with new file name",
		"      Append Old...- start catcher_scanDialog with old catcher file name",
		"      Abort 1D     - abort the 1D scan",
		"      Abort 2D     - abort the 2D scan",
		"AsciiReport Menu:",
		"      Generate Report...  - access the ascii report generation functions",
		"      View Report...      - view an ascii report / text file ",
		"ReportSetup Menu:",
		"      Reset        - to clear the text fields",
		"      Default Seq# - to set default text fields based on FileType setting",
		"RadioButtons:",
		"      scanSee, catcher1D, catcher2D  - to specify report Filetype",
		'      By default all 1D and 2D image file will be generated for catcher file',
		"Text Fields",
		"      seq1       - specify start report seq",
		"      seq2       - specify end report seq",
		"      2D Scan #  - specify catcher 2D scanno",
		"Help Menu",
		"      Help        - display this help page",
		"      CatcherScan - explain the catcher scan function",
		"      Reset       - explain the text fields reset",
		"      Default seq# - default text fields setting" ]:
		Label(t1,text=st).pack(anchor=W,padx=10)
        Button(t1,text='Close',command=t1.destroy).pack(pady=10)

    def helpscan(self):
	t1 = Toplevel(root)
	t1.title('Help on CatcherScan')
	for st in ["                **  Help on CatcherScan Menu **",
		" ",
		"This menu simulates catcher typed 1D/2D scan.  It ensures that",
		"the scan data is saved in catcher format and later on",
		"they can be used by the IDL viewer/catcher program.",
		"The 1D/2D scan MUST be started internally by the start1d/start2d",
		"buttons defined in the catcher_scanDialog of yca program.",
		"The 2D image filename is the 1D filename suffixed with \".image\".",
		"",
		"Setup...      - set the scan1 and scan2 database scan record name",
		"Save New...   - create/overwrite the 1D scan file",
		"Append Old... - append the 1D/2D scan data to selected file",
		"Abort 1D      - abort the 1D scan",
		"Abort 2D      - abort the 2D scan",
	]:
		Label(t1,text=st).pack(anchor=W,padx=10)
        Button(t1,text='Close',command=t1.destroy).pack(pady=10)
		

    def helpsetup(self):
	t1 = Toplevel(root)
	t1.title('Help on Reset')
	for st in ["                **  Help on Reset  **",
		" ",
		"Reset will wipe out all values in input fields seq1,seq2,2D Scan #.",
		"Fields seq1,seq2,and 2D Scan # control the automatical report generation:",
		"seq1  - start sequence # for report generation",
		"seq2  - end sequence # for report generation",
		"2D Scan # - 2D scan # defined in catcher image file",
		" ",
		"If MULTIPLE numbers entered in seq1 field, seq2 will be ignored, e.g",
		"1-5,16-18 entered in seq1, implies 1 to 5 and 16 to 18 are picked.",
		" ",
		"For scanSee file seq1,seq2 imply the 2D image seq range for a 2D/3D scan",
		"For catcher 1D file seq1,seq2 imply the start and end 1D scan #",
		"For catcher 2D image file seq1,seq2 imply the start and end image #"]:
		Label(t1,text=st).pack(anchor=W,padx=10)
        Button(t1,text='Close',command=t1.destroy).pack(pady=10)

    def helpseq(self):
	t1 = Toplevel(root)
	t1.title('Help on Default Seq#')
	for st in ["                **  Help on Default Seq #  **",
		" ",
		"This option automatically set the default values for seq1,seq2", 
		"based on the Report FileType selected.",
		" ",
		"For scanSee 2D/3D scan images, seq1 and seq2 fields represent the",
		"begin and end detector sequence number, seq2 can not exceed 85",
		" ",
		"For 1D catcher file, seq1 and seq2 represent the begin and end",
		"1D scan numbers",
		" ",
		"For 2D catcher image file, seq1 and seq2 represent the detector range",
		"the seq fields can not exceed 15",
		"For 2D catcher image file, if 2D Scan # is set, seq1,seq2 will be ignored"]:
		Label(t1,text=st).pack(anchor=W,padx=10)
        Button(t1,text='Close',command=t1.destroy).pack(pady=10)

    def picktype(self):
	self.type = var.get()
	if self.type == 1:
		self.filter = "*.mda"
	elif self.type == 3:
		self.filter = "*.image"
	else:
		 self.filter = "*"

    def cleardefault(self):
	pick1.set('')
	pick2.set('')
	scanno.set('')

    def setdefault(self):
	if self.type == 1:
		pick1.set(1)
		pick2.set(85)
	elif self.type == 3:
		pick1.set(1)
		pick2.set(15)
	else:
		pick1.set(1)
		pick2.set(1000)

    def openyca(self):
	  os.system("xterm -e yezca &")

    def openfile(self):
	fname = tkFileDialog.askopenfilename(initialdir=self.path,initialfile=self.filter)
	if fname != "":
	  os.system("yezca "+fname + " &")
  	  (path,file) = os.path.split(fname)
	  self.fname = fname
	  self.path = path
	  self.file = file

    def scanSetup(self):
	global pv1,pv2
	scanF = Toplevel(root)
	scanF.title("Setup Scan PVs")
	Label(scanF,text="PV scan1:").pack(side=TOP,padx=5)
	scan1 = StringVar()
	Entry(scanF,width=30,textvariable=scan1).pack(side=TOP)

	Label(scanF,text="PV scan2:").pack(side=TOP,padx=5)
	scan2 = StringVar()
	Entry(scanF,width=30,textvariable=scan2).pack(side=TOP)
	Button(scanF,text='Ok',command=scanF.destroy).pack(side=TOP)
	self.pv1 = scan1
	self.pv2 = scan2
	scan1.set(pv1)
	scan2.set(pv2)

# catcher create file
    def scanfileNew(self):
	global pv1,pv2
	if self.pv1 != "":
	  scan1 = self.pv1
	  scan2 = self.pv2
	  pv2 = scan2.get()
	  pv1 = scan1.get()
	  print pv1,pv2
	fname = tkFileDialog.SaveAs().show(initialdir=self.path)
	if fname != "":
	 if string.find(fname,".mda") == -1:
  	  (path,file) = os.path.split(fname)
	  fn = string.split(file,".image")
	  self.fname = fname
	  self.path = path
	  self.file = fn[0]
	  fname = os.path.join(path,fn[0])
	  print fname
	  print pv1,pv2
	  os.system("yezca catcher_scanDialog "+fname+","+pv1+" &")
	 else:
	  self.badfile(fname)

# catcher append file
    def scanfile(self):
	global pv1,pv2
	if self.pv1 != "":
	  scan1 = self.pv1
	  scan2 = self.pv2
	  pv2 = scan2.get()
	  pv1 = scan1.get()
	  print pv1,pv2
	fname = tkFileDialog.askopenfilename(initialdir=self.path,initialfile=self.file)
	if fname != "":
	 if string.find(fname,".mda") == -1:
  	  (path,file) = os.path.split(fname)
	  fn = string.split(file,".image")
	  self.fname = fname
	  self.path = path
	  self.file = fn[0]
	  fname = os.path.join(path,fn[0])
	  print fname
	  print pv1,pv2
	  os.system("yezca catcher_scanDialog "+fname+","+pv1+" &")
	 else:
	  self.badfile(fname)

# start scan
    def startscan2D(self):
	global pv1,pv2
	if self.pv2 != "":
	  scan2 = self.pv2
	  pv2 = scan2.get()
	  print pv1,pv2
	os.system("caput  "+pv2+".EXSC 1 &")

    def startscan1D(self):
	global pv1,pv2
	if self.pv1 != "":
	  scan1 = self.pv1
	  pv1 = scan1.get()
	  print pv1,pv2
	os.system("caput  "+pv1+".EXSC 1 &")

# pause/go scan
    def scanPause(self):
	global pv1,pv2
	if self.pv1 != "":
	  scan1 = self.pv1
	  pv1 = scan1.get()
	(owner,s1) = string.split(pv1,":")
	print "caput "+owner+":scanPause 1 &"
#	os.system("caput  "+owner+":scanPause 1 &")

    def scanGo(self):
	global pv1,pv2
	if self.pv1 != "":
	  scan1 = self.pv1
	  pv1 = scan1.get()
	(owner,s1) = string.split(pv1,":")
	print "caput "+owner+":scanPause 0 &"
#	os.system("caput  "+owner+":scanPause 1 &")

# abort scan
    def abortscan2D(self):
	global pv1,pv2
	os.system("caput  "+pv2+".EXSC 0 &")

    def abortscan1D(self):
	global pv1,pv2
	os.system("caput  "+pv1+".EXSC 0 &")

    def pickfile(self):
	sel1 = pick1.get()
	sel2 = pick2.get()
	scanno_2d = scanno.get()
	if sel1 == "" :
		return
	if sel2 == "" :
		pick2.set(sel1)
		sel2 = sel1
	ll = getlist(sel1)

	fname = tkFileDialog.askopenfilename(initialdir=self.path,initialfile=self.filter)
	if string.strip(fname) != "":
	    if self.type == 1 :
	      if len(ll) > 1:
		for ii in ll:
		  ki = str(ii)	
		  st = "yezca scanSee_report "+fname+",pick1="+ki+",pick2="+ki
		  print st
		  os.system(st)
	      else:
		if sel1 != '':
		  st = "yezca scanSee_report "+fname+",pick1="+sel1+",pick2="+sel2
		else:
		  st = "yezca scanSee_report "+fname
		print st
		os.system(st)
	    elif self.type == 2:
	      if len(ll) > 1:
		for ii in ll:
		  ki = str(ii)	
		  st = "yezca catcher_report1D "+fname+",pick1="+ki+",pick2="+ki
		  print st
		  os.system(st)
	      else:
		if sel1 != '':
		  st = "yezca catcher_report1D "+fname+",pick1="+sel1+",pick2="+sel2
		else:
		  st = "yezca catcher_report1D "+fname
		print st
		os.system(st)
	    else:
	      if len(ll) > 1:
		for ii in ll:
		  ki = str(ii)	
		  st = "yezca catcher_report2D "+fname+",pick1="+ki+",pick2="+ki
		  print st
		  os.system(st)
	      else:
		if scanno_2d != '':
		  st = "yezca catcher_report2D "+fname+",scanno_2d="+scanno_2d
		elif sel1 != '':
		  st = "yezca catcher_report2D "+fname+",pick1="+sel1+",pick2="+sel2
		else:
		  st = "yezca catcher_report2D "+fname
		print st
		os.system(st)

	(path,file) = os.path.split(fname)
	self.fname = fname
	self.path = path
	self.file = file

    def viewpickfile(self):
	fname = tkFileDialog.askopenfilename(initialdir="ASCII",initialfile="*txt*")
	if fname != "":
	  os.system(editor+fname + " &")

    def texteditpickfile(self):
	fname = tkFileDialog.askopenfilename(initialdir="ASCII",initialfile="*txt*")
	if fname != "":
	  os.system("textedit "+fname + " &")

    def __init__(self,path):
	self.pv1 = ''
	self.pv2 = ''
	self.path = path
	self.fname = ''
	self.file = ''
	self.type = 1
	self.filter = "*.mda"
# ['scanSee','catcher1D','catcher2D']

def getlist(st):
    word = string.split(st,",")
    LL = []
    num = 0
    for item in word:
	pos = string.find(item,"-")
	if pos >= 0:
	   L = rangelist(word[num])
	   ii = num
	   LL = LL + L
	else:
	   no = string.atoi(item)
	   LL.append(no)
	num = num +1
    return LL

def rangelist(s):
    wd = string.split(s,"-")
    wd1 = string.atoi(wd[0])
    wd2 = string.atoi(wd[1])
    L = []
    i = wd1
    while i <= wd2:
	L.append(i)
	i = i + 1
    return L

def makeFileMenu():
    FilBtn = Menubutton(mBar,text='File',underline=0)
    FilBtn.pack(side=LEFT,padx="2m")
    FilBtn.menu = Menu(FilBtn)
    FilBtn.menu.add_command(label='Open Viewer/scanSee...',underline=5,command=asciiRpt.openfile)
    FilBtn.menu.add_command(label='Open Yca...',underline=5,command=asciiRpt.openyca)
    FilBtn.menu.add('separator')
    FilBtn.menu.add_command(label='Quit',underline=0,command=FilBtn.quit)
    FilBtn['menu'] = FilBtn.menu
    return FilBtn

def makeScanMenu():
    ScanBtn = Menubutton(mBar,text='CatcherScan',underline=0)
    ScanBtn.pack(side=LEFT,padx="2m")
    ScanBtn.menu = Menu(ScanBtn)
    ScanBtn.menu.add_command(label='Setup...',underline=0,command=asciiRpt.scanSetup)
    ScanBtn.menu.add('separator')
    ScanBtn.menu.add_command(label='Save New...',underline=5,command=asciiRpt.scanfileNew)
    ScanBtn.menu.add_command(label='Append Old...',underline=0,command=asciiRpt.scanfile)
    ScanBtn.menu.add('separator')
    ScanBtn.menu.add_command(label='Abort 1D',underline=6,command=asciiRpt.abortscan1D)
    ScanBtn.menu.add_command(label='Abort 2D',underline=6,command=asciiRpt.abortscan2D)
    ScanBtn.menu.add('separator')
    ScanBtn.menu.add_command(label='Scan 1D',command=asciiRpt.startscan1D)
    ScanBtn.menu.add_command(label='Scan 2D',command=asciiRpt.startscan2D)
    ScanBtn.menu.add('separator')
    ScanBtn.menu.add_command(label='Scan Pause',command=asciiRpt.scanPause)
    ScanBtn.menu.add_command(label='Scan Go',command=asciiRpt.scanGo)
    ScanBtn['menu'] = ScanBtn.menu
    return ScanBtn

def makeReportMenu():
    RepBtn = Menubutton(mBar,text='AsciiReport',underline=0)
    RepBtn.pack(side=LEFT,padx="2m")
    RepBtn.menu = Menu(RepBtn)
    RepBtn.menu.add_command(label='Generate Report...',underline=0,command=asciiRpt.pickfile)
    RepBtn.menu.add('separator')
    RepBtn.menu.add_command(label='View Report...',underline=0,command=asciiRpt.viewpickfile)
    RepBtn.menu.add_command(label='TextEdit Report...',underline=0,command=asciiRpt.texteditpickfile)
    RepBtn['menu'] = RepBtn.menu
    return RepBtn

def makeSetupMenu():
    SetBtn = Menubutton(mBar,text='ReportSetup',underline=0)
    SetBtn.pack(side=LEFT,padx="2m")
    SetBtn.menu = Menu(SetBtn)
    SetBtn.menu.add_command(label='Reset',underline=0,command=asciiRpt.cleardefault)
    SetBtn.menu.add_command(label='Default Seq#',underline=0,command=asciiRpt.setdefault)
    SetBtn['menu'] = SetBtn.menu
    return SetBtn

def makeHelpMenu():
    HelpBtn = Menubutton(mBar,text='Help',underline=0)
    HelpBtn.pack(side=LEFT,padx="2m")
    HelpBtn.menu = Menu(HelpBtn)
    HelpBtn.menu.add_command(label='Help',underline=0,command=asciiRpt.help)
    HelpBtn.menu.add_command(label='CatcherScan',underline=0,command=asciiRpt.helpscan)
    HelpBtn.menu.add_command(label='Reset',underline=0,command=asciiRpt.helpsetup)
    HelpBtn.menu.add_command(label='Default Seq#',underline=0,command=asciiRpt.helpseq)
    HelpBtn['menu'] = HelpBtn.menu
    return HelpBtn

# main program here

path = os.getcwd()
try:
	f = open('yca.config','r')
	fname = f.readline()
	f.close()
	fname = string.strip(fname)
	(path,file) = os.path.split(fname)
except:
	print path

asciiRpt = ascii(path)
if os.path.exists("ASCII") == 0:
	os.system("mkdir ASCII")

root = Tk()
root.title('Yviewer: scanSee/catcher/asciiReporter')

mBar= Frame(root, relief=RAISED, borderwidth=2)
mBar.pack(fill=X)
FilBtn = makeFileMenu()
ScanBtn = makeScanMenu()
RptBtn = makeReportMenu()
SetBtn = makeSetupMenu()
HelpBtn = makeHelpMenu()
mBar.tk_menuBar(FilBtn,ScanBtn,RptBtn,SetBtn,HelpBtn)

Label(root,text='asciiReport parameters for scanSee/catcher').pack(pady=10)

row1 = Frame(root,borderwidth=2)
Label(row1,text='Report FileType:').pack(padx=10,anchor=W)
var = IntVar()
for text, value in [('scanSee',1), ('catcher1D',2),('catcher2D',3)]:
    Radiobutton(row1,text=text,value=value,variable=var,command=asciiRpt.picktype).pack(anchor=NW)
var.set(1)
row1.pack(side=LEFT,padx=5,pady=5)

row2 = Frame(root,borderwidth=2).pack(side=LEFT)
Label(row2,text="seq1:").pack(side=LEFT,padx=5)
pick1 = StringVar()
Entry(row2,width=24,textvariable=pick1).pack(side=LEFT)
pick1.set(1)

Label(row2,text="seq2:").pack(side=LEFT,padx=5)
pick2 = StringVar()
Entry(row2,width=4,textvariable=pick2).pack(side=LEFT)
pick2.set(1)

Label(row2,text="2D Scan #:").pack(side=LEFT,padx=5)
scanno = StringVar()
Entry(row2,width=4,textvariable=scanno).pack(side=LEFT)


root.mainloop()
