Ejemplo n.º 1
0
class editor:
 def __init__(self,rt):
  if rt==None:
   self.t=Tk()
  else:
   self.t=Toplevel(rt)
  self.t.title("Tkeditor %d"%len(t1))
  self.bar=Menu(rt)
   
  self.filem=Menu(self.bar)
  self.filem.add_command(label="打开",command=self.openfile)
  self.filem.add_command(label="新建",command=neweditor)
  self.filem.add_command(label="保存",command=self.savefile)
  self.filem.add_command(label="关闭",command=self.close)
  self.filem.add_separator()
  self.filem.add_command(label="退出",command=die)
   
  self.helpm=Menu(self.bar)
  self.helpm.add_command(label="关于",command=about)
  self.bar.add_cascade(label="文件",menu=self.filem)
  self.bar.add_cascade(label="帮助",menu=self.helpm)
  self.t.config(menu=self.bar)
   
  self.f=Frame(self.t,width=512)
  self.f.pack(expand=1,fill=BOTH)
   
  self.st=ScrolledText(self.f,background="white")
  self.st.pack(side=LEFT,fill=BOTH,expand=1)
  
  self.open = Button(self)
  self.open["text"] = "open"   
  self.open["fg"] = "Blue"
  self.open["command"] = self.openfile
  self.open.pack({"side":"left"})
  self.open.pack({"anchor":"nw"})
  
 def close(self):
  self.t.destroy()
  print "close"
  
 def openfile(self):
  p1=END
  oname=askopenfilename(filetypes=[("Python file","*.*")])
  if oname:
   for line in fileinput.input(oname):
    self.st.insert(p1,line)
   self.t.title(oname)
  
 def savefile(self):
  sname=asksaveasfilename()
  if sname:
   ofp=open(sname,"w")
   ofp.write(self.st.get(1.0,END))
   ofp.flush()
   ofp.close()
   self.t.title(sname)
class Editor(object):
    def __init__(self):
        self.root = Tk()
        self.root.title('untitled')
        self.menubar = Menu(self.root)
        # file menu
        self.file_menu = Menu(self.menubar)
        self.file_menu.add_command(label='打开', command=self.openfile)
        self.file_menu.add_command(label='保存', command=self.savefile)
        self.file_menu.add_separator()
        self.file_menu.add_command(label='退出', command=self.exit)
        # help menu
        self.help_menu = Menu(self.menubar)
        self.help_menu.add_command(label='关于', command=self.about)
        # menu
        self.menubar.add_cascade(label='文件', menu=self.file_menu)
        self.menubar.add_cascade(label='帮助', menu=self.help_menu)
        self.root.config(menu=self.menubar)
        # frame
        self.frame = Frame(width=512)
        self.frame.pack(expand=1, fill=BOTH)
        # scrolled text
        ft = tkFont.Font(family='Consolas', size=12, weight=tkFont.NORMAL)
        self.st = ScrolledText(self.frame, bg='navyblue', fg='white', font=ft)
        self.st.pack(side=LEFT, fill=BOTH, expand=1)
        # run
        self.root.mainloop()

    def openfile(self):
        filename = askopenfilename(
            filetypes=[('Python files', '*.py'), ('Text files',
                                                  '*.txt'), ('All files',
                                                             '*.*')])
        if filename:
            self.root.title(filename)
            self.st.delete(1.0, END)
            for line in fileinput.input(filename):
                self.st.insert(END, line)

    def savefile(self):
        filename = asksaveasfilename(filetypes=[('Python files', '*.py')],
                                     defaultextension='py')
        if filename:
            ofp = open(filename, 'w')
            ofp.write(self.st.get(1.0, END))
            ofp.flush()
            ofp.close()
            self.root.title(filename)

    def exit(self):
        self.root.destroy()

    def about(self):
        tkMessageBox.showinfo('About Tkeditor', 'Tkeditor V1.0\nby Laozhao')
Ejemplo n.º 3
0
class editor:
    def __init__(self,rt):

        self.top=Tk()
        self.top.title('记事本')
        self.top.geometry('300x400')
        self.bar=Menu(self.top)
  
        self.filem=Menu(self.bar)
        self.filem.add_command(label="打开",command=self.openfile)
        self.filem.add_command(label="新建",command=self.neweditor)
        self.filem.add_command(label="保存",command=self.savefile)
        self.filem.add_command(label="关闭",command=self.close)

        self.helpm=Menu(self.bar)
        self.helpm.add_command(label="Help",command=self.about)
        self.bar.add_cascade(label="文件",menu=self.filem)
        self.bar.add_cascade(label="帮助",menu=self.helpm)
        self.top.config(menu=self.bar)
  
        self.f=Frame(self.top,width=512)
        self.f.pack(expand=1,fill=BOTH)
  
        self.st=ScrolledText(self.f,background="white")
        self.st.pack(side=LEFT,fill=BOTH,expand=1)
        
    def close(self):
        self.top.destroy()
 
    def openfile(self):
        p1=END
        oname=askopenfilename()#filetypes=[("Python file","*.*")])
        if oname:
            for line in fileinput.input(oname):
                self.st.insert(p1,line)
                self.top.title(oname)
 
    def savefile(self):
        sname=asksaveasfilename()
        if sname:
            ofp=open(sname,"w")
            ofp.write(self.st.get(1.0,END).encode('utf-8'))
            ofp.flush()
            ofp.close()
            self.top.title(sname)
 
    def neweditor(self):
        global root
        self.top.append(editor(root))
        
        
    def about(self):
        tkMessageBox.showwarning("Tkeditor",'What?\n记事本也要帮助?')
Ejemplo n.º 4
0
class Add_Group(Frame):
	def __init__(self, parent, app):
		Frame.__init__(self, parent)
		self.parent = parent
		self.app = app

		#Frame to hold Keyword Group new Entry and new keywords text box
		addKGFrame = Frame(parent, bg="#E8E8E8", relief=RAISED)
		addKGFrame.pack(fill=BOTH, expand=True, side=LEFT, padx=10, pady=10)

		#Label for Entry Box
		addGroupLabel = Label(addKGFrame, text="Enter New Group Name",bg="#E8E8E8")
		addGroupLabel.pack(side=TOP)

		#Entry Box for new Keyword Group
		self.addGroup = Entry(addKGFrame, width=30, relief=SUNKEN)
		self.addGroup.pack(side=TOP, fill=X, expand=True, pady=5)

		#Label for New Keywords for Group Text Box
		addKGLabel = Label(addKGFrame, text="Enter New Keywords (Optional)",bg="#E8E8E8")
		addKGLabel.pack(side=TOP, fill=X, expand=True, pady=5)

		#Canvas for Text Box to Enter New Keywords for New Group
		addKGCanvas = Canvas(addKGFrame, bg="#E8E8E8", relief=SUNKEN)
		addKGCanvas.pack(side=TOP, fill=BOTH, expand=True, pady=5)

		#Keywords for new group scrollable text box
		self.addKGText = ScrolledText(addKGCanvas, wrap=WORD, width=25, 
			height=15, relief=SUNKEN, highlightthickness=0, bd=1, padx=1, pady=1)
		self.addKGText.pack(fill=BOTH, side=TOP, expand=True)

		#Button to add new Keyword Group and Keywords
		addKGButton = Button(addKGFrame, text="Add Group", 
			width=30, highlightbackground='#E8E8E8', command=self.group_add)
		addKGButton.pack(side=TOP, fill=BOTH, expand=True)

	#Function to add the keyword group
	def group_add(self):
		newGroup = self.addGroup.get()
		if newGroup != "":
			self.app.key_group.keyword_groups[newGroup] = []

			text = self.addKGText.get('1.0', 'end-1c').splitlines()
			for line in text:
				self.app.key_group.keyword_groups[newGroup].append(line)
			self.app.Groups.groupList.delete(0, END)
			for x in self.app.key_group.keyword_groups:
				self.app.Groups.groupList.insert(END, '%s' % x)

			self.addKGText.delete('1.0', END)
			self.addGroup.delete(0, END)
