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
lineColPosList=[] def callback(event): lineColPosList = textPad.index(CURRENT).split('.') print textPad.index(CURRENT) status["text"]="Line" + lineColPosList[0] + " Column " + lineColPosList[1] root = tk.Tk(className="Intelligent Code Editor") textPad = ScrolledText(root, width=500, height=100,fg="white",bg="black") textPad.config(font=("Arial",15),insertbackground="white") lineColPosList = textPad.index(CURRENT).split('.') textPad.bind("<Button-1>", callback) textPad.bind("<Key>", callback) textPad.focus() status = Label(root, text="Line" + lineColPosList[0] + " Column " + lineColPosList[1], bd=1, relief=SUNKEN, anchor=W) status.pack(side=BOTTOM, fill=X) def replaceText(inputText): inputText = inputText.replace('of','[]') inputText = inputText.replace('function','') inputText = inputText.replace('increment','') inputText = inputText.replace('initialize','') inputText = inputText.replace('condition','') inputText = inputText.replace('math','') inputText = inputText.replace('equals','=')
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))
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 )
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
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()
class GuiPart: def __init__(self, master, queue, queue2, endCommand): self.queue = queue self.queue2 = queue2 self.msg = "" self.targetpics = [] self.currentImage = -1 # Set up the GUI console = Tkinter.Button(master, text='Done', command=endCommand) console.grid(row=3, column=1, sticky=Tkinter.W) #Telemetry Window self.tele = ScrolledText(master, width=50, height=10, wrap='word') self.tele.insert('end', 'Awaiting Telemetry...\n----------------------\n') self.tele.grid(row=0, column=1, columnspan=1, padx=5, pady=5) #Receiving Targets Window self.rt = ScrolledText(master, width=50, height=10, wrap='word') self.rt.insert('end', 'Awaiting Target Data...\n------------------------\n') self.rt.grid(row=0, column=3, columnspan=2, padx=5, pady=5) #Image img = Tkinter.PhotoImage(file="logo.gif") logo = Tkinter.Label(master, image = img) logo.image=img logo.grid(row=0, column=2, padx=5, pady=5) #Obstacles Button obs_but = Tkinter.Button(master, text='Retreive Obstacles From Server', command=self.getObstacles) obs_but.grid(row=1, column=1, sticky=Tkinter.W) #General Terminal Button gt_but = Tkinter.Button(master, text='Submit Data', command=endCommand) gt_but.grid(row=1, column=2, sticky=Tkinter.W) #Upload Targets Button ut_but = Tkinter.Button(master, text='Upload Target Data', command=self.uploadTarget) ut_but.grid(row=1, column=3, columnspan=2, sticky=Tkinter.W) #Receiving Obstacles Window self.obs = ScrolledText(master, width=50, height=10, wrap='word') self.obs.insert('end', 'Ready for Obstacle Data...\n--------------------------\n') self.obs.grid(row=2, column=1, columnspan=1, padx=5, pady=5) #General Terminal Window self.gt = ScrolledText(master, width=50, height=10, wrap='word') self.gt.insert('end', 'Enter in Server Query...\n------------------------\n') self.gt.grid(row=2, column=2, columnspan=1, padx=5, pady=5) #Upload Targets Window #self.ut = ScrolledText(master, width=50, height=10, wrap='word') #self.ut.insert('end', 'Enter in Target Data...\n------------------------\n') target_label_text = ["Target Type: ","Latitude: ","Longitude: ","Orientation:", \ "Shape: ", "BG Color: ", "Letter/#: ","Letter/# Color: "] targetlabelpane = Tkinter.PanedWindow(orient=Tkinter.VERTICAL) for i in target_label_text: targetlabelpane.add(Tkinter.Label(master, text=i,pady=3)) targetlabelpane.grid(row=2, column=3,sticky=Tkinter.W) # Use combobox if user entry is also required # Here we use optionmenu self.available_target_type = Tkinter.StringVar() #["standard", "qrc", "off_axis", "emergent"] self.available_target_type.set("standard") self.available_orientation = Tkinter.StringVar() #["N","E","S","W","NE","SE","SW","NW"] self.available_orientation.set("N") self.available_shapes = Tkinter.StringVar() #["circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross"] self.available_shapes.set("circle") self.available_bg_colors = Tkinter.StringVar() #["white","black","gray","red","blue","green","yellow","purple","brown","orange"] self.available_bg_colors.set("white") self.available_alpha_colors = Tkinter.StringVar() self.available_alpha_colors.set("white") ''' drop_target_type = Tkinter.OptionMenu(master,available_target_type,"standard", "qrc", "off_axis", "emergent") entry_lat = Tkinter.Entry(master, bd=5, width=70) entry_lon = Tkinter.Entry(master, bd=5, width=70) drop_orientation = Tkinter.OptionMenu(master,available_orientation,"N","E","S","W","NE","SE","SW","NW") drop_shapes = Tkinter.OptionMenu(master,available_shapes,"circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross") drop_bg_colors = Tkinter.OptionMenu(master,available_bg_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange") entry_alphanum = Tkinter.Entry(master, bd=5, width=70) drop_alpha_colors= Tkinter.OptionMenu(master,available_alpha_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange") ''' targetpane = Tkinter.PanedWindow(orient=Tkinter.VERTICAL) targetpane.add(Tkinter.OptionMenu(master,self.available_target_type,"standard", "qrc", "off_axis", "emergent")) self.entry_lat = Tkinter.Entry(master, width=10) targetpane.add(self.entry_lat) self.entry_lon = Tkinter.Entry(master,width=10) targetpane.add(self.entry_lon) targetpane.add(Tkinter.OptionMenu(master,self.available_orientation,"N","E","S","W","NE","SE","SW","NW")) targetpane.add(Tkinter.OptionMenu(master,self.available_shapes,"circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross")) targetpane.add(Tkinter.OptionMenu(master,self.available_bg_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange")) self.entry_alphanum = Tkinter.Entry(master, width=10) targetpane.add(self.entry_alphanum) targetpane.add(Tkinter.OptionMenu(master,self.available_alpha_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange")) targetpane.grid(row=2, column=3, padx=5, pady=5) #General Terminal Text Area self.gt_text = Tkinter.Entry(master,width=70) self.gt_text.grid(row=3, column=2, columnspan=1, padx=5, pady=5) #Target Picture Buttons pane = Tkinter.PanedWindow() rti_prev = Tkinter.Button(master, text='Prev Picture', command=self.prevPic) pane.add(rti_prev) self.rti_label = Tkinter.Label(master, text='Awaiting Target') rti_next = Tkinter.Button(master, text='Next Picture', command=self.nextPic) pane.add(rti_next) pane.add(self.rti_label) pane.grid(row=4, column=2, padx=5, pady=5) ''' #Target Images rtimg = Tkinter.PhotoImage(file="target.gif") self.rti = Tkinter.Label(master, image = rtimg) self.rti.image=rtimg self.rti.grid(row=5, column=2, columnspan=1, padx=5, pady=5) ''' # User credentials field cred_label_text = ['Server IP: ','Username: '******'Password: '******'Login', command=self.loginWithCred) self.cred_but.grid(row=8, column=1, columnspan=1, padx=5, pady=5) # Add more GUI stuff here def processIncoming(self): """ Handle all the messages currently in the queue (if any). """ #self.counter = 0 #self.queue.put('asdas') while self.queue.qsize(): try: self.msg = str(self.queue.get(0)) + '\n' # Check contents of message and do what it says # As a test, we simply print it self.tele.insert('end', self.msg) if(float(self.tele.index('end')) > 11.0): self.tele.delete('1.0','end') self.msg2 = self.queue2.get(0) + '\n' #print self.msg2 if(self.msg2.find('Target') == 0): #self.targetpics[self.counter] = self.msg2 self.targetpics.append(self.msg2) #self.counter += 1 else: self.rt.insert('end', self.msg2) except Queue.Empty: pass def getObstacles(self): # GET obstacles request c = pycurl.Curl() buffer = StringIO() c.setopt(pycurl.URL, interop_api_url+'obstacles') c.setopt(pycurl.WRITEDATA, buffer) c.setopt(pycurl.COOKIEFILE, 'sessionid.txt') c.perform() obstacles_json = json.loads(buffer.getvalue()) print("\n\n" + "====Obstacles====") obstacles = json.dumps(obstacles_json, sort_keys=True,indent=4, separators=(',', ': ')) print obstacles self.obs.insert('end', obstacles) def nextPic(self): if(self.currentImage < len(self.targetpics) - 1): self.currentImage += 1 self.nextImage = Tkinter.PhotoImage(file='Photos/' + self.targetpics[self.currentImage].strip()) self.rti.configure(image=self.nextImage) self.rti.image = self.nextImage self.rti_label.configure(text=self.targetpics[self.currentImage].strip()) def prevPic(self): if(self.currentImage > 0): self.currentImage -= 1 self.nextImage = Tkinter.PhotoImage(file='Photos/' + self.targetpics[self.currentImage].strip()) self.rti.configure(image=self.nextImage) self.rti.image = self.nextImage self.rti_label.configure(text=self.targetpics[self.currentImage].strip()) def loginWithCred(self): global interop_api_url interop_api_url = "http://"+self.cred_text[0].get()+"/api/" #print interop_api_url c = pycurl.Curl() c.setopt(pycurl.URL, interop_api_url+'login') c.setopt(pycurl.POSTFIELDS, 'username='******'&password='******'sessionid.txt') c.perform() def uploadTarget(self): global interop_api_url target_data_dict = { \ "type": self.available_target_type.get(), \ "latitude": float(self.entry_lat.get()), \ "longitude": float(self.entry_lon.get()), \ "orientation": self.available_orientation.get(), \ "shape": self.available_shapes.get(), \ "background_color": self.available_bg_colors.get(), \ "alphanumeric": self.entry_alphanum.get(), \ "alphanumeric_color": self.available_alpha_colors.get(), \ } json_target_data = json.dumps(target_data_dict) c = pycurl.Curl() c.setopt(pycurl.URL, interop_api_url+'targets') c.setopt(pycurl.POSTFIELDS, json_target_data) c.setopt(pycurl.COOKIEFILE, 'sessionid.txt') c.perform()
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()
class GuiPart: def __init__(self, master, queue, queue2, endCommand): self.queue = queue self.queue2 = queue2 self.msg = "" self.targetpics = [] self.currentImage = -1 # Set up the GUI console = Tkinter.Button(master, text='Done', command=endCommand) console.grid(row=3, column=1, sticky=Tkinter.W) #Telemetry Window self.tele = ScrolledText(master, width=50, height=10, wrap='word') self.tele.insert('end', 'Awaiting Telemetry...\n----------------------\n') self.tele.grid(row=0, column=1, columnspan=1, padx=5, pady=5) #Receiving Targets Window self.rt = ScrolledText(master, width=50, height=10, wrap='word') self.rt.insert('end', 'Awaiting Target Data...\n------------------------\n') self.rt.grid(row=0, column=3, columnspan=2, padx=5, pady=5) #Image img = Tkinter.PhotoImage(file="logo.gif") logo = Tkinter.Label(master, image=img) logo.image = img logo.grid(row=0, column=2, padx=5, pady=5) #Obstacles Button obs_but = Tkinter.Button(master, text='Retreive Obstacles From Server', command=self.getObstacles) obs_but.grid(row=1, column=1, sticky=Tkinter.W) #General Terminal Button gt_but = Tkinter.Button(master, text='Submit Data', command=endCommand) gt_but.grid(row=1, column=2, sticky=Tkinter.W) #Upload Targets Button ut_but = Tkinter.Button(master, text='Upload Target Data', command=self.uploadTarget) ut_but.grid(row=1, column=3, columnspan=2, sticky=Tkinter.W) #Receiving Obstacles Window self.obs = ScrolledText(master, width=50, height=10, wrap='word') self.obs.insert( 'end', 'Ready for Obstacle Data...\n--------------------------\n') self.obs.grid(row=2, column=1, columnspan=1, padx=5, pady=5) #General Terminal Window self.gt = ScrolledText(master, width=50, height=10, wrap='word') self.gt.insert('end', 'Enter in Server Query...\n------------------------\n') self.gt.grid(row=2, column=2, columnspan=1, padx=5, pady=5) #Upload Targets Window #self.ut = ScrolledText(master, width=50, height=10, wrap='word') #self.ut.insert('end', 'Enter in Target Data...\n------------------------\n') target_label_text = ["Target Type: ","Latitude: ","Longitude: ","Orientation:", \ "Shape: ", "BG Color: ", "Letter/#: ","Letter/# Color: "] targetlabelpane = Tkinter.PanedWindow(orient=Tkinter.VERTICAL) for i in target_label_text: targetlabelpane.add(Tkinter.Label(master, text=i, pady=3)) targetlabelpane.grid(row=2, column=3, sticky=Tkinter.W) # Use combobox if user entry is also required # Here we use optionmenu self.available_target_type = Tkinter.StringVar( ) #["standard", "qrc", "off_axis", "emergent"] self.available_target_type.set("standard") self.available_orientation = Tkinter.StringVar( ) #["N","E","S","W","NE","SE","SW","NW"] self.available_orientation.set("N") self.available_shapes = Tkinter.StringVar( ) #["circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross"] self.available_shapes.set("circle") self.available_bg_colors = Tkinter.StringVar( ) #["white","black","gray","red","blue","green","yellow","purple","brown","orange"] self.available_bg_colors.set("white") self.available_alpha_colors = Tkinter.StringVar() self.available_alpha_colors.set("white") ''' drop_target_type = Tkinter.OptionMenu(master,available_target_type,"standard", "qrc", "off_axis", "emergent") entry_lat = Tkinter.Entry(master, bd=5, width=70) entry_lon = Tkinter.Entry(master, bd=5, width=70) drop_orientation = Tkinter.OptionMenu(master,available_orientation,"N","E","S","W","NE","SE","SW","NW") drop_shapes = Tkinter.OptionMenu(master,available_shapes,"circle","semicircle","quarter_circle","triangle","square","rectangle","trapezoid","pentagon","hexagon","heptagon","octagon","star","cross") drop_bg_colors = Tkinter.OptionMenu(master,available_bg_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange") entry_alphanum = Tkinter.Entry(master, bd=5, width=70) drop_alpha_colors= Tkinter.OptionMenu(master,available_alpha_colors,"white","black","gray","red","blue","green","yellow","purple","brown","orange") ''' targetpane = Tkinter.PanedWindow(orient=Tkinter.VERTICAL) targetpane.add( Tkinter.OptionMenu(master, self.available_target_type, "standard", "qrc", "off_axis", "emergent")) self.entry_lat = Tkinter.Entry(master, width=10) targetpane.add(self.entry_lat) self.entry_lon = Tkinter.Entry(master, width=10) targetpane.add(self.entry_lon) targetpane.add( Tkinter.OptionMenu(master, self.available_orientation, "N", "E", "S", "W", "NE", "SE", "SW", "NW")) targetpane.add( Tkinter.OptionMenu(master, self.available_shapes, "circle", "semicircle", "quarter_circle", "triangle", "square", "rectangle", "trapezoid", "pentagon", "hexagon", "heptagon", "octagon", "star", "cross")) targetpane.add( Tkinter.OptionMenu(master, self.available_bg_colors, "white", "black", "gray", "red", "blue", "green", "yellow", "purple", "brown", "orange")) self.entry_alphanum = Tkinter.Entry(master, width=10) targetpane.add(self.entry_alphanum) targetpane.add( Tkinter.OptionMenu(master, self.available_alpha_colors, "white", "black", "gray", "red", "blue", "green", "yellow", "purple", "brown", "orange")) targetpane.grid(row=2, column=3, padx=5, pady=5) #General Terminal Text Area self.gt_text = Tkinter.Entry(master, width=70) self.gt_text.grid(row=3, column=2, columnspan=1, padx=5, pady=5) #Target Picture Buttons pane = Tkinter.PanedWindow() rti_prev = Tkinter.Button(master, text='Prev Picture', command=self.prevPic) pane.add(rti_prev) self.rti_label = Tkinter.Label(master, text='Awaiting Target') rti_next = Tkinter.Button(master, text='Next Picture', command=self.nextPic) pane.add(rti_next) pane.add(self.rti_label) pane.grid(row=4, column=2, padx=5, pady=5) ''' #Target Images rtimg = Tkinter.PhotoImage(file="target.gif") self.rti = Tkinter.Label(master, image = rtimg) self.rti.image=rtimg self.rti.grid(row=5, column=2, columnspan=1, padx=5, pady=5) ''' # User credentials field cred_label_text = ['Server IP: ', 'Username: '******'Password: '******'Login', command=self.loginWithCred) self.cred_but.grid(row=8, column=1, columnspan=1, padx=5, pady=5) # Add more GUI stuff here def processIncoming(self): """ Handle all the messages currently in the queue (if any). """ #self.counter = 0 #self.queue.put('asdas') while self.queue.qsize(): try: self.msg = str(self.queue.get(0)) + '\n' # Check contents of message and do what it says # As a test, we simply print it self.tele.insert('end', self.msg) if (float(self.tele.index('end')) > 11.0): self.tele.delete('1.0', 'end') self.msg2 = self.queue2.get(0) + '\n' #print self.msg2 if (self.msg2.find('Target') == 0): #self.targetpics[self.counter] = self.msg2 self.targetpics.append(self.msg2) #self.counter += 1 else: self.rt.insert('end', self.msg2) except Queue.Empty: pass def getObstacles(self): # GET obstacles request c = pycurl.Curl() buffer = StringIO() c.setopt(pycurl.URL, interop_api_url + 'obstacles') c.setopt(pycurl.WRITEDATA, buffer) c.setopt(pycurl.COOKIEFILE, 'sessionid.txt') c.perform() obstacles_json = json.loads(buffer.getvalue()) print("\n\n" + "====Obstacles====") obstacles = json.dumps(obstacles_json, sort_keys=True, indent=4, separators=(',', ': ')) print obstacles self.obs.insert('end', obstacles) def nextPic(self): if (self.currentImage < len(self.targetpics) - 1): self.currentImage += 1 self.nextImage = Tkinter.PhotoImage( file='Photos/' + self.targetpics[self.currentImage].strip()) self.rti.configure(image=self.nextImage) self.rti.image = self.nextImage self.rti_label.configure( text=self.targetpics[self.currentImage].strip()) def prevPic(self): if (self.currentImage > 0): self.currentImage -= 1 self.nextImage = Tkinter.PhotoImage( file='Photos/' + self.targetpics[self.currentImage].strip()) self.rti.configure(image=self.nextImage) self.rti.image = self.nextImage self.rti_label.configure( text=self.targetpics[self.currentImage].strip()) def loginWithCred(self): global interop_api_url interop_api_url = "http://" + self.cred_text[0].get() + "/api/" #print interop_api_url c = pycurl.Curl() c.setopt(pycurl.URL, interop_api_url + 'login') c.setopt( pycurl.POSTFIELDS, 'username='******'&password='******'sessionid.txt') c.perform() def uploadTarget(self): global interop_api_url target_data_dict = { \ "type": self.available_target_type.get(), \ "latitude": float(self.entry_lat.get()), \ "longitude": float(self.entry_lon.get()), \ "orientation": self.available_orientation.get(), \ "shape": self.available_shapes.get(), \ "background_color": self.available_bg_colors.get(), \ "alphanumeric": self.entry_alphanum.get(), \ "alphanumeric_color": self.available_alpha_colors.get(), \ } json_target_data = json.dumps(target_data_dict) c = pycurl.Curl() c.setopt(pycurl.URL, interop_api_url + 'targets') c.setopt(pycurl.POSTFIELDS, json_target_data) c.setopt(pycurl.COOKIEFILE, 'sessionid.txt') c.perform()
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