Exemplo n.º 1
0
class GUI(Frame):
    def __init__(self, master=None, app=None, title=''):

        self.engine = app

        Frame.__init__(self, master)
        self.master.title(title)
        self.grid()
        self.createWidgets()

    def createWidgets(self):

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)

        self.nextButton = Button(self, text="next", command=self.next)
        self.nextButton.grid(row=0, column=0, sticky=S)

        self.quitButton = Button(self, text="quit", command=self.quit)
        self.quitButton.grid(row=0, column=1, sticky=S)

        self.inWindow = Text()
        self.inWindow.grid(row=1, column=0, sticky=N + E + S + W)

        self.outWindow = ScrolledText()
        self.outWindow.grid(row=2, column=0, sticky=N + E + S + W)

    def next(self):
        if self.engine <> None:
            self.engine.next()
        else:
            self.clearInput()

    def quit(self):
        self.master.destroy()
        self.engine.quit()

    def write(self, s):
        write(s, outstream=None, widget=self.outWindow)

    def writeln(self, s):
        writeln(s, outstream=None, widget=self.outWindow)

    def get(self):
        return self.inWindow.get(1.0, END)

    def userMultiLineInput(self):
        return self.get()

    def clearOutput(self):
        self.outWindow.delete(1.0, END)

    def clearInput(self):
        self.inWindow.delete(1.0, END)

    def clearInput(self):
        self.inWindow.delete(1.0, END)
Exemplo n.º 2
0
class c_ScrolledTextBox:

    def __init__(self, parent, height, width, row, col):
        self.area = ScrolledText(parent, wrap ='word', 
                             width = width,
                             height = height, relief='raised')
        self.area.grid(row=row,column=col, padx=5, pady=5)   
        self.area.insert('insert', "Hello me")

    def Add_Text(self, text):    
        self.area.insert('insert', text)
Exemplo n.º 3
0
    def onCheckChanges(self):
        window = Toplevel(self.root)
        changes_window = ScrolledText(window,
                                      width=50,
                                      height=15,
                                      state="normal")
        changes_window.grid(row=0, column=0)

        # Clear, rewrite and show changes between opened and downloaded file
        changes_window.delete(1.0, "end")
        changes_window.insert(END, self.file_changes)
Exemplo n.º 4
0
def get_all_books():
	window = Toplevel()
	window.configure(bg='lightgrey')
	window.title("All Books From Library")
	window.resizable(0,0)
	window.geometry("680x400")

	dim.set_dimensions(window)
	cursor = mydb.get_all_books_from_db()
	global my_dict
	my_dict = {}
	for item in cursor:
		my_dict[item[0]] = [item[0],item[1],item[2],item[3],item[4],item[5],item[6]]
			
	print my_dict

	lbl1 = Label(window, text="Books List:", fg='black', font=("Helvetica", 16, "bold"))
	lbl2 = Label(window, text="Book Information:", fg='black', font=("Helvetica", 16,"bold"))
	lbl1.grid(row=0, column=0, sticky=W)
	lbl2.grid(row=0, column=1, sticky=W)

	frm = Frame(window)
	frm.grid(row=1, column=0, sticky=N+S)
	window.rowconfigure(1, weight=1)
	window.columnconfigure(1, weight=1)

	scrollbar = Scrollbar(frm, orient="vertical")
	scrollbar.pack(side=RIGHT, fill=Y)

	global bookList

	bookList = Listbox(frm, width=20, yscrollcommand=scrollbar.set, font=("Helvetica", 12), selectmode=SINGLE)
	bookList.pack(expand=True, fill=Y)
	scrollbar.config(command=bookList.yview)

	global bookInfo

	bookInfo = ScrolledText(window, height=20, wrap=WORD, font=("Helvetica", 12))
	bookInfo.grid(row=1, column=1, sticky=E+W+N)
	# scrollbar_1 = Scrollbar(bookInfo, orient="vertical")
	# scrollbar_1.pack(side=RIGHT, fill=Y)
	# bookInfo.config(yscrollcommand=scrollbar_1.set)
	# scrollbar_1.config(command=bookInfo.yview)

	for item in cursor:
		bookList.insert(END, item[0])

	bookList.bind('<<ListboxSelect>>',on_select)
	window.mainloop()
Exemplo n.º 5
0
class SigMsgBox:
    def __init__(self, parent, fnames):
        self.fnames = fnames
        self.parent = parent
        self.top = Toplevel(parent)
        self.result = None

        Label(self.top,
              text="Verify that the size of the signatures is as expected: "
              ).grid(row=0, columnspan=2)

        self.text = ScrolledText(self.top, bg='#D9D9D9', width=32, height=10)
        self.text.config(state=DISABLED)
        self.text.grid(row=1, columnspan=2)

        self.ok_b = Button(self.top, text="OK", command=self.ok)
        self.no_b = Button(self.top, text="No", command=self.cancel)

        self.ok_b.grid(row=2, column=0)
        self.no_b.grid(row=2, column=1)

        self.add_sigs()

    def ok(self):
        self.result = 1
        if self.parent is not None:
            self.parent.focus_set()
        self.destroy()

    def cancel(self):
        self.result = 0
        if self.parent is not None:
            self.parent.focus_set()
        self.destroy()

    def destroy(self):
        self.top.destroy()

    def add_sigs(self):
        self.text.config(state=NORMAL)
        for fname in self.fnames:
            name = os.path.splitext(os.path.split(fname)[1])[0]
            ct = str(map(lambda x: len(x), read_sig_file(fname)))
            self.text.insert(END, name + ' ' + ct + '\n')
        self.text.config(state=DISABLED)
Exemplo n.º 6
0
class Application(Frame):
	
	def __init__(self, master=None):
		Frame.__init__(self, master)
		self.pack()
		self.createWidgets()

	def getnew(self,event): 
	# When press ENTER, write diary to local file
	# and print out it in Text frame
	# and also clear the Entry box
		line = self.newlog.get()
		f = open('diary log.txt','a+')
		f.write('%s\n' % line)
		f.close()
		self.t.insert(END,"%s\n" %line)
		self.t.see(END)
		self.e.delete(0,END)

	def createWidgets(self):   
		self.newlog = StringVar(self) # define StringVar
		
		self.l = Label(self, text = "Input here: ") # Label Widget 提示输入
		self.l.grid(row = 0, column = 0, sticky = W)
		
		self.e = Entry(self, textvariable = self.newlog, width = 80) # Entry box 输入框
		self.e.bind("<Return>", self.getnew) # bind ENTER to function getnew
		self.e.grid(row = 0, column = 1, sticky = W)
		self.e.focus_set() # make the mouse focus on the entry box
		
		self.t = ScrolledText(self) # ScrolledText 打印出文档的框
		self.t.grid(columnspan = 2, sticky = W)
		f = open('diary log.txt','a+') 
		self.t.insert(END,f.read()) 
		self.t.see(END)
		
		self.b = Button(self, text="QUIT", fg="red", command=self.quit) # 退出的button
		self.b.grid(row = 2, column = 0, sticky = W)
Exemplo n.º 7
0
def Show_Configs():

    root = Tk()
    root.title("Configuration")
    root.geometry("700x500+100+100")

    s = Style()
    s.configure('Yellow.TFrame', background='yellow', borderwidth = 5, padding=15, relief='sunken')

    FrameA = Frame(width=450, height=200, style='Yellow.TFrame')
    FrameB = Frame(width=450, height=200)
    
    root.grid_rowconfigure(1, weight=1, pad=5)
    root.grid_columnconfigure(0, weight=1, pad=5)  

    FrameA.grid(row=0, sticky="ew")
    FrameB.grid(row=1, sticky="ew")  

    cfg_space = ScrolledText(FrameA,
                             wrap = 'word',
                             width =30,
                             height = 6,
                             bg = 'beige')
    cfg_space.grid(row=0, column=0, padx=5, pady=5)
    cfg_space.insert('insert', "pile of text \n more text")

    fix_space = ScrolledText(FrameA,
                             wrap = 'word',
                             width =30,
                             height = 6,
                             bg = 'beige')
    fix_space.grid(row=0, column=1)
    fix_space.insert('insert', "hello text \n more text")    

    clr_space = ScrolledText(FrameB,
                             wrap = 'word',
                             width =30,
                             height = 10,
                             bg = 'beige')
    clr_space.grid(row=0, column=0)
    clr_space.insert('insert', "bottom text \n more text")   
    clr_space.config(state='disabled')      

    seq_space = c_ScrolledTextBox(FrameA,6,30,1,0)
    seq_space.Add_Text("\nHello World")

    root.mainloop()
Exemplo n.º 8
0
class MainGui(Frame):

    def __init__(self, parent=None):
        Frame.__init__(self, parent)

        Label(self, text='Title:', justify=LEFT).grid(row=0, column=0, sticky=E)
        title_var = StringVar(self)
        title_var.set("Bring polynomes to standard form")
        title = Entry(self, textvariable=title_var, width=35)
        title.grid(row=0, column=1, sticky=W)

        Label(self, text='Count of tasks:', justify=LEFT).grid(row=1, column=0, sticky=E)
        count_var = StringVar(self)
        count_var.set("5")
        count = Spinbox(self, from_=0, to=10, textvariable=count_var, width=2)
        count.grid(row=1, column=1, sticky=W)

        Label(self, text='Count of summands in one task:', justify=LEFT).grid(row=2, column=0, sticky=E)
        sum_count_var = StringVar(self)
        sum_count_var.set("5")
        sum_cont = Spinbox(self, from_=0, to=10, textvariable=sum_count_var, width=2)
        sum_cont.grid(row=2, column=1, sticky=W)

        Label(self, text='Maximal degree:').grid(row=3, column=0, sticky=E)
        deg_var = StringVar(self)
        deg_var.set("5")
        deg = Spinbox(self, from_=0, to=10, textvariable=deg_var, width=2)
        deg.grid(row=3, column=1, sticky=W)

        Label(self, text='Coefficients dispersion:').grid(row=4, column=0, sticky=E)
        cof_var = StringVar(self)
        cof_var.set("5")
        cof = Spinbox(self, from_=0, to=10, textvariable=cof_var, width=2)
        cof.grid(row=4, column=1, sticky=W)

        open_files_flag = BooleanVar()
        flag = Checkbutton(self, text='Open files after closing', variable=open_files_flag)
        flag.grid(row=5, column=0, sticky=W)

        self.gui_console = ScrolledText(self, width=50, height=20)
        self.gui_console.grid(row=6, column=0, columnspan=2, sticky=W+E+N+S)

        self.menubar = Menu(self)

        file_menu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label='File', underline=0, menu=file_menu)
        file_menu.add_command(label='Compile', underline=6, command=(lambda: self.compile(self, open_files_flag.get(),
                                                                                          False
                                                                                          )
                                                                     ),
                              accelerator="Ctrl+C")
        file_menu.add_command(label='Compile and close', underline=1,
                              command=(lambda: self.compile(self,
                                                            open_files_flag.get(),
                                                            True
                                                            )
                                       ),
                              accelerator="Alt+Q")
        file_menu.add_command(label='Close', underline=0, command=(lambda: self.quit()), accelerator="Ctrl+Q")

        edit_menu = Menu(self.menubar, tearoff=0)
        self.menubar.add_cascade(label='Edit', underline=0, menu=edit_menu)
        edit_menu.add_command(label='Add', underline=0, command=(lambda: self.add(title.get(),
                                                                                  int(count.get()),
                                                                                  int(sum_cont.get()),
                                                                                  int(deg.get()),
                                                                                  int(cof.get())
                                                                                  )
                                                                 ),
                              accelerator="Ctrl+A")
        try:
            self.master.config(menu=self.menubar)
        except AttributeError:
            self.master.tk.call(self, "config", "-menu", self.menubar)

        self.bind_all("<Control-q>", self.quit_event)
        self.bind_all("<Alt-q>", self.compile_and_quit_event)
        self.bind_all("<Control-a>", self.add_event)
        self.bind_all("<Control-c>", self.compile_event)

    def add(self, title=None, count=10, sum_count=5, deg=4, cof=20):
        polygen_writer(title, count, sum_count, deg, cof)
        # self.gui_console.insert(INSERT, 'Added!\n')
        print 'Added print'

    @staticmethod
    def compile(self, open_files_flag=False, close_flag=False):
        print "gen_close | current direction: " + str(os.getcwd())
        ground_writer()
        problems.close()
        answers.close()
        print 'Files closed'
        status = generate_pdf(answers_filename, open_files_flag)
        if status == 0:
            self.gui_console.insert(INSERT, 'File ' + answers_filename + '.tex compiled successfully...\n')
        else:
            self.gui_console.insert(INSERT, 'Error occurred while compiling file ' + answers_filename + '.tex...\n')
        status = generate_pdf(problems_filename, open_files_flag)
        if status == 0:
            self.gui_console.insert(INSERT, 'File ' + problems_filename + '.tex compiled successfully...\n')
        else:
            self.gui_console.insert(INSERT, 'Error occurred while compiling file ' + problems_filename + '.tex...\n')
        if close_flag:
            self.quit()

    def add_event(self, event):
        self.add()

    def compile_event(self, event):
        self.compile(self)

    def compile_and_quit_event(self, event):
        self.compile(self)
        self.quit()

    def quit_event(self, event):
        self.quit()
Exemplo n.º 9
0
Arquivo: AES.py Projeto: outlaw6/AES
def getText():
    global tekst, textPad
    secret = '123456'
    cipher = AES.new(pad(secret))

    txt = textPad.get('1.0',Tkinter.END)
    encoded = EncodeAES(cipher, txt)
    
    textPad2.insert(Tkinter.INSERT, encoded)	
    pass


root = Tkinter.Tk()
root.geometry("1000x330+300+300")


textPad = ScrolledText(root, width=50, height=20, bg='grey')
textPad.grid(padx=15, pady=5, row=0, column=0)

textPad2 = ScrolledText(root, width=50, height=20, bg='grey')
textPad2.grid(padx=100, pady=5, row=0, column=4)

dugme = Tkinter.Button(root, text='Get Text', width=5, command=getText)
dugme.grid(padx=5, pady=5, row=0, column=2)


tekst = Tkinter.StringVar()
label1 = Tkinter.Label(root, textvariable=tekst)
label1.grid(row=0, column=3)
root.mainloop() 
Exemplo n.º 10
0
class Application (Frame):
    def __init__ (self,master) :
        # Initialize the Frame
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()
        #InPutFrame = Frame (master)
        #InPutFrame.grid(row = 0, column = 0, sticky = W+E+N+S)
        #ScanningFrame = Frame (master)
        #ScanningFrame.grid(row = 0, column = 4, sticky = W+E+N+S)

    def create_widgets(self) :
        # Create the Buttons , Labels , Picture Box , Text Box
        
       ##########Input Part###########

       #Create Label Input Part
        self.InputLabel = Label(self, text = "Input Part\n")
        self.InputLabel.grid(row = 1 , column = 2 , columnspan = 2 , sticky = W )
       
       ##Create Label Inter Number 
        self.InterNumberLabel= Label(self ,  text =" Inter Number : \n")
        self.InterNumberLabel.grid(row = 3 , column = 0 , columnspan = 2 , sticky = W )
       
       #Create Entry Box Inter Number
        self.InterNumberbox = Entry (self , width = 30 , font=("Helvetica Neue", 14))
        self.InterNumberbox.grid(row = 3 , column = 2 , sticky = W )
        
       ##Create Label Inter Arrival Date 
        self.InterArrivalDateLabel= Label(self ,  text =" Inter Arrival Date :\n")
        self.InterArrivalDateLabel.grid(row = 4, column = 0 , columnspan = 2 , sticky = W )
        
        #Create Entry Box Inter Arrival Date
        self.InterArrivalDateBox = Entry (self , width = 30 , font=("Helvetica Neue", 14))
        self.InterArrivalDateBox.grid(row = 4 , column = 2 , sticky = W )
        
        ##Create Label Inter Batch ID 
        self.InterBatchIDLabel= Label(self ,  text =" Inter Batch ID : \n")
        self.InterBatchIDLabel.grid(row = 5, column = 0 , columnspan = 2 , sticky = W )
        
        #Create Entry Box Inter Batch ID 
        self.InterBatchIDBox = Entry (self , width = 30 , font=("Helvetica Neue", 14))
        self.InterBatchIDBox.grid(row = 5 , column = 2 , sticky = W )
        
        ##Create Label Inter More Information
        self.InterMoreInformationLabel= Label(self ,  text =" Inter More Information : \n")
        self.InterMoreInformationLabel.grid(row = 6, column = 0 , columnspan = 2 , sticky = W )
        
        #Create ScrolledText Box Inter More Information
        self.InterMoreInformationBox = ScrolledText(self ,  width = 40, height = 10 , font = ("Helvetica Neue", 12) )
        self.InterMoreInformationBox.grid(row = 6 , column = 2 , sticky = W )
        
        #Create Image Box For QR Code ( Label )
        #self.ImageBoxForQRCode = PhotoImage (self)
        #self.ImageBoxForQRCode.grid(row = 6 , column = 1 , sticky = W )



        #Create QR Button
        self.QRButton = Button(self , height = 7)
        self.QRButton["text"] = "                             Create New QR Code                             "
        self.QRButton.grid(row = 8 , column = 2 , sticky = W )
        self.QRButton["command"] = self.CreateNewQR

        #Create Add to Database Button 
        self.AddToDatabaseButton = Button (self,height = 7)
        self.AddToDatabaseButton["text"] = "                                Add to Database                                 "
        self.AddToDatabaseButton.grid(row = 7 , column = 2 , sticky = W)
        self.AddToDatabaseButton["command"] = self.AddToDatabase
        
        
         ########Scanning Part############

        #Create Label Scanning Part
        self.ScanningLabel = Label(self, text = "     Scanning Part\n")
        self.ScanningLabel.grid(row = 1 , column = 6 , columnspan = 2 , sticky = W )

        #Create Label QR Scann code 
        self.QRScannCodeLabel = Label (self , text = "     QR Scann Code : \n")
        self.QRScannCodeLabel.grid(row = 3 , column = 4 , columnspan = 2 , sticky = W)

        #Create Entry Box QR Scann code
        self.ScanBox = Entry (self , width = 30 , font=("Helvetica Neue", 14))
        self.ScanBox.grid(row = 3 , column = 6 , sticky = W )

        ##Create Label Arrival Date 
        self.ArrivalDateLabel= Label(self ,  text = "     Arrival Date : \n")
        self.ArrivalDateLabel.grid(row = 4, column = 4 , columnspan = 2 , sticky = W )

        #Create Text Box Arrival Date
        self.ArrivalDateBox = Text (self , width = 30,  height = 1 , font=("Helvetica Neue", 14))
        self.ArrivalDateBox.grid(row = 4 , column = 6 , sticky = W )
        
        ##Create Label Batch ID 
        self.BatchIDLabel= Label(self ,  text ="     Batch ID : \n")
        self.BatchIDLabel.grid(row = 5, column = 4 , columnspan = 2 , sticky = W )

        #Create Text Box Batch ID 
        self.BatchIDBox = Text (self , width = 30 ,height = 1, font = ("Helvetica Neue", 14))
        self.BatchIDBox.grid(row = 5 , column = 6 , sticky = W )
        
        ##Create Label More Information
        self.MoreInformationLabel= Label(self ,  text ="     More Information : \n")
        self.MoreInformationLabel.grid(row = 6, column = 4 , columnspan = 2 , sticky = W )
        
        #Create Text Box More Information
        #self.MoreInformationBox = Entry (self , width = 30, font=("Helvetica Neue", 12))
        self.MoreInformationBox = Text (self ,  width = 40, height = 10 , font = ("Helvetica Neue", 12) )
        self.MoreInformationBox.grid(row = 6 , column = 6 , sticky = W )

        #Create Label Add More Information 
        self.AddMoreInformationLabel= Label(self ,  text ="Add More Information : \n")
        self.AddMoreInformationLabel.grid(row = 7, column = 4 , columnspan = 2 , sticky = W )

        #Create ScrolledText Box Add More Information
        self.AddMoreInformationBox = ScrolledText(self ,  width = 40, height = 10 , font = ("Helvetica Neue", 12) )
        self.AddMoreInformationBox.grid(row = 7 , column = 6 , sticky = W )

        #Create Button Bring Information
        self.BringInformationButton = Button (self , height = 2)
        self.BringInformationButton["text"] = "Bring \nInformation"
        self.BringInformationButton.grid(row = 3 , column = 7 , sticky = W )
        self.BringInformationButton["command"] = self.BringInformation

        #Create Add New to Database Button 
        self.AddNewToDatabaseButton = Button (self , height = 7)
        self.AddNewToDatabaseButton["text"] = "Add\n New \n Information \n to Database"
        self.AddNewToDatabaseButton.grid(row = 7 , column = 7 , sticky = W)
        self.AddNewToDatabaseButton["command"] = self.AddNewToDatabase

        #Create Button Delete The Information for this QR code 
        self.DeleteTheInformationForThisQRCodeButton = Button (self , height = 5)
        self.DeleteTheInformationForThisQRCodeButton["text"] = "      Delete The Information For This QR Code      "
        self.DeleteTheInformationForThisQRCodeButton.grid(row = 8 , column = 6 , sticky = W)
        self.DeleteTheInformationForThisQRCodeButton["command"] = self.DeleteTheInformationForThisQRCode


    
       ############ Buttones Programes ################
	 ##get entry data function
	def get_input_entry_data (self):
		self.QRNumberM = self.InterNumberbox.get()
		self.ArraivalDateM = self.InterArrivalDateBox.get()
        self.BatchIDM = self.InterBatchIDBox.get()
        self.MoreInformationM = self.MoreInformationBox.get("1.0", "end-1c")
		
	def get_scan_entry_data (self):
		self.ScanBoxM = self.ScanBox.get()
		self.AddMoreInformationBoxM = self.AddMoreInformationBox.get("1.0", "end-1c")
		
		
		
     ##Create New QR Code Bottun Function . It will create the QR code and shows it as bmp Image
    def CreateNewQR(self):
        #self.qrimg = qrcode.make(self.QRNumberM)
        qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ERROR_CORRECT_L, box_size=10 , border=4,)
        qr.add_data(self.QRNumberM)
        qr.make(fit=True)
        img = qr.make_image(fill_color="black", back_color="white")
        img.show()
        
    
    ##Add to Database Bottun Function
    def AddToDatabase (self):
        #client = MongoClient(port=27017) # Establishing a Connection with Mongo
        #db=client.QRCodeCollection       #Accessing Database
        #QRCode = db.QRCode
		client = pymongo.MongoClient("mongodb://*****:*****@cluster0-shard-00-00-usqui.mongodb.net:27017,cluster0-shard-00-01-usqui.mongodb.net:27017,cluster0-shard-00-02-usqui.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true")
	#	db = client.test
	#	QRCodeCollection=0
    #   QRCodeCollection = { 'QRNumber' : self.QRNumberM , 'ArraivalDate' : self.ArraivalDateM , 'BatchID' : self.BatchIDM , 'MoreInformation' : self.MoreInformationM }
    #   InsertNewDocument = db.QR.insert_one(QRCodeCollection)

    
    ##Bring Information Bottun Function
    def BringInformation (self): pass
#        client = MongoClient(port=27017) # Establishing a Connection with Mongo
#        db=client.QRCodeCollection       #Accessing Database
#        QRCode = db.QRCode
	#   	client = pymongo.MongoClient("mongodb://*****:*****@cluster0-shard-00-00-usqui.mongodb.net:27017,cluster0-shard-00-01-usqui.mongodb.net:27017,cluster0-shard-00-02-usqui.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true")
	#	db = client.test
    #    QRCodeData = db.QR.find_one({'QRNumber': self.ScanBoxM })
    #    for ArraivalDate in QRCodeData :
    #        self.ArrivalDateBox.insert(0.0,ArraivalDate)
    #    for BatchID in QRCodeData :
    #        self.BatchIDBox.insert(0.0,BatchID)
    #    for MoreInformation in QRCodeData :
    #        self.MoreInformationBox.insert(0.0,MoreInformation)
       

    ##Add New Information to Database Button Function 
    def AddNewToDatabase (self) : pass
#        client = MongoClient(port=27017) # Establishing a Connection with Mongo
#        db=client.QRCodeCollection       #Accessing Database
#        QRCode = db.QRCode
    #   	client = pymongo.MongoClient("mongodb://*****:*****@cluster0-shard-00-00-usqui.mongodb.net:27017,cluster0-shard-00-01-usqui.mongodb.net:27017,cluster0-shard-00-02-usqui.mongodb.net:27017/test?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true")
	#	db = client.test
	#	self.AddNewToDatabaseM = [self.AddMoreInformationBoxM , self.MoreInformationM ]
    #    UpdateMoreInfo = db.QR.update_one ({'QRNumber' : self.ScanBoxM},{ '$set':{'QRNumber' : self.QRNumberM ,
    #                                                                                  'ArraivalDate' : self.ArraivalDateM ,
    #                                                                                  'BatchID' : self.BatchIDM ,
    #                                                                                  'MoreInformation' : self.AddNewToDatabaseM }})
    
    ##Delete The Information For This QR Code Button Function
    def DeleteTheInformationForThisQRCode (self) : pass
Exemplo n.º 11
0
        #b=data2.get()
        #op=2
        #p=IP(src=a,dst=b,op)/TCP()
        #send(p)    

button1=Tkinter.Button(bottomframe,text="send packet",command=sendPacket)
button1.grid(row=1,column=0)

button2=Tkinter.Button(bottomframe, text="Print Me", command=printSomething)
button2.grid(row=2,column=0) 


#sniff the data 

T1 = ScrolledText(bottomframe, height=40, width=70)
T1.grid(row=3,column=2)


#def printToBox():
#    with open('sniff.txt','r') as fp:
#        msg=fp.read()
#        fp.close()
#    T1.insert(END,msg)
    


def sniffPackets(packet):        # custom custom packet sniffer action method
    
        if packet.haslayer(IP):
            pckt_src=packet[IP].src
            pckt_dst=packet[IP].dst
Exemplo n.º 12
0
    # Loading the topic given by the user (absolute path is required)
    topf_path = topic_path.decode('utf-8')
    global topic_name
    topic_name = ALDialog.loadTopic(topf_path.encode('utf-8'))

    # Activating the loaded topic
    ALDialog.activateTopic(topic_name)

    # Starting the dialog engine - we need to type an arbitrary string as the identifier
    # We subscribe only ONCE, regardless of the number of topics we have activated
    ALDialog.subscribe('my_dialog_example')


#GUI de demarrage du programme
content.grid(column=0, row=0, sticky=(N, S, E, W))
frame.grid(column=0, row=0, columnspan=1, rowspan=2, sticky=(N, S, E, W))
adresseIPLabel.grid(column=3, row=0, columnspan=2, sticky=(N, W), padx=5)
IPtexteEntree.grid(column=3,
                   row=1,
                   columnspan=2,
                   sticky=(N, E, W),
                   pady=5,
                   padx=5)
boutonDemarrer = Button(content, text="Demarrer", command=lambda: main())
boutonArreter = Button(content, text="Arreter", command=lambda: quitter())
boutonDemarrer.grid(column=3, row=3)
boutonArreter.grid(column=4, row=3)
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1)
content.columnconfigure(0, weight=3)
content.columnconfigure(1, weight=3)
Exemplo n.º 13
0
class WikiPedia:
      def Wiki_Window(self, window):
            self.window = window
            self.window.geometry("1500x1500")
            
      def Notebook(self):
            self.notebook = ttk.Notebook(self.window)
            self.framePyRat = ttk.Frame(self.notebook, width=2500, height=1000)
            self.frameAbout = ttk.Frame(self.notebook, width=2500, height=1000)
            self.notebook.add(self.framePyRat, text='PyPedia')
            self.notebook.add(self.frameAbout, text='About')
            self.notebook.grid(row=0)

      def Design(self):
              ttk.Labelframe(self.window, width=1350, height=140).grid(row=0, sticky = NW)
              Label(self.window, text="Welcome To PyPedia",font=("Helvetica",20)).grid(row=0, column=0, sticky = NW, pady=50, padx = 450)
              image = Image.open("wikilogo.png")
              photo = ImageTk.PhotoImage(image)
              label = Label(image=photo)
              label.image = photo 
              label.grid(row=0, column=0, sticky = NW, padx=1150)

      def search(self):
             global infowiki
             infowiki = StringVar()
             ttk.Labelframe(self.window, width=1350, height=600).grid(row=0, sticky = NW, pady=150, column=0)
             ttk.Labelframe(self.window, width=500, height=300).grid(row=0, sticky = NW, pady=174, column=0, padx=800)
             ttk.Labelframe(self.window, width=750, height=600).grid(row=0, sticky = NW, pady=174, column=0, padx=20)
             self.WikiInfo = ScrolledText(self.window, width=65,height=18, bd=7,font=("Helvetica",15))
             self.WikiInfo.grid(row=0, sticky = NW, pady=280, column=0, padx=20)
             self.WikiInfo.insert(END, "Please Search For Content\n")
          
 
      
                 
            
                
      
      def Content(self):
            global infowiki
            infowiki = StringVar()
            Label(self.window, text="Search:: ",font=("Helvetica",18)).grid(row=0, column=0, sticky = NW, pady=210, padx=30)
            Entry(self.window, width=30, bd=4,textvariable=infowiki, font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=210, padx=140, ipady=3)
            Button(self.window,text="Go", bd=5, command = self.thread).grid(row=0, column=0, sticky = NW, pady=210, padx=500, ipady=1, ipadx=20)
            self.snip = Spinbox(self.window, from_=0, to=1000, width=10)
            self.snip.grid(row=0, column=0, sticky = NW, pady=215, padx=590, ipady=1, ipadx=20)
            Label(self.window, text="Sentence::",font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=190, padx=595)
            ttk.Labelframe(self.window, width=500, height=300).grid(row=0, sticky = NW, pady=480,padx=800, column=0)
            Label(self.window, text="Information ",font=("Helvetica",18)).grid(row=0, column=0, sticky = NW, pady=500, padx=815)
            Label(self.window, text="Image  (0)(0)",font=("Helvetica",18)).grid(row=0, column=0, sticky = NW, pady=160, padx=970)
            
            

            
      def Info(self):
            
            Label(self.window, text="Title :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=540, padx=815)
            Label(self.window, text="Url :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=580, padx=815)
            Label(self.window, text="Total Image In Url :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=625, padx=815)
            Label(self.window, text="Main Image :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=670, padx=815)
            
     

            
              
      def GoSearch(self):
            
            try:
               
                text = "                                                                                                                                                                                          "
                Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=540, padx=870)
                Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=580, padx=860)
                Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=625, padx=985)
                Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=670, padx=940)
                 
                self.WikiInfo.delete(1.0, END)
                self.WikiInfo.insert(END, "Title :: "+infowiki.get())
                self.WikiInfo.insert(END, "\n")
                self.WikiInfo.insert(END, "\n")
                WikiData.wikiSearch(infowiki.get(), self.snip.get())
                self.WikiInfo.insert(END, WikiData.GivingFuck())
                self.Info()
                            
                Label(self.window, text=WikiData.title(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=540, padx=870)
                Label(self.window, text=WikiData.url(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=580, padx=860)
                Label(self.window, text=WikiData.imageAll(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=625, padx=985)
                Label(self.window, text=WikiData.imageFront(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=670, padx=940)

                WikiData.getImage()
                WikiData.ResizeImage()
                
                



                image = Image.open("RE_IMAGE.png")
                photo = ImageTk.PhotoImage(image)
                self.label = Label(image=photo, bd=8)
                self.label.image = photo 
                self.label.grid(row=0, column=0, sticky = NW, pady=200, padx=830 )
                os.system("del image.png")
                os.system("del RE_IMAGE.png")
                     
                    
               
      

            except :
                        global opt
                        opt = []
                        
                        self.WikiInfo.insert(END, " \n")
                        self.WikiInfo.insert(END, "Found Other insted Of  "+ infowiki.get())
                        self.WikiInfo.insert(END, "\n")
                        self.WikiInfo.insert(END, " Please Insert Underscore in space like Apple_Inc \n")
                        serc = wikipedia.search(infowiki.get(), 20)
                        self.WikiInfo.insert(END, "\n")
                        for i in serc:
                              
                                    opt.append(i)
                                    self.WikiInfo.insert(END, i," \n")
                                    self.WikiInfo.insert(END, " \n")
                                    self.WikiInfo.insert(END, "\n")
                                    
                        

                
      def  thread(self):
            proc = threading.Thread(target = self.GoSearch)
            proc.start()
Exemplo n.º 14
0
    def initialisation(self):
        global input_pipe
        global output_pipe

        if len(sys.argv) > 2:
            print 'output_pipe : ', output_pipe
        global ChaineALire
        global st
        global fp
        global colorbox
        global sortieTube
        global entreeTube

        texte = """ Welcome in GUI for ARINC 653 emulator 
"""

        #on cree un fenetre principale 'fp' a� partir du 'modele' Tk
        #fp = Tk()
        self.title('ARINC 653 Partition')

        #Declaration du texte deroulant dans 'fp'
        st = ScrolledText(self, wrap="word")
        st.grid(column=1, columnspan=2, rowspan=2, sticky='nw')

        #Creation d'un panneau 'menu_bottom' insere dans 'fp'
        #		menu_bottom = Frame(self,borderwidth=2)
        #		menu_bottom.grid(column=1,columnspan=3,sticky='sw')

        ##Creation d'une etiquette inseree dans 'menu_bottom'
        #etiquette = Label(menu_bottom,text = 'Commande : ')
        #etiquette.grid(row=1,column=1,sticky='w')

        ##Creation d'un boutton dans 'menu_bottom'
        #b = Button(menu_bottom,text='execute',command=self.affiche_commande)
        #b.grid(row=1,column=3,sticky='e')

        ##Creation d'un boite d'edition dans 'nenu_top'
        #entre = Entry(menu_bottom,width=20,relief='sunken')
        #entre.insert(END,'Texte a afficher')
        #entre.grid(row=1,column=2,sticky='ew')

        #Creation d'une etiquette inseree
        etiquette = Label(self, text='Command : ')
        etiquette.grid(row=2, column=0, sticky='w')

        #Creation d'un boutton
        b = Button(self, text='execute', command=self.affiche_commande)
        b.grid(row=2, column=2, sticky='e')

        #Creation d'un boite d'edition dans 'nenu_top'
        entre = Entry(self, width=20, relief='sunken')
        entre.insert(END, 'Text to send')
        entre.grid(row=2, column=1, sticky='ew')

        partitionbox = Label(self, text='Active partition : ')
        partitionbox.grid(column=0, row=0, sticky='n')

        self.labelVariable = StringVar()
        self.backcolorlabel = StringVar()
        self.frontcolorlabel = StringVar()
        self.backcolorlabel = "LightBlue"
        self.frontcolorlabel = "Black"
        label = Label(self,
                      textvariable=self.labelVariable,
                      anchor="w",
                      fg=self.frontcolorlabel,
                      bg=self.backcolorlabel,
                      height=28)
        label.grid(column=0, row=1, sticky='EW')

        #on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
        st.insert(END, texte)
        #on applique a� tout le texte la police par defaut
        st.config(font='Arial 12')
        st.config(foreground='Black')
        #on configure le fond du 'texte derouant'
        st.config(background='LightBlue')
        #e = Entry(st,width=25)

        self.grid_columnconfigure(1, weight=1)
        self.rowconfigure(1, weight=1)

        self.resizable(False, True)
        self.update()
        self.geometry(self.geometry())

        try:
            assert input_pipe != ''

        except AssertionError:
            showerror('error', "no pipe choosed")
            input_pipe = tkFileDialog.askopenfilename(
                title='Choose the input pipe to open',
                defaultextension='.fifo')

        #openning the INPUT pipe
        try:
            assert input_pipe != ''

            try:

                #			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
                sortieTube = os.open(input_pipe, os.O_RDONLY)
                if sortieTube == -1:
                    raise ValueError
            except ValueError:
                showerror('Error', "fail to open the Input pipe's output")
        except AssertionError:
            showerror("Error", "You must choose a pipe first")

        #openning the OUTPUT pipe
        if len(sys.argv
               ) > 2:  #if an output pipe was given as the second argument
            try:
                assert output_pipe != ''

                #opening the pipe
                try:
                    entreeTube = os.open(output_pipe, os.O_WRONLY)

                    if entreeTube == -1:
                        raise ValueError
                except ValueError:
                    showerror('Error', "Could not open Output pipe")
            except AssertionError:
                showerror("Error", "You must choose an output pipe first")
                output_pipe = tkFileDialog.askopenfilename(
                    title='Choose the output pipe to open',
                    defaultextension='.fifo')
Exemplo n.º 15
0
class Editor:
    def __init__(self, parentself):

        self.parent = parentself
        self.clmct = 0

    def open_command(self):
        file = tkFileDialog.askopenfile(parent=root,
                                        mode='rb',
                                        title='Select a file')
        if file != None:
            contents = file.read()
            self.textPad.insert('1.0', contents)
            file.close()

    def save_command(self):
        file = tkFileDialog.asksaveasfile(mode='w')
        if file != None:
            # slice off the last character from get, as an extra return is added
            data = self.textPad.get('1.0', END + '-1c')
            file.write(data)
            file.close()

    def exit_command(self):
        if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
            self.top.destroy()

    def about_command(self):
        label = tkMessageBox.showinfo(
            "About",
            "Just Another TextPad \n Copyright \n No rights left to reserve")

    def dummy(self):
        print "I am a Dummy Command, I will be removed in the next step"

    def rehearsePattern(self):
        self.parent.formula.set(self.getPatternInsertText())
        self.parent.play_in_thread_seq()

    def addPattern(self):

        self.textPad.insert(INSERT, self.getPatternInsertText())

    def getPatternInsertText(self):
        ptn = self.editorPttn.get() + " "
        transpose = "+" + self.transposeOffset.get() + " "
        fromto = self.editorFrom.get() + "-" + self.editorTo.get()
        reps = "*" + self.Repetitions.get() + " "
        stringtoinsert = "{" + ptn + transpose + fromto + "}" + reps
        return stringtoinsert

    def saveText(self):
        self.parent.trackText.set(self.textPad.get(1.0, END))
        self.top.destroy()

    def addDrop(self):
        print self.dropPattern.get()

    def clm(self):
        self.clmct += 1
        return self.clmct

    def clm0(self):
        self.clmct = 0

    def init_ui(self):

        self.top = Toplevel(self.parent.root)
        self.top.geometry('800x600')
        #self.top.grid_columnconfigure(0, weight=1, uniform="fred")
        self.editorPttn = StringVar()
        self.editorFrom = StringVar()
        self.editorTo = StringVar()
        self.transposeOffset = StringVar()
        self.Repetitions = StringVar()
        self.dropPattern = StringVar()

        label_font = tkFont.Font(family='Courer', size=25)

        Label(self.top, text="Pattern").grid(row=0, column=0, sticky=NW)
        self.editorPttn.set("1")
        self.editorPtnDropDown = OptionMenu(self.top, self.editorPttn, 1, 2, 3,
                                            4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
                                            14, 15, 16, 17, 18, 19, 20, 21, 22,
                                            23, 24, 25, 26, 27, 28, 29, 30, 31,
                                            32)
        self.editorPtnDropDown.grid(row=0, column=self.clm(), sticky=NW)

        Label(self.top, text="From").grid(row=0, column=self.clm(), sticky=NW)
        self.editorFrom.set('1')  # set the default option
        editorFromDropDown = OptionMenu(self.top, self.editorFrom, 1, 2, 3, 4,
                                        5, 6, 7, 8)
        editorFromDropDown.grid(row=0, column=self.clm(), sticky=NW)

        Label(self.top, text="To").grid(row=0, column=self.clm(), sticky=NW)
        self.editorTo.set('32')  # set the default option
        editorToDropDown = OptionMenu(self.top, self.editorTo, 4, 8, 12, 16,
                                      20, 24, 28, 32)
        editorToDropDown.grid(row=0, column=self.clm(), sticky=NW)

        Label(self.top, text="Transpose").grid(row=0,
                                               column=self.clm(),
                                               sticky=NW)
        self.transposeOffset.set('0')  # set the default option
        transposeOffsetDropDown = OptionMenu(self.top, self.transposeOffset, 0,
                                             1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                                             12)
        transposeOffsetDropDown.grid(row=0, column=self.clm(), sticky=NW)

        Label(self.top, text="Repetitions").grid(row=0,
                                                 column=self.clm(),
                                                 sticky=NW)
        self.Repetitions.set('1')  # set the default option
        RepetitionsDropDown = OptionMenu(self.top, self.Repetitions, 1, 2, 3,
                                         4, 5, 6, 7, 8)
        RepetitionsDropDown.grid(row=0, column=self.clm(), sticky=NW)

        patternRehearseButton = Button(self.top,
                                       text="Preview",
                                       command=self.rehearsePattern)
        patternRehearseButton.grid(row=0, column=self.clm(), sticky=NW)

        patternHelperButton = Button(self.top,
                                     text="Add",
                                     command=self.addPattern)
        patternHelperButton.grid(row=0, column=self.clm(), sticky=NW)

        columnTotal = self.clm()

        Label(self.top, text="Drop Pattern").grid(row=1,
                                                  column=self.clm0(),
                                                  sticky=NW)
        self.dropPattern.set("1")
        self.dropPatternDropDown = OptionMenu(self.top, self.dropPattern, 1, 2,
                                              3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
                                              13, 14, 15, 16, 17, 18, 19, 20,
                                              21, 22, 23, 24, 25, 26, 27, 28,
                                              29, 30, 31, 32)
        self.dropPatternDropDown.grid(row=1, column=self.clm(), sticky=NW)

        patternHelperButton = Button(self.top,
                                     text="Add Drop",
                                     command=self.addDrop)
        patternHelperButton.grid(row=1, column=self.clm(), sticky=NW)

        self.textPad = ScrolledText(self.top,
                                    width=40,
                                    height=10,
                                    font=label_font)
        self.textPad.grid(row=2, column=0, columnspan=columnTotal, sticky=NW)
        self.textPad.insert(END, self.parent.trackText.get())
        #for i in range(self.clmct+1):
        #self.top.grid_columnconfigure(i, weight=1, uniform="foo")

        okbtn = Button(self.top, text="Ok", command=self.saveText)
        okbtn.grid(row=3, column=0)
        cancelbtn = Button(self.top, text="Cancel")
        cancelbtn.grid(row=3, column=1)
        menu = Menu(self.top)
        self.top.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=self.dummy)
        filemenu.add_command(label="Open...", command=self.open_command)
        filemenu.add_command(label="Save", command=self.save_command)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.exit_command)
        helpmenu = Menu(menu)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=self.about_command)
Exemplo n.º 16
0
        parser.second_pass(lines)


    f.close()


root = Tkinter.Tk(className="CO Project")
#root.geometry('{}x{}'.format(50, 150))
root.grid_columnconfigure(0, weight = 1)
root.grid_columnconfigure(0, weight = 1)
root.grid_rowconfigure(1, weight = 1)
root.grid_rowconfigure(3, weight = 1)
Tkinter.Label(root, height = '2', text = 'Input').grid(row =0,column = 0)
Tkinter.Label(root, height = '2', text = 'Simulation Output').grid(row =2,column = 0)
input_asm = ScrolledText(root,height = '17')
input_asm.grid(row = 1, column = 0, sticky = N+S+W+E)
output_monitor = ScrolledText(root,height = '12', state= 'disabled')
output_monitor.grid(row = 3, column = 0, sticky = N+S+W+E)

# create a menu & define functions for each menu item

def open_command():
        file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Select a file')
        if file != None:
            new() 
	    contents = file.read()
            input_asm.insert('1.0',contents)
            file.close()


def save_command():
Exemplo n.º 17
0
class DualView(Frame):
    def __init__(self, parent, filename, goban_size=200):
        #Tk.__init__(self,parent)
        Frame.__init__(self, parent)

        self.parent = parent
        self.filename = filename
        self.goban_size = goban_size

        self.initialize()

        self.current_move = 1
        self.display_move(self.current_move)

        #self.after(100,self.center)

        self.pressed = 0

    def close_app(self):
        for popup in self.all_popups[:]:
            popup.close()
            """
			if popup.okgnugo:
				print "killing gnugo"
				popup.gnugo.kill()
			if popup.okleela:
				print "killing leela"
				popup.leela.kill()
			"""
        self.destroy()
        self.parent.destroy()

    def prev_move(self, event=None):
        if self.current_move > 1:
            self.pressed = time.time()
            self.current_move -= 1
            pf = partial(self.goto_move,
                         move_number=self.current_move,
                         pressed=self.pressed)
            self.parent.after(0, lambda: pf())

    def next_move(self, event=None):
        if self.current_move < get_node_number(self.gameroot):
            self.pressed = time.time()
            self.current_move += 1
            pf = partial(self.goto_move,
                         move_number=self.current_move,
                         pressed=self.pressed)
            self.parent.after(0, lambda: pf())

    def goto_move(self, move_number, pressed):
        self.move_number.config(text=str(move_number) + '/' +
                                str(get_node_number(self.gameroot)))
        if self.pressed == pressed:
            self.display_move(self.current_move)

    def leave_variation(self, goban, grid, markup):
        self.comment_box2.delete(1.0, END)
        goban.display(grid, markup)

    def show_variation(self, event, goban, grid, markup, i, j):
        sequence = markup[i][j]
        temp_grid = copy(grid)
        temp_markup = copy(markup)

        for u in range(self.dim):
            for v in range(self.dim):
                if temp_markup[u][v] != 0:
                    temp_markup[u][v] = ''

        k = 1
        for color, (u, v), s, comment, displaycolor in sequence:
            temp_grid[u][v] = color
            temp_markup[u][v] = k
            k += 1

        goban.display(temp_grid, temp_markup)

        self.comment_box2.delete(1.0, END)
        if comment:
            self.comment_box2.insert(END, comment)
        u = i + goban.mesh[i][j][0]
        v = j + goban.mesh[i][j][1]
        local_area = goban.draw_point(u, v, 1, color="", outline="")
        goban.tag_bind(local_area, "<Leave>",
                       lambda e: self.leave_variation(goban, grid, markup))

    def display_move(self, move=1):
        dim = self.dim
        goban1 = self.goban1
        goban2 = self.goban2

        self.move_number.config(text=str(move) + '/' +
                                str(get_node_number(self.gameroot)))
        print "========================"
        print "displaying move", move
        grid1 = [[0 for row in range(dim)] for col in range(dim)]
        markup1 = [["" for row in range(dim)] for col in range(dim)]
        grid2 = [[0 for row in range(dim)] for col in range(dim)]
        markup2 = [["" for row in range(dim)] for col in range(dim)]
        board, _ = sgf_moves.get_setup_and_moves(self.sgf)

        for colour, move0 in board.list_occupied_points():
            if move0 is None:
                continue
            row, col = move0
            if colour == 'b':
                place(grid1, row, col, 1)
                place(grid2, row, col, 1)

        m = 0
        for m in range(1, move):
            one_move = get_node(self.gameroot, m)
            if one_move == False:
                print "(0)leaving because one_move==False"
                return

            ij = one_move.get_move()[1]

            if ij == None:
                print "(0)skipping because ij==None", ij
                continue

            if one_move.get_move()[0] == 'b': color = 1
            else: color = 2
            i, j = ij
            place(grid1, i, j, color)
            place(grid2, i, j, color)

            if len(one_move) == 0:
                print "(0)leaving because len(one_move)==0"
                goban1.display(grid1, markup1)
                goban2.display(grid2, markup2)
                return

        #indicating last play with delta
        self.comment_box1.delete(1.0, END)
        if m > 0:
            if get_node(self.gameroot, m + 2).parent.has_property("C"):
                self.comment_box1.insert(
                    END,
                    get_node(self.gameroot, m + 2).parent.get("C"))
            markup1[i][j] = 0
            markup2[i][j] = 0
        self.comment_box2.delete(1.0, END)
        #next sequence in current game ############################################################################
        main_sequence = []
        for m in range(5):
            one_move = get_node(self.gameroot, move + m)
            if one_move == False:
                print "(00)leaving because one_move==False"
                break
            ij = one_move.get_move()[1]
            if ij == None:
                print "(0)skipping because ij==None", ij
                break
            if one_move.get_move()[0] == 'b': c = 1
            else: c = 2
            main_sequence.append([c, ij, "A", None, "blue"])
            if m == 0:
                real_game_ij = ij
        try:
            #i,j=one_move=get_node(self.gameroot,move).get_move()[1]
            i, j = get_node(self.gameroot, move).get_move()[1]
        except:
            self.prev_move()
            return
        markup1[i][j] = main_sequence

        #alternative sequences ####################################################################################
        parent = get_node(self.gameroot, move - 1)
        if one_move == False:
            print "(1)leaving because one_move==False"
            return
        if len(parent) <= 1:
            print "no alternative move"
            #display(goban1,grid1,markup1)
            #display(goban2,grid2,markup2)
            goban1.display(grid1, markup1)
            goban2.display(grid2, markup2)

            return

        for a in range(1, len(parent)):
            one_alternative = parent[a]
            ij = one_alternative.get_move()[1]

            if ij == real_game_ij: displaycolor = "blue"
            else: displaycolor = "red"

            if one_alternative.get_move()[0] == 'b': c = 1
            else: c = 2

            if one_alternative.has_property("C"):
                comment = one_alternative.get("C")
            else:
                comment = ''
            alternative_sequence = [[
                c, ij, chr(64 + a), comment, displaycolor
            ]]
            while len(one_alternative) > 0:
                one_alternative = one_alternative[0]
                ij = one_alternative.get_move()[1]
                if one_alternative.get_move()[0] == 'b': c = 1
                else: c = 2
                alternative_sequence.append(
                    [c, ij, chr(64 + a), comment, "whocare?"])
            i, j = parent[a].get_move()[1]
            markup2[i][j] = alternative_sequence

        goban1.display(grid1, markup1)
        goban2.display(grid2, markup2)

    def open_move(self):
        print "Opening move", self.current_move
        new_popup = OpenMove(self, self.current_move, self.dim, self.sgf,
                             self.goban_size)
        self.all_popups.append(new_popup)

    def initialize(self):

        txt = open(self.filename)
        self.sgf = sgf.Sgf_game.from_string(txt.read())
        txt.close()

        self.dim = self.sgf.get_size()
        self.komi = self.sgf.get_komi()

        print "boardsize:", self.dim
        #goban.dim=size

        #goban.prepare_mesh()
        self.gameroot = self.sgf.get_root()

        self.parent.title('GoReviewPartner')
        self.parent.protocol("WM_DELETE_WINDOW", self.close_app)

        self.all_popups = []

        self.configure(background=bg)

        Label(self, text='   ', background=bg).grid(column=0, row=0)
        Button(self, text='prev', command=self.prev_move).grid(column=1, row=1)
        Button(self, text='open', command=self.open_move).grid(column=2, row=1)
        Button(self, text='next', command=self.next_move).grid(column=3, row=1)

        self.move_number = Label(self, text='   ', background=bg)
        self.move_number.grid(column=2, row=2)

        self.parent.bind('<Left>', self.prev_move)
        self.parent.bind('<Right>', self.next_move)

        #Label(app,background=bg).grid(column=1,row=2)

        row = 10

        Label(self, background=bg).grid(column=1, row=row - 1)

        #self.goban1 = Canvas(self, width=10, height=10,bg=bg,bd=0, borderwidth=0)
        self.goban1 = Goban(self.dim,
                            master=self,
                            width=10,
                            height=10,
                            bg=bg,
                            bd=0,
                            borderwidth=0)

        self.goban1.grid(column=1, row=row)
        Label(self, text='            ', background=bg).grid(column=2, row=row)
        #self.goban2 = Canvas(self, width=10, height=10,bg=bg,bd=0, borderwidth=0)
        self.goban2 = Goban(self.dim,
                            master=self,
                            width=10,
                            height=10,
                            bg=bg,
                            bd=0,
                            borderwidth=0)
        self.goban2.grid(column=3, row=row)

        self.goban1.space = self.goban_size / (self.dim + 1)
        self.goban2.space = self.goban_size / (self.dim + 1)

        Label(self, text='   ', background=bg).grid(column=4, row=row + 1)

        self.comment_box1 = ScrolledText(self, height=5)
        self.comment_box1.grid(column=1, row=row + 4)

        self.comment_box2 = ScrolledText(self, height=5)
        self.comment_box2.grid(column=3, row=row + 4)

        Label(self, text='   ', background=bg).grid(column=4, row=row + 5)

        goban.show_variation = self.show_variation
Exemplo n.º 18
0
class GUI:
    def __init__(self):
        self.version = "2.1"

        self.root = Tk()
        self.root.title("IMSafe %s ---  By: Patrick T. Cossette" %
                        self.version)

        self.encryptionFunction = IMCrypt2.encryptText
        self.decryptionFunction = IMCrypt2.decryptText

        self.useNewMethod = IntVar()
        self.useNewMethod.set(1)

        self.key = "Red Castle"
        self.server = StringVar()
        self.username = StringVar()
        self.username.set(environ["USER"])
        self.settingsUp = False
        self.connected = False
        self.master = None
        self.usernamePreview = StringVar()
        self.usernamePreview.set(self.username.get())
        self.all_recipts = []

        self.keyTxt = StringVar()
        self.keyTxt2 = StringVar()

        self.keyTxt.set(self.key)
        self.keyTxt2.set(self.key)

        self.queue = Queue.Queue()

        self.server.set("http://www.example.com/IMSafe.php")

        self.network = IMNetwork.IMNetwork()
        self.network.screen_name = self.username.get()
        self.network.address = self.server.get()

        self.scheme = IntVar()
        self.scheme.set(1)  #color scheme, 1 = green on black.

        #Foreground, background, insertion cursor, entry background, username highlight, foreign username highlight
        self.colorSchemes = [
            ("green", "black", "red", "gray", "red", "blue"),
            ("black", "white", "black", "white", "blue", "red"),
            ("red", "black", "green", "gray", "green", "blue"),
            ("yellow", "black", "blue", "gray", "blue", "green"),
            ("blue", "black", "purple", "gray", "red", "black"),
            ("black", "gray", "black", "gray", "blue", "red"),
            ("black", "blue", "white", "blue", "white", "black"),
            ("black", "white", "black", "white", "blue", "red"),
            ("green", "black", "red", "gray", "red", "blue")
        ]

        self.fontSize = 15
        self.checked = IntVar()
        self.checked.set(1)

        self.alwaysOntop = IntVar()
        self.alwaysOntop.set(0)

        self.fullscreen = IntVar()
        self.fullscreen.set(0)
        self.previousSize = ""

        self.playSoundWithFocus = IntVar()
        self.playSoundWithoutFocus = IntVar()
        self.playSoundOnRecieve = IntVar()
        self.playSoundOnSend = IntVar()
        self.mute = IntVar()

        self.playingSound = False  #Prevents overlap when recieving a massive numbger of messages

        self.playSoundWithFocus.set(1)
        self.playSoundWithoutFocus.set(1)
        self.playSoundOnRecieve.set(1)
        self.playSoundOnSend.set(1)
        self.mute.set(0)

        self.tags = 0  #Keep up with tags while highlighting text

        filemenu = Menu(self.root, tearoff=0)
        filemenu.add_command(label="Open Encrypted File           ⌘O",
                             command=self.openFile)
        filemenu.add_command(label="Save Encrypted File            ⌘S",
                             command=self.saveFile)
        filemenu.add_command(label="Open Text File                   ⌘T",
                             command=self.openText)
        filemenu.add_command(label="Save Text File", command=self.saveText)
        filemenu.add_separator()
        filemenu.add_command(label="Encrypt File                         ⌘E",
                             command=self.encryptFile)
        filemenu.add_command(label="Decrypt File                        ⌘D",
                             command=self.decryptFile)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.destroy)

        encryptmenu = Menu(self.root, tearoff=0)
        encryptmenu.add_checkbutton(label="Use Latest Encryption Method",
                                    command=self.setMethod,
                                    variable=self.useNewMethod)

        self.chatmenu = Menu(self.root, tearoff=0)
        self.chatmenu.add_command(
            label="Connect",
            command=lambda: self.connectToServer(self.server.get()))
        self.chatmenu.add_command(label="Disconnect",
                                  command=self.disconnectFromServer,
                                  state="disabled")
        self.chatmenu.add_separator()
        self.chatmenu.add_command(label="Settings", command=self.settings)

        viewmenu = Menu(self.root, tearoff=0)
        viewmenu.add_checkbutton(label="Word Wrap                        ⌘W",
                                 command=self.toggleWrap,
                                 variable=self.checked)
        viewmenu.add_command(label="Clear Screen",
                             command=lambda: self.txt.delete(1.0, END))
        viewmenu.add_separator()
        viewmenu.add_command(label="Increase Font                    ⌘Num+",
                             command=self.increaseFont)
        viewmenu.add_command(label="Decrease Font                   ⌘Num-",
                             command=self.decreaseFont)
        viewmenu.add_checkbutton(label="Always Ontop",
                                 command=lambda: self.root.wm_attributes(
                                     "-topmost", self.alwaysOntop.get()),
                                 variable=self.alwaysOntop)
        viewmenu.add_checkbutton(
            label="Fullscreen                                F11",
            command=self.toggleFullscreen,
            variable=self.fullscreen)
        viewmenu.add_separator()

        colrmenu = Menu(self.root, tearoff=0)

        colrmenu.add_radiobutton(
            label="Color Scheme 1                         F1",
            command=self.changeScheme,
            variable=self.scheme,
            value=1)
        colrmenu.add_radiobutton(
            label="Color Scheme 2                         F2",
            command=self.changeScheme,
            variable=self.scheme,
            value=2)
        colrmenu.add_radiobutton(
            label="Color Scheme 3                         F3",
            command=self.changeScheme,
            variable=self.scheme,
            value=3)
        colrmenu.add_radiobutton(
            label="Color Scheme 4                         F4",
            command=self.changeScheme,
            variable=self.scheme,
            value=4)
        colrmenu.add_radiobutton(
            label="Color Scheme 5                         F5",
            command=self.changeScheme,
            variable=self.scheme,
            value=5)
        colrmenu.add_radiobutton(
            label="Color Scheme 6                         F6",
            command=self.changeScheme,
            variable=self.scheme,
            value=6)
        colrmenu.add_radiobutton(
            label="Color Scheme 7                         F7",
            command=self.changeScheme,
            variable=self.scheme,
            value=7)
        colrmenu.add_radiobutton(
            label="Color Scheme 8                         F8",
            command=self.changeScheme,
            variable=self.scheme,
            value=8)
        colrmenu.add_radiobutton(
            label="Color Scheme 9                         F9",
            command=self.changeScheme,
            variable=self.scheme,
            value=9)
        viewmenu.add_cascade(label="Color Scheme", menu=colrmenu)

        soundmenu = Menu(self.root, tearoff=0)
        soundmenu.add_command(label="Play Sound When:", state="disabled")
        soundmenu.add_checkbutton(label="Chat has focus",
                                  command=self.saveConfiguration,
                                  variable=self.playSoundWithFocus)
        soundmenu.add_checkbutton(label="Chat doesn't have focus",
                                  command=self.saveConfiguration,
                                  variable=self.playSoundWithoutFocus)
        soundmenu.add_checkbutton(label="Recieving Messages",
                                  command=self.saveConfiguration,
                                  variable=self.playSoundOnRecieve)
        soundmenu.add_checkbutton(label="Sending Messages",
                                  command=self.saveConfiguration,
                                  variable=self.playSoundOnSend)
        soundmenu.add_separator()
        soundmenu.add_checkbutton(
            label="Mute                                 ⌘M",
            command=self.saveConfiguration,
            variable=self.mute)

        helpmenu = Menu(self.root, tearoff=0)
        helpmenu.add_command(label="Help", command=self.showHelp)
        helpmenu.add_command(label="About", command=self.showAbout)

        menubar = Menu(self.root)
        menubar.add_cascade(label="File", menu=filemenu)
        menubar.add_cascade(label="Encryption", menu=encryptmenu)
        menubar.add_cascade(label="Chat", menu=self.chatmenu)
        menubar.add_cascade(label="View", menu=viewmenu)
        menubar.add_cascade(label="Sound", menu=soundmenu)
        menubar.add_cascade(label="Help", menu=helpmenu)
        self.root.config(menu=menubar)

        self.chat = StringVar()

        self.root.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)

        self.txt = ScrolledText(self.root,
                                wrap=WORD,
                                fg='green',
                                bg='black',
                                font=("Courier", 14),
                                width=80,
                                insertbackground="red",
                                insertwidth=3,
                                maxundo=5,
                                undo=True)
        self.txt.grid(sticky=N + S + E + W)
        self.txt.rowconfigure(0, weight=1)
        self.txt.columnconfigure(0, weight=1)

        self.inputVar = StringVar()
        self.input = Entry(self.root,
                           textvariable=self.inputVar,
                           font=("Courier", 14),
                           width=115,
                           bg="gray",
                           fg="black")
        self.input.grid(sticky=N + S + E + W)
        self.input.bind("<Return>", self.sendText)
        self.input.rowconfigure(0, weight=1)
        self.input.columnconfigure(0, weight=1)
        self.input.focus()

        self.root.bind("<Command-s>", self.saveFile)
        self.root.bind("<Command-o>", self.openFile)
        self.root.bind("<Command-t>", self.openText)
        self.root.bind("<Command-d>", self.decryptFile)
        self.root.bind("<Command-e>", self.encryptFile)
        self.root.bind("<Command-+>", self.increaseFont)
        self.root.bind("<Command-=>", self.increaseFont)
        self.root.bind("<Command-minus>", self.decreaseFont)
        self.root.bind("<Command-a>", self.selectAll)
        self.root.bind("<Command-m>", self.toggleMute)
        self.root.bind("<F11>", self.toggleFullscreen)

        self.root.bind("<F1>", lambda (Event): self.setScheme(1))
        self.root.bind("<F2>", lambda (Event): self.setScheme(2))
        self.root.bind("<F3>", lambda (Event): self.setScheme(3))
        self.root.bind("<F4>", lambda (Event): self.setScheme(4))
        self.root.bind("<F5>", lambda (Event): self.setScheme(5))
        self.root.bind("<F6>", lambda (Event): self.setScheme(6))
        self.root.bind("<F7>", lambda (Event): self.setScheme(7))
        self.root.bind("<F8>", lambda (Event): self.setScheme(8))
        self.root.bind("<F9>", lambda (Event): self.setScheme(9))

        self.root.wm_iconbitmap("%s\\icon.ico" % getcwd())
        self.addText("IMSafe %s\nBy: Patrick T. Cossette\n\n" % self.version)
        self.network.updateCallback = self.recvMessage

        self.loadConfiguration()

    def setMethod(self):
        if self.useNewMethod.get():
            print "using new method"
            self.encryptionFunction = IMCrypt2.encryptText
            self.decryptionFunction = IMCrypt2.decryptText
        else:
            print "using old method"
            self.encryptionFunction = IMCrypt.encryptText
            self.decryptionFunction = IMCrypt.decryptText

    def toggleMute(self, Event):
        if self.mute.get():
            self.mute.set(0)
        else:
            self.mute.set(1)

    def saveConfiguration(self):
        f = file(r"%s\settings.conf" % getcwd(), 'w')
        f.write(
            "%d\n%s\n%s\n%s\n%s\n%s\n%s\n%s" %
            (self.scheme.get(), self.server.get(), self.username.get(),
             self.playSoundWithFocus.get(), self.playSoundWithoutFocus.get(),
             self.playSoundOnRecieve.get(), self.playSoundOnSend.get(),
             self.mute.get()))

        f.close()

    def loadConfiguration(self):
        try:
            f = file(r"%s\settings.conf" % getcwd(), 'r')
            settings = f.read()
            settings = settings.split("\n")
            if len(settings
                   ) < 8:  #Make sure the settings file is intact and complete
                self.saveDefaultSettings()
            else:
                self.scheme.set(int(settings[0]))
                self.server.set(settings[1])
                self.username.set(settings[2])
                self.playSoundWithFocus.set(int(settings[3]))
                self.playSoundWithoutFocus.set(int(settings[4]))
                self.playSoundOnRecieve.set(int(settings[5]))
                self.playSoundOnSend.set(int(settings[6]))
                self.mute.set(int(settings[7]))
                self.setScheme(self.scheme.get())

            f.close()
        except:  #make sure the file is actually there, and intact with proper values, if not, revert to default settings
            self.saveDefaultSettings()

    def saveDefaultSettings(self):
        f = file(r"%s\settings.conf" % getcwd(), 'w')
        f.write(
            "1\nhttp://www.example.com/imsafe/IMSafe.php\n%s\n1\n1\n1\n1\n0" %
            environ["USER"])
        f.close()

    def updateChatMenu(self):
        if self.connected:
            #self.txt["state"] = "disabled"
            self.chatmenu.entryconfig(0, state="disabled")
            self.chatmenu.entryconfig(1, state="normal")
        else:
            #self.txt["state"] = "normal"
            self.chatmenu.entryconfig(0, state="normal")
            self.chatmenu.entryconfig(1, state="disabled")

    def recvMessage(self, message):

        if message[0:6] == "update":
            message = message[6::]

            highlight = 5  #If the message is from the user, use a different highlight color for  the username ^_^
            allMessages = message.split("<message_separator>")

            for message in allMessages:
                seg = message.split("<time_separator>")
                name = seg[0]
                print "appending recipts"
                self.network.recipts.append(seg[1])  #Log this message recipt
                if seg[1] in self.all_recipts:
                    return

                self.all_recipts.append(seg[1])

                d = seg[2]  #Encrypted Message
                id = name.split(" ")[0][1::]
                if id == self.username.get():
                    #Sent a message!
                    highlight = 4
                    if self.playSoundOnSend.get():
                        self.notifacation(txt="send")
                else:
                    #Recieving a message!
                    if self.playSoundOnRecieve.get():
                        self.notifacation(txt="recv")

                self.addText(name)  #Usernames get fancy color shit.
                lines = len(self.txt.get(1.0, END).split("\n")) - 1
                columns = len(name)

                self.txt.tag_add(
                    str(self.tags), float(lines),
                    ".".join([str(lines), str(columns + 1)])
                )  #just for the record, the way the tag index works is F*****G RETARDED.
                self.txt.tag_config(
                    str(self.tags),
                    foreground=self.colorSchemes[self.scheme.get() -
                                                 1][highlight],
                    font=("courier", self.fontSize, "bold"))

                self.tags += 1
                self.txt.update_idletasks()
                self.txt.tag_add(
                    str(self.tags),
                    ".".join([str(lines),
                              str(len(name.split(" ")[0]) + 1)]),
                    ".".join([str(lines), str(columns)]))
                self.txt.tag_config(str(self.tags),
                                    font=("courier", self.fontSize - 1))

                self.tags += 1

                self.addText(self.decryptionFunction(d, self.key) + "\n")

        elif message[0:4] == "list":
            message = message[4::]
            self.addText("\n\nUsers currently logged in: \n")
            for user in message.split(","):
                self.addText(user + "\n")
                lines = len(self.txt.get(1.0, END).split("\n")) - 2
                columns = len(user)

                self.txt.tag_add(str(self.tags), float(lines),
                                 ".".join([str(lines),
                                           str(columns + 1)]))
                self.txt.tag_config(
                    str(self.tags),
                    foreground=self.colorSchemes[self.scheme.get() - 1][4])
                self.tags += 1

    def notifacation(self, txt="recv"):
        if self.mute.get(): return

        if (self.root.focus_displayof() and self.playSoundWithFocus.get()
                or (not self.root.focus_displayof()
                    and self.playSoundWithoutFocus.get())):
            threading._start_new_thread(self.playSound, ("%s.wav" % txt, ))

    def selectAll(self, event=None):
        return
        self.txt.focus_set()
        self.txt.tag_add(SEL, "1.0", END)
        self.root.after(4, self.selectAll)

    def toggleFullscreen(self, event=None):
        if event:
            if self.fullscreen.get():
                self.fullscreen.set(0)
            else:
                self.fullscreen.set(1)

        if self.fullscreen.get():
            self.previousSize = self.root.geometry()
            #self.root.geometry("%dx%d+0+0" % (self.root.winfo_screenwidth(), self.root.winfo_screenheight()))  #Using state("zoomed") instead. this method causes the user's text Entry bar to fall off the screen unless the window is maximized first
            self.root.state("zoomed")
            self.root.overrideredirect(1)

        else:
            self.root.state("normal")
            self.root.overrideredirect(0)
            self.root.geometry(self.previousSize)

    def increaseFont(self, event=None):
        geo = self.root.geometry()  #preserve window size
        self.fontSize += 1
        self.txt["font"] = ("courier", self.fontSize)
        self.input["font"] = ("courier", self.fontSize)
        self.root.geometry(geo)

    def decreaseFont(self, event=None):
        geo = self.root.geometry()
        if self.fontSize < 6: return
        self.fontSize -= 1
        self.txt["font"] = ("courier", self.fontSize)
        self.input["font"] = ("courier", self.fontSize)
        self.root.geometry(geo)

    def setScheme(self, s):
        self.scheme.set(s)
        self.changeScheme()

    def changeScheme(self):
        s = self.scheme.get() - 1
        self.txt["fg"] = self.colorSchemes[s][0]
        self.txt["bg"] = self.colorSchemes[s][1]
        self.txt["insertbackground"] = self.colorSchemes[s][2]
        self.input["bg"] = self.colorSchemes[s][3]

        if s > 5:  #Black on blue gets bold text =D
            self.txt["font"] = ("courier", self.fontSize, "bold")
            self.input["font"] = ("courier", self.fontSize, "bold")
        else:
            self.txt["font"] = ("courier", self.fontSize)
            self.input["font"] = ("courier", self.fontSize)

        self.saveConfiguration()

    def toggleWrap(self, event=None):
        if self.txt["wrap"] == WORD:
            self.txt["wrap"] = NONE
        else:
            self.txt["wrap"] = WORD

    def showHelp(self):
        self.addText(
            "\n\nCommands:\n /help - display this help screen\n /about - show the about page\n /clear - clear all text from the screen\n /me - send text in 3rd person\n /setkey <key> - change the encryption key to '<key>'\n /setname <name> - set your display name in the chatroom to '<name>'\n /list - Get a list of people currenlty logged on\n /settings - Show current settings\n /connect <ip address> - connect to an IMSafe server\n /disconnect - disconnect from the IMSafe server\n /exit - close the window\n\nThis software's encryption methods are only suitable for plain text. Attempting to encrypt videos, images, or any files other than those containing plain text will likely result in error!\n\nThe default key is \"Red Castle\", it is highly recommended that you change the key prior to using this software; the key will reset to the default every time the program is opened, for security purposes the key you choose is not remembered, you will have to re-enter it every time you wish to use this software, this can be done by going to Chat->Settings or using the /setkey command.\n\n"
        )

        #Highlight all the commands
        lines = len(self.txt.get(1.0, END).split("\n"))
        for a, b in zip(
            (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17),
            ("6", "12", "9", "10", "6", "9", "8", "4", "7", "7", "6")):
            self.txt.tag_add(str(self.tags), float(lines - a),
                             ".".join([str(lines - a), b]))

        self.txt.tag_config(str(self.tags),
                            foreground=self.colorSchemes[self.scheme.get() -
                                                         1][4])

    def showAbout(self):
        self.addText(
            "\n\nCreated By: Patrick T. Cossette\nwww.DigitalDiscrepancy.com\n\nThis software is an example of a simple encryption algorithm. This software was written for the purpose of demonstration and experimentation and is probably not suitable to send or store sensitive information. Use at your own risk.\n\n Licensed under GNU General Public License, version 2, see LICENSE for more info"
        )
        lines = len(self.txt.get(1.0, END).split("\n"))
        self.txt.tag_add(str(self.tags),
                         float(lines - 7) + .12,
                         ".".join([str(lines - 7), '33']))
        self.txt.tag_config(str(self.tags),
                            foreground=self.colorSchemes[self.scheme.get() -
                                                         1][4])

    def encryptFile(self, event=None):
        f = self.openText(show=False)
        if not f: return
        self.saveFile(fileName=f[0], text=f[1])

    def decryptFile(
        self,
        event=None
    ):  #Attempt to decrypt something thats not encrypted and you'll lose that file. forever. seriously. don't do it.
        f = self.openFile(show=False)
        if not f: return
        self.saveText(fileName=f[0], text=f[1])

    def openText(self, event=None, show=True):
        fileName = tkFileDialog.askopenfilename(title="Open Text File",
                                                filetypes=[
                                                    ("Text File", ".txt"),
                                                    ("All Files", ".*")
                                                ])
        if fileName == "":
            return False
        self.txt.delete(1.0, END)

        open = file(fileName, 'r')
        text = open.read()

        if show: self.txt.insert(END, text)
        open.close()

        return (fileName, text)

    def saveText(self, event=None, fileName=None, text=None):
        if fileName == None:
            fileName = tkFileDialog.asksaveasfilename(title="Save Text File",
                                                      filetypes=[("Text File",
                                                                  ".txt"),
                                                                 ("All Files",
                                                                  ".*")])
            if fileName == "":
                return False
        if len(fileName) > 3:
            if fileName[-4::] != ".txt":
                fileName += ".txt"
        else:
            fileName += ".txt"

        save = file(fileName, 'w')
        if text:
            save.write(text)
        else:
            save.write(self.txt.get(1.0, END))
        save.close()

    def openFile(self, event=None, show=True):
        fileName = tkFileDialog.askopenfilename(title="Open Encrypted File",
                                                filetypes=[
                                                    ("Encrypted Text File",
                                                     ".txt"),
                                                    ("All Files", ".*")
                                                ])
        if fileName == "":
            return False

        self.txt.delete(1.0, END)

        open = file(fileName, 'rb')
        text = open.read()

        open.close()
        if show:
            self.txt.insert(END, self.decryptionFunction(text, self.key))
        else:
            return (fileName, self.decryptionFunction(text, self.key))

    def saveFile(self, event=None, fileName=None, text=False):
        if fileName == None:
            fileName = tkFileDialog.asksaveasfilename(
                title="Save Encrypted File",
                filetypes=[("Encrypted Text File", ".txt"),
                           ("All Files", ".*")])
            if fileName == "":
                return False

        if len(fileName) > 3:
            if fileName[-4::] != ".txt":
                fileName += ".txt"
        else:
            fileName += ".txt"

        save = file(fileName, 'wb')
        if text:
            save.write(self.encryptionFunction(text, self.key))
        else:
            save.write(
                self.encryptionFunction(self.txt.get(1.0, END), self.key))
        save.close()

    def sendText(self, event):
        text = self.inputVar.get()
        if not len(text): return
        if text[0] == "/":  #user has entered a command, not a message
            if len(text) > 5 and text[0:6] == "/clear":
                self.txt.delete(1.0, END)

            elif len(text) > 8 and text[0:7] == "/setkey":
                self.key = text.split("/setkey ")[1]

            elif len(text) > 9 and text[0:8] == "/setname":

                self.username.set(text.split("/setname ")[1])
                self.usernamePreview.set(self.username.get())
                self.network.screen_name = self.username.get()

                self.saveConfiguration()

            elif len(text) > 7 and text[0:8] == "/connect":
                if len(text) > 9 and text[0:9] == "/connect ":
                    self.server.set(text.split("/connect ")[1])
                    self.saveConfiguration()

                self.connectToServer(self.server.get())

            elif len(text) > 10 and text[0:11] == "/disconnect":
                self.disconnectFromServer()

            elif len(text) > 4 and text[0:5] == "/exit":
                self.root.destroy()

            elif len(text) > 4 and text[0:5] == "/help":
                self.showHelp()

            elif len(text) > 8 and text[0:9] == "/settings":
                self.addText(
                    "\n\nServer: %s\nUsername: %s\nkey: %s\n" %
                    (self.server.get(), self.username.get(), self.key))

            elif len(text) > 5 and text[0:6] == "/about":
                self.showAbout()

            elif len(text) > 2 and text[0:3] == "/me":
                self.sendChat(
                    text
                )  #This command will be caught within the sendChat function, as it is a message manipulator

            elif len(text) > 4 and text[0:5] == "/list":
                if self.connected:
                    self.network.list()  #List other users on the server
                else:
                    self.addText(
                        "You are not currently connected to a chatroom!\n")

            else:
                self.addText(
                    "Invalid Command - Type /help for a list of commands\n")

        else:
            self.sendChat(text)

        self.inputVar.set("")

    def playSound(self, sound):
        if self.playingSound:  #Prevent overlap!
            return

        return_code = subprocess.call(["afplay", sound])

        chunk = 1024

# Simple "fire and forget" notification

    doesntWorkonMac = """
		self.playingSound = True
		wf = wave.open(sound, 'rb')
		p = pyaudio.PyAudio()

		stream = p.open(format =
                p.get_format_from_width(wf.getsampwidth()),
                channels = wf.getnchannels(),
                rate = wf.getframerate(),
                output = True)

		data = wf.readframes(chunk)

		while data != '':
			stream.write(data)
			data = wf.readframes(chunk)

		stream.close()
		p.terminate()
		self.playingSound = False """

    def sendChat(self, message):

        if not self.connected:
            self.addText(
                "\nYou are not connected to an IMSafe server. Use the /connect command to connect to a server or go to Chat -> Connect\n\n"
            )
        else:
            print "\n\nsending  chat: ", message
            if len(message) > 4 and message[0:3] == "/me":
                responce = self.network.sendData(self.encryptionFunction(
                    message[4::], self.key),
                                                 options="first_person")
            else:
                responce = self.network.sendData(
                    self.encryptionFunction(message, self.key))
            if responce[0] != 2:
                self.connected = False
                self.updateChatMenu()
                self.addText(responce[1] + "\n")

            print "\n\nresponse: ", responce

    def addText(self, text):
        self.txt.insert(END, text)
        self.txt.yview(MOVETO, 1.0)
        #self.root.after(500, self.update_me)

    def show(self):
        self.loadConfiguration
        self.root.mainloop()

    def closeSettings(self):
        self.settingsUp = False

    def disconnectFromServer(self):
        self.addText("\n\nYou have disconnected from the server\n\n")
        self.network.disconnect()
        self.connected = False
        self.updateChatMenu()

    def connectToServer(self, address):
        self.network.screen_name = self.username.get()
        self.network.address = self.server.get()
        self.addText("\n\nConnecting to server at " + address + " ...\n\n")
        self.root.update()
        res = self.network.connect()
        if res[0]:
            self.connected = True
            self.addText(res[1] + "\n")
        else:
            self.connected = False
            self.addText("Connection Failed!\n\n%s\n" % res[1])
        self.updateChatMenu()

    def saveSettings(self):
        if self.txtKey.get() == "" or self.txtKey2.get() == "":
            showerror(
                "D=",
                "Your key can't be blank!\n\nPlease enter a valid key, the longer the better!."
            )
        elif self.txtKey.get() != self.txtKey2.get():
            showerror("D=", "The keys you entered do not match!")
        else:
            showinfo(":)", "Your settings haved been saved!")
            self.key = self.txtKey.get()

        self.username.set(self.usernamePreview.get())

        self.network.screen_name = self.username.get()
        self.network.address = self.server.get()
        self.saveConfiguration()
        self.master.focus_force()

    def settings(self):
        self.settingsUp = True

        self.master = Toplevel(self.root)
        self.master.title("Settings")
        self.master.wm_iconbitmap("%s\\icon.ico" % getcwd())
        if self.alwaysOntop.get():
            self.alwaysOntop.set(0)
            self.root.wm_attributes("-topmost", 0)
            self.addText("\"Always onotop\" feature deactivated\n")

        self.usernamePreview.set(self.username.get())

        self.keyTxt.set(self.key)
        self.keyTxt2.set(self.key)
        self.f = Frame(self.master)

        self.lblServer = Label(self.f, text="Server: ")
        self.lblServer.grid(row=0, column=0, sticky=E, pady=2, padx=2)
        self.txtServer = Entry(self.f, textvariable=self.server)
        self.txtServer.grid(row=0, column=1, pady=2, padx=2)

        self.lblUser = Label(self.f, text="Screename: ")
        self.lblUser.grid(row=1, column=0, sticky=E, pady=2, padx=2)
        self.txtUser = Entry(self.f, textvariable=self.usernamePreview)
        self.txtUser.grid(row=1, column=1, pady=2, padx=2)

        self.lblKey = Label(self.f, text="Key: ")
        self.lblKey.grid(row=2, column=0, sticky=E, pady=2, padx=2)
        self.txtKey = Entry(self.f, textvariable=self.keyTxt, show="*")
        self.txtKey.grid(row=2, column=1, pady=2, padx=2)

        self.lblKey2 = Label(self.f, text="Confirm: ")
        self.lblKey2.grid(row=3, column=0, sticky=E, pady=2, padx=2)
        self.txtKey2 = Entry(self.f, textvariable=self.keyTxt2, show="*")
        self.txtKey2.grid(row=3, column=1, pady=2, padx=2)
        self.f.grid(rowspan=2, columnspan=4)

        Button(self.master,
               width=15,
               text="Save Settings",
               command=self.saveSettings).grid(row=5, column=0, pady=4, padx=4)
        Button(self.master, width=15, text="Exit",
               command=self.master.destroy).grid(row=5,
                                                 column=1,
                                                 pady=4,
                                                 padx=4)

        self.master.focus_set()
        self.master.grab_set()
        self.root.wait_window(self.master)

        self.master.mainloop()
Exemplo n.º 19
0
def add_textpad():
    new_tp = ScrolledText(root, height=HEIGHT)
    new_tp.grid(row=len(text_pads))
    text_pads.append(new_tp)
Exemplo n.º 20
0
def construct():

    sample_prog = '''int main (void)
{
    int x;
    int y;

    x = (1 + 2) * (3 / 4);
    y = 1 + 2 * 3 - 4 / 5;

    return x + y;
}'''

    def callback():

        input = inputBox.get(1.0, END)

        # Lexical tab
        message, output, tokens = lexical(input)
        lexTab = tabs['Lexical']
        lexTab.configure(state=NORMAL)
        lexTab.delete(1.0, END)
        lexTab.insert(INSERT, message + output)
        lexTab.configure(state=DISABLED)

        # Syntax tab
        message, output, root, syn_pass = syntax(tokens)
        synTab = tabs['Syntax']
        synTab.configure(state=NORMAL)
        synTab.delete(1.0, END)
        synTab.insert(INSERT, message + output)
        synTab.configure(state=DISABLED)

        # Semantics tab
        if syn_pass:
            message = semantic(root)
        else:
            message = "Couldn't perform semantic analysis"
        semTab = tabs['Semantics']
        semTab.configure(state=NORMAL)
        semTab.delete(1.0, END)
        semTab.insert(INSERT, message)
        semTab.configure(state=DISABLED)

    master = Tk()
    master.title("C- Compiler")

    # Frames
    buttonFrame = Frame(master)
    buttonFrame.grid(row=1, column=1)

    # Labels
    Label(master, text="Input").grid(row=0, column=0)
    Label(master, text="Output").grid(row=0, column=1)

    # Buttons
    compileButton = Button(buttonFrame, text='Compile', command=callback)
    compileButton.grid(row=0, column=0)

    # Text Boxes
    inputBox = ScrolledText(master, width=50, height=40)
    inputBox.grid(row=2, column=0)
    inputBox.insert(INSERT, sample_prog)

    # Notebook to hold tabs
    notebook = ttk.Notebook(master)
    notebook.grid(row=2, column=1)
    tabs = {"Lexical": [], "Syntax": [], "Semantics": []}
    tab_order = ["Lexical", "Syntax", "Semantics"]

    for tabname in tab_order:
        tab = ScrolledText(notebook, width=50, height=40)
        tab.configure(state=DISABLED)
        tabs[tabname] = tab
        notebook.add(tab, text=tabname)

    master.mainloop()
test2_label.config(bg='White', fg='Black')
test2_label.grid(row=1,column=1, padx=20,pady=20,sticky=W)
test2 = Entry(root)
test2.config(bg='White',fg='Black')
test2.grid(row=1,column=2,columnspan=2,padx=5,pady=5,sticky=W)
test_label = Label(root, text="Enter time period")
test_label.config(bg='White', fg='Black')
test_label.grid(row=2,column=1, padx=20,pady=20,sticky=W)
v=StringVar()
r1=Radiobutton(root, text="Today", variable=v, value=" today ",indicatoron = 0)
r1.config(bg='White', fg='Black')
r1.grid(row=2,column=2)
r2=Radiobutton(root, text="Lastweek", variable=v, value="lastweek",indicatoron = 0)
r2.config(bg='White', fg='Black')
r2.grid(row=3,column=2)


bn1 = Button(root, text="Analyse", command=btn)
# bn1.config(bg='White', fg='Black')
bn1.grid(row=4,column=1,padx=50,pady=20,sticky=W)

bn3 = Button(root, text="clear console", command=gen)
# bn3.config(bg='White', fg='Black')
bn3.grid(row=4,column=2,padx=50,pady=5,sticky=E)
textPad = ScrolledText(root, width=110, height=25,bg='White',fg='Black')
# textPad.config(,anchor=E,justify=LEFT)
textPad.grid(row=6,column=1,columnspan=3,padx=5,pady=10,sticky=W)
#,rowspan=4

root.mainloop()
Exemplo n.º 22
0
class GuiPart:
    def __init__(self, master, queue, queue2, endCommand):
        self.queue = queue
        self.queue2 = queue2
        self.msg = ""
        self.targetpics = []
        self.currentImage = -1
        
        # Set up the GUI
        console = Tkinter.Button(master, text='Done', command=endCommand)
        console.grid(row=3, column=1, sticky=Tkinter.W)

        #Telemetry Window
        self.tele = ScrolledText(master, width=50, height=10, wrap='word')
        self.tele.insert('end', 'Awaiting Telemetry...\n----------------------\n')
        self.tele.grid(row=0, column=1, columnspan=1, padx=5, pady=5)

        #Receiving Targets Window
        self.rt = ScrolledText(master, width=50, height=10, wrap='word')
        self.rt.insert('end', 'Awaiting Target Data...\n------------------------\n')
        self.rt.grid(row=0, column=3, columnspan=2, padx=5, pady=5)

        #Image
        img = Tkinter.PhotoImage(file="logo.gif")
        logo = Tkinter.Label(master, image = img)
        logo.image=img
        logo.grid(row=0, column=2, padx=5, pady=5)

        #Obstacles Button
        obs_but = Tkinter.Button(master, text='Retreive Obstacles From Server', command=self.getObstacles)
        obs_but.grid(row=1, column=1, sticky=Tkinter.W)

        #General Terminal Button
        gt_but = Tkinter.Button(master, text='Submit Data', command=endCommand)
        gt_but.grid(row=1, column=2, sticky=Tkinter.W)

        #Upload Targets Button
        ut_but = Tkinter.Button(master, text='Upload Target Data', command=self.uploadTarget)
        ut_but.grid(row=1, column=3, columnspan=2, sticky=Tkinter.W)

        #Receiving Obstacles Window
        self.obs = ScrolledText(master, width=50, height=10, wrap='word')
        self.obs.insert('end', 'Ready for Obstacle Data...\n--------------------------\n')
        self.obs.grid(row=2, column=1, columnspan=1, padx=5, pady=5)

        #General Terminal Window
        self.gt = ScrolledText(master, width=50, height=10, wrap='word')
        self.gt.insert('end', 'Enter in Server Query...\n------------------------\n')
        self.gt.grid(row=2, column=2, columnspan=1, padx=5, pady=5)

        #Upload Targets Window
        #self.ut = ScrolledText(master, width=50, height=10, wrap='word')
        #self.ut.insert('end', 'Enter in Target Data...\n------------------------\n')
        
        target_label_text = ["Target Type:    ","Latitude: ","Longitude:  ","Orientation:", \
                           "Shape: ", "BG Color: ", "Letter/#:  ","Letter/# Color: "]
        targetlabelpane = Tkinter.PanedWindow(orient=Tkinter.VERTICAL)
        for i in target_label_text:
            targetlabelpane.add(Tkinter.Label(master, text=i,pady=3))
        targetlabelpane.grid(row=2, column=3,sticky=Tkinter.W)
        
        # Use combobox if user entry is also required
        # Here we use optionmenu
        self.available_target_type = Tkinter.StringVar() #["standard", "qrc", "off_axis", "emergent"]
        self.available_target_type.set("standard")
        self.available_orientation = Tkinter.StringVar() #["N","E","S","W","NE","SE","SW","NW"]
        self.available_orientation.set("N")
        self.available_shapes = Tkinter.StringVar()      #["circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross"]
        self.available_shapes.set("circle")
        self.available_bg_colors = Tkinter.StringVar()   #["white","black","gray","red","blue","green","yellow","purple","brown","orange"]
        self.available_bg_colors.set("white")
        self.available_alpha_colors = Tkinter.StringVar()
        self.available_alpha_colors.set("white")

        '''
        drop_target_type = Tkinter.OptionMenu(master,available_target_type,"standard", "qrc", "off_axis", "emergent")
        entry_lat = Tkinter.Entry(master, bd=5, width=70)
        entry_lon = Tkinter.Entry(master, bd=5, width=70)
        drop_orientation = Tkinter.OptionMenu(master,available_orientation,"N","E","S","W","NE","SE","SW","NW")
        drop_shapes = Tkinter.OptionMenu(master,available_shapes,"circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross")
        drop_bg_colors = Tkinter.OptionMenu(master,available_bg_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange")
        entry_alphanum = Tkinter.Entry(master, bd=5, width=70)
        drop_alpha_colors= Tkinter.OptionMenu(master,available_alpha_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange")
        '''
        
        targetpane = Tkinter.PanedWindow(orient=Tkinter.VERTICAL)
        targetpane.add(Tkinter.OptionMenu(master,self.available_target_type,"standard", "qrc", "off_axis", "emergent"))
        self.entry_lat = Tkinter.Entry(master, width=10)
        targetpane.add(self.entry_lat)
        self.entry_lon = Tkinter.Entry(master,width=10)
        targetpane.add(self.entry_lon)
        targetpane.add(Tkinter.OptionMenu(master,self.available_orientation,"N","E","S","W","NE","SE","SW","NW"))
        targetpane.add(Tkinter.OptionMenu(master,self.available_shapes,"circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross"))
        targetpane.add(Tkinter.OptionMenu(master,self.available_bg_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange"))
        self.entry_alphanum = Tkinter.Entry(master, width=10)
        targetpane.add(self.entry_alphanum)
        targetpane.add(Tkinter.OptionMenu(master,self.available_alpha_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange"))
    
        targetpane.grid(row=2, column=3, padx=5, pady=5)

        #General Terminal Text Area
        self.gt_text = Tkinter.Entry(master,width=70)
        self.gt_text.grid(row=3, column=2, columnspan=1, padx=5, pady=5)

        #Target Picture Buttons
        pane = Tkinter.PanedWindow()
        rti_prev = Tkinter.Button(master, text='Prev Picture', command=self.prevPic)
        pane.add(rti_prev)
        self.rti_label = Tkinter.Label(master, text='Awaiting Target')
        rti_next = Tkinter.Button(master, text='Next Picture', command=self.nextPic)
        pane.add(rti_next)
        pane.add(self.rti_label)
        pane.grid(row=4, column=2, padx=5, pady=5)

        '''
        #Target Images
        rtimg = Tkinter.PhotoImage(file="target.gif")
        self.rti = Tkinter.Label(master, image = rtimg)
        self.rti.image=rtimg
        self.rti.grid(row=5, column=2, columnspan=1, padx=5, pady=5)
        '''
        # User credentials field
        cred_label_text = ['Server IP:    ','Username: '******'Password:  '******'Login', command=self.loginWithCred)
        self.cred_but.grid(row=8, column=1, columnspan=1, padx=5, pady=5)
        # Add more GUI stuff here

    def processIncoming(self):
        """
        Handle all the messages currently in the queue (if any).
        """
        #self.counter = 0
        #self.queue.put('asdas')
        while self.queue.qsize():
            try:
                self.msg = str(self.queue.get(0)) + '\n'
                # Check contents of message and do what it says
                # As a test, we simply print it
                self.tele.insert('end', self.msg)
                if(float(self.tele.index('end')) > 11.0):
                    self.tele.delete('1.0','end')
                self.msg2 = self.queue2.get(0) + '\n'
                #print self.msg2
                if(self.msg2.find('Target') == 0):
                    #self.targetpics[self.counter] = self.msg2
                    self.targetpics.append(self.msg2)
                    #self.counter += 1
                else:
                    self.rt.insert('end', self.msg2)
            except Queue.Empty:
                pass
    
    def getObstacles(self):
        # GET obstacles request

        c = pycurl.Curl()

        buffer = StringIO()
        c.setopt(pycurl.URL, interop_api_url+'obstacles')
        c.setopt(pycurl.WRITEDATA, buffer)
        c.setopt(pycurl.COOKIEFILE, 'sessionid.txt')
        c.perform()

        obstacles_json = json.loads(buffer.getvalue())

        print("\n\n" + "====Obstacles====")
        obstacles = json.dumps(obstacles_json, sort_keys=True,indent=4, separators=(',', ': '))
        print obstacles
        self.obs.insert('end', obstacles)
    
    def nextPic(self):
        if(self.currentImage < len(self.targetpics) - 1):
            self.currentImage += 1
            self.nextImage = Tkinter.PhotoImage(file='Photos/' + self.targetpics[self.currentImage].strip())
            self.rti.configure(image=self.nextImage)
            self.rti.image = self.nextImage
            self.rti_label.configure(text=self.targetpics[self.currentImage].strip())

    def prevPic(self):
        if(self.currentImage > 0):
            self.currentImage -= 1
            self.nextImage = Tkinter.PhotoImage(file='Photos/' + self.targetpics[self.currentImage].strip())
            self.rti.configure(image=self.nextImage)
            self.rti.image = self.nextImage
            self.rti_label.configure(text=self.targetpics[self.currentImage].strip())

    def loginWithCred(self):
        global interop_api_url
        interop_api_url = "http://"+self.cred_text[0].get()+"/api/"
        #print interop_api_url
        c = pycurl.Curl()
        c.setopt(pycurl.URL, interop_api_url+'login')
        c.setopt(pycurl.POSTFIELDS, 'username='******'&password='******'sessionid.txt')
        c.perform()

    def uploadTarget(self):
        global interop_api_url
        target_data_dict = { \
            "type": self.available_target_type.get(), \
            "latitude": float(self.entry_lat.get()), \
            "longitude": float(self.entry_lon.get()), \
            "orientation": self.available_orientation.get(), \
            "shape": self.available_shapes.get(), \
            "background_color": self.available_bg_colors.get(), \
            "alphanumeric": self.entry_alphanum.get(), \
            "alphanumeric_color": self.available_alpha_colors.get(), \
        }
        json_target_data = json.dumps(target_data_dict)
        c = pycurl.Curl()
        c.setopt(pycurl.URL, interop_api_url+'targets')
        c.setopt(pycurl.POSTFIELDS, json_target_data)
        c.setopt(pycurl.COOKIEFILE, 'sessionid.txt')
        c.perform()
Exemplo n.º 23
0
	def initialisation(self):
		global input_pipe
		global output_pipe

		if len(sys.argv) > 2 :
			print 'output_pipe : ', output_pipe
		global ChaineALire
		global st
		global fp
		global colorbox
		global sortieTube
		global entreeTube



		texte = """ Welcome in GUI for ARINC 653 emulator 
"""

		#on cree un fenetre principale 'fp' a� partir du 'modele' Tk   
		#fp = Tk()
		self.title('ARINC 653 Partition')	

		#Declaration du texte deroulant dans 'fp'
		st = ScrolledText(self,wrap="word")
		st.grid(column=1,columnspan=2,rowspan=2,sticky='nw')

		#Creation d'un panneau 'menu_bottom' insere dans 'fp'
#		menu_bottom = Frame(self,borderwidth=2)
#		menu_bottom.grid(column=1,columnspan=3,sticky='sw')

		##Creation d'une etiquette inseree dans 'menu_bottom'
		#etiquette = Label(menu_bottom,text = 'Commande : ')
		#etiquette.grid(row=1,column=1,sticky='w')

		##Creation d'un boutton dans 'menu_bottom'
		#b = Button(menu_bottom,text='execute',command=self.affiche_commande)
		#b.grid(row=1,column=3,sticky='e')

		##Creation d'un boite d'edition dans 'nenu_top'
		#entre = Entry(menu_bottom,width=20,relief='sunken')
		#entre.insert(END,'Texte a afficher')
		#entre.grid(row=1,column=2,sticky='ew')
			
		#Creation d'une etiquette inseree
		etiquette = Label(self,text = 'Command : ')
		etiquette.grid(row=2,column=0,sticky='w')			
		
		#Creation d'un boutton
		b = Button(self,text='execute',command=self.affiche_commande)
		b.grid(row=2,column=2,sticky='e')

		#Creation d'un boite d'edition dans 'nenu_top'
		entre = Entry(self,width=20,relief='sunken')
		entre.insert(END,'Text to send')
		entre.grid(row=2,column=1,sticky='ew')
		
		partitionbox = Label(self ,text = 'Active partition : ')
		partitionbox.grid(column=0,row=0,sticky='n')
		
		self.labelVariable = StringVar()
		self.backcolorlabel = StringVar()
		self.frontcolorlabel = StringVar()
		self.backcolorlabel = "LightBlue"
		self.frontcolorlabel = "Black"
		label = Label(self,textvariable=self.labelVariable,
			anchor="w",fg=self.frontcolorlabel,bg=self.backcolorlabel,height=28)
		label.grid(column=0,row=1,sticky='EW')
		


		#on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
		st.insert(END,texte)
		#on applique a� tout le texte la police par defaut
		st.config(font = 'Arial 12')
		st.config(foreground='Black')
		#on configure le fond du 'texte derouant'
		st.config(background='LightBlue')
		#e = Entry(st,width=25)


		self.grid_columnconfigure(1,weight=1)
		self.rowconfigure(1,weight=1)
		
		self.resizable(False,True)
		self.update()
		self.geometry(self.geometry())
		
		try:
			assert input_pipe != ''
		
		except AssertionError:
			showerror('error', "no pipe choosed")
			input_pipe = tkFileDialog.askopenfilename(title='Choose the input pipe to open', defaultextension ='.fifo')

		#openning the INPUT pipe
		try:
			assert input_pipe != ''	

			try :

	#			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
				sortieTube = os.open(input_pipe,os.O_RDONLY)
				if sortieTube == -1 :
					raise ValueError
			except ValueError :		
				showerror('Error', "fail to open the Input pipe's output")
		except AssertionError:
			showerror("Error", "You must choose a pipe first")


		#openning the OUTPUT pipe
		if len(sys.argv) > 2 : #if an output pipe was given as the second argument
			try:
				assert output_pipe != ''

				#opening the pipe
				try :
					entreeTube = os.open(output_pipe,os.O_WRONLY)
			
					if entreeTube == -1 :
						raise ValueError
				except ValueError :
					showerror('Error', "Could not open Output pipe")
			except AssertionError:
				showerror("Error", "You must choose an output pipe first")
				output_pipe = tkFileDialog.askopenfilename(title='Choose the output pipe to open', defaultextension ='.fifo')	
Exemplo n.º 24
0
v = sys.version

from Tkinter import *
import tkFileDialog
from ScrolledText import *

root = Tk("Text Editor")
text = ScrolledText(root)

# add some color fam
text.configure(background='black')
text.configure(insertbackground='green')
text.configure(foreground='green')
text.configure(font=("Courier", 12))
text.grid()


# Saving a file
def saveas():
    global text
    t = text.get("1.0", "end-1c")
    #savelocation = raw_input("> ")
    savelocation = tkFileDialog.asksaveasfilename()
    file1 = open(savelocation, "w+")
    file1.write(t)
    file1.close()


# Open a file function
def open1():
Exemplo n.º 25
0
class TextEditor(EventBasedAnimationClass):

    @staticmethod
    def make2dList(rows, cols):
        # From 15-112 class notes
        a=[]
        for row in xrange(rows): a += [[0]*cols]
        return a

    @staticmethod
    def readFile(filename, mode="rt"):
        # From 15-112 class notes
        # rt = "read text"
        with open(filename, mode) as fin:
            return fin.read()

    @staticmethod
    def writeFile(filename, contents, mode="wt"):
        # From 15-112 class notes
        # wt = "write text"
        with open(filename, mode) as fout:
            fout.write(contents)


    def highlightError(self, lineNumber):
        # highlights error in the code based on line number
        self.textWidget.tag_remove("error",1.0,END)
        self.textWidget.tag_add("error", "%d.0"%lineNumber,
            "%d.end"%lineNumber)
        self.textWidget.tag_config("error", underline = 1)

    def colorIsBlack(self, color):
        # ranks whether a color is nearing black or white
        color = color[1:]
        count = int(color,16)
        if(count<(16**len(color) -1 )/2):
            return True
        return False

    def styleTokens(self,tokenisedText,colorScheme,
                    startIndex,seenlen,seenLines,flag):
        # apply style to tokens in the text
        for token in tokenisedText:
            styleForThisToken = colorScheme.style_for_token(token[0])
            if(styleForThisToken['color']):
                self.currentColor = "#" + styleForThisToken['color'] 
            else:
                if(self.colorIsBlack(colorScheme.background_color)):
                    self.currentColor = "White"
                else: self.currentColor = "Black"
            if(token[1] == "\n"): seenLines += 1
            if(seenLines > 23 and flag): break
            # the '#' is to denote hex value
            textWidget = self.textWidget
            newSeenLen = seenlen + len(token[1])
            textWidget.tag_add(startIndex+"+%dc"%seenlen,
                startIndex+"+%dc"%(seenlen),
                startIndex+"+%dc"%(newSeenLen))
            self.textWidget.tag_config(startIndex+"+%dc"%seenlen,
                foreground = self.currentColor)
            seenlen = newSeenLen

    def checkErrors(self):
        # checks whether there is an error in the code by parsing it
        # and analysing the traceback
        errors = MyParse().pythonCodeContainsErrorOnParse(self.currentText)
        if(errors[0]):
            try:
                lineNumber=int(errors[1][-5][errors[1][-5].find("line ")+5:])
            except:
                lineNumber=int(errors[1][-7][errors[1][-7].find("line ")+5:])
            self.highlightError(lineNumber)
        else:
            self.textWidget.tag_remove("error",1.0,END)

    def highlightText(self,lineCounter = "1",columnCounter = "0",flag = False):
        # highlight text since syntax mode is on
        text = self.currentText.split("\n")
        text = "\n".join(text[int(lineCounter)-1:])
        startIndex = lineCounter + "." + columnCounter
        seenlen, seenLines = 0,0
        tokenisedText = pygments.lex(text, self.lexer)
        if(self.colorScheme):
            colorScheme = pygments.styles.get_style_by_name(self.colorScheme)
        else:
            colorScheme = pygments.styles.get_style_by_name(
                self.defaultColorScheme)
        if(self.colorIsBlack(colorScheme.background_color)):
            self.insertColor = "White"
        else: self.insertColor = "Black"
        self.textWidget.config(background = colorScheme.background_color,
            highlightbackground = colorScheme.highlight_color,
            highlightcolor = colorScheme.highlight_color,
            insertbackground = self.insertColor)
        self.styleTokens(tokenisedText,colorScheme,startIndex,seenlen,
            seenLines, flag)
        if(self.fileExtension == ".py" and self.errorDetectionMode):
            self.checkErrors()

    def editDistance(self,currentWord, word):
        # wagner-fischer algorithm for calculating levenshtein distance
        dp = TextEditor.make2dList(len(currentWord)+1, len(word)+1)
        costOfInsertion = 1
        costOfDeletion = 1
        costOfSubstitution = 1
        for i in xrange(len(currentWord)+1):
            dp[i][0] = i*costOfInsertion
        for i in xrange(len(word)+1):
            dp[0][i] = i*costOfDeletion
        for i in xrange(1,len(currentWord)+1):
            for j in xrange(1,len(word)+1):
                if(currentWord[i-1] == word[j-1]):
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i][j-1]+costOfInsertion,
                            dp[i-1][j]+costOfDeletion,dp[i-1][j-1] + 
                            costOfSubstitution)
        return dp[len(currentWord)][len(word)]

    def wordsAreSimilar(self, currentWord, word):
        if(word.startswith(currentWord)):
            return True, abs(len(currentWord)-len(word))/2
        similarity = self.editDistance(currentWord, word)
        return float(similarity)/len(currentWord)<=.5,similarity 

    def cleanWord(self, word):
        # cleans a word by removing all not (char or numbers)
        processedWord = ""
        for c in word:
            if(c in string.ascii_uppercase or
                c in string.ascii_lowercase or 
                c in "1234567890"):
                processedWord += c
        return processedWord

    def sortSuggestionDict(self):
        # sorts suggestion dictionary
        self.suggestionDict = sorted(self.suggestionDict.items(),
             key=operator.itemgetter(1))

    def findMatchesToWord(self, currentWord):
        # checks words in current text and adds them to suggestionDict
        # based on whether they are similar or not
        if(currentWord == ""): return []
        listOfWords = self.currentText.split()
        for word in listOfWords:
            word = self.cleanWord(word)
            if word!= currentWord[:-1]:
                similar = self.wordsAreSimilar(currentWord, word)
                if(similar[0] and word not in self.suggestionDict):
                    self.suggestionDict[word] = similar[1]
        self.sortSuggestionDict
        return self.suggestionDict

    def getCurrentWord(self):
        # gets current word user is typing
        word = self.textWidget.get(self.textWidget.index("insert wordstart"), 
            self.textWidget.index("insert wordend"))
        if(word == "\n" or word == " "):
            word = self.textWidget.get(
                self.textWidget.index("insert -1c wordstart"), 
                self.textWidget.index("insert wordend"))
        word = word.replace("\n","")
        return word

    def openFile(self):
        # opens a file, also detects whether it is 
        # a program or not
        self.initProgrammingModeAttributes()
        path = tkFileDialog.askopenfilename()
        if(path):
            self.currentFilePath = path
            self.currentFile = os.path.basename(path)
            self.currentText = TextEditor.readFile(path)
            self.textWidget.delete(1.0,END)
            self.textWidget.insert(1.0,self.currentText)
            self.fileExtension = os.path.splitext(path)[1]
            self.root.wm_title(self.currentFile)
            if(self.fileExtension != ".txt" and
                pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])):
                self.programmingMode = True
                self.lexer = pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])
                self.highlightText()

    def saveFile(self):
        if(self.currentFilePath):
            TextEditor.writeFile(self.currentFilePath, self.currentText)

    def saveAs(self):
        # saves a file, automatically adds extension
        path = tkFileDialog.asksaveasfilename()
        if(path):
            if(self.fileExtension): path += self.fileExtension
            else: path += ".txt"
            TextEditor.writeFile(path, self.currentText)
            self.currentFilePath = path
            self.currentFile = os.path.basename(path)
            self.root.wm_title(self.currentFile)
            if(self.fileExtension !=".txt" and
                pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])):
                self.programmingMode = True
                self.lexer = pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])
                self.highlightText()

    def newTab(self):
        TextEditor(1500,50).run()

    def undo(self):
        self.textWidget.edit_undo()

    def redo(self):
        self.textWidget.edit_redo()

    def cut(self):
        if self.textWidget.tag_ranges("sel"):
            self.clipboard = self.textWidget.get("sel.first","sel.last")
            self.textWidget.delete("sel.first","sel.last")
        else:
            self.clipboard = ""

    def copy(self):
        if self.textWidget.tag_ranges("sel"):
            self.clipboard = self.textWidget.get("sel.first","sel.last")

    def paste(self):
        if self.textWidget.tag_ranges("sel"):
            self.textWidget.insert("insert",self.clipboard)

    def resetFontAttribute(self):
        self.font = tkFont.Font(family = self.currentFont,
            size = self.fontSize)
        self.textWidget.config(font = self.font)

    def increaseFontSize(self):
        self.fontSize += 2
        self.resetFontAttribute()

    def decreaseFontSize(self):
        self.fontSize -= 2
        self.resetFontAttribute()

    def highlightString(self,searchString):
        lenSearchString = len(searchString) 
        self.textWidget.tag_delete("search")
        self.textWidget.tag_config("search", background = "#FFE792")
        start = 1.0
        while True:
            pos = self.textWidget.search(searchString, start, stopindex = END)
            if(not pos):
                break
            self.textWidget.tag_add("search", pos, pos+"+%dc"%(lenSearchString))
            start = pos + "+1c"

    # search highlight color #FFE792
    def searchInText(self):
        title = "Search"
        message = "Enter word to search for"
        searchString = tkSimpleDialog.askstring(title,message)
        if(searchString == None): return
        self.highlightString(searchString)

    def commentCode(self):
        # puts an annotation in the currently selected text
        title = "Comment"
        message = "Enter comment for selection"
        comment = tkSimpleDialog.askstring(title,message)
        if(comment == None): return
        if self.textWidget.tag_ranges("sel"):
            self.textWidget.tag_add("comment",
                self.textWidget.index(SEL_FIRST),
                self.textWidget.index(SEL_LAST))
            self.textWidget.tag_config("comment", underline = 1)
            self.comments += [self.textWidget.index(SEL_FIRST) + "|" +
                self.textWidget.index(SEL_LAST) + "|" + comment]
            if(self.collaborativeCodingMode):
                # can only send strings through socket 
                self.client.sendData(";".join(self.comments))

    def findAndReplaceInText(self):
        # finds and replaces a word
        title = "Find and replace"
        message = "Enter string to remove"
        stringToRemove = tkSimpleDialog.askstring(title,message)
        if(stringToRemove == None): return
        message = "Enter string to add"
        stringToReplace = tkSimpleDialog.askstring(title, message)
        if(stringToReplace == None): return
        self.currentText = self.currentText.replace(
            stringToRemove, stringToReplace)
        self.textWidget.delete(1.0, END)
        self.textWidget.insert(1.0, self.currentText)
        self.highlightString(stringToReplace)

    def initTextWidget(self):
        # initialises text widget
        # used the below link to make it stop resizing on font change
        # http://stackoverflow.com/questions/9833698/
        # python-tkinter-how-to-stop-text-box-re-size-on-font-change
        self.textWidgetContainer = Frame(self.root, borderwidth = 1,
            relief = "sunken", width = 600, height = 400)
        self.textWidgetContainer.grid_propagate(False)
        self.textWidgetContainer.pack(side = TOP, fill = "both", expand = True)
        self.textWidgetContainer.grid_rowconfigure(0, weight=1)
        self.textWidgetContainer.grid_columnconfigure(0, weight=1)
        self.textWidget = ScrolledText(self.textWidgetContainer, 
            width = 10,
            font = self.font,
            background =self.textWidgetBackGround)
        self.textWidget.grid(row = 0, column = 0, sticky = "nsew")
        self.textWidget.config(insertbackground = self.cursorColor,
            foreground = self.textWidgetDefaultFontColor,
            tabs = ("%dc"%self.tabWidth,"%dc"%(2*self.tabWidth)),
            undo = True)

    def initFont(self):
        self.currentFont = "Arial"
        self.fontSize = 15
        self.font = tkFont.Font(family = self.currentFont, 
            size = self.fontSize)

    def initProgrammingModeAttributes(self):
        self.programmingMode = False
        self.errorDetectionMode = False
        self.colorScheme = None
        self.defaultColorScheme = "monokai"
        self.lexer = None

    def initMoreGeneralAttributes(self):
        self.hostingServer = False
        self.hostIP = None
        self.joinedServerIP = None
        self.server = None
        self.client = None
        self.spellCorrector = SpellCorrector()
        self.root.wm_title("Untitled")
        self.commentButX = self.width - 300
        self.commentButY = 10
        self.commentButWidth = 200
        self.commentButHeight = self.height - 10

    def initGeneralAttributes(self):
        # general editor attributes
        self.currentText,self.tabWidth = "",1
        self.rulerWidth,self.currentFilePath = None,None
        self.currentFile = None
        self.fileExtension = None
        self.suggestionDict = dict()
        self.indentationLevel = 0
        self.prevChar = None
        self.spellCorrection = False
        self.clipboard = ""
        self.comments = ["comments"]
        self.collaborativeCodingMode = False
        self.insertColor = "Black"
        self.initMoreGeneralAttributes()

    def initTextWidgetAttributes(self):
        self.textWidgetBackGround = "White"
        self.textWidgetDefaultFontColor = "Black"
        self.textWidgetTabSize = ""
        self.cursorColor = "Black"

    def initAttributes(self):
        self.initGeneralAttributes()
        self.initFont()
        self.initProgrammingModeAttributes()
        self.initTextWidgetAttributes()

    def addEditMenu(self):
        self.editMenu = Menu(self.menuBar, tearoff = 0)
        self.editMenu.add_command(label = "Undo", command = self.undo)
        self.editMenu.add_command(label = "Redo", command = self.redo)
        self.editMenu.add_command(label = "Cut", command = self.cut)
        self.editMenu.add_command(label = "Copy", command = self.copy)
        self.editMenu.add_command(label = "Paste", command = self.paste)
        self.editMenu.add_command(label = "Increase Font", 
            command = self.increaseFontSize)
        self.editMenu.add_command(label = "Decrease Font", 
            command = self.decreaseFontSize)
        self.menuBar.add_cascade(label = "Edit", menu = self.editMenu)

    def addFileMenu(self):
        self.fileMenu = Menu(self.menuBar, tearoff = 0)
        self.fileMenu.add_command(label = "Open", command = self.openFile)
        self.fileMenu.add_command(label = "New File", command = self.newTab)
        self.fileMenu.add_command(label = "Save", command = self.saveFile)
        self.fileMenu.add_command(label = "Save As", command = self.saveAs)
        self.menuBar.add_cascade(label = "File", menu = self.fileMenu)

    def setFileExtension(self, ext):
        # sets file extension
        self.fileExtension = ext
        self.programmingMode = True
        try:
            self.lexer = pygments.lexers.guess_lexer_for_filename("example%s"%self.fileExtension,[])
        except:
            self.lexer = pygments.lexers.guess_lexer_for_filename("example.py",[])
        self.highlightText()

    def setColorScheme(self, colorScheme):
        self.colorScheme = colorScheme
        self.programmingMode = True
        # assumes start from python
        if(not self.lexer):
            self.lexer = pygments.lexers.guess_lexer_for_filename("example.py",[])
            self.fileExtension = ".py"
        self.highlightText()

    # should have radio buttons for this
    def turnOnErrorDetection(self):
        self.errorDetectionMode = True
        self.setFileExtension(".py")

    def turnOffErrorDetection(self):
        self.errorDetectionMode = False

    def turnOnSpellCorrection(self):
        self.spellCorrection = True

    def turnOffSpellCorrection(self):
        self.spellCorrection = False

    def addErrorDetectionMenu(self):
        self.errorDetectionMenu = Menu(self.menuBar, tearoff = 0)
        self.errorDetectionMenu.add_command(label = "Python error detection ON",
            command = self.turnOnErrorDetection)
        self.errorDetectionMenu.add_command(label = "Python error detection OFF",
            command = self.turnOffErrorDetection)
        self.viewMenu.add_cascade(label = "Error Detection",
            menu = self.errorDetectionMenu)

    def addSpellCorrectionMenu(self):
        self.spellCorrectionMenu = Menu(self.menuBar, tearoff = 0)
        self.spellCorrectionMenu.add_command(label = "Spelling Correction ON",
            command = self.turnOnSpellCorrection)
        self.spellCorrectionMenu.add_command(label = "Spelling Correction OFF",
            command = self.turnOffSpellCorrection)
        self.viewMenu.add_cascade(label = "Spelling Correction",
            menu = self.spellCorrectionMenu)

    def addColorSchemeCommand(self, name):
        self.colorSchemeMenu.add_command(label = name,
                command = lambda : self.setColorScheme(name))

    def addColorSchemeMenu(self):
        # colorScheme Menu
        self.colorSchemeMenu = Menu(self.menuBar, tearoff = 0)
        self.addColorSchemeCommand("manni")
        self.addColorSchemeCommand("igor")
        self.addColorSchemeCommand("xcode")
        self.addColorSchemeCommand("vim")
        self.addColorSchemeCommand("autumn")
        self.addColorSchemeCommand("vs")
        self.addColorSchemeCommand("rrt")
        self.addColorSchemeCommand("native")
        self.addColorSchemeCommand("perldoc")
        self.addColorSchemeCommand("borland")
        self.addColorSchemeCommand("tango")
        self.addColorSchemeCommand("emacs")
        self.addColorSchemeCommand("friendly")
        self.addColorSchemeCommand("monokai")
        self.addColorSchemeCommand("paraiso-dark")
        self.addColorSchemeCommand("colorful")
        self.addColorSchemeCommand("murphy")
        self.addColorSchemeCommand("bw")
        self.addColorSchemeCommand("pastie")
        self.addColorSchemeCommand("paraiso-light")
        self.addColorSchemeCommand("trac")
        self.addColorSchemeCommand("default")
        self.addColorSchemeCommand("fruity")
        self.menuBar.add_cascade(label = "Color Scheme",
            menu = self.colorSchemeMenu)

    def addLanguageCommand(self, language, extension):
        self.syntaxMenu.add_command(label = language, 
            command = lambda : self.setFileExtension(extension))

    def addSyntaxMenu(self):
        self.syntaxMenu = Menu(self.menuBar, tearoff = 0)
        self.addLanguageCommand("Python",".py")
        self.addLanguageCommand("C++",".cpp")
        self.addLanguageCommand("Javascript",".js")
        self.addLanguageCommand("Java",".java")
        self.addLanguageCommand("HTML",".html")
        self.addLanguageCommand("CSS",".css")
        self.addLanguageCommand("PHP",".php")
        self.addLanguageCommand("Haskell",".hs")
        self.addLanguageCommand("Clojure",".clj")
        self.addLanguageCommand("CoffeeScript",".coffee")
        self.addLanguageCommand("AppleScript",".scpt")
        self.addLanguageCommand("Objective C",".h")
        self.addLanguageCommand("Scheme",".scm")
        self.addLanguageCommand("Ruby",".rb")
        self.addLanguageCommand("OCaml",".ml")
        self.addLanguageCommand("Scala",".scala")
        self.viewMenu.add_cascade(label = "Syntax", menu = self.syntaxMenu)
        self.menuBar.add_cascade(label = "View", menu = self.viewMenu)

    def addViewMenu(self):
        self.viewMenu = Menu(self.menuBar, tearoff = 0)
        # syntax Menu
        self.addSyntaxMenu()
        self.addColorSchemeMenu()
        self.addErrorDetectionMenu()
        self.addSpellCorrectionMenu()

    def displayMessageBox(self, title = "", text = ""):
        tkMessageBox.showinfo(title, text)

    def startServer(self):
        # starts a new thread running the server
        self.collaborativeCodingMode = True
        start_new_thread(self.server.acceptConnection(),())

    def startRecieving(self):    
        # starts a new thread to recieve data
        start_new_thread(self.client.recieveData,())

    def collaborateWrapper(self):
        # starts collaborative mode
        if(not self.collaborativeCodingMode):
            self.server = Server()
            host = self.server.getHost()
            self.hostingServer = True
            self.hostIP = host
            self.client = Client(host)
            start_new_thread(self.startServer,())
            start_new_thread(self.startRecieving,())
            self.client.sendData(";".join(self.comments))
            time.sleep(.01)
            self.client.sendData(self.currentText)

    def joinServer(self):
        # starts a new thread to recieve data
        start_new_thread(self.client.recieveData,())

    def joinServerWrapper(self):
        # join a server for collaboration
        if(not self.collaborativeCodingMode):
            try:
                self.collaborativeCodingMode = True
                title = "Host IP address"
                message = "Enter IP address of server to link to."
                host = tkSimpleDialog.askstring(title,message)
                if(host == None): 
                    self.collaborativeCodingMode = False
                    return       
                self.joinedServerIP = host
                self.client = Client(host)
                start_new_thread(self.joinServer,())
            except:
                self.collaborativeCodingMode = False
                self.joinedServerIP = None
                print "Server isn't running"
                self.displayMessageBox("Error","Server isn't running")

    def addNetworkMenu(self):
        self.networkMenu = Menu(self.menuBar, tearoff = 0)
        self.networkMenu.add_command(label = "Collaborate| Create new server", 
                                    command = self.collaborateWrapper)
        self.networkMenu.add_command(label = "Collaborate| Join server", 
                                    command = self.joinServerWrapper)
        self.menuBar.add_cascade(label = "Collaborative", 
                                menu = self.networkMenu)
        
    def addFindMenu(self):
        self.findMenu = Menu(self.menuBar, tearoff = 0)
        self.findMenu.add_command(label = "Search", command =self.searchInText)
        self.findMenu.add_command(label = "Find and Replace", 
            command = self.findAndReplaceInText)
        self.menuBar.add_cascade(label = "Find", menu = self.findMenu)

    def showHelp(self):
        self.helpCanvasRoot = Tk()
        self.helpCanvas = Canvas(self.helpCanvasRoot, width = 600, height = 600)
        self.helpCanvasRoot.wm_title("Collaborative Coder | Help")
        self.helpCanvas.pack()
        canvas = self.helpCanvas
        canvas.create_rectangle(0,0,600,600,fill="Grey")
        canvas.create_text(300,30,text = "Collaborative Coder!", 
            font = "Arial 30 bold italic underline")
        canvas.create_rectangle(8,48,592,596,fill = "White",
            width = 2)
        message = """
        1. Find all options on the top of the screen in the menu bar.
        2. There are two boxes on the screen which hold 
            comments and suggestions(Autocomplete and
            Spelling Correction) respectively.
            To choose a suggestion double click on it.
        3. To enable syntax highlighting choose the programming 
            language in View --> Syntax menu.
        4. Choose the color scheme you want in the color
            scheme menu.
        5. Press Command+B to compile python code.
        6. Turn on or off dynamic python error detection and 
           spelling correction from view menu.
        7. To collaborate with others you can either start a server
            or join a server
                1. To start a server click 
                    Collaboration --> Start New Server
                    This will display your IP address in the 
                    bottom which your friend will join.
                2. To join click Collaboration --> Join Server
                    Enter server IP you want to join
                    and click OK.
        8. To annotate select a piece of text and press 
            the comment button in the bottom right. When your cursor
            shows up in those indices the annotation will show
            up in the comments box.

        """
        canvas.create_text(10,50,text = message, anchor = "nw",
            fill = "Dark Blue", font = "Arial 18 bold")
        canvas.mainloop()

    def showAbout(self):
        self.aboutCanvasRoot = Tk()
        self.aboutCanvas = Canvas(self.aboutCanvasRoot, width = 600,height =670)
        self.aboutCanvasRoot.wm_title("Collaborative Coder | About")
        self.aboutCanvas.pack()
        self.aboutCanvas.create_rectangle(0,0,600,670,fill="Grey")
        self.aboutCanvas.create_text(300,30,text = "Collaborative Coder!", 
            font = "Arial 30 bold italic underline")
        self.aboutCanvas.create_rectangle(8,48,592,652,fill = "White",
            width = 2)
        message = """
        This is a text editor application made by Manik Panwar
        for the course 15-112 Fundamentals of programming and 
        computer science at Carnegie Mellon University,
        which you can use to edit text documents and write code.
        Not only can you do this on your own
        machine but you can also collaborate 
        with friends live on different computers 
        through the internet and edit the same 
        text documents; all the while commenting 
        and annotating the text which automatically 
        shows up on your friends computer.
        Apart from all the general text editor features 
        this also supports syntax highlighting for 
        all major languages, autocompletion(which show up 
        in the suggestion box), autoindenation,
        auto parentheses completion, spelling correction,
        dynamic python error detection, multiple text editor 
        color schemes and live collaboration with 
        others on other machines. For collaborating with 
        a friend you can either create a server and ask 
        your friends to join your server or
        join an already running server. All you have to 
        do now is choose a language from the syntax menu, 
        choose your color scheme and preferences, set up 
        collaboration with a friend, and get started on 
        that 15-112 inspired project you are now about to do!
        """
        self.aboutCanvas.create_text(10,50,text = message, anchor = "nw",
            fill = "Dark Blue", font = "Arial 18 bold")
        self.aboutCanvasRoot.mainloop()

    def addHelpMenu(self):
        self.helpMenu = Menu(self.menuBar, tearoff = 0)
        self.helpMenu.add_command(label = "Help", command = self.showHelp)
        self.helpMenu.add_command(label = "About", command = self.showAbout)
        self.menuBar.add_cascade(label = "Help", menu = self.helpMenu)

    def initListBox(self):
        self.suggestionBox = Listbox(self.root, width = 50,
                    height = 5,selectmode = SINGLE)
        self.scrollbar = Scrollbar(self.root, orient = VERTICAL)
        self.scrollbar.config(command = self.suggestionBox.yview)
        self.scrollbar.pack(side = RIGHT,fill = Y)
        self.suggestionBox.config(yscrollcommand = self.scrollbar.set,
            background = "Grey")
        self.suggestionBox.pack(side = RIGHT)
        self.suggestionBox.insert(END, "Suggestions(Autocomplete and Spelling correction):")

    def initCommentBox(self):
        self.commentBoxFontSize = 20
        self.commentBox = Listbox(self.root, width = 180,height = 5, 
                                    selectmode = SINGLE)
        self.commentScrollbar = Scrollbar(self.root, orient = VERTICAL)
        self.commentScrollbar.config(command = self.commentBox.yview)
        self.commentScrollbar.pack(side = RIGHT,fill = Y)
        self.commentBoxFont = tkFont.Font(family = self.currentFont,
            size = self.commentBoxFontSize)
        self.commentBox.config(yscrollcommand = self.commentScrollbar.set,
            background = "Grey", foreground = "Black",
            font = self.commentBoxFont)
        self.commentBox.pack(side = RIGHT, fill = X)
        self.commentBox.insert(END,"Comments (if any) in current cursor index:")

    def initMenuBar(self):
        # init menuBar
        self.menuBar = Menu(self.root)
        # file menu option
        self.addFileMenu()
        # Edit menu option
        self.addEditMenu()
        # Find menu option
        self.addFindMenu()
        # View menu option
        self.addViewMenu()
        # Network menu
        self.addNetworkMenu()
        # Help menu
        self.addHelpMenu()
        self.root.config(menu = self.menuBar)

    def onTabPressed(self, event):
        if(self.fileExtension == ".py"):
            self.indentationLevel += 1

    def bindEvents(self):
        self.textWidget.bind("<Tab>",lambda event: self.onTabPressed(event))
        self.suggestionBox.bind("<Double-Button-1>", 
                                lambda event: self.replaceWord(event))

    def indent(self):
        if(self.fileExtension == ".py"):
            self.textWidget.insert("insert","\t"*self.indentationLevel)

    def modifyIndent(self, event):
        # modifies indentation based on python rules
        if(self.fileExtension == ".py"):
            if(event.char == ":"): 
                self.indentationLevel += 1
            elif(event.keysym == "BackSpace"):
                line = self.textWidget.get("insert linestart","insert lineend")
                flag = True
                for c in line:
                    if not((c == " ") or (c == "\t")):
                        flag = False
                        break
                if(flag):
                    self.indentationLevel = (self.indentationLevel - 1 if 
                        self.indentationLevel>=1 else 0)

    def completeParens(self, event):
        # autocomplete parens
        if(event.char == "{" and self.programmingMode):
            self.textWidget.insert("insert","\n"+"\t"*self.indentationLevel+"}")
            self.currentText = self.textWidget.get(1.0,END)
        elif(event.char == "(" and self.programmingMode):
            self.textWidget.insert("insert",")")
            self.currentText = self.textWidget.get(1.0,END)

    def replaceWord(self,event):
        # replaces a word on double click in suggestion box
        word = self.getCurrentWord()
        self.textWidget.delete("insert - %dc"%(len(word)),"insert")
        wordToReplace = ""
        if(self.suggestionBox.curselection()):
            wordToReplace = self.suggestionBox.get(
                            self.suggestionBox.curselection())
            if(wordToReplace != "Suggestions(Autocomplete and Spelling correction):"):
                self.textWidget.insert("insert", wordToReplace)
            self.resetSuggestions()

    def calculateSuggestions(self):
        # populates suggestion box
        self.suggestionBox.delete(0,END)
        self.suggestionDict = dict()
        currentWord = self.getCurrentWord()
        self.findMatchesToWord(currentWord)
        self.suggestionBox.insert(END,
            "Suggestions(Autocomplete and Spelling correction):")
        for key in self.suggestionDict:
            self.suggestionBox.insert(END,key)
        if(self.spellCorrection):
            correctSpelling = self.spellCorrector.correct(currentWord)
            if(not currentWord.startswith(correctSpelling)):
                self.suggestionBox.insert(END, correctSpelling)

    def resetSuggestions(self):
        self.suggestionBox.delete(0,END)
        self.suggestionBox.insert(END, 
            "Suggestions(Autocomplete and Spelling correction):")
        self.suggestionDict = dict()

    def compilePythonCode(self):
        if(self.currentFile):
            self.saveFile()
            original_stdout = sys.stdout
            try:
                a = compiler.compile(self.currentText, self.currentFile, 
                                    mode = "exec")
                # (http://stackoverflow.com/questions/4904079/
                # execute-a-block-of-python-code-with-exec-capturing-all-its-output)
                # captures stdout in temp stringIO buffer to get output
                # and then reverts changes
                buffer = StringIO()
                sys.stdout = buffer
                eval(a)
                sys.stdout = original_stdout
                val = buffer.getvalue()
                rt = Tk()
                outputText = ScrolledText(rt, width = 50)
                outputText.insert(END, val)
                outputText.pack()
                rt.mainloop()
            except:
                print "Error!"
                self.displayMessageBox("Error","There is an error in the code.")
                sys.stdout = original_stdout
        else:
            self.saveAs()

    def getLineAndColFromIndex(self, index):
        return int(index.split('.')[0]),int(index.split('.')[1])

    def checkIfInCommonRange(self, comment):
        # check if insert is in range of any comment
        index = self.textWidget.index("insert")
        indexCStart = comment[0]
        indexCEnd = comment[1]
        line,col = self.getLineAndColFromIndex(index)
        line1,col1 = self.getLineAndColFromIndex(indexCStart)
        line2,col2 = self.getLineAndColFromIndex(indexCEnd)
        if((line>line1 and line<line2) or
            (line == line1 and col>=col1 and (line1!=line2 or col<=col2)) or 
            (line == line2 and col<=col2 and (line1!=line2 or col>=col1))):
            return True
        else:
            return False

    def checkComments(self):
        self.commentBox.delete(0,END)
        self.commentBox.insert(END,"Comments (if any) in current cursor index:")
        for comment in self.comments:
            if("|" in comment):
                comment = comment.split("|")
                if(self.checkIfInCommonRange(comment)):
                    self.commentBox.insert(END, comment[2])

    def onKeyPressed(self, event):
        ctrl  = ((event.state & 0x0004) != 0)
        shift = ((event.state & 0x0001) != 0)
        command = ((event.state & 0x0008) != 0)
        flag = False
        self.checkComments()
        if(self.textWidget.get(1.0,END)!=self.currentText):
            flag = True
        if(event.char.isalpha()):
            self.calculateSuggestions()
        if(event.keysym == "Return" and self.fileExtension == ".py"):
            self.indent()
        if(event.keysym in ["Return"," ","\n","\t","BackSpace","space"]):
            self.resetSuggestions()
        self.currentText = self.textWidget.get(1.0,END)
        self.modifyIndent(event)
        self.completeParens(event)
        if((flag) and self.collaborativeCodingMode):
            self.client.sendData(self.currentText)
        if(self.programmingMode):
            if((command and event.keysym in "vV")):
                self.highlightText()
            else:
                insertLineNumber = int(self.textWidget.index(
                                                    "insert").split(".")[0])
                self.highlightText(
                        str(insertLineNumber),"0", 
                        (event.keysym!="Return" and 
                        not self.collaborativeCodingMode)
                        ) 
        if(self.fileExtension == ".py" and command and event.keysym in "bB"):
            self.compilePythonCode()

    def onMousePressed(self, event):
        # remove search tag if it exists
        self.textWidget.tag_delete("search")
        self.checkComments()
        if((event.x>=self.commentButX) and 
            (event.x<=(self.commentButX + self.commentButWidth)) and
            (event.y>=self.commentButY) and 
            (event.y<=(self.commentButY + self.commentButHeight))):
            self.commentCode()

    def onTimerFired(self):
        pass

    def redrawAll(self):
        # draws info onto canvas
        self.canvas.delete(ALL)
        self.canvas.create_rectangle(0,0,self.width,self.height,fill = "Black")
        self.canvas.create_rectangle(self.commentButX,self.commentButY,
            self.commentButX+self.commentButWidth,
            self.commentButY+self.commentButHeight,fill = "Grey")
        self.canvas.create_text(self.commentButX + self.commentButWidth/2,
            self.commentButY + self.commentButHeight/2,text = "Comment")
        self.canvas.create_text(400,10,
            text = "Press help in the menu bar to get started", fill = "White")
        if(self.programmingMode):
            self.canvas.create_text(600,10,
                            text = "Programming mode on",fill="Green")
        if(self.errorDetectionMode):
            self.canvas.create_text(600,25,
                            text = "Error detection mode on",fill = "Green")
        if(self.spellCorrection):
            self.canvas.create_text(600,40,
                            text = "Spelling Correction on",fill = "Green")
        a = self.textWidget.index("insert")
        ln = int(a.split(".")[0])
        l = self.textWidget.get("insert linestart","insert")
        cn = 1
        for c in l:
            if(c == "\t"):
                cn += 4*self.tabWidth
            else:
                cn += 1
        self.canvas.create_text(100,10,text="Row:%d Column:%d"%(ln,cn),
                                fill = "White")
        self.canvas.create_text(850,30,text = "Collaborative Coder!",
            fill = "Grey", font = "Arial 30 bold")
        if(self.hostingServer):
            self.canvas.create_text(400,30,
                text = "Hosting server at IP: %s"%(self.hostIP),fill="White")
        elif(self.joinedServerIP):
            self.canvas.create_text(400,30,
                text = "Joined server at IP: %s"%(self.joinedServerIP),
                fill = "White")


    def initAnimation(self):
        self.timerCounter = 10000
        self.initAttributes()
        self.initTextWidget()
        self.initMenuBar()
        self.initListBox()
        self.initCommentBox()
        self.bindEvents()
Exemplo n.º 26
0
class UI:
        def print_message(self,msg):
                msg = msg + "\n"
                self.scrollview["state"] = NORMAL
                self.scrollview.mark_set("insert", "1.0")# 1 is line number , 0 is coloumn
                self.scrollview.insert(INSERT,msg) # or END can be used
                self.scrollview["state"] = DISABLED
                #self.scrollview.see(END)
                
	def __init__(self, myParent):
                self.mylist = [i for i in range(1,53)]
                self.display_cards(human_cards)
                self.button1 = Button(root)
                self.button1["text"]= "Fetch"    ### (2)
                self.button1.bind("<Button-1>", self.onFetchClick)
                self.button1.grid(row=1,column=10)
                self.scrollview = ScrolledText(root,width=10,height = 10,state = DISABLED)
                self.scrollview.grid(row=200,column=5)
                #self.scrollbar = Scrollbar(root) 
                #self.scrollbar.pack(side=RIGHT, fill=Y)
    

        def display_top_card(self,topc):
            self.image = Image.open("classic-cards/"+topc+".png")
            #self.image = self.image.rotate(45)
            #self.image = self.image.resize((100,200))
            self.photo = ImageTk.PhotoImage(self.image)
            self.label = Label(image=self.photo)
            self.label.image = self.photo # keep a reference!
            self.label.filename = topc
            self.label.grid(row=0,column=10)
            print "length of cards is " + str(len(comp_cards))
            self.leftlabel = Label(root,text= "PC has " + str(len(comp_cards)) + " cards",font = "Verdana 10 bold")
            self.leftlabel.grid(row=2,column=10)


        def display_cards(self,newlist):
                r = 0
                c = -1
                counter = 0 
                self.mywidgets=[]
                for i in newlist:
                        if counter%10 == 0:
                                r = r + 1
                                c = 0
                        else:
                                c = c + 1
                        counter = counter + 1
                        self.image = Image.open("classic-cards/"+str(i)+".png")
                        #self.image = self.image.rotate(45)
                        #self.image = self.image.resize((100,200))
                        self.photo = ImageTk.PhotoImage(self.image)
                        self.label = Label(image=self.photo)
                        self.label.image = self.photo # keep a reference!
                        self.label.filename = i
                        self.label.grid(row=r,column=c)
                        self.label.bind("<Button-1>", self.onClick)
                        self.mywidgets.append(self.label)

        def onFetchClick(self,event):
            global human_cards
            if len(carddeck) == 0:
                #TODO reshuffle completed and put them
                reorder_completed()
            card = getcard(carddeck)
            human_cards.append(card)
            self.destroyAll()
            self.display_cards(human_cards)
            play_computer(topcard)
            if len(comp_cards) == 0:
                    tkMessageBox.showinfo("Boooo", "You have lost :-( ")
                    quitfunc()
            self.display_top_card(topcard)

        def onClick(self,event):
                global human_cards,comp_cards,carddeck,topcard
                #self.mylist.remove(event.widget.filename)
                if(play_human(topcard,event.widget.filename)):
                    self.destroyAll()
                    self.display_cards(human_cards)
                    if len(human_cards) == 0:
                        tkMessageBox.showinfo("Crazy", "You have won!!!")
                        quitfunc()
                    play_computer(topcard)
                    print str(len(comp_cards)) + " before modify"
                    if len(comp_cards) == 0:
                        tkMessageBox.showinfo("Boooo", "You have lost :-( ")
                        quitfunc()
                    self.display_top_card(topcard)
                
                

        def destroyAll(self):
                for i in self.mywidgets:
                        i.destroy()
Exemplo n.º 27
0
cheatSheetBtn = Button(mainframe, text='Cheat Sheet', command=openCheatSheet)
cheatSheetBtn.grid(column=1, row=0, sticky=(W, E))

regexVar = StringVar()
regexEntry = Entry(mainframe, width=7, textvariable=regexVar)
regexEntry.grid(column=0, row=1, sticky=(W, E), columnspan=2)

row2Label = Label(mainframe, text='"""')
row2Label.grid(column=0, row=2, sticky=(W, E), columnspan=2)

row3Label = Label(mainframe, text='>>> haystack_string = r"""')
row3Label.grid(column=0, row=3, sticky=(W, E), columnspan=2)

haystackVar = StringVar()
haystackEntry = ScrolledText(mainframe, width=7, height=5)
haystackEntry.grid(column=0, row=4, sticky=(W, E), columnspan=2)

row5Label = Label(mainframe, text='"""')
row5Label.grid(column=0, row=5, sticky=(W, E), columnspan=2)

# Row 6 is the Regex Flags row
flagsFrame = Frame(mainframe, padding="3 3 12 12")
flagsFrame.grid(column=0, row=6, sticky=(W, E), columnspan=2)
flagsFrame.columnconfigure(0, weight=1)
flagsFrame.rowconfigure(0, weight=1)

row6Label = Label(flagsFrame, text=">>> flags = 0 | ")
row6Label.grid(column=0, row=0, sticky=W)

reIVar = BooleanVar()
reIVar.set(False)
Exemplo n.º 28
0
class PyAbel:  #(tk.Tk):

    def __init__(self, parent):
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.fn = None
        self.old_fn = None
        self.old_method = None
        self.old_fi = None
        self.AIM = None
        self.rmx = (368, 393)

        # matplotlib figure
        self.f = Figure(figsize=(2, 4))
        self.gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2])
        self.gs.update(wspace=0.2, hspace=0.5)

        self.plt = []
        self.plt.append(self.f.add_subplot(self.gs[0]))
        self.plt.append(self.f.add_subplot(self.gs[1]))
        self.plt.append(self.f.add_subplot(self.gs[2], sharex=self.plt[0],
                        sharey=self.plt[0]))
        self.plt.append(self.f.add_subplot(self.gs[3]))
        for i in [0, 2]:
            self.plt[i].set_adjustable('box-forced')

        # hide until have data
        for i in range(4):
            self.plt[i].axis("off")

        # tkinter 
        # set default font size for buttons
        self.font = tkFont.Font(size=11)
        self.fontB = tkFont.Font(size=12, weight='bold')

        #frames top (buttons), text, matplotlib (canvas)
        self.main_container = tk.Frame(self.parent, height=10, width=100)
        self.main_container.pack(side="top", fill="both", expand=True)

        self.button_frame = tk.Frame(self.main_container)
        #self.info_frame = tk.Frame(self.main_container)
        self.matplotlib_frame = tk.Frame(self.main_container)

        self.button_frame.pack(side="top", fill="x", expand=True)
        #self.info_frame.pack(side="top", fill="x", expand=True)
        self.matplotlib_frame.pack(side="top", fill="both", expand=True)

        self._menus()
        self._button_area()
        self._plot_canvas()
        self._text_info_box()

    def _button_frame(self):
        self.button_frame = tk.Frame(self.main_container)
        self.button_frame.pack(side="top", fill="x", expand=True)
        self._menus()

    def _menus(self):
        # menus with callback ----------------
        # duplicates the button interface
        self.menubar = tk.Menu(self.parent)
        self.transform_method = tk.IntVar()

        # File - menu
        self.filemenu = tk.Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="Load image file",
                                  command=self._loadimage)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self._quit)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        # Process - menu
        self.processmenu = tk.Menu(self.menubar, tearoff=0)
        self.processmenu.add_command(label="Center image", command=self._center)
        self.submenu=tk.Menu(self.processmenu)
        for method in Abel_methods:
            self.submenu.add_radiobutton(label=method,
                 var=self.transform_method, val=Abel_methods.index(method),
                 command=self._transform)
        self.processmenu.add_cascade(label="Inverse Abel transform",
                 menu=self.submenu, underline=0)

        self.processmenu.add_command(label="Speed distribution",
                                     command=self._speed)
        self.processmenu.add_command(label="Angular distribution",
                                     command=self._anisotropy)
        self.angmenu=tk.Menu(self.processmenu)
        self.menubar.add_cascade(label="Processing", menu=self.processmenu)
    
        # view - menu
        self.viewmenu = tk.Menu(self.menubar, tearoff=0)
        self.viewmenu.add_command(label="Raw image", command=self._display)
        self.viewmenu.add_command(label="Inverse Abel transformed image",
                                  command=self._transform)
        self.viewmenu.add_command(label="view buttons",
                                  command=self._on_buttons)
        self.menubar.add_cascade(label="View", menu=self.viewmenu)


    def _button_area(self):
        # grid layout  
        # make expandable
        for col in range(5):
            self.button_frame.columnconfigure(col, weight=1)
            self.button_frame.rowconfigure(col, weight=1)

        # column 0 ---------
        # load image file button
        self.load = tk.Button(master=self.button_frame, text="load image",
                              font=self.fontB,
                              command=self._loadimage)
        self.load.grid(row=0, column=0, sticky=tk.W, padx=(5, 10), pady=(5, 0))
        self.sample_image = ttk.Combobox(master=self.button_frame,
                         font=self.font,
                         values=["from file", "from transform", "sample dribinski", "sample Ominus"],
                         width=14, height=4)
        self.sample_image.current(0)
        self.sample_image.grid(row=1, column=0, padx=(5, 10))

        # quit
        self.quit = tk.Button(master=self.button_frame, text="quit",
                              font=self.fontB,
                              command=self._quit)
        self.quit.grid(row=3, column=0, sticky=tk.W, padx=(5, 10), pady=(0, 5))
   
        # column 1 -----------
        # center image
        self.center = tk.Button(master=self.button_frame, text="center image",
                                anchor=tk.W, 
                                font=self.fontB,
                                command=self._center)
        self.center.grid(row=0, column=1, padx=(0, 20), pady=(5, 0))
        self.center_method = ttk.Combobox(master=self.button_frame,
                         font=self.font,
                         values=["com", "slice", "gaussian", "image_center"],
                         width=10, height=4)
        self.center_method.current(1)
        self.center_method.grid(row=1, column=1, padx=(0, 20))

        # column 2 -----------
        # Abel transform image
        self.recond = tk.Button(master=self.button_frame,
                                text="Abel transform image",
                                font=self.fontB,
                                command=self._transform)
        self.recond.grid(row=0, column=2, padx=(0, 10), pady=(5, 0))

        self.transform = ttk.Combobox(master=self.button_frame,
                         values=Abel_methods,
                         font=self.font,
                         width=10, height=len(Abel_methods))
        self.transform.current(2)
        self.transform.grid(row=1, column=2, padx=(0, 20))

        self.direction = ttk.Combobox(master=self.button_frame,
                         values=["inverse", "forward"],
                         font=self.font,
                         width=8, height=2)
        self.direction.current(0)
        self.direction.grid(row=2, column=2, padx=(0, 20))


        # column 3 -----------
        # speed button
        self.speed = tk.Button(master=self.button_frame, text="speed",
                               font=self.fontB,
                               command=self._speed)
        self.speed.grid(row=0, column=5, padx=20, pady=(5, 0))
        
        self.speedclr = tk.Button(master=self.button_frame, text="clear plot",
                                  font=self.font, command=self._speed_clr)
        self.speedclr.grid(row=1, column=5, padx=20)

        # column 4 -----------
        # anisotropy button
        self.aniso = tk.Button(master=self.button_frame, text="anisotropy",
                               font=self.fontB,
                               command=self._anisotropy)
        self.aniso.grid(row=0, column=6, pady=(5, 0))

        self.subframe = tk.Frame(self.button_frame)
        self.subframe.grid(row=1, column=6)
        self.rmin = tk.Entry(master=self.subframe, text='rmin', width=3,
                               font=self.font)
        self.rmin.grid(row=0, column=0)
        self.rmin.delete(0, tk.END)
        self.rmin.insert(0, self.rmx[0])
        self.lbl = tk.Label(master=self.subframe, text="to", font=self.font)
        self.lbl.grid(row=0, column=1)
        self.rmax = tk.Entry(master=self.subframe, text='rmax', width=3,
                             font=self.font)
        self.rmax.grid(row=0, column=2)
        self.rmax.delete(0, tk.END)
        self.rmax.insert(0, self.rmx[1])


        # turn off button interface
        self.hide_buttons = tk.Button(master=self.button_frame,
                                      text="hide buttons",
                                      font=self.fontB,
                                      command=self._hide_buttons)
        self.hide_buttons.grid(row=3, column=6, sticky=tk.E, pady=(0, 20))

    def _text_info_box(self):
        # text info box ---------------------
        self.text = ScrolledText(master=self.button_frame, height=4, 
                            fg="mediumblue",
                            bd=1, relief=tk.SUNKEN)
        self.text.insert(tk.END, "Work in progress, some features may"
                         " be incomplete\n\n")
        self.text.insert(tk.END, "To start load an image data file using"
                         " 'load image' button (or file menu)\n")
        self.text.insert(tk.END, "e.g. data/O2-ANU1024.txt.bz2\n")
        self.text.grid(row=3, column=1, columnspan=3, padx=5)


    def _plot_canvas(self):
        # matplotlib canvas --------------------------
        self.canvas = FigureCanvasTkAgg(self.f, master=self.matplotlib_frame) 
        #self.cid = self.canvas.mpl_connect('button_press_event', self._onclick)

        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.parent)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(anchor=tk.W, side=tk.TOP, fill=tk.BOTH, expand=1)


    def _onclick(self,event):
        print('button={:d}, x={:f}, y={:f}, xdata={:f}, ydata={:f}'.format(
        event.button, event.x, event.y, event.xdata, event.ydata))


    # call back functions -----------------------
    def _display(self):
        if self.fn is None:
            self._loadimage()

        # display image
        self.plt[0].imshow(self.IM, vmin=0)
        #rows, cols = self.IM.shape
        #r2 = rows/2
        #c2 = cols/2
        #self.a.plot((r2, r2), (0, cols), 'r--', lw=0.1)
        #self.a.plot((0, rows), (c2, c2),'r--', lw=0.1)
        #self.f.colorbar(self.a.get_children()[2], ax=self.f.gca())
        self.plt[0].set_title("raw image", fontsize=10)
        self.canvas.show()


    def _loadimage(self):

        if self.fn is not None:
            # clear old plot
            for i in range(4):
                self._clr_plt(i)
                self.plt[i].axis("off")

        self.fn = self.sample_image.get()
        # update what is occurring text box
        self.text.insert(tk.END, "\nloading image file {:s}".format(self.fn))
        self.text.see(tk.END)
        self.canvas.show()

        if self.fn == "from file":
            self.fn = askopenfilename()
            # read image file
            if ".txt" in self.fn:
                self.IM = np.loadtxt(self.fn)
            else:
                self.IM = imread(self.fn)
        elif self.fn == "from transform":
            self.IM = self.AIM
            self.AIM = None
            for i in range(1,4):
                self._clr_plt(i)
                self.plt[i].axis("off")
            self.direction.current(0)
        else:
            self.fn = self.fn.split(' ')[-1]
            self.IM = abel.tools.analytical.sample_image(n=1001, name=self.fn)
            self.direction.current(1) # raw images require 'forward' transform
            self.text.insert(tk.END,"\nsample image: (1) Abel transform 'forward', ")
            self.text.insert(tk.END,"              (2) load 'from transform', ") 
            self.text.insert(tk.END,"              (3) Abel transform 'inverse', ")
            self.text.insert(tk.END,"              (4) Speed")
            self.text.see(tk.END)


        # if even size image, make odd
        if self.IM.shape[0] % 2 == 0:
            self.IM = shift(self.IM, (-0.5, -0.5))[:-1,:-1]
    
        self.old_method = None
        self.AIM = None
        self.action = "file"
        self.rmin.delete(0, tk.END)
        self.rmin.insert(0, self.rmx[0])
        self.rmax.delete(0, tk.END)
        self.rmax.insert(0, self.rmx[1])

        # show the image
        self._display()
    

    def _center(self):
        self.action = "center"

        center_method = self.center_method.get()
        # update information text box
        self.text.insert(tk.END, "\ncentering image using {:s}".\
                         format(center_method))
        self.canvas.show()
    
        # center image via chosen method
        self.IM = abel.tools.center.center_image(self.IM, method=center_method,
                                  odd_size=True)
        self.text.insert(tk.END, "\ncenter offset = {:}".format(self.offset))
        self.text.see(tk.END)
    
        self._display()
    
    
    def _transform(self):
        #self.method = Abel_methods[self.transform_method.get()]
        self.method = self.transform.get()
        self.fi = self.direction.get()
    
        if self.method != self.old_method or self.fi != self.old_fi:
            # Abel transform of whole image
            self.text.insert(tk.END,"\n{:s} {:s} Abel transform:".\
                             format(self.method, self.fi))
            if "basex" in self.method:
                self.text.insert(tk.END,
                              "\nbasex: first time calculation of the basis"
                              " functions may take a while ...")
            if "onion" in self.method:
               self.text.insert(tk.END,"\nonion_peeling: method is in early "
                              "testing and may not produce reliable results")
            if "direct" in self.method:
               self.text.insert(tk.END,"\ndirect: calculation is slowed if Cython"
                                       " unavailable ...")
            self.canvas.show()
    
            self.AIM = abel.transform(self.IM, method=self.method, 
                                      direction=self.fi,
                                      symmetry_axis=None)['transform']
            self.rmin.delete(0, tk.END)
            self.rmin.insert(0, self.rmx[0])
            self.rmax.delete(0, tk.END)
            self.rmax.insert(0, self.rmx[1])
    
        if self.old_method != self.method or self.fi != self.old_fi or\
           self.action not in ["speed", "anisotropy"]:
            self.plt[2].set_title(self.method+" {:s} Abel transform".format(self.fi),
                            fontsize=10)
            self.plt[2].imshow(self.AIM, vmin=0, vmax=self.AIM.max()/5.0)
            #self.f.colorbar(self.c.get_children()[2], ax=self.f.gca())
            #self.text.insert(tk.END, "{:s} inverse Abel transformed image".format(self.method))

        self.text.see(tk.END)
        self.old_method = self.method
        self.old_fi = self.fi
        self.canvas.show()
    
    def _speed(self):
        self.action = "speed"
        # inverse Abel transform
        self._transform()
        # update text box in case something breaks
        self.text.insert(tk.END, "\nspeed distribution")
        self.text.see(tk.END)
        self.canvas.show()
    
        # speed distribution
        self.radial, self.speed_dist = abel.tools.vmi.angular_integration(self.AIM)
    
        self.plt[1].axis("on")
        self.plt[1].plot(self.radial, self.speed_dist/self.speed_dist[10:].max(),
                         label=self.method)
        self.plt[1].axis(xmax=500, ymin=-0.05)
        self.plt[1].set_xlabel("radius (pixels)", fontsize=9)
        self.plt[1].set_ylabel("normalized intensity")
        self.plt[1].set_title("radial speed distribution", fontsize=12)
        self.plt[1].legend(fontsize=9)

        self.action = None
        self.canvas.show()

    def _speed_clr(self):
        self._clr_plt(1)

    def _clr_plt(self, i):
        self.f.delaxes(self.plt[i])
        self.plt[i] = self.f.add_subplot(self.gs[i]) 
        self.canvas.show()
    
    def _anisotropy(self):

        def P2(x):   # 2nd order Legendre polynomial
            return (3*x*x-1)/2
    
    
        def PAD(theta, beta, amp):
            return amp*(1 + beta*P2(np.cos(theta)))
    
        self.action = "anisotropy"
        self._transform()
        # radial range over which to follow the intensity variation with angle
        self.rmx = (int(self.rmin.get()), int(self.rmax.get()))
    
        self.text.insert(tk.END,"\nanisotropy parameter pixel range {:} to {:}: "\
                               .format(*self.rmx))
        self.canvas.show()
    
        # inverse Abel transform
        self._transform()
    
        # intensity vs angle
        self.intensity, self.theta = abel.tools.vmi.\
                                     calculate_angular_distributions(self.AIM,\
                                     radial_ranges=[self.rmx,])
    
        # fit to P2(cos theta)
        self.beta, self.amp = abel.tools.vmi.anisotropy_parameter(self.theta, self.intensity[0])
    
        self.text.insert(tk.END," beta = {:g}+-{:g}".format(*self.beta))
    
        self._clr_plt(3)
        self.plt[3].axis("on")
        
        self.plt[3].plot(self.theta, self.intensity[0], 'r-')
        self.plt[3].plot(self.theta, PAD(self.theta, self.beta[0], self.amp[0]), 'b-', lw=2)
        self.plt[3].annotate("$\\beta({:d},{:d})={:.2g}\pm{:.2g}$".format(*self.rmx+self.beta), (-np.pi/2,-2))
        self.plt[3].set_title("anisotropy", fontsize=12)
        self.plt[3].set_xlabel("angle", fontsize=9)
        self.plt[3].set_ylabel("intensity")

        self.action = None
        self.canvas.show()

    def _hide_buttons(self):
        self.button_frame.destroy()

    def _on_buttons(self):
        self._button_frame()
    
    def _quit(self):
        self.parent.quit()     # stops mainloop
        self.parent.destroy()  # this is necessary on Windows to prevent
Exemplo n.º 29
0
class SphxUI():
    def __init__(self, root):

        self.data = SphxData()
        self.xdopy = XdoPy()
        self.gooey = GuiPiece(self.data.MAIN_PATH, self.data.GUI_PIECE_DIR)
        self.script_dir = self.data.SCRIPT_DIR
        self.txt_dir = self.data.TXT_FILE_DIR

        # sphx data to reset upon new or fill upon load
        self.script_lines = []
        self.gui_pieces = []
        self.window_names = []
        self.passed_script_data = None
        self.text_file_pass = None
        self.return_data = None
        self.gui_piece_list_active = False
        self.script_fn = None

        # generate UI
        self.root = root
        self.master = Frame(self.root)
        self.master.grid()
        self.add_file_menu()
        self.create_script_pad()
        self.create_action_buttons()
        self.create_gui_pieces_list()
        return

    def start(self):
        self.root.mainloop()
        return

    def _dummy(self):
        pass

    def _dummy_event(self, event, arg=None):
        pass

    # TOP MENU
    #
    #
    def add_file_menu(self):
        self.menubar = Menu(self.root)
        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="New", command=self._new)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Open...", command=self._open)
        self.filemenu.add_command(label="Save",
                                  command=lambda: self._save(saveas=False))
        self.filemenu.add_command(label="Save As...",
                                  command=lambda: self._save(saveas=True))
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self._regular_exit)
        self.menubar.add_cascade(label="File", menu=self.filemenu)
        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About", command=self._dummy)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)
        self.root.config(menu=self.menubar)

    def _clear_everything(self):
        self.script_pad.delete('1.0', END)
        for button in self.gui_piece_buttons:
            button.config(text='')
        for line in self.script_lines:
            if line[2]:
                self.script_pad.tag_delete(line[2])
        self.script_lines = []
        self.gui_pieces = []
        self.window_names = []
        self.passed_script_data = None
        self.return_data = None
        self.gui_piece_list_active = False

    def _new(self):
        self.new_save = Toplevel()
        self.new_save.title('Save Script?')
        new_frame1 = Frame(self.new_save)
        new_frame1.grid(row=0, column=0)
        label = Label(
            new_frame1,
            text='Do you want to save your script before starting over?')
        label.grid()
        new_frame2 = Frame(self.new_save)
        new_frame2.grid(row=1, column=0)
        button = Button(new_frame2,
                        text='Yes',
                        command=lambda: self._new_save(0))
        button.grid(row=0, column=0)
        button = Button(new_frame2,
                        text='No',
                        command=lambda: self._new_save(1))
        button.grid(row=0, column=1)
        button = Button(new_frame2,
                        text='Cancel',
                        command=lambda: self._new_save(2))
        button.grid(row=0, column=2)

    def _new_save(self, answer):
        if answer == 0:
            if self.script_fn:
                self._save()
            else:
                self._save(False)
            self._clear_everything()
            self.new_save.destroy()
        if answer == 1:
            self._clear_everything()
            self.new_save.destroy()
        if answer == 2:
            self.new_save.destroy()

    def _open(self):
        if self.script_lines == [] and self.gui_pieces == []:
            self._load_everything()
            return
        self.open_save = Toplevel()
        self.open_save.title('Save Script?')
        new_frame1 = Frame(self.open_save)
        new_frame1.grid(row=0, column=0)
        label = Label(
            new_frame1,
            text='Do you want to save your script before opening a saved one?')
        label.grid()
        new_frame2 = Frame(self.open_save)
        new_frame2.grid(row=1, column=0)
        button = Button(new_frame2,
                        text='Yes',
                        command=lambda: self._open_save(0))
        button.grid(row=0, column=0)
        button = Button(new_frame2,
                        text='No',
                        command=lambda: self._open_save(1))
        button.grid(row=0, column=1)
        button = Button(new_frame2,
                        text='Cancel',
                        command=lambda: self._open_save(2))
        button.grid(row=0, column=2)

    def _open_save(self, answer):
        if answer == 0:
            if self.script_fn:
                self._save()
            else:
                self._save(False)
            self.open_save.destroy()
            self._load_everything()
        if answer == 1:
            self.open_save.destroy()
            self._load_everything()
        if answer == 2:
            self.open_save.destroy()

    def _load_everything(self):
        f = tkFileDialog.askopenfilename(initialdir=self.data.SCRIPT_DIR,
                                         title="Open Script",
                                         filetypes=(("sphx files", "*.sphx"),
                                                    ("all files", "*.*")))
        with open(f, 'r') as openfile:
            sphx_dict = json.load(openfile)
        self.script_fn = f.rpartition('/')[2]
        openfile.close()
        self._clear_everything()
        self.script_lines = sphx_dict['script_lines']
        self.gui_pieces = sphx_dict['gui_pieces']
        button_index = 0
        for gui_piece in self.gui_pieces:
            gui_piece_text = '{0}. {1}'.format(button_index + 1, gui_piece)
            self.gui_piece_buttons[button_index].config(text=gui_piece_text)
            button_index += 1
        for line in self.script_lines:
            line_number, script_text, tagname, tag_start, tag_end, script_data = line
            self.script_pad.insert(END, script_text + '\n')
            self._scanfix_script_lines(None)

    def _save(self, saveas=False):
        self._scanfix_script_lines(None)
        script_dict = {
            'script_lines': self.script_lines,
            'gui_pieces': self.gui_pieces
        }
        if not saveas and self.script_fn:
            with open(os.path.join(self.data.SCRIPT_DIR, self.script_fn),
                      'w') as outfile:
                json.dump(script_dict, outfile)
                self.script_fn = outfile.name.rpartition('/')[2]
        if (saveas or not self.script_fn) or (saveas and not self.script_fn):
            outfile = tkFileDialog.asksaveasfile(
                mode='w',
                defaultextension='.sphx',
                initialdir=self.data.SCRIPT_DIR)
            if outfile is None:
                return
            json.dump(script_dict, outfile)
            outfile.close()
            self.script_fn = outfile.name.rpartition('/')[2]

    def _regular_exit(self):
        self.exit_save = Toplevel()
        self.exit_save.title('Save Script')
        exit_frame1 = Frame(self.exit_save)
        exit_frame1.grid(row=0, column=0)
        label = Label(exit_frame1,
                      text='Do you want to save your script before exiting?')
        label.grid()
        exit_frame2 = Frame(self.exit_save)
        exit_frame2.grid(row=1, column=0)
        button = Button(exit_frame2,
                        text='Yes',
                        command=lambda: self._exit_save(0))
        button.grid(row=0, column=0)
        button = Button(exit_frame2,
                        text='No',
                        command=lambda: self._exit_save(1))
        button.grid(row=0, column=1)
        button = Button(exit_frame2,
                        text='Cancel',
                        command=lambda: self._exit_save(2))
        button.grid(row=0, column=2)

    def _exit_save(self, answer):
        if answer == 0:
            if self.script_fn:
                self._save()
            else:
                self._save(False)
            self.root.quit()
        if answer == 1:
            self.root.quit()
        if answer == 2:
            self.exit_save.destroy()

    # SCRIPT PAD COLUMN
    #
    #
    def create_script_pad(self):
        script_pad_label = Label(self.master,
                                 text='SCRIPT BUILD (right-click for options)')
        script_pad_label.grid(row=0, column=1)
        self.script_pad = ScrolledText(self.master, width=75, height=32)
        self.script_pad.grid(row=1, column=1, sticky='nw')
        self.script_pad.bind('<KeyRelease>', self._scanfix_script_lines)
        self.print_button = Button(self.master,
                                   text='Print Script Line Data To Terminal',
                                   command=self._print_script_line_data)
        self.print_button.grid(row=2, column=1, sticky='nwes')
        return

    def _print_script_line_data(self):
        for line in self.script_lines:
            print(line[1])

    def _get_tag_data(self, line_count, line_text, script_data):
        tag_start = '{0}.{1}'.format(line_count, line_text.index(script_data))
        tag_end = '{0}.{1}'.format(
            line_count,
            line_text.index(script_data) + len(script_data))
        return tag_start, tag_end

    def _scanfix_script_lines(self, event):
        new_script_lines = []
        new_text = self.script_pad.get('1.0', END)
        new_text_lines = new_text.split('\n')
        line_count = 0
        gui_tags = []
        win_tags = []
        key_tags = []
        self.script_lines = []
        new_window_names = []
        for line in new_text_lines:
            line_count += 1
            if ';' and ' ' in line:
                line_text = line.rpartition(';')[0]
                line_pieces = line_text.split(' ')
                action = line_pieces[0]
                script_line_data = []
                if action in [a[0] for a in self.data.GUI_ACTIONS]:
                    script_data = line_pieces[1]
                    tag_index = len(gui_tags)
                    tag_name = 'gui{0}'.format(tag_index)
                    self.script_pad.tag_delete(tag_name)
                    gui_tags.append(tag_name)
                    tag_start, tag_end = self._get_tag_data(
                        line_count, line_text, script_data)
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                    self.script_pad.tag_add(tag_name, tag_start, tag_end)
                    self.script_pad.tag_config(tag_name,
                                               background='blue',
                                               foreground='white')
                    self.script_pad.tag_bind(
                        tag_name,
                        '<Button-3>',
                        lambda event, arg=script_line_data: self.
                        _gui_piece_menu_popup(event, arg))
                if action in [a[0] for a in self.data.WINDOW_ACTIONS]:
                    script_data = line_pieces[1]
                    tag_index = len(win_tags)
                    tag_name = 'win{0}'.format(tag_index)
                    self.script_pad.tag_delete(tag_name)
                    win_tags.append(tag_name)
                    tag_start, tag_end = self._get_tag_data(
                        line_count, line_text, script_data)
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                    if action == 'name_active_window':
                        new_window_names.append(script_data)
                        self.script_pad.tag_add(tag_name, tag_start, tag_end)
                        self.script_pad.tag_config(tag_name,
                                                   background='gray',
                                                   foreground='white')
                    else:
                        self.script_pad.tag_add(tag_name, tag_start, tag_end)
                        self.script_pad.tag_config(tag_name,
                                                   background='pink',
                                                   foreground='white')
                        self.script_pad.tag_bind(
                            tag_name,
                            '<Button-3>',
                            lambda event, arg=script_line_data: self.
                            _window_menu_popup(event, arg))
                if action in [a[0] for a in self.data.KEYBOARD_ACTIONS]:
                    script_data = line_text.partition(' ')[2]
                    tag_index = len(key_tags)
                    tag_name = 'key{0}'.format(tag_index)
                    key_tags.append(tag_name)
                    tag_start, tag_end = self._get_tag_data(
                        line_count, line_text, script_data)
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                    self.script_pad.tag_add(tag_name, tag_start, tag_end)
                    if 'type' in action:
                        tag_bg, tag_fg = 'green', 'white'
                    else:
                        tag_bg, tag_fg = 'green', 'yellow'
                    self.script_pad.tag_config(tag_name,
                                               background=tag_bg,
                                               foreground=tag_fg)
                    self.script_pad.tag_bind(
                        tag_name,
                        '<Button-3>',
                        lambda event, arg=script_line_data: self.
                        _text_piece_popup(event, arg))
                if action in [a[0] for a in self.data.OTHER_ACTIONS]:
                    script_data = None
                    tag_name = None
                    tag_start, tag_end = None, None
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                if len(script_line_data) > 0:
                    self.script_lines.append(script_line_data)
        self.window_names = sorted(new_window_names)
        if len(self.window_names) == 0:
            self.action_buttons_list[15].config(state=DISABLED)
            self.action_buttons_list[16].config(state=DISABLED)
        else:
            if not self.gui_piece_list_active:
                self.action_buttons_list[15].config(state='normal')
                self.action_buttons_list[16].config(state='normal')
        return

    # ACTION BUTTONS COLUMN
    #
    #
    def create_action_buttons(self):
        action_buttons_label = Label(self.master, text='SCRIPT ACTIONS')
        action_buttons_label.grid(row=0, column=2)
        self.action_buttons = Frame(self.master)
        self.action_buttons.grid(row=1, column=2, sticky='nw')
        self.auto_snap = IntVar()
        self.auto_snap.set(1)
        self.auto_snap_check = Checkbutton(self.action_buttons,
                                           text='Auto-snap',
                                           variable=self.auto_snap)
        self.auto_snap_check.grid(row=0, column=2)
        self.action_buttons_list = []
        action_index = 0
        for i in range(3):
            for j in range(3):
                button = Button(self.action_buttons,
                                text=self.data.GUI_ACTIONS[action_index][0],
                                pady=5,
                                command=functools.partial(
                                    self._append_gui_piece_action,
                                    self.data.GUI_ACTIONS[action_index][1]))
                button.grid(row=i + 1, column=j, sticky='nwes')
                action_index += 1
                self.action_buttons_list.append(button)
        action_index = 0
        for i in range(2):
            for j in range(3):
                if i == 0 and j == 0:
                    continue
                button = Button(
                    self.action_buttons,
                    text=self.data.KEYBOARD_ACTIONS[action_index][0],
                    pady=5,
                    command=functools.partial(
                        self._append_text_piece_action,
                        self.data.KEYBOARD_ACTIONS[action_index][1]))
                button.grid(row=i + 4, column=j, sticky='nwes')
                self.action_buttons_list.append(button)
                action_index += 1
        action_index = 0
        for j in range(3):
            button = Button(self.action_buttons,
                            text=self.data.WINDOW_ACTIONS[action_index][0],
                            pady=5,
                            command=functools.partial(
                                self._append_window_action,
                                self.data.WINDOW_ACTIONS[action_index][1]))
            button.grid(row=6, column=j, sticky='nwes')
            if j > 0:
                button.config(state=DISABLED)
            self.action_buttons_list.append(button)
            action_index += 1
        action_index = 0
        for j in range(2):
            button = Button(self.action_buttons,
                            text=self.data.OTHER_ACTIONS[action_index][0],
                            pady=5,
                            command=functools.partial(
                                self._append_other_action,
                                self.data.OTHER_ACTIONS[action_index][1]))
            button.grid(row=7, column=j + 1, sticky='nwes')
            self.action_buttons_list.append(button)
            action_index += 1
        # insert another layer for hover-over data about script action

        return

    # GUI PIECES COLUMN
    #
    #
    def create_gui_pieces_list(self):
        gui_pieces_label = Label(self.master,
                                 text='GUI PIECES (click to view)')
        gui_pieces_label.grid(row=0, column=0)
        self.gui_piece_buttons = []
        self.gui_pieces_pad = Frame(self.master)
        self.gui_pieces_pad.grid(row=1, column=0, sticky='nw')
        button_index = 0
        for j in range(2):
            for i in range(25):
                new_button = Button(self.gui_pieces_pad,
                                    text='',
                                    bg='blue',
                                    fg='white',
                                    borderwidth=0,
                                    width=15,
                                    padx=0,
                                    pady=0,
                                    command=functools.partial(
                                        self._gui_piece_button_click,
                                        button_index))
                button_index += 1
                new_button.grid(row=i, column=j, sticky='w')
                self.gui_piece_buttons.append(new_button)
        self.gui_piece_extras = Frame(self.master)
        self.gui_piece_extras.grid(row=2, column=0, sticky='nwes')
        self.take_new_gui_piece_button = Button(self.gui_piece_extras,
                                                text='Take New',
                                                command=self._get_gui_piece)
        self.take_new_gui_piece_button.grid(row=0, column=0, sticky='nwes')
        # TO FINISH -- LOAD BUTTON
        self.load_png_gui_piece_button = Button(self.gui_piece_extras,
                                                text='Load Png',
                                                command=self._dummy)
        self.load_png_gui_piece_button.config(state=DISABLED)
        self.load_png_gui_piece_button.grid(row=0, column=1, sticky='nwes')
        # TO FINISH -- REMOVE BUTTON
        self.remove_gui_piece_button = Button(
            self.gui_piece_extras,
            text='Remove',
            command=lambda: self._activate_gui_pieces_list(None))
        self.remove_gui_piece_button.grid(row=0, column=2, sticky='nwes')
        return

    def _append_gui_pieces_list(self, gui_piece):
        gui_piece_text = '{0}. {1}'.format(len(self.gui_pieces) + 1, gui_piece)
        self.gui_piece_buttons[len(
            self.gui_pieces)].config(text=gui_piece_text)
        self.gui_pieces.append(gui_piece)
        return

    def _remove_gui_piece(self, button_index):
        removed_gui_piece = self.gui_pieces.pop(button_index)
        if button_index < len(self.gui_pieces):
            for replace_index in range(button_index, len(self.gui_pieces)):
                self.gui_piece_buttons[replace_index].config(
                    text='{0}. {1}'.format(replace_index +
                                           1, self.gui_pieces[replace_index]))
        self.gui_piece_buttons[len(self.gui_pieces)].config(text='')
        for index in range(len(self.script_lines)):
            line_data = self.script_lines[index][-1]
            if line_data == removed_gui_piece:
                data = '<right-click>', self.script_lines[index]
                self._replace_gui_piece(data)
        return

    def _activate_gui_pieces_list(self, script_line_data):
        if len(self.gui_pieces):
            for button in self.gui_piece_buttons:
                button.config(fg='white', bg='red')
            self.script_pad.config(state=DISABLED)
            self.print_button.config(state=DISABLED)
            for button in self.action_buttons_list:
                button.config(state=DISABLED)
            self.take_new_gui_piece_button.config(state=DISABLED)
            # self.load_png_gui_piece_button.config(state=DISABLED)
            self.remove_gui_piece_button.config(state=DISABLED)
            self.gui_piece_list_active = True
            self.passed_script_data = script_line_data

    def _gui_piece_button_click(self, button_index):
        if button_index < len(self.gui_pieces):
            gui_piece = self.gui_pieces[button_index]
            if not self.gui_piece_list_active:
                self._display_gui_piece(gui_piece)
            else:
                if self.passed_script_data:
                    script_line_data = self.passed_script_data
                    data = gui_piece, script_line_data
                    self._replace_gui_piece(data)
                else:
                    self._remove_gui_piece(button_index)
                for button in self.gui_piece_buttons:
                    button.config(bg='blue', fg='white')
                self.print_button.config(state='normal')
                for button in self.action_buttons_list:
                    button.config(state='normal')
                if len(self.window_names) == 0:
                    self.action_buttons_list[15].config(state=DISABLED)
                    self.action_buttons_list[16].config(state=DISABLED)
                self.take_new_gui_piece_button.config(state='normal')
                # self.load_png_gui_piece_button.config(state='normal')
                self.remove_gui_piece_button.config(state='normal')
                self.gui_piece_list_active = False

    #     -- gui piece action functions --
    #
    #
    def _append_gui_piece_action(self, script_text):
        if self.auto_snap.get():
            gui_piece = self._get_gui_piece()
        else:
            gui_piece = '<right-click>'
        script_line = script_text.format(gui_piece)
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)

    def _gui_piece_menu_popup(self, event, script_line_data):
        self.popup_menu1 = Menu(self.root, tearoff=0)
        self.popup_menu1.add_command(label='View',
                                     command=functools.partial(
                                         self._display_gui_piece,
                                         script_line_data[-1]))
        self.popup_menu1.add_command(label='Take New',
                                     command=functools.partial(
                                         self._sub_new_gui_piece,
                                         script_line_data))
        self.popup_menu1.add_command(label='Choose From Others',
                                     command=functools.partial(
                                         self._activate_gui_pieces_list,
                                         script_line_data))
        self.popup_menu1.post(event.x_root, event.y_root)
        self.master.bind('<Button-1>', self._destroy_gui_piece_menu)
        self.master.bind('<Button-3>', self._destroy_gui_piece_menu)
        self.script_pad.bind('<Enter>', self._destroy_gui_piece_menu)

    def _get_gui_piece(self):
        self.root.iconify()
        self.gooey.take_new_gui_piece()
        self.root.deiconify()
        gui_piece = self.gooey.gui_piece_filename
        self._append_gui_pieces_list(gui_piece)
        return gui_piece

    def _display_gui_piece(self, gui_piece):
        if gui_piece != '<right-click>':
            self.img_viewer = Toplevel()
            self.img_viewer.title(gui_piece)
            img_open = Image.open(
                os.path.join(self.data.GUI_PIECE_DIR, gui_piece))
            img = ImageTk.PhotoImage(img_open)
            img_label = Label(self.img_viewer, image=img)
            img_label.image = img
            img_label.grid(row=0, column=0, padx=20, pady=20)

    def _replace_gui_piece(self, data):
        new_gui_piece, script_line_data = data
        line_number, script_text, gui_tagname, gui_tag_start, gui_tag_end, gui_piece = script_line_data
        self.script_pad.config(state='normal')
        self.script_pad.delete(gui_tag_start, gui_tag_end)
        self.script_pad.insert(gui_tag_start, new_gui_piece)
        self._scanfix_script_lines(None)

    def _sub_new_gui_piece(self, gui_tag_data):
        data = self._get_gui_piece(), gui_tag_data
        self._replace_gui_piece(data)

    def _destroy_gui_piece_menu(self, event):
        self.popup_menu1.destroy()

    #     -- window action functions --
    #
    #
    def _append_window_action(self, script_text):
        if script_text.split(' ')[0] == 'name_active_window':
            if len(self.window_names) == 0:
                self.action_buttons_list[13].config(state='normal')
                self.action_buttons_list[14].config(state='normal')
            window_name = 'window{0}'.format(
                str(len(self.window_names)).zfill(2))
            self.window_names.append(window_name)
        else:
            window_name = self.window_names[-1]
        script_line = script_text.format(window_name)
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)

    def _window_menu_popup(self, event, script_line_data):
        self.popup_menu2 = Menu(self.root, tearoff=0)
        for other_window_name in self.window_names:
            data = other_window_name, script_line_data
            self.popup_menu2.add_command(label=other_window_name,
                                         command=functools.partial(
                                             self._replace_window_name, data))
        self.popup_menu2.post(event.x_root, event.y_root)
        self.master.bind('<Button-1>', self._destroy_window_name_menu)
        self.master.bind('<Button-3>', self._destroy_window_name_menu)
        self.script_pad.bind('<Enter>', self._destroy_window_name_menu)

    def _replace_window_name(self, data):
        self.popup_menu2.destroy()
        new_window_name, script_line_data = data
        line_number, script_text, win_tagname, win_tag_start, win_tag_end, window_name = script_line_data
        self.script_pad.delete(win_tag_start, win_tag_end)
        self.script_pad.insert(win_tag_start, new_window_name)
        self._scanfix_script_lines(None)

    def _destroy_window_name_menu(self, event):
        self.popup_menu2.destroy()

    #     -- type_text action functions --
    #
    #
    def _append_text_piece_action(self, script_text):
        text_piece = '<right-click>'
        script_line = script_text.format(text_piece)
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)

    def _text_piece_popup(self, event, data):
        open_text_file = False
        text_piece = data[-1]
        if text_piece == '<right-click>':
            text_piece = ''

        if 'type' in data[1]:
            if 'type_text_file' in data[1]:
                open_text_file = True
            else:
                text_type_title = 'Text to Type:'
        else:
            text_type_title = 'Key(s) to Press:'
        if not open_text_file:
            self.get_text = Toplevel()
            self.get_text.title(text_type_title)
            self.text_entry = Entry(self.get_text,
                                    text=text_piece,
                                    width=75,
                                    font=("Helvetica", 12))
            self.text_entry.grid()
            self.text_entry.bind(
                '<Return>',
                lambda event, arg=data: self._replace_text_piece(event, arg))
        else:
            self._open_text_file(data)

    def _open_text_file(self, script_line_data):
        f = tkFileDialog.askopenfilename(initialdir=self.data.TXT_FILE_DIR,
                                         title="Open Text File",
                                         filetypes=(("txt files", "*.txt"),
                                                    ("all files", "*.*")))
        if f is None:
            return
        with open(f, 'r') as openfile:
            text_from_file = openfile.read()
        self.text_file_pass = f.rpartition('/')[2]
        self._replace_text_piece(None, script_line_data)
        return

    def _replace_text_piece(self, event, data):
        line_number, script_text, text_tagname, text_tag_start, text_tag_end, text_piece = data
        if 'type_text_file' in script_text:
            new_text_piece = self.text_file_pass
        else:
            new_text_piece = self.text_entry.get()
            self.get_text.destroy()
        self.script_pad.config(state='normal')
        self.script_pad.delete(text_tag_start, text_tag_end)
        self.script_pad.insert(text_tag_start, new_text_piece)
        self._scanfix_script_lines(None)

    #     -- sleep & other action functions --
    #
    #
    def _append_other_action(self, script_text):
        script_line = script_text
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)
Exemplo n.º 30
0
 def help(self):
     help_window = Toplevel(master=self.window)
     help_window.title("Graph viewer help")
     text = ScrolledText(master=help_window)
     text.insert(END, help_text)
     text.grid(row=0,column=0)
Exemplo n.º 31
0
class MipsxTkGui(Frame):
  


    def __init__(self, parent, control):

      	Frame.__init__(self, parent)   
         
       	self.parent = parent

        self.parent.title("Mipsx - GUI for gdb multiarch")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

	# Para expandir cuando las ventanas cambian de tamao 
	for i in range(3):
		self.columnconfigure(i, weight=1)
	for i in range(20):
		self.rowconfigure(i, weight=1)

        lbl = Label(self, text="Registros")
        lbl.grid(row=1,column=2, sticky=W, pady=4, padx=5)
        

        self.registros = Text(self,height=12,width=80)
        self.registros.grid(row=2, column=2, columnspan=1, rowspan=5, 
            sticky=E+W+S+N)
        
        lbl = Label(self, text="Programa en Assembler y Prorama Binario Decodificado (disassemble) ")
        lbl.grid(row=7, column=2, pady=1, padx=1, sticky=W+N+E+S)
        
    	self.programa = Text(self, height=6,width=80)
        self.programa.grid(row=8, column=2, columnspan=1, rowspan=5, 
            padx=1, sticky=E+W+S+N)

        lbl = Label(self, text='Memoria - Segmento de datos (debe existir la etiqueta "memoria") - Segmento de texto - Pila')
        lbl.grid(row=13, column=2, pady=1, padx=1, sticky=W+N+E+S)

        self.memoria = Text(self,height=15,width=80)
        self.memoria.grid(row=14, column=2, columnspan=1, rowspan=5, 
            padx=1, sticky=E+W+S+N)

        lbl4 = Label(self, text="Mensajes de Depuracion")
        lbl4.grid(row=13, column=0, pady=1, padx=1, sticky=W+N+E+S)

        self.mensajes = Text(self,height=8,width=60)
        self.mensajes.grid(row=14, column=0, columnspan=1, rowspan=5, 
            padx=1, sticky=E+W+S+N)

        lbl = Label(self, text="Editor del Programa")
        lbl.grid(row=1,column=0, sticky=W, pady=4, padx=5) 
     
	self.editor = ScrolledText(self,height=20,width=60)
	self.editor.grid(row=2, column=0, columnspan=1, rowspan=10, 
            padx=1, sticky=E+W+S+N)
        
      
	menu = Menu(root)
	root.config(menu=menu)
	filemenu = Menu(menu)

	menu.add_cascade(label="Archivo", menu=filemenu)
	filemenu.add_command(label="Nuevo", command=control.nuevo)
	filemenu.add_command(label="Abrir...", command=control.abrir)
	filemenu.add_command(label="Guardar...", command=control.guardar)
	filemenu.add_separator()
	filemenu.add_command(label="Salir", command=control.salir)


	menu.add_command(label="Run", command=control.ejecutar)
	menu.add_command(label="Next", command=control.prox_instruccion)
	menu.add_command(label="Breakpoint", command=control.no_hacer_nada)
	menu.add_command(label="Compilar y Cargar", command=control.compilarycargar)

	helpmenu = Menu(menu)
	menu.add_cascade(label="Ayuda", menu=helpmenu)
	helpmenu.add_command(label="Acerca de...", command=control.acercade)
	menu.add_command(label="Salir", command=control.salir)

    def limpiar_panel(self, panel):
		panel.delete('1.0',END)

    def panel_agregar(self, panel, contenido):
		panel.insert(END, contenido)

    def panel_leer(self, panel):
		return panel.get('1.0', END+'-1c')

    def mostrar_en_area(self, area):
		area.insert(END,contents)

    # Al abrir un archivo deseamos tener un area de trabajo cero
    def limpiar_paneles(self):
		self.mensajes.delete('1.0',END)
		self.memoria.delete('1.0',END)
		self.programa.delete('1.0',END)
		self.registros.delete('1.0',END)
Exemplo n.º 32
0
class DualView(Frame):
	def __init__(self,parent,filename,goban_size=200):
		#Tk.__init__(self,parent)
		Frame.__init__(self,parent)
		
		self.parent=parent
		self.filename=filename
		self.goban_size=goban_size
		

		
		self.initialize()
		
		self.current_move=1
		self.display_move(self.current_move)
		
		#self.after(100,self.center)
		
		self.pressed=0

	def close_app(self):
		for popup in self.all_popups[:]:
			popup.close()
			"""
			if popup.okgnugo:
				print "killing gnugo"
				popup.gnugo.kill()
			if popup.okleela:
				print "killing leela"
				popup.leela.kill()
			"""
		self.destroy()
		self.parent.destroy()

	
	def prev_10_move(self,event=None):
		self.current_move=max(1,self.current_move-10)
		self.pressed=time.time()
		pf=partial(self.goto_move,move_number=self.current_move,pressed=self.pressed)
		self.parent.after(0,lambda: pf())

	def prev_move(self,event=None):
		if self.current_move>1:
			self.pressed=time.time()
			self.current_move-=1
			pf=partial(self.goto_move,move_number=self.current_move,pressed=self.pressed)
			self.parent.after(0,lambda: pf())
	
	def next_10_move(self,event=None):
		self.current_move=min(get_node_number(self.gameroot),self.current_move+10)
		self.pressed=time.time()
		pf=partial(self.goto_move,move_number=self.current_move,pressed=self.pressed)
		self.parent.after(0,lambda: pf())
	
	def next_move(self,event=None):
		if self.current_move<get_node_number(self.gameroot):
			self.pressed=time.time()
			self.current_move+=1
			pf=partial(self.goto_move,move_number=self.current_move,pressed=self.pressed)
			self.parent.after(0,lambda: pf())
			
	def first_move(self,event=None):
		self.current_move=1
		self.pressed=time.time()
		pf=partial(self.goto_move,move_number=self.current_move,pressed=self.pressed)
		self.parent.after(0,lambda: pf())
		
	def final_move(self,event=None):
		self.current_move=get_node_number(self.gameroot)
		self.pressed=time.time()
		pf=partial(self.goto_move,move_number=self.current_move,pressed=self.pressed)
		self.parent.after(0,lambda: pf())
	

	def goto_move(self,move_number,pressed):
		self.move_number.config(text=str(move_number)+'/'+str(get_node_number(self.gameroot)))
		if self.pressed==pressed:
			self.display_move(self.current_move)
			
	def leave_variation(self,goban,grid,markup):
		self.comment_box2.delete(1.0, END)
		self.parent.bind("<Up>", lambda e: None)
		self.parent.bind("<Down>", lambda e: None)
		self.current_variation_sequence=None
		self.clear_status()
		goban.display(grid,markup)

	def show_variation(self,event,goban,grid,markup,i,j):
		sequence=markup[i][j]
		self.show_variation_move(goban,grid,markup,i,j,len(sequence))
	
	
	def show_variation_move(self,goban,grid,markup,i,j,move):
		sequence=markup[i][j]
		temp_grid=copy(grid)
		temp_markup=copy(markup)
		
		for u in range(self.dim):
			for v in range(self.dim):
				if temp_markup[u][v]!=0:
					temp_markup[u][v]=''
		
		k=1
		for color,(u,v),s,comment,displaycolor,letter_color in sequence[:move]:
			#temp_grid[u][v]=color
			place(temp_grid,u,v,color)
			temp_markup[u][v]=k
			k+=1
		
		goban.display(temp_grid,temp_markup)
		
		self.comment_box2.delete(1.0, END)
		if comment:
			self.comment_box2.insert(END,comment)
		u=i+goban.mesh[i][j][0]
		v=j+goban.mesh[i][j][1]
		local_area=goban.draw_point(u,v,1,color="",outline="")
		goban.tag_bind(local_area, "<Leave>", lambda e: self.leave_variation(goban,grid,markup))
		
		self.current_variation_goban=goban
		self.current_variation_grid=grid
		self.current_variation_markup=markup
		self.current_variation_i=i
		self.current_variation_j=j
		self.current_variation_move=move
		self.current_variation_sequence=sequence
		
		self.parent.bind("<Up>", self.show_variation_next)
		self.parent.bind("<Down>", self.show_variation_prev)
		self.parent.bind("<MouseWheel>", self.mouse_wheel)
		goban.tag_bind(local_area,"<Button-4>", self.show_variation_next)
		goban.tag_bind(local_area,"<Button-5>", self.show_variation_prev)
		self.set_status("Use mouse wheel or keyboard up/down keys to display the sequence move by move.")
	
	def mouse_wheel(self,event):
		if self.current_variation_sequence==None:
			return
		d = event.delta
		if d>0:
			self.show_variation_next()
		elif d<0:
			self.show_variation_prev()
	
	def show_variation_next(self,event=None):
		
		move=(self.current_variation_move+1)%(len(self.current_variation_sequence)+1)
		move=max(1,move)
		print move,'/',len(self.current_variation_sequence)
		self.show_variation_move(self.current_variation_goban,self.current_variation_grid,self.current_variation_markup,self.current_variation_i,self.current_variation_j,move)
	
	def show_variation_prev(self,event=None):
		move=(self.current_variation_move-1)%len(self.current_variation_sequence)
		if move<1:
			move=len(self.current_variation_sequence)
		
		self.show_variation_move(self.current_variation_goban,self.current_variation_grid,self.current_variation_markup,self.current_variation_i,self.current_variation_j,move)

	def display_move(self,move=1):
		dim=self.dim
		goban1=self.goban1
		goban2=self.goban2
		

		
		self.move_number.config(text=str(move)+'/'+str(get_node_number(self.gameroot)))
		print "========================"
		print "displaying move",move
		grid1=[[0 for row in range(dim)] for col in range(dim)]
		markup1=[["" for row in range(dim)] for col in range(dim)]
		grid2=[[0 for row in range(dim)] for col in range(dim)]
		markup2=[["" for row in range(dim)] for col in range(dim)]
		board, _ = sgf_moves.get_setup_and_moves(self.sgf)

		for colour, move0 in board.list_occupied_points():
			if move0 is None:
				continue
			row, col = move0
			if colour=='b':
				place(grid1,row,col,1)
				place(grid2,row,col,1)
		
		m=0
		for m in range(1,move):
			one_move=get_node(self.gameroot,m)
			if one_move==False:
				print "(0)leaving because one_move==False"
				return
			
			ij=one_move.get_move()[1]
			
			if ij==None:
				print "(0)skipping because ij==None",ij
				continue

			
			if one_move.get_move()[0]=='b':color=1
			else:color=2
			i,j=ij
			place(grid1,i,j,color)
			place(grid2,i,j,color)
			
			if len(one_move)==0:
				print "(0)leaving because len(one_move)==0"
				goban1.display(grid1,markup1)
				goban2.display(grid2,markup2)
				return
		
		
		
		#indicating last play with delta
		self.comment_box1.delete(1.0, END)
		if m>0:
			if get_node(self.gameroot,m+1).has_property("C"):
				self.comment_box1.insert(END,get_node(self.gameroot,m+1).get("C"))
			markup1[i][j]=0
			markup2[i][j]=0
		
		self.comment_box2.delete(1.0, END)
		#next sequence in current game ############################################################################
		main_sequence=[]
		for m in range(5):
			one_move=get_node(self.gameroot,move+m)
			if one_move==False:
				print "(00)leaving because one_move==False"
				break
			ij=one_move.get_move()[1]
			if ij==None:
				print "(0)skipping because ij==None",ij
				break
			if one_move.get_move()[0]=='b':	c=1
			else: c=2
			main_sequence.append([c,ij,"A",None,"black","black"])
			if m==0:
				real_game_ij=ij
		try:
			#i,j=one_move=get_node(self.gameroot,move).get_move()[1]
			i,j=get_node(self.gameroot,move).get_move()[1]
		except:
			self.prev_move()
			return
		markup1[i][j]=main_sequence
		
		#alternative sequences ####################################################################################
		parent=get_node(self.gameroot,move-1)
		if parent==False:
			print "(1)leaving because one_move==False"
			return
		if len(parent)<=1:
			print "no alternative move"
			#display(goban1,grid1,markup1)
			#display(goban2,grid2,markup2)
			goban1.display(grid1,markup1)
			goban2.display(grid2,markup2)
			
			return
		
		for a in range(1,len(parent)):
			one_alternative=parent[a]
			ij=one_alternative.get_move()[1]
			
			
			
			displaycolor='black'
			
			
			if one_alternative.get_move()[0]=='b': c=1
			else: c=2

			if one_alternative.has_property("C"):
				comment=one_alternative.get("C")
				black_prob=float(one_alternative.get("C").split(": ")[1].replace("%","").split('/')[0])
				white_prob=100-black_prob
				#print "black_prob:",black_prob,'c=',c
				if c==1:
					if black_prob>=50:
						displaycolor="blue"
					else:
						displaycolor="red"
				else:
					if black_prob>50:
						displaycolor="red"
					else:
						displaycolor="blue"
			else: comment=''
			
			if ij==real_game_ij: letter_color="black"
			else: letter_color=displaycolor
			
			alternative_sequence=[[c,ij,chr(64+a),comment,displaycolor,letter_color]]
			while len(one_alternative)>0:
				one_alternative=one_alternative[0]
				ij=one_alternative.get_move()[1]
				if one_alternative.get_move()[0]=='b':c=1
				else:c=2
				alternative_sequence.append([c,ij,chr(64+a),comment,"whocare?","whocare"])
			i,j=parent[a].get_move()[1]
			markup2[i][j]=alternative_sequence
			
		goban1.display(grid1,markup1)
		goban2.display(grid2,markup2)

	def open_move(self):
		print "Opening move",self.current_move
		new_popup=OpenMove(self,self.current_move,self.dim,self.sgf,self.goban_size)
		self.all_popups.append(new_popup)
		
	def initialize(self):
				
		txt = open(self.filename)
		self.sgf = sgf.Sgf_game.from_string(txt.read())
		txt.close()
		
		self.dim=self.sgf.get_size()
		self.komi=self.sgf.get_komi()
		
		print "boardsize:",self.dim
		#goban.dim=size
		
		#goban.prepare_mesh()
		self.gameroot=self.sgf.get_root()
		

		self.parent.title('GoReviewPartner')
		self.parent.protocol("WM_DELETE_WINDOW", self.close_app)
		
		
		self.all_popups=[]
		
		self.configure(background=bg)
		
		Label(self,text='   ',background=bg).grid(column=0,row=0)
		
		buttons_bar=Frame(self,background=bg)
		buttons_bar.grid(column=1,row=1,columnspan=3)
		
		first_move_button=Button(buttons_bar, text='|<< ',command=self.first_move)
		first_move_button.grid(column=8,row=1)
		
		prev_10_moves_button=Button(buttons_bar, text=' << ',command=self.prev_10_move)
		prev_10_moves_button.grid(column=9,row=1)
		
		prev_button=Button(buttons_bar, text='prev',command=self.prev_move)
		prev_button.grid(column=10,row=1)
		
		Label(buttons_bar,text='          ',background=bg).grid(column=19,row=1)
		
		open_button=Button(buttons_bar, text='open',command=self.open_move)
		open_button.grid(column=20,row=1)

		Label(buttons_bar,text='          ',background=bg).grid(column=29,row=1)
		
		next_button=Button(buttons_bar, text='next',command=self.next_move)
		next_button.grid(column=30,row=1)
		
		next_10_moves_button=Button(buttons_bar, text=' >> ',command=self.next_10_move)
		next_10_moves_button.grid(column=31,row=1)
		
		final_move_button=Button(buttons_bar, text=' >>|',command=self.final_move)
		final_move_button.grid(column=32,row=1)
		
		first_move_button.bind("<Enter>",lambda e: self.set_status("Go to first move."))
		prev_10_moves_button.bind("<Enter>",lambda e: self.set_status("Go back 10 moves."))
		prev_button.bind("<Enter>",lambda e: self.set_status("Go back one move. Shortcut: keyboard left key."))
		open_button.bind("<Enter>",lambda e: self.set_status("Open this position onto a third goban to play out variations."))
		next_button.bind("<Enter>",lambda e: self.set_status("Go forward one move. Shortcut: keyboard right key."))
		next_10_moves_button.bind("<Enter>",lambda e: self.set_status("Go forward 10 moves."))
		final_move_button.bind("<Enter>",lambda e: self.set_status("Go to final move."))
		
		for button in [first_move_button,prev_10_moves_button,prev_button,open_button,next_button,next_10_moves_button,final_move_button]:
			button.bind("<Leave>",lambda e: self.clear_status())
		
		self.move_number=Label(self,text='   ',background=bg)
		self.move_number.grid(column=2,row=2)

		self.parent.bind('<Left>', self.prev_move)
		self.parent.bind('<Right>', self.next_move)

		#Label(app,background=bg).grid(column=1,row=2)

		row=10

		#Label(self,background=bg).grid(column=1,row=row-1)

		#self.goban1 = Canvas(self, width=10, height=10,bg=bg,bd=0, borderwidth=0)
		self.goban1 = Goban(self.dim,master=self, width=10, height=10,bg=bg,bd=0, borderwidth=0)
		
		self.goban1.grid(column=1,row=row)
		Label(self, text='            ',background=bg).grid(column=2,row=row)
		#self.goban2 = Canvas(self, width=10, height=10,bg=bg,bd=0, borderwidth=0)
		self.goban2 = Goban(self.dim, master=self, width=10, height=10,bg=bg,bd=0, borderwidth=0)
		self.goban2.grid(column=3,row=row)

		self.goban1.space=self.goban_size/(self.dim+1+1)
		self.goban2.space=self.goban_size/(self.dim+1+1)

		Label(self,text='   ',background=bg).grid(column=4,row=row+1)
		
		police = tkFont.nametofont("TkFixedFont")
		lpix = police.measure("a")

		self.comment_box1=ScrolledText(self,font=police,wrap="word",width=int(self.goban_size/lpix-2),height=5,foreground='black')
		self.comment_box1.grid(column=1,row=row+4)
		
		self.comment_box2=ScrolledText(self,font=police,wrap="word",width=int(self.goban_size/lpix-2),height=5,foreground='black')
		self.comment_box2.grid(column=3,row=row+4)
		
		self.status_bar=Label(self,text='',background=bg)
		self.status_bar.grid(column=1,row=row+5,sticky=W,columnspan=3)
		
		#Label(self,text='   ',background=bg).grid(column=4,row=row+6)
		
		goban.show_variation=self.show_variation
		
	def set_status(self,msg):
		self.status_bar.config(text=msg)
		
	def clear_status(self):
		self.status_bar.config(text="")
Exemplo n.º 33
0
class OcsGenericEntityGui(Frame):

    # +
    # __init__ method
    # -
    def __init__(self, parent=None, system='', entity='', standalone=True):

        # get arguments
        self._parent = parent
        self._system = system
        self._entity = entity
        self._standalone = standalone

        # declare some variables and initialize them
        self._device = None
        self._parameter = None
        self._startid = None
        self._value = None

        self.result = None

        # create an instance of this generic entity
        self._this = OcsGenericEntity(self._system, self._entity, False)

        # now add the GUI stuff
        Frame.__init__(self,
                       self._parent,
                       bd=1,
                       relief=SUNKEN,
                       bg=ocsGenericEntityBackgroundColour.get(
                           self._system, OCS_GENERIC_ENTITY_BACKGROUND_COLOUR))
        Label(self._parent,
              text='{0:s} {1:s}'.format(self._system, self._entity),
              foreground='blue',
              bg=ocsGenericEntityBackgroundColour.get(
                  self._system, OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
              font=('helvetica', 12, 'normal')).grid(row=0, sticky=NSEW)
        # Label(self._parent, text=self._entity, foreground='blue', bg=ocsGenericEntityBackgroundColour.get(
        #    self._system, OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
        #    font=('helvetica', 12, 'bold')).grid(row=1, sticky=NSEW)
        self.create_generic_buttons(self._parent, self._system)

        # Add text widget to display logging info
        self._st = ScrolledText(self._parent, state='disabled')
        self._st.configure(font='TkFixedFont')
        self._st.grid(column=0, row=1, sticky='w', columnspan=1)
        self._th = OcsTextHandler(self._st)

        # Add the handler to logger
        self._this.logger.addHandler(self._th)

        self._simFlag = BooleanVar()
        self._simFlag.set(False)
        self._this._simulate = self._simFlag.get()
        # self._this.logger.debug("self._this._simulate = {0:d}".format(self._this._simulate))

        self.sim_widget = Checkbutton(self._parent,
                                      text='SIMULATION',
                                      variable=self._simFlag,
                                      height=2)
        self.sim_widget.config(fg='black',
                               bg=ocsGenericEntityBackgroundColour.get(
                                   self._system,
                                   OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                               font=('helvetica', 10, 'roman'))
        self.sim_widget.grid(row=2, sticky=NSEW)

        self._simFlag.trace('w', self.sim_change)
        self._simFlag.set(True)

        Label(self._parent,
              text='Generic Commands',
              foreground='blue',
              bg=ocsGenericEntityBackgroundColour.get(
                  self._system, OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
              font=('helvetica', 10, 'italic')).grid(row=3, sticky=NSEW)
        Label(self._parent,
              text='Business Logic Commands',
              foreground='blue',
              bg=ocsGenericEntityBackgroundColour.get(
                  self._system, OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
              font=('helvetica', 10, 'italic')).grid(row=11, sticky=NSEW)
        Label(self._parent,
              text='Behavioural Commands',
              foreground='blue',
              bg=ocsGenericEntityBackgroundColour.get(
                  self._system, OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
              font=('helvetica', 10, 'italic')).grid(row=14, sticky=NSEW)

        if self._standalone:
            OcsQuitButton(self._parent).grid(row=23, sticky=NSEW)

    # +
    # (trace) method(s)
    # -
    def sim_change(self, *args):
        self._this.logger.debug("args = {0:s}".format(str(args)))
        simflag = self._simFlag.get()
        self._this._simulate = simflag
        if simflag:
            self.sim_widget.config(bg='#ff4040',
                                   font=('helvetica', 12, 'bold'))
        else:
            self.sim_widget.config(bg="#00ee00",
                                   font=('helvetica', 12, 'roman'))
        # self._this.logger.debug("self._this._simulate = {0:d}".format(self._this._simulate))

    # +
    # (deferred) methods()
    # -
    def get_command_dialog_string(self, name=''):
        s = 'generic command dialog box'
        for e1 in self._this.generic_help:
            t = e1.split()
            if t[0].lower() == name.lower():
                return e1
        return s

    # +
    # (command) methods()
    # -
    def abort_handler(self):
        if self._this:
            self._this.abort()

    def disable_handler(self):
        if self._this:
            self._this.disable()

    def enable_handler(self):
        if self._this:
            self._this.enable()

    def entercontrol_handler(self):
        if self._this:
            self._this.entercontrol()

    def exitcontrol_handler(self):
        if self._this:
            self._this.exitcontrol()

    def setvalue_handler(self):
        OcsEntryDialog(self, self.get_command_dialog_string('setvalue'),
                       ['Parameter', 'Value'])
        if self._this:
            if self.result:
                self._parameter = self.result['Parameter']
                self._value = self.result['Value']
                self._this.logger.debug(
                    "calling self._this.setvalue('{0:s}', '{1:s}')".format(
                        str(self._parameter), str(self._value)))
                self._this.setvalue(parameter=self._parameter,
                                    value=self._value)
            else:
                self._parameter = ''
                self._value = ''
                self._this.logger.debug(
                    "self._this.setvalue('{0:s}', '{1:s}') cancelled".format(
                        str(self._parameter), str(self._value)))

    def standby_handler(self):
        if self._this:
            self._this.standby()

    def start_handler(self):
        OcsEntryDialog(self, self.get_command_dialog_string('start'),
                       ['StartId'])
        if self._this:
            if self.result:
                self._startid = self.result['StartId']
                self._this.logger.debug(
                    "calling self._this.start('{0:s}')".format(
                        str(self._startid)))
                self._this.start(startid=self._startid)
            else:
                self._startid = ''
                self._this.logger.debug(
                    "self._this.start('{0:s}') cancelled".format(
                        str(self._startid)))

    def stop_handler(self):
        OcsEntryDialog(self, self.get_command_dialog_string('stop'),
                       ['Device'])
        if self._this:
            if self.result:
                self._device = self.result['Device']
                self._this.logger.debug(
                    "calling self._this.stop('{0:s}')".format(str(
                        self._device)))
                self._this.stop(device=self._device)
            else:
                self._device = ''
                self._this.logger.debug(
                    "self._this.stop('{0:s}') cancelled".format(
                        str(self._device)))

    # +
    # createGenericButtons() method
    # -
    def create_generic_buttons(self, _parent=None, system=''):
        self._parent = _parent
        self._system = system
        for e2 in self._this.generic_help:
            t = e2.split()
            tl = t[0].lower()
            if tl == 'abort':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.abort_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=12, sticky=NSEW)
            elif tl == 'disable':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.disable_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=4, sticky=NSEW)
            elif tl == 'enable':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.enable_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=5, sticky=NSEW)
            elif tl == 'entercontrol':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.entercontrol_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=6, sticky=NSEW)
            elif tl == 'exitcontrol':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.exitcontrol_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=7, sticky=NSEW)
            elif tl == 'setvalue':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.setvalue_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=8, sticky=NSEW)
            elif tl == 'start':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.start_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=9, sticky=NSEW)
            elif tl == 'standby':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.standby_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=10, sticky=NSEW)
            elif tl == 'stop':
                widget = Button(self._parent,
                                text=t[0],
                                bg=ocsGenericEntityBackgroundColour.get(
                                    self._system,
                                    OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                                command=self.stop_handler,
                                font=('helvetica', 12, 'normal'),
                                state=NORMAL)
                widget.grid(row=13, sticky=NSEW)
            else:
                pass

        for e3 in range(15, 23):
            widget = Button(self._parent,
                            text='-',
                            bg=ocsGenericEntityBackgroundColour.get(
                                self._system,
                                OCS_GENERIC_ENTITY_BACKGROUND_COLOUR),
                            font=('helvetica', 12, 'normal'),
                            state=DISABLED)
            widget.grid(row=e3, sticky=NSEW)
Exemplo n.º 34
0
class PyGrbl_Editor(Frame):
    def __init__(self, master, app):
        Frame.__init__(self, master = master)

        ##  WHO AM I ?
        #print("Who am I:  " + self.winfo_class())  # = 'Frame' !!
        #print("Who is my master: " + master.__class__.__name__) # = Frame
        #print("Who is my app: " + app.__class__.__name__) # = PyGrbl_GUI
        #print("Who am I:  " + self.__class__.__name__) # = 'PyGrbl_Editor'

        self.app = app
        self.app.servicemenu.entryconfig("Editor", state = "normal")
        self.app.apps.append(self.__class__.__name__)
        self.openFileTrace = self.app.fileOpenFlag.trace_variable('w', self.fileOpenTraceAction)

        self.editorWaiting = False # to prevent conflict gCodeChecker & Editor 'fileOpenTrace'

        self.createEditorWidgets()
        
        self.master.rowconfigure(0, weight = 1)
        self.master.columnconfigure(0, weight = 1)
        self.grid(column = 0, row = 0, sticky = (N, S, W, E))


    def createEditorWidgets(self):
        # Text Pad
        self.textPad = ScrolledText(self, width = 30, height = 10, font = "TkTextFont")
        self.textPad.grid(row = 0, column = 0, padx = 10, pady = 10, sticky = (N, S, W, E))
        self.columnconfigure(0, weight = 1)
        self.rowconfigure(0, weight = 1)

        self.save = Button(self, text = "Save", width = 6, command = lambda: self.saveFile())
        self.save.grid(row = 0, column = 1, padx = 10, pady = 10, sticky = N)

    def fileOpenTraceAction(self, name, index, mode):
        try:
            if self.app.fileOpenFlag.get() == True:
                if self.app.currentApp == self.app.Editor:
                    contents = self.app.inFile.read()
                    contents = contents.replace('\r', '')
                    self.app.inFile.seek(0) # reset inFile cursor to top of file
                    self.textPad.insert(1.0, contents)
                elif self.editorWaiting:
                    contents = self.app.inFile.read()
                    self.app.inFile.seek(0) # reset inFile cursor to top of file
                    self.textPad.insert(1.0, contents)
                    self.editorWaiting = False
                else:
                    self.editorWaiting = True
                    self.after(1000, self.fileOpenTraceAction(name, index, mode))

            elif self.app.fileOpenFlag.get() == False:
                self.textPad.delete(1.0, END)

            if self.app.debugMode > 1: print("fileOpenTraceAction: Ok")

        except:
            print("fileOpenTraceAction: Error")

    def saveFile(self):
        filename = asksaveasfile(mode = 'w')
        if filename:
            data = self.textPad.get(1.0, END+'-1c')
            filename.write(data)
            filename.close()
Exemplo n.º 35
0
class MipsxTkGui(Frame):
    def __init__(self, parent, control):

        Frame.__init__(self, parent)

        self.parent = parent

        self.parent.title("Mipsx - GUI for gdb multiarch")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        # Para expandir cuando las ventanas cambian de tamao
        for i in range(3):
            self.columnconfigure(i, weight=1)
        for i in range(20):
            self.rowconfigure(i, weight=1)

        lbl = Label(self, text="Registros")
        lbl.grid(row=1, column=2, sticky=W, pady=4, padx=5)

        self.registros = Text(self, height=12, width=80)
        self.registros.grid(row=2,
                            column=2,
                            columnspan=1,
                            rowspan=5,
                            sticky=E + W + S + N)

        lbl = Label(
            self,
            text=
            "Programa en Assembler y Prorama Binario Decodificado (disassemble) "
        )
        lbl.grid(row=7, column=2, pady=1, padx=1, sticky=W + N + E + S)

        self.programa = Text(self, height=6, width=80)
        self.programa.grid(row=8,
                           column=2,
                           columnspan=1,
                           rowspan=5,
                           padx=1,
                           sticky=E + W + S + N)

        lbl = Label(
            self,
            text=
            'Memoria - Segmento de datos (debe existir la etiqueta "memoria") - Segmento de texto - Pila'
        )
        lbl.grid(row=13, column=2, pady=1, padx=1, sticky=W + N + E + S)

        self.memoria = Text(self, height=15, width=80)
        self.memoria.grid(row=14,
                          column=2,
                          columnspan=1,
                          rowspan=5,
                          padx=1,
                          sticky=E + W + S + N)

        lbl4 = Label(self, text="Mensajes de Depuracion")
        lbl4.grid(row=13, column=0, pady=1, padx=1, sticky=W + N + E + S)

        self.mensajes = Text(self, height=8, width=60)
        self.mensajes.grid(row=14,
                           column=0,
                           columnspan=1,
                           rowspan=5,
                           padx=1,
                           sticky=E + W + S + N)

        lbl = Label(self, text="Editor del Programa")
        lbl.grid(row=1, column=0, sticky=W, pady=4, padx=5)

        self.editor = ScrolledText(self, height=20, width=60)
        self.editor.grid(row=2,
                         column=0,
                         columnspan=1,
                         rowspan=10,
                         padx=1,
                         sticky=E + W + S + N)

        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)

        menu.add_cascade(label="Archivo", menu=filemenu)
        filemenu.add_command(label="Nuevo", command=control.nuevo)
        filemenu.add_command(label="Abrir...", command=control.abrir)
        filemenu.add_command(label="Guardar...", command=control.guardar)
        filemenu.add_separator()
        filemenu.add_command(label="Salir", command=control.salir)

        menu.add_command(label="Run", command=control.ejecutar)
        menu.add_command(label="Next", command=control.prox_instruccion)
        menu.add_command(label="Breakpoint", command=control.no_hacer_nada)
        menu.add_command(label="Compilar y Cargar",
                         command=control.compilarycargar)

        helpmenu = Menu(menu)
        menu.add_cascade(label="Ayuda", menu=helpmenu)
        helpmenu.add_command(label="Acerca de...", command=control.acercade)
        menu.add_command(label="Salir", command=control.salir)

    def limpiar_panel(self, panel):
        panel.delete('1.0', END)

    def panel_agregar(self, panel, contenido):
        panel.insert(END, contenido)

    def panel_leer(self, panel):
        return panel.get('1.0', END + '-1c')

    def mostrar_en_area(self, area):
        area.insert(END, contents)

    # Al abrir un archivo deseamos tener un area de trabajo cero
    def limpiar_paneles(self):
        self.mensajes.delete('1.0', END)
        self.memoria.delete('1.0', END)
        self.programa.delete('1.0', END)
        self.registros.delete('1.0', END)
Exemplo n.º 36
0
class GuiPart:
    def __init__(self, master, queue, queue2, endCommand):
        self.queue = queue
        self.queue2 = queue2
        self.msg = ""
        self.targetpics = []
        self.currentImage = -1
        
        # Set up the GUI
        console = Tkinter.Button(master, text='Done', command=endCommand)
        console.grid(row=3, column=1, sticky=Tkinter.W)

        #Telemetry Window
        self.tele = ScrolledText(master, width=50, height=10, wrap='word')
        self.tele.insert('end', 'Awaiting Telemetry...\n----------------------\n')
        self.tele.grid(row=0, column=1, columnspan=1, padx=5, pady=5)

        #Receiving Targets Window
        self.rt = ScrolledText(master, width=50, height=10, wrap='word')
        self.rt.insert('end', 'Awaiting Target Data...\n------------------------\n')
        self.rt.grid(row=0, column=3, columnspan=1, padx=5, pady=5)

        #Image
        img = Tkinter.PhotoImage(file="logo.gif")
        logo = Tkinter.Label(master, image = img)
        logo.image=img
        logo.grid(row=0, column=2, padx=5, pady=5)

        #Obstacles Button
        obs_but = Tkinter.Button(master, text='Retreive Obstacles From Server', command=self.getObstacles)
        obs_but.grid(row=1, column=1, sticky=Tkinter.W)

        #General Terminal Button
        gt_but = Tkinter.Button(master, text='Submit Data', command=endCommand)
        gt_but.grid(row=1, column=2, sticky=Tkinter.W)

        #Upload Targets Button
        ut_but = Tkinter.Button(master, text='Upload Target Data', command=endCommand)
        ut_but.grid(row=1, column=3, sticky=Tkinter.W)

        #Receiving Obstacles Window
        self.obs = ScrolledText(master, width=50, height=10, wrap='word')
        self.obs.insert('end', 'Ready for Obstacle Data...\n--------------------------\n')
        self.obs.grid(row=2, column=1, columnspan=1, padx=5, pady=5)

        #General Terminal Window
        self.gt = ScrolledText(master, width=50, height=10, wrap='word')
        self.gt.insert('end', 'Enter in Server Query...\n------------------------\n')
        self.gt.grid(row=2, column=2, columnspan=1, padx=5, pady=5)

        #Upload Targets Window
        self.ut = ScrolledText(master, width=50, height=10, wrap='word')
        self.ut.insert('end', 'Enter in Target Data...\n------------------------\n')
        self.ut.grid(row=2, column=3, columnspan=1, padx=5, pady=5)

        #General Terminal Text Area
        self.gt_text = Tkinter.Entry(master, bd=5, width=70)
        self.gt_text.grid(row=3, column=2, columnspan=1, padx=5, pady=5)

        #Target Picture Buttons
        pane = Tkinter.PanedWindow()
        rti_prev = Tkinter.Button(master, text='Prev Picture', command=self.prevPic)
        pane.add(rti_prev)
        self.rti_label = Tkinter.Label(master, text='Awaiting Target')
        rti_next = Tkinter.Button(master, text='Next Picture', command=self.nextPic)
        pane.add(rti_next)
        pane.add(self.rti_label)
        pane.grid(row=4, column=2, padx=5, pady=5)

        #Target Images
        rtimg = Tkinter.PhotoImage(file="target.gif")
        self.rti = Tkinter.Label(master, image = rtimg)
        self.rti.image=rtimg
        self.rti.grid(row=5, column=2, columnspan=1, padx=5, pady=5)
        
        # Add more GUI stuff here

    def processIncoming(self):
        """
        Handle all the messages currently in the queue (if any).
        """
        #self.counter = 0
        while self.queue.qsize():
            try:
                self.msg = str(self.queue.get(0)) + '\n'
                # Check contents of message and do what it says
                # As a test, we simply print it
                self.tele.insert('end', self.msg)
                self.msg2 = self.queue2.get(0) + '\n'
                if(self.msg2.find('Target') == 0):
                    #self.targetpics[self.counter] = self.msg2
                    self.targetpics.append(self.msg2)
                    #self.counter += 1
                else:
                    self.rt.insert('end', self.msg2)
            except Queue.Empty:
                pass
    
    def getObstacles(self):
        # GET obstacles request

        c = pycurl.Curl()

        buffer = StringIO()
        c.setopt(pycurl.URL, interop_api_url+'obstacles')
        c.setopt(pycurl.WRITEDATA, buffer)
        c.setopt(pycurl.COOKIEFILE, 'sessionid.txt')
        c.perform()

        obstacles_json = json.loads(buffer.getvalue())

        print("\n\n" + "====Obstacles====")
        obstacles = json.dumps(obstacles_json, sort_keys=True,indent=4, separators=(',', ': '))
        print obstacles
        self.obs.insert('end', obstacles)
    
    def nextPic(self):
        if(self.currentImage < len(self.targetpics) - 1):
            self.currentImage += 1
            self.nextImage = Tkinter.PhotoImage(file='Photos/' + self.targetpics[self.currentImage].strip())
            self.rti.configure(image=self.nextImage)
            self.rti.image = self.nextImage
            self.rti_label.configure(text=self.targetpics[self.currentImage].strip())

    def prevPic(self):
        if(self.currentImage > 0):
            self.currentImage -= 1
            self.nextImage = Tkinter.PhotoImage(file='Photos/' + self.targetpics[self.currentImage].strip())
            self.rti.configure(image=self.nextImage)
            self.rti.image = self.nextImage
            self.rti_label.configure(text=self.targetpics[self.currentImage].strip())
Exemplo n.º 37
0
class PatchClampGUI(Frame):
    """
    Simple GUI for the patch clamp robot.
    Controls:
        conect/disconnect robot (controller, arm, camera, amplifier and pump to be specified)
        Launch auto calibration
        Load previous calibration
        Set position to Zero
        Positionning pipette when left clicking on camera window
        Patch (and clamp if enable) at given position by right clicking on camera window
        Enable/disable clamp when right clicking
        Clamping
        Enable/disable pipette following the camera
        Enable/disable resistance metering
        Check pipette resistance for patch
    """
    def __init__(self, master=None):
        Frame.__init__(self, master)

        # State variables
        self.pause = 0
        self.calibrated = 0

        # Variables for manipulator, microscope
        self.robot = None
        self.controller = None
        self.arm = None
        self.camera = None
        self.amplifier = None
        self.pump = None
        self.continuous = IntVar()
        self.follow = IntVar()

        # GUI

        # Connection to robot
        self.robot_box = LabelFrame(self, text='Connection')
        self.robot_box.grid(row=0, column=0, padx=5, pady=5)

        # Controller
        self.ask_controller = Label(self.robot_box, text='Controller: ')
        self.ask_controller.grid(row=0, column=0, padx=2, pady=2)

        self.controllist = ttk.Combobox(self.robot_box,
                                        state='readonly',
                                        values='SM5 SM10')
        self.controllist.grid(row=0, column=1, columnspan=2, padx=2, pady=2)

        # Arm
        self.ask_arm = Label(self.robot_box, text='Arm: ')
        self.ask_arm.grid(row=1, column=0, padx=2, pady=2)

        self.armlist = ttk.Combobox(self.robot_box,
                                    state='readonly',
                                    values='dev1 dev2 Arduino')
        self.armlist.grid(row=1, column=1, columnspan=2, padx=2, pady=2)

        # Camera
        self.ask_camera = Label(self.robot_box, text='Camera: ')
        self.ask_camera.grid(row=2, column=0, padx=2, pady=2)

        self.camlist = ttk.Combobox(self.robot_box,
                                    state='readonly',
                                    values='Hamamatsu Lumenera')
        self.camlist.grid(row=2, column=1, columnspan=2, padx=2, pady=2)

        # Amplifier
        self.ask_amp = Label(self.robot_box, text='Amplifier: ')
        self.ask_amp.grid(row=3, column=0, padx=2, pady=2)

        self.amplist = ttk.Combobox(self.robot_box,
                                    state='readonly',
                                    values='FakeAmplifier Multiclamp')
        self.amplist.grid(row=3, column=1, columnspan=2, padx=2, pady=2)

        # Pump for pressure control
        self.ask_pump = Label(self.robot_box, text='Pump: ')
        self.ask_pump.grid(row=4, column=0, padx=2, pady=2)

        self.pumplist = ttk.Combobox(self.robot_box,
                                     state='readonly',
                                     values='FakePump OB1')
        self.pumplist.grid(row=4, column=1, columnspan=2, padx=2, pady=2)

        # Connection button
        self.connection = Button(self.robot_box,
                                 text='Connect',
                                 command=self.connect,
                                 bg='green',
                                 fg='white')
        self.connection.grid(row=5, column=0, padx=2, pady=2)

        # disconnection button
        self.disconnection = Button(self.robot_box,
                                    text='Disconnect',
                                    command=self.disconnect,
                                    state='disable')
        self.disconnection.grid(row=5, column=1, padx=2, pady=2)

        # Top right frame
        self.tr = LabelFrame(self, bd=0)
        self.tr.grid(row=0, column=1, padx=2, pady=2)

        # Auto calibration
        self.calibrate_box = LabelFrame(self.tr, text='Calibration')
        self.calibrate_box.grid(row=0, column=0, padx=2, pady=2)

        # Begin calibration button
        self.calibrate = Button(self.calibrate_box,
                                text='Calibrate',
                                command=self.calibration,
                                state='disable')
        self.calibrate.grid(row=0, column=0, padx=2, pady=2)

        # Load the previous calibration button
        self.load_calibrate = Button(self.calibrate_box,
                                     text='Load calibration',
                                     command=self.load_cali,
                                     state='disable')
        self.load_calibrate.grid(row=0, column=1, padx=2, pady=2)

        # Message to indicate if robot is calibrated or not
        self.calibrate_msg = Label(self.calibrate_box,
                                   text='Robot is NOT calibrated !',
                                   fg='red')
        self.calibrate_msg.grid(row=1, column=0, padx=2, pady=2, columnspan=3)

        # PUMP
        self.pump_box = LabelFrame(self.tr, text='Pressure controller')
        self.pump_box.grid(row=1, column=0, padx=2, pady=2)

        # Patch button
        self.patch = Button(self.pump_box, text='Seal', state='disable')
        self.patch.grid(row=0, column=0, padx=2, pady=2)

        # Clamp button
        self.clamp = Button(self.pump_box, text='Break-in', state='disable')
        self.clamp.grid(row=0, column=1, padx=2, pady=2)

        # Nearing button
        self.nearing = Button(self.pump_box, text='Nearing', state='disable')
        self.nearing.grid(row=0, column=2, padx=2, pady=2)

        # High pressure
        self.push = Button(self.pump_box, text='Push', state='disable')
        self.push.grid(row=0, column=3, padx=2, pady=2)

        # Clamp when right click on/off
        self.clamp_switch = Checkbutton(self.pump_box,
                                        text='Break-in when clicking',
                                        command=self.enable_clamp,
                                        state='disable')
        self.clamp_switch.grid(row=1, column=0, padx=2, pady=2, columnspan=2)

        # release button
        self.release = Button(self.pump_box, text='Release', state='disable')
        self.release.grid(row=1, column=2, padx=2, pady=2)

        # Control of amplifier
        self.meter_box = LabelFrame(self, text='Metering')
        self.meter_box.grid(row=1, column=1, padx=2, pady=2)

        # Selection of meter: potential or resistance
        self.chosen_meter = IntVar()
        self.choose_resistance = Radiobutton(self.meter_box,
                                             text='Resistance metering',
                                             variable=self.chosen_meter,
                                             value=1,
                                             command=self.switch_meter)
        self.choose_resistance.select()
        self.choose_resistance.grid(row=0, column=0, padx=2, pady=2)

        self.choose_potential = Radiobutton(self.meter_box,
                                            text='Potential metering',
                                            variable=self.chosen_meter,
                                            value=2,
                                            command=self.switch_meter)
        self.choose_potential.grid(row=0, column=1, padx=2, pady=2)

        # display resistance
        self.res_window = Label(self.meter_box, text='Resistance: ')
        self.res_window.grid(row=1, column=0, padx=2, pady=2)

        self.res_value = Label(self.meter_box, text='0 Ohm')
        self.res_value.grid(row=1, column=1, padx=2, pady=2)

        self.potential_window = Label(self.meter_box, text='Potential')
        self.potential_window.grid(row=2, column=0, padx=2, pady=2)

        self.potential_value = Label(self.meter_box, text='0 V')
        self.potential_value.grid(row=2, column=1, padx=2, pady=2)

        # Check the resistance of the pipette for patching button

        # continuous resistance metering on/off
        self.continuous_meter = Checkbutton(
            self.meter_box,
            text='Continuous metering',
            variable=self.continuous,
            command=self.switch_continuous_meter,
            state='disable')
        self.continuous_meter.grid(row=3, column=0, padx=2, pady=2)

        self.check_pipette_resistance = Button(self.meter_box,
                                               text='Check pipette',
                                               command=self.init_patch_clamp,
                                               state='disable')
        self.check_pipette_resistance.grid(row=3, column=1, padx=2, pady=2)

        # Other controls
        self.misc = LabelFrame(self, text='misc')
        self.misc.grid(row=1, column=0, padx=2, pady=2)

        # reset postion
        self.zero = Button(self.misc,
                           text='Go to zero',
                           command=self.reset_pos,
                           state='disable')
        self.zero.grid(row=0, column=0, padx=2, pady=2)

        # Save position
        self.save_pos = Button(self.misc,
                               text='Save position',
                               state='disable')
        self.save_pos.grid(row=0, column=1, padx=2, pady=2)

        # Pipette follow camera on/off
        self.switch_follow = Checkbutton(self.misc,
                                         text='Following',
                                         command=self.following,
                                         variable=self.follow,
                                         state='disable')
        self.switch_follow.grid(row=1, column=0, padx=2, pady=2)

        self.offset_slide = Scale(self.misc, from_=0, to=20, orient=HORIZONTAL)
        self.offset_slide.set(2)
        self.offset_slide.grid(row=1, column=1, padx=2, pady=2)

        self.follow_paramecia = IntVar()
        self.paramecia = Checkbutton(self.misc,
                                     text='paramecia',
                                     variable=self.follow_paramecia,
                                     command=self.switch_follow_paramecia,
                                     state='disable')
        self.paramecia.grid(row=2, column=0, padx=2, pady=2)

        self.screenshots = Button(self.misc,
                                  text='Screenshot',
                                  state='disable')
        self.screenshots.grid(row=2, column=1, padx=2, pady=2)

        # Messages zone
        self.text_zone = ScrolledText(master=self,
                                      width=60,
                                      height=10,
                                      state='disabled')
        self.text_zone.grid(row=2, column=0, columnspan=3)

        # Quit button
        self.QUIT = Button(self,
                           text='QUIT',
                           bg='orange',
                           fg='white',
                           command=self.exit)
        self.QUIT.grid(row=3, column=0, padx=2, pady=2)

        # Stop button
        self.emergency_stop = Button(self,
                                     text='STOP',
                                     bg='red',
                                     fg='white',
                                     command=self.stop_moves)
        self.emergency_stop.grid(row=3, column=1, padx=2, pady=2)

        self.message = ''

        self.pack()

    def connect(self):
        """
        Connect to the robot
        """
        # Devices to connect to
        self.controller = self.controllist.get()
        self.arm = self.armlist.get()
        self.amplifier = self.amplist.get()
        self.pump = self.pumplist.get()
        self.camera = self.camlist.get()

        # Checking primordial devices have been specified: controller, arm and camera
        if not self.controller:
            showerror('Connection error', 'Please specify a controller.')
        elif not self.arm:
            showerror('Connection error',
                      'Please specify a device for the arm.')
        elif not self.camera:
            showerror('Connection error', 'Please specify a camera.')
        else:
            # Connection to the robot
            self.robot = PatchClampRobot(self.controller, self.arm,
                                         self.camera, self.amplifier,
                                         self.pump, False)

            # Setting messages
            self.message = self.robot.message

            # Disable connection buttons and lists
            self.controllist['state'] = 'disabled'
            self.armlist['state'] = 'disabled'
            self.amplist['state'] = 'disabled'
            self.camlist['state'] = 'disabled'
            self.pumplist['state'] = 'disabled'
            self.connection.config(state='disable')

            # Activate all the others buttons
            self.load_calibrate.config(state='normal')
            self.calibrate.config(state='normal')
            self.zero.config(state='normal')
            self.disconnection.config(state='normal')
            self.continuous_meter.config(state='normal')
            self.check_pipette_resistance.config(state='normal')
            self.patch.config(state='normal', command=self.robot.pressure.seal)
            self.release.config(state='normal',
                                command=self.robot.pressure.release)
            self.nearing.config(state='normal',
                                command=self.robot.pressure.nearing)
            self.push.config(state='normal',
                             command=self.robot.pressure.high_pressure)
            self.clamp.config(state='normal', command=self.robot.clamp)
            self.clamp_switch.config(state='normal')
            self.switch_follow.config(state='normal')
            self.save_pos.config(state='normal',
                                 command=self.robot.save_position)
            self.paramecia.config(state='normal')
            self.screenshots.config(state='normal',
                                    command=self.robot.save_img)

            # Checking changes of robot messages and display them
            self.check_message()
        pass

    def disconnect(self):
        """
        Disconnect the robot. For now reconnection doesn't work (controller not really disconnected)
        :return: 
        """
        # stoping threads linked to the robot
        self.robot.stop()
        del self.robot
        self.robot = None

        # Disable all buttons and enable connection buttons
        self.calibrate.config(state='disable')
        self.load_calibrate.config(state='disable')
        self.zero.config(state='disable')
        self.controllist['state'] = 'readonly'
        self.armlist['state'] = 'readonly'
        self.amplist['state'] = 'readonly'
        self.camlist['state'] = 'readonly'
        self.pumplist['state'] = 'readonly'
        self.connection.config(state='normal')
        self.disconnection.config(state='disable')
        self.check_pipette_resistance.config(state='disable')
        self.clamp.config(state='disable', command=None)
        self.patch.config(state='disable', command=None)
        self.release.config(state='disable', command=None)
        self.nearing.config(state='disable', command=None)
        self.push.config(state='disable', command=None)
        self.save_pos.config(state='disable', command=None)
        self.clamp_switch.config(state='disable')
        self.switch_follow.config(state='disable')
        pass

    def calibration(self):
        """
        Launch auto calibration
        :return: 
        """
        if self.robot:
            # Connection to the robot has been established
            if askokcancel(
                    'Calibrating',
                    'Please put the tip of the pipette in focus and at the center of the image.',
                    icon=INFO):
                # Pipette in focus and centered: calibrating
                self.robot.event['event'] = 'Calibration'
                self.wait_calibration()
            pass

    def wait_calibration(self):
        if self.robot.event['event'] == 'Calibration':
            self.after(10, self.wait_calibration)
        elif self.robot.calibrated:
            self.calibrate_msg.config(text='Robot calibrated', fg='black')

    def load_cali(self):
        """
        Loads previous calibration
        :return: 
        """
        if self.robot:
            # Connection to the robot has been established
            if askokcancel(
                    'Loading calibration',
                    'Please put the tip of the pipette in focus and at the center of the image.',
                    icon=INFO):
                # Pipette in focus and centered: loading calibration
                self.robot.load_calibration()
                if self.robot.calibrated:
                    self.calibrate_msg.config(text='Robot calibrated',
                                              fg='black')
            pass

    def reset_pos(self):
        """
        Reset position to null position
        :return: 
        """
        if self.robot:
            self.robot.go_to_zero()
        pass

    def get_res(self):
        """
        Retrieve the resistance metered by robot.
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.res_value['text'] = self.robot.get_resistance(res_type='text')
            with open('Resistance.txt', 'at') as f:
                f.write(str(self.robot.get_resistance()) + '\n')
            if self.continuous.get():
                # Retrieving continuoulsy enabled
                if (self.chosen_meter.get() == 1) | (
                        self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_resistance.select()
                    self.after(10, self.get_res)
                elif (self.chosen_meter.get() == 2) | (
                        not self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_potential.select()
                    self.after(10, self.get_pot)
        pass

    def get_pot(self):
        """
        Retrieve the resistance metered by robot.
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.potential_value['text'] = self.robot.get_potential(
                res_type='text')
            if self.continuous.get():
                # Retrieving continuoulsy enabled
                if (self.chosen_meter.get() == 1) | (
                        self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_resistance.select()
                    self.after(10, self.get_res)
                elif (self.chosen_meter.get() == 2) | (
                        not self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_potential.select()
                    self.after(10, self.get_pot)
        pass

    def init_patch_clamp(self):
        """
        Checks if conditions for patching are met (pipette resistance)
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.choose_resistance.select()
            if self.robot.init_patch_clamp():
                # Conditions are met, enable continous resistance metering
                self.continuous_meter.select()
                self.choose_resistance.select()
                self.switch_continuous_meter()
                file_res = open('Resistance.txt', 'wt')
                file_res.close()
        pass

    def enable_clamp(self):
        """
        Enable/disable calmp when right clicking on the camera window
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.robot.enable_clamp ^= 1
        pass

    def switch_continuous_meter(self):
        """
        Enable/Disable continuous resistance metering
        :return: 
        """
        if self.robot:
            if self.continuous.get():
                # Continuous metering button is checked, activate continuous metering
                self.robot.set_continuous_meter(True)

                if self.chosen_meter.get() == 1:
                    self.get_res()
                elif self.chosen_meter.get() == 2:
                    self.get_pot()
            else:
                # Continuous metering button unchecked, deactivate continuous metering
                self.robot.set_continuous_meter(False)
        pass

    def switch_meter(self):
        if self.robot:
            if self.chosen_meter.get() == 1:
                self.robot.amplifier.meter_resist_enable(True)
            elif self.chosen_meter.get() == 2:
                self.robot.amplifier.meter_resist_enable(False)

    def following(self):
        """
        Enable/disable pipette following the camera 
        :return: 
        """
        if self.robot:
            # Connection of robot established, enable folowing if follow button is checked
            self.robot.following = self.follow.get()
        pass

    def switch_follow_paramecia(self):
        if self.robot:
            self.robot.follow_paramecia = self.follow_paramecia.get()

    def check_message(self):
        """
        Retrieve messages from robot and display them when they change
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.robot.offset = self.offset_slide.get()
            if self.message != self.robot.message:
                # Message memory is different from actual robot message
                self.message = self.robot.message
                if self.message[:5] == 'ERROR':
                    # The new message is an error, display the message in a new window
                    showerror('ERROR', self.message)

                # Activate the message zone, write the message and deactivate message zone (thus make a read only)
                self.text_zone.config(state='normal')
                self.text_zone.insert(INSERT, self.message + '\n')
                self.text_zone.config(state='disabled')
                self.text_zone.see(END)

                # Update memory and actual message: if same messages follow each other, both are retrieve
                self.message = ''
                self.robot.message = ''

            # Check again in 10ms
            self.after(10, self.check_message)
        pass

    def stop_moves(self):
        if self.robot:
            self.robot.arm.stop()
            self.robot.microscope.stop()

    def exit(self):
        """
        Close GUI and all threads
        :return: 
        """
        if self.robot:
            # Connection of robot established, disconnecting
            self.robot.stop()
            del self.robot
        # quit GUI
        self.quit()
Exemplo n.º 38
0
class PyAbel:  #(tk.Tk):
    def __init__(self, parent):
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.fn = None
        self.old_fn = None
        self.old_method = None
        self.old_fi = None
        self.AIM = None
        self.rmx = (368, 393)

        # matplotlib figure
        self.f = Figure(figsize=(2, 4))
        self.gs = gridspec.GridSpec(2, 2, width_ratios=[1, 2])
        self.gs.update(wspace=0.2, hspace=0.5)

        self.plt = []
        self.plt.append(self.f.add_subplot(self.gs[0]))
        self.plt.append(self.f.add_subplot(self.gs[1]))
        self.plt.append(
            self.f.add_subplot(self.gs[2],
                               sharex=self.plt[0],
                               sharey=self.plt[0]))
        self.plt.append(self.f.add_subplot(self.gs[3]))
        for i in [0, 2]:
            self.plt[i].set_adjustable('box-forced')

        # hide until have data
        for i in range(4):
            self.plt[i].axis("off")

        # tkinter
        # set default font size for buttons
        self.font = tkFont.Font(size=11)
        self.fontB = tkFont.Font(size=12, weight='bold')

        #frames top (buttons), text, matplotlib (canvas)
        self.main_container = tk.Frame(self.parent, height=10, width=100)
        self.main_container.pack(side="top", fill="both", expand=True)

        self.button_frame = tk.Frame(self.main_container)
        #self.info_frame = tk.Frame(self.main_container)
        self.matplotlib_frame = tk.Frame(self.main_container)

        self.button_frame.pack(side="top", fill="x", expand=True)
        #self.info_frame.pack(side="top", fill="x", expand=True)
        self.matplotlib_frame.pack(side="top", fill="both", expand=True)

        self._menus()
        self._button_area()
        self._plot_canvas()
        self._text_info_box()

    def _button_frame(self):
        self.button_frame = tk.Frame(self.main_container)
        self.button_frame.pack(side="top", fill="x", expand=True)
        self._menus()

    def _menus(self):
        # menus with callback ----------------
        # duplicates the button interface
        self.menubar = tk.Menu(self.parent)
        self.transform_method = tk.IntVar()

        # File - menu
        self.filemenu = tk.Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="Load image file",
                                  command=self._loadimage)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self._quit)
        self.menubar.add_cascade(label="File", menu=self.filemenu)

        # Process - menu
        self.processmenu = tk.Menu(self.menubar, tearoff=0)
        self.processmenu.add_command(label="Center image",
                                     command=self._center)
        self.submenu = tk.Menu(self.processmenu)
        for method in Abel_methods:
            self.submenu.add_radiobutton(label=method,
                                         var=self.transform_method,
                                         val=Abel_methods.index(method),
                                         command=self._transform)
        self.processmenu.add_cascade(label="Inverse Abel transform",
                                     menu=self.submenu,
                                     underline=0)

        self.processmenu.add_command(label="Speed distribution",
                                     command=self._speed)
        self.processmenu.add_command(label="Angular distribution",
                                     command=self._anisotropy)
        self.angmenu = tk.Menu(self.processmenu)
        self.menubar.add_cascade(label="Processing", menu=self.processmenu)

        # view - menu
        self.viewmenu = tk.Menu(self.menubar, tearoff=0)
        self.viewmenu.add_command(label="Raw image", command=self._display)
        self.viewmenu.add_command(label="Inverse Abel transformed image",
                                  command=self._transform)
        self.viewmenu.add_command(label="view buttons",
                                  command=self._on_buttons)
        self.menubar.add_cascade(label="View", menu=self.viewmenu)

    def _button_area(self):
        # grid layout
        # make expandable
        for col in range(5):
            self.button_frame.columnconfigure(col, weight=1)
            self.button_frame.rowconfigure(col, weight=1)

        # column 0 ---------
        # load image file button
        self.load = tk.Button(master=self.button_frame,
                              text="load image",
                              font=self.fontB,
                              command=self._loadimage)
        self.load.grid(row=0, column=0, sticky=tk.W, padx=(5, 10), pady=(5, 0))
        self.sample_image = ttk.Combobox(master=self.button_frame,
                                         font=self.font,
                                         values=[
                                             "from file", "from transform",
                                             "sample dribinski",
                                             "sample Ominus"
                                         ],
                                         width=14,
                                         height=4)
        self.sample_image.current(0)
        self.sample_image.grid(row=1, column=0, padx=(5, 10))

        # quit
        self.quit = tk.Button(master=self.button_frame,
                              text="quit",
                              font=self.fontB,
                              command=self._quit)
        self.quit.grid(row=3, column=0, sticky=tk.W, padx=(5, 10), pady=(0, 5))

        # column 1 -----------
        # center image
        self.center = tk.Button(master=self.button_frame,
                                text="center image",
                                anchor=tk.W,
                                font=self.fontB,
                                command=self._center)
        self.center.grid(row=0, column=1, padx=(0, 20), pady=(5, 0))
        self.center_method = ttk.Combobox(
            master=self.button_frame,
            font=self.font,
            values=["com", "slice", "gaussian", "image_center"],
            width=10,
            height=4)
        self.center_method.current(1)
        self.center_method.grid(row=1, column=1, padx=(0, 20))

        # column 2 -----------
        # Abel transform image
        self.recond = tk.Button(master=self.button_frame,
                                text="Abel transform image",
                                font=self.fontB,
                                command=self._transform)
        self.recond.grid(row=0, column=2, padx=(0, 10), pady=(5, 0))

        self.transform = ttk.Combobox(master=self.button_frame,
                                      values=Abel_methods,
                                      font=self.font,
                                      width=10,
                                      height=len(Abel_methods))
        self.transform.current(2)
        self.transform.grid(row=1, column=2, padx=(0, 20))

        self.direction = ttk.Combobox(master=self.button_frame,
                                      values=["inverse", "forward"],
                                      font=self.font,
                                      width=8,
                                      height=2)
        self.direction.current(0)
        self.direction.grid(row=2, column=2, padx=(0, 20))

        # column 3 -----------
        # speed button
        self.speed = tk.Button(master=self.button_frame,
                               text="speed",
                               font=self.fontB,
                               command=self._speed)
        self.speed.grid(row=0, column=5, padx=20, pady=(5, 0))

        self.speedclr = tk.Button(master=self.button_frame,
                                  text="clear plot",
                                  font=self.font,
                                  command=self._speed_clr)
        self.speedclr.grid(row=1, column=5, padx=20)

        # column 4 -----------
        # anisotropy button
        self.aniso = tk.Button(master=self.button_frame,
                               text="anisotropy",
                               font=self.fontB,
                               command=self._anisotropy)
        self.aniso.grid(row=0, column=6, pady=(5, 0))

        self.subframe = tk.Frame(self.button_frame)
        self.subframe.grid(row=1, column=6)
        self.rmin = tk.Entry(master=self.subframe,
                             text='rmin',
                             width=3,
                             font=self.font)
        self.rmin.grid(row=0, column=0)
        self.rmin.delete(0, tk.END)
        self.rmin.insert(0, self.rmx[0])
        self.lbl = tk.Label(master=self.subframe, text="to", font=self.font)
        self.lbl.grid(row=0, column=1)
        self.rmax = tk.Entry(master=self.subframe,
                             text='rmax',
                             width=3,
                             font=self.font)
        self.rmax.grid(row=0, column=2)
        self.rmax.delete(0, tk.END)
        self.rmax.insert(0, self.rmx[1])

        # turn off button interface
        self.hide_buttons = tk.Button(master=self.button_frame,
                                      text="hide buttons",
                                      font=self.fontB,
                                      command=self._hide_buttons)
        self.hide_buttons.grid(row=3, column=6, sticky=tk.E, pady=(0, 20))

    def _text_info_box(self):
        # text info box ---------------------
        self.text = ScrolledText(master=self.button_frame,
                                 height=4,
                                 fg="mediumblue",
                                 bd=1,
                                 relief=tk.SUNKEN)
        self.text.insert(
            tk.END, "Work in progress, some features may"
            " be incomplete\n\n")
        self.text.insert(
            tk.END, "To start load an image data file using"
            " 'load image' button (or file menu)\n")
        self.text.insert(tk.END, "e.g. data/O2-ANU1024.txt.bz2\n")
        self.text.grid(row=3, column=1, columnspan=3, padx=5)

    def _plot_canvas(self):
        # matplotlib canvas --------------------------
        self.canvas = FigureCanvasTkAgg(self.f, master=self.matplotlib_frame)
        #self.cid = self.canvas.mpl_connect('button_press_event', self._onclick)

        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self.parent)
        self.toolbar.update()
        self.canvas._tkcanvas.pack(anchor=tk.W,
                                   side=tk.TOP,
                                   fill=tk.BOTH,
                                   expand=1)

    def _onclick(self, event):
        print('button={:d}, x={:f}, y={:f}, xdata={:f}, ydata={:f}'.format(
            event.button, event.x, event.y, event.xdata, event.ydata))

    # call back functions -----------------------
    def _display(self):
        if self.fn is None:
            self._loadimage()

        # display image
        self.plt[0].imshow(self.IM, vmin=0)
        #rows, cols = self.IM.shape
        #r2 = rows/2
        #c2 = cols/2
        #self.a.plot((r2, r2), (0, cols), 'r--', lw=0.1)
        #self.a.plot((0, rows), (c2, c2),'r--', lw=0.1)
        #self.f.colorbar(self.a.get_children()[2], ax=self.f.gca())
        self.plt[0].set_title("raw image", fontsize=10)
        self.canvas.show()

    def _loadimage(self):

        if self.fn is not None:
            # clear old plot
            for i in range(4):
                self._clr_plt(i)
                self.plt[i].axis("off")

        self.fn = self.sample_image.get()
        # update what is occurring text box
        self.text.insert(tk.END, "\nloading image file {:s}".format(self.fn))
        self.text.see(tk.END)
        self.canvas.show()

        if self.fn == "from file":
            self.fn = askopenfilename()
            # read image file
            if ".txt" in self.fn:
                self.IM = np.loadtxt(self.fn)
            else:
                self.IM = imread(self.fn)
        elif self.fn == "from transform":
            self.IM = self.AIM
            self.AIM = None
            for i in range(1, 4):
                self._clr_plt(i)
                self.plt[i].axis("off")
            self.direction.current(0)
        else:
            self.fn = self.fn.split(' ')[-1]
            self.IM = abel.tools.analytical.sample_image(n=1001, name=self.fn)
            self.direction.current(1)  # raw images require 'forward' transform
            self.text.insert(tk.END,
                             "\nsample image: (1) Abel transform 'forward', ")
            self.text.insert(tk.END,
                             "              (2) load 'from transform', ")
            self.text.insert(tk.END,
                             "              (3) Abel transform 'inverse', ")
            self.text.insert(tk.END, "              (4) Speed")
            self.text.see(tk.END)

        # if even size image, make odd
        if self.IM.shape[0] % 2 == 0:
            self.IM = shift(self.IM, (-0.5, -0.5))[:-1, :-1]

        self.old_method = None
        self.AIM = None
        self.action = "file"
        self.rmin.delete(0, tk.END)
        self.rmin.insert(0, self.rmx[0])
        self.rmax.delete(0, tk.END)
        self.rmax.insert(0, self.rmx[1])

        # show the image
        self._display()

    def _center(self):
        self.action = "center"

        center_method = self.center_method.get()
        # update information text box
        self.text.insert(tk.END, "\ncentering image using {:s}".\
                         format(center_method))
        self.canvas.show()

        # center image via chosen method
        self.IM = abel.tools.center.center_image(self.IM,
                                                 method=center_method,
                                                 odd_size=True)
        self.text.insert(tk.END, "\ncenter offset = {:}".format(self.offset))
        self.text.see(tk.END)

        self._display()

    def _transform(self):
        #self.method = Abel_methods[self.transform_method.get()]
        self.method = self.transform.get()
        self.fi = self.direction.get()

        if self.method != self.old_method or self.fi != self.old_fi:
            # Abel transform of whole image
            self.text.insert(tk.END,"\n{:s} {:s} Abel transform:".\
                             format(self.method, self.fi))
            if "basex" in self.method:
                self.text.insert(
                    tk.END, "\nbasex: first time calculation of the basis"
                    " functions may take a while ...")
            if "direct" in self.method:
                self.text.insert(
                    tk.END, "\ndirect: calculation is slowed if Cython"
                    " unavailable ...")
            self.canvas.show()

            self.AIM = abel.Transform(self.IM,
                                      method=self.method,
                                      direction=self.fi,
                                      symmetry_axis=None)
            self.rmin.delete(0, tk.END)
            self.rmin.insert(0, self.rmx[0])
            self.rmax.delete(0, tk.END)
            self.rmax.insert(0, self.rmx[1])

        if self.old_method != self.method or self.fi != self.old_fi or\
           self.action not in ["speed", "anisotropy"]:
            self.plt[2].set_title(self.method +
                                  " {:s} Abel transform".format(self.fi),
                                  fontsize=10)
            self.plt[2].imshow(self.AIM.transform,
                               vmin=0,
                               vmax=self.AIM.transform.max() / 5.0)
            #self.f.colorbar(self.c.get_children()[2], ax=self.f.gca())
            #self.text.insert(tk.END, "{:s} inverse Abel transformed image".format(self.method))

        self.text.see(tk.END)
        self.old_method = self.method
        self.old_fi = self.fi
        self.canvas.show()

    def _speed(self):
        self.action = "speed"
        # inverse Abel transform
        self._transform()
        # update text box in case something breaks
        self.text.insert(tk.END, "\nspeed distribution")
        self.text.see(tk.END)
        self.canvas.show()

        # speed distribution
        self.radial, self.speed_dist = abel.tools.vmi.angular_integration(
            self.AIM.transform)

        self.plt[1].axis("on")
        self.plt[1].plot(self.radial,
                         self.speed_dist / self.speed_dist[10:].max(),
                         label=self.method)
        self.plt[1].axis(xmax=500, ymin=-0.05)
        self.plt[1].set_xlabel("radius (pixels)", fontsize=9)
        self.plt[1].set_ylabel("normalized intensity")
        self.plt[1].set_title("radial speed distribution", fontsize=12)
        self.plt[1].legend(fontsize=9)

        self.action = None
        self.canvas.show()

    def _speed_clr(self):
        self._clr_plt(1)

    def _clr_plt(self, i):
        self.f.delaxes(self.plt[i])
        self.plt[i] = self.f.add_subplot(self.gs[i])
        self.canvas.show()

    def _anisotropy(self):
        def P2(x):  # 2nd order Legendre polynomial
            return (3 * x * x - 1) / 2

        def PAD(theta, beta, amp):
            return amp * (1 + beta * P2(np.cos(theta)))

        self.action = "anisotropy"
        self._transform()
        # radial range over which to follow the intensity variation with angle
        self.rmx = (int(self.rmin.get()), int(self.rmax.get()))

        self.text.insert(tk.END,"\nanisotropy parameter pixel range {:} to {:}: "\
                               .format(*self.rmx))
        self.canvas.show()

        # inverse Abel transform
        self._transform()

        # intensity vs angle
        self.intensity, self.theta = abel.tools.vmi.\
                                     radial_integration(self.AIM.transform,\
                                     radial_ranges=[self.rmx,])

        # fit to P2(cos theta)
        self.beta, self.amp = abel.tools.vmi.anisotropy_parameter(
            self.theta, self.intensity[0])

        self.text.insert(tk.END, " beta = {:g}+-{:g}".format(*self.beta))

        self._clr_plt(3)
        self.plt[3].axis("on")

        self.plt[3].plot(self.theta, self.intensity[0], 'r-')
        self.plt[3].plot(self.theta,
                         PAD(self.theta, self.beta[0], self.amp[0]),
                         'b-',
                         lw=2)
        self.plt[3].annotate(
            "$\\beta({:d},{:d})={:.2g}\pm{:.2g}$".format(*self.rmx +
                                                         self.beta),
            (-np.pi / 2, -2))
        self.plt[3].set_title("anisotropy", fontsize=12)
        self.plt[3].set_xlabel("angle", fontsize=9)
        self.plt[3].set_ylabel("intensity")

        self.action = None
        self.canvas.show()

    def _hide_buttons(self):
        self.button_frame.destroy()

    def _on_buttons(self):
        self._button_frame()

    def _quit(self):
        self.parent.quit()  # stops mainloop
        self.parent.destroy()  # this is necessary on Windows to prevent
Exemplo n.º 39
0
class GUI(object):
    selected_file = None
    file_changes = ""

    def __init__(self, parent, client):
        '''
        :param parent: Tkinter object
        :param client: Client object
        '''

        self.root = parent
        self.client = client

        # load initial setting
        self.text = ScrolledText(self.root, width=50, height=15)
        self.text.grid(row=0, column=2, columnspan=3)

        # Loading the list of files in menu
        self.files_list = Listbox(self.root, height=5)
        self.files_list.grid(column=0, row=0, sticky=(N, W, E, S))

        # Attach scroll to list of files
        self.scrollbar = ttk.Scrollbar(self.root,
                                       orient=VERTICAL,
                                       command=self.files_list.yview)
        self.scrollbar.grid(column=1, row=0, sticky=(N, S))
        self.files_list['yscrollcommand'] = self.scrollbar.set

        ttk.Sizegrip().grid(column=1, row=1, sticky=(S, E))
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_rowconfigure(0, weight=1)

        # Status
        self.status = StringVar()
        self.label = Label(self.root, textvariable=self.status)
        self.set_notification_status("-")

        # Radio button to choose "Access"
        self.label.grid(column=0, columnspan=2, sticky=(W))
        self.access_button_val = StringVar()
        self.public_access = Radiobutton(self.root,
                                         text="Make file public",
                                         variable=self.access_button_val,
                                         value="0",
                                         state=DISABLED,
                                         command=self.onAccessChange)
        self.private_access = Radiobutton(self.root,
                                          text="Make file private",
                                          variable=self.access_button_val,
                                          value="1",
                                          state=DISABLED,
                                          command=self.onAccessChange)
        self.public_access.grid(column=2, row=2, sticky=(E))
        self.private_access.grid(column=3, row=2, sticky=(E))

        # Button check changes
        self.button_check_changes = Button(self.root,
                                           text="Check Changes",
                                           command=self.onCheckChanges)
        self.button_check_changes.grid(column=4, row=2, sticky=(E))

        # Main menu in GUI ----------------------------------------------------------------------------
        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)

        self.menu.add_command(label="New file", command=self.onFileCreation)
        # self.menu.add_command(label="Open", command=self.onOpenFile)
        self.menu.add_command(label="Delete file",
                              state=DISABLED,
                              command=self.onFileDeletion)
        self.menu.add_command(label="Exit", command=self.onExit)

        # Update list of accessible files (request to server)
        self.upload_list_of_accessible_files_into_menu()

        # Start triggers for the first launch
        self.block_text_window()
        self.block_button_check_changes()

        # Add triggers
        # Recognize any press on the keyboard and"Enter" press
        self.text.bind("<Key>", self.onKeyPress)
        self.text.bind("<Return>", self.onEnterPress)

        self.root.protocol('WM_DELETE_WINDOW', self.onExit)
        self.files_list.bind('<<ListboxSelect>>', self.onFileSelection)

    # Triggers in the GUI window ========================================================================
    # ========= Triggers in text area ===================================================================
    def get_index(self, index):
        return tuple(map(int, str(self.text.index(index)).split(".")))

    def onKeyPress(self, event):
        current_file = self.selected_file
        # inserted character and position of change
        char, pos_change = event.char, str(self.text.index("insert"))

        # char = char.encode('utf-8')

        # print repr(char)
        # char = char.encode('utf-8')
        # print repr(char)

        # If any file was chosen
        if current_file:
            # self.count += 1
            # if self.count == 5:
            #     self.text.insert(1.1, "click here!")
            # c, pos = event.char, self.get_index("insert")

            if event.keysym == "BackSpace":
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.BACKSPACE,
                                                  pos_change)
                print "backspace", pos_change

            elif event.keysym == "Delete":
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.DELETE,
                                                  pos_change)
                print "Delete pressed", pos_change
                # self.text.delete(float(pos_change[0]) + .1)

            elif char != "" and event.keysym != "Escape":
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.INSERT,
                                                  pos_change,
                                                  key=char)
                print "pressed", char, pos_change, event.keysym

    def onEnterPress(self, event):
        current_file = self.selected_file

        # If any file was chosen
        if current_file:
            char, pos_change = event.char, str(self.text.index("insert"))

            # "Enter" was pressed
            if char in ["\r", "\n"]:
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.ENTER,
                                                  pos_change)
                print repr("\n"), self.get_index("insert")
            else:
                print(char)

    # ========= Other triggers ==========================================================================
    def onFileSelection(self, event):
        # Get currently selected file
        widget = self.files_list
        try:
            index = int(widget.curselection()[0])
            selected_file = widget.get(index)
        except:
            selected_file = None

        if selected_file and (not self.selected_file
                              or self.selected_file != selected_file):
            # Update notification bar
            self.set_notification_status("selected file " + selected_file)

            # Save previously opened text file in local storage
            self.save_opened_text()

            # Download selected file
            resp_code, response_data = self.client.get_file_on_server(
                selected_file)

            # Split additional arguments
            am_i_owner, file_access, content = response_data

            # Freeze delete and access buttons
            self.block_delete_button()
            self.block_access_buttons()

            # Case: File was successfully downloaded
            if resp_code == RESP.OK:
                # If I'm owner, then I can delete file and change its access
                if am_i_owner == "1":
                    self.release_delete_button()
                    self.choose_access_button(file_access)
                    self.chosen_access = file_access

                # Unblock and update text window
                self.unblock_text_window()
                self.replace_text(content)

                # Check and write changes in the file (prepare them)
                # When user clicks on the button, then these changes will be shown in the window)
                self.compare_local_copy_with_origin(selected_file,
                                                    original_text=content)
                self.unblock_button_check_changes()

            # Case: Error response from server on file downloading
            else:
                self.clear_text()
                self.block_text_window()

            # Update notification bar
            self.set_notification_status("download file", resp_code)
            # print "Error occurred while tried to download file"

            self.selected_file = selected_file

    def onFileCreation(self):
        ask_file_dialog = DialogAskFileName(self.root)

        # Fetch values from Dialog form
        file_name = ask_file_dialog.file_name

        # Check if the user didn't press cancel
        if file_name:
            access = str(ask_file_dialog.access)  # Private(1) or Public(0)

            # Send request to server to create file
            resp_code = self.client.create_new_file(file_name, access)

            if resp_code == RESP.OK:
                self.save_opened_text()

                # add new file to the list
                self.files_list.insert(END, file_name)

                # Choose access button and activate delete button
                self.release_delete_button()
                self.choose_access_button(access)

            # Update notification bar
            self.set_notification_status("File creation", resp_code)

    # Trigger on switching between access buttons
    def onAccessChange(self):
        curent_access = self.access_button_val.get()
        file_name = self.selected_file

        # Request to the server to change access to the file
        if self.chosen_access != curent_access:
            resp_code = self.client.change_access_to_file(
                file_name, self.chosen_access)

            self.set_notification_status(
                "change access to file " + str(file_name), resp_code)
        self.chosen_access = curent_access

    # Trigger on file deletion button
    def onFileDeletion(self):
        # Send request to server to delete file
        file_name = self.selected_file

        resp_code = self.client.delete_file(file_name)

        # Block window, until user will select the file
        if resp_code == RESP.OK:
            self.remove_file_from_menu_and_delete_local_copy(file_name)

        # Update notification bar
        self.set_notification_status("file deletion", resp_code)

    # def onOpenFile(self):
    #     tk_file = tkFileDialog.askopenfile(parent=root, mode='rb', title='Select a file')
    #
    #     with open('test.txt','w') as f:
    #         f.write(self.text.get(1.0, END))
    #
    #     if tk_file:
    #         contents = tk_file.read()
    #         self.upload_content_into_textfield(contents)
    #         tk_file.close()

    def onCheckChanges(self):
        window = Toplevel(self.root)
        changes_window = ScrolledText(window,
                                      width=50,
                                      height=15,
                                      state="normal")
        changes_window.grid(row=0, column=0)

        # Clear, rewrite and show changes between opened and downloaded file
        changes_window.delete(1.0, "end")
        changes_window.insert(END, self.file_changes)

    def onExit(self):
        if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
            # save opened text in window
            self.save_opened_text()
            self.root.destroy()

    # Functions to work with interface ==================================================================
    def compare_local_copy_with_origin(self, local_file_name, original_text):
        '''
        :param local_file_name: File that may locate on the client side
        :param original_text: original content on the server
        :return: (Boolean) True - if the texts are the same
        '''
        local_file_path = os.path.join(client_files_dir, local_file_name)

        # If local copy of the file exists, then compare copies
        if os.path.isfile(local_file_path):
            with open(local_file_path, "r") as lf:
                local_content = lf.read()

            if local_content == original_text:
                self.file_changes = "Information is the same as in local copy"

            else:
                self.file_changes = "Information doesn't match!\n"

                local_content, original_text = local_content.strip(
                ).splitlines(), original_text.strip().splitlines()

                # Write mismatches and mismatches
                for line in difflib.unified_diff(local_content,
                                                 original_text,
                                                 lineterm=''):
                    self.file_changes += line + "\n"

        else:
            self.file_changes = "Local copy was not found"

    def upload_list_of_accessible_files_into_menu(self):
        resp_code, accessible_files = self.client.get_accessible_files()
        # accessible_files = []
        # resp_code = 0

        for filename in accessible_files:
            self.files_list.insert(END, filename)

        # Update notification bar
        self.set_notification_status("List of files", resp_code)

    # Save previously opened text file in local storage
    def save_opened_text(self):
        if self.selected_file is not None:
            ps_file_path = os.path.join(client_files_dir, self.selected_file)

            with open(ps_file_path, "w") as f:
                content = self.get_text()
                content = content.encode('utf-8')
                print repr(content)
                f.write(content)

    def get_text(self):
        contents = self.text.get(1.0, Tkinter.END)

        # Tkinter adds \n in the text field. That's why we should deduct it.
        contents = contents[:len(contents) - len("\n")]

        return contents

    def set_text(self, info):
        self.text.insert(END, info)

    def replace_text(self, content):
        self.clear_text()
        self.set_text(content)

    def clear_text(self):
        self.text.delete(1.0, "end")

    def block_text_window(self):
        # block text area
        self.text.config(state=DISABLED, background="gray")

    def unblock_text_window(self):
        self.text.config(state=NORMAL, background="white")

    # Delete button block
    def block_delete_button(self):
        self.menu.entryconfigure("Delete file", state="disabled")

    # Delete button release
    def release_delete_button(self):
        self.menu.entryconfigure("Delete file", state="normal")

    # Block and reset Access radio buttons
    def block_access_buttons(self):
        self.public_access.configure(state="disabled")
        self.private_access.configure(state="disabled")

    # Update Access radio buttons
    def choose_access_button(self, file_access):
        # Unfreeze buttons if they're not active
        self.public_access.configure(state="normal")
        self.private_access.configure(state="normal")

        # Select current access to file in radio button
        if file_access == ACCESS.PRIVATE:
            self.private_access.select()

        elif file_access == ACCESS.PUBLIC:
            self.public_access.select()

    # (un)Block the button "check changes"
    def block_button_check_changes(self):
        self.button_check_changes.config(state=DISABLED)

    def unblock_button_check_changes(self):
        self.button_check_changes.config(state=NORMAL)

    def set_notification_status(self, message, err_code=None):
        if err_code:
            message += ".\n" + error_code_to_string(err_code)

        self.status.set("Last action: " + message)

    # NOTIFICATION UPDATES (From server) ===============================================================
    # ======== Some change was made in file by another client ==========================================
    def notification_update_file(self, change):
        '''
        Another client made the change => update text window
        :param change: (string) in format
        '''

        # Parse change that arrived from server
        # position is in format "row.column"
        file_to_change, change_type, pos, key = parse_change(
            change, case_update_file=True)

        # And check whether the selected file matches with file in change
        if self.selected_file and self.selected_file == file_to_change:
            # Depending on change, do the change

            if change_type == CHANGE_TYPE.DELETE:
                self.text.delete(pos)

            elif change_type == CHANGE_TYPE.BACKSPACE:
                splitted_pos = pos.split(".")
                row, column = int(splitted_pos[0]), int(splitted_pos[1])

                if row - 1 > 0 and column == 0:
                    # Get last index in previous line, and delete it
                    pr_pos = str(row - 1) + ".0"
                    pr_line_last_len = len(self.text.get(pr_pos, pos))
                    last_index = str(row - 1) + "." + str(pr_line_last_len)

                    self.text.delete(last_index)
                elif column > 0:
                    pos_to_del = str(row) + "." + str(column - 1)
                    self.text.delete(pos_to_del)

            elif change_type == CHANGE_TYPE.ENTER:
                self.text.insert(pos, "\n")

            elif change_type == CHANGE_TYPE.INSERT:
                self.text.insert(pos, key)

            # print file_to_change, change_type, pos, key
            self.set_notification_status("another user changed the file")

    # ======== Another client created a document with public access ====================================
    def notification_file_creation(self, change):
        file_name = parse_change(change)
        file_name = file_name[0]

        # Update file list
        self.files_list.insert(END, file_name)

        # Update notification bar
        self.set_notification_status(
            "another client created file with public access")

    # ======== Another client deleted a document =======================================================
    def notification_file_deletion(self, change):
        '''
        :param change: (string) contain file
        '''
        deleted_file = parse_change(change)
        deleted_file = deleted_file[0]

        # Delete file from menu and its local copy and block the window if current=changed_file
        notification = "owner deleted file " + str(deleted_file)
        self.remove_file_from_menu_and_delete_local_copy(
            deleted_file, notification)

    # ======== Another client changed the access to the file (made it private/public) ==================
    def notification_changed_access_to_file(self, change):
        file_name, access = parse_change(change)

        # Owner changed access to file to Private status
        if access == ACCESS.PRIVATE:
            notification = "another client changed access file " + str(
                file_name) + " to private"
            notification += ". Local copy deleted"

            # Delete file from menu and its local copy and block the window if current=changed_file
            self.remove_file_from_menu_and_delete_local_copy(
                file_name, notification)

            # Freeze some buttons (access/delete/text)
            self.set_state_after_deletion()

        # Owner changed access to file to Public status
        elif access == ACCESS.PUBLIC:
            # Add file to the end of list of files
            self.files_list.insert(END, file_name)

            notification = "another client opened access to file " + str(
                file_name)
            self.set_notification_status(notification)

    # OTHER FUNCTIONS ==================================================================================
    # Reset states after deletion
    def set_state_after_deletion(self):
        self.clear_text()
        self.block_delete_button()
        self.block_access_buttons()
        self.block_text_window()
        self.selected_file = None
        self.block_button_check_changes()

    # Delete file from menu and its local copy (if exists)
    def remove_file_from_menu_and_delete_local_copy(self,
                                                    file_name,
                                                    notification=None):
        '''
        :param file_name: (string) file that should ne deleted
        :param notification: (string)
            optional param. Will update status bar, if the deletion was performed
        :return: (Boolean) True if file deletion was performed
        '''
        wasFileRemoved = False

        files_in_menu = self.files_list.get(0, END)

        if file_name in files_in_menu:
            for index, file_in_menu in enumerate(files_in_menu):
                if file_name == file_in_menu:
                    # Delete file from menu
                    self.files_list.delete(index)

                    # Update status bar
                    if notification:
                        self.set_notification_status(notification)

                    wasFileRemoved = True
                    break

        # Delete local copy of the file
        self.client.delete_local_file_copy(file_name)

        # Check if deleted file is currently opened in the text window
        if self.selected_file and self.selected_file == file_name:
            # Change states for some buttons (as after deletion)
            self.set_state_after_deletion()

            # Set prev. selected file to None to avoid conflicts (when user presses on keys)
            self.selected_file = None

        return wasFileRemoved
Exemplo n.º 40
0
class App():
    def __init__(self, root, conf):
        self.conf = conf
        self.items = conf.get_top_level_items()
        self.tree = ttk.Treeview(root, selectmode="browse", columns=("name", "value", "type"), displaycolumns=("value", "type"), height=30)
        
        ysb = ttk.Scrollbar(orient=VERTICAL, command= self.tree.yview)
        xsb = ttk.Scrollbar(orient=HORIZONTAL, command= self.tree.xview)
        self.tree.configure(yscroll=ysb.set, xscroll=xsb.set)
        
        self.tree.heading('#0', text='Configuration Tree', anchor='w')
        self.tree.column("#0", minwidth=0, width=800, stretch=True)

        self.tree.heading("name", text="Name")   
        self.tree.column("name", minwidth=0, width=200, stretch=True)
        
        self.tree.heading("value", text="Value")   
        self.tree.column("value", minwidth=0, width=50, stretch=True)
        
        self.tree.heading("type", text="Type")   
        self.tree.column("type", minwidth=0, width=50, stretch=True)

        self.add_root_items(self.items)
        
        self.help = ScrolledText(root, width=130, height=10)
        self.msg = StringVar()
        self.info = Label(root, fg="green", font=("Helvetica", 16), anchor=W, justify=LEFT, textvariable=self.msg)
        
        self.msg.set("Please set configurations, then you can save it!")
        
        self.tree.grid(row=0, column=0)
        self.help.grid(row=1, column=0)
        self.info.grid(row=2, column=0)
        ysb.grid(row=0, column=1, sticky='ns')
        xsb.grid(row=1, column=0, sticky='ew')
        
        root.grid()
        
        self.root = root
        
        # create a toplevel menu
        menubar = Menu(root)
        menubar.add_command(label="Save Config!", command=self.OnSaveConfig)
        menubar.add_command(label="Quit Config!", command=self.OnQuitConfig)

        # display the menu
        root.config(menu=menubar)
    
        self.tree.bind("<Double-1>", self.OnDoubleClick)
        self.tree.bind("<<TreeviewSelect>>", self.OnSelection)
    
    def add_subr_items(self, parent, items):
        for item in items:
            if item.get_visibility() != "n":
                if item.is_symbol():
                    str = 'config {0}'.format(item.get_name())
                    self.tree.insert(parent, "end", text=str, values=[item.get_name(), item.get_value(), kconf.TYPENAME[item.get_type()]], open=True)
                elif item.is_menu():
                    str = 'menu "{0}"'.format(item.get_title())
                    parent = self.tree.insert(parent, "end", text=str, open=True)
                    self.add_subr_items(parent, item.get_items())
                elif item.is_choice():
                    str = 'choice "{0}"'.format(item.get_prompts()[0])
                    parent = self.tree.insert(parent, "end", text=str, open=True)
                    self.add_subr_items(parent, item.get_items())
                elif item.is_comment():
                    str = 'comment "{0}"'.format(item.get_text())
                    self.tree.insert(parent, "end", text=str, open=True)
                
    def add_root_items(self, items):
        for item in items:
            if item.get_visibility() != "n":
                if item.is_symbol():
                    str = 'config {0}'.format(item.get_name())
                    self.tree.insert("", "end", text=str, values=[item.get_name(), item.get_value(), kconf.TYPENAME[item.get_type()]], open=True)
                elif item.is_menu():
                    str = 'menu "{0}"'.format(item.get_title())
                    parent = self.tree.insert("", "end", text=str, open=True)
                    self.add_subr_items(parent, item.get_items())
                elif item.is_choice():
                    str = 'choice "{0}"'.format(item.get_prompts()[0])
                    parent = self.tree.insert("", "end", text=str, open=True)
                    self.add_subr_items(parent, item.get_items())
                elif item.is_comment():
                    str = 'comment "{0}"'.format(item.get_text())
                    self.tree.insert("", "end", text=str, open=True)

    def search_for_item(self, name, item=None):
        children = self.tree.get_children(item)
        for child in children:
            nameval = self.tree.set(child, "name")
            if nameval == name:
                return child
            else:
                res = self.search_for_item(name, child)
                if res:
                    return res
        return None
                    
    def OnDoubleClick(self, event):
        mitem = self.tree.identify('item',event.x, event.y)
        nameval = self.tree.set(mitem, "name")
        symbol = self.conf.get_symbol(nameval)
        
        if symbol is None:
            return
        
        if (symbol.get_type() == kconf.BOOL or (symbol.get_type() == kconf.TRISTATE and not self.conf.is_tristate_enabled())):
            if (symbol.is_choice_symbol() and len(symbol.get_parent().get_items()) == 1):
                self.msg.set("A boolean choice, exactly one config option must be set to y, so no change here!")
                return
            if (symbol.get_value() == "y"):
                print("Setting " + symbol.get_name() + " to n")
                symbol.set_user_value("n")
                if (symbol.get_value() == "y"):
                    self.msg.set("A boolean choice that is the only 'y' in the choice group can not be set to 'n'")
                    symbol.set_user_value("y")
                    return
                self.tree.set(mitem, "value", symbol.get_value())
            else:
                print("Setting " + symbol.get_name() + " to y")
                symbol.set_user_value("y")   
                self.tree.set(mitem, "value", symbol.get_value())
            print("Dependents for " + symbol.get_name() + " {" + symbol.get_visibility() + "} " + " [" + symbol.get_value() + "]:")
            for sym in symbol.get_dependent_symbols():
                print(sym.get_name() + " {"+sym.get_visibility() + "} " + " [" + sym.get_value() + "] ")
                mitem = self.search_for_item(sym.get_name(), None)
                if (mitem):
                    self.tree.set(mitem, "value", sym.get_value())
            print("========================================")
        elif (symbol.get_type() == kconf.TRISTATE and self.conf.is_tristate_enabled()):
            nono = False
            if (symbol.is_choice_symbol() and len(symbol.get_parent().get_items()) == 1):
                self.msg.set("A single tristate choice in one choice group can not be set to 'n'")
                nono = True
            # 'y'->'m'->'n'->'y'->'m'->'n'->...
            if (symbol.get_value() == "y"):
                print("Setting " + symbol.get_name() + " to m")
                symbol.set_user_value("m")
                if (symbol.get_value() == "y"):
                    self.msg.set("A tristate choice that is the only 'y' in the choice group can not be set to 'n'")
                    symbol.set_user_value("y")
                    return
                self.tree.set(mitem, "value", symbol.get_value())
            elif (symbol.get_value() == "m"):
                print("Setting " + symbol.get_name() + " to n")
                symbol.set_user_value("n")
                if (symbol.get_value() == "m"):
                    self.msg.set("A tristate choice that is the only 'm' in the choice group can not be set to 'n'")
                    symbol.set_user_value("m")
                    return
                self.tree.set(mitem, "value", symbol.get_value())
            else:
                print("Setting " + symbol.get_name() + " to y")
                symbol.set_user_value("y")   
                self.tree.set(mitem, "value", symbol.get_value())
            print("Dependents for " + symbol.get_name() + " {" + symbol.get_visibility() + "} " + " [" + symbol.get_value() + "]:")
            for sym in symbol.get_dependent_symbols():
                print(sym.get_name() + " {"+sym.get_visibility() + "} " + " [" + sym.get_value() + "] ")
                mitem = self.search_for_item(sym.get_name(), None)
                if (mitem):
                    self.tree.set(mitem, "value", sym.get_value())
            print("========================================")            
        elif (symbol.get_type() == kconf.INT or symbol.get_type() == kconf.HEX or symbol.get_type() == kconf.STRING):
            self.pop = PopupWindow(self.root, symbol.get_name(), symbol.get_value())
            self.root.wait_window(self.pop.top)
            if (self.pop.v == True):
                print("Setting " + symbol.get_name() + " to " + self.pop.value)
                symbol.set_user_value(self.pop.value)
                print("Now " + symbol.get_name() + " is " + symbol.get_value())
                self.tree.set(mitem, "value", symbol.get_value())
            
        return
                    
    def OnSelection(self, event):
        mitem = self.tree.focus()
        values = self.tree.item(mitem,"values");
        if (values):
            symbol = self.conf.get_symbol(values[0])
            if (symbol):                
                self.msg.set("Please Double Click to update config option value!")
                self.help.delete(1.0, END)
                help = symbol.get_help()
                if (help):
                    self.help.insert(INSERT, help)

        return

    def OnSaveConfig(self):
        self.conf.write_config(".config")
        self.conf.write_config_python("config.py")
        header_dir = conf.get_config_header_dir()
        dstfile = os.path.join(header_dir, "config.h") 
        dstdir = os.path.split(dstfile)[0]
        if not os.path.exists(dstdir):
            os.makedirs(dstdir)
        self.conf.write_config_header(dstfile)
        self.msg.set("Configurations Saved!")
        return
 
    def OnQuitConfig(self):
        self.root.quit()
        return
Exemplo n.º 41
0
                 bg='green',
                 command=lambda: menu(5))
button5.grid(row=602, column=3, sticky=W, columnspan=1)

button6 = Button(app,
                 text="Exit App",
                 font='Lato 20',
                 width=15,
                 bg='blue',
                 fg='red',
                 command=lambda: menu(6))
button6.grid(row=1000, column=1, sticky=N, columnspan=2)

# set up the text widget
user_view = ScrolledText(app, width=60, height=45, wrap=WORD)
user_view.grid(row=0, column=4, rowspan=1000)
user_view.configure(state='normal')
x = ''' 
	Welcome to the IOT Vulnerability Scanner

This is version number 3.1 of the Scanner. 
This tool has been created as a final year project by 
the Cybersecurity MSc student Elis Achim.


In order to start nay of the tests, please select one of 
the buttons on the left in order to test your network 
for vulnerabilities in regards to your IOT devices.

For more information about this software as well as 
step by step instructions on how to use it please click 
Exemplo n.º 42
0
    def __init__(self, parent):

        Frame.__init__(self, parent)

        self.parent = parent
        self.ejecucion = False

        def prox_instruccion():
            p.stdin.write('step 1\n')

            mostrar_en(area4, "proximo")

            estado()
            if self.ejecucion:
                memoria()
                registros()
                listado()

        def ejecutar():
            while self.ejecucion:
                prox_instruccion()

        def salida(w, findelinea):
            w.delete("1.0", END)

            a = p.stdout.readline()
            while not findelinea in a:
                # Esto es para saber si la ejecucion termino'.
                # TODO: Hay que quitarlo de este metodo. Donde ponerlo?
                if "No stack" in a:
                    self.ejecucion = False
                    w.insert(END, '\n\nEjecucion FINALIZADA\n\n')

                a = a.replace('(gdb) ', '')
                w.insert(END, a)
                a = p.stdout.readline()

        def mostrar_en(w, findelinea):
            p.stdin.write(findelinea)
            p.stdin.write('\r\n')
            salida(w, findelinea)

        def mostrar_en_depuracion():

            file = open("/tmp/archivotemp" + PUERTOyPS + ".txt")
            contents = file.read()
            #area4.delete('1.0',END)
            area4.insert(END, contents)
            file.close()

        def memoria():
            # Para mostrar el segmento de datos, la etiqueta memoria debe estar al principio
            p.stdin.write('info address memoria\n')
            p.stdin.write('infomemoria\n')
            a = p.stdout.readline()
            solicitar_seg_de_datos = ""
            while not "infomemoria" in a:
                print "a : " + a
                if "Symbol " in a:
                    a = a.replace('(gdb) Symbol "memoria" is at ', '')
                    a = a.replace(' in a file compiled without debugging.', '')
                    solicitar_seg_de_datos = "x/40xw " + a + "\n"
                a = p.stdout.readline()

            if solicitar_seg_de_datos == "":
                p.stdin.write('x/40xw $pc\n')
            else:
                p.stdin.write(solicitar_seg_de_datos)
            p.stdin.write('x/40xw main\n')
            p.stdin.write('x/128 $sp - 128\n')
            mostrar_en(area3, "memoria")

        def estado():
            p.stdin.write('info frame\n')
            mostrar_en(area4, "estado")
            file = open("/tmp/archivotemp" + PUERTOyPS + ".txt")
            contents = file.readline()
            while not "Remote" in contents:
                print contents
                area4.insert(END, contents)
                contents = file.readline()

            area4.insert(
                END,
                "----------------------------------------\nSalida Estandar : \n\n"
            )

            contents = file.read()
            file.close()
            area4.insert(END, contents)

        def registros():
            p.stdin.write('info register\n')
            mostrar_en(area1, "registros")

        def listado():
            p.stdin.write('list 1,100\n')
            # p.stdin.write('disas main \n')
            p.stdin.write('disas \n')
            mostrar_en(area2, "listado")

        def compilarparasie():
            area4.delete('1.0', END)
            area4.insert('1.0', "Compilando para la SIE ...\r\n")
            root.update_idletasks()

            p.stdin.write('detach \n')
            guardar_archivo_a_compilar()
            tub = Popen(
                ['mipsx_compilarparasie.sh', self.archivoacompilar, PUERTOyPS],
                stdout=PIPE,
                stdin=PIPE,
                stderr=STDOUT)
            streamdata = tub.communicate()[0]
            mostrar_en_depuracion()

            if tub.returncode == 0:
                area4.insert(END, "Compilacion para la SIE OK\n")
            else:
                area4.insert(END, "ERROR al compilar y cargar")
                mostrar_en_depuracion()

        def compilarycargar():
            area4.delete('1.0', END)
            area4.insert('1.0', "Compilando y Cargando ...\r\n")
            root.update_idletasks()

            p.stdin.write('detach \n')
            guardar_archivo_a_compilar()
            tub = Popen(
                ['mipsx_compilarycargar.sh', self.archivoacompilar, PUERTOyPS],
                stdout=PIPE,
                stdin=PIPE,
                stderr=STDOUT)
            streamdata = tub.communicate()[0]
            mostrar_en_depuracion()

            if tub.returncode == 0:
                area4.insert(END, "Compilacion y carga : OK\n")

                # ejecutable = self.archivoactual+".elf"
                # ejecutable = ntpath.basename(ejecutable)
                ejecutable = self.archivoacompilar + ".elf"
                ejecutable = ntpath.basename(ejecutable)

                # Nos conectamos al gdbserver
                # ip_mips="10.0.15.232"
                # ip_mips="192.168.0.71"

                ip_mips = "10.0.15.50"
                #comando='target extended-remote '+ip_mips+':'+PUERTOyPS+'\n'
                comando = 'target remote ' + ip_mips + ':' + PUERTOyPS + '\n'
                p.stdin.write(comando)

                # gdbfile = 'set remote exec-file /tmp/'+ejecutable+'\n'
                # p.stdin.write(gdbfile)
                # Respondemos "y"es a recargar
                p.stdin.write('y \n')

                # Abrimos con gdb el archivo ejecutable
                gdbfile = 'file /tmp/' + ejecutable + '\n'
                p.stdin.write(gdbfile)
                # Respondemos "y"es a recargar
                p.stdin.write('y \n')

                p.stdin.write('delete \n')
                p.stdin.write('y \n')
                p.stdin.write('break main\n')
                # p.stdin.write('run\n')
                p.stdin.write('continue\n')
                self.ejecucion = True

                mostrar_en(area4, "estado")
                memoria()
                registros()
                listado()
            else:
                area4.insert(END, "ERROR al compilar y cargar")
                mostrar_en_depuracion()

        PUERTOyPS = str(random.randrange(4000, 8000 + 1))
        # PUERTOyPS="4567"

        self.parent.title("Mipsx - GUI for gdb multiarch")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        # Para expandir cuando las ventanas cambian de tamao
        for i in range(3):
            self.columnconfigure(i, weight=1)
        for i in range(20):
            self.rowconfigure(i, weight=1)

        lbl = Label(
            self,
            text=
            "Registros                                      GDB en MIPS - MR3020"
        )
        lbl.grid(row=1, column=2, sticky=W, pady=4, padx=5)

        area1 = Text(self, height=12, width=80)
        area1.grid(row=2,
                   column=2,
                   columnspan=1,
                   rowspan=5,
                   sticky=E + W + S + N)

        lbl = Label(
            self,
            text=
            "Programa en Assembler y Programa Binario Decodificado (disassemble)"
        )
        lbl.grid(row=7, column=2, pady=1, padx=1, sticky=W + N + E + S)

        area2 = Text(self, height=6, width=80)
        area2.grid(row=8,
                   column=2,
                   columnspan=1,
                   rowspan=5,
                   padx=1,
                   sticky=E + W + S + N)

        lbl = Label(
            self,
            text=
            'Memoria - Segmento de datos (debe existir la etiqueta "memoria") - Segmento de texto - Pila'
        )
        lbl.grid(row=13, column=2, pady=1, padx=1, sticky=W + N + E + S)

        area3 = Text(self, height=15, width=80)
        area3.grid(row=14,
                   column=2,
                   columnspan=1,
                   rowspan=5,
                   padx=1,
                   sticky=E + W + S + N)

        lbl4 = Label(self, text="Mensajes de Depuracion")
        lbl4.grid(row=13, column=0, pady=1, padx=1, sticky=W + N + E + S)

        area4 = Text(self, height=8, width=60)
        area4.grid(row=14,
                   column=0,
                   columnspan=1,
                   rowspan=5,
                   padx=1,
                   sticky=E + W + S + N)

        lbl = Label(self, text="Editor del Programa")
        lbl.grid(row=1, column=0, sticky=W, pady=4, padx=5)

        area5 = ScrolledText(self, height=20, width=60)
        area5.grid(row=2,
                   column=0,
                   columnspan=1,
                   rowspan=10,
                   padx=1,
                   sticky=E + W + S + N)

        # Variables globales
        archivoactual = "hello.s"
        archivoacompilar = "hello.s"
        archivotemp = "/tmp/archivotemp" + PUERTOyPS + ".txt"
        # ip_mips = "10.0.15.232"
        ip_mips = "10.0.15.50"

        # ip_mips = "192.168.0.71"

        # Al abrir un archivo deseamos tener un area de trabajo cero
        def limpiar_areas():
            area4.delete('1.0', END)
            area3.delete('1.0', END)
            area2.delete('1.0', END)
            area1.delete('1.0', END)

        def abrir_en_editor(archivo):
            fd = open(archivo)
            contents = fd.read()
            area5.delete('1.0', END)
            area5.insert('1.0', contents)
            fd.close()
            self.archivoactual = archivo
            print self.archivoactual

        def open_command():
            FILEOPENOPTIONS = dict(defaultextension='*.s',
                                   filetypes=[('Archivo assembler', '*.s'),
                                              ('Todos los archivos', '*.*')])
            file = tkFileDialog.askopenfile(parent=root,
                                            mode='rb',
                                            title='Select a file',
                                            **FILEOPENOPTIONS)
            if file != None:
                limpiar_areas()
                abrir_en_editor(file.name)

        def guardar_archivo_a_compilar():
            self.archivoacompilar = "/tmp/archivo" + PUERTOyPS + ".s"
            tub = Popen(['rm', self.archivoacompilar],
                        stdout=PIPE,
                        stdin=PIPE,
                        stderr=STDOUT)
            streamdata = tub.communicate()[0]
            tub = Popen(['touch', self.archivoacompilar],
                        stdout=PIPE,
                        stdin=PIPE,
                        stderr=STDOUT)
            streamdata = tub.communicate()[0]
            tmp = open(self.archivoacompilar, "w")
            if tmp != None:
                data = area5.get('1.0', END + '-1c')
                tmp.write(data)
                tmp.close()

                archivotmppwd = "archivo" + PUERTOyPS + ".s"
                tub = Popen(['cp', self.archivoacompilar, archivotmppwd],
                            stdout=PIPE,
                            stdin=PIPE,
                            stderr=STDOUT)
                streamdata = tub.communicate()[0]

        def save_command():
            file = tkFileDialog.asksaveasfile(mode='w')
            if file != None:
                # slice off the last character from get, as an extra return is added
                data = area5.get('1.0', END + '-1c')
                file.write(data)
                file.close()
                self.archivoactual = file.name
                print self.archivoactual

        def exit_command():
            if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
                root.destroy()

        def about_command():
            label = tkMessageBox.showinfo(
                "Acerca de",
                "MIPSX - GUI for gdb multiarch\n\nEntorno de desarrollo en lenguaje assembler arquitectura MIPS\nEste programa ensabla, genera el programa ejecutable, y lo ejecuta en modo debug en una maquina MIPS real\n\nCopyright 2014 Rafael Ignacio Zurita\n\nFacultad de Informatica\nUniversidad Nacional del Comahue\n\nThis program is free software; you can redistribute it and/or modify it under the terms of the GPL v2"
            )

        def dummy():
            print "I am a Dummy Command, I will be removed in the next step"

        def no_hacer_nada():
            print "nada por hacer"

        def archivo_sin_guardar():
            data = area5.get('1.0', END + '-1c')
            fd = open(self.archivoactual)
            contents = fd.read()
            fd.close()
            if data == contents:
                return False
            res = tkMessageBox.askquestion(
                "Confirmar",
                "Archivo sin guardar\nEsta seguro de finalizar el programa?",
                icon='warning')
            if res == 'yes':
                return False
            return True

        def salir():
            if archivo_sin_guardar():
                return

            tmp = "/tmp/archivo" + PUERTOyPS + ".s"
            tmp2 = "archivo" + PUERTOyPS + ".s"
            tmp3 = "/tmp/archivo" + PUERTOyPS + ".s.elf"
            tmp4 = "/tmp/archivotemp" + PUERTOyPS + ".txt"
            tub = Popen(['rm', tmp, tmp2, tmp3, tmp4],
                        stdout=PIPE,
                        stdin=PIPE,
                        stderr=STDOUT)
            streamdata = tub.communicate()[0]

            tmp2 = "/tmp/archivo" + PUERTOyPS + ".s.o"
            ip_mips = "10.0.15.50"
            tub = Popen([
                'mipsx_finalizar_gdbserver.sh', ip_mips, PUERTOyPS, tmp, tmp2,
                tmp3, tmp4
            ],
                        stdout=PIPE,
                        stdin=PIPE,
                        stderr=STDOUT)
            streamdata = tub.communicate()[0]
            # ip_mips = "10.0.15.232"
            # ip_mips = "192.168.0.71"
            # killgdbserver = Popen(['sshpass', '-p', clave, 'ssh', '-o', 'StrictHostKeyChecking=no', '-l', 'root', ip_mips, comando], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
            quit()

        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="Archivo", menu=filemenu)
        filemenu.add_command(label="Nuevo", command=dummy)
        filemenu.add_command(label="Abrir...", command=open_command)
        filemenu.add_command(label="Guardar...", command=save_command)
        filemenu.add_separator()
        filemenu.add_command(label="Salir", command=salir)

        menu.add_command(label="Run", command=ejecutar)
        menu.add_command(label="Next", command=prox_instruccion)
        menu.add_command(label="Breakpoint", command=no_hacer_nada)
        menu.add_command(label="Compilar y Cargar", command=compilarycargar)
        menu.add_command(label="Compilar para SIE", command=compilarparasie)

        helpmenu = Menu(menu)
        menu.add_cascade(label="Ayuda", menu=helpmenu)
        helpmenu.add_command(label="Acerca de...", command=about_command)
        menu.add_command(label="Salir", command=salir)
        abrir_en_editor("hello.s")

        # para que al cerrar la ventana cierre los temporales y los borre
        root.protocol("WM_DELETE_WINDOW", salir)
Exemplo n.º 43
0
            sys.stdout = old_stdout
        storePacket(p)
        send(p)

    p.show()
    global e
    global d
    e = output
    d = output2
    printPacket()


label_pktheader = Label(bottomframe, text="Packet Header")
label_pktheader.grid(row=0, column=1)
T = ScrolledText(bottomframe, height=10, width=100)
T.grid(row=1, column=1, padx=50, pady=50)


def printPacket():

    global e
    global d
    print(e)
    print(d)

    T.delete('1.0', Tkinter.END)
    T.insert(Tkinter.END, e)
    T.insert(Tkinter.END, d)

    #elif packetType=='ARP':
    #a=data1.get()
Exemplo n.º 44
0
	
	
	code_f = Frame(root)
	code_f.rowconfigure(1, weight=1)
	code_f.rowconfigure(2, weight=1)
	code_f.rowconfigure(3, weight=1)
	
	einzahl_f = Frame(code_f)
	einzahl_f.grid(row=1, column=1, pady=10, sticky=tk.N+tk.W+tk.E+tk.S)
	einzahl_f.rowconfigure(1, weight=1)
	einzahl_f.rowconfigure(2, weight=1)
	einzahl_f.columnconfigure(1, weight=1)
	einzahl_l = Label(einzahl_f, text="GeldEinzahlen (kontonr, betrag):")
	einzahl_l.grid(row=1, column=1)
	einzahl_t = ScrolledText(einzahl_f, width=75, height=10)
	einzahl_t.grid(row=2, column=1, sticky=tk.N+tk.W+tk.E+tk.S)
	
	
	abheb_f = Frame(code_f)
	abheb_f.grid(row=2, column=1, pady=10, sticky=tk.N+tk.W+tk.E+tk.S)
	abheb_f.rowconfigure(1, weight=1)
	abheb_f.rowconfigure(2, weight=1)
	abheb_f.columnconfigure(1, weight=1)
	abheb_l = Label(abheb_f, text="GeldAbheben (kontonr, betrag):")
	abheb_l.grid(row=1, column=1)
	abheb_t = ScrolledText(abheb_f, width=10, height=10)
	abheb_t.grid(row=2, column=1, sticky=tk.N+tk.W+tk.E+tk.S)
	
	ueberweis_f = Frame(code_f)
	ueberweis_f.grid(row=3, column=1, pady=10, sticky=tk.N+tk.W+tk.E+tk.S)
	ueberweis_f.rowconfigure(1, weight=1)
Exemplo n.º 45
0
class terminalApp_tk(Tkinter.Tk):
	def quitNow(self):
		if (connection_tk.serialStatus == 1):
			terminalProcess.ser.close()
		terminalProcess.programStatus = 1
		self.destroy()
	
	def openLog(self):
		os.system("start notepad.exe terminal_tools_Log.txt") 		#Open workbook in open office automatically
	
	def readMe(self):
		os.system("start notepad.exe terminal_tools_readme.txt") 	#Open workbook in open office automatically
	
	def __init__(self,parent):
		Tkinter.Tk.__init__(self,parent)
		self.parent = parent
		self.initialize()
		self.protocol('WM_DELETE_WINDOW', self.quitNow)
	
	def connectPage(self):
		print connection_tk.serialStatus
		if (connection_tk.serialStatus == 0):
			connection_tk.serialStatus = 1
			connectPage = connection_tk(None)							#Create GUI named app
			connectPage.title('Connect Page')						#Give app some text in titlebar
			connectPage.mainloop()
			
		else:
			terminalProcess.ser.close()
			connection_tk.serialStatus = 0
			print "Not Connected"
			
	def initialize(self):
		self.grid()

		#MenuBar
		#File
		menubar = Menu(self)										#Create Menu bar
		fileMenu = Menu(menubar,tearoff=0)
		fileMenu.add_command(label="Connect/Disconnect",command=self.connectPage)	#Add submenu for opening log
		fileMenu.add_command(label="View Log",command=self.openLog)	#Add submenu for opening log
		fileMenu.add_command(label="Exit",command=self.quitNow)		#Add submenu for quiting program
		menubar.add_cascade(label="File", menu=fileMenu)			#Add top level menu
		
		
		
		#Help
		helpMenu = Menu(menubar,tearoff=0)
		helpMenu.add_command(label="Readme",command=self.readMe)	
		#helpMenu.add_command(label="About",command=self.about)		
		menubar.add_cascade(label="Help", menu=helpMenu)			
		self.config(menu=menubar)									#Display the menubar
		
		#Logging
		self.logCheckValue = IntVar()
		self.logCheckBox = Checkbutton(self, text = "Enable Logging", variable = self.logCheckValue, command = self.logCheckFunction, height = 1, width = 25)
		self.logCheckBox.grid(column=0, row=0, columnspan=2,sticky='EW')		#Align in GUI
		
		#Text Boxes
		self.terminalVariable0 = Tkinter.StringVar()
		self.terminal0 = Tkinter.Entry(self,textvariable=self.terminalVariable0)#Create text box
		self.terminal0.grid(column=0, row=2,sticky='EW')						#Align in GUI
		self.terminal0.bind("<Return>", self.commandEnter0)						#Add "enter key" event handler to text box
		self.terminalVariable0.set(defaultCommands[0])							#Set textbox default text
		
		self.terminalVariable1 = Tkinter.StringVar()
		self.terminal1 = Tkinter.Entry(self,textvariable=self.terminalVariable1)#Create text box
		self.terminal1.grid(column=0, row=3,sticky='EW')						#Align in GUI
		self.terminal1.bind("<Return>", self.commandEnter1)						#Add "enter key" event handler to text box
		self.terminalVariable1.set(defaultCommands[1])							#Set textbox default text
		
		self.terminalVariable2 = Tkinter.StringVar()
		self.terminal2 = Tkinter.Entry(self,textvariable=self.terminalVariable2)#Create text box
		self.terminal2.grid(column=0, row=4,sticky='EW')						#Align in GUI
		self.terminal2.bind("<Return>", self.commandEnter2)						#Add "enter key" event handler to text box
		self.terminalVariable2.set(defaultCommands[2])							#Set textbox default text
		
		self.terminalVariable3 = Tkinter.StringVar()
		self.terminal3 = Tkinter.Entry(self,textvariable=self.terminalVariable3)#Create text box
		self.terminal3.grid(column=0, row=5,sticky='EW')						#Align in GUI
		self.terminal3.bind("<Return>", self.commandEnter3)						#Add "enter key" event handler to text box
		self.terminalVariable3.set(defaultCommands[3])							#Set textbox default text
		
		self.terminalVariable4 = Tkinter.StringVar()
		self.terminal4 = Tkinter.Entry(self,textvariable=self.terminalVariable4)#Create text box
		self.terminal4.grid(column=0, row=6,sticky='EW')						#Align in GUI
		self.terminal4.bind("<Return>", self.commandEnter4)						#Add "enter key" event handler to text box
		self.terminalVariable4.set(defaultCommands[4])							#Set textbox default text	
		
		self.lumpText = ScrolledText(self, undo=True, wrap=WORD, width = 25, height = 5)
		self.lumpText.grid(column=0,row=8,columnspan=2,sticky='EW')
		
		#Buttons
		button0 = Tkinter.Button(self,text=u"Send 1",command=self.commandButton0)	#Create button with OnButtonClick event handler
		button0.grid(column=1,row=2)
		
		button1 = Tkinter.Button(self,text=u"Send 2",command=self.commandButton1)	#Create button with OnButtonClick event handler
		button1.grid(column=1,row=3)
		
		button2 = Tkinter.Button(self,text=u"Send 3",command=self.commandButton2)	#Create button with OnButtonClick event handler
		button2.grid(column=1,row=4)

		button3 = Tkinter.Button(self,text=u"Send 4",command=self.commandButton3)	#Create button with OnButtonClick event handler
		button3.grid(column=1,row=5)
		
		button4 = Tkinter.Button(self,text=u"Send 5",command=self.commandButton4)	#Create button with OnButtonClick event handler
		button4.grid(column=1,row=6)
		
		button5 = Tkinter.Button(self,text=u"Send Bulk Commands", 
									width=35, command=self.commandButton5)			#Create button with OnButtonClick event handler
		button5.grid(column=0,row=9,columnspan=2)
		
		self.seperator0 = Frame(height=2,bd=1,relief=SUNKEN,bg='#000000')
		self.seperator0.grid(column=0,row=1,columnspan=2,padx=0,pady=5,sticky='EW')
		
		self.seperator1 = Frame(height=2,bd=1,relief=SUNKEN,bg='#000000')
		self.seperator1.grid(column=0,row=7,columnspan=2,padx=0,pady=10,sticky='EW')
		
		#Labels
		#self.labelVariable = Tkinter.StringVar()
		#label = Tkinter.Label(self,textvariable=self.labelVariable,	#Create label
		#						anchor="w",fg="white",bg="blue")	
		#label.grid(column=0,row=5,columnspan=2,sticky='EW')
		#self.labelVariable.set(u"")
		
		self.grid_columnconfigure(0,weight=1)							#Resize columns and rows when window is resized
		self.resizable(True,False)										#Prevent vertical sizing
		self.update()													#Render Objects
		self.geometry(self.geometry())									#Fix box size to box size
		#self.terminal0.focus_set()										#Set focus to entry box
		#self.terminal0.selection_range(0, Tkinter.END)					#Select text in entry box
		
	def logCheckFunction(self):
		global log
		terminalProcess.loggingStatus = self.logCheckValue.get()
		if (terminalProcess.loggingStatus == 0):
			if (log.closed == False):
				log.close()
		elif (terminalProcess.loggingStatus == 1):
			if (log.closed == True):
				log = open((os.path.join(os.path.dirname(sys.executable),'terminal_tools_log.txt')), 'a')

	def commandEnter0(self, event):
		self.commandButton0()
	def commandEnter1(self, event):
		self.commandButton1()
	def commandEnter2(self, event):
		self.commandButton2()
	def commandEnter3(self, event):
		self.commandButton3()
	def commandEnter4(self, event):
		self.commandButton4()	
			
	def commandButton0(self):
		terminalProcess.command = self.terminalVariable0.get() + '\r'
		terminalProcess.writeInterrupt = 1
		#self.labelVariable.set("Command 1" + terminalProcess.confirmation)			#Set label to textbox + "enter" on hitting return
		
	def commandButton1(self):
		terminalProcess.command = self.terminalVariable1.get() + '\r'
		terminalProcess.writeInterrupt = 1											#Interrupt to write to serial
		#self.labelVariable.set("Command 2" + terminalProcess.confirmation)			#Set label to success or failure
		
	def commandButton2(self):
		terminalProcess.command = self.terminalVariable2.get() + '\r'
		terminalProcess.writeInterrupt = 1
		#self.labelVariable.set("Command 3" + terminalProcess.confirmation)			#Set label to success or failure
		
	def commandButton3(self):
		terminalProcess.command = self.terminalVariable3.get() + '\r'
		terminalProcess.writeInterrupt = 1											#Interrupt to write to serial
		#self.labelVariable.set("Command 4" + terminalProcess.confirmation)			#Set label to success or failure
		
	def commandButton4(self):
		#self.labelVariable.set(terminalProcess.confirmation)						#Set label to textbox + "enter" on hitting return
		terminalProcess.command = self.terminalVariable4.get() + '\r'
		terminalProcess.writeInterrupt = 1		
		#self.labelVariable.set("Command 5" + terminalProcess.confirmation)			#Set label to success or failure
		
	def commandButton5(self):
		commandLumpText = self.lumpText.get(1.0, END)
		commandSplit = commandLumpText.split('\n')
		terminalProcess.commandArray = commandSplit
		terminalProcess.writeInterrupt = 2	
Exemplo n.º 46
0
class editor:
    def __init__(self, master):
        frame = Frame(master, width=80, height=150)
        frame.pack()

        self.var = StringVar()

        menu = Menu(root)
        root.config(menu=menu)
        subMenu = Menu(menu)
        menu.add_cascade(label="File", menu=subMenu)
        subMenu.add_command(label="Open...\t\t  Ctrl+O", command=self.open)
        subMenu.add_separator()
        subMenu.add_command(label="Exit\t\t         Ctrl+Q",
                            command=self.close)

        editMenu = Menu(menu)
        menu.add_cascade(label="Edit", menu=editMenu)
        editMenu.add_command(label="Find...\t     Ctrl+F", command=self.fin)
        editMenu.add_separator()
        editMenu.add_command(label="Replace\t  Ctrl+H", command=self.rep)
        editMenu.add_separator()
        editMenu.add_command(label="Reset", command=self.res)
        editMenu.add_separator()
        formatMenu = Menu(menu)
        menu.add_cascade(label="Format", menu=formatMenu)
        runMenu = Menu(menu)
        menu.add_cascade(label="Run", menu=runMenu)

        optionsMenu = Menu(menu)
        menu.add_cascade(label="Options", menu=optionsMenu)

        windowsMenu = Menu(menu)
        menu.add_cascade(label="Windows", menu=windowsMenu)

        helpMenu = Menu(menu)
        menu.add_cascade(label="Help", menu=helpMenu)

        self.text = ScrolledText(frame, width=70, height=25)
        self.text.grid(row=3, columnspan=3)
        self.text.tag_configure('t', background='green', foreground='white')

    def open(self):
        self.f = askopenfilename()
        self.var.set(self.f)
        self.display()

    def display(self):
        self.fr = open(str(self.f), 'r')
        n = self.fr.read()
        self.n = n
        if n != '':
            self.text.insert(END, str(n))

    def res(self):
        self.e.delete(0, END)
        self.text.delete('1.0', END)

    def findword(self):

        self.text.tag_remove('t', '1.0', END)
        x = 0
        r = re.compile(self.e.get())
        self.fr.seek(0)
        z = self.fr.readline()
        count = 1
        while z != '':
            y = r.search(z[x:])
            if y:

                self.text.tag_add('t',
                                  str(count) + '.' + str(x + y.start()),
                                  str(count) + '.' + str(x + y.end()))
                x = x + y.end() + 1
                continue
            count += 1
            x = 0
            z = self.fr.readline()

    def rep(self):
        window = Toplevel(root)
        self.nw(window)

    def fin(self):
        wind = Toplevel(root)
        self.win_n(wind)

    def win_n(self, master):
        frame = Frame(master)
        frame.pack()

        self.label1 = Label(frame, textvariable=self.var, padx=5, pady=5)
        self.label1.grid(row=0, columnspan=2)

        label2 = Label(frame, text='Enter word:-', padx=2, pady=10)
        label2.grid(row=0)
        self.label1 = Label(frame, textvariable=self.var, padx=5, pady=5)
        self.label1.grid(row=0, column=2)

        button1 = Button(frame, text="Find", command=self.findword)
        button1.grid(row=0, column=4)
        self.e = Entry(frame, width=20)
        self.e.grid(row=0, column=2)

    def nw(self, master):
        frame = Frame(master)
        frame.pack()
        label1 = Label(frame, text='Find:-')
        label1.grid(row=0)
        self.entry1 = Entry(frame)
        self.entry1.grid(row=0, column=1)
        label1 = Label(frame, text='Replace:-')
        label1.grid(row=1)
        self.entry2 = Entry(frame)
        self.entry2.grid(row=1, column=1)
        button1 = Button(frame, text="Replace", command=self.rep1)
        button1.grid(row=0, column=2)
        button2 = Button(frame, text="Replace all", command=self.rep2)
        button2.grid(row=1, column=2)
        button3 = Button(frame, text="close", command=self.close)
        button3.grid(row=2, column=1)

    def rep1(self):
        w = self.entry1.get()
        r = self.entry2.get()

        m = re.sub(w, r, self.n, 1)

        if m != '':
            self.text.delete(1.0, END)
            self.text.insert(END, str(m))

    def rep2(self):

        w = self.entry1.get()
        r = self.entry2.get()

        m = re.sub(w, r, self.n)

        if m != '':
            self.text.delete(1.0, END)
            self.text.insert(END, str(m))

    def close(self):

        tkMessageBox.showinfo("Close", "Close?")
        answer = tkMessageBox.askquestion("close", "Are You Sure?")
        if (answer == "yes"):

            print("Done")
Exemplo n.º 47
0
class App(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.set_style()
        self.master.grid()
        self.create_widgets()
        sys.stdout = TextEmit(self.st2, 'stdout')
        sys.stderr = TextEmit(self.st2, 'stderr')
        self.cached_dict_of_dict = {}

    def set_style(self):
        s = ttk.Style()
        s.configure('TButton', padding=(5))
        s.configure('TCombobox', padding=(5))
        s.configure('exe.TButton', foreground='red')

    def parse_data(self):
        data_file = self.com.get()
        print('\n[Data File]: %s' % data_file)
        print('=' * 52)
        user_input = self.st1.get('0.1', 'end-1c')
        query_list = CSV_Dict.get_query_list(user_input)
        if data_file and query_list:
            if data_file not in self.cached_dict_of_dict:
                c = CSV_Dict.from_raw_data(os.path.join(DATA_PAHT,
                                                        data_file))
                current_dict = c.detailed_dict
                self.cached_dict_of_dict[data_file] = current_dict
            else:
                current_dict = self.cached_dict_of_dict[data_file]
            print('[Dictionary count]: %s\n' % len(current_dict.keys()))
            print('\n' + '=' * 52)
            CSV_Dict.do_query(query_list, current_dict)
            print('===== [Mission Complete] =====\n')
        else:
            sys.stderr.write('----- [Mission Failed] -----\n')
            print('\n')

    def clear_output(self):
        self.st2.configure(state='normal')
        self.st2.delete('1.0', 'end')
        self.st2.configure(state='disabled')

    def show_summary_of_data_file(self):
        data_file = os.path.join(DATA_PAHT, self.com.get())
        base_name = self.com.get()
        if not os.path.isfile(data_file):
            sys.stderr.write('>>>>> [Error]: Data file does not exist: %s\n' %
                             data_file)
        print('\n[Show Data File Summary]  %s' % base_name)
        print('=' * 52)
        with open(data_file, 'r') as f:
            for i, line in enumerate(f):
                if i < SUMMARY_LINE:
                    print('[ %d ] %s' % (i, line.strip()))
                else:
                    print('[ 10] ... ...')
                    print('[...] ... ...')
                    break

    def create_widgets(self):
        self.content = ttk.Frame(self.master, padding=(5))

        self.b1 = ttk.Button(self.content, text='Clear Query')
        self.combo_value = StringVar()
        self.com = ttk.Combobox(self.content, textvariable=self.combo_value,
                                state='readonly')
        if not os.path.isdir(DATA_PAHT):
            os.mkdir(data_folder)
        self.com['values'] = os.listdir(DATA_PAHT)
        if len(self.com['values']) > 0:
            self.com.current(0)
        else:
            sys.stderr.write('Please put csv data file in data folder and '
                             'restart this program.')
        self.b2 = ttk.Button(self.content, text='Data Summary',
                             command=self.show_summary_of_data_file)
        self.b3 = ttk.Button(self.content, text='Query', style='exe.TButton')
        self.b4 = ttk.Button(self.content, text='Clear Log')
        self.st1 = ScrolledText(self.content)
        self.st2 = ScrolledText(self.content)

        self.b1.grid(row=0, column=0, sticky=(W))
        self.b2.grid(row=0, column=1, sticky=(E))
        self.com.grid(row=0, column=1, sticky=(W+E))
        self.b3.grid(row=0, column=2, sticky=(W))
        self.b4.grid(row=0, column=3, sticky=(E))
        self.st1.grid(row=1, column=0, columnspan=2, sticky=(W+E+S+N))
        self.st2.grid(row=1, column=2, columnspan=2, sticky=(W+E+S+N))
        self.content.grid(row=0, column=0, sticky=(W+E+S+N))

        self.b1['command'] = lambda: self.st1.delete('0.1', 'end')
        self.b3['command'] = self.parse_data
        self.b4['command'] = self.clear_output

        self.master.rowconfigure(0, weight=1)
        self.master.columnconfigure(0, weight=1)
        self.content.rowconfigure(0, weight=0)
        self.content.rowconfigure(1, weight=1)
        self.content.columnconfigure(0, weight=1)
        self.content.columnconfigure(1, weight=1)
        self.content.columnconfigure(2, weight=1)
        self.content.columnconfigure(3, weight=1)

        self.st1.focus()
Exemplo n.º 48
0
Arquivo: mipsx.py Projeto: zrafa/mipsx
     def __init__(self, parent):

      	Frame.__init__(self, parent)   
         
       	self.parent = parent
	self.ejecucion = False



    	def prox_instruccion():
		p.stdin.write('step 1\n')

		mostrar_en(area4, "proximo")

		estado()
		if self.ejecucion:
			memoria()
			registros()
			listado()
		
	def ejecutar():
		while self.ejecucion:
			prox_instruccion()

	def salida(w, findelinea):
		w.delete("1.0", END)
				
		a = p.stdout.readline()
		while not findelinea in a:
			# Esto es para saber si la ejecucion termino'. 
			# TODO: Hay que quitarlo de este metodo. Donde ponerlo?
			if "No stack" in a:
				self.ejecucion = False
				w.insert(END,'\n\nEjecucion FINALIZADA\n\n')

			a = a.replace('(gdb) ', '')				
			w.insert(END,a)		
			a = p.stdout.readline() 		
	
	def mostrar_en(w, findelinea):
		p.stdin.write(findelinea)
		p.stdin.write('\r\n')
		salida(w, findelinea)

	def mostrar_en_depuracion():
		
     		file = open("/tmp/archivotemp"+PUERTOyPS+".txt")
	        contents = file.read()
		#area4.delete('1.0',END)
		area4.insert(END,contents)
		file.close()

		

	def memoria():
		# Para mostrar el segmento de datos, la etiqueta memoria debe estar al principio
		p.stdin.write('info address memoria\n')
		p.stdin.write('infomemoria\n')
		a = p.stdout.readline()
		solicitar_seg_de_datos = ""
		while not "infomemoria" in a:
			print "a : "+a
			if "Symbol " in a:
				a = a.replace('(gdb) Symbol "memoria" is at ', '')
				a = a.replace(' in a file compiled without debugging.','')
				solicitar_seg_de_datos = "x/40xw "+a+"\n"
			a = p.stdout.readline()
			
		if solicitar_seg_de_datos == "":
			p.stdin.write('x/40xw $pc\n')
		else:
			p.stdin.write(solicitar_seg_de_datos)
		p.stdin.write('x/40xw main\n')
		p.stdin.write('x/128 $sp - 128\n')
		mostrar_en(area3, "memoria")
	

	def estado():
		p.stdin.write('info frame\n')
		mostrar_en(area4, "estado")
     		file = open("/tmp/archivotemp"+PUERTOyPS+".txt")
	        contents = file.readline()
		while not "Remote" in contents:
			print contents
			area4.insert(END,contents)
	        	contents = file.readline()

		area4.insert(END,"----------------------------------------\nSalida Estandar : \n\n")

		contents = file.read()
		file.close()
		area4.insert(END,contents)


	def registros():
		p.stdin.write('info register\n')
		mostrar_en(area1, "registros")


	def listado():
		p.stdin.write('list 1,100\n')
		# p.stdin.write('disas main \n')
		p.stdin.write('disas \n')
		mostrar_en(area2, "listado")

	def compilarparasie():
		area4.delete('1.0',END)
		area4.insert('1.0',"Compilando para la SIE ...\r\n")
		root.update_idletasks()

		p.stdin.write('detach \n')
		guardar_archivo_a_compilar()
		tub = Popen(['mipsx_compilarparasie.sh', self.archivoacompilar, PUERTOyPS], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
		streamdata = tub.communicate()[0]
		mostrar_en_depuracion()

		if tub.returncode == 0:
			area4.insert(END, "Compilacion para la SIE OK\n")
		else:
			area4.insert(END, "ERROR al compilar y cargar")
			mostrar_en_depuracion()


	def compilarycargar():
		area4.delete('1.0',END)
		area4.insert('1.0',"Compilando y Cargando ...\r\n")
		root.update_idletasks()

		p.stdin.write('detach \n')
		guardar_archivo_a_compilar()
		tub = Popen(['mipsx_compilarycargar.sh', self.archivoacompilar, PUERTOyPS], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
		streamdata = tub.communicate()[0]
		mostrar_en_depuracion()

		if tub.returncode == 0:
			area4.insert(END, "Compilacion y carga : OK\n")


			# ejecutable = self.archivoactual+".elf"
			# ejecutable = ntpath.basename(ejecutable)
			ejecutable = self.archivoacompilar+".elf"
			ejecutable = ntpath.basename(ejecutable)

			# Nos conectamos al gdbserver
			# ip_mips="10.0.15.232"
			# ip_mips="192.168.0.71"

			ip_mips="10.0.15.50"
			#comando='target extended-remote '+ip_mips+':'+PUERTOyPS+'\n'
			comando='target remote '+ip_mips+':'+PUERTOyPS+'\n'
			p.stdin.write(comando)

			# gdbfile = 'set remote exec-file /tmp/'+ejecutable+'\n'
			# p.stdin.write(gdbfile)
			# Respondemos "y"es a recargar			
			p.stdin.write('y \n')

			# Abrimos con gdb el archivo ejecutable
			gdbfile = 'file /tmp/'+ejecutable+'\n'
			p.stdin.write(gdbfile)
			# Respondemos "y"es a recargar			
			p.stdin.write('y \n')
		
			p.stdin.write('delete \n')
			p.stdin.write('y \n')
			p.stdin.write('break main\n')
			# p.stdin.write('run\n')
			p.stdin.write('continue\n')
			self.ejecucion = True

			mostrar_en(area4,"estado")
			memoria()
			registros()
			listado()
		else:
			area4.insert(END, "ERROR al compilar y cargar")
			mostrar_en_depuracion()


	PUERTOyPS=str( random.randrange(4000,8000+1) )
	# PUERTOyPS="4567"


        self.parent.title("Mipsx - GUI for gdb multiarch")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

	# Para expandir cuando las ventanas cambian de tamao 
	for i in range(3):
		self.columnconfigure(i, weight=1)
	for i in range(20):
		self.rowconfigure(i, weight=1)

        lbl = Label(self, text="Registros                                      GDB en MIPS - MR3020")
        lbl.grid(row=1,column=2, sticky=W, pady=4, padx=5)
        

        area1 = Text(self,height=12,width=80)
        area1.grid(row=2, column=2, columnspan=1, rowspan=5, 
            sticky=E+W+S+N)
        
        lbl = Label(self, text="Programa en Assembler y Programa Binario Decodificado (disassemble)")
        lbl.grid(row=7, column=2, pady=1, padx=1, sticky=W+N+E+S)
        
    	area2 = Text(self, height=6,width=80)
        area2.grid(row=8, column=2, columnspan=1, rowspan=5, 
            padx=1, sticky=E+W+S+N)

        lbl = Label(self, text='Memoria - Segmento de datos (debe existir la etiqueta "memoria") - Segmento de texto - Pila')
        lbl.grid(row=13, column=2, pady=1, padx=1, sticky=W+N+E+S)

        area3 = Text(self,height=15,width=80)
        area3.grid(row=14, column=2, columnspan=1, rowspan=5, 
            padx=1, sticky=E+W+S+N)

        lbl4 = Label(self, text="Mensajes de Depuracion")
        lbl4.grid(row=13, column=0, pady=1, padx=1, sticky=W+N+E+S)

        area4 = Text(self,height=8,width=60)
        area4.grid(row=14, column=0, columnspan=1, rowspan=5, 
            padx=1, sticky=E+W+S+N)

        lbl = Label(self, text="Editor del Programa")
        lbl.grid(row=1,column=0, sticky=W, pady=4, padx=5) 
     
	area5 = ScrolledText(self,height=20,width=60)
	area5.grid(row=2, column=0, columnspan=1, rowspan=10, 
            padx=1, sticky=E+W+S+N)


	# Variables globales 
	archivoactual = "hello.s"
	archivoacompilar = "hello.s"
	archivotemp = "/tmp/archivotemp"+PUERTOyPS+".txt"
	# ip_mips = "10.0.15.232"
	ip_mips = "10.0.15.50"
	# ip_mips = "192.168.0.71"

	# Al abrir un archivo deseamos tener un area de trabajo cero
	def limpiar_areas():
		area4.delete('1.0',END)
		area3.delete('1.0',END)
		area2.delete('1.0',END)
		area1.delete('1.0',END)

	def abrir_en_editor(archivo):
		fd = open(archivo)      
		contents = fd.read()
		area5.delete('1.0',END)
	        area5.insert('1.0',contents)
	        fd.close()
	        self.archivoactual = archivo
		print self.archivoactual

	def open_command():
		FILEOPENOPTIONS = dict(defaultextension='*.s',
                  filetypes=[('Archivo assembler','*.s'), ('Todos los archivos','*.*')])
	        file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Select a file',
				**FILEOPENOPTIONS)
	        if file != None:
			limpiar_areas()
			abrir_en_editor(file.name)	      
 
	def guardar_archivo_a_compilar():
		self.archivoacompilar = "/tmp/archivo"+PUERTOyPS+".s"
		tub = Popen(['rm', self.archivoacompilar], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
		streamdata = tub.communicate()[0]
		tub = Popen(['touch', self.archivoacompilar], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
		streamdata = tub.communicate()[0]
		tmp = open(self.archivoacompilar, "w")
	    	if tmp != None:
	        	data = area5.get('1.0', END+'-1c')
	        	tmp.write(data)
	        	tmp.close()

			archivotmppwd = "archivo"+PUERTOyPS+".s"
			tub = Popen(['cp', self.archivoacompilar, archivotmppwd], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
			streamdata = tub.communicate()[0]
	

	def save_command():
	    file = tkFileDialog.asksaveasfile(mode='w')
	    if file != None:
	    # slice off the last character from get, as an extra return is added
	        data = area5.get('1.0', END+'-1c')
	        file.write(data)
	        file.close()
		self.archivoactual = file.name
                print self.archivoactual
         
	def exit_command():
	    if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
	        root.destroy()
	 
	def about_command():
	    label = tkMessageBox.showinfo("Acerca de", "MIPSX - GUI for gdb multiarch\n\nEntorno de desarrollo en lenguaje assembler arquitectura MIPS\nEste programa ensabla, genera el programa ejecutable, y lo ejecuta en modo debug en una maquina MIPS real\n\nCopyright 2014 Rafael Ignacio Zurita\n\nFacultad de Informatica\nUniversidad Nacional del Comahue\n\nThis program is free software; you can redistribute it and/or modify it under the terms of the GPL v2")
		         
 
	def dummy():
	    print "I am a Dummy Command, I will be removed in the next step"

	def no_hacer_nada():
		print "nada por hacer"

	def archivo_sin_guardar():
		data = area5.get('1.0', END+'-1c')
		fd = open(self.archivoactual)      
		contents = fd.read()
	        fd.close()
		if data == contents:
			return False
		res = tkMessageBox.askquestion("Confirmar", "Archivo sin guardar\nEsta seguro de finalizar el programa?", icon='warning')
		if res == 'yes':
			return False
		return True

	def salir():
		if archivo_sin_guardar():
			return

		tmp = "/tmp/archivo"+PUERTOyPS+".s"
		tmp2 = "archivo"+PUERTOyPS+".s"
		tmp3 = "/tmp/archivo"+PUERTOyPS+".s.elf"
		tmp4 = "/tmp/archivotemp"+PUERTOyPS+".txt"
		tub = Popen(['rm', tmp, tmp2, tmp3, tmp4], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
		streamdata = tub.communicate()[0]

		tmp2 = "/tmp/archivo"+PUERTOyPS+".s.o"
		ip_mips = "10.0.15.50"
		tub = Popen(['mipsx_finalizar_gdbserver.sh', ip_mips, PUERTOyPS, tmp, tmp2, tmp3, tmp4], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
		streamdata = tub.communicate()[0]
		# ip_mips = "10.0.15.232"
		# ip_mips = "192.168.0.71"
		# killgdbserver = Popen(['sshpass', '-p', clave, 'ssh', '-o', 'StrictHostKeyChecking=no', '-l', 'root', ip_mips, comando], stdout=PIPE, stdin=PIPE, stderr=STDOUT)	
		quit()



	menu = Menu(root)
	root.config(menu=menu)
	filemenu = Menu(menu)
	menu.add_cascade(label="Archivo", menu=filemenu)
	filemenu.add_command(label="Nuevo", command=dummy)
	filemenu.add_command(label="Abrir...", command=open_command)
	filemenu.add_command(label="Guardar...", command=save_command)
	filemenu.add_separator()
	filemenu.add_command(label="Salir", command=salir)


	menu.add_command(label="Run", command=ejecutar)
	menu.add_command(label="Next", command=prox_instruccion)
	menu.add_command(label="Breakpoint", command=no_hacer_nada)
	menu.add_command(label="Compilar y Cargar", command=compilarycargar)
	menu.add_command(label="Compilar para SIE", command=compilarparasie)

	helpmenu = Menu(menu)
	menu.add_cascade(label="Ayuda", menu=helpmenu)
	helpmenu.add_command(label="Acerca de...", command=about_command)
	menu.add_command(label="Salir", command=salir)
 	abrir_en_editor("hello.s")
        
	# para que al cerrar la ventana cierre los temporales y los borre
	root.protocol("WM_DELETE_WINDOW", salir)