Ejemplo n.º 5
0
class LogWindow(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title("Network Simulator Log")
        self.text = ScrolledText(self)
        self.text.pack(fill=BOTH, expand=1)
        self.pack(fill=BOTH, expand=1)
        self.text.config(
            background="black",
            foreground="white",
            font=Font(family="Courier", weight="bold"),
            # state=DISABLED,
            wrap=NONE,
        )

        self.text.tag_config("DEBUG", foreground="green")
        self.text.tag_config("ERROR", foreground="red")
        self.text.tag_config("CRITICAL", foreground="red")
        self.text.tag_config("EXCEPTION", foreground="red")
        self.text.tag_config("WARNING", foreground="yellow")
        self.text.tag_config("INFO", foreground="white")

        self.text.bind("<Key>", lambda e: 'break')
        self.text.bind("<Return>", self._clear)
        self.queue = Queue()
        self._update()

    def _clear(self, event):
        self.text.delete(1.0, END)
        return 'break'

    def _update(self):
        try:
            while True:
                text, level = self.queue.get(block=False)

                at_bottom = self.text.yview()[1] == 1.0
                # self.text.config(state=NORMAL)
                if len(self.text.get(1.0, END).strip()) != 0:
                    text = "\n" + text
                self.text.insert(END, text, str(level))
                # self.text.config(state=DISABLED)
                if at_bottom:
                    self.text.yview_moveto(1.0)
        except Empty:
            pass
        self.after(50, self._update)

    def append(self, entry, level="INFO"):
        self.queue.put((entry, level))
Ejemplo n.º 6
0
class LogWindow(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title("Network Simulator Log")
        self.text = ScrolledText(self)
        self.text.pack(fill=BOTH, expand=1)
        self.pack(fill=BOTH, expand=1)
        self.text.config(
            background="black",
            foreground="white",
            font=Font(
                family="Courier", weight="bold"),
            # state=DISABLED,
            wrap=NONE, )

        self.text.tag_config("DEBUG", foreground="green")
        self.text.tag_config("ERROR", foreground="red")
        self.text.tag_config("CRITICAL", foreground="red")
        self.text.tag_config("EXCEPTION", foreground="red")
        self.text.tag_config("WARNING", foreground="yellow")
        self.text.tag_config("INFO", foreground="white")

        self.text.bind("<Key>", lambda e: 'break')
        self.text.bind("<Return>", self._clear)
        self.queue = Queue()
        self._update()

    def _clear(self, event):
        self.text.delete(1.0, END)
        return 'break'

    def _update(self):
        try:
            while True:
                text, level = self.queue.get(block=False)

                at_bottom = self.text.yview()[1] == 1.0
                # self.text.config(state=NORMAL)
                if len(self.text.get(1.0, END).strip()) != 0:
                    text = "\n" + text
                self.text.insert(END, text, str(level))
                # self.text.config(state=DISABLED)
                if at_bottom:
                    self.text.yview_moveto(1.0)
        except Empty:
            pass
        self.after(50, self._update)

    def append(self, entry, level="INFO"):
        self.queue.put((entry, level))
Ejemplo n.º 7
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
Ejemplo n.º 8
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)
Ejemplo n.º 9
0
class Application:
    def __init__(self, file=None):
        self.root = Tk()
        self.root.title("Pipeline Viewer")
        self.file = file
        self.dbGraph = gs.dbGraph
        self.WIDTH = 1000
        self.HEIGHT = 800
        #gs.plot(self.graph, bbox=(self.WIDTH - 100, self.HEIGHT-100))
        self.root.geometry("{0}x{1}".format(self.WIDTH, self.HEIGHT))
        self.root.columnconfigure(0, weight=10)
        self.root.columnconfigure(1, weight=1)
        #self.root.rowconfigure(0, weight=10)
        self.root.rowconfigure(1, weight=10)
        #self.root.rowconfigure(2, weight=10)

        self.nodes = []
        self.edges = []
        self.selColor = "green"
        self.currSel = None
        self.isCtrlDown = False
        self.drawingEdge = False

        self.c = Canvas(self.root, bg="white")
        self.c.grid(row=0, column=0, rowspan=5, sticky=N + S + W + E)

        self.stateBar = Label(self.root,
                              text="",
                              bd=1,
                              relief=SUNKEN,
                              anchor=W)
        self.stateBar.grid(row=4, columnspan=3, sticky=E + W)

        self.list = Listbox(self.root, width=30)
        self.sbar = Scrollbar(self.root)
        self.sbar.config(command=self.list.yview)
        self.list.config(yscrollcommand=self.sbar.set)
        self.list.grid(row=1, column=1, sticky=N + S + E + W)
        self.sbar.grid(row=1, column=2, sticky=N + S)
        for i in range(len(self.dbGraph.vs)):
            self.list.insert(i, self.dbGraph.vs[i]["varSet"]["className"])

        self.addButton = Button(self.root,
                                text="Add",
                                command=self.addToLayout)
        self.addButton.grid(row=0, column=1, columnspan=2, sticky=E + W)

        self.addButton = Button(self.root,
                                text="Save",
                                command=self.saveAttributes)
        self.addButton.grid(row=2, column=1, columnspan=2, sticky=E + W)
        self.scrolledText = ScrolledText(self.root,
                                         width=30,
                                         undo=True,
                                         setgrid=True,
                                         wrap='word')
        self.scrolledText.grid(row=3,
                               column=1,
                               columnspan=2,
                               sticky=N + S + W + E)

        self.scrolledText.insert("insert", "")

        self.dummyEdge = Edge((-1, -1), (-1, -1), self.c, None, None,
                              "dummyEdge")
        self.c.bind("<Button-1>", self.mouseDown)
        self.c.bind("<Button1-Motion>", self.mouseMove)
        self.c.bind("<Button1-ButtonRelease>", self.mouseUp)
        self.root.bind("<KeyPress-Control_L>", self.controlDown)
        self.root.bind("<KeyRelease-Control_L>", self.controlUp)
        self.root.bind("<Delete>", self.deleteSelection)

        self.list.bind('<<ListboxSelect>>', self.deselect)

        if self.file is not None:
            self.openLayout(dialog=False)
        else:
            self.newLayout()

        menubar = Menu(self.root)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="New", command=self.newLayout)
        filemenu.add_command(label="Open", command=self.openLayout)
        filemenu.add_command(label="Save", command=self.saveLayout)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.quit)
        menubar.add_cascade(label="File", menu=filemenu)
        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Reorder")
        menubar.add_cascade(label="Edit", menu=editmenu)
        self.root.config(menu=menubar)

        self.root.after(10, self.drawLoop)
        self.root.mainloop()

    def newLayout(self):
        for n in self.nodes:
            n.delete()
        for e in self.edges:
            e.delete()
        self.nodes, self.edges = [], []
        self.currSel = None
        self.isCtrlDown = False
        self.drawingEdge = False
        self.graph = gs.Graph()
        self.graph.vs["name"] = ""

    def openLayout(self, dialog=True):
        if dialog:
            self.file = askopenfilename(filetypes=(("XML files", "*.xml"),
                                                   ("All files", "*.*")))
        self.newLayout()
        self.graph = gs.unserializeGraph(self.file)
        gs.buildDependences(self.graph)
        self.topologicalGrid()
        #gs.plot(self.graph, bbox=(self.WIDTH - 100, self.HEIGHT-100))
        self.createNodesFromGraph()
        self.createEdgesFromGraph()

    def saveLayout(self):
        f = asksaveasfile(mode='w',
                          defaultextension=".xml",
                          filetypes=(("XML files", "*.xml"), ("All files",
                                                              "*.*")))
        if f is None:
            return
        f.write(gs.serializeGraph(self.graph, f.name))
        f.close()

        name = f.name
        name = name.replace(".xml", "")
        generateBenchmark(f.name, "{0}Benchmark.xml".format(name))
        generateEmbedded(f.name, "{0}Embedded.xml".format(name))

    def addToLayout(self):
        self.addNodeFromDB(self.list.get(ACTIVE))

    def saveAttributes(self):
        if self.currSel in self.nodes:
            attr = ast.literal_eval(self.scrolledText.get(1.0, END))
            self.graph.vs[gs.iv(self.currSel.tag, self.graph)]["varSet"] = attr

    def topologicalGrid(self):
        positions = self.graph.topological_sorting()
        width = 85
        height = (self.HEIGHT -
                  250) / (max([n.degree() for n in self.graph.vs]) + 1)
        height2 = (self.HEIGHT) / len(self.graph.vs)
        beg = filter(lambda x: self.graph.vs[x].indegree() == 0, positions)
        self.graph.vs["x"] = 5
        self.graph.vs["y"] = 5
        i = 0
        for p in beg:
            self.graph.vs[p]["y"] += i * height2
            i += 1
        for p in positions:
            node = self.graph.vs[p]
            j = 0
            order = sorted(node.successors(),
                           key=lambda x: len(
                               filter(lambda n: isinstance(n, int),
                                      x.shortest_paths()[0])),
                           reverse=True)
            for succ in order:
                succ["x"] = node["x"] + width
                succ["y"] = node["y"] + j * height

                j += 1

    def tagNode(self, n1, n2):
        return "{0}_to_{1}".format(n1, n2)

    def findNode(self, name):
        for n in self.nodes:
            if name == n.tag:
                return n
        return None

    def findEdge(self, n1, n2=None):
        if n2 is None:
            tag = n1
        else:
            tag = self.tagNode(n1, n2)
        for e in self.edges:
            if tag == e.tag:
                return e
        return None

    def addNodeFromDB(self, n):
        node = gs.addVertexFromDB(n, self.graph)
        if node is not None:
            node["x"] = self.WIDTH - Node.width
            node["y"] = 0
            self.nodes.append(
                Node(node["x"], node["y"], len(node["varSet"]["dependencies"]),
                     self.c, node["name"]))

    def addEdge(self, n1, n2):
        if (self.findEdge(n1, n2) is None) and (n1 != n2):
            if gs.addEdge(n1, n2, self.graph):
                node1 = self.findNode(n1)
                node2 = self.findNode(n2)
                self.edges.append(
                    Edge(self.c.coords(node1.rect), self.c.coords(node2.rect),
                         self.c, node1, node2, self.tagNode(n1, n2)))

    def createNodesFromGraph(self):
        for n in self.graph.vs:
            self.nodes.append(
                Node(n["x"], n["y"], len(n["varSet"]["dependencies"]), self.c,
                     n["name"]))
        for n in self.nodes:
            coords = self.c.coords(n.rect)
            while len(
                    self.c.find_overlapping(
                        coords[0], coords[1], coords[2],
                        coords[3])) == 2 + len(n.ovals) and coords[1] > 0:
                self.c.move(n.tag, 0, -1)
                coords = self.c.coords(n.rect)

            self.c.move(n.tag, 0, 1.5 * Node.height)

    def createEdgesFromGraph(self):
        for e in self.graph.get_edgelist():
            n1 = self.graph.vs[e[0]]["name"]
            n2 = self.graph.vs[e[1]]["name"]
            node1 = self.findNode(n1)
            node2 = self.findNode(n2)
            self.edges.append(
                Edge(self.c.coords(node1.rect), self.c.coords(node2.rect),
                     self.c, node1, node2, self.tagNode(n1, n2)))

    def drawLoop(self):
        for e in self.edges:
            n1 = self.c.coords(e.n1.rect)
            index = self.graph.vs[gs.iv(
                e.n2.tag,
                self.graph)]["varSet"]["dependencies"].index(e.n1.tag)
            n2 = self.c.coords(e.n2.ovals[index])

            xs = arrowFit(n1[0], n1[2], n2[0], n2[2])
            ys = arrowFit(n1[1], n1[3], n2[1], n2[3])
            self.c.coords(e.tag, xs[0], ys[0], xs[1], ys[1])

        self.root.after(10, self.drawLoop)

    def removeEdge(self, n1, n2):
        edge = self.findEdge(n1, n2)
        edge.delete()
        gs.removeEdge(n1, n2, self.graph)
        self.edges.remove(edge)

    def removeNode(self, n):
        node = self.findNode(n)
        for succ in self.graph.vs[gs.iv(n, self.graph)].successors():
            self.removeEdge(node.tag, succ["name"])

        for pred in self.graph.vs[gs.iv(n, self.graph)].predecessors():
            self.removeEdge(pred["name"], node.tag)

        gs.removeVertex(node.tag, self.graph)
        node.delete()
        self.nodes.remove(node)

    def inRect(self, x, y, rect):
        if (x < rect[0]):
            return False
        if (y < rect[1]):
            return False
        if (x > rect[2]):
            return False
        if (y > rect[3]):
            return False
        return True

    def deselect(self, event):
        if self.currSel is not None:
            self.c.itemconfig(primTag(self.currSel.tag),
                              fill=self.currSel.defaultColor)
            self.c.itemconfig(primTag(self.currSel.tag), width=1)
            self.currSel = None

    def handleSelection(self, event):
        self.list.selection_clear(0, END)
        dstObject = self.c.find_overlapping(event.x, event.y, event.x + 1,
                                            event.y + 1)
        objs = self.c.gettags(dstObject)
        self.deselect(event)
        self.scrolledText.delete("1.0", END)
        self.scrolledText.insert("insert", "")
        if (len(dstObject)):
            objs = self.c.gettags(dstObject[0])
            s = self.findNode(objs[0])
            if s is None:
                s = self.findEdge(objs[0])
            if s is not None:
                self.currSel = s
                self.c.itemconfig(primTag(self.currSel.tag),
                                  fill=self.selColor)
                self.c.itemconfig(primTag(self.currSel.tag), width=2)

    def mouseDown(self, event):
        self.handleSelection(event)
        self.x1, self.y1 = event.x, event.y
        if self.currSel in self.nodes:
            self.scrolledText.insert(
                "insert",
                json.dumps(self.graph.vs[gs.iv(self.currSel.tag,
                                               self.graph)]["varSet"],
                           indent=4).replace("null", "None"))

            if self.isCtrlDown:
                self.drawingEdge = True
                self.c.coords("dummyEdge", self.x1, self.y1, self.x1, self.y1)

    def mouseMove(self, event):
        x2, y2 = event.x, event.y
        if not self.drawingEdge:
            dx, dy = x2 - self.x1, y2 - self.y1
            if self.currSel is not None:
                self.c.move(self.currSel.tag, dx, dy)
                self.x1, self.y1 = x2, y2
        else:
            coords = self.c.coords("dummyEdge")
            self.c.coords(self.dummyEdge.arrow, coords[0], coords[1], x2, y2)
            self.c.tag_raise(self.dummyEdge.arrow)

    def mouseUp(self, event):
        if not self.drawingEdge:
            if self.currSel is not None:
                self.c.itemconfig(primTag(self.currSel.tag), width=1)
        else:
            dstObject = self.c.find_overlapping(event.x, event.y, event.x + 1,
                                                event.y + 1)[0]
            dstTag = self.c.gettags(dstObject)[0]
            if (dstTag in [n.tag for n in self.nodes]) and (self.inRect(
                    event.x, event.y, self.c.coords(dstTag))):
                self.addEdge(self.currSel.tag, dstTag)

            self.drawingEdge = False
            self.c.coords(self.dummyEdge.arrow, -1, -1, -1, -1)

    def deleteSelection(self, event):
        if self.currSel is not None:
            if self.currSel in self.nodes:
                self.removeNode(self.currSel.tag)
            elif self.currSel in self.edges:
                self.removeEdge(self.currSel.n1.tag, self.currSel.n2.tag)

        self.currSel = None

    def controlDown(self, event):
        self.isCtrlDown = True

    def controlUp(self, event):
        self.isCtrlDown = False
Ejemplo n.º 10
0
    global g_name,f_param_name,f_param_type,g_type,f_isfunc
    g_name = None
    g_type = None
    f_param_name = []
    f_param_type = []
    f_isfunc = False

###################################### UI Segment ######################################

def quit_error_label():
	src_program = textPad.get('1.0',END)
	file_writer = open('src_program.c','w')
	file_writer.write(src_program.strip())
	file_writer.close()
	root.destroy()

def print_error(err_msg):
	global error_label
	# parser.stop_yacc()
	label = Label(text=err_msg)
	label.pack()
	# button = Button(text='Quit', command=quit_error_label)
	# button.pack()

textPad.pack()
src_program = textPad.get('1.0',END)
lexer = lex.lex()
parser = yacc.yacc()
parser.parse(src_program)

