class GUI(Frame): def __init__(self, master=None, app=None, title=''): self.engine = app Frame.__init__(self, master) self.master.title(title) self.grid() self.createWidgets() def createWidgets(self): top = self.winfo_toplevel() top.rowconfigure(0, weight=1) top.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) self.nextButton = Button(self, text="next", command=self.next) self.nextButton.grid(row=0, column=0, sticky=S) self.quitButton = Button(self, text="quit", command=self.quit) self.quitButton.grid(row=0, column=1, sticky=S) self.inWindow = Text() self.inWindow.grid(row=1, column=0, sticky=N + E + S + W) self.outWindow = ScrolledText() self.outWindow.grid(row=2, column=0, sticky=N + E + S + W) def next(self): if self.engine <> None: self.engine.next() else: self.clearInput() def quit(self): self.master.destroy() self.engine.quit() def write(self, s): write(s, outstream=None, widget=self.outWindow) def writeln(self, s): writeln(s, outstream=None, widget=self.outWindow) def get(self): return self.inWindow.get(1.0, END) def userMultiLineInput(self): return self.get() def clearOutput(self): self.outWindow.delete(1.0, END) def clearInput(self): self.inWindow.delete(1.0, END) def clearInput(self): self.inWindow.delete(1.0, END)
class GredAboutBox(GatoDialogs.AboutBox): def body(self, master): self.resizable(0, 0) self.catIconImage = PhotoImage(data=GatoIcons.gred) self.catIcon = Label(master, image=self.catIconImage) self.catIcon.pack(side=TOP) label = Label(master, text=GatoDialogs.crnotice1) label.pack(side=TOP) label = Label(master, font="Helvetica 10", text=GatoDialogs.crnotice2, justify=CENTER) label.pack(side=TOP) color = self.config("bg")[4] self.infoText = ScrolledText( master, relief=FLAT, padx=3, pady=3, background=color, #foreground="black", wrap='word', width=60, height=12, font="Times 10") self.infoText.pack(expand=0, fill=X, side=BOTTOM) self.infoText.delete('0.0', END) self.infoText.insert('0.0', GatoGlobals.gLGPLText) self.infoText.configure(state=DISABLED) self.title("Gred - About")
class GredAboutBox(GatoDialogs.AboutBox): def body(self, master): self.resizable(0,0) self.catIconImage = PhotoImage(data=GatoIcons.gred) self.catIcon = Label(master, image=self.catIconImage) self.catIcon.pack(side=TOP) label = Label(master, text=GatoDialogs.crnotice1) label.pack(side=TOP) label = Label(master, font="Helvetica 10", text=GatoDialogs.crnotice2, justify=CENTER) label.pack(side=TOP) color = self.config("bg")[4] self.infoText = ScrolledText(master, relief=FLAT, padx=3, pady=3, background=color, #foreground="black", wrap='word', width=60, height=12, font="Times 10") self.infoText.pack(expand=0, fill=X, side=BOTTOM) self.infoText.delete('0.0', END) self.infoText.insert('0.0', GatoGlobals.gLGPLText) self.infoText.configure(state=DISABLED) self.title("Gred - About")
def defaultcheck(): global w3 w3 = Toplevel() w3.wm_attributes('-fullscreen', 1) of = open('License.dat', 'r') for of2 in of: of2==of2 root.iconify() if of2 == ugoku: p = open('Path.dat', 'r') for i in p: if not os.path.exists(i): Dialog.Dialog(root, title = 'alert', bitmap = 'info', text = u'プログラムファイルが見つかりません。%s' % i, strings = ['OK'], default = 0) sys.exit() else: actlog() w3.destroy() elif of2 == eke: actname.set(ids) os.chdir(currentdir) f1 = Frame(w3) f2 = Frame(w3) f3 = Frame(w3) f4 = Frame(w3) Label(w3, text = '%s' % osnam).pack() t0 = ScrolledText(w3) t0.pack() fi = open('README.txt') t0.delete('1.0', 'end') for x in fi: t0.insert('end', x.decode('shift_jis')) fi.close() t0.focus_set() Label(w3, text = u'管理者登録').pack() Label(w3, textvariable = pwcon).pack() Label(f1, textvariable = actname).pack(side = RIGHT) Label(f1, text = u'管理者名').pack(side = LEFT) Entry(f2, textvariable = actpw, show = '*').pack(side = RIGHT) Label(f2, text = u'パスワード(8文字)').pack(side = LEFT) Entry(f3, textvariable = actpwc, show = '*').pack(side = RIGHT) Label(f3, text = u'確認のためもう一度入力').pack(side = LEFT) Button(f4, text = u'作成', command = makeid).pack(side = LEFT) Button(f4, text = u'キャンセル', command = sys.exit).pack(side = RIGHT) f1.pack() f2.pack() f3.pack() f4.pack() root.lower() else: Dialog.Dialog(root, title = 'alert', bitmap = 'info', text = u'ライセンス認証されていないため、本ソフトを起動できませんでした', strings = ['OK'], default = 0) sys.exit()
class Editor(object): def __init__(self): self.root = Tk() self.root.title('untitled') self.menubar = Menu(self.root) # file menu self.file_menu = Menu(self.menubar) self.file_menu.add_command(label='打开', command=self.openfile) self.file_menu.add_command(label='保存', command=self.savefile) self.file_menu.add_separator() self.file_menu.add_command(label='退出', command=self.exit) # help menu self.help_menu = Menu(self.menubar) self.help_menu.add_command(label='关于', command=self.about) # menu self.menubar.add_cascade(label='文件', menu=self.file_menu) self.menubar.add_cascade(label='帮助', menu=self.help_menu) self.root.config(menu=self.menubar) # frame self.frame = Frame(width=512) self.frame.pack(expand=1, fill=BOTH) # scrolled text ft = tkFont.Font(family='Consolas', size=12, weight=tkFont.NORMAL) self.st = ScrolledText(self.frame, bg='navyblue', fg='white', font=ft) self.st.pack(side=LEFT, fill=BOTH, expand=1) # run self.root.mainloop() def openfile(self): filename = askopenfilename( filetypes=[('Python files', '*.py'), ('Text files', '*.txt'), ('All files', '*.*')]) if filename: self.root.title(filename) self.st.delete(1.0, END) for line in fileinput.input(filename): self.st.insert(END, line) def savefile(self): filename = asksaveasfilename(filetypes=[('Python files', '*.py')], defaultextension='py') if filename: ofp = open(filename, 'w') ofp.write(self.st.get(1.0, END)) ofp.flush() ofp.close() self.root.title(filename) def exit(self): self.root.destroy() def about(self): tkMessageBox.showinfo('About Tkeditor', 'Tkeditor V1.0\nby Laozhao')
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)
class Add_Group(Frame): def __init__(self, parent, app): Frame.__init__(self, parent) self.parent = parent self.app = app #Frame to hold Keyword Group new Entry and new keywords text box addKGFrame = Frame(parent, bg="#E8E8E8", relief=RAISED) addKGFrame.pack(fill=BOTH, expand=True, side=LEFT, padx=10, pady=10) #Label for Entry Box addGroupLabel = Label(addKGFrame, text="Enter New Group Name",bg="#E8E8E8") addGroupLabel.pack(side=TOP) #Entry Box for new Keyword Group self.addGroup = Entry(addKGFrame, width=30, relief=SUNKEN) self.addGroup.pack(side=TOP, fill=X, expand=True, pady=5) #Label for New Keywords for Group Text Box addKGLabel = Label(addKGFrame, text="Enter New Keywords (Optional)",bg="#E8E8E8") addKGLabel.pack(side=TOP, fill=X, expand=True, pady=5) #Canvas for Text Box to Enter New Keywords for New Group addKGCanvas = Canvas(addKGFrame, bg="#E8E8E8", relief=SUNKEN) addKGCanvas.pack(side=TOP, fill=BOTH, expand=True, pady=5) #Keywords for new group scrollable text box self.addKGText = ScrolledText(addKGCanvas, wrap=WORD, width=25, height=15, relief=SUNKEN, highlightthickness=0, bd=1, padx=1, pady=1) self.addKGText.pack(fill=BOTH, side=TOP, expand=True) #Button to add new Keyword Group and Keywords addKGButton = Button(addKGFrame, text="Add Group", width=30, highlightbackground='#E8E8E8', command=self.group_add) addKGButton.pack(side=TOP, fill=BOTH, expand=True) #Function to add the keyword group def group_add(self): newGroup = self.addGroup.get() if newGroup != "": self.app.key_group.keyword_groups[newGroup] = [] text = self.addKGText.get('1.0', 'end-1c').splitlines() for line in text: self.app.key_group.keyword_groups[newGroup].append(line) self.app.Groups.groupList.delete(0, END) for x in self.app.key_group.keyword_groups: self.app.Groups.groupList.insert(END, '%s' % x) self.addKGText.delete('1.0', END) self.addGroup.delete(0, END)
class LogWindow(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master.title("Network Simulator Log") self.text = ScrolledText(self) self.text.pack(fill=BOTH, expand=1) self.pack(fill=BOTH, expand=1) self.text.config( background="black", foreground="white", font=Font( family="Courier", weight="bold"), # state=DISABLED, wrap=NONE, ) self.text.tag_config("DEBUG", foreground="green") self.text.tag_config("ERROR", foreground="red") self.text.tag_config("CRITICAL", foreground="red") self.text.tag_config("EXCEPTION", foreground="red") self.text.tag_config("WARNING", foreground="yellow") self.text.tag_config("INFO", foreground="white") self.text.bind("<Key>", lambda e: 'break') self.text.bind("<Return>", self._clear) self.queue = Queue() self._update() def _clear(self, event): self.text.delete(1.0, END) return 'break' def _update(self): try: while True: text, level = self.queue.get(block=False) at_bottom = self.text.yview()[1] == 1.0 # self.text.config(state=NORMAL) if len(self.text.get(1.0, END).strip()) != 0: text = "\n" + text self.text.insert(END, text, str(level)) # self.text.config(state=DISABLED) if at_bottom: self.text.yview_moveto(1.0) except Empty: pass self.after(50, self._update) def append(self, entry, level="INFO"): self.queue.put((entry, level))
class LogWindow(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master.title("Network Simulator Log") self.text = ScrolledText(self) self.text.pack(fill=BOTH, expand=1) self.pack(fill=BOTH, expand=1) self.text.config( background="black", foreground="white", font=Font(family="Courier", weight="bold"), # state=DISABLED, wrap=NONE, ) self.text.tag_config("DEBUG", foreground="green") self.text.tag_config("ERROR", foreground="red") self.text.tag_config("CRITICAL", foreground="red") self.text.tag_config("EXCEPTION", foreground="red") self.text.tag_config("WARNING", foreground="yellow") self.text.tag_config("INFO", foreground="white") self.text.bind("<Key>", lambda e: 'break') self.text.bind("<Return>", self._clear) self.queue = Queue() self._update() def _clear(self, event): self.text.delete(1.0, END) return 'break' def _update(self): try: while True: text, level = self.queue.get(block=False) at_bottom = self.text.yview()[1] == 1.0 # self.text.config(state=NORMAL) if len(self.text.get(1.0, END).strip()) != 0: text = "\n" + text self.text.insert(END, text, str(level)) # self.text.config(state=DISABLED) if at_bottom: self.text.yview_moveto(1.0) except Empty: pass self.after(50, self._update) def append(self, entry, level="INFO"): self.queue.put((entry, level))
class AboutBox(tkSimpleDialog.Dialog): """ The application's about box """ def buttonbox(self): # Stolen from tkSimpleDialog.py # add standard button box. override if you don't want the # standard buttons box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=RIGHT, padx=5, pady=5) self.bind("<Return>", self.ok) box.pack(side=BOTTOM, fill=X) def body(self, master): self.resizable(0, 0) self.catIconImage = PhotoImage(data=GatoIcons.gato) # statt file= self.catIcon = Label(master, image=self.catIconImage) self.catIcon.pack(side=TOP) label = Label(master, text=crnotice1) label.pack(side=TOP) label = Label(master, font="Helvetica 10", text=crnotice2, justify=CENTER) label.pack(side=TOP) color = self.config("bg")[4] self.infoText = ScrolledText( master, relief=FLAT, padx=3, pady=3, background=color, #foreground="black", wrap='word', width=60, height=12, font="Times 10") self.infoText.pack(expand=0, fill=X, side=BOTTOM) self.infoText.delete('0.0', END) self.infoText.insert('0.0', GatoGlobals.gLGPLText) self.infoText.configure(state=DISABLED) self.title("Gato - About")
class dashboard(object): def __init__(self, width, height): self.labels = [] self.convertedCode = "" self.st = ScrolledText(width=70, height=21) self.st.pack(side=RIGHT) self.code = "" self.width = width self.height = height self.cx, self.cy = self.width/2, self.height/2 self.funcLine = self.cx + 100 def displayCode(self, code): self.code = code self.st.delete("1.0",END) self.st.insert(INSERT, code) def inRange(self, x, y): for i in xrange(len(self.labels)): obj = self.labels[i].inRange(x, y) if(obj != None): return obj return None def addLabel(self, obj): self.labels.append(obj) def draw(self, canvas): canvas.create_text((self.width+self.funcLine)/2, 20, text="Dashboard", font="Arial 18 bold") canvas.create_line(self.funcLine, 310, self.width, 310, width=4, fill="gray") canvas.create_text((self.width+self.funcLine)/2, 330, text="Python Code Translation", font="Arial 14 bold") canvas.create_window(self.funcLine, 345, window=self.st, anchor="nw") for i in xrange(len(self.labels)): self.labels[i].draw(canvas) def setConvertCode(self, code): self.convertedCode = code
class AboutBox(tkSimpleDialog.Dialog): """ The application's about box """ def buttonbox(self): # Stolen from tkSimpleDialog.py # add standard button box. override if you don't want the # standard buttons box = Frame(self) w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE) w.pack(side=RIGHT, padx=5, pady=5) self.bind("<Return>", self.ok) box.pack(side=BOTTOM,fill=X) def body(self, master): self.resizable(0,0) self.catIconImage = PhotoImage(data=GatoIcons.gato) # statt file= self.catIcon = Label(master, image=self.catIconImage) self.catIcon.pack(side=TOP) label = Label(master, text=crnotice1) label.pack(side=TOP) label = Label(master, font="Helvetica 10", text=crnotice2, justify=CENTER) label.pack(side=TOP) color = self.config("bg")[4] self.infoText = ScrolledText(master, relief=FLAT, padx=3, pady=3, background=color, #foreground="black", wrap='word', width=60, height=12, font="Times 10") self.infoText.pack(expand=0, fill=X, side=BOTTOM) self.infoText.delete('0.0', END) self.infoText.insert('0.0', GatoGlobals.gLGPLText) self.infoText.configure(state=DISABLED) self.title("Gato - About")
class MainWnd: def __init__(self, parent): self.search_str = StringVar() self.parent = parent root.protocol("WM_DELETE_WINDOW", self.ask_quit) self.parent.title("snippets") self.parent.configure(padx=10, pady=10) self.parent.minsize(630, 480) self.create_widgets() db_path = os.path.join(abspath(dirname(__file__)), "snip.db") db_exists = os.path.isfile(db_path) self.connection = sqlite3.connect(db_path) self.connection.row_factory = dict_factory self.cursor = self.connection.cursor() if not db_exists: self.cursor.execute('create table snippet (caption, content)') self.fill_list() self.snip_content.focus_set() def ask_quit(self): if tkMessageBox.askokcancel("Quit", "You want to quit now?"): self.parent.destroy() def __del__(self): self.connection.close() def create_widgets(self): self.search_box = Entry(self.parent, textvariable=self.search_str) self.search_str.set("New snippet") self.search_box.pack(fill=X) self.toolbar_f = Frame(self.parent, pady=5) self.toolbar_f.pack(fill=X) self.newbtn = Button(self.toolbar_f, text="New", command=self.on_new) self.newbtn.pack(side=LEFT) self.savebtn = Button(self.toolbar_f, text="Save", command=self.on_save) self.savebtn.pack(side=LEFT) self.updatebtn = Button(self.toolbar_f, text="Update", command=self.on_update) self.updatebtn.pack(side=LEFT) self.delbtn = Button(self.toolbar_f, text="Delete", command=self.on_delete) self.delbtn.pack(side=LEFT) self.copybtn = Button(self.toolbar_f, text="Copy to clipboard", command=self.on_copy) self.copybtn.pack(side=LEFT) self.quitbtn = Button(self.toolbar_f, text="Quit", command=self.on_quit) self.quitbtn.pack(side=LEFT) self.pwin = PanedWindow(self.parent, showhandle=True) self.pwin.pack(fill=BOTH, expand=1) self.list_f = Frame(self.pwin) self.list_sb = Scrollbar(self.list_f, orient=VERTICAL) self.snip_list = Listbox(self.list_f, yscrollcommand=self.list_sb.set) self.list_sb.config(command=self.snip_list.yview) self.snip_list.bind('<ButtonRelease-1>', self.on_snippet_selected) self.snip_list.pack(side=LEFT, fill=BOTH, expand=1) self.list_sb.pack(side=RIGHT, fill=Y) self.pwin.add(self.list_f) self.pwin.paneconfigure(self.list_f, minsize=177) self.snippetFont = Font(family="courier", size=11, weight=NORMAL) self.snip_content = ScrolledText(self.pwin, height=20, width=40, padx=5, pady=5, font=self.snippetFont) self.pwin.add(self.snip_content) # noinspection PyTypeChecker def fill_list(self): self.snip_list.delete(0, END) self.cursor.execute('select * from snippet') for r in self.cursor.fetchall(): self.snip_list.insert(END, r['caption']) def on_new(self): self.search_str.set("") self.snip_content.delete(1.0, END) def on_save(self): self.cursor.execute( 'insert into snippet (caption,content) values (?,?)', (self.search_str.get(), self.snip_content.get(1.0, END),)) self.connection.commit() self.fill_list() def on_update(self): self.cursor.execute( 'update snippet set content=? where caption=?', (self.snip_content.get(1.0, END), self.search_str.get())) self.connection.commit() def on_delete(self): index = self.snip_list.curselection()[0] seltext = self.snip_list.get(index) self.cursor.execute( 'delete from snippet where caption=?', (seltext,)) self.connection.commit() self.snip_list.delete(ANCHOR) self.on_new() def on_copy(self): self.parent.clipboard_clear() self.parent.clipboard_append(self.snip_content.get(1.0, END)) def on_quit(self): self.parent.destroy() # noinspection PyTypeChecker def on_snippet_selected(self, _): try: index = self.snip_list.curselection()[0] except IndexError: return selected_text = self.snip_list.get(index) self.snip_content.delete(1.0, END) self.cursor.execute( 'select * from snippet where caption=?', (selected_text,)) r = self.cursor.fetchone() if r['caption']: self.search_str.set(r['caption']) if r['content']: self.snip_content.insert(INSERT, r['content']) self.snip_content.focus_set()
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 HTMLViewer(Toplevel): """ Basic class which provides a scrollable area for viewing HTML text and a Dismiss button """ def __init__(self, htmlcode, title, master=None): Toplevel.__init__(self, master) #self.protocol('WM_DELETE_WINDOW',self.withdraw) self.titleprefix = title color = self.config("bg")[4] borderFrame = Frame(self, relief=SUNKEN, bd=2) # Extra Frame self.text = ScrolledText( borderFrame, relief=FLAT, padx=3, pady=3, background='white', #background=color, #foreground="black", wrap='word', width=60, height=20, spacing1=3, spacing2=2, spacing3=3) self.text.pack(expand=1, fill=BOTH) #self.text.insert('0.0', text) self.text['state'] = DISABLED borderFrame.pack(side=TOP, expand=1, fill=BOTH) box = Frame(self) w = Button(box, text="Dismiss", width=10, command=self.doWithdraw, default=ACTIVE) w.pack(side=RIGHT, padx=5, pady=5) self.bind("<Return>", self.doWithdraw) box.pack(side=BOTTOM, fill=BOTH) self.setStyle() self.insert(htmlcode) def setStyle(self): baseSize = 14 self.text.config(font="Times %d" % baseSize) self.text.tag_config('h1', font="Times %d bold" % (baseSize + 8)) self.text.tag_config('h2', font="Times %d bold" % (baseSize + 6)) self.text.tag_config('h3', font="Times %d bold" % (baseSize + 4)) self.text.tag_config('h4', font="Times %d bold" % (baseSize + 2)) self.text.tag_config('h5', font="Times %d bold" % (baseSize + 1)) self.text.tag_config('b', font="Times %d bold" % baseSize) self.text.tag_config('em', font="Times %d italic" % baseSize) self.text.tag_config('pre', font="Courier %d" % baseSize) self.text.tag_config('tt', font="Courier %d" % baseSize) def doWithdraw(self, event=None): # Need to eat optional event so that we can use is in both button and bind callback self.withdraw() def Update(self, htmlcode, title): self.titleprefix = title self.insert(htmlcode) def insert(self, htmlcode): self.text['state'] = NORMAL self.text.delete('0.0', END) writer = HTMLWriter(self.text, self) format = formatter.AbstractFormatter(writer) #parser = htmllib.HTMLParser(format) parser = MyHTMLParser(format, self.text) parser.nofill = False parser.feed(htmlcode) parser.close() self.text['state'] = DISABLED if parser.title != None: self.title(self.titleprefix + " - " + parser.title) else: self.title(self.titleprefix)
class Example(Frame): def __init__(self, master): Frame.__init__(self, master) self.master = master self.initUI() def initUI(self): #self.topMessage = StringVar() self.master.title("ZDRa Interface") self.pack(fill=BOTH, expand=1, side=LEFT) m1 = PanedWindow(self.master, width=750) m1.pack(fill=BOTH, expand=1) scrollbar = Scrollbar(self) scrollbar.pack(side=RIGHT, fill=Y) menubar = Menu(self.master) self.master.config(menu=menubar) fileMenu = Menu(menubar) zcgaMenu = Menu(menubar) zdraMenu = Menu(menubar) gpsaMenu = Menu(menubar) fileMenu.add_command(label="Open", command=self.onOpen) zcgaMenu.add_command(label="ZCGa Check", command=self.zcgacheck) zdraMenu.add_command(label="ZDRa Check", command=self.zdracheck) #zdraMenu.add_command(label = "Totalise Spec", command=self.totalisespec) #zdraMenu.add_command(label = "Add Refinements") gpsaMenu.add_command(label="Proof Skeleton", command=self.createskeleton) gpsaMenu.add_command(label="ProofPower-Z Skeleton", command=self.createppgpsa) gpsaMenu.add_command(label="Isabelle Skeleton", command=self.createIsaPS) gpsaMenu.add_command(label="FillInIsaSkeleton", command=self.fillInIsa) menubar.add_cascade(label="File", menu=fileMenu) menubar.add_cascade(label="ZCGa", menu=zcgaMenu) menubar.add_cascade(label="ZDRa", menu=zdraMenu) menubar.add_cascade(label="GPSa", menu=gpsaMenu) self.txt = Text(self, yscrollcommand=scrollbar.set) self.txt.pack(fill=BOTH, expand=1) self.m2 = PanedWindow(m1, orient=VERTICAL) m1.add(self.m2) toplabel = Label(self.m2, text="Messages") toplabel.pack() self.top = ScrolledText(self.m2, wrap=WORD, state=DISABLED) self.m2.add(self.top) self.top.pack() bottomlabel = Label(self.m2, text="User input") bottomlabel.pack() self.bottom = ScrolledText(self.m2, wrap=WORD) self.m2.add(self.bottom) self.bottom.pack() scrollbar.config(command=self.txt.yview) self.txt.insert( END, "Please choose a specification by clicking on file then open") b = Button(self.m2, text="Submit Message", command=self.submitbutton) b.pack() self.file_opt = options = {} options['defaultextension'] = '.thy' options['filetypes'] = [('thy files', '.thy'), ('all files', '.*')] #self.topMessage.set("Please pick a specification from the top left") def totalisespec(self): self.gpsalocation = totalise.findgpsa(self.fl) if os.path.isfile(self.gpsalocation): self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Found Specifications") self.top.config(state=DISABLED) else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Please convert specification into GPSa first") self.top.config(state=DISABLED) def zdracheck(self): zdracheck.totalcheck(self.fl) #self.thedepgraph = zdracheck.creatdepgraphplot(self.fl) #self.thegoto = zdracheck.createplot(self.fl) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, zdracheck.printoutput()) self.top.config(state=DISABLED) self.depbutton = Button(self.m2, text="Show Dependency", command=self.showDependency) self.depbutton.pack() self.gotobutton = Button(self.m2, text="Show GoTo", command=self.showGoTo) self.gotobutton.pack() def zcgacheck(self): zcga.specCorrect(self.fl) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, zcga.printoutput()) self.top.config(state=DISABLED) def showGoTo(self): self.goto_location = totalise.find_goto_name(self.fl) gotoWindow = Toplevel() gotoWindow.title("GoTo Graph") canvas = Canvas(gotoWindow, width=600, height=600) canvas.pack() #photoimage = ImageTk.PhotoImage(file=self.goto_location) # canvas.create_image(300, 300, image=photoimage) gotoWindow.pack() #zdracheck.showplot(self.thegoto) def showDependency(self): self_dep_location = totalise.find_dp_name(self.fl) gotoWindow = Toplevel() gotoWindow.title("Dep Graph") canvas = Canvas(gotoWindow, width=600, height=600) canvas.pack() # photoimage = ImageTk.PhotoImage(file=self_dep_location) # canvas.create_image(300, 300, image=photoimage) gotoWindow.pack() #zdracheck.showplot(self.thedepgraph) def showgpsa(self): self.gpsalocation = totalise.findgpsa(self.fl) if os.path.isfile(self.gpsalocation): gpsawindow = Toplevel() gpsawindow.title("ProofPower Skeleton") gpsaspec = ScrolledText(gpsawindow, wrap=WORD) gpsaspec.pack() gpsaspecif = self.readFile(self.gpsalocation) gpsaspec.config(state=NORMAL) gpsaspec.insert(END, gpsaspecif) gpsaspec.config(state=DISABLED) else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Please convert specification into GPSa first") self.top.config(state=DISABLED) def showIsaSkel(self): self.Isalocation = totalise.findisagpsa(self.fl) if os.path.isfile(self.Isalocation): isawindow = Toplevel() isawindow.title("Isabelle Skeleton") isaspec = ScrolledText(isawindow, wrap=WORD) isaspec.pack() isaspecif = self.readFile(self.Isalocation) isaspec.config(state=NORMAL) isaspec.insert(END, isaspecif) isaspec.config(state=DISABLED) else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert( END, "Please convert specification into Isabelle Skeleton first") self.top.config(state=DISABLED) def fillInIsa(self): self.Isalocation = totalise.findisagpsa(self.fl) if os.path.isfile(self.Isalocation): if ('\\usepackage{zmathlang}' in open( self.fl).read()) or ('\\usepackage{zmathlang}' in open( self.fl).read()): self.Isalocation = totalise.findisagpsa(self.fl) zdra.x.fillinIsa(self.fl, self.Isalocation) zdra.x.fillinIsa(self.fl, self.Isalocation) zdra.x.fillNames(self.Isalocation) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Isabelle Skeleton successfully filled in ") self.top.config(state=DISABLED) else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Please select your isabelle skeleton:") self.top.config(state=DISABLED) filename = tkFileDialog.askopenfilename(**self.file_opt) zdra.x.fillinIsa(self.fl, filename) zdra.x.fillinIsa(self.fl, filename) zdra.x.fillNames(filename) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Isabelle Skeleton successfully filled in ") self.top.config(state=DISABLED) else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert( END, "Please convert specification into Isabelle Skeleton first") self.top.config(state=DISABLED) def askopenfilename(self): filename = tkFileDialog.askopenfilename(**self.file_opt) if filename: print filename def createppgpsa(self): zdra.createPPZskel(self.fl) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "ProofPower-Z Skeleton Created") self.top.config(state=DISABLED) self.gpsabutton = Button(self.m2, text="Show PP Skeleton", command=self.showgpsa) self.gpsabutton.pack() def createIsaPS(self): zdra.createIsaskel(self.fl) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Isabelle Skeleton Created") self.top.config(state=DISABLED) self.gpsabutton = Button(self.m2, text="Show Isabelle Skeleton", command=self.showIsaSkel) self.gpsabutton.pack() def showskeleton(self): self.skel_location = zdracheck.findskeleton(self.fl) if os.path.isfile(self.skel_location): skelwindow = Toplevel() skelwindow.title("Generalised Skeleton") skelspec = ScrolledText(skelwindow, wrap=WORD) skelspec.pack() skelspecif = self.readFile(self.skel_location) skelspec.insert(END, skelspecif) skelspec.config(state=DISABLED) else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Please convert specification into GPSa first") self.top.config(state=DISABLED) def createskeleton(self): if zdracheck.isthereanyloops() == False: zdracheck.createskeleton(self.fl) self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Skeleton Created") self.top.config(state=DISABLED) self.skelbutton = Button(self.m2, text="Show Skeleton", command=self.showskeleton) self.skelbutton.pack() else: self.top.config(state=NORMAL) self.top.delete(1.0, END) self.top.insert(END, "Loops in reasoning \nCan not create Skeleton") self.top.config(state=DISABLED) def submitbutton(self): print self.bottom.get("1.0", "end-1c") def onOpen(self): ftypes = [('Tex files', '*.tex'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) self.fl = dlg.show() if self.fl != '': self.txt.delete(1.0, END) self.text = self.readFile(self.fl) self.txt.insert(END, self.text) self.top.config(state=NORMAL) self.top.delete(1.0, END) def readFile(self, filename): f = open(filename, "r") text = f.read() return text
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 Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.serial_list = None self.updator = None self.news_list = None self.firmware_list = None # initialize widgets/UI self.createWindow(master, 1280, 800) self.createWidget(master) try: self.network_manager = NetworkManager(self) profile_path = os.path.join( os.path.join(os.path.split(os.path.realpath(__file__))[0]), "net.conf") profile_u_path = path_2_unicode(profile_path) self.network_manager.detect_network_queue() self.network_manager.load_config(profile_u_path) self.network_manager.run_tasks() self.network_manager.detect_serial_port() self.network_manager.detect_news() self.output_to_panel('success', 'Connecting remote end successfully!\n') except Exception as e: self.output_to_panel( 'error', 'Network manager setup failed! Details: ' + str(e) + '\n') self.init_ad_board() self.init_output_board() def show_firmware_details(self, event): lbx = event.widget index = lbx.curselection() size = len(index) if size > 0: for i in index[::-1]: self.firmware_text.delete(1.0, END) self.firmware_text.insert( END, 'Firmware:\n' + self.firmware_list[i]["name"] + '\n\n') self.firmware_text.see(END) details = self.firmware_list[i]["details"] for item in details: if item["type"] == "feature": self.firmware_text.insert(END, 'Features:\n') self.firmware_text.see(END) for index, descs in enumerate(item["description"]): self.firmware_text.insert(END, descs + '\n\n') self.firmware_text.see(END) elif item["type"] == "bug": self.firmware_text.insert(END, 'Bugs:\n') self.firmware_text.see(END) for index, descs in enumerate(item["description"]): self.firmware_text.insert(END, descs + '\n\n') self.firmware_text.see(END) self.firmware_text.see(END) def init_output_board(self): prompt_conf = { "info": "blue", "progress": "yellow", "success": "green", "error": "red" } for tag, color in prompt_conf.items(): self.info_text.tag_config(tag, foreground=color) def init_ad_board(self): prompt_conf = {"info": "blue", "warning": "yellow", "solved": "green"} for tag, color in prompt_conf.items(): self.news_text.tag_config(tag, foreground=color) def show_notice(self, level, msg): prompt = {} (prompt['info'], prompt['warning'], prompt['solved']) = ["☼", "☢", "☑"] if level in ['info', 'warning', 'solved']: self.news_text.insert(END, prompt[level], level) self.news_text.insert(END, ' ' + msg) self.news_text.see(END) def output_to_panel(self, level, msg): prompt = {} (prompt['info'], prompt['progress'], prompt['success'], prompt['error']) = ["☼", "➢", "✔", "✘"] if level in ['info', 'progress', 'success', 'error']: self.info_text.insert(END, prompt[level], level) self.info_text.insert(END, ' ' + msg) self.info_text.see(END) def createWindow(self, root, width, height): screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) root.geometry(size) root.maxsize(width, height) root.minsize(width, height) def createWidget(self, master): ft = tkFont.Font(family='Lucida Console', size=15) self.news_panel = Frame(master, width=450) self.news_panel.pack(side=LEFT, fill=Y) self.news_upper_menu = Frame(self.news_panel, height=10) self.news_upper_menu.pack(side=TOP, fill=X, pady=5) self.btn_connect_to_remote = Button(self.news_upper_menu, width=64, text="Reconnect to remote", height=1, command=self.reconnect_to_remote) self.btn_connect_to_remote.pack(side=LEFT, anchor="n", padx=10) self.news_board = Frame(self.news_panel) self.news_board.pack(side=TOP, fill=X, pady=5) self.news_text = ScrolledText(self.news_board, state="normal", width=66, height=10, font=ft, highlightbackground='black', highlightthickness=1) self.news_text.pack(side=LEFT, anchor="n", padx=5) self.firmware_board = Frame(self.news_panel) self.firmware_board.pack(side=TOP, fill=X, pady=5) firmware_list_ft = tkFont.Font(family='Lucida Console', size=12) self.lbx_firmware = Listbox(self.firmware_board, width=29, height=32, font=firmware_list_ft) self.lbx_firmware.pack(side=LEFT, anchor="n", padx=5) self.lbx_firmware.bind('<<ListboxSelect>>', self.show_firmware_details) self.firmware_text = ScrolledText(self.firmware_board, state="normal", width=44, height=34, font=firmware_list_ft, highlightbackground='black', highlightthickness=1) self.firmware_text.pack(side=LEFT, anchor="n", padx=5) self.news_lower_menu = Frame(self.news_panel, height=10) self.news_lower_menu.pack(side=TOP, fill=X, pady=5) self.btn_upgrade_from_remote = Button( self.news_lower_menu, width=64, text="Upgrade from remote", height=1, command=self.create_remote_upgrade_thread) self.btn_upgrade_from_remote.pack(side=LEFT, anchor="n", padx=10) self.user_panel = Frame(master) self.user_panel.pack(side=LEFT, fill=Y) self.user_upper_menu = Frame(self.user_panel, height=10) self.user_upper_menu.pack(side=TOP, fill=X, pady=5) self.lb_port_list = Label(self.user_upper_menu, text="Port:", width=6, height=1) self.lb_port_list.pack(side=LEFT, anchor="n", padx=5) self.port_item = StringVar() self.cb_port_list = ttk.Combobox(self.user_upper_menu, width=25, textvariable=self.port_item, state="readonly") self.cb_port_list["values"] = self.serial_list or ("Empty") self.cb_port_list.current(0) self.cb_port_list.pack(side=LEFT, anchor="w", padx=5) self.btn_select = Button(self.user_upper_menu, text="Select", height=1, width=18, command=self.select_firmware) self.btn_select.pack(side=LEFT, anchor="w", padx=10) self.btn_clear = Button(self.user_upper_menu, text="Clear", height=1, width=8, command=self.clear_info_text) self.btn_clear.pack(side=LEFT, anchor="w", padx=10) self.display_board = Frame(self.user_panel) self.display_board.pack(side=TOP, fill=X, pady=5) self.info_text = ScrolledText(self.display_board, state="normal", width=70, height=39, font=ft, highlightbackground='black', highlightthickness=1) self.info_text.bind("<KeyPress>", lambda e: "break") self.info_text.pack(side=LEFT, anchor="n", padx=5) self.info_text.drop_target_register('DND_Files') self.info_text.dnd_bind('<<Drop>>', self.drop_file) self.user_lower_menu = Frame(self.user_panel, height=10) self.user_lower_menu.pack(side=TOP, fill=X, pady=5) self.btn_upgrade_from_local = Button( self.user_lower_menu, width=64, text="Upgrade from local", height=1, command=self.create_upgrade_thread) self.btn_upgrade_from_local.pack(side=LEFT, anchor="n", padx=10) self.output_to_panel('info', "Drag and drop local firmware into here.\n") def drop_file(self, event): self.file_path = event.data if self.file_path is not None and self.file_path != "": self.output_to_panel('success', "Selected path: " + self.file_path + '\n') def select_firmware(self): self.file_path = filedialog.askopenfilename( filetypes=[('BIN', 'bin'), ('HEX', 'hex')]) if self.file_path is not None and self.file_path != "": self.output_to_panel('success', "Selected path: " + self.file_path + '\n') def clear_info_text(self): self.info_text.delete(1.0, END) def create_remote_upgrade_thread(self): index = self.lbx_firmware.curselection() size = len(index) if size > 0: remote_upgrade_thread = threading.Thread( target=self.start_to_remote_upgrade, args=(index)) remote_upgrade_thread.setDaemon(True) remote_upgrade_thread.start() else: self.output_to_panel( 'error', "You haven't selected any remote firmware!\n") def start_to_remote_upgrade(self, firmware_index): ''' self.btn_upgrade_from_local["state"] = "disabled" self.btn_upgrade_from_remote["state"] = "disabled" self.btn_connect_to_remote["state"] = "disabled" self.btn_select["state"] = "disabled" self.btn_clear["state"] = "disabled" ''' try: url = self.firmware_list[firmware_index]["url"] self.output_to_panel('info', 'Start to get firmware from remote...\n') r = requests.get(url) if r.status_code == 200: firmware_path = os.path.join( os.path.join(os.path.split(os.path.realpath(__file__))[0]), "Firmware", "origin", "firmware.zip") firmware_u_path = path_2_unicode(firmware_path) with open(firmware_u_path, "wb") as code: code.write(r.content) self.output_to_panel( 'success', 'Firmware downloaded to Firmware/origin/\n') elif r.status_code == 404: self.output_to_panel('error', 'Firmware doesn\'t exist\n') return else: self.output_to_panel( 'error', 'Firmware downloaded error! Details: code--%d\n' % r.status_code) return except Exception as e: self.output_to_panel( 'error', 'Firmware downloaded error! Details: ' + str(e) + '\n') return self.output_to_panel('info', 'Start to extract files from zip...\n') firmware_extract_path = os.path.join( os.path.join(os.path.split(os.path.realpath(__file__))[0]), "Firmware", "extract") firmware_extract_u_path = path_2_unicode(firmware_extract_path) self.target_file_list = [] try: f = zipfile.ZipFile(firmware_u_path, 'r') for file in f.namelist(): if '_S_' in file or 'hex' in file or 'HEX' in file: self.target_file_list.append(file) f.extract(file, firmware_extract_u_path) self.output_to_panel('success', 'Firmware extracted to Firmware/extract\n') except Exception as e: self.output_to_panel( 'error', 'Firmware extracted error! Details: ' + str(e) + '\n') return self.updator = FirmwareUpdator(self.info_text) profile_path = os.path.join( os.path.join(os.path.split(os.path.realpath(__file__))[0]), "default.conf") profile_u_path = path_2_unicode(profile_path) self.file_path = path_2_unicode( os.path.join(firmware_extract_path, self.target_file_list[0])) self.updator.update_firmware(profile_u_path, self.port_item.get(), self.file_path) ''' self.btn_upgrade_from_local["state"] = "normal" self.btn_upgrade_from_remote["state"] = "normal" self.btn_connect_to_remote["state"] = "normal" self.btn_select["state"] = "normal" self.btn_clear["state"] = "normal" ''' def create_upgrade_thread(self): if hasattr(self, 'file_path'): upgrade_thread = threading.Thread(target=self.start_to_upgrade, args=()) upgrade_thread.setDaemon(True) upgrade_thread.start() else: self.output_to_panel('error', "You haven't selected any firmware files!\n") def start_to_upgrade(self): self.btn_upgrade_from_local["state"] = "disabled" self.btn_upgrade_from_remote["state"] = "disabled" self.btn_connect_to_remote["state"] = "disabled" self.btn_select["state"] = "disabled" self.btn_clear["state"] = "disabled" self.updator = FirmwareUpdator(self.info_text) profile = os.path.join( os.path.split(os.path.realpath(__file__))[0], "default.conf") profile_path = os.path.join( os.path.join(os.path.split(os.path.realpath(__file__))[0]), "default.conf") profile_u_path = path_2_unicode(profile_path) self.updator.update_firmware(profile_u_path, self.port_item.get(), self.file_path) self.btn_upgrade_from_local["state"] = "normal" self.btn_upgrade_from_remote["state"] = "normal" self.btn_connect_to_remote["state"] = "normal" self.btn_select["state"] = "normal" self.btn_clear["state"] = "normal" def reconnect_to_remote(self): self.network_manager.run_tasks() self.output_to_panel('success', 'Reconnecting remote end successfully!\n') def close_connection(self): if self.updator is not None: self.updator.close_serial()
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 Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.serial_list = None self.createWindow(master, 680, 350) self.createWidget(master) def createWindow(self, root, width, height): screenwidth = root.winfo_screenwidth() screenheight = root.winfo_screenheight() size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2) root.geometry(size) root.maxsize(width, height) root.minsize(width, height) def createWidget(self, master): self.device_helper = DeviceHelper() self.device_helper.find_all_devices(self) self.menu = Frame(master, height=10, background="#f2f2f2") self.menu.pack(side=TOP, fill=X, pady=5) self.display_board = Frame(master, background="#f2f2f2") self.display_board.pack(side=TOP, fill=X) self.lb_port_list = Label(self.menu, text="Port:", width=4, background="#f2f2f2") self.lb_port_list.pack(side=LEFT, anchor="n", padx=5, pady=5) self.port_item = StringVar() self.cb_port_list = ttk.Combobox(self.menu, width=20, textvariable=self.port_item, state="readonly", background="#f2f2f2") self.cb_port_list["values"] = self.serial_list or ("Empty") self.cb_port_list.current(0) self.cb_port_list.pack(side=LEFT, anchor="w", pady=5) self.btn_select = Button(self.menu, text="Select", height=1, width=13, command=self.select_firmware, bg="#f2f2f2") self.btn_select.pack(side=LEFT, anchor="w", padx=10) self.btn_upgrade = Button(self.menu, text="Upgrade", height=1, width=13, command=self.create_upgrade_thread, bg="#f2f2f2") self.btn_upgrade.pack(side=LEFT, anchor="w", padx=10) self.btn_clear = Button(self.menu, text="Clear", height=1, width=8, command=self.clear_info_text, bg="#f2f2f2") self.btn_clear.pack(side=LEFT, anchor="w", padx=10) self.info_text = ScrolledText(self.display_board, state="normal", width=93) self.info_text.bind("<KeyPress>", lambda e: "break") self.info_text.pack(side=LEFT, anchor="n", padx=5, fill=Y) def select_firmware(self): self.file_path = filedialog.askopenfilename(filetypes=[('BIN', 'bin')]) if self.file_path is not None and self.file_path != "": self.info_text.insert( END, "New firmware file has been selected! Path:" + self.file_path + '\n') self.info_text.see(END) def clear_info_text(self): self.info_text.delete(1.0, END) def create_upgrade_thread(self): if hasattr(self, 'file_path'): tConnected = threading.Thread(target=self.start_to_upgrade, args=()) tConnected.setDaemon(True) tConnected.start() else: self.info_text.insert( END, "Error, you haven't selected any firmware files!\n") self.info_text.see(END) def start_to_upgrade(self): self.btn_upgrade["state"] = "disabled" updator = FirmwareUpdator(self.info_text) profile = os.path.join( os.path.split(os.path.realpath(__file__))[0], "default.conf") updator.update_firmware(profile, self.port_item.get(), self.file_path) self.btn_upgrade["state"] = "normal"
class editor: def __init__(self, master): frame = Frame(master, width=80, height=150) frame.pack() self.var = StringVar() menu = Menu(root) root.config(menu=menu) subMenu = Menu(menu) menu.add_cascade(label="File", menu=subMenu) subMenu.add_command(label="Open...\t\t Ctrl+O", command=self.open) subMenu.add_separator() subMenu.add_command(label="Exit\t\t Ctrl+Q", command=self.close) editMenu = Menu(menu) menu.add_cascade(label="Edit", menu=editMenu) editMenu.add_command(label="Find...\t Ctrl+F", command=self.fin) editMenu.add_separator() editMenu.add_command(label="Replace\t Ctrl+H", command=self.rep) editMenu.add_separator() editMenu.add_command(label="Reset", command=self.res) editMenu.add_separator() formatMenu = Menu(menu) menu.add_cascade(label="Format", menu=formatMenu) runMenu = Menu(menu) menu.add_cascade(label="Run", menu=runMenu) optionsMenu = Menu(menu) menu.add_cascade(label="Options", menu=optionsMenu) windowsMenu = Menu(menu) menu.add_cascade(label="Windows", menu=windowsMenu) helpMenu = Menu(menu) menu.add_cascade(label="Help", menu=helpMenu) self.text = ScrolledText(frame, width=70, height=25) self.text.grid(row=3, columnspan=3) self.text.tag_configure('t', background='green', foreground='white') def open(self): self.f = askopenfilename() self.var.set(self.f) self.display() def display(self): self.fr = open(str(self.f), 'r') n = self.fr.read() self.n = n if n != '': self.text.insert(END, str(n)) def res(self): self.e.delete(0, END) self.text.delete('1.0', END) def findword(self): self.text.tag_remove('t', '1.0', END) x = 0 r = re.compile(self.e.get()) self.fr.seek(0) z = self.fr.readline() count = 1 while z != '': y = r.search(z[x:]) if y: self.text.tag_add('t', str(count) + '.' + str(x + y.start()), str(count) + '.' + str(x + y.end())) x = x + y.end() + 1 continue count += 1 x = 0 z = self.fr.readline() def rep(self): window = Toplevel(root) self.nw(window) def fin(self): wind = Toplevel(root) self.win_n(wind) def win_n(self, master): frame = Frame(master) frame.pack() self.label1 = Label(frame, textvariable=self.var, padx=5, pady=5) self.label1.grid(row=0, columnspan=2) label2 = Label(frame, text='Enter word:-', padx=2, pady=10) label2.grid(row=0) self.label1 = Label(frame, textvariable=self.var, padx=5, pady=5) self.label1.grid(row=0, column=2) button1 = Button(frame, text="Find", command=self.findword) button1.grid(row=0, column=4) self.e = Entry(frame, width=20) self.e.grid(row=0, column=2) def nw(self, master): frame = Frame(master) frame.pack() label1 = Label(frame, text='Find:-') label1.grid(row=0) self.entry1 = Entry(frame) self.entry1.grid(row=0, column=1) label1 = Label(frame, text='Replace:-') label1.grid(row=1) self.entry2 = Entry(frame) self.entry2.grid(row=1, column=1) button1 = Button(frame, text="Replace", command=self.rep1) button1.grid(row=0, column=2) button2 = Button(frame, text="Replace all", command=self.rep2) button2.grid(row=1, column=2) button3 = Button(frame, text="close", command=self.close) button3.grid(row=2, column=1) def rep1(self): w = self.entry1.get() r = self.entry2.get() m = re.sub(w, r, self.n, 1) if m != '': self.text.delete(1.0, END) self.text.insert(END, str(m)) def rep2(self): w = self.entry1.get() r = self.entry2.get() m = re.sub(w, r, self.n) if m != '': self.text.delete(1.0, END) self.text.insert(END, str(m)) def close(self): tkMessageBox.showinfo("Close", "Close?") answer = tkMessageBox.askquestion("close", "Are You Sure?") if (answer == "yes"): print("Done")
class ScaleDemo(Frame): def smooth(self, x, window_len=11): s = numpy.r_[2 * x[0] - x[window_len - 1::-1], x, 2 * x[-1] - x[-1:-window_len:-1]] w = numpy.hanning(window_len) y = numpy.convolve(w / w.sum(), s, mode='same') return y[window_len:-window_len + 1] def __init__(self): self.fileName = "" self.rawData = "" self.processedData = "" self.file_loaded = False self.f = Frame.__init__(self) self.pack() self.master.title("Wheeze") self.master.geometry("1020x650") self.menu = Menu(self) self.master.config(menu=self.menu) self.tkMenu = Menu(self.menu) self.menu.add_cascade(label="File", menu=self.tkMenu) self.tkMenu.add_command(label="Open", command=self.readData) self.tkMenuData = Menu(self.menu) self.menu.add_cascade(label="Data", menu=self.tkMenuData) self.tkMenuData.add_command(label="Process", command=self.breath_stats) self.tkMenuData.add_command(label="Save", command=self.saveData) self.left_frame = Frame(height=150, width=50) self.left_frame.pack(side=LEFT, fill=BOTH, expand=1) self.right_frame = Frame(height=150, width=50) self.right_frame.pack(side=LEFT, fill=BOTH, expand=1) self.top_frame1 = Frame(self.left_frame, borderwidth=5, relief=RIDGE) self.top_frame1.pack(side=TOP, fill=BOTH, expand=1) self.bottom_frame1 = Frame( self.left_frame, borderwidth=5, relief=RIDGE, ) self.bottom_frame1.pack(side=BOTTOM, fill=BOTH, expand=1) self.top_frame2 = Frame(self.right_frame, borderwidth=5, relief=RIDGE) self.top_frame2.pack(side=TOP, fill=BOTH, expand=1) self.bottom_frame2 = Frame( self.right_frame, borderwidth=5, relief=RIDGE, ) self.bottom_frame2.pack(side=BOTTOM, fill=BOTH, expand=1) f = Figure(figsize=(5, 4), dpi=80) self.ax1 = f.add_subplot(121) self.ax4 = f.add_subplot(122) self.dataPlot = FigureCanvasTkAgg(f, master=self.top_frame2) self.dataPlot.get_tk_widget().pack(side=BOTTOM, fill=BOTH) f = Figure(figsize=(3, 4), dpi=65) self.ax2 = f.add_subplot(111) self.l1 = self.ax1.axvline(color='r') self.l2 = self.ax1.axvline(color='r') self.dataPlot2 = FigureCanvasTkAgg(f, master=self.top_frame1) self.dataPlot2.get_tk_widget().pack(side=TOP, fill=BOTH) f = Figure(figsize=(3, 4), dpi=65) self.dataPlot3 = FigureCanvasTkAgg(f, master=self.top_frame1) self.ax3 = f.add_subplot(111) self.dataPlot3.get_tk_widget().pack(side=TOP, fill=BOTH) self.scrolled_text = ScrolledText(self.bottom_frame2) self.scrolled_text.pack(side=TOP, fill=BOTH) self.control1 = Scale(self.bottom_frame1, from_=0, to=100, showvalue=0, orient=HORIZONTAL, command=self.updatePlot1) self.control1.pack(fill=X) self.control1.set(0) self.control2 = Scale(self.bottom_frame1, from_=0, to=100, showvalue=0, orient=HORIZONTAL, command=self.updatePlot2) self.control2.pack(fill=X) self.control2.set(100) self.control_smooth = Scale(self.bottom_frame1, from_=0, to=100, showvalue=1, orient=HORIZONTAL, command=self.updatePlot3) self.control_smooth.pack(fill=X) self.control_smooth.set(4) self.dataPlot.show() self.dataPlot2.show() def updatePlot1(self, scaleValue): end = int(scaleValue) self.l1.set_xdata(end) self.dataPlot3.draw() self.plot_data(self.control1.get(), self.control2.get(), self.control_smooth.get()) def updatePlot2(self, scaleValue): end = int(scaleValue) self.l2.set_xdata(end) self.dataPlot3.draw() self.plot_data(self.control1.get(), self.control2.get(), self.control_smooth.get()) def updatePlot3(self, scaleValue): self.plot_data(self.control1.get(), self.control2.get(), self.control_smooth.get()) def plot_data(self, start_data, end_data, smooth_val): if self.file_loaded == True: self.scrolled_text.delete(1.0, END) self.smooth_value = smooth_val self.ax1.clear() self.ax2.clear() self.ax4.clear() smooth_x, smooth_y = self.smooth_data(start_data, end_data, smooth_val) self.ax2.grid(True) self.ax2.plot(smooth_x, smooth_y, '-b') axis([0, len(self.rawy), -1, 1]) self.dataPlot2.draw() self.breaths = self.separate_breaths(smooth_x, smooth_y) for breath in self.breaths: self.ax1.plot(breath[1], breath[2], '-y') self.ax4.plot(breath[3], breath[2], '-y') self.ax1.grid(True) self.ax4.grid(True) self.dataPlot.draw() def saveData(self): if self.fileName != "": fileName = asksaveasfilename(title="Save breath data as", filetypes=[("csv file", ".csv"), ("All files", ".*")]) file = open(fileName, 'w') file.write('File Name') for lab in self.lables: file.write("," + lab) file.write("\n") for item in self.bstats: file.write(self.fileName) for d in item: file.write("," + str(d)) file.write("\n") file.close() def readData(self): self.fileName = askopenfilename(title="Open file", filetypes=[("txt file", ".txt"), ("All files", ".*")]) file = self.fileName self.file_loaded = True self.master.title("Wheeze-" + file) self.rawy = numpy.loadtxt(file, skiprows=1) self.rawx = [i for i in range(len(self.rawy))] self.ax3.clear() self.ax3.plot(self.rawx, self.rawy, '-b') self.ax3.grid(True) axis([0, len(self.rawy), -1, 1]) self.l1 = self.ax3.axvline(color='r') self.l2 = self.ax3.axvline(color='r') self.control1.configure(to=len(self.rawy)) self.control1.set(100) self.control2.configure(to=len(self.rawy)) self.control2.set(len(self.rawy)) self.plot_data(self.control1.get(), self.control2.get(), self.control_smooth.get()) def smooth_data(self, start_data, end_data, smooth_size): flow = self.rawy[start_data:end_data] time = [i / 100.0 for i in range(len(flow))] length = numpy.size(time) smooth_data_length = length - (2 * smooth_size) smooth_data_value = numpy.zeros((smooth_data_length, 2)) for i in range(smooth_size, length - smooth_size): smooth_data_value[i - smooth_size] = [ time[i], numpy.average(flow[i - smooth_size:i + smooth_size]) ] smooth_time = smooth_data_value[:, 0] smooth_flow = smooth_data_value[:, 1] zeroed = numpy.average(smooth_flow) for i in range(len(smooth_flow)): smooth_flow[i] -= zeroed return smooth_time, smooth_flow def separate_breaths(self, smooth_time, smooth_flow): def find_start(pos): flag = False if smooth_flow[pos] < 0: flag = True for i in range(1, 4): if smooth_flow[pos + i] < 0: flag = False return flag # seperate breaths breath = [] # 4 is number of +ve value after a -ve that corresponds to crossing # mid point for i in range(len(smooth_time) - 4): if find_start(i): breath.append(i) whole_breaths = (len(breath) // 2) * 2 - 1 breaths = [] for i in range( whole_breaths): # this ensures we only take whole breaths time = smooth_time[breath[i]:breath[i + 1] + 1] flow = smooth_flow[breath[i]:breath[i + 1] + 1] v = 0 volume = [] ztime = [0] flow_dif = [0] for i in range(len(flow)): v += (0.5 * (flow[i - 1] + flow[i]) * (time[i] - time[i - 1])) volume.append(v) flow_dif.append(volume[i] - volume[i - 1]) for i in range(1, len(time)): ztime.append(time[i] - time[0]) abreath = [time, ztime, flow, volume, flow_dif] breaths.append(abreath) return breaths def breath_stats(self): def binary_search(n_list, value_to_find, lo, hi): while lo < hi: mid = (lo + hi) // 2 midval = n_list[mid] if midval > value_to_find: lo = mid + 1 elif midval < value_to_find: hi = mid return mid def binary_search_neg(n_list, value_to_find, lo, hi): while lo < hi: mid = (lo + hi) // 2 midval = n_list[mid] if midval > value_to_find: lo = mid + 1 elif midval < value_to_find: hi = mid return mid def find_crossover(aflow): xpoint = 0 flag = False for pos in range(len(aflow)): if aflow[pos] > 0: flag = True for i in range(1, 4): if aflow[pos + i] > 0: flag = False if flag: xpoint = pos return xpoint def find_volume(start_at, finish_at, time, aflow): volume = 0.0 for i in range((start_at + 1), finish_at): volume += ( (aflow[i] + aflow[i - 1]) / 2.0) * (time[i] - time[i - 1]) return volume def find_cog(start_at, midpoint, aflow): i = start_at sumVol = 0.0 while sumVol + (-aflow[i] * 0.01) < midpoint: sumVol += (-aflow[i] * 0.01) i += 1 return i def find_centroid(tag, start_at, finish_at, volume, aflow): max_volume = max(volume[start_at:finish_at]) min_volume = min(volume[start_at:finish_at]) volume_range = max_volume - min_volume max_flow = max(aflow[start_at:finish_at]) min_flow = min(aflow[start_at:finish_at]) flow_range = max_flow - min_flow v_count = 0.0 f_count = 0.0 s_count = 0 count = 0 sa = finish_at - start_at for i in range(10000): c = int(random.random() * sa + start_at) f = random.random() * flow_range + min_flow if (tag and f >= aflow[c]) or ((tag == False) and f <= aflow[c]): v = volume[c] v_count += v f_count += f s_count += 1 v_est = v_count / s_count f_est = f_count / s_count return volume_range, flow_range, v_est, f_est def find_FVG_TNG(tag, start_at, finish_at, volume, aflow): max_volume = max(volume[start_at:finish_at]) min_volume = min(volume[start_at:finish_at]) volume_range = max_volume - min_volume max_flow = max(aflow[start_at:finish_at]) min_flow = min(aflow[start_at:finish_at]) flow_range = max_flow - min_flow v_count = 0.0 f_count = 0.0 s_count = 0 count = 0 for i in range(10000): f = random.random() * flow_range + min_flow v = random.random() * volume_range + min_volume if tag: count = binary_search(volume, v, start_at, finish_at) else: count = binary_search_neg(volume, v, start_at, finish_at) if (tag and f >= aflow[count]) or ((tag == False) and f >= aflow[count]): v_count += v f_count += f s_count += 1 v_est = v_count / s_count f_est = f_count / s_count return volume_range, flow_range, v_est, f_est def get_Slope(start_at, finish_at, sample, aflow): length = len(aflow[start_at:finish_at]) length20 = int(length * 0.2) + start_at length80 = int(length * 0.8) + start_at x2 = sample[start_at:length20] y2 = aflow[start_at:length20] # call liner regression for that data set slope, intercept, r_value, p_value, std_err = stats.linregress( x2, y2) angle_1 = math.degrees(math.atan(slope)) self.ax1.plot(x2, y2, '.' '-r') x2 = sample[length20:length80] y2 = aflow[length20:length80] self.ax1.plot(x2, y2, '.' '-g') # call liner regression for that data set slope, intercept, r_value, p_value, std_err = stats.linregress( x2, y2) angle_2 = math.degrees(math.atan(slope)) x2 = sample[length80:finish_at] y2 = aflow[length80:finish_at] self.ax1.plot(x2, y2, '.' '-b') # call liner regression for that data set slope, intercept, r_value, p_value, std_err = stats.linregress( x2, y2) angle_3 = math.degrees(math.atan(slope)) return angle_1, angle_2, angle_3 self.scrolled_text.delete(1.0, END) self.bstats = list() self.lables = [ 'Ttot', 'Ti', 'Pif', 'Tpif', 'Te', 'Pef', 'Tepf', 'Vt-in', 'Vt-out', 'Fvg_v', 'Fvg_f', 'vrange', 'frange', 'Fvg_v_in', 'fvg_f_in', 'vrange_in', 'frange_in', 'Cit', 'cif', 'trange', 'frange', 'Cit_in', 'cif_in', 'trange_in', 'frange_n', 'Tppef20', 'Tppef80' ] for seperate_breath in self.breaths: sample_time, breath_time, flow, volume, flow_dif = seperate_breath breathstat = list() sTtot = breath_time[-1] # total breath length x_over = find_crossover(flow) Ti = breath_time[x_over] sPif = max(flow) sTpif = breath_time[numpy.argmax(flow)] Te = breath_time[-1] - breath_time[x_over] sPef = min(flow[x_over:len(flow)]) sTepf = breath_time[numpy.argmin(flow)] - breath_time[x_over] in_Vol = find_volume(0, x_over, breath_time, flow) out_Vol = -find_volume(x_over, len(flow), breath_time, flow) vrange, flowrange, fvgtng_v, fvgtng_f = find_FVG_TNG( True, x_over, len(volume), volume, flow) vrangea, flowrangea, fvgtng_va, fvgtng_fa = find_centroid( False, 1, x_over, volume, flow) calc1 = fvgtng_v / vrange calc2 = fvgtng_f / flowrange trange, frange, Ci_t, Ci_f = find_centroid(True, x_over, len(breath_time), breath_time, flow) trangea, frangea, Ci_ta, Ci_fa = find_centroid( False, 1, x_over, breath_time, flow) a1, a2, a3 = get_Slope(numpy.argmin(flow), len(flow), breath_time, flow) Tppef20 = 180.0 - a1 + a2 Tppef80 = 180.0 - a3 + a2 breathstat.append(sTtot) breathstat.append(Ti), breathstat.append(sPif) breathstat.append(sTpif) breathstat.append(Te) breathstat.append(sPef) breathstat.append(sTepf) breathstat.append(in_Vol) breathstat.append(out_Vol) breathstat.append(fvgtng_v) breathstat.append(fvgtng_f) breathstat.append(vrange) breathstat.append(flowrange) breathstat.append(fvgtng_va) breathstat.append(fvgtng_fa) breathstat.append(vrangea) breathstat.append(flowrangea) breathstat.append(Ci_t) breathstat.append(Ci_f) breathstat.append(trange) breathstat.append(frange) breathstat.append(Ci_ta) breathstat.append(Ci_fa) breathstat.append(trangea) breathstat.append(frangea) breathstat.append(Tppef20) breathstat.append(Tppef80) self.bstats.append(breathstat) self.ax1.plot(Ci_t, Ci_f, 'o' '-r') self.ax4.plot(fvgtng_v, fvgtng_f, 'o' '-r') self.ax1.plot(Ci_ta, Ci_fa, 'o' '-r') self.ax4.plot(fvgtng_va, fvgtng_fa, 'o' '-r') self.dataPlot.draw() data_array = numpy.zeros((len(self.bstats), len(breathstat))) for indx, breath in enumerate(self.bstats): for indy, item in enumerate(breath): data_array[indx][indy] = item means = np.mean(data_array, axis=0) stdvs = np.std(data_array, axis=0) line = ("Number of breaths: %.2f \n" % len(self.bstats)) self.scrolled_text.insert(END, line) line = ("Smoothed: %.2f \n" % self.smooth_value) self.scrolled_text.insert(END, line) line = ("Start at: %.2f \n" % self.control1.get()) self.scrolled_text.insert(END, line) line = ("End at: %.2f \n" % self.control2.get()) self.scrolled_text.insert(END, line) for i, val in enumerate(means): line = " " + self.lables[i] + "\t \t" + ("%.2f \t" % val) + ( " %.2f \n" % stdvs[i]) self.scrolled_text.insert(END, line)
class App(): def __init__(self, root, conf): self.conf = conf self.items = conf.get_top_level_items() self.tree = ttk.Treeview(root, selectmode="browse", columns=("name", "value", "type"), displaycolumns=("value", "type"), height=30) ysb = ttk.Scrollbar(orient=VERTICAL, command= self.tree.yview) xsb = ttk.Scrollbar(orient=HORIZONTAL, command= self.tree.xview) self.tree.configure(yscroll=ysb.set, xscroll=xsb.set) self.tree.heading('#0', text='Configuration Tree', anchor='w') self.tree.column("#0", minwidth=0, width=800, stretch=True) self.tree.heading("name", text="Name") self.tree.column("name", minwidth=0, width=200, stretch=True) self.tree.heading("value", text="Value") self.tree.column("value", minwidth=0, width=50, stretch=True) self.tree.heading("type", text="Type") self.tree.column("type", minwidth=0, width=50, stretch=True) self.add_root_items(self.items) self.help = ScrolledText(root, width=130, height=10) self.msg = StringVar() self.info = Label(root, fg="green", font=("Helvetica", 16), anchor=W, justify=LEFT, textvariable=self.msg) self.msg.set("Please set configurations, then you can save it!") self.tree.grid(row=0, column=0) self.help.grid(row=1, column=0) self.info.grid(row=2, column=0) ysb.grid(row=0, column=1, sticky='ns') xsb.grid(row=1, column=0, sticky='ew') root.grid() self.root = root # create a toplevel menu menubar = Menu(root) menubar.add_command(label="Save Config!", command=self.OnSaveConfig) menubar.add_command(label="Quit Config!", command=self.OnQuitConfig) # display the menu root.config(menu=menubar) self.tree.bind("<Double-1>", self.OnDoubleClick) self.tree.bind("<<TreeviewSelect>>", self.OnSelection) def add_subr_items(self, parent, items): for item in items: if item.get_visibility() != "n": if item.is_symbol(): str = 'config {0}'.format(item.get_name()) self.tree.insert(parent, "end", text=str, values=[item.get_name(), item.get_value(), kconf.TYPENAME[item.get_type()]], open=True) elif item.is_menu(): str = 'menu "{0}"'.format(item.get_title()) parent = self.tree.insert(parent, "end", text=str, open=True) self.add_subr_items(parent, item.get_items()) elif item.is_choice(): str = 'choice "{0}"'.format(item.get_prompts()[0]) parent = self.tree.insert(parent, "end", text=str, open=True) self.add_subr_items(parent, item.get_items()) elif item.is_comment(): str = 'comment "{0}"'.format(item.get_text()) self.tree.insert(parent, "end", text=str, open=True) def add_root_items(self, items): for item in items: if item.get_visibility() != "n": if item.is_symbol(): str = 'config {0}'.format(item.get_name()) self.tree.insert("", "end", text=str, values=[item.get_name(), item.get_value(), kconf.TYPENAME[item.get_type()]], open=True) elif item.is_menu(): str = 'menu "{0}"'.format(item.get_title()) parent = self.tree.insert("", "end", text=str, open=True) self.add_subr_items(parent, item.get_items()) elif item.is_choice(): str = 'choice "{0}"'.format(item.get_prompts()[0]) parent = self.tree.insert("", "end", text=str, open=True) self.add_subr_items(parent, item.get_items()) elif item.is_comment(): str = 'comment "{0}"'.format(item.get_text()) self.tree.insert("", "end", text=str, open=True) def search_for_item(self, name, item=None): children = self.tree.get_children(item) for child in children: nameval = self.tree.set(child, "name") if nameval == name: return child else: res = self.search_for_item(name, child) if res: return res return None def OnDoubleClick(self, event): mitem = self.tree.identify('item',event.x, event.y) nameval = self.tree.set(mitem, "name") symbol = self.conf.get_symbol(nameval) if symbol is None: return if (symbol.get_type() == kconf.BOOL or (symbol.get_type() == kconf.TRISTATE and not self.conf.is_tristate_enabled())): if (symbol.is_choice_symbol() and len(symbol.get_parent().get_items()) == 1): self.msg.set("A boolean choice, exactly one config option must be set to y, so no change here!") return if (symbol.get_value() == "y"): print("Setting " + symbol.get_name() + " to n") symbol.set_user_value("n") if (symbol.get_value() == "y"): self.msg.set("A boolean choice that is the only 'y' in the choice group can not be set to 'n'") symbol.set_user_value("y") return self.tree.set(mitem, "value", symbol.get_value()) else: print("Setting " + symbol.get_name() + " to y") symbol.set_user_value("y") self.tree.set(mitem, "value", symbol.get_value()) print("Dependents for " + symbol.get_name() + " {" + symbol.get_visibility() + "} " + " [" + symbol.get_value() + "]:") for sym in symbol.get_dependent_symbols(): print(sym.get_name() + " {"+sym.get_visibility() + "} " + " [" + sym.get_value() + "] ") mitem = self.search_for_item(sym.get_name(), None) if (mitem): self.tree.set(mitem, "value", sym.get_value()) print("========================================") elif (symbol.get_type() == kconf.TRISTATE and self.conf.is_tristate_enabled()): nono = False if (symbol.is_choice_symbol() and len(symbol.get_parent().get_items()) == 1): self.msg.set("A single tristate choice in one choice group can not be set to 'n'") nono = True # 'y'->'m'->'n'->'y'->'m'->'n'->... if (symbol.get_value() == "y"): print("Setting " + symbol.get_name() + " to m") symbol.set_user_value("m") if (symbol.get_value() == "y"): self.msg.set("A tristate choice that is the only 'y' in the choice group can not be set to 'n'") symbol.set_user_value("y") return self.tree.set(mitem, "value", symbol.get_value()) elif (symbol.get_value() == "m"): print("Setting " + symbol.get_name() + " to n") symbol.set_user_value("n") if (symbol.get_value() == "m"): self.msg.set("A tristate choice that is the only 'm' in the choice group can not be set to 'n'") symbol.set_user_value("m") return self.tree.set(mitem, "value", symbol.get_value()) else: print("Setting " + symbol.get_name() + " to y") symbol.set_user_value("y") self.tree.set(mitem, "value", symbol.get_value()) print("Dependents for " + symbol.get_name() + " {" + symbol.get_visibility() + "} " + " [" + symbol.get_value() + "]:") for sym in symbol.get_dependent_symbols(): print(sym.get_name() + " {"+sym.get_visibility() + "} " + " [" + sym.get_value() + "] ") mitem = self.search_for_item(sym.get_name(), None) if (mitem): self.tree.set(mitem, "value", sym.get_value()) print("========================================") elif (symbol.get_type() == kconf.INT or symbol.get_type() == kconf.HEX or symbol.get_type() == kconf.STRING): self.pop = PopupWindow(self.root, symbol.get_name(), symbol.get_value()) self.root.wait_window(self.pop.top) if (self.pop.v == True): print("Setting " + symbol.get_name() + " to " + self.pop.value) symbol.set_user_value(self.pop.value) print("Now " + symbol.get_name() + " is " + symbol.get_value()) self.tree.set(mitem, "value", symbol.get_value()) return def OnSelection(self, event): mitem = self.tree.focus() values = self.tree.item(mitem,"values"); if (values): symbol = self.conf.get_symbol(values[0]) if (symbol): self.msg.set("Please Double Click to update config option value!") self.help.delete(1.0, END) help = symbol.get_help() if (help): self.help.insert(INSERT, help) return def OnSaveConfig(self): self.conf.write_config(".config") self.conf.write_config_python("config.py") header_dir = conf.get_config_header_dir() dstfile = os.path.join(header_dir, "config.h") dstdir = os.path.split(dstfile)[0] if not os.path.exists(dstdir): os.makedirs(dstdir) self.conf.write_config_header(dstfile) self.msg.set("Configurations Saved!") return def OnQuitConfig(self): self.root.quit() return
class ScaleDemo(Frame): def smooth(self,x,window_len=11): s=numpy.r_[2*x[0]-x[window_len-1::-1],x,2*x[-1]-x[-1:-window_len:-1]] w=numpy.hanning(window_len) y=numpy.convolve(w/w.sum(),s,mode='same') return y[window_len:-window_len+1] def __init__(self): self.fileName="" self.rawData="" self.processedData="" self.file_loaded = False self.f = Frame.__init__(self) self.pack() self.master.title("Wheeze") self.master.geometry("1020x650") self.menu = Menu(self) self.master.config(menu=self.menu) self.tkMenu = Menu(self.menu) self.menu.add_cascade(label="File", menu=self.tkMenu) self.tkMenu.add_command(label="Open", command=self.readData) self.tkMenuData = Menu(self.menu) self.menu.add_cascade(label="Data", menu=self.tkMenuData) self.tkMenuData.add_command(label="Process", command=self.breath_stats) self.tkMenuData.add_command(label="Save", command=self.saveData) self.left_frame = Frame(height=150, width=50) self.left_frame.pack(side=LEFT, fill=BOTH, expand=1) self.right_frame = Frame(height=150, width=50) self.right_frame.pack(side=LEFT, fill=BOTH, expand=1) self.top_frame1 = Frame(self.left_frame, borderwidth=5, relief=RIDGE) self.top_frame1.pack(side=TOP, fill=BOTH, expand=1) self.bottom_frame1 = Frame(self.left_frame, borderwidth=5, relief=RIDGE,) self.bottom_frame1.pack(side=BOTTOM, fill=BOTH, expand=1) self.top_frame2 = Frame(self.right_frame, borderwidth=5, relief=RIDGE) self.top_frame2.pack(side=TOP, fill=BOTH, expand=1) self.bottom_frame2 = Frame(self.right_frame, borderwidth=5, relief=RIDGE,) self.bottom_frame2.pack(side=BOTTOM, fill=BOTH, expand=1) f = Figure(figsize=(5, 4), dpi=80) self.ax1 = f.add_subplot(121) self.ax4 = f.add_subplot(122) self.dataPlot = FigureCanvasTkAgg(f, master=self.top_frame2) self.dataPlot.get_tk_widget().pack(side=BOTTOM, fill=BOTH) f = Figure(figsize=(3, 4), dpi=65) self.ax2 = f.add_subplot(111) self.l1 = self.ax1.axvline(color='r') self.l2 = self.ax1.axvline(color='r') self.dataPlot2 = FigureCanvasTkAgg(f, master=self.top_frame1) self.dataPlot2.get_tk_widget().pack(side=TOP, fill=BOTH) f = Figure(figsize=(3, 4), dpi=65) self.dataPlot3 = FigureCanvasTkAgg(f, master=self.top_frame1) self.ax3 = f.add_subplot(111) self.dataPlot3.get_tk_widget().pack(side=TOP, fill=BOTH) self.scrolled_text = ScrolledText(self.bottom_frame2) self.scrolled_text.pack(side=TOP, fill=BOTH) self.control1 = Scale(self.bottom_frame1 , from_=0, to=100, showvalue=0, orient=HORIZONTAL, command=self.updatePlot1) self.control1.pack(fill=X) self.control1.set(0) self.control2 = Scale(self.bottom_frame1 , from_=0, to=100, showvalue=0, orient=HORIZONTAL, command=self.updatePlot2) self.control2.pack(fill=X) self.control2.set(100) self.control_smooth = Scale(self.bottom_frame1 , from_=0, to=100, showvalue=1, orient=HORIZONTAL, command=self.updatePlot3) self.control_smooth.pack(fill=X) self.control_smooth.set(4) self.dataPlot.show() self.dataPlot2.show() def updatePlot1(self, scaleValue): end = int(scaleValue) self.l1.set_xdata(end) self.dataPlot3.draw() self.plot_data(self.control1.get(), self.control2.get(),self.control_smooth.get()) def updatePlot2(self, scaleValue): end = int(scaleValue) self.l2.set_xdata(end) self.dataPlot3.draw() self.plot_data(self.control1.get(), self.control2.get(),self.control_smooth.get()) def updatePlot3(self,scaleValue): self.plot_data(self.control1.get(), self.control2.get(),self.control_smooth.get()) def plot_data(self, start_data, end_data,smooth_val): if self.file_loaded == True : self.scrolled_text.delete(1.0, END) self.smooth_value = smooth_val self.ax1.clear() self.ax2.clear() self.ax4.clear() smooth_x, smooth_y = self.smooth_data(start_data, end_data,smooth_val) self.ax2.grid(True) self.ax2.plot(smooth_x, smooth_y, '-b'); axis([0, len(self.rawy), -1, 1]) self.dataPlot2.draw() self.breaths = self.separate_breaths(smooth_x, smooth_y) for breath in self.breaths: self.ax1.plot(breath[1], breath[2], '-y') self.ax4.plot(breath[3], breath[2], '-y') self.ax1.grid(True) self.ax4.grid(True) self.dataPlot.draw() def saveData(self): if self.fileName !="": fileName = asksaveasfilename(title="Save breath data as", filetypes=[("csv file",".csv"),("All files",".*")]) file = open(fileName,'w') file.write('File Name') for lab in self.lables: file.write(","+lab) file.write("\n") for item in self.bstats: file.write(self.fileName) for d in item: file.write(","+str(d)) file.write("\n") file.close() def readData(self): self.fileName = askopenfilename(title="Open file", filetypes=[("txt file",".txt"),("All files",".*")]) file = self.fileName self.file_loaded = True self.master.title("Wheeze-"+file) self.rawy = numpy.loadtxt(file, skiprows=1) self.rawx = [i for i in range(len(self.rawy))] self.ax3.clear() self.ax3.plot(self.rawx, self.rawy, '-b') self.ax3.grid(True) axis([0, len(self.rawy), -1, 1]) self.l1 = self.ax3.axvline(color='r') self.l2 = self.ax3.axvline(color='r') self.control1.configure(to=len(self.rawy)) self.control1.set(100) self.control2.configure(to=len(self.rawy)) self.control2.set(len(self.rawy)) self.plot_data(self.control1.get(), self.control2.get(),self.control_smooth.get()) def smooth_data(self, start_data, end_data,smooth_size): flow = self.rawy[start_data:end_data] time = [i / 100.0 for i in range(len(flow))] length = numpy.size(time) smooth_data_length = length - (2 * smooth_size) smooth_data_value = numpy.zeros((smooth_data_length, 2)) for i in range(smooth_size, length - smooth_size): smooth_data_value[i - smooth_size] = [time[i], numpy.average(flow[i - smooth_size:i + smooth_size])] smooth_time = smooth_data_value[:, 0] smooth_flow = smooth_data_value[:, 1] zeroed = numpy.average(smooth_flow) for i in range(len(smooth_flow)): smooth_flow[i]-=zeroed return smooth_time, smooth_flow def separate_breaths(self, smooth_time, smooth_flow): def find_start(pos): flag = False if smooth_flow[pos] < 0: flag = True for i in range(1, 4): if smooth_flow[pos + i] < 0: flag = False return flag # seperate breaths breath = [] # 4 is number of +ve value after a -ve that corresponds to crossing # mid point for i in range(len(smooth_time) - 4): if find_start(i): breath.append(i) whole_breaths = (len(breath) // 2) * 2 - 1 breaths = [] for i in range(whole_breaths): # this ensures we only take whole breaths time = smooth_time[breath[i]:breath[i + 1] + 1] flow = smooth_flow[breath[i]:breath[i + 1] + 1] v=0 volume=[] ztime=[0] flow_dif =[0] for i in range(len(flow)): v+=(0.5*(flow[i-1]+flow[i])*(time[i]-time[i-1])) volume.append(v) flow_dif.append(volume[i]-volume[i-1]) for i in range(1,len(time)): ztime.append(time[i] - time[0]) abreath = [time,ztime, flow,volume,flow_dif] breaths.append(abreath) return breaths def breath_stats(self): def binary_search(n_list, value_to_find, lo, hi): while lo < hi: mid = (lo+hi)//2 midval = n_list[mid] if midval > value_to_find: lo = mid+1 elif midval < value_to_find: hi = mid return mid def binary_search_neg(n_list, value_to_find, lo, hi): while lo < hi: mid = (lo+hi)//2 midval = n_list[mid] if midval > value_to_find: lo = mid+1 elif midval < value_to_find: hi = mid return mid def find_crossover(aflow): xpoint = 0 flag = False for pos in range(len(aflow)): if aflow[pos]>0 : flag = True for i in range(1,4): if aflow[pos+i] >0: flag = False if flag: xpoint = pos return xpoint def find_volume(start_at,finish_at,time,aflow): volume = 0.0 for i in range((start_at+1),finish_at): volume += ((aflow[i]+aflow[i-1])/2.0)*(time[i]-time[i-1]) return volume def find_cog(start_at,midpoint,aflow): i=start_at sumVol=0.0 while sumVol+(-aflow[i]*0.01)<midpoint: sumVol+=(-aflow[i]*0.01) i+=1 return i def find_centroid(tag,start_at,finish_at,volume,aflow): max_volume = max(volume[start_at:finish_at]) min_volume = min(volume[start_at:finish_at]) volume_range = max_volume-min_volume max_flow = max(aflow[start_at:finish_at]) min_flow = min(aflow[start_at:finish_at]) flow_range = max_flow-min_flow v_count = 0.0 f_count = 0.0 s_count = 0 count =0 sa = finish_at-start_at for i in range(10000): c = int(random.random()*sa+start_at) f = random.random()*flow_range+min_flow if (tag and f>= aflow[c]) or ((tag==False) and f<= aflow[c]): v = volume[c] v_count+=v f_count+=f s_count+=1 v_est = v_count/s_count f_est = f_count/s_count return volume_range, flow_range,v_est , f_est def find_FVG_TNG(tag,start_at,finish_at,volume,aflow): max_volume = max(volume[start_at:finish_at]) min_volume = min(volume[start_at:finish_at]) volume_range = max_volume-min_volume max_flow = max(aflow[start_at:finish_at]) min_flow = min(aflow[start_at:finish_at]) flow_range = max_flow-min_flow v_count = 0.0 f_count = 0.0 s_count = 0 count =0 for i in range(10000): f = random.random()*flow_range+min_flow v = random.random()*volume_range+min_volume if tag: count = binary_search(volume,v,start_at,finish_at) else: count = binary_search_neg(volume,v,start_at,finish_at) if (tag and f>= aflow[count]) or ((tag==False) and f>= aflow[count]): v_count+=v f_count+=f s_count+=1 v_est = v_count/s_count f_est = f_count/s_count return volume_range, flow_range,v_est , f_est def get_Slope(start_at,finish_at,sample,aflow): length = len(aflow[start_at:finish_at]) length20 = int(length*0.2)+start_at length80 = int(length*0.8)+start_at x2 = sample[start_at:length20] y2 = aflow[start_at:length20] # call liner regression for that data set slope, intercept, r_value, p_value, std_err = stats.linregress(x2,y2) angle_1 = math.degrees(math.atan(slope)) self.ax1.plot(x2,y2,'.' '-r') x2 = sample[length20:length80] y2 = aflow[length20:length80] self.ax1.plot(x2,y2,'.' '-g') # call liner regression for that data set slope, intercept, r_value, p_value, std_err = stats.linregress(x2,y2) angle_2 = math.degrees(math.atan(slope)) x2 = sample[length80:finish_at] y2 = aflow[length80:finish_at] self.ax1.plot(x2,y2,'.' '-b') # call liner regression for that data set slope, intercept, r_value, p_value, std_err = stats.linregress(x2,y2) angle_3 = math.degrees(math.atan(slope)) return angle_1, angle_2, angle_3 self.scrolled_text.delete(1.0, END) self.bstats=list() self.lables = ['Ttot','Ti','Pif','Tpif','Te','Pef','Tepf','Vt-in','Vt-out','Fvg_v','Fvg_f','vrange','frange','Fvg_v_in','fvg_f_in','vrange_in','frange_in','Cit','cif','trange','frange','Cit_in','cif_in','trange_in','frange_n','Tppef20','Tppef80'] for seperate_breath in self.breaths: sample_time,breath_time, flow,volume,flow_dif = seperate_breath breathstat=list() sTtot = breath_time[-1] # total breath length x_over = find_crossover(flow) Ti = breath_time[x_over] sPif = max(flow) sTpif = breath_time[numpy.argmax(flow)] Te = breath_time[-1]-breath_time[x_over] sPef = min(flow[x_over:len(flow)]) sTepf = breath_time[numpy.argmin(flow)] - breath_time[x_over] in_Vol = find_volume(0,x_over,breath_time,flow) out_Vol = -find_volume(x_over,len(flow),breath_time,flow) vrange, flowrange, fvgtng_v, fvgtng_f = find_FVG_TNG(True,x_over,len(volume),volume,flow) vrangea, flowrangea, fvgtng_va, fvgtng_fa = find_centroid(False,1,x_over,volume,flow) calc1 = fvgtng_v/vrange calc2 = fvgtng_f/flowrange trange, frange,Ci_t, Ci_f = find_centroid(True,x_over,len(breath_time),breath_time,flow) trangea, frangea,Ci_ta, Ci_fa = find_centroid(False,1,x_over,breath_time,flow) a1,a2,a3 = get_Slope(numpy.argmin(flow),len(flow),breath_time,flow) Tppef20 = 180.0-a1+a2 Tppef80 = 180.0-a3+a2 breathstat.append(sTtot) breathstat.append(Ti), breathstat.append(sPif) breathstat.append(sTpif) breathstat.append(Te) breathstat.append(sPef) breathstat.append(sTepf) breathstat.append(in_Vol) breathstat.append(out_Vol) breathstat.append(fvgtng_v) breathstat.append(fvgtng_f) breathstat.append(vrange) breathstat.append(flowrange) breathstat.append(fvgtng_va) breathstat.append(fvgtng_fa) breathstat.append(vrangea) breathstat.append(flowrangea) breathstat.append(Ci_t) breathstat.append(Ci_f) breathstat.append(trange) breathstat.append(frange) breathstat.append(Ci_ta) breathstat.append(Ci_fa) breathstat.append(trangea) breathstat.append(frangea) breathstat.append(Tppef20) breathstat.append(Tppef80) self.bstats.append(breathstat) self.ax1.plot(Ci_t, Ci_f ,'o' '-r') self.ax4.plot(fvgtng_v, fvgtng_f ,'o' '-r') self.ax1.plot(Ci_ta, Ci_fa ,'o' '-r') self.ax4.plot(fvgtng_va, fvgtng_fa ,'o' '-r') self.dataPlot.draw() data_array = numpy.zeros((len(self.bstats),len(breathstat))) for indx, breath in enumerate(self.bstats): for indy, item in enumerate(breath): data_array[indx][indy] = item means = np.mean(data_array, axis=0) stdvs = np.std(data_array, axis=0) line = ("Number of breaths: %.2f \n" % len(self.bstats)) self.scrolled_text.insert(END, line) line = ("Smoothed: %.2f \n" % self.smooth_value) self.scrolled_text.insert(END, line) line = ("Start at: %.2f \n" % self.control1.get()) self.scrolled_text.insert(END, line) line = ("End at: %.2f \n" % self.control2.get()) self.scrolled_text.insert(END, line) for i, val in enumerate(means): line = " "+self.lables[i]+"\t \t"+("%.2f \t" % val)+(" %.2f \n" % stdvs[i]) self.scrolled_text.insert(END, line)
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 createGUI: calcComp = calculateGrade() def __init__(self): self.window = Tk() self.window.title("ENGR102 Numerical Grade Calculator") self.window.geometry('900x600') #Draws the Gui def drawElements(self): self.lbl1 = Label(self.window, text="MP1 % ") self.lbl1.grid(column=0, row=0) self.txt1 = Entry(self.window, width=10) self.txt1.grid(column=1, row=0) self.lbl2 = Label(self.window, text="MP2 % ") self.lbl2.grid(column=2, row=0) self.txt2 = Entry(self.window, width=10) self.txt2.grid(column=3, row=0) self.lbl3 = Label(self.window, text="MP3 % ") self.lbl3.grid(column=4, row=0) self.txt3 = Entry(self.window, width=10) self.txt3.grid(column=5, row=0) self.lbl4 = Label(self.window, text="MP4 % ") self.lbl4.grid(column=6, row=0) self.txt4 = Entry(self.window, width=10) self.txt4.grid(column=7, row=0) self.lbl5 = Label(self.window, text="MP5 % ") self.lbl5.grid(column=8, row=0) self.txt5 = Entry(self.window, width=10) self.txt5.grid(column=9, row=0) self.midterm = Label(self.window, text="Midterm % ", height=2) self.midterm.grid(column=0, row=1) self.txt6 = Entry(self.window, width=10) self.txt6.grid(column=1, row=1) self.final = Label(self.window, text="Final % ", height=2) self.final.grid(column=0, row=2) self.txt7 = Entry(self.window, width=10) self.txt7.grid(column=1, row=2) self.attendence = Label(self.window, text="Attendence % ", height=2) self.attendence.grid(column=0, row=3) self.txt8 = Entry(self.window, width=10) self.txt8.grid(column=1, row=3) self.gradingFile = Label(self.window, text="Grading File ", height=2) self.gradingFile.grid(column=4, row=2) self.uploadGradingFile = Button(self.window, text="Browse", bg="orange", fg="black", command=self.openGradeSheet) self.uploadGradingFile.grid(column=5, row=2) self.gradingFileName = Label(self.window, text="", height=2) self.gradingFileName.grid(column=6, row=2) self.attendenceFile = Label(self.window, text="Attendence File ", height=2) self.attendenceFile.grid(column=4, row=3) self.uploadattendenceFile = Button(self.window, text="Browse", bg="orange", fg="black", command=self.openAttendenceSheet) self.uploadattendenceFile.grid(column=5, row=3) self.attendenceFileName = Label(self.window, text="", height=2) self.attendenceFileName.grid(column=6, row=3) self.calculateBtn = Button( self.window, text="Calculate", height=2, bg="orange", fg="black", command=self.initWeightage) #createGUI.calcComp.importData) self.calculateBtn.grid(column=4, row=8) self.saveBtn = Button(self.window, text="Save", height=2, bg="orange", fg="black") self.saveBtn.grid(column=5, row=8) self.txt = ScrolledText(self.window, width=100, height=20) self.txt.place(x=100, y=200) self.printData() self.window.mainloop() # This method is called on clicking calculate button. And stores the weightage assigned to diferent assessments. def initWeightage(self): createGUI.calcComp.MP1 = float(self.txt1.get()) createGUI.calcComp.MP2 = float(self.txt2.get()) createGUI.calcComp.MP3 = float(self.txt3.get()) createGUI.calcComp.MP4 = float(self.txt4.get()) createGUI.calcComp.MP5 = float(self.txt5.get()) createGUI.calcComp.MIDTERM = float(self.txt6.get()) createGUI.calcComp.FINAL = float(self.txt7.get()) createGUI.calcComp.ATTENDENCE = float(self.txt8.get()) #When total assignments weightage doesn't sum to 100, this error is popped. if createGUI.calcComp.checkTotal() == False: tkMessageBox.showerror( 'Error', 'The assessment components do NOT sum up to 100') #Else grades are calculated and displayed on Text area. else: self.data, self.students = createGUI.calcComp.importData() self.updateResult() #This method is called to open a file Dialog for uploading grade sheet. def openGradeSheet(self): filename = tkFileDialog.askopenfilename( initialdir="/", title="Select file", filetypes=(("all files", "*.*"), ("jpeg files", "*.jpg"))) print filename createGUI.calcComp.gradingSheet = filename #self.gradingFileName.configure(text=filename) #This method is called to open a file Dialog for uploading Attendence sheet. def openAttendenceSheet(self): filename = tkFileDialog.askopenfilename( initialdir="/", title="Select file", filetypes=(("all files", "*.*"), ("jpeg files", "*.jpg"))) print filename createGUI.calcComp.attendenceSheet = filename #self.attendenceFileName.configure(text=filename) #This method prints the grades on the scrollable text region. def printData(self): if (os.path.exists('grades.xlsx')): self.txt.delete(1.0, END) book1 = xlrd.open_workbook('grades.xlsx') grades = book1.sheet_by_index(0) i = 0 result = "" while True: try: name = grades.cell(i, 0).value result += (name + "\t\t") score = grades.cell(i, 1).value result += (str(score) + "\n") i += 1 except: break print result self.txt.insert(INSERT, result) #update result on the text area. def updateResult(self): self.txt.delete(1.0, END) result = "" for i in self.students: result += i + "\t\t" result += (str(self.data[i]) + "\n") self.txt.insert(INSERT, result)
class HTMLViewer(Toplevel): """ Basic class which provides a scrollable area for viewing HTML text and a Dismiss button """ def __init__(self, htmlcode, title, master=None): Toplevel.__init__(self, master) #self.protocol('WM_DELETE_WINDOW',self.withdraw) self.titleprefix = title color = self.config("bg")[4] borderFrame = Frame(self, relief=SUNKEN, bd=2) # Extra Frame self.text = ScrolledText(borderFrame, relief=FLAT, padx=3, pady=3, background='white', #background=color, #foreground="black", wrap='word', width=60, height=20, spacing1=3, spacing2=2, spacing3=3) self.text.pack(expand=1, fill=BOTH) #self.text.insert('0.0', text) self.text['state'] = DISABLED borderFrame.pack(side=TOP,expand=1,fill=BOTH) box = Frame(self) w = Button(box, text="Dismiss", width=10, command=self.doWithdraw, default=ACTIVE) w.pack(side=RIGHT, padx=5, pady=5) self.bind("<Return>", self.doWithdraw) box.pack(side=BOTTOM,fill=BOTH) self.setStyle() self.insert(htmlcode) def setStyle(self): baseSize = 14 self.text.config(font="Times %d" % baseSize) self.text.tag_config('h1', font="Times %d bold" % (baseSize + 8)) self.text.tag_config('h2', font="Times %d bold" % (baseSize + 6)) self.text.tag_config('h3', font="Times %d bold" % (baseSize + 4)) self.text.tag_config('h4', font="Times %d bold" % (baseSize + 2)) self.text.tag_config('h5', font="Times %d bold" % (baseSize + 1)) self.text.tag_config('b', font="Times %d bold" % baseSize) self.text.tag_config('em', font="Times %d italic" % baseSize) self.text.tag_config('pre', font="Courier %d" % baseSize) self.text.tag_config('tt', font="Courier %d" % baseSize) def doWithdraw(self, event=None): # Need to eat optional event so that we can use is in both button and bind callback self.withdraw() def Update(self,htmlcode, title): self.titleprefix = title self.insert(htmlcode) def insert(self, htmlcode): self.text['state'] = NORMAL self.text.delete('0.0', END) writer = HTMLWriter(self.text, self) format = formatter.AbstractFormatter(writer) #parser = htmllib.HTMLParser(format) parser = MyHTMLParser(format, self.text) parser.nofill=False parser.feed(htmlcode) parser.close() self.text['state'] = DISABLED if parser.title != None: self.title(self.titleprefix + " - " + parser.title) else: self.title(self.titleprefix)
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 App(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.set_style() self.master.grid() self.create_widgets() sys.stdout = TextEmit(self.st2, 'stdout') sys.stderr = TextEmit(self.st2, 'stderr') self.cached_dict_of_dict = {} def set_style(self): s = ttk.Style() s.configure('TButton', padding=(5)) s.configure('TCombobox', padding=(5)) s.configure('exe.TButton', foreground='red') def parse_data(self): data_file = self.com.get() print('\n[Data File]: %s' % data_file) print('=' * 52) user_input = self.st1.get('0.1', 'end-1c') query_list = CSV_Dict.get_query_list(user_input) if data_file and query_list: if data_file not in self.cached_dict_of_dict: c = CSV_Dict.from_raw_data(os.path.join(DATA_PAHT, data_file)) current_dict = c.detailed_dict self.cached_dict_of_dict[data_file] = current_dict else: current_dict = self.cached_dict_of_dict[data_file] print('[Dictionary count]: %s\n' % len(current_dict.keys())) print('\n' + '=' * 52) CSV_Dict.do_query(query_list, current_dict) print('===== [Mission Complete] =====\n') else: sys.stderr.write('----- [Mission Failed] -----\n') print('\n') def clear_output(self): self.st2.configure(state='normal') self.st2.delete('1.0', 'end') self.st2.configure(state='disabled') def show_summary_of_data_file(self): data_file = os.path.join(DATA_PAHT, self.com.get()) base_name = self.com.get() if not os.path.isfile(data_file): sys.stderr.write('>>>>> [Error]: Data file does not exist: %s\n' % data_file) print('\n[Show Data File Summary] %s' % base_name) print('=' * 52) with open(data_file, 'r') as f: for i, line in enumerate(f): if i < SUMMARY_LINE: print('[ %d ] %s' % (i, line.strip())) else: print('[ 10] ... ...') print('[...] ... ...') break def create_widgets(self): self.content = ttk.Frame(self.master, padding=(5)) self.b1 = ttk.Button(self.content, text='Clear Query') self.combo_value = StringVar() self.com = ttk.Combobox(self.content, textvariable=self.combo_value, state='readonly') if not os.path.isdir(DATA_PAHT): os.mkdir(data_folder) self.com['values'] = os.listdir(DATA_PAHT) if len(self.com['values']) > 0: self.com.current(0) else: sys.stderr.write('Please put csv data file in data folder and ' 'restart this program.') self.b2 = ttk.Button(self.content, text='Data Summary', command=self.show_summary_of_data_file) self.b3 = ttk.Button(self.content, text='Query', style='exe.TButton') self.b4 = ttk.Button(self.content, text='Clear Log') self.st1 = ScrolledText(self.content) self.st2 = ScrolledText(self.content) self.b1.grid(row=0, column=0, sticky=(W)) self.b2.grid(row=0, column=1, sticky=(E)) self.com.grid(row=0, column=1, sticky=(W+E)) self.b3.grid(row=0, column=2, sticky=(W)) self.b4.grid(row=0, column=3, sticky=(E)) self.st1.grid(row=1, column=0, columnspan=2, sticky=(W+E+S+N)) self.st2.grid(row=1, column=2, columnspan=2, sticky=(W+E+S+N)) self.content.grid(row=0, column=0, sticky=(W+E+S+N)) self.b1['command'] = lambda: self.st1.delete('0.1', 'end') self.b3['command'] = self.parse_data self.b4['command'] = self.clear_output self.master.rowconfigure(0, weight=1) self.master.columnconfigure(0, weight=1) self.content.rowconfigure(0, weight=0) self.content.rowconfigure(1, weight=1) self.content.columnconfigure(0, weight=1) self.content.columnconfigure(1, weight=1) self.content.columnconfigure(2, weight=1) self.content.columnconfigure(3, weight=1) self.st1.focus()
class SimpleTextEditor: def __init__(self, parent): self.parent = parent self.textWidget = ScrolledText(parent, width=80, height=50, font=(tkFont.Font(family= "Consolas", size= "12"))) self.textWidget.pack() self.menuBar = tk.Menu(parent, tearoff=0) # About Menu self.about_menu = tk.Menu(self.menuBar, tearoff= 0) self.menuBar.add_cascade(label= "Text Perfect", menu= self.about_menu) self.about_menu.add_command(label= "About", command= self.about_command) # File Menu self.file_menu = tk.Menu(self.menuBar, tearoff = 0) self.menuBar.add_cascade(label = "File", menu=self.file_menu) self.file_menu.add_command(label="New", command=self.new_command, accelerator="Cmd+N") self.parent.bind_all("<Command-n>", self.new_command) self.parent.bind_all("<Command-N>", self.new_command) self.file_menu.add_command(label="New Tab", command=self.new_tab, accelerator="Cmd+Opt+N") self.parent.bind_all("<Command-Option-n>", self.new_tab) self.parent.bind_all("<Command-Option-N>", self.new_tab) self.file_menu.add_separator() self.file_menu.add_command(label="Open", command=self.open_command, accelerator="Cmd+O") self.parent.bind_all("<Command-o>", self.open_command) self.parent.bind_all("<Command-O>", self.open_command) self.file_menu.add_command(label="Save", command=self.save_command, accelerator="Cmd+S") self.parent.bind_all("<Command-s>", self.save_command) self.parent.bind_all("<Command-S>", self.save_command) self.file_menu.add_separator() self.file_menu.add_command(label= "Quit", command= self.exit_program, accelerator="Cmd+W") self.parent.bind_all("<Command-w>", self.exit_program) self.parent.bind_all("<Command-W>", self.exit_program) # Edit Menu self.edit_menu = tk.Menu(self.menuBar, tearoff=0) self.menuBar.add_cascade(label= "Edit", menu= self.edit_menu) self.edit_menu.add_command(label = "Cut", command = self.cut_command, accelerator="Cmd+X") self.parent.bind_all("<Command-Shift-x>", self.cut_command) self.parent.bind_all("<Command-Shift-X>", self.cut_command) self.edit_menu.add_command(label = "Copy", command = self.copy_command, accelerator="Cmd+C") self.parent.bind_all("<Command-Shift-c>", self.copy_command) self.parent.bind_all("<Command-Shift-C>", self.copy_command) self.edit_menu.add_command(label = "Paste", command = self.paste_command, accelerator="Cmd+V") self.parent.bind_all("<Command-Shift-v>", self.paste_command) self.parent.bind_all("<Command-Shift-V>", self.paste_command) self.edit_menu.add_separator() self.edit_menu.add_command(label= "Find", command= self.find_command) parent.config(menu=self.menuBar) ################################################## def open_command(self, event=None): file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Select a file') if file != None: contents = file.read() self.textWidget.insert("1.0",contents) file.close() def save_command(self, event=None): file = tkFileDialog.asksaveasfile(mode= 'w') if file != None: data = self.textWidget.get("1.0", END+'-1c') #strip trailing \n at EOF file.write(data) file.close() def exit_program(self, event=None): if tkMessageBox.askokcancel("Quit", "Are you sure you want to quit?"): self.parent.destroy() #Opens up new text widget correctly but screws up closing the parent window via the menu def new_command(self, event=None): win = Toplevel() SimpleTextEditor.__init__(self, win) #Currently under construction def new_tab(self, event=None): #self.parent.add(self.textWidget, text="new tab", state='normal') new_frame = tk.Frame(self.parent) self.parent.add(new_frame, text='new', state='normal') def cut_command(self, event=None): text = self.textWidget.get(SEL_FIRST, SEL_LAST) self.textWidget.delete(SEL_FIRST, SEL_LAST) self.textWidget.clipboard_clear() self.textWidget.clipboard_append(text) def copy_command(self, event=None): text = self.textWidget.get(SEL_FIRST, SEL_LAST) self.textWidget.clipboard_clear() self.textWidget.clipboard_append(text) def paste_command(self, event=None): try: text = self.textWidget.selection_get(selection= 'CLIPBOARD') self.textWidget.insert(INSERT, text) except TclError: pass def find_command(self): # Currently only works for highlighted text and will only find one match to the string, not all of the instances # Also does not work with key binding because of askstring hanging window bug :/ target = askstring('SimpleEditor', 'Search String?') if target: where = self.textWidget.search(target, INSERT, END) if where: print where pastit = where + ('+%dc' % len(target)) self.textWidget.tag_add(SEL, where, pastit) self.textWidget.mark_set(INSERT, pastit) self.textWidget.see(INSERT) self.textWidget.focus() def about_command(self): label = tkMessageBox.showinfo("About", "A super duper simple text editor. It's now available through github, thanks to Jason!") #dummy function as a place holder while constructing further functionality def dummy_funct(self, event=None): print"The life of a function is often very lonely..."
class TkApp(tk.Tk): def __init__(self, className=" TextMate"): tk.Tk.__init__(self, className=className) self.textPad = ScrolledText(self, width=50, height=30, font=("Monospace Regular", 13), highlightthickness=0, bd=4, undo="True") self.iconbitmap(r'te.ico') self.textPad.pack() menu = tk.Menu(self) self.textPad.tag_config("bt", background="yellow") self.textPad.tag_config("kw", foreground="medium sea green") self.textPad.tag_config("com", foreground="red") self.textPad.tag_config("str", foreground="purple") self.config(menu=menu) filemenu = tk.Menu(menu) menu.add_cascade(label="File", menu=filemenu) filemenu.add_command(label="New File", command=self.new_command, accelerator="Ctrl+N") self.bind_all("<Control-n>",self.new_command) filemenu.add_command(label="Open", command=self.open_command, accelerator="Ctrl+O") self.bind_all("<Control-o>",self.open_command) filemenu.add_separator() filemenu.add_command(label="Save", command=self.save_command, accelerator="Ctrl+S") self.bind_all("<Control-s>",self.save_command) filemenu.add_command(label="Save As", command=self.saveas_command, accelerator="Ctrl+Shift+S") self.bind_all("<Control-Shift-S>",self.saveas_command) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.exit_command, accelerator="Ctrl+Q") self.bind_all("<Control-q>",self.exit_command) editmenu=tk.Menu(menu) menu.add_cascade(label="Edit", menu=editmenu) editmenu.add_command(label="Undo", command=self.undo_command, accelerator="Ctrl+Z") editmenu.add_command(label="Redo", command=self.redo_command, accelerator="Ctrl+Shift+Z") self.bind_all("<Control-Shift-Z>",self.redo_command) editmenu.add_separator() editmenu.add_command(label="Cut", command=self.cut_command, accelerator="Ctrl+X") editmenu.add_command(label="Copy", command=self.copy_command, accelerator="Ctrl+C") editmenu.add_command(label="Paste", command=self.paste_command, accelerator="Ctrl+V") editmenu.add_separator() editmenu.add_command(label="Select All", command=self.selectall_command, accelerator="Ctrl+A") self.bind_all("<Control-a>",self.selectall_command) editmenu.add_command(label="Delete All", command=self.deleteall_command, accelerator="Ctrl+D") self.bind_all("<Control-d>",self.deleteall_command) formatmenu = tk.Menu(menu) menu.add_cascade(label="Format", menu=formatmenu) formatmenu.add_command(label="Font", command=self.font_command, accelerator="Ctrl+M") self.bind_all("<Control-m>",self.font_command) formatmenu.add_separator() formatmenu.add_command(label="Bold", command=self.bold_command, accelerator="Ctrl+B") self.bind_all("<Control-b>",self.bold_command) formatmenu.add_command(label="Italics", command=self.italic_command, accelerator="Ctrl+I") self.bind_all("<Control-i>",self.italic_command) formatmenu.add_command(label="Underline", command=self.underline_command, accelerator="Ctrl+U") self.bind_all("<Control-u>",self.underline_command) formatmenu.add_command(label="Bold-Italic", command=self.bolditalic_command) preferences = tk.Menu(menu) menu.add_cascade(label="Preferences", menu=preferences) preferences.add_radiobutton(label="Text Mode", command =self.text_command) preferences.add_radiobutton(label="Code Mode", command =self.code_command) toolsmenu = tk.Menu(menu) menu.add_cascade(label="Tools", menu=toolsmenu) toolsmenu.add_command(label="Find", command=self.find_command, accelerator="Ctrl+F") self.bind_all("<Control-f>",self.find_command) toolsmenu.add_command(label="Replace", command=self.replace_command, accelerator="Ctrl+H") self.bind_all("<Control-h>",self.replace_command) toolsmenu.add_separator() toolsmenu.add_command(label="Spell Check", command=self.spellcheck_command) toolsmenu.add_command(label="Translate", command=self.translate_command) toolsmenu.add_command(label="Brace Matching", command=self.braces_command) toolsmenu.add_command(label="Document Comparision", command=self.comparedoc_command) helpmenu = tk.Menu(menu) menu.add_cascade(label="Help", menu=helpmenu) helpmenu.add_command(label="About", command=self.about_command) def new_command(self,*args): new=TkApp() def open_command(self,*args): data = self.textPad.get('1.0', 'end-1c') flag=0 for i in data: if(i!='\n'): flag=1 break if(not(flag)): file = askopenfile(mode='rb',title='Select a file') if file != None: self.deleteall_command(self,*args) contents = file.read() self.textPad.insert('1.0',contents) file.close() else: if(askokcancel("Save", "You have unsaved changes. Save?")): self.save_command(self,*args) file = askopenfile(mode='rb',title='Select a file') if file != None: self.deleteall_command(self,*args) contents = file.read() self.textPad.insert('1.0',contents) file.close() global filename if(file!=None): a=[x for x in str(file).split("'")] filename=a[1] def save_command(self,*args): contents = self.textPad.get('1.0','end-1c') global filename try: with open(filename, 'w') as outputFile: outputFile.write(contents) except IOError: self.saveas_command() def saveas_command(self,*args): file = asksaveasfile(mode = 'w', title='Save As') if file != None: data = self.textPad.get('1.0', 'end-1c') file.write(data) file.close() global filename a=[x for x in str(file).split("'")] filename=a[1] def exit_command(self,*args): data = self.textPad.get('1.0', 'end-1c') flag=0 for i in data: if(i!='\n'): flag=1 break if(flag): if(askokcancel("Save", "Save before closing?")): self.save_command(self,*args) self.destroy() else: if(askokcancel("Quit", "Are you sure you want to quit?")): self.destroy() def code_command(self,*args): self.bind("<Key>",self.auto_indent,add="+") self.bind("<Return>",self.keep_indent) self.bind("<Key>",self.keywords_command,add="+") self.bind("<Key>",self.comment_command,add="+") self.bind("<Key>",self.string_command,add="+") def text_command(self,*args): self.unbind("<Key>") self.unbind("<Return>") def copy_command(self,*args): try: self.clipboard_clear() text = self.textPad.get("sel.first", "sel.last") self.clipboard_append(text) except: pass def paste_command(self,*args): try: text = self.selection_get(selection='CLIPBOARD') self.textPad.insert('insert', text) except: pass def cut_command(self,*args): try: self.copy_command() self.textPad.delete("sel.first", "sel.last") except: pass def selectall_command(self,*args): self.textPad.tag_add('sel','1.0', 'end') def deleteall_command(self,*args): self.textPad.delete('1.0', 'end') def undo_command(self,*args): try: self.textPad.edit_undo() except: pass def redo_command(self,*args): try: self.textPad.edit_redo() except: pass def find_command(self,*args): search=askstring("Find", "") if(search==None): return l=len(search) data = self.textPad.get('1.0', 'end-1c') ind=[m.start() for m in finditer(search,data)] for i in ind: corpus=data[:i] last=0 line_no=1 k=0 for j in corpus: k+=1 if(j=='\n'): line_no+=1 last=k st=str(line_no)+'.'+str(i-last) end=str(line_no)+'.'+str(i-last+l) self.textPad.tag_add('bt',st,end) def replace_command(self,*args): search=askstring("Find", "") rep=askstring("Replace with", "") if(search==None or rep==None): return l=len(search) data = self.textPad.get('1.0', 'end-1c') ind=[m.start() for m in finditer(search,data)] for count in range(len(ind)): data = self.textPad.get('1.0', 'end-1c') if(search in data): i=data.index(search) corpus=data[:i] last=0 line_no=1 k=0 for j in corpus: k+=1 if(j=='\n'): line_no+=1 last=k st=str(line_no)+'.'+str(i-last) end=str(line_no)+'.'+str(i-last+l) self.textPad.delete(st,end) self.textPad.insert(st,rep) def about_command(self,*args): label = showinfo("TextMate", "A small and lightweight text editor.\n© 2017. All rights reserved.") def braces_command(self,*args): data = self.textPad.get('1.0', 'end-1c') a=[] for i in data: if(i=='(' or i=='{' or i=='['): a.append(i) if(i==')'): if(a==[] or a[-1]!='('): label = showinfo("Brace Matching","Parenthesis don't match") return else: a.pop() if(i=='}'): if(a==[] or a[-1]!='{'): label = showinfo("Brace Matching","Curly braces don't match") return else: a.pop() if(i==']'): if(a==[] or a[-1]!='['): label = showinfo("Brace Matching","Square braces don't match") return else: a.pop() if(a==[]): label = showinfo("Brace Matching","All braces match!") else: ch=a[-1] if(ch=='('): label = showinfo("Brace Matching","Parenthesis don't match") return elif(ch=='{'): label = showinfo("Brace Matching","Curly braces don't match") return else: label = showinfo("Brace Matching","Square braces don't match") return def spellcheck_command(self,*args): dic=Dict("en_US") data=word_tokenize(self.textPad.get('1.0', 'end-1c')) for word in data: if not dic.check(word) and word.isalpha(): suggestions_list=dic.suggest(word) suggestions_str="" for w in suggestions_list: suggestions_str+=w+" " showinfo("Suggestions for '"+word+"'\n",suggestions_str) showinfo("Spell Check","Finished checking!") def translate_command(self,*args): try: translator = Translator() text = self.textPad.get("sel.first", "sel.last") language = askstring("Translate", "Kannada | Hindi | Tamil | Telugu | English") if language.lower() == "kannada": language = "kn" elif language.lower() == "hindi": language = "hi" elif language.lower() == "telugu": language = "te" elif language.lower() == "tamil": language = "ta" elif language.lower() == "english": language = "en" s = translator.translate(text, dest = language) self.textPad.delete("sel.first", "sel.last") self.textPad.insert('insert', s.text) except: pass def keywords_command(self,event): C_keywords=["auto","double","int","struct","break","else","long", "switch","case","enum","register","typedef","char","extern", "return","union","const","float","short","unsigned","do", "continue","for","signed","void","default","goto","sizeof", "volatile","if","static","while","printf","scanf","include"] for key in C_keywords: l=len(key) data = self.textPad.get('1.0', 'end-1c') ind=[m.start() for m in finditer(key,data)] for i in ind: corpus=data[:i] last=0 line_no=1 k=0 for j in corpus: k+=1 if(j=='\n'): line_no+=1 last=k st=str(line_no)+'.'+str(i-last) end=str(line_no)+'.'+str(i-last+l) self.textPad.tag_add('kw',st,end) def comparedoc_command(self,*args): cmpfile = askopenfile(mode='rb',title='Select a file to compare with') if cmpfile != None: contents = cmpfile.read() cmpfile.close() data = self.textPad.get('1.0', 'end-1c') line=[x for x in contents.split("\n")] line1=[x for x in data.split("\n")] num=min(len(line),len(line1)) x=1 for i in range(num): s=str(line[i]) s1=str(line1[i]) s=sub(r'\s','',s) s1=sub(r'\s','',s1) if(s==s1): xy=str(x)+'.0' xy1=str(x)+'.54' self.textPad.tag_add('sel',xy,xy1) x+=1 def keep_indent(self,event): try: if self.brace_count != 0: text = self.brace_count*" " self.textPad.insert('insert', text) except: pass brace_count = 0 def auto_indent(self,event): try: if event.char == '{': self.brace_count += 1 text = "\n"+(self.brace_count*" ") self.textPad.insert('insert', text) if event.char == '}': self.brace_count -= 1 text = "\n"+(self.brace_count*" ") self.textPad.insert('insert', text) except: pass def comment_command(self,event): data = self.textPad.get('1.0', 'end-1c') search="\/\*" ind=[m.start() for m in finditer(search,data)] for i in ind: corpus=data[:i] last=0 line_no=1 k=0 for j in corpus: k+=1 if(j=='\n'): line_no+=1 last=k st=str(line_no)+'.'+str(i-last) find=data[i+2:] flag=0 if("*/" in find): la=(find.index("*/"))+1 last1=0 k=0 for j in range(la): k+=1 if(find[j]=='\n'): flag=1 line_no+=1 last1=k if(flag==0): end=str(line_no)+'.'+str(la+i-last+3) else: end=str(line_no)+'.'+str(la-last1+1) else: end='end-1c' self.textPad.tag_add('com',st,end) data = self.textPad.get('1.0', 'end-1c') ind1=[m.start() for m in finditer("//",data)] for i in ind1: corpus=data[:i] last=0 line_no=1 k=0 for j in corpus: k+=1 if(j=='\n'): line_no+=1 last=k st=str(line_no)+'.'+str(i-last) end=str(line_no)+'.100' self.textPad.tag_add('com',st,end) def string_command(self,event): data = self.textPad.get('1.0', 'end-1c') search="\"" ind=[m.start() for m in finditer(search,data)] bool=0 for i in ind: bool+=1 if(bool%2==0): continue corpus=data[:i] last=0 line_no=1 k=0 for j in corpus: k+=1 if(j=='\n'): line_no+=1 last=k st=str(line_no)+'.'+str(i-last) find=data[i+1:] flag=0 if("\"" in find): la=(find.index("\"")) last1=0 k=0 for j in range(la): k+=1 if(find[j]=='\n'): flag=1 line_no+=1 last1=k if(flag==0): end=str(line_no)+'.'+str(la+i-last+2) else: end=str(line_no)+'.'+str(la-last1+1) else: end='end-1c' self.textPad.tag_add('str',st,end) def bold_command(self,*args): current_tags = self.textPad.tag_names() bold = Font(self.textPad, self.textPad.cget("font")) bold.config(weight="bold") self.textPad.tag_config("bld", font=bold) if "bld" in current_tags: self.textPad.tag_delete("bld", '1.0', 'end-1c') else: self.textPad.tag_add("bld", '1.0', 'end-1c') def italic_command(self,*args): current_tags = self.textPad.tag_names() italics = Font(self.textPad, self.textPad.cget("font")) italics.config(slant="italic") self.textPad.tag_config("ita", font=italics) if "ita" in current_tags: self.textPad.tag_delete("ita", '1.0', 'end-1c') else: self.textPad.tag_add("ita", '1.0', 'end-1c') def underline_command(self,*args): current_tags = self.textPad.tag_names() underline = Font(self.textPad, self.textPad.cget("font")) underline.config(underline=True) self.textPad.tag_config("und", font=underline) if "und" in current_tags: self.textPad.tag_delete("und", '1.0', 'end-1c') else: self.textPad.tag_add("und", '1.0', 'end-1c') def bolditalic_command(self,*args): current_tags = self.textPad.tag_names() bold_italic = Font(self.textPad, self.textPad.cget("font")) bold_italic.config(weight="bold",slant="italic") self.textPad.tag_config("bldita", font=bold_italic) if "bldita" in current_tags: self.textPad.tag_delete("bldita", '1.0', 'end-1c') else: self.textPad.tag_add("bldita", '1.0', 'end-1c') def font_command(self,*args): try: font_specs = askstring("Font", "Font Style-Font Size") font_specs = font_specs.split('-') new_font = Font(self.textPad, self.textPad.cget("font")) new_font.config(family=font_specs[0], size=font_specs[1]) self.textPad.tag_config("newfont", font=new_font) self.textPad.tag_add("newfont", '1.0', 'end-1c') except: pass
class UI: def __init__(self, password): self.password = password self.window = Tk() self.day = StringVar() self.day.set(date.today().day) self.month = StringVar() self.month.set(date.today().month) self.year = StringVar() self.year.set(date.today().year) self.text = StringVar() self.dateFrame = Frame(self.window) self.dateFrame["padx"] = 20 self.dateFrame["pady"] = 10 self.dateFrame.pack() self.dayL = Label(self.dateFrame) self.dayL["text"] = "Tag:" self.dayL.pack(side='left', padx=10) self.dayI = Entry(self.dateFrame) self.dayI["width"] = 5 self.dayI["textvariable"] = self.day self.dayI.pack(side='left', padx=5) self.monthL = Label(self.dateFrame) self.monthL["text"] = "Monat:" self.monthL.pack(side='left', padx=5) self.monthI = Entry(self.dateFrame) self.monthI["width"] = 5 self.monthI["textvariable"] = self.month self.monthI.pack(side='left', padx=5) self.yearL = Label(self.dateFrame) self.yearL["text"] = "Jahr:" self.yearL.pack(side='left', padx=5) self.yearI = Entry(self.dateFrame) self.yearI["width"] = 5 self.yearI["textvariable"] = self.year self.yearI.pack(side='left', padx=5) self.button = Button(self.dateFrame) self.button["text"] = "Erstellen" self.button["width"] = 20 self.button["command"] = self.buttonCallback self.button.pack(side='left', padx=20) self.textI = ScrolledText(self.window) self.updateTextI("e") self.textI.pack() self.exportB = Button(self.window) self.exportB["text"] = "Export" self.exportB["width"] = 20 self.exportB["command"] = self.exportButtonCallback self.exportB.pack(pady=15) self.buttonCallback() self.window.mainloop() def updateTextI(self, t): self.textI.delete("1.0", END) self.textI.insert(END, t) def buttonCallback(self): d = "%s-%s-%s" % (self.year.get(), self.month.get(), self.day.get()) #print(getAccountingString(d)) self.updateTextI(getAccountingString(d, self.password)) def exportButtonCallback(self): pass
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 MainWnd: def __init__(self, parent): self.search_str = StringVar() self.parent = parent root.protocol("WM_DELETE_WINDOW", self.ask_quit) self.parent.title("snippets") self.parent.configure(padx=10, pady=10) self.parent.minsize(630, 480) self.create_widgets() db_path = os.path.join(abspath(dirname(__file__)), "snip.db") db_exists = os.path.isfile(db_path) self.connection = sqlite3.connect(db_path) self.connection.row_factory = dict_factory self.cursor = self.connection.cursor() if not db_exists: self.cursor.execute('create table snippet (caption, content)') self.fill_list() self.snip_content.focus_set() def ask_quit(self): if tkMessageBox.askokcancel("Quit", "You want to quit now?"): self.parent.destroy() def __del__(self): self.connection.close() def create_widgets(self): self.search_box = Entry(self.parent, textvariable=self.search_str) self.search_str.set("New snippet") self.search_box.pack(fill=X) self.toolbar_f = Frame(self.parent, pady=5) self.toolbar_f.pack(fill=X) self.newbtn = Button(self.toolbar_f, text="New", command=self.on_new) self.newbtn.pack(side=LEFT) self.savebtn = Button(self.toolbar_f, text="Save", command=self.on_save) self.savebtn.pack(side=LEFT) self.updatebtn = Button(self.toolbar_f, text="Update", command=self.on_update) self.updatebtn.pack(side=LEFT) self.delbtn = Button(self.toolbar_f, text="Delete", command=self.on_delete) self.delbtn.pack(side=LEFT) self.copybtn = Button(self.toolbar_f, text="Copy to clipboard", command=self.on_copy) self.copybtn.pack(side=LEFT) self.quitbtn = Button(self.toolbar_f, text="Quit", command=self.on_quit) self.quitbtn.pack(side=LEFT) self.pwin = PanedWindow(self.parent, showhandle=True) self.pwin.pack(fill=BOTH, expand=1) self.list_f = Frame(self.pwin) self.list_sb = Scrollbar(self.list_f, orient=VERTICAL) self.snip_list = Listbox(self.list_f, yscrollcommand=self.list_sb.set) self.list_sb.config(command=self.snip_list.yview) self.snip_list.bind('<ButtonRelease-1>', self.on_snippet_selected) self.snip_list.pack(side=LEFT, fill=BOTH, expand=1) self.list_sb.pack(side=RIGHT, fill=Y) self.pwin.add(self.list_f) self.pwin.paneconfigure(self.list_f, minsize=177) self.snippetFont = Font(family="courier", size=11, weight=NORMAL) self.snip_content = ScrolledText(self.pwin, height=20, width=40, padx=5, pady=5, font=self.snippetFont) self.pwin.add(self.snip_content) # noinspection PyTypeChecker def fill_list(self): self.snip_list.delete(0, END) self.cursor.execute('select * from snippet') for r in self.cursor.fetchall(): self.snip_list.insert(END, r['caption']) def on_new(self): self.search_str.set("") self.snip_content.delete(1.0, END) def on_save(self): self.cursor.execute( 'insert into snippet (caption,content) values (?,?)', ( self.search_str.get(), self.snip_content.get(1.0, END), )) self.connection.commit() self.fill_list() def on_update(self): self.cursor.execute( 'update snippet set content=? where caption=?', (self.snip_content.get(1.0, END), self.search_str.get())) self.connection.commit() def on_delete(self): index = self.snip_list.curselection()[0] seltext = self.snip_list.get(index) self.cursor.execute('delete from snippet where caption=?', (seltext, )) self.connection.commit() self.snip_list.delete(ANCHOR) self.on_new() def on_copy(self): self.parent.clipboard_clear() self.parent.clipboard_append(self.snip_content.get(1.0, END)) def on_quit(self): self.parent.destroy() # noinspection PyTypeChecker def on_snippet_selected(self, _): try: index = self.snip_list.curselection()[0] except IndexError: return selected_text = self.snip_list.get(index) self.snip_content.delete(1.0, END) self.cursor.execute('select * from snippet where caption=?', (selected_text, )) r = self.cursor.fetchone() if r['caption']: self.search_str.set(r['caption']) if r['content']: self.snip_content.insert(INSERT, r['content']) self.snip_content.focus_set()
class WikiPedia: def Wiki_Window(self, window): self.window = window self.window.geometry("1500x1500") def Notebook(self): self.notebook = ttk.Notebook(self.window) self.framePyRat = ttk.Frame(self.notebook, width=2500, height=1000) self.frameAbout = ttk.Frame(self.notebook, width=2500, height=1000) self.notebook.add(self.framePyRat, text='PyPedia') self.notebook.add(self.frameAbout, text='About') self.notebook.grid(row=0) def Design(self): ttk.Labelframe(self.window, width=1350, height=140).grid(row=0, sticky = NW) Label(self.window, text="Welcome To PyPedia",font=("Helvetica",20)).grid(row=0, column=0, sticky = NW, pady=50, padx = 450) image = Image.open("wikilogo.png") photo = ImageTk.PhotoImage(image) label = Label(image=photo) label.image = photo label.grid(row=0, column=0, sticky = NW, padx=1150) def search(self): global infowiki infowiki = StringVar() ttk.Labelframe(self.window, width=1350, height=600).grid(row=0, sticky = NW, pady=150, column=0) ttk.Labelframe(self.window, width=500, height=300).grid(row=0, sticky = NW, pady=174, column=0, padx=800) ttk.Labelframe(self.window, width=750, height=600).grid(row=0, sticky = NW, pady=174, column=0, padx=20) self.WikiInfo = ScrolledText(self.window, width=65,height=18, bd=7,font=("Helvetica",15)) self.WikiInfo.grid(row=0, sticky = NW, pady=280, column=0, padx=20) self.WikiInfo.insert(END, "Please Search For Content\n") def Content(self): global infowiki infowiki = StringVar() Label(self.window, text="Search:: ",font=("Helvetica",18)).grid(row=0, column=0, sticky = NW, pady=210, padx=30) Entry(self.window, width=30, bd=4,textvariable=infowiki, font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=210, padx=140, ipady=3) Button(self.window,text="Go", bd=5, command = self.thread).grid(row=0, column=0, sticky = NW, pady=210, padx=500, ipady=1, ipadx=20) self.snip = Spinbox(self.window, from_=0, to=1000, width=10) self.snip.grid(row=0, column=0, sticky = NW, pady=215, padx=590, ipady=1, ipadx=20) Label(self.window, text="Sentence::",font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=190, padx=595) ttk.Labelframe(self.window, width=500, height=300).grid(row=0, sticky = NW, pady=480,padx=800, column=0) Label(self.window, text="Information ",font=("Helvetica",18)).grid(row=0, column=0, sticky = NW, pady=500, padx=815) Label(self.window, text="Image (0)(0)",font=("Helvetica",18)).grid(row=0, column=0, sticky = NW, pady=160, padx=970) def Info(self): Label(self.window, text="Title :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=540, padx=815) Label(self.window, text="Url :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=580, padx=815) Label(self.window, text="Total Image In Url :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=625, padx=815) Label(self.window, text="Main Image :",font=("Helvetica",15)).grid(row=0, column=0, sticky = NW, pady=670, padx=815) def GoSearch(self): try: text = " " Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=540, padx=870) Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=580, padx=860) Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=625, padx=985) Label(self.window, text=text,font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=670, padx=940) self.WikiInfo.delete(1.0, END) self.WikiInfo.insert(END, "Title :: "+infowiki.get()) self.WikiInfo.insert(END, "\n") self.WikiInfo.insert(END, "\n") WikiData.wikiSearch(infowiki.get(), self.snip.get()) self.WikiInfo.insert(END, WikiData.GivingFuck()) self.Info() Label(self.window, text=WikiData.title(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=540, padx=870) Label(self.window, text=WikiData.url(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=580, padx=860) Label(self.window, text=WikiData.imageAll(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=625, padx=985) Label(self.window, text=WikiData.imageFront(),font=("Helvetica",12)).grid(row=0, column=0, sticky = NW, pady=670, padx=940) WikiData.getImage() WikiData.ResizeImage() image = Image.open("RE_IMAGE.png") photo = ImageTk.PhotoImage(image) self.label = Label(image=photo, bd=8) self.label.image = photo self.label.grid(row=0, column=0, sticky = NW, pady=200, padx=830 ) os.system("del image.png") os.system("del RE_IMAGE.png") except : global opt opt = [] self.WikiInfo.insert(END, " \n") self.WikiInfo.insert(END, "Found Other insted Of "+ infowiki.get()) self.WikiInfo.insert(END, "\n") self.WikiInfo.insert(END, " Please Insert Underscore in space like Apple_Inc \n") serc = wikipedia.search(infowiki.get(), 20) self.WikiInfo.insert(END, "\n") for i in serc: opt.append(i) self.WikiInfo.insert(END, i," \n") self.WikiInfo.insert(END, " \n") self.WikiInfo.insert(END, "\n") def thread(self): proc = threading.Thread(target = self.GoSearch) proc.start()
class PyGrbl_Editor(Frame): def __init__(self, master, app): Frame.__init__(self, master = master) ## WHO AM I ? #print("Who am I: " + self.winfo_class()) # = 'Frame' !! #print("Who is my master: " + master.__class__.__name__) # = Frame #print("Who is my app: " + app.__class__.__name__) # = PyGrbl_GUI #print("Who am I: " + self.__class__.__name__) # = 'PyGrbl_Editor' self.app = app self.app.servicemenu.entryconfig("Editor", state = "normal") self.app.apps.append(self.__class__.__name__) self.openFileTrace = self.app.fileOpenFlag.trace_variable('w', self.fileOpenTraceAction) self.editorWaiting = False # to prevent conflict gCodeChecker & Editor 'fileOpenTrace' self.createEditorWidgets() self.master.rowconfigure(0, weight = 1) self.master.columnconfigure(0, weight = 1) self.grid(column = 0, row = 0, sticky = (N, S, W, E)) def createEditorWidgets(self): # Text Pad self.textPad = ScrolledText(self, width = 30, height = 10, font = "TkTextFont") self.textPad.grid(row = 0, column = 0, padx = 10, pady = 10, sticky = (N, S, W, E)) self.columnconfigure(0, weight = 1) self.rowconfigure(0, weight = 1) self.save = Button(self, text = "Save", width = 6, command = lambda: self.saveFile()) self.save.grid(row = 0, column = 1, padx = 10, pady = 10, sticky = N) def fileOpenTraceAction(self, name, index, mode): try: if self.app.fileOpenFlag.get() == True: if self.app.currentApp == self.app.Editor: contents = self.app.inFile.read() contents = contents.replace('\r', '') self.app.inFile.seek(0) # reset inFile cursor to top of file self.textPad.insert(1.0, contents) elif self.editorWaiting: contents = self.app.inFile.read() self.app.inFile.seek(0) # reset inFile cursor to top of file self.textPad.insert(1.0, contents) self.editorWaiting = False else: self.editorWaiting = True self.after(1000, self.fileOpenTraceAction(name, index, mode)) elif self.app.fileOpenFlag.get() == False: self.textPad.delete(1.0, END) if self.app.debugMode > 1: print("fileOpenTraceAction: Ok") except: print("fileOpenTraceAction: Error") def saveFile(self): filename = asksaveasfile(mode = 'w') if filename: data = self.textPad.get(1.0, END+'-1c') filename.write(data) filename.close()
class Editor: def __init__(self): # init main window of GUI self.root = Tk() self.root.title('Text Editor - Brian Dinh') self.root.minsize(width=800, height = 800) self.root.pack_propagate(0) self.root.option_add('*tearOff', False) # init text box (used as the basis of the text editor) self.textBox = ScrolledText(self.root, height=100, relief=SUNKEN, undo=1) self.textBox.pack(side=TOP, fill=BOTH) # init top menu toolbar elements self.menu = Menu(self.root, relief=RAISED) self.root.config(menu=self.menu) self.fileMenu = Menu(self.menu) self.fileMenu.add_command(label='New', command=self.newFile, accelerator='Ctrl+N') self.fileMenu.add_command(label='Open', command=self.openFile, accelerator='Ctrl+O') self.fileMenu.add_command(label='Save', command=self.saveFile, accelerator='Ctrl+S') self.fileMenu.add_command(label='Save As', command=self.saveAsFile) self.fileMenu.add_separator() self.fileMenu.add_command(label='Exit', command=self.root.destroy) self.editMenu = Menu(self.menu) self.editMenu.add_command(label='Undo', command=self.textBox.edit_undo, accelerator='Ctrl+Z') self.editMenu.add_separator() self.editMenu.add_command(label='Cut', command=self.cut, accelerator='Ctrl+X') self.editMenu.add_command(label='Copy', command=self.copy, accelerator='Ctrl+C') self.editMenu.add_command(label='Paste', command=self.paste, accelerator='Ctrl+V') self.editMenu.add_separator() self.editMenu.add_command(label='Select All', command=self.selectAll, accelerator='Ctrl+A') self.menu.add_cascade(label='File', menu=self.fileMenu) self.menu.add_cascade(label='Edit', menu=self.editMenu) # key binds - missing undo because Tkinter has its own built in # don't need keybinds for ctrl x,c,v - os handles it, just use clipboard contents self.textBox.bind_all('<Control-n>', self.newFile) self.textBox.bind_all('<Control-o>', self.openFile) self.textBox.bind_all('<Control-s>', self.saveFile) self.textBox.bind_all('<Control-a>', self.selectAll) # variables self.fileName = '' def runGUI(self): self.root.mainloop() def updateTitleBar(self): self.root.title('Text Editor - ' + self.fileName) def openFile(self, event=None): fname = tkFileDialog.askopenfilename() if fname: # prevent file opener from overwriting existing self.fileName = fname contents = self.readFile(self.fileName) self.textBox.delete(1.0, END) self.textBox.insert(INSERT, contents) self.updateTitleBar() def readFile(self, fileName): f = open(fileName, 'r') contents = f.read() f.close() return contents def newFile(self, event=None): self.textBox.delete(1.0, END) self.fileName = 'New Text Document' self.updateTitleBar() def saveFile(self, event=None): contents = self.textBox.get(1.0, END) if self.fileName: f = open(self.fileName, 'w') f.write(self.textBox.get(1.0, END)) f.close() else: self.saveAsFile() def saveAsFile(self): contents = self.textBox.get(1.0, END) fname = tkFileDialog.asksaveasfilename() if fname: self.fileName = fname f = open(self.fileName, 'w') f.write(self.textBox.get(1.0, END)) f.close() self.updateTitleBar() def selectAll(self, event=None): self.textBox.tag_add(SEL, 1.0, END) self.textBox.mark_set(INSERT, 1.0) self.textBox.see(INSERT) return 'break' def copy(self, event=None): self.textBox.clipboard_clear() self.textBox.clipboard_append(self.textBox.get('sel.first', 'sel.last')) def cut(self, event=None): self.copy() self.textBox.delete('sel.first', 'sel.last') def paste(self, event=None): self.textBox.insert(INSERT, self.textBox.selection_get(selection='CLIPBOARD'))
class Application: def __init__(self, file=None): self.root = Tk() self.root.title("Pipeline Viewer") self.file = file self.dbGraph = gs.dbGraph self.WIDTH = 1000 self.HEIGHT = 800 #gs.plot(self.graph, bbox=(self.WIDTH - 100, self.HEIGHT-100)) self.root.geometry("{0}x{1}".format(self.WIDTH, self.HEIGHT)) self.root.columnconfigure(0, weight=10) self.root.columnconfigure(1, weight=1) #self.root.rowconfigure(0, weight=10) self.root.rowconfigure(1, weight=10) #self.root.rowconfigure(2, weight=10) self.nodes = [] self.edges = [] self.selColor = "green" self.currSel = None self.isCtrlDown = False self.drawingEdge = False self.c = Canvas(self.root, bg="white") self.c.grid(row=0, column=0, rowspan=5, sticky=N + S + W + E) self.stateBar = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.stateBar.grid(row=4, columnspan=3, sticky=E + W) self.list = Listbox(self.root, width=30) self.sbar = Scrollbar(self.root) self.sbar.config(command=self.list.yview) self.list.config(yscrollcommand=self.sbar.set) self.list.grid(row=1, column=1, sticky=N + S + E + W) self.sbar.grid(row=1, column=2, sticky=N + S) for i in range(len(self.dbGraph.vs)): self.list.insert(i, self.dbGraph.vs[i]["varSet"]["className"]) self.addButton = Button(self.root, text="Add", command=self.addToLayout) self.addButton.grid(row=0, column=1, columnspan=2, sticky=E + W) self.addButton = Button(self.root, text="Save", command=self.saveAttributes) self.addButton.grid(row=2, column=1, columnspan=2, sticky=E + W) self.scrolledText = ScrolledText(self.root, width=30, undo=True, setgrid=True, wrap='word') self.scrolledText.grid(row=3, column=1, columnspan=2, sticky=N + S + W + E) self.scrolledText.insert("insert", "") self.dummyEdge = Edge((-1, -1), (-1, -1), self.c, None, None, "dummyEdge") self.c.bind("<Button-1>", self.mouseDown) self.c.bind("<Button1-Motion>", self.mouseMove) self.c.bind("<Button1-ButtonRelease>", self.mouseUp) self.root.bind("<KeyPress-Control_L>", self.controlDown) self.root.bind("<KeyRelease-Control_L>", self.controlUp) self.root.bind("<Delete>", self.deleteSelection) self.list.bind('<<ListboxSelect>>', self.deselect) if self.file is not None: self.openLayout(dialog=False) else: self.newLayout() menubar = Menu(self.root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="New", command=self.newLayout) filemenu.add_command(label="Open", command=self.openLayout) filemenu.add_command(label="Save", command=self.saveLayout) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.root.quit) menubar.add_cascade(label="File", menu=filemenu) editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Reorder") menubar.add_cascade(label="Edit", menu=editmenu) self.root.config(menu=menubar) self.root.after(10, self.drawLoop) self.root.mainloop() def newLayout(self): for n in self.nodes: n.delete() for e in self.edges: e.delete() self.nodes, self.edges = [], [] self.currSel = None self.isCtrlDown = False self.drawingEdge = False self.graph = gs.Graph() self.graph.vs["name"] = "" def openLayout(self, dialog=True): if dialog: self.file = askopenfilename(filetypes=(("XML files", "*.xml"), ("All files", "*.*"))) self.newLayout() self.graph = gs.unserializeGraph(self.file) gs.buildDependences(self.graph) self.topologicalGrid() #gs.plot(self.graph, bbox=(self.WIDTH - 100, self.HEIGHT-100)) self.createNodesFromGraph() self.createEdgesFromGraph() def saveLayout(self): f = asksaveasfile(mode='w', defaultextension=".xml", filetypes=(("XML files", "*.xml"), ("All files", "*.*"))) if f is None: return f.write(gs.serializeGraph(self.graph, f.name)) f.close() name = f.name name = name.replace(".xml", "") generateBenchmark(f.name, "{0}Benchmark.xml".format(name)) generateEmbedded(f.name, "{0}Embedded.xml".format(name)) def addToLayout(self): self.addNodeFromDB(self.list.get(ACTIVE)) def saveAttributes(self): if self.currSel in self.nodes: attr = ast.literal_eval(self.scrolledText.get(1.0, END)) self.graph.vs[gs.iv(self.currSel.tag, self.graph)]["varSet"] = attr def topologicalGrid(self): positions = self.graph.topological_sorting() width = 85 height = (self.HEIGHT - 250) / (max([n.degree() for n in self.graph.vs]) + 1) height2 = (self.HEIGHT) / len(self.graph.vs) beg = filter(lambda x: self.graph.vs[x].indegree() == 0, positions) self.graph.vs["x"] = 5 self.graph.vs["y"] = 5 i = 0 for p in beg: self.graph.vs[p]["y"] += i * height2 i += 1 for p in positions: node = self.graph.vs[p] j = 0 order = sorted(node.successors(), key=lambda x: len( filter(lambda n: isinstance(n, int), x.shortest_paths()[0])), reverse=True) for succ in order: succ["x"] = node["x"] + width succ["y"] = node["y"] + j * height j += 1 def tagNode(self, n1, n2): return "{0}_to_{1}".format(n1, n2) def findNode(self, name): for n in self.nodes: if name == n.tag: return n return None def findEdge(self, n1, n2=None): if n2 is None: tag = n1 else: tag = self.tagNode(n1, n2) for e in self.edges: if tag == e.tag: return e return None def addNodeFromDB(self, n): node = gs.addVertexFromDB(n, self.graph) if node is not None: node["x"] = self.WIDTH - Node.width node["y"] = 0 self.nodes.append( Node(node["x"], node["y"], len(node["varSet"]["dependencies"]), self.c, node["name"])) def addEdge(self, n1, n2): if (self.findEdge(n1, n2) is None) and (n1 != n2): if gs.addEdge(n1, n2, self.graph): node1 = self.findNode(n1) node2 = self.findNode(n2) self.edges.append( Edge(self.c.coords(node1.rect), self.c.coords(node2.rect), self.c, node1, node2, self.tagNode(n1, n2))) def createNodesFromGraph(self): for n in self.graph.vs: self.nodes.append( Node(n["x"], n["y"], len(n["varSet"]["dependencies"]), self.c, n["name"])) for n in self.nodes: coords = self.c.coords(n.rect) while len( self.c.find_overlapping( coords[0], coords[1], coords[2], coords[3])) == 2 + len(n.ovals) and coords[1] > 0: self.c.move(n.tag, 0, -1) coords = self.c.coords(n.rect) self.c.move(n.tag, 0, 1.5 * Node.height) def createEdgesFromGraph(self): for e in self.graph.get_edgelist(): n1 = self.graph.vs[e[0]]["name"] n2 = self.graph.vs[e[1]]["name"] node1 = self.findNode(n1) node2 = self.findNode(n2) self.edges.append( Edge(self.c.coords(node1.rect), self.c.coords(node2.rect), self.c, node1, node2, self.tagNode(n1, n2))) def drawLoop(self): for e in self.edges: n1 = self.c.coords(e.n1.rect) index = self.graph.vs[gs.iv( e.n2.tag, self.graph)]["varSet"]["dependencies"].index(e.n1.tag) n2 = self.c.coords(e.n2.ovals[index]) xs = arrowFit(n1[0], n1[2], n2[0], n2[2]) ys = arrowFit(n1[1], n1[3], n2[1], n2[3]) self.c.coords(e.tag, xs[0], ys[0], xs[1], ys[1]) self.root.after(10, self.drawLoop) def removeEdge(self, n1, n2): edge = self.findEdge(n1, n2) edge.delete() gs.removeEdge(n1, n2, self.graph) self.edges.remove(edge) def removeNode(self, n): node = self.findNode(n) for succ in self.graph.vs[gs.iv(n, self.graph)].successors(): self.removeEdge(node.tag, succ["name"]) for pred in self.graph.vs[gs.iv(n, self.graph)].predecessors(): self.removeEdge(pred["name"], node.tag) gs.removeVertex(node.tag, self.graph) node.delete() self.nodes.remove(node) def inRect(self, x, y, rect): if (x < rect[0]): return False if (y < rect[1]): return False if (x > rect[2]): return False if (y > rect[3]): return False return True def deselect(self, event): if self.currSel is not None: self.c.itemconfig(primTag(self.currSel.tag), fill=self.currSel.defaultColor) self.c.itemconfig(primTag(self.currSel.tag), width=1) self.currSel = None def handleSelection(self, event): self.list.selection_clear(0, END) dstObject = self.c.find_overlapping(event.x, event.y, event.x + 1, event.y + 1) objs = self.c.gettags(dstObject) self.deselect(event) self.scrolledText.delete("1.0", END) self.scrolledText.insert("insert", "") if (len(dstObject)): objs = self.c.gettags(dstObject[0]) s = self.findNode(objs[0]) if s is None: s = self.findEdge(objs[0]) if s is not None: self.currSel = s self.c.itemconfig(primTag(self.currSel.tag), fill=self.selColor) self.c.itemconfig(primTag(self.currSel.tag), width=2) def mouseDown(self, event): self.handleSelection(event) self.x1, self.y1 = event.x, event.y if self.currSel in self.nodes: self.scrolledText.insert( "insert", json.dumps(self.graph.vs[gs.iv(self.currSel.tag, self.graph)]["varSet"], indent=4).replace("null", "None")) if self.isCtrlDown: self.drawingEdge = True self.c.coords("dummyEdge", self.x1, self.y1, self.x1, self.y1) def mouseMove(self, event): x2, y2 = event.x, event.y if not self.drawingEdge: dx, dy = x2 - self.x1, y2 - self.y1 if self.currSel is not None: self.c.move(self.currSel.tag, dx, dy) self.x1, self.y1 = x2, y2 else: coords = self.c.coords("dummyEdge") self.c.coords(self.dummyEdge.arrow, coords[0], coords[1], x2, y2) self.c.tag_raise(self.dummyEdge.arrow) def mouseUp(self, event): if not self.drawingEdge: if self.currSel is not None: self.c.itemconfig(primTag(self.currSel.tag), width=1) else: dstObject = self.c.find_overlapping(event.x, event.y, event.x + 1, event.y + 1)[0] dstTag = self.c.gettags(dstObject)[0] if (dstTag in [n.tag for n in self.nodes]) and (self.inRect( event.x, event.y, self.c.coords(dstTag))): self.addEdge(self.currSel.tag, dstTag) self.drawingEdge = False self.c.coords(self.dummyEdge.arrow, -1, -1, -1, -1) def deleteSelection(self, event): if self.currSel is not None: if self.currSel in self.nodes: self.removeNode(self.currSel.tag) elif self.currSel in self.edges: self.removeEdge(self.currSel.n1.tag, self.currSel.n2.tag) self.currSel = None def controlDown(self, event): self.isCtrlDown = True def controlUp(self, event): self.isCtrlDown = False
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 Summarizer: def __init__(self): self.root = Tk() self.lowerBound = DoubleVar(value=0.8) self.fileName = "No files imported yet" self.statusBar = Label(self.root, bd=2, text=self.fileName, anchor=W) self.statusBar.pack(side=BOTTOM, fill=X) self.textBox = ScrolledText(self.root, height=18, width=47, bg="white", wrap=WORD, ) self.textBox.pack(side=RIGHT, fill=X) self.root.title('NLTK Text Summarizer - Brian Dinh') self.root.minsize(width=550, height=350) # fixed height and width self.root.maxsize(width=550, height=350) self.leftFrame = Frame(self.root) self.leftFrame.pack(side=LEFT) self.entryBoxLabel = Label(self.leftFrame, text='Percentage Lower Bound:', anchor=W) self.entryBoxLabel.pack(side=TOP) self.entryBox = Entry(self.leftFrame, textvariable=self.lowerBound, width=15, justify=CENTER) self.entryBox.pack(side=TOP) self.importButton = Button(self.leftFrame, text="Import Text", height=5, width=20, command=self.importText) self.importButton.pack(side=TOP, pady=7) self.generateButton = Button(self.leftFrame, text="Generate Text", height=5, width=20, command=self.generateSummary) self.generateButton.pack(side=TOP) # list of stopwords from nltk library self.stopWords = set(stopwords.words('english')) self.stemmer = SnowballStemmer('english') self.contents = '' # the original text def runGUI(self): self.root.mainloop() def generateSummary(self): summary = self.generate() self.textBox.delete(1.0, END) self.textBox.insert(INSERT, summary) def importText(self): fname = tkFileDialog.askopenfilename() if len(fname) > 0: # prevent file opener from overwriting existing self.fileName = fname self.readFile() currentFile = "Current File: " + self.fileName self.updateStatus() def updateStatus(self): # update status bar to show current file path self.statusBar.configure(text=self.fileName) def readFile(self): f = open(self.fileName, 'r') self.contents = f.read() f.close() # list of all words in the text def getWords(self): return word_tokenize(self.contents.decode('utf-8', 'ignore')); #list of sentences in the text def getSentences(self): return sent_tokenize(self.contents.decode('utf-8', 'ignore')) def getWordFrequency(self, words): frequency = {} # dictionary mapping words to their frequency for word in words: word = word.lower() if word in self.stopWords: continue # stop words add no value to sentence weight word = self.stemmer.stem(word) # only keep common prefixes of words if word in frequency: frequency[word] += 1 else: frequency[word] = 1 return frequency # extractive summarization method; no complicated machine learning stuff # assign values to sentences based on sum of its words' frequencies def scoreSentences(self, sentences, frequency): sentenceValues = {} for sentence in sentences: # loop each sentence for word, freq in frequency.iteritems(): # loop each word's frequency if word in sentence.lower(): # if the word is in the sentence if sentence in sentenceValues: # add it to the current sum sentenceValues[sentence] += freq; else: sentenceValues[sentence] = freq; return sentenceValues def generate(self): # tokenize into words and sentences, then determine freq and sentence values words = self.getWords() sentences = self.getSentences() frequency = self.getWordFrequency(words) sentenceValues = self.scoreSentences(sentences, frequency) # minimum value of summary must be > some % of maximum sentence value highestValue = max(sentenceValues.values()) threshold = int(self.lowerBound.get() * highestValue) # then compare each sentence value with the threshold value summary = '' for sentence in sentences: if sentence in sentenceValues and sentenceValues[sentence] >= threshold: summary += ' ' + sentence; return summary
class SphxUI(): def __init__(self, root): self.data = SphxData() self.xdopy = XdoPy() self.gooey = GuiPiece(self.data.MAIN_PATH, self.data.GUI_PIECE_DIR) self.script_dir = self.data.SCRIPT_DIR self.txt_dir = self.data.TXT_FILE_DIR # sphx data to reset upon new or fill upon load self.script_lines = [] self.gui_pieces = [] self.window_names = [] self.passed_script_data = None self.text_file_pass = None self.return_data = None self.gui_piece_list_active = False self.script_fn = None # generate UI self.root = root self.master = Frame(self.root) self.master.grid() self.add_file_menu() self.create_script_pad() self.create_action_buttons() self.create_gui_pieces_list() return def start(self): self.root.mainloop() return def _dummy(self): pass def _dummy_event(self, event, arg=None): pass # TOP MENU # # def add_file_menu(self): self.menubar = Menu(self.root) self.filemenu = Menu(self.menubar, tearoff=0) self.filemenu.add_command(label="New", command=self._new) self.filemenu.add_separator() self.filemenu.add_command(label="Open...", command=self._open) self.filemenu.add_command(label="Save", command=lambda: self._save(saveas=False)) self.filemenu.add_command(label="Save As...", command=lambda: self._save(saveas=True)) self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self._regular_exit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.helpmenu = Menu(self.menubar, tearoff=0) self.helpmenu.add_command(label="About", command=self._dummy) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.root.config(menu=self.menubar) def _clear_everything(self): self.script_pad.delete('1.0', END) for button in self.gui_piece_buttons: button.config(text='') for line in self.script_lines: if line[2]: self.script_pad.tag_delete(line[2]) self.script_lines = [] self.gui_pieces = [] self.window_names = [] self.passed_script_data = None self.return_data = None self.gui_piece_list_active = False def _new(self): self.new_save = Toplevel() self.new_save.title('Save Script?') new_frame1 = Frame(self.new_save) new_frame1.grid(row=0, column=0) label = Label( new_frame1, text='Do you want to save your script before starting over?') label.grid() new_frame2 = Frame(self.new_save) new_frame2.grid(row=1, column=0) button = Button(new_frame2, text='Yes', command=lambda: self._new_save(0)) button.grid(row=0, column=0) button = Button(new_frame2, text='No', command=lambda: self._new_save(1)) button.grid(row=0, column=1) button = Button(new_frame2, text='Cancel', command=lambda: self._new_save(2)) button.grid(row=0, column=2) def _new_save(self, answer): if answer == 0: if self.script_fn: self._save() else: self._save(False) self._clear_everything() self.new_save.destroy() if answer == 1: self._clear_everything() self.new_save.destroy() if answer == 2: self.new_save.destroy() def _open(self): if self.script_lines == [] and self.gui_pieces == []: self._load_everything() return self.open_save = Toplevel() self.open_save.title('Save Script?') new_frame1 = Frame(self.open_save) new_frame1.grid(row=0, column=0) label = Label( new_frame1, text='Do you want to save your script before opening a saved one?') label.grid() new_frame2 = Frame(self.open_save) new_frame2.grid(row=1, column=0) button = Button(new_frame2, text='Yes', command=lambda: self._open_save(0)) button.grid(row=0, column=0) button = Button(new_frame2, text='No', command=lambda: self._open_save(1)) button.grid(row=0, column=1) button = Button(new_frame2, text='Cancel', command=lambda: self._open_save(2)) button.grid(row=0, column=2) def _open_save(self, answer): if answer == 0: if self.script_fn: self._save() else: self._save(False) self.open_save.destroy() self._load_everything() if answer == 1: self.open_save.destroy() self._load_everything() if answer == 2: self.open_save.destroy() def _load_everything(self): f = tkFileDialog.askopenfilename(initialdir=self.data.SCRIPT_DIR, title="Open Script", filetypes=(("sphx files", "*.sphx"), ("all files", "*.*"))) with open(f, 'r') as openfile: sphx_dict = json.load(openfile) self.script_fn = f.rpartition('/')[2] openfile.close() self._clear_everything() self.script_lines = sphx_dict['script_lines'] self.gui_pieces = sphx_dict['gui_pieces'] button_index = 0 for gui_piece in self.gui_pieces: gui_piece_text = '{0}. {1}'.format(button_index + 1, gui_piece) self.gui_piece_buttons[button_index].config(text=gui_piece_text) button_index += 1 for line in self.script_lines: line_number, script_text, tagname, tag_start, tag_end, script_data = line self.script_pad.insert(END, script_text + '\n') self._scanfix_script_lines(None) def _save(self, saveas=False): self._scanfix_script_lines(None) script_dict = { 'script_lines': self.script_lines, 'gui_pieces': self.gui_pieces } if not saveas and self.script_fn: with open(os.path.join(self.data.SCRIPT_DIR, self.script_fn), 'w') as outfile: json.dump(script_dict, outfile) self.script_fn = outfile.name.rpartition('/')[2] if (saveas or not self.script_fn) or (saveas and not self.script_fn): outfile = tkFileDialog.asksaveasfile( mode='w', defaultextension='.sphx', initialdir=self.data.SCRIPT_DIR) if outfile is None: return json.dump(script_dict, outfile) outfile.close() self.script_fn = outfile.name.rpartition('/')[2] def _regular_exit(self): self.exit_save = Toplevel() self.exit_save.title('Save Script') exit_frame1 = Frame(self.exit_save) exit_frame1.grid(row=0, column=0) label = Label(exit_frame1, text='Do you want to save your script before exiting?') label.grid() exit_frame2 = Frame(self.exit_save) exit_frame2.grid(row=1, column=0) button = Button(exit_frame2, text='Yes', command=lambda: self._exit_save(0)) button.grid(row=0, column=0) button = Button(exit_frame2, text='No', command=lambda: self._exit_save(1)) button.grid(row=0, column=1) button = Button(exit_frame2, text='Cancel', command=lambda: self._exit_save(2)) button.grid(row=0, column=2) def _exit_save(self, answer): if answer == 0: if self.script_fn: self._save() else: self._save(False) self.root.quit() if answer == 1: self.root.quit() if answer == 2: self.exit_save.destroy() # SCRIPT PAD COLUMN # # def create_script_pad(self): script_pad_label = Label(self.master, text='SCRIPT BUILD (right-click for options)') script_pad_label.grid(row=0, column=1) self.script_pad = ScrolledText(self.master, width=75, height=32) self.script_pad.grid(row=1, column=1, sticky='nw') self.script_pad.bind('<KeyRelease>', self._scanfix_script_lines) self.print_button = Button(self.master, text='Print Script Line Data To Terminal', command=self._print_script_line_data) self.print_button.grid(row=2, column=1, sticky='nwes') return def _print_script_line_data(self): for line in self.script_lines: print(line[1]) def _get_tag_data(self, line_count, line_text, script_data): tag_start = '{0}.{1}'.format(line_count, line_text.index(script_data)) tag_end = '{0}.{1}'.format( line_count, line_text.index(script_data) + len(script_data)) return tag_start, tag_end def _scanfix_script_lines(self, event): new_script_lines = [] new_text = self.script_pad.get('1.0', END) new_text_lines = new_text.split('\n') line_count = 0 gui_tags = [] win_tags = [] key_tags = [] self.script_lines = [] new_window_names = [] for line in new_text_lines: line_count += 1 if ';' and ' ' in line: line_text = line.rpartition(';')[0] line_pieces = line_text.split(' ') action = line_pieces[0] script_line_data = [] if action in [a[0] for a in self.data.GUI_ACTIONS]: script_data = line_pieces[1] tag_index = len(gui_tags) tag_name = 'gui{0}'.format(tag_index) self.script_pad.tag_delete(tag_name) gui_tags.append(tag_name) tag_start, tag_end = self._get_tag_data( line_count, line_text, script_data) script_line_data = [ line_count, line, tag_name, tag_start, tag_end, script_data ] self.script_pad.tag_add(tag_name, tag_start, tag_end) self.script_pad.tag_config(tag_name, background='blue', foreground='white') self.script_pad.tag_bind( tag_name, '<Button-3>', lambda event, arg=script_line_data: self. _gui_piece_menu_popup(event, arg)) if action in [a[0] for a in self.data.WINDOW_ACTIONS]: script_data = line_pieces[1] tag_index = len(win_tags) tag_name = 'win{0}'.format(tag_index) self.script_pad.tag_delete(tag_name) win_tags.append(tag_name) tag_start, tag_end = self._get_tag_data( line_count, line_text, script_data) script_line_data = [ line_count, line, tag_name, tag_start, tag_end, script_data ] if action == 'name_active_window': new_window_names.append(script_data) self.script_pad.tag_add(tag_name, tag_start, tag_end) self.script_pad.tag_config(tag_name, background='gray', foreground='white') else: self.script_pad.tag_add(tag_name, tag_start, tag_end) self.script_pad.tag_config(tag_name, background='pink', foreground='white') self.script_pad.tag_bind( tag_name, '<Button-3>', lambda event, arg=script_line_data: self. _window_menu_popup(event, arg)) if action in [a[0] for a in self.data.KEYBOARD_ACTIONS]: script_data = line_text.partition(' ')[2] tag_index = len(key_tags) tag_name = 'key{0}'.format(tag_index) key_tags.append(tag_name) tag_start, tag_end = self._get_tag_data( line_count, line_text, script_data) script_line_data = [ line_count, line, tag_name, tag_start, tag_end, script_data ] self.script_pad.tag_add(tag_name, tag_start, tag_end) if 'type' in action: tag_bg, tag_fg = 'green', 'white' else: tag_bg, tag_fg = 'green', 'yellow' self.script_pad.tag_config(tag_name, background=tag_bg, foreground=tag_fg) self.script_pad.tag_bind( tag_name, '<Button-3>', lambda event, arg=script_line_data: self. _text_piece_popup(event, arg)) if action in [a[0] for a in self.data.OTHER_ACTIONS]: script_data = None tag_name = None tag_start, tag_end = None, None script_line_data = [ line_count, line, tag_name, tag_start, tag_end, script_data ] if len(script_line_data) > 0: self.script_lines.append(script_line_data) self.window_names = sorted(new_window_names) if len(self.window_names) == 0: self.action_buttons_list[15].config(state=DISABLED) self.action_buttons_list[16].config(state=DISABLED) else: if not self.gui_piece_list_active: self.action_buttons_list[15].config(state='normal') self.action_buttons_list[16].config(state='normal') return # ACTION BUTTONS COLUMN # # def create_action_buttons(self): action_buttons_label = Label(self.master, text='SCRIPT ACTIONS') action_buttons_label.grid(row=0, column=2) self.action_buttons = Frame(self.master) self.action_buttons.grid(row=1, column=2, sticky='nw') self.auto_snap = IntVar() self.auto_snap.set(1) self.auto_snap_check = Checkbutton(self.action_buttons, text='Auto-snap', variable=self.auto_snap) self.auto_snap_check.grid(row=0, column=2) self.action_buttons_list = [] action_index = 0 for i in range(3): for j in range(3): button = Button(self.action_buttons, text=self.data.GUI_ACTIONS[action_index][0], pady=5, command=functools.partial( self._append_gui_piece_action, self.data.GUI_ACTIONS[action_index][1])) button.grid(row=i + 1, column=j, sticky='nwes') action_index += 1 self.action_buttons_list.append(button) action_index = 0 for i in range(2): for j in range(3): if i == 0 and j == 0: continue button = Button( self.action_buttons, text=self.data.KEYBOARD_ACTIONS[action_index][0], pady=5, command=functools.partial( self._append_text_piece_action, self.data.KEYBOARD_ACTIONS[action_index][1])) button.grid(row=i + 4, column=j, sticky='nwes') self.action_buttons_list.append(button) action_index += 1 action_index = 0 for j in range(3): button = Button(self.action_buttons, text=self.data.WINDOW_ACTIONS[action_index][0], pady=5, command=functools.partial( self._append_window_action, self.data.WINDOW_ACTIONS[action_index][1])) button.grid(row=6, column=j, sticky='nwes') if j > 0: button.config(state=DISABLED) self.action_buttons_list.append(button) action_index += 1 action_index = 0 for j in range(2): button = Button(self.action_buttons, text=self.data.OTHER_ACTIONS[action_index][0], pady=5, command=functools.partial( self._append_other_action, self.data.OTHER_ACTIONS[action_index][1])) button.grid(row=7, column=j + 1, sticky='nwes') self.action_buttons_list.append(button) action_index += 1 # insert another layer for hover-over data about script action return # GUI PIECES COLUMN # # def create_gui_pieces_list(self): gui_pieces_label = Label(self.master, text='GUI PIECES (click to view)') gui_pieces_label.grid(row=0, column=0) self.gui_piece_buttons = [] self.gui_pieces_pad = Frame(self.master) self.gui_pieces_pad.grid(row=1, column=0, sticky='nw') button_index = 0 for j in range(2): for i in range(25): new_button = Button(self.gui_pieces_pad, text='', bg='blue', fg='white', borderwidth=0, width=15, padx=0, pady=0, command=functools.partial( self._gui_piece_button_click, button_index)) button_index += 1 new_button.grid(row=i, column=j, sticky='w') self.gui_piece_buttons.append(new_button) self.gui_piece_extras = Frame(self.master) self.gui_piece_extras.grid(row=2, column=0, sticky='nwes') self.take_new_gui_piece_button = Button(self.gui_piece_extras, text='Take New', command=self._get_gui_piece) self.take_new_gui_piece_button.grid(row=0, column=0, sticky='nwes') # TO FINISH -- LOAD BUTTON self.load_png_gui_piece_button = Button(self.gui_piece_extras, text='Load Png', command=self._dummy) self.load_png_gui_piece_button.config(state=DISABLED) self.load_png_gui_piece_button.grid(row=0, column=1, sticky='nwes') # TO FINISH -- REMOVE BUTTON self.remove_gui_piece_button = Button( self.gui_piece_extras, text='Remove', command=lambda: self._activate_gui_pieces_list(None)) self.remove_gui_piece_button.grid(row=0, column=2, sticky='nwes') return def _append_gui_pieces_list(self, gui_piece): gui_piece_text = '{0}. {1}'.format(len(self.gui_pieces) + 1, gui_piece) self.gui_piece_buttons[len( self.gui_pieces)].config(text=gui_piece_text) self.gui_pieces.append(gui_piece) return def _remove_gui_piece(self, button_index): removed_gui_piece = self.gui_pieces.pop(button_index) if button_index < len(self.gui_pieces): for replace_index in range(button_index, len(self.gui_pieces)): self.gui_piece_buttons[replace_index].config( text='{0}. {1}'.format(replace_index + 1, self.gui_pieces[replace_index])) self.gui_piece_buttons[len(self.gui_pieces)].config(text='') for index in range(len(self.script_lines)): line_data = self.script_lines[index][-1] if line_data == removed_gui_piece: data = '<right-click>', self.script_lines[index] self._replace_gui_piece(data) return def _activate_gui_pieces_list(self, script_line_data): if len(self.gui_pieces): for button in self.gui_piece_buttons: button.config(fg='white', bg='red') self.script_pad.config(state=DISABLED) self.print_button.config(state=DISABLED) for button in self.action_buttons_list: button.config(state=DISABLED) self.take_new_gui_piece_button.config(state=DISABLED) # self.load_png_gui_piece_button.config(state=DISABLED) self.remove_gui_piece_button.config(state=DISABLED) self.gui_piece_list_active = True self.passed_script_data = script_line_data def _gui_piece_button_click(self, button_index): if button_index < len(self.gui_pieces): gui_piece = self.gui_pieces[button_index] if not self.gui_piece_list_active: self._display_gui_piece(gui_piece) else: if self.passed_script_data: script_line_data = self.passed_script_data data = gui_piece, script_line_data self._replace_gui_piece(data) else: self._remove_gui_piece(button_index) for button in self.gui_piece_buttons: button.config(bg='blue', fg='white') self.print_button.config(state='normal') for button in self.action_buttons_list: button.config(state='normal') if len(self.window_names) == 0: self.action_buttons_list[15].config(state=DISABLED) self.action_buttons_list[16].config(state=DISABLED) self.take_new_gui_piece_button.config(state='normal') # self.load_png_gui_piece_button.config(state='normal') self.remove_gui_piece_button.config(state='normal') self.gui_piece_list_active = False # -- gui piece action functions -- # # def _append_gui_piece_action(self, script_text): if self.auto_snap.get(): gui_piece = self._get_gui_piece() else: gui_piece = '<right-click>' script_line = script_text.format(gui_piece) self.script_pad.insert(END, script_line) self._scanfix_script_lines(None) def _gui_piece_menu_popup(self, event, script_line_data): self.popup_menu1 = Menu(self.root, tearoff=0) self.popup_menu1.add_command(label='View', command=functools.partial( self._display_gui_piece, script_line_data[-1])) self.popup_menu1.add_command(label='Take New', command=functools.partial( self._sub_new_gui_piece, script_line_data)) self.popup_menu1.add_command(label='Choose From Others', command=functools.partial( self._activate_gui_pieces_list, script_line_data)) self.popup_menu1.post(event.x_root, event.y_root) self.master.bind('<Button-1>', self._destroy_gui_piece_menu) self.master.bind('<Button-3>', self._destroy_gui_piece_menu) self.script_pad.bind('<Enter>', self._destroy_gui_piece_menu) def _get_gui_piece(self): self.root.iconify() self.gooey.take_new_gui_piece() self.root.deiconify() gui_piece = self.gooey.gui_piece_filename self._append_gui_pieces_list(gui_piece) return gui_piece def _display_gui_piece(self, gui_piece): if gui_piece != '<right-click>': self.img_viewer = Toplevel() self.img_viewer.title(gui_piece) img_open = Image.open( os.path.join(self.data.GUI_PIECE_DIR, gui_piece)) img = ImageTk.PhotoImage(img_open) img_label = Label(self.img_viewer, image=img) img_label.image = img img_label.grid(row=0, column=0, padx=20, pady=20) def _replace_gui_piece(self, data): new_gui_piece, script_line_data = data line_number, script_text, gui_tagname, gui_tag_start, gui_tag_end, gui_piece = script_line_data self.script_pad.config(state='normal') self.script_pad.delete(gui_tag_start, gui_tag_end) self.script_pad.insert(gui_tag_start, new_gui_piece) self._scanfix_script_lines(None) def _sub_new_gui_piece(self, gui_tag_data): data = self._get_gui_piece(), gui_tag_data self._replace_gui_piece(data) def _destroy_gui_piece_menu(self, event): self.popup_menu1.destroy() # -- window action functions -- # # def _append_window_action(self, script_text): if script_text.split(' ')[0] == 'name_active_window': if len(self.window_names) == 0: self.action_buttons_list[13].config(state='normal') self.action_buttons_list[14].config(state='normal') window_name = 'window{0}'.format( str(len(self.window_names)).zfill(2)) self.window_names.append(window_name) else: window_name = self.window_names[-1] script_line = script_text.format(window_name) self.script_pad.insert(END, script_line) self._scanfix_script_lines(None) def _window_menu_popup(self, event, script_line_data): self.popup_menu2 = Menu(self.root, tearoff=0) for other_window_name in self.window_names: data = other_window_name, script_line_data self.popup_menu2.add_command(label=other_window_name, command=functools.partial( self._replace_window_name, data)) self.popup_menu2.post(event.x_root, event.y_root) self.master.bind('<Button-1>', self._destroy_window_name_menu) self.master.bind('<Button-3>', self._destroy_window_name_menu) self.script_pad.bind('<Enter>', self._destroy_window_name_menu) def _replace_window_name(self, data): self.popup_menu2.destroy() new_window_name, script_line_data = data line_number, script_text, win_tagname, win_tag_start, win_tag_end, window_name = script_line_data self.script_pad.delete(win_tag_start, win_tag_end) self.script_pad.insert(win_tag_start, new_window_name) self._scanfix_script_lines(None) def _destroy_window_name_menu(self, event): self.popup_menu2.destroy() # -- type_text action functions -- # # def _append_text_piece_action(self, script_text): text_piece = '<right-click>' script_line = script_text.format(text_piece) self.script_pad.insert(END, script_line) self._scanfix_script_lines(None) def _text_piece_popup(self, event, data): open_text_file = False text_piece = data[-1] if text_piece == '<right-click>': text_piece = '' if 'type' in data[1]: if 'type_text_file' in data[1]: open_text_file = True else: text_type_title = 'Text to Type:' else: text_type_title = 'Key(s) to Press:' if not open_text_file: self.get_text = Toplevel() self.get_text.title(text_type_title) self.text_entry = Entry(self.get_text, text=text_piece, width=75, font=("Helvetica", 12)) self.text_entry.grid() self.text_entry.bind( '<Return>', lambda event, arg=data: self._replace_text_piece(event, arg)) else: self._open_text_file(data) def _open_text_file(self, script_line_data): f = tkFileDialog.askopenfilename(initialdir=self.data.TXT_FILE_DIR, title="Open Text File", filetypes=(("txt files", "*.txt"), ("all files", "*.*"))) if f is None: return with open(f, 'r') as openfile: text_from_file = openfile.read() self.text_file_pass = f.rpartition('/')[2] self._replace_text_piece(None, script_line_data) return def _replace_text_piece(self, event, data): line_number, script_text, text_tagname, text_tag_start, text_tag_end, text_piece = data if 'type_text_file' in script_text: new_text_piece = self.text_file_pass else: new_text_piece = self.text_entry.get() self.get_text.destroy() self.script_pad.config(state='normal') self.script_pad.delete(text_tag_start, text_tag_end) self.script_pad.insert(text_tag_start, new_text_piece) self._scanfix_script_lines(None) # -- sleep & other action functions -- # # def _append_other_action(self, script_text): script_line = script_text self.script_pad.insert(END, script_line) self._scanfix_script_lines(None)
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
class GUI: def __init__(self): self.version = "2.1" self.root = Tk() self.root.title("IMSafe %s --- By: Patrick T. Cossette" % self.version) self.encryptionFunction = IMCrypt2.encryptText self.decryptionFunction = IMCrypt2.decryptText self.useNewMethod = IntVar() self.useNewMethod.set(1) self.key = "Red Castle" self.server = StringVar() self.username = StringVar() self.username.set(environ["USER"]) self.settingsUp = False self.connected = False self.master = None self.usernamePreview = StringVar() self.usernamePreview.set(self.username.get()) self.all_recipts = [] self.keyTxt = StringVar() self.keyTxt2 = StringVar() self.keyTxt.set(self.key) self.keyTxt2.set(self.key) self.queue = Queue.Queue() self.server.set("http://www.example.com/IMSafe.php") self.network = IMNetwork.IMNetwork() self.network.screen_name = self.username.get() self.network.address = self.server.get() self.scheme = IntVar() self.scheme.set(1) #color scheme, 1 = green on black. #Foreground, background, insertion cursor, entry background, username highlight, foreign username highlight self.colorSchemes = [ ("green", "black", "red", "gray", "red", "blue"), ("black", "white", "black", "white", "blue", "red"), ("red", "black", "green", "gray", "green", "blue"), ("yellow", "black", "blue", "gray", "blue", "green"), ("blue", "black", "purple", "gray", "red", "black"), ("black", "gray", "black", "gray", "blue", "red"), ("black", "blue", "white", "blue", "white", "black"), ("black", "white", "black", "white", "blue", "red"), ("green", "black", "red", "gray", "red", "blue") ] self.fontSize = 15 self.checked = IntVar() self.checked.set(1) self.alwaysOntop = IntVar() self.alwaysOntop.set(0) self.fullscreen = IntVar() self.fullscreen.set(0) self.previousSize = "" self.playSoundWithFocus = IntVar() self.playSoundWithoutFocus = IntVar() self.playSoundOnRecieve = IntVar() self.playSoundOnSend = IntVar() self.mute = IntVar() self.playingSound = False #Prevents overlap when recieving a massive numbger of messages self.playSoundWithFocus.set(1) self.playSoundWithoutFocus.set(1) self.playSoundOnRecieve.set(1) self.playSoundOnSend.set(1) self.mute.set(0) self.tags = 0 #Keep up with tags while highlighting text filemenu = Menu(self.root, tearoff=0) filemenu.add_command(label="Open Encrypted File ⌘O", command=self.openFile) filemenu.add_command(label="Save Encrypted File ⌘S", command=self.saveFile) filemenu.add_command(label="Open Text File ⌘T", command=self.openText) filemenu.add_command(label="Save Text File", command=self.saveText) filemenu.add_separator() filemenu.add_command(label="Encrypt File ⌘E", command=self.encryptFile) filemenu.add_command(label="Decrypt File ⌘D", command=self.decryptFile) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.root.destroy) encryptmenu = Menu(self.root, tearoff=0) encryptmenu.add_checkbutton(label="Use Latest Encryption Method", command=self.setMethod, variable=self.useNewMethod) self.chatmenu = Menu(self.root, tearoff=0) self.chatmenu.add_command( label="Connect", command=lambda: self.connectToServer(self.server.get())) self.chatmenu.add_command(label="Disconnect", command=self.disconnectFromServer, state="disabled") self.chatmenu.add_separator() self.chatmenu.add_command(label="Settings", command=self.settings) viewmenu = Menu(self.root, tearoff=0) viewmenu.add_checkbutton(label="Word Wrap ⌘W", command=self.toggleWrap, variable=self.checked) viewmenu.add_command(label="Clear Screen", command=lambda: self.txt.delete(1.0, END)) viewmenu.add_separator() viewmenu.add_command(label="Increase Font ⌘Num+", command=self.increaseFont) viewmenu.add_command(label="Decrease Font ⌘Num-", command=self.decreaseFont) viewmenu.add_checkbutton(label="Always Ontop", command=lambda: self.root.wm_attributes( "-topmost", self.alwaysOntop.get()), variable=self.alwaysOntop) viewmenu.add_checkbutton( label="Fullscreen F11", command=self.toggleFullscreen, variable=self.fullscreen) viewmenu.add_separator() colrmenu = Menu(self.root, tearoff=0) colrmenu.add_radiobutton( label="Color Scheme 1 F1", command=self.changeScheme, variable=self.scheme, value=1) colrmenu.add_radiobutton( label="Color Scheme 2 F2", command=self.changeScheme, variable=self.scheme, value=2) colrmenu.add_radiobutton( label="Color Scheme 3 F3", command=self.changeScheme, variable=self.scheme, value=3) colrmenu.add_radiobutton( label="Color Scheme 4 F4", command=self.changeScheme, variable=self.scheme, value=4) colrmenu.add_radiobutton( label="Color Scheme 5 F5", command=self.changeScheme, variable=self.scheme, value=5) colrmenu.add_radiobutton( label="Color Scheme 6 F6", command=self.changeScheme, variable=self.scheme, value=6) colrmenu.add_radiobutton( label="Color Scheme 7 F7", command=self.changeScheme, variable=self.scheme, value=7) colrmenu.add_radiobutton( label="Color Scheme 8 F8", command=self.changeScheme, variable=self.scheme, value=8) colrmenu.add_radiobutton( label="Color Scheme 9 F9", command=self.changeScheme, variable=self.scheme, value=9) viewmenu.add_cascade(label="Color Scheme", menu=colrmenu) soundmenu = Menu(self.root, tearoff=0) soundmenu.add_command(label="Play Sound When:", state="disabled") soundmenu.add_checkbutton(label="Chat has focus", command=self.saveConfiguration, variable=self.playSoundWithFocus) soundmenu.add_checkbutton(label="Chat doesn't have focus", command=self.saveConfiguration, variable=self.playSoundWithoutFocus) soundmenu.add_checkbutton(label="Recieving Messages", command=self.saveConfiguration, variable=self.playSoundOnRecieve) soundmenu.add_checkbutton(label="Sending Messages", command=self.saveConfiguration, variable=self.playSoundOnSend) soundmenu.add_separator() soundmenu.add_checkbutton( label="Mute ⌘M", command=self.saveConfiguration, variable=self.mute) helpmenu = Menu(self.root, tearoff=0) helpmenu.add_command(label="Help", command=self.showHelp) helpmenu.add_command(label="About", command=self.showAbout) menubar = Menu(self.root) menubar.add_cascade(label="File", menu=filemenu) menubar.add_cascade(label="Encryption", menu=encryptmenu) menubar.add_cascade(label="Chat", menu=self.chatmenu) menubar.add_cascade(label="View", menu=viewmenu) menubar.add_cascade(label="Sound", menu=soundmenu) menubar.add_cascade(label="Help", menu=helpmenu) self.root.config(menu=menubar) self.chat = StringVar() self.root.rowconfigure(0, weight=1) self.root.columnconfigure(0, weight=1) self.txt = ScrolledText(self.root, wrap=WORD, fg='green', bg='black', font=("Courier", 14), width=80, insertbackground="red", insertwidth=3, maxundo=5, undo=True) self.txt.grid(sticky=N + S + E + W) self.txt.rowconfigure(0, weight=1) self.txt.columnconfigure(0, weight=1) self.inputVar = StringVar() self.input = Entry(self.root, textvariable=self.inputVar, font=("Courier", 14), width=115, bg="gray", fg="black") self.input.grid(sticky=N + S + E + W) self.input.bind("<Return>", self.sendText) self.input.rowconfigure(0, weight=1) self.input.columnconfigure(0, weight=1) self.input.focus() self.root.bind("<Command-s>", self.saveFile) self.root.bind("<Command-o>", self.openFile) self.root.bind("<Command-t>", self.openText) self.root.bind("<Command-d>", self.decryptFile) self.root.bind("<Command-e>", self.encryptFile) self.root.bind("<Command-+>", self.increaseFont) self.root.bind("<Command-=>", self.increaseFont) self.root.bind("<Command-minus>", self.decreaseFont) self.root.bind("<Command-a>", self.selectAll) self.root.bind("<Command-m>", self.toggleMute) self.root.bind("<F11>", self.toggleFullscreen) self.root.bind("<F1>", lambda (Event): self.setScheme(1)) self.root.bind("<F2>", lambda (Event): self.setScheme(2)) self.root.bind("<F3>", lambda (Event): self.setScheme(3)) self.root.bind("<F4>", lambda (Event): self.setScheme(4)) self.root.bind("<F5>", lambda (Event): self.setScheme(5)) self.root.bind("<F6>", lambda (Event): self.setScheme(6)) self.root.bind("<F7>", lambda (Event): self.setScheme(7)) self.root.bind("<F8>", lambda (Event): self.setScheme(8)) self.root.bind("<F9>", lambda (Event): self.setScheme(9)) self.root.wm_iconbitmap("%s\\icon.ico" % getcwd()) self.addText("IMSafe %s\nBy: Patrick T. Cossette\n\n" % self.version) self.network.updateCallback = self.recvMessage self.loadConfiguration() def setMethod(self): if self.useNewMethod.get(): print "using new method" self.encryptionFunction = IMCrypt2.encryptText self.decryptionFunction = IMCrypt2.decryptText else: print "using old method" self.encryptionFunction = IMCrypt.encryptText self.decryptionFunction = IMCrypt.decryptText def toggleMute(self, Event): if self.mute.get(): self.mute.set(0) else: self.mute.set(1) def saveConfiguration(self): f = file(r"%s\settings.conf" % getcwd(), 'w') f.write( "%d\n%s\n%s\n%s\n%s\n%s\n%s\n%s" % (self.scheme.get(), self.server.get(), self.username.get(), self.playSoundWithFocus.get(), self.playSoundWithoutFocus.get(), self.playSoundOnRecieve.get(), self.playSoundOnSend.get(), self.mute.get())) f.close() def loadConfiguration(self): try: f = file(r"%s\settings.conf" % getcwd(), 'r') settings = f.read() settings = settings.split("\n") if len(settings ) < 8: #Make sure the settings file is intact and complete self.saveDefaultSettings() else: self.scheme.set(int(settings[0])) self.server.set(settings[1]) self.username.set(settings[2]) self.playSoundWithFocus.set(int(settings[3])) self.playSoundWithoutFocus.set(int(settings[4])) self.playSoundOnRecieve.set(int(settings[5])) self.playSoundOnSend.set(int(settings[6])) self.mute.set(int(settings[7])) self.setScheme(self.scheme.get()) f.close() except: #make sure the file is actually there, and intact with proper values, if not, revert to default settings self.saveDefaultSettings() def saveDefaultSettings(self): f = file(r"%s\settings.conf" % getcwd(), 'w') f.write( "1\nhttp://www.example.com/imsafe/IMSafe.php\n%s\n1\n1\n1\n1\n0" % environ["USER"]) f.close() def updateChatMenu(self): if self.connected: #self.txt["state"] = "disabled" self.chatmenu.entryconfig(0, state="disabled") self.chatmenu.entryconfig(1, state="normal") else: #self.txt["state"] = "normal" self.chatmenu.entryconfig(0, state="normal") self.chatmenu.entryconfig(1, state="disabled") def recvMessage(self, message): if message[0:6] == "update": message = message[6::] highlight = 5 #If the message is from the user, use a different highlight color for the username ^_^ allMessages = message.split("<message_separator>") for message in allMessages: seg = message.split("<time_separator>") name = seg[0] print "appending recipts" self.network.recipts.append(seg[1]) #Log this message recipt if seg[1] in self.all_recipts: return self.all_recipts.append(seg[1]) d = seg[2] #Encrypted Message id = name.split(" ")[0][1::] if id == self.username.get(): #Sent a message! highlight = 4 if self.playSoundOnSend.get(): self.notifacation(txt="send") else: #Recieving a message! if self.playSoundOnRecieve.get(): self.notifacation(txt="recv") self.addText(name) #Usernames get fancy color shit. lines = len(self.txt.get(1.0, END).split("\n")) - 1 columns = len(name) self.txt.tag_add( str(self.tags), float(lines), ".".join([str(lines), str(columns + 1)]) ) #just for the record, the way the tag index works is F*****G RETARDED. self.txt.tag_config( str(self.tags), foreground=self.colorSchemes[self.scheme.get() - 1][highlight], font=("courier", self.fontSize, "bold")) self.tags += 1 self.txt.update_idletasks() self.txt.tag_add( str(self.tags), ".".join([str(lines), str(len(name.split(" ")[0]) + 1)]), ".".join([str(lines), str(columns)])) self.txt.tag_config(str(self.tags), font=("courier", self.fontSize - 1)) self.tags += 1 self.addText(self.decryptionFunction(d, self.key) + "\n") elif message[0:4] == "list": message = message[4::] self.addText("\n\nUsers currently logged in: \n") for user in message.split(","): self.addText(user + "\n") lines = len(self.txt.get(1.0, END).split("\n")) - 2 columns = len(user) self.txt.tag_add(str(self.tags), float(lines), ".".join([str(lines), str(columns + 1)])) self.txt.tag_config( str(self.tags), foreground=self.colorSchemes[self.scheme.get() - 1][4]) self.tags += 1 def notifacation(self, txt="recv"): if self.mute.get(): return if (self.root.focus_displayof() and self.playSoundWithFocus.get() or (not self.root.focus_displayof() and self.playSoundWithoutFocus.get())): threading._start_new_thread(self.playSound, ("%s.wav" % txt, )) def selectAll(self, event=None): return self.txt.focus_set() self.txt.tag_add(SEL, "1.0", END) self.root.after(4, self.selectAll) def toggleFullscreen(self, event=None): if event: if self.fullscreen.get(): self.fullscreen.set(0) else: self.fullscreen.set(1) if self.fullscreen.get(): self.previousSize = self.root.geometry() #self.root.geometry("%dx%d+0+0" % (self.root.winfo_screenwidth(), self.root.winfo_screenheight())) #Using state("zoomed") instead. this method causes the user's text Entry bar to fall off the screen unless the window is maximized first self.root.state("zoomed") self.root.overrideredirect(1) else: self.root.state("normal") self.root.overrideredirect(0) self.root.geometry(self.previousSize) def increaseFont(self, event=None): geo = self.root.geometry() #preserve window size self.fontSize += 1 self.txt["font"] = ("courier", self.fontSize) self.input["font"] = ("courier", self.fontSize) self.root.geometry(geo) def decreaseFont(self, event=None): geo = self.root.geometry() if self.fontSize < 6: return self.fontSize -= 1 self.txt["font"] = ("courier", self.fontSize) self.input["font"] = ("courier", self.fontSize) self.root.geometry(geo) def setScheme(self, s): self.scheme.set(s) self.changeScheme() def changeScheme(self): s = self.scheme.get() - 1 self.txt["fg"] = self.colorSchemes[s][0] self.txt["bg"] = self.colorSchemes[s][1] self.txt["insertbackground"] = self.colorSchemes[s][2] self.input["bg"] = self.colorSchemes[s][3] if s > 5: #Black on blue gets bold text =D self.txt["font"] = ("courier", self.fontSize, "bold") self.input["font"] = ("courier", self.fontSize, "bold") else: self.txt["font"] = ("courier", self.fontSize) self.input["font"] = ("courier", self.fontSize) self.saveConfiguration() def toggleWrap(self, event=None): if self.txt["wrap"] == WORD: self.txt["wrap"] = NONE else: self.txt["wrap"] = WORD def showHelp(self): self.addText( "\n\nCommands:\n /help - display this help screen\n /about - show the about page\n /clear - clear all text from the screen\n /me - send text in 3rd person\n /setkey <key> - change the encryption key to '<key>'\n /setname <name> - set your display name in the chatroom to '<name>'\n /list - Get a list of people currenlty logged on\n /settings - Show current settings\n /connect <ip address> - connect to an IMSafe server\n /disconnect - disconnect from the IMSafe server\n /exit - close the window\n\nThis software's encryption methods are only suitable for plain text. Attempting to encrypt videos, images, or any files other than those containing plain text will likely result in error!\n\nThe default key is \"Red Castle\", it is highly recommended that you change the key prior to using this software; the key will reset to the default every time the program is opened, for security purposes the key you choose is not remembered, you will have to re-enter it every time you wish to use this software, this can be done by going to Chat->Settings or using the /setkey command.\n\n" ) #Highlight all the commands lines = len(self.txt.get(1.0, END).split("\n")) for a, b in zip( (7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17), ("6", "12", "9", "10", "6", "9", "8", "4", "7", "7", "6")): self.txt.tag_add(str(self.tags), float(lines - a), ".".join([str(lines - a), b])) self.txt.tag_config(str(self.tags), foreground=self.colorSchemes[self.scheme.get() - 1][4]) def showAbout(self): self.addText( "\n\nCreated By: Patrick T. Cossette\nwww.DigitalDiscrepancy.com\n\nThis software is an example of a simple encryption algorithm. This software was written for the purpose of demonstration and experimentation and is probably not suitable to send or store sensitive information. Use at your own risk.\n\n Licensed under GNU General Public License, version 2, see LICENSE for more info" ) lines = len(self.txt.get(1.0, END).split("\n")) self.txt.tag_add(str(self.tags), float(lines - 7) + .12, ".".join([str(lines - 7), '33'])) self.txt.tag_config(str(self.tags), foreground=self.colorSchemes[self.scheme.get() - 1][4]) def encryptFile(self, event=None): f = self.openText(show=False) if not f: return self.saveFile(fileName=f[0], text=f[1]) def decryptFile( self, event=None ): #Attempt to decrypt something thats not encrypted and you'll lose that file. forever. seriously. don't do it. f = self.openFile(show=False) if not f: return self.saveText(fileName=f[0], text=f[1]) def openText(self, event=None, show=True): fileName = tkFileDialog.askopenfilename(title="Open Text File", filetypes=[ ("Text File", ".txt"), ("All Files", ".*") ]) if fileName == "": return False self.txt.delete(1.0, END) open = file(fileName, 'r') text = open.read() if show: self.txt.insert(END, text) open.close() return (fileName, text) def saveText(self, event=None, fileName=None, text=None): if fileName == None: fileName = tkFileDialog.asksaveasfilename(title="Save Text File", filetypes=[("Text File", ".txt"), ("All Files", ".*")]) if fileName == "": return False if len(fileName) > 3: if fileName[-4::] != ".txt": fileName += ".txt" else: fileName += ".txt" save = file(fileName, 'w') if text: save.write(text) else: save.write(self.txt.get(1.0, END)) save.close() def openFile(self, event=None, show=True): fileName = tkFileDialog.askopenfilename(title="Open Encrypted File", filetypes=[ ("Encrypted Text File", ".txt"), ("All Files", ".*") ]) if fileName == "": return False self.txt.delete(1.0, END) open = file(fileName, 'rb') text = open.read() open.close() if show: self.txt.insert(END, self.decryptionFunction(text, self.key)) else: return (fileName, self.decryptionFunction(text, self.key)) def saveFile(self, event=None, fileName=None, text=False): if fileName == None: fileName = tkFileDialog.asksaveasfilename( title="Save Encrypted File", filetypes=[("Encrypted Text File", ".txt"), ("All Files", ".*")]) if fileName == "": return False if len(fileName) > 3: if fileName[-4::] != ".txt": fileName += ".txt" else: fileName += ".txt" save = file(fileName, 'wb') if text: save.write(self.encryptionFunction(text, self.key)) else: save.write( self.encryptionFunction(self.txt.get(1.0, END), self.key)) save.close() def sendText(self, event): text = self.inputVar.get() if not len(text): return if text[0] == "/": #user has entered a command, not a message if len(text) > 5 and text[0:6] == "/clear": self.txt.delete(1.0, END) elif len(text) > 8 and text[0:7] == "/setkey": self.key = text.split("/setkey ")[1] elif len(text) > 9 and text[0:8] == "/setname": self.username.set(text.split("/setname ")[1]) self.usernamePreview.set(self.username.get()) self.network.screen_name = self.username.get() self.saveConfiguration() elif len(text) > 7 and text[0:8] == "/connect": if len(text) > 9 and text[0:9] == "/connect ": self.server.set(text.split("/connect ")[1]) self.saveConfiguration() self.connectToServer(self.server.get()) elif len(text) > 10 and text[0:11] == "/disconnect": self.disconnectFromServer() elif len(text) > 4 and text[0:5] == "/exit": self.root.destroy() elif len(text) > 4 and text[0:5] == "/help": self.showHelp() elif len(text) > 8 and text[0:9] == "/settings": self.addText( "\n\nServer: %s\nUsername: %s\nkey: %s\n" % (self.server.get(), self.username.get(), self.key)) elif len(text) > 5 and text[0:6] == "/about": self.showAbout() elif len(text) > 2 and text[0:3] == "/me": self.sendChat( text ) #This command will be caught within the sendChat function, as it is a message manipulator elif len(text) > 4 and text[0:5] == "/list": if self.connected: self.network.list() #List other users on the server else: self.addText( "You are not currently connected to a chatroom!\n") else: self.addText( "Invalid Command - Type /help for a list of commands\n") else: self.sendChat(text) self.inputVar.set("") def playSound(self, sound): if self.playingSound: #Prevent overlap! return return_code = subprocess.call(["afplay", sound]) chunk = 1024 # Simple "fire and forget" notification doesntWorkonMac = """ self.playingSound = True wf = wave.open(sound, 'rb') p = pyaudio.PyAudio() stream = p.open(format = p.get_format_from_width(wf.getsampwidth()), channels = wf.getnchannels(), rate = wf.getframerate(), output = True) data = wf.readframes(chunk) while data != '': stream.write(data) data = wf.readframes(chunk) stream.close() p.terminate() self.playingSound = False """ def sendChat(self, message): if not self.connected: self.addText( "\nYou are not connected to an IMSafe server. Use the /connect command to connect to a server or go to Chat -> Connect\n\n" ) else: print "\n\nsending chat: ", message if len(message) > 4 and message[0:3] == "/me": responce = self.network.sendData(self.encryptionFunction( message[4::], self.key), options="first_person") else: responce = self.network.sendData( self.encryptionFunction(message, self.key)) if responce[0] != 2: self.connected = False self.updateChatMenu() self.addText(responce[1] + "\n") print "\n\nresponse: ", responce def addText(self, text): self.txt.insert(END, text) self.txt.yview(MOVETO, 1.0) #self.root.after(500, self.update_me) def show(self): self.loadConfiguration self.root.mainloop() def closeSettings(self): self.settingsUp = False def disconnectFromServer(self): self.addText("\n\nYou have disconnected from the server\n\n") self.network.disconnect() self.connected = False self.updateChatMenu() def connectToServer(self, address): self.network.screen_name = self.username.get() self.network.address = self.server.get() self.addText("\n\nConnecting to server at " + address + " ...\n\n") self.root.update() res = self.network.connect() if res[0]: self.connected = True self.addText(res[1] + "\n") else: self.connected = False self.addText("Connection Failed!\n\n%s\n" % res[1]) self.updateChatMenu() def saveSettings(self): if self.txtKey.get() == "" or self.txtKey2.get() == "": showerror( "D=", "Your key can't be blank!\n\nPlease enter a valid key, the longer the better!." ) elif self.txtKey.get() != self.txtKey2.get(): showerror("D=", "The keys you entered do not match!") else: showinfo(":)", "Your settings haved been saved!") self.key = self.txtKey.get() self.username.set(self.usernamePreview.get()) self.network.screen_name = self.username.get() self.network.address = self.server.get() self.saveConfiguration() self.master.focus_force() def settings(self): self.settingsUp = True self.master = Toplevel(self.root) self.master.title("Settings") self.master.wm_iconbitmap("%s\\icon.ico" % getcwd()) if self.alwaysOntop.get(): self.alwaysOntop.set(0) self.root.wm_attributes("-topmost", 0) self.addText("\"Always onotop\" feature deactivated\n") self.usernamePreview.set(self.username.get()) self.keyTxt.set(self.key) self.keyTxt2.set(self.key) self.f = Frame(self.master) self.lblServer = Label(self.f, text="Server: ") self.lblServer.grid(row=0, column=0, sticky=E, pady=2, padx=2) self.txtServer = Entry(self.f, textvariable=self.server) self.txtServer.grid(row=0, column=1, pady=2, padx=2) self.lblUser = Label(self.f, text="Screename: ") self.lblUser.grid(row=1, column=0, sticky=E, pady=2, padx=2) self.txtUser = Entry(self.f, textvariable=self.usernamePreview) self.txtUser.grid(row=1, column=1, pady=2, padx=2) self.lblKey = Label(self.f, text="Key: ") self.lblKey.grid(row=2, column=0, sticky=E, pady=2, padx=2) self.txtKey = Entry(self.f, textvariable=self.keyTxt, show="*") self.txtKey.grid(row=2, column=1, pady=2, padx=2) self.lblKey2 = Label(self.f, text="Confirm: ") self.lblKey2.grid(row=3, column=0, sticky=E, pady=2, padx=2) self.txtKey2 = Entry(self.f, textvariable=self.keyTxt2, show="*") self.txtKey2.grid(row=3, column=1, pady=2, padx=2) self.f.grid(rowspan=2, columnspan=4) Button(self.master, width=15, text="Save Settings", command=self.saveSettings).grid(row=5, column=0, pady=4, padx=4) Button(self.master, width=15, text="Exit", command=self.master.destroy).grid(row=5, column=1, pady=4, padx=4) self.master.focus_set() self.master.grab_set() self.root.wait_window(self.master) self.master.mainloop()
class Editor: def __init__(self, root): self.active_filename = None self.filename_label = Label(root, text='No file specified!', fg='purple', font=('times', 18, 'italic')) self.filename_label.pack() frame = Frame(root) frame.pack() frame.configure(background='black') root.title("Editor") # Create a text frame self.textPad = ScrolledText(root, width=60, height=30) self.textPad.pack() # Create an open button self.open_button = Button(frame, text='Open', width=15, fg='blue', command=self.open_command) self.open_button.pack(padx=5, pady=5, side=LEFT) # Create a create button self.edit_button = Button(frame, text='Create', width=15, fg='blue', command=self.create_command) self.edit_button.pack(padx=5, pady=5, side=LEFT) # Create a save button self.save_button = Button(frame, text='Save', width=15, fg='blue', command=self.save_command) self.save_button.pack(padx=5, pady=5, side=LEFT) # Create a close button self.close_button = Button(frame, text='Close', width=15, fg='blue', command=self.exit_command) self.close_button.pack(padx=5, pady=5, side=LEFT) # Rewrite an active file def save_command(self): if self.active_filename is not None: self.filename_label.config(text = 'Editing: ' + basename(self.active_filename)) a = self.textPad.get('1.0', END) f = open(self.active_filename, 'w') f.write(a) f.close() # Exit from tk def exit_command(self): if tkMessageBox.askokcancel("Quit", "Are you sure?"): root.destroy() # Open file def open_command(self): file = tkFileDialog.askopenfile(parent=root, mode='rb', title='Select a file', **FILEOPENOPTIONS) if file != None: self.active_filename = file.name self.filename_label.config(text='Editing: ' + basename(self.active_filename)) data = file.read() self.textPad.delete('1.0', END) self.textPad.insert('1.0', data) file.close() def create_command(self): # Create a child window self.child = Toplevel(root) self.child.title("Create a file") self.child.geometry('250x75') # Create a label Label(self.child, text='Enter a filename', ).grid(row=0, padx=5) # Create an entry widget entry_filename = Entry(self.child) entry_filename.grid(row=0, column=1) def get_filename(): self.active_filename = entry_filename.get() if not self.active_filename: return if '.txt' not in self.active_filename: self.active_filename += '.txt' self.filename_label.config(text='Editing: ' + basename(self.active_filename)) self.textPad.delete('1.0', END) self.child.destroy() # Save a filename button Button(self.child, text='Confirm!', command=get_filename).grid(row=1, column=1, sticky=W, pady=5)
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