root.mainloop()
Ejemplo n.º 11
0
class TkApp(tk.Tk):
    def __init__(self, className=" TextMate"):
        tk.Tk.__init__(self, className=className)
        self.textPad = ScrolledText(self, width=50, height=30, font=("Monospace Regular", 13), highlightthickness=0, bd=4, undo="True")
        self.iconbitmap(r'te.ico')
        self.textPad.pack()

        menu = tk.Menu(self)
        self.textPad.tag_config("bt", background="yellow")
        self.textPad.tag_config("kw", foreground="medium sea green")
        self.textPad.tag_config("com", foreground="red")
        self.textPad.tag_config("str", foreground="purple")
        self.config(menu=menu)
                      
        filemenu = tk.Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New File", command=self.new_command, accelerator="Ctrl+N")
        self.bind_all("<Control-n>",self.new_command)
        filemenu.add_command(label="Open", command=self.open_command, accelerator="Ctrl+O")
        self.bind_all("<Control-o>",self.open_command)
        filemenu.add_separator()
        filemenu.add_command(label="Save", command=self.save_command, accelerator="Ctrl+S")
        self.bind_all("<Control-s>",self.save_command)
        filemenu.add_command(label="Save As", command=self.saveas_command, accelerator="Ctrl+Shift+S")
        self.bind_all("<Control-Shift-S>",self.saveas_command)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.exit_command, accelerator="Ctrl+Q")
        self.bind_all("<Control-q>",self.exit_command)

        editmenu=tk.Menu(menu)
        menu.add_cascade(label="Edit", menu=editmenu)
        editmenu.add_command(label="Undo", command=self.undo_command, accelerator="Ctrl+Z")
        editmenu.add_command(label="Redo", command=self.redo_command, accelerator="Ctrl+Shift+Z")
        self.bind_all("<Control-Shift-Z>",self.redo_command)
        editmenu.add_separator()
        editmenu.add_command(label="Cut", command=self.cut_command, accelerator="Ctrl+X")
        editmenu.add_command(label="Copy", command=self.copy_command, accelerator="Ctrl+C")
        editmenu.add_command(label="Paste", command=self.paste_command, accelerator="Ctrl+V")
        editmenu.add_separator()
        editmenu.add_command(label="Select All", command=self.selectall_command, accelerator="Ctrl+A")
        self.bind_all("<Control-a>",self.selectall_command)
        editmenu.add_command(label="Delete All", command=self.deleteall_command, accelerator="Ctrl+D")
        self.bind_all("<Control-d>",self.deleteall_command)

        formatmenu = tk.Menu(menu)
        menu.add_cascade(label="Format", menu=formatmenu)
        formatmenu.add_command(label="Font", command=self.font_command, accelerator="Ctrl+M")
        self.bind_all("<Control-m>",self.font_command)
        formatmenu.add_separator()
        formatmenu.add_command(label="Bold", command=self.bold_command, accelerator="Ctrl+B")
        self.bind_all("<Control-b>",self.bold_command)
        formatmenu.add_command(label="Italics", command=self.italic_command, accelerator="Ctrl+I")
        self.bind_all("<Control-i>",self.italic_command)
        formatmenu.add_command(label="Underline", command=self.underline_command, accelerator="Ctrl+U")
        self.bind_all("<Control-u>",self.underline_command)
        formatmenu.add_command(label="Bold-Italic", command=self.bolditalic_command)
        
        preferences = tk.Menu(menu)
        menu.add_cascade(label="Preferences", menu=preferences)
        preferences.add_radiobutton(label="Text Mode", command =self.text_command)
        preferences.add_radiobutton(label="Code Mode", command =self.code_command)
        
        toolsmenu = tk.Menu(menu)
        menu.add_cascade(label="Tools", menu=toolsmenu)
        toolsmenu.add_command(label="Find", command=self.find_command, accelerator="Ctrl+F")
        self.bind_all("<Control-f>",self.find_command)
        toolsmenu.add_command(label="Replace", command=self.replace_command, accelerator="Ctrl+H")
        self.bind_all("<Control-h>",self.replace_command)
        toolsmenu.add_separator()      
        toolsmenu.add_command(label="Spell Check", command=self.spellcheck_command)
        toolsmenu.add_command(label="Translate", command=self.translate_command)
        toolsmenu.add_command(label="Brace Matching", command=self.braces_command)
        toolsmenu.add_command(label="Document Comparision", command=self.comparedoc_command)
        
        helpmenu = tk.Menu(menu)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About", command=self.about_command)
        
    def new_command(self,*args):
        new=TkApp()

    def open_command(self,*args):
        data = self.textPad.get('1.0', 'end-1c')
        flag=0
        for i in data:
            if(i!='\n'):
                flag=1
                break
        if(not(flag)):
            file = askopenfile(mode='rb',title='Select a file')
            if file != None:
                self.deleteall_command(self,*args)
                contents = file.read()
                self.textPad.insert('1.0',contents)
                file.close()
        else:
            if(askokcancel("Save", "You have unsaved changes. Save?")):
                self.save_command(self,*args)
            file = askopenfile(mode='rb',title='Select a file')
            if file != None:
                self.deleteall_command(self,*args)
                contents = file.read()
                self.textPad.insert('1.0',contents)
                file.close()
        global filename
        if(file!=None):
            a=[x for x in str(file).split("'")]
            filename=a[1]

    def save_command(self,*args):
        contents = self.textPad.get('1.0','end-1c')
        global filename
        try:
            with open(filename, 'w') as outputFile:  
                outputFile.write(contents)         
        except IOError:                     
            self.saveas_command()    

    def saveas_command(self,*args):
        file = asksaveasfile(mode = 'w', title='Save As')
        if file != None:
            data = self.textPad.get('1.0', 'end-1c')
            file.write(data)
            file.close()
            global filename
            a=[x for x in str(file).split("'")]
            filename=a[1]
            
    def exit_command(self,*args):
        data = self.textPad.get('1.0', 'end-1c')
        flag=0
        for i in data:
            if(i!='\n'):
                flag=1
                break
        if(flag):
            if(askokcancel("Save", "Save before closing?")):
                self.save_command(self,*args)
            self.destroy()
        else:
            if(askokcancel("Quit", "Are you sure you want to quit?")):
                self.destroy()

    def code_command(self,*args):
        self.bind("<Key>",self.auto_indent,add="+")
        self.bind("<Return>",self.keep_indent)
        self.bind("<Key>",self.keywords_command,add="+")
        self.bind("<Key>",self.comment_command,add="+")
        self.bind("<Key>",self.string_command,add="+")

    def text_command(self,*args):
        self.unbind("<Key>")
        self.unbind("<Return>")

    def copy_command(self,*args):
        try:
            self.clipboard_clear()
            text = self.textPad.get("sel.first", "sel.last")
            self.clipboard_append(text)
        except:
            pass

    def paste_command(self,*args):
        try:
            text = self.selection_get(selection='CLIPBOARD')
            self.textPad.insert('insert', text)
        except:
            pass

    def cut_command(self,*args):
        try:
            self.copy_command()
            self.textPad.delete("sel.first", "sel.last")
        except:
            pass

    def selectall_command(self,*args):
        self.textPad.tag_add('sel','1.0', 'end')
        
    def deleteall_command(self,*args):
        self.textPad.delete('1.0', 'end')

    def undo_command(self,*args):
        try:
            self.textPad.edit_undo()
        except:
            pass

    def redo_command(self,*args):
        try:
            self.textPad.edit_redo()
        except:
            pass

    def find_command(self,*args):
        search=askstring("Find", "")
        if(search==None):
            return
        l=len(search)
        data = self.textPad.get('1.0', 'end-1c')
        ind=[m.start() for m in finditer(search,data)]
        for i in ind:
            corpus=data[:i]
            last=0
            line_no=1
            k=0
            for j in corpus:
                k+=1
                if(j=='\n'):
                    line_no+=1
                    last=k
            st=str(line_no)+'.'+str(i-last)
            end=str(line_no)+'.'+str(i-last+l)
            self.textPad.tag_add('bt',st,end)

    def replace_command(self,*args):
        search=askstring("Find", "")
        rep=askstring("Replace with", "")
        if(search==None or rep==None):
            return
        l=len(search)
        data = self.textPad.get('1.0', 'end-1c')
        ind=[m.start() for m in finditer(search,data)]
        for count in range(len(ind)):
            data = self.textPad.get('1.0', 'end-1c')
            if(search in data):
                i=data.index(search)
            corpus=data[:i]
            last=0
            line_no=1
            k=0
            for j in corpus:
                k+=1
                if(j=='\n'):
                    line_no+=1
                    last=k
            st=str(line_no)+'.'+str(i-last)
            end=str(line_no)+'.'+str(i-last+l)
            self.textPad.delete(st,end)
            self.textPad.insert(st,rep)
                
    def about_command(self,*args):
        label = showinfo("TextMate", "A small and lightweight text editor.\n© 2017. All rights reserved.")

    def braces_command(self,*args):
        data = self.textPad.get('1.0', 'end-1c')
        a=[]
        for i in data:
            if(i=='(' or i=='{' or i=='['):
                a.append(i)
            if(i==')'):
                if(a==[] or a[-1]!='('):
                    label = showinfo("Brace Matching","Parenthesis don't match")
                    return
                else:
                    a.pop()
            if(i=='}'):
                if(a==[] or a[-1]!='{'):
                    label = showinfo("Brace Matching","Curly braces don't match")
                    return
                else:
                    a.pop()
            if(i==']'):
                if(a==[] or a[-1]!='['):
                    label = showinfo("Brace Matching","Square braces don't match")
                    return
                else:
                    a.pop()
        if(a==[]):
            label = showinfo("Brace Matching","All braces match!")
        else:
            ch=a[-1]
            if(ch=='('):
                label = showinfo("Brace Matching","Parenthesis don't match")
                return
            elif(ch=='{'):
                label = showinfo("Brace Matching","Curly braces don't match")
                return
            else:
                label = showinfo("Brace Matching","Square braces don't match")
                return

    def spellcheck_command(self,*args):
        dic=Dict("en_US")
        data=word_tokenize(self.textPad.get('1.0', 'end-1c'))
        for word in data:
                if not dic.check(word) and word.isalpha():
                        suggestions_list=dic.suggest(word)
                        suggestions_str=""
                        for w in suggestions_list:
                                suggestions_str+=w+" "
                        showinfo("Suggestions for '"+word+"'\n",suggestions_str)
        showinfo("Spell Check","Finished checking!")
        
    def translate_command(self,*args):
        try:
                translator = Translator()
                text = self.textPad.get("sel.first", "sel.last")
                language = askstring("Translate", "Kannada | Hindi | Tamil | Telugu | English")
                if language.lower() == "kannada":
                        language = "kn"
                elif language.lower() == "hindi":
                        language = "hi"
                elif language.lower() == "telugu":
                        language = "te"
                elif language.lower() == "tamil":
                        language = "ta"
                elif language.lower() == "english":
                        language = "en"
                s = translator.translate(text, dest = language)
                self.textPad.delete("sel.first", "sel.last")
                self.textPad.insert('insert', s.text)
        except:
                pass

    def keywords_command(self,event):
        C_keywords=["auto","double","int","struct","break","else","long",
                    "switch","case","enum","register","typedef","char","extern",
                    "return","union","const","float","short","unsigned","do",
                    "continue","for","signed","void","default","goto","sizeof",
                    "volatile","if","static","while","printf","scanf","include"]
        for key in C_keywords:
            l=len(key)
            data = self.textPad.get('1.0', 'end-1c')
            ind=[m.start() for m in finditer(key,data)]
            for i in ind:
                corpus=data[:i]
                last=0
                line_no=1
                k=0
                for j in corpus:
                    k+=1
                    if(j=='\n'):
                        line_no+=1
                        last=k
                st=str(line_no)+'.'+str(i-last)
                end=str(line_no)+'.'+str(i-last+l)
                self.textPad.tag_add('kw',st,end)

    def comparedoc_command(self,*args):
        cmpfile = askopenfile(mode='rb',title='Select a file to compare with')
        if cmpfile != None:
            contents = cmpfile.read()
            cmpfile.close()
            data = self.textPad.get('1.0', 'end-1c')
            line=[x for x in contents.split("\n")]
            line1=[x for x in data.split("\n")]
            num=min(len(line),len(line1))
            x=1
            for i in range(num):
                s=str(line[i])
                s1=str(line1[i])
                s=sub(r'\s','',s)
                s1=sub(r'\s','',s1)
                if(s==s1):
                    xy=str(x)+'.0'
                    xy1=str(x)+'.54'
                    self.textPad.tag_add('sel',xy,xy1)
                x+=1

    def keep_indent(self,event):
        try:
            if self.brace_count != 0:
                text = self.brace_count*"	"
                self.textPad.insert('insert', text)
        except:
            pass

    brace_count = 0    
    def auto_indent(self,event):
        try:
            if event.char == '{':
                self.brace_count += 1
                text = "\n"+(self.brace_count*"	")		
                self.textPad.insert('insert', text)
            if event.char == '}':
                self.brace_count -= 1
                text = "\n"+(self.brace_count*"	")
                self.textPad.insert('insert', text)
        except:
                pass

    def comment_command(self,event):
        data = self.textPad.get('1.0', 'end-1c')
        search="\/\*"
        ind=[m.start() for m in finditer(search,data)]
        for i in ind:
            corpus=data[:i]
            last=0
            line_no=1
            k=0
            for j in corpus:
                k+=1
                if(j=='\n'):
                    line_no+=1
                    last=k
            st=str(line_no)+'.'+str(i-last)
            find=data[i+2:]
            flag=0
            if("*/" in find):
                la=(find.index("*/"))+1
                last1=0
                k=0
                for j in range(la):
                    k+=1
                    if(find[j]=='\n'):
                        flag=1
                        line_no+=1
                        last1=k
                if(flag==0):
                    end=str(line_no)+'.'+str(la+i-last+3)
                else:
                    end=str(line_no)+'.'+str(la-last1+1)
            else:
                end='end-1c'
            self.textPad.tag_add('com',st,end)

        data = self.textPad.get('1.0', 'end-1c')    
        ind1=[m.start() for m in finditer("//",data)]
        for i in ind1:
            corpus=data[:i]
            last=0
            line_no=1
            k=0
            for j in corpus:
                k+=1
                if(j=='\n'):
                    line_no+=1
                    last=k
            st=str(line_no)+'.'+str(i-last)
            end=str(line_no)+'.100'
            self.textPad.tag_add('com',st,end)

    def string_command(self,event):
        data = self.textPad.get('1.0', 'end-1c')
        search="\""
        ind=[m.start() for m in finditer(search,data)]
        bool=0
        for i in ind:
            bool+=1
            if(bool%2==0):
                continue
            corpus=data[:i]
            last=0
            line_no=1
            k=0
            for j in corpus:
                k+=1
                if(j=='\n'):
                    line_no+=1
                    last=k
            st=str(line_no)+'.'+str(i-last)
            find=data[i+1:]
            flag=0
            if("\"" in find):
                la=(find.index("\""))
                last1=0
                k=0
                for j in range(la):
                    k+=1
                    if(find[j]=='\n'):
                        flag=1
                        line_no+=1
                        last1=k
                if(flag==0):
                    end=str(line_no)+'.'+str(la+i-last+2)
                else:
                    end=str(line_no)+'.'+str(la-last1+1)
            else:
                end='end-1c'
            self.textPad.tag_add('str',st,end)
            
    def bold_command(self,*args):
        current_tags = self.textPad.tag_names()
        bold = Font(self.textPad, self.textPad.cget("font"))
        bold.config(weight="bold")
        self.textPad.tag_config("bld", font=bold)
        if "bld" in current_tags:
                self.textPad.tag_delete("bld", '1.0', 'end-1c')
        else:
                self.textPad.tag_add("bld", '1.0', 'end-1c') 	
                
    def italic_command(self,*args):
        current_tags = self.textPad.tag_names()
        italics = Font(self.textPad, self.textPad.cget("font"))
        italics.config(slant="italic")
        self.textPad.tag_config("ita", font=italics)
        if "ita" in current_tags:
                self.textPad.tag_delete("ita", '1.0', 'end-1c')
        else:
                self.textPad.tag_add("ita", '1.0', 'end-1c')

    def underline_command(self,*args):
        current_tags = self.textPad.tag_names()
        underline = Font(self.textPad, self.textPad.cget("font"))
        underline.config(underline=True)
        self.textPad.tag_config("und", font=underline)
        if "und" in current_tags:
                self.textPad.tag_delete("und", '1.0', 'end-1c')
        else:
                self.textPad.tag_add("und", '1.0', 'end-1c')
                
    def bolditalic_command(self,*args):
        current_tags = self.textPad.tag_names()
        bold_italic = Font(self.textPad, self.textPad.cget("font"))
        bold_italic.config(weight="bold",slant="italic")
        self.textPad.tag_config("bldita", font=bold_italic)
        if "bldita" in current_tags:
                self.textPad.tag_delete("bldita", '1.0', 'end-1c')
        else:
                self.textPad.tag_add("bldita", '1.0', 'end-1c')
           
    def font_command(self,*args):
        try:
                font_specs = askstring("Font", "Font Style-Font Size")
                font_specs = font_specs.split('-')
                new_font = Font(self.textPad, self.textPad.cget("font"))
                new_font.config(family=font_specs[0], size=font_specs[1])
                self.textPad.tag_config("newfont", font=new_font)
                self.textPad.tag_add("newfont", '1.0', 'end-1c')
        except:
                pass
class editor:
	def __init__(self,rt):
		if rt==None:
			self.t=Tk()
		else:
			self.t=Toplevel(rt)
		self.t.title("汇编器")#("汇编器 %d"%len(t1))
		self.t.geometry("550x600")  
		self.bar=Menu(rt)
		
		self.filem=Menu(self.bar, tearoff=0)
		self.filem.add_command(label="打开",command=self.openfile)
		#self.filem.add_command(label="新建",command=neweditor)
		self.filem.add_command(label="保存",command=self.savefile)
		#self.filem.add_command(label="关闭",command=self.close)
		self.filem.add_separator()
		self.filem.add_command(label="退出",command=die)
		
		self.compilem=Menu(self.bar, tearoff=0)
		self.compilem.add_command(label="编译生成Bin文件",command=self.compile)

		self.bar.add_cascade(label="文件",menu=self.filem)
		self.bar.add_cascade(label="编译",menu=self.compilem)
		self.t.config(menu=self.bar)
		
		self.f=Frame(self.t,width=512)
		self.f.pack(expand=1,fill=BOTH)
		
		self.st=ScrolledText(self.f,background="white", font=('courier', 20, 'normal'))
		self.st.pack(side=LEFT,fill=BOTH,expand=1)
	
	def close(self):
		self.t.destroy()
	
	def openfile(self):
		p1=END
		oname=askopenfilename(filetypes=[("Python file","*.txt")])
		if oname:
			for line in fileinput.input(oname):
				self.st.insert(p1,line)
			self.t.title(oname)
	
	def savefile(self):
		self.savefileData(self.st.get(1.0,END))

	def savefileData(self, data):
		sname=asksaveasfilename(filetypes=[("Python file","*.txt")])
		if sname:
			ofp=open(sname,"wb")
			ofp.write(data)
			ofp.flush()
			ofp.close()
			self.t.title(sname)

	def compile(self):
		binCodeList = complieCode(self.st.get(1.0,END))
		if binCodeList != None:
			dataList = ["v2.0 raw"]
			lineCount = (len(binCodeList)+15) / 16
			for x in xrange(0,lineCount):
				lineDataList = []
				for y in xrange(16*x, 16*(x+1)):
					if y >= len(binCodeList):
						break
					lineDataList.append("%X" % binCodeList[y])
				dataList.append(' '.join(lineDataList))
			data = '\n'.join(dataList)
			self.savefileData(data)
Ejemplo n.º 13
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()
Ejemplo n.º 14
0
class MainWnd:
    def __init__(self, parent):
        self.search_str = StringVar()
        self.parent = parent

        root.protocol("WM_DELETE_WINDOW", self.ask_quit)

        self.parent.title("snippets")
        self.parent.configure(padx=10, pady=10)
        self.parent.minsize(630, 480)
        self.create_widgets()

        db_path = os.path.join(abspath(dirname(__file__)), "snip.db")
        db_exists = os.path.isfile(db_path)
        self.connection = sqlite3.connect(db_path)
        self.connection.row_factory = dict_factory
        self.cursor = self.connection.cursor()

        if not db_exists:
            self.cursor.execute('create table snippet (caption, content)')

        self.fill_list()
        self.snip_content.focus_set()

    def ask_quit(self):
        if tkMessageBox.askokcancel("Quit", "You want to quit now?"):
            self.parent.destroy()

    def __del__(self):
        self.connection.close()

    def create_widgets(self):
        self.search_box = Entry(self.parent, textvariable=self.search_str)
        self.search_str.set("New snippet")
        self.search_box.pack(fill=X)

        self.toolbar_f = Frame(self.parent, pady=5)
        self.toolbar_f.pack(fill=X)

        self.newbtn = Button(self.toolbar_f, text="New", command=self.on_new)
        self.newbtn.pack(side=LEFT)

        self.savebtn = Button(self.toolbar_f,
                              text="Save",
                              command=self.on_save)
        self.savebtn.pack(side=LEFT)

        self.updatebtn = Button(self.toolbar_f,
                                text="Update",
                                command=self.on_update)
        self.updatebtn.pack(side=LEFT)

        self.delbtn = Button(self.toolbar_f,
                             text="Delete",
                             command=self.on_delete)
        self.delbtn.pack(side=LEFT)

        self.copybtn = Button(self.toolbar_f,
                              text="Copy to clipboard",
                              command=self.on_copy)
        self.copybtn.pack(side=LEFT)

        self.quitbtn = Button(self.toolbar_f,
                              text="Quit",
                              command=self.on_quit)
        self.quitbtn.pack(side=LEFT)

        self.pwin = PanedWindow(self.parent, showhandle=True)
        self.pwin.pack(fill=BOTH, expand=1)

        self.list_f = Frame(self.pwin)
        self.list_sb = Scrollbar(self.list_f, orient=VERTICAL)
        self.snip_list = Listbox(self.list_f, yscrollcommand=self.list_sb.set)
        self.list_sb.config(command=self.snip_list.yview)
        self.snip_list.bind('<ButtonRelease-1>', self.on_snippet_selected)
        self.snip_list.pack(side=LEFT, fill=BOTH, expand=1)
        self.list_sb.pack(side=RIGHT, fill=Y)
        self.pwin.add(self.list_f)
        self.pwin.paneconfigure(self.list_f, minsize=177)

        self.snippetFont = Font(family="courier", size=11, weight=NORMAL)
        self.snip_content = ScrolledText(self.pwin,
                                         height=20,
                                         width=40,
                                         padx=5,
                                         pady=5,
                                         font=self.snippetFont)
        self.pwin.add(self.snip_content)

    # noinspection PyTypeChecker
    def fill_list(self):
        self.snip_list.delete(0, END)
        self.cursor.execute('select * from snippet')
        for r in self.cursor.fetchall():
            self.snip_list.insert(END, r['caption'])

    def on_new(self):
        self.search_str.set("")
        self.snip_content.delete(1.0, END)

    def on_save(self):
        self.cursor.execute(
            'insert into snippet (caption,content) values (?,?)', (
                self.search_str.get(),
                self.snip_content.get(1.0, END),
            ))
        self.connection.commit()
        self.fill_list()

    def on_update(self):
        self.cursor.execute(
            'update snippet set content=? where caption=?',
            (self.snip_content.get(1.0, END), self.search_str.get()))
        self.connection.commit()

    def on_delete(self):
        index = self.snip_list.curselection()[0]
        seltext = self.snip_list.get(index)
        self.cursor.execute('delete from snippet where caption=?', (seltext, ))
        self.connection.commit()
        self.snip_list.delete(ANCHOR)
        self.on_new()

    def on_copy(self):
        self.parent.clipboard_clear()
        self.parent.clipboard_append(self.snip_content.get(1.0, END))

    def on_quit(self):
        self.parent.destroy()

    # noinspection PyTypeChecker
    def on_snippet_selected(self, _):
        try:
            index = self.snip_list.curselection()[0]
        except IndexError:
            return
        selected_text = self.snip_list.get(index)
        self.snip_content.delete(1.0, END)
        self.cursor.execute('select * from snippet where caption=?',
                            (selected_text, ))
        r = self.cursor.fetchone()
        if r['caption']:
            self.search_str.set(r['caption'])
        if r['content']:
            self.snip_content.insert(INSERT, r['content'])
        self.snip_content.focus_set()
Ejemplo n.º 15
0
class Example(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)

        self.master = master
        self.initUI()

    def initUI(self):
        #self.topMessage = StringVar()

        self.master.title("ZDRa Interface")
        self.pack(fill=BOTH, expand=1, side=LEFT)

        m1 = PanedWindow(self.master, width=750)
        m1.pack(fill=BOTH, expand=1)

        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)
        zcgaMenu = Menu(menubar)
        zdraMenu = Menu(menubar)
        gpsaMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        zcgaMenu.add_command(label="ZCGa Check", command=self.zcgacheck)
        zdraMenu.add_command(label="ZDRa Check", command=self.zdracheck)
        #zdraMenu.add_command(label = "Totalise Spec", command=self.totalisespec)
        #zdraMenu.add_command(label = "Add Refinements")
        gpsaMenu.add_command(label="Proof Skeleton",
                             command=self.createskeleton)
        gpsaMenu.add_command(label="ProofPower-Z Skeleton",
                             command=self.createppgpsa)
        gpsaMenu.add_command(label="Isabelle Skeleton",
                             command=self.createIsaPS)
        gpsaMenu.add_command(label="FillInIsaSkeleton", command=self.fillInIsa)
        menubar.add_cascade(label="File", menu=fileMenu)
        menubar.add_cascade(label="ZCGa", menu=zcgaMenu)
        menubar.add_cascade(label="ZDRa", menu=zdraMenu)
        menubar.add_cascade(label="GPSa", menu=gpsaMenu)

        self.txt = Text(self, yscrollcommand=scrollbar.set)
        self.txt.pack(fill=BOTH, expand=1)

        self.m2 = PanedWindow(m1, orient=VERTICAL)
        m1.add(self.m2)

        toplabel = Label(self.m2, text="Messages")
        toplabel.pack()

        self.top = ScrolledText(self.m2, wrap=WORD, state=DISABLED)
        self.m2.add(self.top)
        self.top.pack()

        bottomlabel = Label(self.m2, text="User input")
        bottomlabel.pack()

        self.bottom = ScrolledText(self.m2, wrap=WORD)
        self.m2.add(self.bottom)
        self.bottom.pack()

        scrollbar.config(command=self.txt.yview)

        self.txt.insert(
            END, "Please choose a specification by clicking on file then open")

        b = Button(self.m2, text="Submit Message", command=self.submitbutton)
        b.pack()

        self.file_opt = options = {}
        options['defaultextension'] = '.thy'
        options['filetypes'] = [('thy files', '.thy'), ('all files', '.*')]

        #self.topMessage.set("Please pick a specification from the top left")

    def totalisespec(self):
        self.gpsalocation = totalise.findgpsa(self.fl)
        if os.path.isfile(self.gpsalocation):
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END, "Found Specifications")
            self.top.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)

    def zdracheck(self):
        zdracheck.totalcheck(self.fl)
        #self.thedepgraph = zdracheck.creatdepgraphplot(self.fl)
        #self.thegoto = zdracheck.createplot(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, zdracheck.printoutput())
        self.top.config(state=DISABLED)
        self.depbutton = Button(self.m2,
                                text="Show Dependency",
                                command=self.showDependency)
        self.depbutton.pack()
        self.gotobutton = Button(self.m2,
                                 text="Show GoTo",
                                 command=self.showGoTo)
        self.gotobutton.pack()

    def zcgacheck(self):
        zcga.specCorrect(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, zcga.printoutput())
        self.top.config(state=DISABLED)

    def showGoTo(self):
        self.goto_location = totalise.find_goto_name(self.fl)
        gotoWindow = Toplevel()
        gotoWindow.title("GoTo Graph")
        canvas = Canvas(gotoWindow, width=600, height=600)
        canvas.pack()
        #photoimage = ImageTk.PhotoImage(file=self.goto_location)
        # canvas.create_image(300, 300, image=photoimage)
        gotoWindow.pack()
        #zdracheck.showplot(self.thegoto)

    def showDependency(self):
        self_dep_location = totalise.find_dp_name(self.fl)
        gotoWindow = Toplevel()
        gotoWindow.title("Dep Graph")
        canvas = Canvas(gotoWindow, width=600, height=600)
        canvas.pack()
        #   photoimage = ImageTk.PhotoImage(file=self_dep_location)
        # canvas.create_image(300, 300, image=photoimage)
        gotoWindow.pack()
        #zdracheck.showplot(self.thedepgraph)

    def showgpsa(self):
        self.gpsalocation = totalise.findgpsa(self.fl)
        if os.path.isfile(self.gpsalocation):
            gpsawindow = Toplevel()
            gpsawindow.title("ProofPower Skeleton")
            gpsaspec = ScrolledText(gpsawindow, wrap=WORD)
            gpsaspec.pack()
            gpsaspecif = self.readFile(self.gpsalocation)
            gpsaspec.config(state=NORMAL)
            gpsaspec.insert(END, gpsaspecif)
            gpsaspec.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)

    def showIsaSkel(self):
        self.Isalocation = totalise.findisagpsa(self.fl)
        if os.path.isfile(self.Isalocation):
            isawindow = Toplevel()
            isawindow.title("Isabelle Skeleton")
            isaspec = ScrolledText(isawindow, wrap=WORD)
            isaspec.pack()
            isaspecif = self.readFile(self.Isalocation)
            isaspec.config(state=NORMAL)
            isaspec.insert(END, isaspecif)
            isaspec.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(
                END,
                "Please convert specification into Isabelle Skeleton first")
            self.top.config(state=DISABLED)

    def fillInIsa(self):
        self.Isalocation = totalise.findisagpsa(self.fl)
        if os.path.isfile(self.Isalocation):
            if ('\\usepackage{zmathlang}' in open(
                    self.fl).read()) or ('\\usepackage{zmathlang}' in open(
                        self.fl).read()):
                self.Isalocation = totalise.findisagpsa(self.fl)
                zdra.x.fillinIsa(self.fl, self.Isalocation)
                zdra.x.fillinIsa(self.fl, self.Isalocation)
                zdra.x.fillNames(self.Isalocation)
                self.top.config(state=NORMAL)
                self.top.delete(1.0, END)
                self.top.insert(END,
                                "Isabelle Skeleton successfully filled in ")
                self.top.config(state=DISABLED)
            else:
                self.top.config(state=NORMAL)
                self.top.delete(1.0, END)
                self.top.insert(END, "Please select your isabelle skeleton:")
                self.top.config(state=DISABLED)
                filename = tkFileDialog.askopenfilename(**self.file_opt)
                zdra.x.fillinIsa(self.fl, filename)
                zdra.x.fillinIsa(self.fl, filename)
                zdra.x.fillNames(filename)
                self.top.config(state=NORMAL)
                self.top.delete(1.0, END)
                self.top.insert(END,
                                "Isabelle Skeleton successfully filled in ")
                self.top.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(
                END,
                "Please convert specification into Isabelle Skeleton first")
            self.top.config(state=DISABLED)

    def askopenfilename(self):
        filename = tkFileDialog.askopenfilename(**self.file_opt)
        if filename:
            print filename

    def createppgpsa(self):
        zdra.createPPZskel(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, "ProofPower-Z Skeleton Created")
        self.top.config(state=DISABLED)
        self.gpsabutton = Button(self.m2,
                                 text="Show PP Skeleton",
                                 command=self.showgpsa)
        self.gpsabutton.pack()

    def createIsaPS(self):
        zdra.createIsaskel(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, "Isabelle Skeleton Created")
        self.top.config(state=DISABLED)
        self.gpsabutton = Button(self.m2,
                                 text="Show Isabelle Skeleton",
                                 command=self.showIsaSkel)
        self.gpsabutton.pack()

    def showskeleton(self):
        self.skel_location = zdracheck.findskeleton(self.fl)
        if os.path.isfile(self.skel_location):
            skelwindow = Toplevel()
            skelwindow.title("Generalised Skeleton")
            skelspec = ScrolledText(skelwindow, wrap=WORD)
            skelspec.pack()
            skelspecif = self.readFile(self.skel_location)
            skelspec.insert(END, skelspecif)
            skelspec.config(state=DISABLED)

        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)

    def createskeleton(self):
        if zdracheck.isthereanyloops() == False:
            zdracheck.createskeleton(self.fl)
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END, "Skeleton Created")
            self.top.config(state=DISABLED)
            self.skelbutton = Button(self.m2,
                                     text="Show Skeleton",
                                     command=self.showskeleton)
            self.skelbutton.pack()
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Loops in reasoning \nCan not create Skeleton")
            self.top.config(state=DISABLED)

    def submitbutton(self):
        print self.bottom.get("1.0", "end-1c")

    def onOpen(self):
        ftypes = [('Tex files', '*.tex'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        self.fl = dlg.show()

        if self.fl != '':
            self.txt.delete(1.0, END)
            self.text = self.readFile(self.fl)
            self.txt.insert(END, self.text)
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)

    def readFile(self, filename):
        f = open(filename, "r")
        text = f.read()
        return text
Ejemplo n.º 16
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()
Ejemplo n.º 17
0
class Editor:
    def __init__(self):
        # init main window of GUI
        self.root = Tk()
        self.root.title('Text Editor - Brian Dinh')
        self.root.minsize(width=800, height = 800)
        self.root.pack_propagate(0)
        self.root.option_add('*tearOff', False)
        # init text box (used as the basis of the text editor)
        self.textBox = ScrolledText(self.root, height=100, relief=SUNKEN, undo=1)
        self.textBox.pack(side=TOP, fill=BOTH)
        # init top menu toolbar elements
        self.menu = Menu(self.root, relief=RAISED)
        self.root.config(menu=self.menu)
        self.fileMenu = Menu(self.menu)
        self.fileMenu.add_command(label='New', command=self.newFile, accelerator='Ctrl+N')
        self.fileMenu.add_command(label='Open', command=self.openFile, accelerator='Ctrl+O')
        self.fileMenu.add_command(label='Save', command=self.saveFile, accelerator='Ctrl+S')
        self.fileMenu.add_command(label='Save As', command=self.saveAsFile)
        self.fileMenu.add_separator()
        self.fileMenu.add_command(label='Exit', command=self.root.destroy)
        self.editMenu = Menu(self.menu)
        self.editMenu.add_command(label='Undo', command=self.textBox.edit_undo, accelerator='Ctrl+Z')
        self.editMenu.add_separator()
        self.editMenu.add_command(label='Cut', command=self.cut, accelerator='Ctrl+X')
        self.editMenu.add_command(label='Copy', command=self.copy, accelerator='Ctrl+C')
        self.editMenu.add_command(label='Paste', command=self.paste, accelerator='Ctrl+V')
        self.editMenu.add_separator()
        self.editMenu.add_command(label='Select All', command=self.selectAll, accelerator='Ctrl+A')
        self.menu.add_cascade(label='File', menu=self.fileMenu)
        self.menu.add_cascade(label='Edit', menu=self.editMenu)
        # key binds - missing undo because Tkinter has its own built in
        # don't need keybinds for ctrl x,c,v - os handles it, just use clipboard contents
        self.textBox.bind_all('<Control-n>', self.newFile)
        self.textBox.bind_all('<Control-o>', self.openFile)
        self.textBox.bind_all('<Control-s>', self.saveFile)
        self.textBox.bind_all('<Control-a>', self.selectAll)
        # variables
        self.fileName = ''
        
    def runGUI(self):
        self.root.mainloop()

    def updateTitleBar(self):
        self.root.title('Text Editor - ' + self.fileName)

    def openFile(self, event=None):
        fname = tkFileDialog.askopenfilename()
        if fname: # prevent file opener from overwriting existing
            self.fileName = fname
            contents = self.readFile(self.fileName)
            self.textBox.delete(1.0, END)
            self.textBox.insert(INSERT, contents)
            self.updateTitleBar()

    def readFile(self, fileName):
        f = open(fileName, 'r')
        contents = f.read()
        f.close()
        return contents

    def newFile(self, event=None):
        self.textBox.delete(1.0, END)
        self.fileName = 'New Text Document'
        self.updateTitleBar()

    def saveFile(self, event=None):
        contents = self.textBox.get(1.0, END)
        if self.fileName:
            f = open(self.fileName, 'w')
            f.write(self.textBox.get(1.0, END))
            f.close()
        else:
            self.saveAsFile()

    def saveAsFile(self):
        contents = self.textBox.get(1.0, END)
        fname = tkFileDialog.asksaveasfilename()
        if fname:
            self.fileName = fname
            f = open(self.fileName, 'w')
            f.write(self.textBox.get(1.0, END))
            f.close()
            self.updateTitleBar()

    def selectAll(self, event=None):
        self.textBox.tag_add(SEL, 1.0, END)
        self.textBox.mark_set(INSERT, 1.0)
        self.textBox.see(INSERT)
        return 'break'

    def copy(self, event=None):
        self.textBox.clipboard_clear()
        self.textBox.clipboard_append(self.textBox.get('sel.first', 'sel.last'))

    def cut(self, event=None):
        self.copy()
        self.textBox.delete('sel.first', 'sel.last')
    
    def paste(self, event=None):
        self.textBox.insert(INSERT, self.textBox.selection_get(selection='CLIPBOARD'))
Ejemplo n.º 18
0
class Textee:
    def __init__(self, master):
        self.master = master
        self.theme = 'dark' # the startup will always be opposite
        self.options = TexteeOptions()
        self.status_bar = TexteeStatusBar(master)
        self.create_menu(master)
        self.create_ui(master)
        self.set_bindings(master)
        self.file = None
        self.find_text = ''
        self.font_dialog = None
        self.find_and_replace_dialog = None
        self.windows = []
        
    def create_menu(self, master):
        self.menu = Menu(master)
        master.config(menu=self.menu)
        
        filemenu = Menu(self.menu)
        self.menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=self.new_file)
        filemenu.add_command(label="Open...", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_file)
        filemenu.add_command(label="Save As", command=lambda: self.save_file(save_as=True))
        filemenu.add_separator()
        filemenu.add_command(label="New window", command=self.new_window)
        filemenu.add_separator()
        filemenu.add_command(label="Print", command=self.printer)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.exit)

        editmenu = Menu(self.menu)
        self.menu.add_cascade(label='Edit', menu=editmenu)
        editmenu.add_command(label='Copy', command=lambda: event_generate(self.editor, 'Copy'))
        editmenu.add_command(label='Paste', command=lambda: event_generate(self.editor, 'Paste'))
        editmenu.add_command(label='Undo', command=lambda: event_generate(self.editor, 'Undo'))
        editmenu.add_separator()
        editmenu.add_command(label='Goto', command=self.goto_line) # need to develop custom find with regex
        editmenu.add_command(label='Find', command=self.find) # need to develop custom find with regex
        editmenu.add_command(label='Find & Replace', command=self.find_and_replace) # need to test the replace logic in separate playground
        editmenu.add_separator()
        editmenu.add_command(label='Check spelling', command=self.spell_check) # need to see how to use system's grammer check.. if not possible remove it.

        formatmenu = Menu(self.menu)
        self.menu.add_cascade(label='Format', menu=formatmenu)
        formatmenu.add_command(label='Font', command=self.select_font) # pop-up to select system fonts
        formatmenu.add_checkbutton(label='Wrap', onvalue=True, offvalue=False, variable=self.options.wrap, command=self.toggle_wrap)
        
        viewmenu = Menu(self.menu)
        self.menu.add_cascade(label='View', menu=viewmenu)
        viewmenu.add_checkbutton(label='Status bar', onvalue=True, offvalue=False, variable=self.options.status_bar, command=lambda: self.status_bar.display(self.options.status_bar.get()))
        viewmenu.add_command(label='Toggle theme', command=self.toggle_theme)
        
        helpmenu = Menu(self.menu)
        self.menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About", command=lambda : self.about())

    def create_ui(self, master):
        self.editor = ScrolledText(master, width=100, height=50, highlightthickness=0)
        self.editor.config(undo=True)
        self.editor.pack(expand=YES, fill='both', padx=0, pady=0)
        self.toggle_theme()
        #print_configs(self.editor)
        
        # Create pop-menu for the entire editor.. do some cool stuff with it
        self.editor.popmenu = Menu(self.master, tearoff=0)
        # TODO : later need to do smart copy/paste i.e. selected text copy of entire line copy
        self.editor.popmenu.add_command(label='Copy', command=lambda: event_generate(self.editor, 'Copy'))
        self.editor.popmenu.add_command(label='Paste', command=lambda: event_generate(self.editor, 'Paste'))
        # TODO : disable undo when not available, not sure if its possible. Need to check research later
        self.editor.popmenu.add_command(label='Undo', command=lambda: event_generate(self.editor, 'Undo'))
        self.editor.popmenu.add_separator()
        # TODO : 'share' this will be the best feature in the editor, share the file with the future textee sharing api
        self.editor.popmenu.add_command(label='Share', command=do_nothing)

        # add status bar by default, it can be hidden from menu
        self.status_bar.update_status('Hi there')
        
    def set_bindings(self, master):
        master.bind_class('Text', '<Control-a>', select_all)
        master.bind_class('Text', '<Control-s>', lambda event: self.save_file())
        master.bind_class('Text', '<Control-o>', lambda event: self.open_file())
        master.bind_class('Text', '<Control-n>', lambda event: self.new_file())
        master.bind_class('Text', '<Control-g>', lambda event: self.goto_line())
        master.bind_class('Text', '<Control-f>', lambda event: self.find())
        master.bind_class('Text', '<Control-p>', lambda event: self.printer())
        master.bind_class('Text', '<Control-;>', lambda event: self.find_and_replace()) # this function is only for temporoy use - for dev purpose only

        # editor section bindings only
        self.editor.bind('<Button-2>', self.show_right_click_menu) # for right-click
        self.editor.bind('<Button-3>', self.show_right_click_menu) # for middle-click (scroll press)

        #display the current cursor position
        self.display_current_position()


    def new_file(self):
        self.file = None
        self.editor.delete('1.0', END+'-1c') # clear all the contents

    def open_file(self):
        self.file = tkFileDialog.askopenfilename(parent=self.master,title='Select a file')
        if self.file != None and self.file != '':
            self.editor.delete('1.0', END+'-1c') # clear all the contents
            infile = open(self.file, 'r')
            contents = infile.read()
            self.editor.insert('1.0',contents)
            infile.close()

    def save_file(self, save_as=False):
        data = self.editor.get('1.0', END+'-1c')
        save_as_file = None

        # if saving the file by creation
        if self.file == None or save_as == True:
            save_as_file = tkFileDialog.asksaveasfilename() # attempt to select the filename, the user can select cancel so check agian below

        # the above could result in None if the user cancels the dialog
        if save_as_file:
            self.file = save_as_file

        # final check, as both the above could result in None
        if self.file != None:
            outfile = open(self.file, 'w')
            outfile.write(data)
            outfile.close()

    def goto_line(self):
        lineno = tkSimpleDialog.askinteger('Textee', 'Goto line:')
        if lineno > 0:
            self.editor.mark_set(INSERT, lineno + 0.0) #convert to float
            self.editor.see(INSERT)
        self.editor.focus_set()

    def toggle_theme(self):
        if self.theme == 'light':
            self.editor.config(bg='black', fg='white', insertbackground='white',highlightcolor='black')
            self.editor.frame.config(bg='black')
            # theme for misspelled words
            self.editor.tag_configure("misspelled", foreground="red", underline=True)
            self.theme = 'dark'
        else:
            self.editor.config(bg='white', fg='black', insertbackground='black',highlightcolor='white')
            self.editor.frame.config(bg='white')
            # theme for misspelled words
            self.editor.tag_configure("misspelled", foreground="red", underline=True)
            self.theme = 'light'

    def toggle_wrap(self):
        # self.editor.cget('wrap') # gets the config value
        if not self.options.wrap.get():
            self.editor.config(wrap='none')
        else:
            self.editor.config(wrap='word')

    def find(self):
        find_text = tkSimpleDialog.askstring("Textee", "Enter text to search", initialvalue=self.find_text)
        if find_text:
            if find_text == self.find_text:
                start_pos = self.editor.search(find_text, self.editor.index('insert'), stopindex=END, nocase=True)
            else:
                start_pos = self.editor.search(find_text, '1.0', stopindex=END, nocase=True)
                
            self.find_text = find_text
            if(start_pos):
                end_pos = '%s+%sc' % (start_pos, len(self.find_text))
                self.editor.tag_add(SEL, start_pos, end_pos)
                self.editor.mark_set(INSERT, end_pos) # mark the cursor to end of find text to start editing
                self.editor.see(INSERT) # bing the cursor position in the viewport incase of long text causinng scrollbar
                self.editor.focus_set() # strangely tkinter doesnt return focus after prompt
            else:
                tkMessageBox.showinfo("Textee", "No morw matches found")
        else:
            self.editor.focus_set() # strangely tkinter doesnt return focus after prompt

    def find_and_replace(self):
        #show the custom dialog
        self.find_and_replace_dialog = TexteeFindAndReplaceDialog(self.master)
        if self.find_and_replace_dialog.find_text:
            start_pos = self.editor.search(self.find_and_replace_dialog.find_text, '1.0', stopindex=END, nocase=True)
            # lazy recursive replace for all the matched elements, no need to parse whole dataset again and again
            while start_pos:
                self.editor.delete(start_pos, '%s+%sc' % (start_pos, len(self.find_and_replace_dialog.find_text)))
                self.editor.insert(start_pos, self.find_and_replace_dialog.replace_with)
                # break after first replace if replace all flag is off
                if not self.find_and_replace_dialog.replace_all:
                    break
                start_pos = self.editor.search(self.find_and_replace_dialog.find_text, '%s+%sc' % (start_pos, len(self.find_and_replace_dialog.replace_with)), stopindex=END, nocase=True)


    def select_font(self):
        self.font_dialog = TexteeFontDialog(self.master)
        fs = 12 # default size for any font selected

        if self.font_dialog.selected_font_family:
            ff = self.font_dialog.selected_font_family
        
        if self.font_dialog.selected_font_size:
            fs = self.font_dialog.selected_font_size

        print ff, fs, " - font properties"

        if ff and fs > 0:
            self.default_font = tkFont.Font(self.master, family=ff, size=fs)
            self.editor.config(font=self.default_font)

    def show_right_click_menu(self, event):
        print 'going to display popmenu at', event.x_root, event.y_root
        try:
            self.editor.popmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            # TODO: not sure why we need this, pasting it from the documentation. Later check to remove it
            self.editor.popmenu.grab_release()

    def spell_check(self):
        # check if the dictonary exists in the system (only mac and linux have it at this location)
        # TODO: to check on windows how to do?
        print "inside the spell check"
        if not os.path.exists('/usr/share/dict/words'):
            return

        with open('/usr/share/dict/words', 'r') as words_file:
            system_words = words_file.read().split('\n') 
            current_file_lines = self.editor.get('1.0', END+'-1c').split('\n') 

            for lineno, current_line in enumerate(current_file_lines):
                current_line_words = re.split('\W', current_line)
                columnposition = 0 # this is to ignore the white space with which we split above, the marking of the invalid word should be be without the space
                for word in current_line_words:
                    start_index = '%s.%s' % (lineno+1, columnposition)
                    end_index = '%s+%dc' % (start_index, len(word))
                    if word in system_words:
                        self.editor.tag_remove('misspelled', start_index, end_index)
                    else:
                        self.editor.tag_add('misspelled', start_index, end_index)
                    columnposition += len(word)+1 # take into account the space
     
    def display_current_position(self):
        cursor_position =  self.editor.index("insert").replace('.', ',')
        self.status_bar.update_status(cursor_position)
        self.master.after(self.status_bar.update_interval, self.display_current_position)

    def printer(self):
        if not os.path.exists('/usr/bin/lpr'):
            tkMessageBox.showerror('Printing is not supported with your operating system')
            return
        lpr = subprocess.Popen('/usr/bin/lpr', stdin=subprocess.PIPE)
        text = self.editor.get('1.0', END+'-1c')
        lpr.stdin.write(text)
        lpr.stdin.close()

    def new_window(self):
        #allow multiple windows to be opened
        root = Tkinter.Tk(className=" Textee")
        root.title("Textee - A Stupid Text Editor")
        app = Textee(root)
        self.windows.append(app)
        root.mainloop()
        

    def about(self):
        tkMessageBox.showinfo("About", "Textee - A stupid text editor")

    def exit(self, master):
        if tkMessageBox.askokcancel("Quit", "Are you sure?"):
            master.destroy()
Ejemplo n.º 19
0
class diary(Frame):

 def __init__(self,rt):
    if rt == None:
      self.t=Tk()    #创建顶层窗口t
    else:
      self.t=Toplevel(rt) #使用toplevel窗口模式
    self.t.title("窗口- %d"%len(t1))
    Frame.__init__(self,rt)
    self.pack(fill=BOTH, expand=1)
    


    '''定义按钮'''
    '''Possible values are specified as compass directions:
    "n" (north, or top edge), "ne", (north-east, or top right corner), 
    "e", "se", "s", "sw", "w", "nw" or "center".
    Layout布局
    pack side :It can be top, bottom, left and right. The default is top
    color: color names (e.g. "red") or hex RGB codes (e.g. "#ff340a").
    anchor :Pack widget will be anchored to specific side if the width is less than space is assigned. The valid edges are n,e,w,s(东西南北)
    '''

    self.f=Frame(self,width=512)
    self.f.pack(expand=1,fill=BOTH)
   
    self.st=ScrolledText(self.f,background="beige")
    self.st.tag_configure('bold_italics', font=('Arial', 12, 'bold', 'italic'))
    self.st.tag_configure('big', font=('Verdana', 20, 'bold'))
    self.st.tag_configure('color', foreground='#476042', 
                        font=('Tempus Sans ITC', 12, 'bold'))
    self.st.pack(side=LEFT,fill=BOTH,expand=1)
    
    self.open = Button(self)
    self.open["text"] = "打开文件"
    self.open["fg"] = "Blue"
    self.open["command"] = self.diary_open_txt
    self.open.pack({"side":"left"})
    self.open.pack({"anchor":"nw"})
    
    self.newfile = Button(self)
    self.newfile["text"] = "新建"
    self.newfile["fg"] = "black"
    self.newfile["command"] = neweditor
    self.newfile.pack({"side":"left"})
    self.newfile.pack({"anchor":"nw"})
   
    self.save = Button(self)
    self.save["text"] = "保存"
    self.save["fg"] = "black" 
    self.save["command"] = self.savefile
    self.save.pack({"side":"left"})
    self.save.pack({"anchor":"n"})
    
    self.quit = Button(self)
    self.quit["text"] = "关闭"
    self.quit["fg"] = "red"
    self.quit["command"] = self.close
    self.quit.pack({"side":"left"})
    self.quit.pack({"anchor":"center"})

    self.guan_yu = Button(self)
    self.guan_yu["text"] = "关于"
    self.guan_yu["fg"] = "red"
    self.guan_yu["command"] = lambda:self.about1()
    '''lambda后面跟的是表达式,注意调用函数需要增加()
    可以多试试它,挺不错的'''
    self.guan_yu.pack({"side":"right"})
    self.guan_yu.pack({"anchor":"center"})

    self.contents = StringVar()
    self.ent=Entry(self,textvariable=self.contents)    #http://effbot.org/tkinterbook/entry.htm
    self.ent.pack({"side":"bottom"},expand=1,fill='x')
    self.ent.bind("<Enter>",self.entry_enter)
    
 def entry_enter(self,event):
    entry_text = self.contents.get()
    print entry_text
    self.st.insert(END,entry_text)
    self.ent.delete(0,'end') #输入完成清空输入框信息
    


#定义打开文件函数    
 def diary_open_txt(self):
    p1=END
    oname=askopenfilename(filetypes=[("文本文件","*.txt*")])
    txt_open=codecs.open(oname, 'r', "GB2312")
    txt_read=txt_open.read()
    print txt_read
    if oname:
     for line in txt_read:  #fileinput.input(oname): 更新为
      self.st.insert(p1,line,'color') #调用字体
    
    '''
    if oname:
        for line in fileinput.input(oname):  #fileinput.input(oname): 更新为
         self.st.insert(p1,line)
         '''

    self.t.title(oname)
    txt_open.close()

 
 def savefile(self):
  sname=asksaveasfilename(title="保存为txt",filetypes=[("文本文件","*.txt")])
  if sname:
   ofp=open(sname,"w")
   now = datetime.datetime.now()    #添加时间
   otherStyleTime = now.strftime("%Y-%m-%d %H:%M:%S")
   ofp.write("\n\r")
   ofp.write(u"--- 时间%s --- " % otherStyleTime + "\n")
   ofp.write(self.st.get(1.0,END))

   ofp.flush()  #刷新
   ofp.close()
   self.t.title(sname + u"已保存")
  
 def close(self):
  self.t.destroy() #注意此处销毁当前窗口
  print u"关闭窗口"

 def about1(self):
  tkMessageBox.showinfo("小小记事本","V1.1\n"
  "创建于2015年10月29日\n"
  "作者:robo_one")
  print u"-关于-" *3
Ejemplo n.º 20
0
class MainWnd:
    def __init__(self, parent):
        self.search_str = StringVar()
        self.parent = parent

        root.protocol("WM_DELETE_WINDOW", self.ask_quit)

        self.parent.title("snippets")
        self.parent.configure(padx=10, pady=10)
        self.parent.minsize(630, 480)
        self.create_widgets()

        db_path = os.path.join(abspath(dirname(__file__)), "snip.db")
        db_exists = os.path.isfile(db_path)
        self.connection = sqlite3.connect(db_path)
        self.connection.row_factory = dict_factory
        self.cursor = self.connection.cursor()

        if not db_exists:
            self.cursor.execute('create table snippet (caption, content)')

        self.fill_list()
        self.snip_content.focus_set()

    def ask_quit(self):
        if tkMessageBox.askokcancel("Quit", "You want to quit now?"):
            self.parent.destroy()

    def __del__(self):
        self.connection.close()

    def create_widgets(self):
        self.search_box = Entry(self.parent, textvariable=self.search_str)
        self.search_str.set("New snippet")
        self.search_box.pack(fill=X)

        self.toolbar_f = Frame(self.parent, pady=5)
        self.toolbar_f.pack(fill=X)

        self.newbtn = Button(self.toolbar_f, text="New", command=self.on_new)
        self.newbtn.pack(side=LEFT)

        self.savebtn = Button(self.toolbar_f, text="Save", command=self.on_save)
        self.savebtn.pack(side=LEFT)

        self.updatebtn = Button(self.toolbar_f, text="Update", command=self.on_update)
        self.updatebtn.pack(side=LEFT)

        self.delbtn = Button(self.toolbar_f, text="Delete", command=self.on_delete)
        self.delbtn.pack(side=LEFT)

        self.copybtn = Button(self.toolbar_f, text="Copy to clipboard", command=self.on_copy)
        self.copybtn.pack(side=LEFT)

        self.quitbtn = Button(self.toolbar_f, text="Quit", command=self.on_quit)
        self.quitbtn.pack(side=LEFT)

        self.pwin = PanedWindow(self.parent, showhandle=True)
        self.pwin.pack(fill=BOTH, expand=1)

        self.list_f = Frame(self.pwin)
        self.list_sb = Scrollbar(self.list_f, orient=VERTICAL)
        self.snip_list = Listbox(self.list_f, yscrollcommand=self.list_sb.set)
        self.list_sb.config(command=self.snip_list.yview)
        self.snip_list.bind('<ButtonRelease-1>', self.on_snippet_selected)
        self.snip_list.pack(side=LEFT, fill=BOTH, expand=1)
        self.list_sb.pack(side=RIGHT, fill=Y)
        self.pwin.add(self.list_f)
        self.pwin.paneconfigure(self.list_f, minsize=177)

        self.snippetFont = Font(family="courier", size=11, weight=NORMAL)
        self.snip_content = ScrolledText(self.pwin, height=20, width=40,
                                         padx=5, pady=5,
                                         font=self.snippetFont)
        self.pwin.add(self.snip_content)


    # noinspection PyTypeChecker
    def fill_list(self):
        self.snip_list.delete(0, END)
        self.cursor.execute('select * from snippet')
        for r in self.cursor.fetchall():
            self.snip_list.insert(END, r['caption'])

    def on_new(self):
        self.search_str.set("")
        self.snip_content.delete(1.0, END)

    def on_save(self):
        self.cursor.execute(
            'insert into snippet (caption,content) values (?,?)',
            (self.search_str.get(), self.snip_content.get(1.0, END),))
        self.connection.commit()
        self.fill_list()

    def on_update(self):
        self.cursor.execute(
            'update snippet set content=? where caption=?',
            (self.snip_content.get(1.0, END), self.search_str.get()))
        self.connection.commit()

    def on_delete(self):
        index = self.snip_list.curselection()[0]
        seltext = self.snip_list.get(index)
        self.cursor.execute(
            'delete from snippet where caption=?',
            (seltext,))
        self.connection.commit()
        self.snip_list.delete(ANCHOR)
        self.on_new()

    def on_copy(self):
        self.parent.clipboard_clear()
        self.parent.clipboard_append(self.snip_content.get(1.0, END))

    def on_quit(self):
        self.parent.destroy()

    # noinspection PyTypeChecker
    def on_snippet_selected(self, _):
        try:
            index = self.snip_list.curselection()[0]
        except IndexError:
            return
        selected_text = self.snip_list.get(index)
        self.snip_content.delete(1.0, END)
        self.cursor.execute(
            'select * from snippet where caption=?',
            (selected_text,))
        r = self.cursor.fetchone()
        if r['caption']:
            self.search_str.set(r['caption'])
        if r['content']:
            self.snip_content.insert(INSERT, r['content'])
        self.snip_content.focus_set()
Ejemplo n.º 21
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
Ejemplo n.º 22
0
class GUI:
    queue = []
    client_socket = None
    text = None

    #root = Tkinter.Tk(className=" Collaborative Text Editor")
    #textPad = ScrolledText(root, width=100, height=80)

    def __init__(self, file, socket):
        self.queue = []
        self.client_socket = socket
        self.text = text_file.File()
        self.text.download_from_txt(file)
        root = Tkinter.Tk(className=" Collaborative Text Editor")
        self.textPad = ScrolledText(root, width=100, height=80)
        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        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)
        # Insert given text
        if file:
            f = open(file, 'r')
            self.textPad.insert(END, f.read())
        # Keybord bindings to virtual events
        self.textPad.bind("<Button-1>", self.mouse_button)
        self.textPad.bind("<Control-v>", self.key_disable)
        self.textPad.bind("<Control-c>", self.key_disable)
        self.textPad.bind("<Shift_L>", self.key_shift)
        self.textPad.bind("<Delete>", self.key_disable)
        self.textPad.bind("<Tab>", self.key_disable)
        self.textPad.bind("<Insert>", self.key_disable)
        self.textPad.bind("<Return>", self.key_enter)
        self.textPad.bind("<BackSpace>", self.key_backspace)
        self.textPad.bind("<Key>", self.key_press)
        self.textPad.bind("<KeyRelease>", self.key)
        self.textPad.pack()
        root.bind('<<send_recv>>', self.send_receive)

        def heartbeat():
            while True:
                time.sleep(0.5)
                root.event_generate('<<send_recv>>', when='tail')

        th = Thread(None, heartbeat)
        th.setDaemon(True)
        th.start()

        root.mainloop()

    def send_receive(self, event):
        #print "Good"
        if self.queue:
            self.client_socket.send(self.queue.pop(0))
            print self.queue
        else:
            self.client_socket.send('Nothing')
        triple = self.client_socket.recv(1024)
        triple_list = self.get_triples(triple)
        for triple in triple_list:
            insert = self.text.parse_triple(triple)
            self.text.change(insert[0], insert[1], insert[2])
            if insert[2] == "bs":
                if insert[1] == -1:
                    self.textPad.insert("%d.0" % (insert[0] - 1),
                                        "%d.end" % insert[0],
                                        self.text.rows[insert[0] - 1])
                else:
                    self.textPad.delete(
                        "%d.%d" % (insert[0] + 1, insert[1]),
                        "%d.%d" % (insert[0] + 1, insert[1] + 1))
            elif insert[2] == "ent":
                self.textPad.insert("%d.%d" % (insert[0] + 1, insert[1]), "\n")
            else:
                self.textPad.insert("%d.%d" % (insert[0] + 1, insert[1]),
                                    insert[2])

    def get_triples(self, input_triple):
        output = []
        while "(" in input_triple:
            left_index = input_triple.index("(")
            right_index = input_triple.index(")")
            output.append(input_triple[left_index:right_index + 1])
            input_triple = input_triple[right_index + 1:]
        return output

    #Function raises by Tk events.
    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, root):
        if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
            root.destroy()

    def about_command(self):
        label = tkMessageBox.showinfo(
            "About",
            "Collaborative text editor \n Developed by Bachinskiy A., Shapaval R., \
                                        Shuchorukov M., Tkachuk D. using Tk.tkinter.\n No rights left to reserve :)"
        )

    #Here come all button handlers
    def key_enter(self, event):
        s = self.textPad.index(INSERT)
        self.add_to_queue(s, "ent")

    def key_backspace(self, event):
        s = self.textPad.index(INSERT)
        self.add_to_queue(s, "bs")

    def key_disable(self, event):
        self.textPad.config(state=DISABLED)
        global disableFlag
        disableFlag = True

    def mouse_button(self, event):
        self.textPad.config(state=NORMAL)

    def key_shift(self, event):
        global shiftFlag
        shiftFlag = True

    def key(self, event):
        #print event.keycode
        global disableFlag
        global shiftFlag
        if disableFlag == True:
            #print "disabled"
            if event.keysym != "v":
                disableFlag = False
        else:
            #print event.keycode
            #Shift handling
            if shiftFlag == True:
                s = self.textPad.index(INSERT)
                self.add_to_queue(s)
                shiftFlag = False
            else:
                #Block output for Arrows keys
                if event.keysym == "Down" or event.keysym == "Up" or \
                        event.keysym == "Right" or event.keysym == "Left":
                    print event.keysym
                    return
                #Block output for Ctrl, Shift, BackSpace, Tab, Delete, etc
                if event.keysym == "Alt_L" or event.keysym == "Alt_R" or \
                                event.keysym == "BackSpace" or event.keysym == "Delete" or \
                                event.keysym == "Control_L" or event.keysym == "Control_R" or \
                                event.keysym == "Shift_L" or event.keysym == "Shift_R" or \
                                event.keysym == "Tab" or event.keysym == "Return":
                    print event.keysym
                    return
                self.textPad.config(state=NORMAL)
                s = self.textPad.index(INSERT)
                self.add_to_queue(s)

    def key_press(self, event):
        self.textPad.config(state=DISABLED)
        time.sleep(0.2)
        self.textPad.config(state=NORMAL)

    def add_to_queue(self, s, key=""):
        point_index = s.index(".")
        index1 = int(s[:point_index])
        index2 = int(s[point_index + 1:])
        out = self.textPad.get("%d.%d" % (index1, index2 - 1),
                               "%d.%d" % (index1, index2))
        if key:
            if key == "ent":
                self.queue.append("(%d,%d,%s)" % (index1 - 1, index2, key))
            if key == "bs":
                self.queue.append("(%d,%d,%s)" % (index1 - 1, index2 - 1, key))
        else:
            self.queue.append("(%d,%d,%s)" % (index1 - 1, index2 - 1, out))
        print self.queue
Ejemplo n.º 23
0
class pathPrint(object):
    def loadCode(self):
        newFileName = tkFileDialog.askopenfilename(title="Select robot path code...",filetypes=(("Text files","*.txt"),("All Files","*.*")))
        
        if newFileName: #If string is not empty
            #Load text file
            #f = open(newFileName,'r') #Open Read-only
            self.text.delete("1.0",END)
            self.text.insert(INSERT,newFileName.read())
            f.close()

    def saveCode(self):
        savefile = tkFileDialog.asksaveasfile(title="Save robot path code as...",mode='w',defaultextension=".txt") 
        
        if savefile:
            savefile.write = self.text.get("1.0",END)
            savefile.close()

    def __init__(self,title,textinit):
         
        self.wind = Toplevel() #TOPLEVEL when you have more than one
        self.wind.title(title) 
        self.wind.geometry("400x300")
        self.wi = Canvas(self.wind,bg="white")
        self.wi.pack(expand=YES,fill=BOTH)
        self.text = ScrolledText(master=self.wi, height=30, wrap=WORD)
        self.text.insert(INSERT,textinit)
        self.text.pack()
        #self.textinit = textinit #Get the actual text of the path
        
        menubar = Menu(self.wind)
        self.wind.config(menu=menubar)

        robotmenu = Menu(menubar)
        #robotmenu.add_command(label="Load Code", command=self.loadCode)
        #robotmenu.add_command(label="Save Code", command=self.saveCode)
        menubar.add_cascade(label="File",menu=robotmenu)
        

    def printMap(self):
        value = self.text.get("1.0",END) #Return the current value of the scrollable text field

        #Break it apart into single lines
        
        value = value.split('\n')
        #print value

        #Get rid of blank lines

        script = [[0 for x in range(2)] for y in range(len(value))] #init array to contain data
        
        for x in range(0,len(value)-1):
            
            doesMove = value[x].find('move')
            doesRotate = value[x].find('rotate')

            if doesMove != -1:
                #It's moving
                script[x][0] = 'm'
            elif doesRotate != -1:
                #It's rotating
                script[x][0] = 'r'

            #Get the VALUE
            try:
                script[x][1] = int(re.findall(r'[+-]?\d+(?:\.\d+)?',value[x])[0])
            except:
                script.pop(x)

        print script
      
        return script
class SimpleTextEditor:

    def __init__(self, parent):
        self.parent = parent
        self.textWidget = ScrolledText(parent, width=80, height=50, font=(tkFont.Font(family= "Consolas", size= "12")))
        self.textWidget.pack()

        self.menuBar = tk.Menu(parent, tearoff=0)
        # About Menu
        self.about_menu = tk.Menu(self.menuBar, tearoff= 0)
        self.menuBar.add_cascade(label= "Text Perfect", menu= self.about_menu)
        self.about_menu.add_command(label= "About", command= self.about_command)

        # File Menu
        self.file_menu = tk.Menu(self.menuBar, tearoff = 0)
        self.menuBar.add_cascade(label = "File", menu=self.file_menu)
        self.file_menu.add_command(label="New", command=self.new_command, accelerator="Cmd+N")
        self.parent.bind_all("<Command-n>", self.new_command)
        self.parent.bind_all("<Command-N>", self.new_command)
        self.file_menu.add_command(label="New Tab", command=self.new_tab, accelerator="Cmd+Opt+N")
        self.parent.bind_all("<Command-Option-n>", self.new_tab)
        self.parent.bind_all("<Command-Option-N>", self.new_tab)
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Open", command=self.open_command, accelerator="Cmd+O")
        self.parent.bind_all("<Command-o>", self.open_command)
        self.parent.bind_all("<Command-O>", self.open_command)
        self.file_menu.add_command(label="Save", command=self.save_command, accelerator="Cmd+S")
        self.parent.bind_all("<Command-s>", self.save_command)
        self.parent.bind_all("<Command-S>", self.save_command)
        self.file_menu.add_separator()
        self.file_menu.add_command(label= "Quit", command= self.exit_program, accelerator="Cmd+W")
        self.parent.bind_all("<Command-w>", self.exit_program)
        self.parent.bind_all("<Command-W>", self.exit_program)

        # Edit Menu
        self.edit_menu = tk.Menu(self.menuBar, tearoff=0)
        self.menuBar.add_cascade(label= "Edit", menu= self.edit_menu)
        self.edit_menu.add_command(label = "Cut", command = self.cut_command, accelerator="Cmd+X")
        self.parent.bind_all("<Command-Shift-x>", self.cut_command)
        self.parent.bind_all("<Command-Shift-X>", self.cut_command)
        self.edit_menu.add_command(label = "Copy", command = self.copy_command, accelerator="Cmd+C")
        self.parent.bind_all("<Command-Shift-c>", self.copy_command)
        self.parent.bind_all("<Command-Shift-C>", self.copy_command)
        self.edit_menu.add_command(label = "Paste", command = self.paste_command, accelerator="Cmd+V")
        self.parent.bind_all("<Command-Shift-v>", self.paste_command)
        self.parent.bind_all("<Command-Shift-V>", self.paste_command)
        self.edit_menu.add_separator()
        self.edit_menu.add_command(label= "Find", command= self.find_command)

        parent.config(menu=self.menuBar)
        
##################################################

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

    def save_command(self, event=None):
        file = tkFileDialog.asksaveasfile(mode= 'w')
        if file != None:
            data = self.textWidget.get("1.0", END+'-1c')   #strip trailing \n at EOF
            file.write(data)
            file.close()

    def exit_program(self, event=None):
        if tkMessageBox.askokcancel("Quit", "Are you sure you want to quit?"):
            self.parent.destroy()
     
    #Opens up new text widget correctly but screws up closing the parent window via the menu       
    def new_command(self, event=None):
        win = Toplevel()
        SimpleTextEditor.__init__(self, win)
        
    #Currently under construction    
    def new_tab(self, event=None):
        #self.parent.add(self.textWidget, text="new tab", state='normal')
        new_frame = tk.Frame(self.parent)
        self.parent.add(new_frame, text='new', state='normal')
        
    def cut_command(self, event=None):
        text = self.textWidget.get(SEL_FIRST, SEL_LAST)
        self.textWidget.delete(SEL_FIRST, SEL_LAST)
        self.textWidget.clipboard_clear()
        self.textWidget.clipboard_append(text) 
        
    def copy_command(self, event=None):
        text = self.textWidget.get(SEL_FIRST, SEL_LAST)
        self.textWidget.clipboard_clear()
        self.textWidget.clipboard_append(text)
        
    def paste_command(self, event=None):
        try:
            text = self.textWidget.selection_get(selection= 'CLIPBOARD')
            self.textWidget.insert(INSERT, text)
        except TclError:
            pass
            
    def find_command(self):                  
        # Currently only works for highlighted text and will only find one match to the string, not all of the instances
        # Also does not work with key binding because of askstring hanging window bug :/
        target = askstring('SimpleEditor', 'Search String?')
        if target:
            where = self.textWidget.search(target, INSERT, END)
            if where:
                print where
                pastit = where + ('+%dc' % len(target))
                self.textWidget.tag_add(SEL, where, pastit)
                self.textWidget.mark_set(INSERT, pastit)
                self.textWidget.see(INSERT)
                self.textWidget.focus()       

    def about_command(self):
        label = tkMessageBox.showinfo("About", "A super duper simple text editor. It's now available through github, thanks to Jason!")                


    #dummy function as a place holder while constructing further functionality        
    def dummy_funct(self, event=None):
        print"The life of a function is often very lonely..."
Ejemplo n.º 25
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	
Ejemplo n.º 26
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()
Ejemplo n.º 27
0
class EditorMain(object):
    def __init__(self):
        self.root = tk.Tk(className="PyNestML IDE")
        self.after_id = None

        self.text_frame = tk.Frame(self.root,
                                   width=self.root.winfo_screenwidth(),
                                   height=self.root.winfo_screenheight() *
                                   0.70)
        self.text_frame.pack_propagate(False)
        self.textPad = ScrolledText(self.text_frame,
                                    height=1,
                                    width=1,
                                    undo=True)
        self.textPad.pack(side="top", fill="both", expand=True)
        self.text_frame.pack(side="top", fill="both", expand=True)

        self.line_nr_frame = tk.Frame(self.root,
                                      width=self.root.winfo_screenwidth())
        self.line_nr_frame.pack_propagate(False)
        self.line_nr = tk.Text(self.root,
                               width=self.root.winfo_screenwidth(),
                               height=1)
        self.line_nr.pack(side="top", fill="both", expand=True)
        self.line_nr_frame.pack(side="top", fill="both", expand=True)

        self.console_frame = tk.Frame(self.root,
                                      width=self.root.winfo_screenwidth(),
                                      height=self.root.winfo_screenheight() *
                                      0.20)
        self.console_frame.pack_propagate(False)
        self.console = ScrolledText(self.console_frame, width=1, height=1)
        self.console.pack(side="top", fill="both", expand=True)
        self.console_frame.pack(side="top", fill="both", expand=True)

        self.menu = Menu(root=self.root, text_pad=self.textPad, editor=self)
        self.highlighter = Highlighter(self.textPad, self)

        # insert empty model
        self.textPad.insert('1.0', 'PyNestML             \n')
        self.textPad.insert('2.0', '         Model       \n')
        self.textPad.insert('3.0', '               Editor\n')
        self.textPad.tag_add("l1", "%s.%s" % (1, 0),
                             "%s.%s" % (1, len('PyNestML')))
        self.textPad.tag_add("l2", "%s.%s" % (2, 0),
                             "%s.%s" % (2, len('         Model')))
        self.textPad.tag_add("l3", "%s.%s" % (3, 0),
                             "%s.%s" % (3, len('               Editor')))
        self.textPad.tag_config("l1", background="white", foreground="blue")
        self.textPad.tag_config("l2", background="white", foreground="red")
        self.textPad.tag_config("l3", background="white", foreground="green")
        self.last = self.textPad.get('0.0', tk.END)
        # insert start position of cursor
        self.console.pack(side=tk.BOTTOM)
        self.console.configure(state='disabled')
        self.line_nr.insert('1.0', 'Position: 0:0')
        self.line_nr.configure(state='disabled')
        # bind keys
        self.bind_keys()
        self.root.mainloop()

    def change_button_state(self, active=True):
        if not active:
            self.menu.modelmenu.entryconfig('Check CoCos', state=tk.DISABLED)
            self.menu.modelmenu.entryconfig('Compile Model', state=tk.DISABLED)
        else:
            self.menu.modelmenu.entryconfig('Check CoCos', state=tk.NORMAL)
            self.menu.modelmenu.entryconfig('Compile Model', state=tk.NORMAL)

    def exit_editor(self, _):
        self.menu.exit_command()

    def store_command(self, _):
        self.menu.save_command()

    def check_model(self):
        self.change_button_state(False)
        thread = threading.Thread(target=self.check_model_in_separate_thread)
        thread.start()
        return thread  # returns immediately after the thread starts

    def check_model_in_separate_thread(self):
        self.textPad.configure(state='disabled')
        ModelChecker.check_model_with_cocos(self.textPad.get('0.0', tk.END))
        self.report_findings()
        self.textPad.configure(state='normal')

    def check_syntax_in_separate_thread(self):
        ModelChecker.check_model_syntax(self.textPad.get('0.0', tk.END))
        self.report_findings()

    def check_model_syntax(self, _):
        self.update_line_number()
        # cancel the old job
        if self.after_id is not None:
            self.textPad.after_cancel(self.after_id)

        # create a new job
        self.after_id = self.textPad.after(800, self.do_check_model_syntax)

    def do_check_model_syntax(self):
        if self.textPad.get('0.0', tk.END) != self.last:
            if self.last is None or "".join(
                    self.textPad.get('0.0', tk.END).split()) != "".join(
                        self.last.split()):
                thread = threading.Thread(
                    target=self.check_syntax_in_separate_thread)
                thread.start()
                self.last = self.textPad.get('0.0', tk.END)
                return thread  # returns immediately after the thread starts

    def update_line_number(self):
        self.line_nr.configure(state='normal')
        self.line_nr.delete('1.0', tk.END)
        pos = self.textPad.index(tk.INSERT).split('.')
        self.line_nr.insert('1.0', 'Position: %s:%s' % (pos[0], pos[1]))
        self.line_nr.configure(state='disabled')

    def report_findings(self):
        # print('process complete!')
        self.highlighter.process_report()
        self.change_button_state(True)

    def bind_keys(self):
        # bind the events
        self.textPad.bind('<Control-q>', self.exit_editor)
        self.textPad.bind('<KeyRelease>', self.check_model_syntax)
        self.textPad.bind('<Control-s>', self.store_command)

    def clear_console(self):
        self.console.delete('1.0', tk.END)

    def report(self, text):
        if self.menu.show_syntax_errors_var.get() == 1:
            self.console.configure(state='normal')
            self.console.insert(tk.END, text + '\n')
            self.console.configure(state='disabled')

    def inc_font_size(self):
        f = tkFont.Font(self.textPad, self.textPad.cget('font'))
        self.textPad.configure(font=("Courier", f.configure()['size'] + 1))

    def dec_font_size(self):
        f = tkFont.Font(self.textPad, self.textPad.cget('font'))
        if not f.configure()['size'] - 1 < 4:
            self.textPad.configure(font=("Courier", f.configure()['size'] - 1))
Ejemplo n.º 28
0
class MemoPadFrame( Frame ):

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

        # Modelの初期化
        self.version = (0, 2, 5)
        self.memos = MemoPad()
        self.memos.addObserver(self)

        # change-logger のバインド
        self.changeLogger = ChangeLogger()
        self.memos.addObserver( self.changeLogger )

        # View-Controller の初期化
        self.master.title( 'MemoPad %d.%d.%d' % self.version )
        self.make_listPanel(self)
        self.make_editAria(self)
        self.pack(fill=BOTH)

        # データの復帰
        self.memos.loadImage()


        def bye():
            self.saveMemo()    # 現在編集中のメモをセーブ
            self.memos.saveImage()

            print 'bye'
            self.master.destroy()

        self.master.protocol('WM_DELETE_WINDOW', bye )


    def make_listPanel(self, parent):
        frm = Frame(parent)

        # リストの生成・配置
        def changeTarget(evt):
            try: index = int(self.memoList.curselection()[0])
            except: index = None

            self.saveMemo()
            if index != None: self.selectMemo( index )


        self.memoList = ScrolledListbox(frm,
                                        selectmode=BROWSE,
                                        width=72,
                                        height=7 )
        self.memoList.bind("<ButtonRelease>", changeTarget )
        self.memoList.bind('<B1-Motion>', changeTarget )
        self.memoList.pack(side=LEFT, fill=BOTH)


        # ボタンの作成
        btnfrm = Frame(frm)

        def appendMemo():
            self.saveMemo()
            self.memos.appendMemo()

        Button( btnfrm,
                text='new',
                command=appendMemo ).pack(side=TOP, fill=X)


        def deleteMemo():
            self.saveMemo()
            self.memos.removeMemo()

        Button( btnfrm,
                text='delete',
                command=deleteMemo ).pack(side=TOP, fill=X)


        btnfrm.pack(side=LEFT)

        frm.pack(side=TOP, fill=X)



    def make_editAria(self, parent):
        self.text = ScrolledText( parent )
        self.text.pack(side=TOP, fill=BOTH)

        def updateTitle(evt):
            '''実験コード。まだ
            改行や行末改行の削除に弱いです
            '''
#            print self.text.index('1.end')
#            print self.text.index(INSERT)

            if self.text.index(INSERT).split('.')[0] == '1': # 1行目
                itemnum = self.memos.getSelectedIndex()

                self.memoList.delete(itemnum)
                self.memoList.insert(itemnum,
                             "%s | %s" % (self.memos[itemnum].getDatetime().strftime("%Y-%m-%d %H:%M"),
                                          u'%s%s%s' % ( self.text.get('1.0', INSERT), 
                                                        evt.char.decode('utf_8'),
                                                        self.text.get(INSERT, '1.end'))))
                self.memoList.selection_clear(0,END)
                self.memoList.selection_set(itemnum)
                self.memoList.see(itemnum)


        self.text.bind('<Key>', updateTitle )

        def ime_ctrl_m(evt):
            if evt.keycode == 0:
                self.text.insert( INSERT, evt.char )
        self.text.bind('<Control-Key>',ime_ctrl_m)

    #==================================
    # observer
    #==================================

    def update(self, aspect, obj):
        if aspect == 'saveImage' : return

        # リストの表示 (全更新 or 選択行の変更)
        if aspect == "selectMemo":
            self.selectList()
        elif aspect == "setText":
            self.renderOneLine(self.memos.getSelectedIndex())
        else:
            self.renderList()

        # テキストエリアの表示
        if aspect != "setText":
            self.renderTextArea()

        print "disyplay update (%s)" % aspect



    #==================================
    # rendering
    #==================================

    def renderList(self):
        self.memoList.delete(0, END)
        for memo in self.memos:
            self.memoList.insert(END, 
                                 "%s | %s" % (memo.getDatetime().strftime("%Y-%m-%d %H:%M"),
                                              memo.getTitle()))

        if self.memos.getSelectedItem() != None:
            self.memoList.selection_set( self.memos.getSelectedIndex() )
            self.memoList.see( self.memos.getSelectedIndex() )


    def selectList(self):
        try:
            if int(self.memoList.curselection()[0]) == self.memos.getSelectedIndex():
                return
        except: # そもそも選択が成されていない
            pass

        self.memoList.selection_clear(0,END)
        self.memoList.selection_set( self.memos.getSelectedIndex() )
        self.memoList.see( self.memos.getSelectedIndex() )



    def renderOneLine(self, index ):
        if self.memoList.get(index) == self.memos[index].getTitle(): return

        try: indexbackup = int(self.memoList.curselection()[0])
        except: indexbackup = self.memos.getSelectedIndex()

        self.memoList.delete(index)
        self.memoList.insert(index,
                             "%s | %s" % (self.memos[index].getDatetime().strftime("%Y-%m-%d %H:%M"),
                                          self.memos[index].getTitle()))

        if indexbackup != None:
            self.memoList.selection_clear(0,END)
            self.memoList.selection_set(indexbackup)
            self.memoList.see(indexbackup)



    def renderTextArea(self):
        self.text.delete('1.0', END )
        if self.memos.getSelectedItem() != None:
            self.text.insert(END, self.memos.getSelectedItem().getText())



    #==================================
    # controller-function (VC->M)
    #==================================

    def saveMemo( self, memo=None ):
        if memo == None:
            memo = self.memos.getSelectedItem()
            if memo == None: return

        if memo.getText() == self.text.get('1.0', END)[:-1]: return # 内容が同じ場合はなにもしない

        self.memos.getSelectedItem().setText( self.text.get('1.0', END)[:-1] )
        print '--- save "%s"---' % memo.getTitle()

    def selectMemo( self, index ):
        self.memos.selectMemo( index )
Ejemplo n.º 29
0
class Editor:
    def __init__(self, root):
        self.active_filename = None
        self.filename_label = Label(root, text='No file specified!', fg='purple', font=('times', 18, 'italic'))
        self.filename_label.pack()
        frame = Frame(root)
        frame.pack()
        frame.configure(background='black')
        root.title("Editor")
        # Create a text frame
        self.textPad = ScrolledText(root, width=60, height=30)
        self.textPad.pack()

        # Create an open button
        self.open_button = Button(frame, text='Open', width=15, fg='blue', command=self.open_command)
        self.open_button.pack(padx=5, pady=5, side=LEFT)

        # Create a create button
        self.edit_button = Button(frame, text='Create', width=15, fg='blue', command=self.create_command)
        self.edit_button.pack(padx=5, pady=5, side=LEFT)

        # Create a save button
        self.save_button = Button(frame, text='Save', width=15, fg='blue', command=self.save_command)
        self.save_button.pack(padx=5, pady=5, side=LEFT)

        # Create a close button
        self.close_button = Button(frame, text='Close', width=15, fg='blue', command=self.exit_command)
        self.close_button.pack(padx=5, pady=5, side=LEFT)

    # Rewrite an active file
    def save_command(self):
        if self.active_filename is not None:
            self.filename_label.config(text = 'Editing: ' + basename(self.active_filename))
            a = self.textPad.get('1.0', END)
            f = open(self.active_filename, 'w')
            f.write(a)
            f.close()

    # Exit from tk
    def exit_command(self):
        if tkMessageBox.askokcancel("Quit", "Are you sure?"):
            root.destroy()

    # Open file
    def open_command(self):
            file = tkFileDialog.askopenfile(parent=root, mode='rb', title='Select a file', **FILEOPENOPTIONS)
            if file != None:
                self.active_filename = file.name
                self.filename_label.config(text='Editing: ' + basename(self.active_filename))
                data = file.read()
                self.textPad.delete('1.0', END)
                self.textPad.insert('1.0', data)
                file.close()

    def create_command(self):
        # Create a child window
        self.child = Toplevel(root)
        self.child.title("Create a file")
        self.child.geometry('250x75')
        # Create a label
        Label(self.child, text='Enter a filename', ).grid(row=0, padx=5)

        # Create an entry widget
        entry_filename = Entry(self.child)
        entry_filename.grid(row=0, column=1)

        def get_filename():
            self.active_filename = entry_filename.get()
            if not self.active_filename:
                return
            if '.txt' not in self.active_filename:
                self.active_filename += '.txt'
                self.filename_label.config(text='Editing: ' + basename(self.active_filename))
            self.textPad.delete('1.0', END)
            self.child.destroy()


        # Save a filename button
        Button(self.child, text='Confirm!', command=get_filename).grid(row=1, column=1, sticky=W, pady=5)
Ejemplo n.º 30
0
class mainwindow:
    def __init__(self, master):
        self.master = master
        if os.path.exists("C:\Python27") or os.path.exists("C:\Python36-32"):

            self.frame2 = tk.LabelFrame(
                self.master,
                text="Editor",
                width=800,
                height=self.master.winfo_screenheight(),
                bd=5)
            self.frame3 = tk.LabelFrame(
                self.master,
                text="Output",
                width=self.master.winfo_screenwidth() - 830,
                height=(self.master.winfo_screenheight()) / 2,
                bd=5)
            self.frame2.grid(row=1, column=0, padx=8)
            self.frame2.pack_propagate(0)
            self.frame3.grid(row=1, column=1, sticky='nw')
            self.frame3.pack_propagate(0)
            self.textPad = ScrolledText(self.frame2, width=800, height=1000)
            self.textPad.focus_set()
            self.textPad.bind('<KeyPress>', self.onKeyPress)
            self.textPad.bind('<Control-Key-a>', self.select_all)
            self.textPad.bind('<Control-Key-A>', self.select_all)
            self.outputpad = Text(self.frame3, width=450, height=400)
            self.textPad.pack()
            self.outputpad.pack()
            self.outputpad.configure(state='disabled')
            self.filename = ""
            self.final_data = ""
            self.entry = 0
            self.s = wincl.Dispatch("SAPI.SpVoice")
            self.s.Rate = 1
            global voice
            self.special_char = {
                '(': 'Parenthesis L',
                ')': 'Parenthestis R',
                '[': 'Bracket L',
                ']': 'Bracket R',
                '{': 'Curly Braces L',
                '}': 'Curly Braces R',
                '<': 'Angle Bracket L',
                '>': 'Angle Bracket R',
                ':': 'Colon',
                '!': 'Exclamation Mark',
                '~': 'Tilde',
                '^': 'Caret',
                '-': 'Hyphen',
                ' ': 'Space',
                '|': 'Pipe',
                ';': 'Semicolon',
                '\'': 'Single Quote',
                '"': 'Double Quote',
                '?': 'Question Mark',
                ',': 'Comma',
                '.': 'Period'
            }
            if os.path.exists("C:\Python27\PowerPad"): pass
            else: os.makedirs("C:\Python27\PowerPad")
            os.chdir("C:\\Python27\\PowerPad")
            os.environ["PATH"] += os.pathsep + "C:\Python27\PowerPad"
        else:
            tkMessageBox.showerror("Python Not Found",
                                   "Sorry, no Python available")
            s = wincl.Dispatch("SAPI.SpVoice")
            s.Rate = 1
            s.Speak(
                "python is not installed, Please intall python on your Computer"
            )
            self.master.destroy()

    def speak(self, string):
        self.s.Speak(string)

    def select_all(self, event):
        self.textPad.tag_add(SEL, "1.0", END)
        self.textPad.mark_set(INSERT, "1.0")
        self.textPad.see(INSERT)
        return 'break'

    def outputconf(self):
        self.outputpad.configure(state='normal')
        self.outputpad.insert('end', '>>> Running Your Code\n')
        self.outputpad.configure(state='disabled')

    def alreadysave(self, data, filename):
        self.speak("SAVING " + filename)
        self.saved_file = open(filename, "w+")
        self.saved_file.write(data)
        self.saved_file.close()

    def popup(self):
        self.w = popupWindow(self.master)
        self.w.e.focus_set()
        self.master.wait_window(self.w.top)
        self.filename = self.w.val

    def open_file(self):
        try:
            self.speak("ENTER THE FILE NAME WITHOUT EXTENSION AND PRESS ENTER")
            self.master.bell()
            self.popup()
            file = open(self.filename, "r")
            contents = file.read()
            self.textPad.delete('0.0', 'end')
            self.outputpad.configure(state='normal')
            self.outputpad.delete('0.0', 'end')
            self.outputpad.configure(state='disabled')
            self.textPad.insert('1.0', contents)
            file.close()
            self.final_data = self.textPad.get('1.0', END + '-1c')
            self.textPad.focus_set()
            self.frame2.configure(text=self.filename)
        except IOError:
            pass

    def SaVe(self, data):
        self.final_data = self.data
        if not self.filename:
            self.speak("ENTER THE FILE NAME WITHOUT EXTENSION AND PRESS ENTER")
            self.master.bell()
            self.popup2()
            if str(self.filename) in os.listdir("C:\\Python27\\PowerPad"):
                if self.onreplace() == "yes":
                    self.alreadysave(self.data, self.filename)
                    self.textPad.focus_set()
                else:
                    self.speak("ENTER THE NAME AGAIN")
                    self.popup2()
                    self.SaVe(self.data)
            else:
                self.SaVe(self.filename)
        else:
            self.alreadysave(self.data, self.filename)
        self.textPad.focus_set()
        self.frame2.configure(text=self.filename)

    def popup2(self):
        self.w1 = popupWindow1(self.master)
        self.w1.e1.focus_set()
        self.master.wait_window(self.w1.top1)
        self.filename = self.w1.val1

    def outputgen(self, filename):
        process = subprocess.Popen(["python", filename],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        self.output = process.stdout.readlines()
        self.error = process.stderr.readlines()
        process.wait()
        '''if not 'prompt' in os.environ:
			self.speak("input")
			print("in")'''

        if self.error:
            self.speak("Error")
            self.errorsay(self.error)
        else:
            self.speak("Output")
            self.outputsay(self.output)

    def errorline(self, error):
        s = ""
        for i in error:
            if not "line" in i:
                pass
            else:
                s += i
        x = s.split(",")
        s = ""
        for i in x:
            if not "line" in i:
                pass
            else:
                s += i
        return s

    def errorsay(self, error):
        s = self.errorline(error)
        x = ((error[-1].split(":"))[0]) + " ON THE "
        self.outputpad.configure(state='normal')
        self.outputpad.insert('end', x + s)
        self.outputpad.configure(state='disabled')
        l = s.split(' ')
        errorline = (self.textPad.get('1.0', END +
                                      '-1c').split("\n"))[int(l[-1][0]) - 1]
        self.textPad.mark_set("insert",
                              "%d.%d" % (int(l[-1][0]), len(errorline)))
        self.speak(x)
        self.speak(s)
        for i in errorline:
            if i in self.special_char.keys(): self.speak(self.special_char[i])
            else: self.speak(i)

    def outputsay(self, output):
        self.outputpad.configure(state='normal')
        for i in output:
            self.speak(i)
            self.outputpad.insert('end', i)
        self.outputpad.configure(state='disabled')

    def onexit(self):
        self.speak("PRESS Y TO EXIT AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Exit", "Are You Sure?")

    def onopen(self):
        self.speak(
            "THERE ARE SOME UNSAVED CHANGES DO YOU WANT TO SAVE THE FILE BEFORE OPEN A FILE?"
        )
        self.speak("PRESS Y TO SAVE AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Save and Open", "Are You Sure?")

    def onsave(self):
        self.speak(
            "THERE ARE SOME UNSAVED CHANGES DO YOU WANT TO SAVE THE FILE BEFORE EXIT?"
        )
        self.speak("PRESS Y TO SAVE AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Save and Exit", "Are You Sure?")

    def onreplace(self):
        self.speak(
            "THERE ALREADY EXIXT FILE WITH THE SAME NAME, DO YOU WANT TO REPLACE IT ?"
        )
        self.speak("PRESS Y TO REPLACE AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Replace", "Are You Sure?")

    def pressf1(self):
        if self.final_data != self.data:
            if self.onsave() == "yes":
                self.SaVe(self.data)
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
            else:
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
        else:
            self.final_data = ""
            self.filename = ""
            self.textPad.delete('0.0', 'end')

        self.outputpad.configure(state='normal')
        self.outputpad.delete('0.0', 'end')
        self.outputpad.configure(state='disabled')
        self.frame2.configure(text="Editor")
        self.speak("Opening a new Tab")

    def pressf2(self):
        if self.final_data != self.data:
            if self.onopen() == "yes":
                self.SaVe(self.data)
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
                self.open_file()
            else:
                self.alreadysave(self.data, self.filename)
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
                self.open_file()
        else:
            self.open_file()

    def pressf4(self):
        if not self.final_data == self.data:
            if self.onsave() == "yes":
                self.SaVe(self.data)
                self.master.destroy()
            else:
                self.master.destroy()
        else:
            if self.onexit() == "yes": self.master.destroy()
            else: pass

    def pressf5(self):
        if self.filename:
            self.outputconf()
            self.alreadysave(self.data, self.filename)
            self.outputgen(self.filename)
        else:
            self.SaVe(self.data)
            self.outputconf()
            self.outputgen(self.filename)

    def pressf8(self):
        global voice
        if voice == 0:
            voice = 1
            self.s.Voice = self.s.GetVoices().Item(voice)
        else:
            voice = 0
            self.s.Voice = self.s.GetVoices().Item(voice)

    def pressf11(self):
        self.speak("INSTRUCTIONS ARE ")
        self.speak(
            "PRESS F1 FOR NEW FILE, F2 TO OPEN FILE, F3 TO SAVE FILE, F4 TO EXIT, F5 TO COMPILE, F6 TO LISTEN ALL CODE, F7 TO CLEAR ALL, F8 TO CHANGE VOICE, F9 TO KNOW ABOUT US, F11 FOR INSTRUCTIONS"
        )

    def onKeyPress(self, event):
        #global self.filename
        #self.speak(event.keysym)
        #print(event.keysym)
        global row, col
        row, col = self.textPad.index('insert').split('.')
        self.data = self.textPad.get('1.0', END + '-1c')

        if event.keysym == "F1": self.pressf1()

        elif event.keysym == "F2":
            self.speak("OPENING")
            if self.data == "": self.open_file()
            else: self.pressf2()

        elif event.keysym == "F3":
            self.speak("SAVING")
            if self.data == "": pass
            else: self.SaVe(self.data)

        elif event.keysym == "F4":
            self.speak("EXITING")
            if self.data == "":
                if self.onexit() == "yes": self.master.destroy()
                else: pass
            else: self.pressf4()

        elif event.keysym == "F5":
            self.speak("COMPILE")
            if self.data == "": pass
            else: self.pressf5()

        elif event.keysym == "F6":
            self.speak("CODE IS")
            self.speak(self.data)

        elif event.keysym == "F7":
            self.speak("CLEARING ALL CODE")
            self.textPad.delete("0.0", 'end')

        elif event.keysym == "F8":
            self.speak("CHANGING VOICE")
            self.pressf8()

        elif event.keysym == "F9":
            #self.speak("ABOUT Us");
            self.speak("CREATED BY NANDISH PATEL")

        elif event.keysym == "F11":
            self.speak("INSTRUCTIONS")
            self.pressf11()

        else:
            pass
Ejemplo n.º 31
-1
class editor:
    def __init__(self, rt):
        if rt == None:
            self.t = Tk()
        else:
            self.t = Toplevel(rt)
        self.t.title("Tkeditor %d" % len(t1))
        self.bar = Menu(rt)

        self.filem = Menu(self.bar)
        self.filem.add_command(label="打开", command=self.openfile)
        self.filem.add_command(label="新建", command=neweditor)
        self.filem.add_command(label="保存", command=self.savefile)
        self.filem.add_command(label="关闭", command=self.close)
        self.filem.add_separator()
        self.filem.add_command(label="退出", command=die)

        self.helpm = Menu(self.bar)
        self.helpm.add_command(label="关于", command=about)
        self.bar.add_cascade(label="文件", menu=self.filem)
        self.bar.add_cascade(label="帮助", menu=self.helpm)
        self.t.config(menu=self.bar)

        self.f = Frame(self.t, width=512)
        self.f.pack(expand=1, fill=BOTH)

        self.st = ScrolledText(self.f, background="white")
        self.st.pack(side=LEFT, fill=BOTH, expand=1)

        self.open = Button(self)
        self.open["text"] = "open"
        self.open["fg"] = "Blue"
        self.open["command"] = self.openfile
        self.open.pack({"side": "left"})
        self.open.pack({"anchor": "nw"})

    def close(self):
        self.t.destroy()
        print "close"

    def openfile(self):
        p1 = END
        oname = askopenfilename(filetypes=[("Python file", "*.*")])
        if oname:
            for line in fileinput.input(oname):
                self.st.insert(p1, line)
            self.t.title(oname)

    def savefile(self):
        sname = asksaveasfilename()
        if sname:
            ofp = open(sname, "w")
            ofp.write(self.st.get(1.0, END))
            ofp.flush()
            ofp.close()
            self.t.title(sname)