class NFrame(Frame): """docstring for ClassName""" #Crea el Frame principal y coloca imagenes #parametros #@[in] master es la ventana padre donde se colocara el frame #@[in] inicial es un boolean que es True si es el primer frame creado #@[in] img es un boolean que indica si debe de pregargar texturas para un frame #si no le proporcionamos ningun dato a incial tendra por defecto True def __init__(self, master, inicial=True, img=False): Frame.__init__(self, master) self.master = master self.__list_label = [] self.__list_listbox = [] self.__list_scrollbar = [] self.__list_button = [] self.__texture = [] if inicial == True: self.init_window(master) if img == True: self.__loadIMG() #add imagenes dependiendo del tipo de sistema sobre el que opera el programa #Modifica las caracteristicas de la ventana principal def init_window(self, master): self.master.title("MOTVIAL") if sys.platform.startswith('win32'): self.master.iconbitmap("image\\cod.ico") elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): #self.master.iconbitmap("image/cod.ico") pass self.master.geometry("1114x608") self.master.configure(bg="#353535") self.master.resizable(1, 1) self.configure(height=300, width=10, background="#353535") self.pack(side=RIGHT, ipadx=0, ipady=0) #Precarga las texturas para despuer ser recortadas def __loadIMG(self): try: if sys.platform.startswith('win32'): ruta = "image\\texture.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/texture.png" self.__texture.append(Image.open(ruta)) except Exception as e: pass #Permite configurar un frame creado def ConfigureF(self, ax=600, ay=52, x=0, y=0, bg="#353535"): self.configure(height=ay, width=ax, background=bg) self.place(x=x, y=y) #Crea un Label def addLabel(self, textvar="NONE", ax=4, ay=10, x=0, y=0, bg="#353535", fontcolor="#FFFFFF"): label = Label(self, height=ay, width=ax, background=bg, text=textvar, fg=fontcolor) label.place(x=x, y=y) self.__list_label.append(label) return label #Crea un TextBox def addListBox(self, ax=600, ay=52, x=0, y=0, bg="#B4045F"): scrolly = Scrollbar(self, activebackground="#171212", bg="#171212", orient=VERTICAL, troughcolor="#171212") listbox = Listbox(self, height=ay, width=ax, background=bg, borderwidth=0, highlightcolor="#4d86a1", selectbackground="#4d86a1", activestyle=NONE, highlightbackground="#4a4a4a", yscrollcommand=scrolly.set) listbox.config(font=("", 10), fg="#FFFFFF") listbox.place(x=0, y=0) scrolly.place(x=651, y=0, height=387) self.__list_listbox.append(listbox) self.__list_scrollbar.append(scrolly) for x in self.__list_listbox: x.configure(yscrollcommand=scrolly.set) scrolly.configure(command=self.__yview) #metodo privado add scrollbar a los textbox def __yview(self, *args): for x in self.__list_listbox: x.yview(*args) def clickEventListbox(self, index): self.__list_listbox[index].configure(selectmode=SINGLE) self.__list_listbox[index].bind('<Double-1>', self.__openImage) def Error(self, error="Se produjo un error"): Ventana2 = Toplevel(self.master) Ventana2.configure(height=100, width=260, bg="#4a4a4a") Ventana2.title("Error") Error = Label(Ventana2, text=error, bg="#4a4a4a", fg="#FFFFFF") Error.place(x=40, y=15) Error.config(font=("", 12)) Salir = Button(Ventana2, width=10, text="Salir", command=Ventana2.destroy) Salir.place(x=85, y=55) def __openImage(self, event): try: index = self.__list_listbox[0].get( self.__list_listbox[0].curselection()) #print(index[3:16]) if str(index[3:16]) != "Serial Number": if sys.platform.startswith('win32'): root = "image\\" + str(index[3:9]) + ".jpg" elif sys.platform.startswith( 'linux') or sys.platform.startswith('darwin'): root = "image/" + str(index[3:9]) + ".jpg" #print(root) im = imread(root) imshow("image", im) except Exception as e: self.Error("Error al cargar la imagen") #add texto en pantalla def addText(self, x, text, n): self.__list_listbox[x].insert(END, text) if (n + 2) % 2 == 0: self.__list_listbox[x].itemconfigure(n, bg="#696969") def retTextBox(self, x): return self.__list_listbox[x] #add button def addButtonI(self, dim=(0, 0, 206, 109), x=0, y=0, command=0): try: crop = self.__texture[0].crop(dim) render = ImageTk.PhotoImage(crop) nbutton = Button(self, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1") nbutton.image = render nbutton.place(x=x, y=y) self.__list_button.append(nbutton) if command == 1: nbutton.configure(command=self.showOne) elif command == 2: nbutton.configure(command=self.showAll) elif command == 3: pass elif command == 4: nbutton.configure(command=self.master.destroy) return nbutton except Exception as e: self.Error("Error al cargar Texturas") return -1 def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def yview(self, *args): self.listbox1.yview(*args) def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def Switch(self, root, Ventana2): root.deiconify() Ventana2.destroy() def load50(self, Poss, mode="a"): maxi = self.buscMax() I = Poss[0] F = Poss[1] if mode == "+": Poss[1] = Poss[1] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) Poss[0] = Poss[1] - 50 if Poss[0] < 0: Poss[0] = 0 elif mode == "-" and Poss[0] != 0: Poss[0] = Poss[0] - 50 if Poss[0] < 0: Poss[0] = 0 Poss[1] = Poss[0] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) if mode == "a" or Poss[0] != I or Poss[1] != F: asca = ManagementJson("Helloword.json") lista = asca.intervaloIF(Poss[0], Poss[1]) #cargando texto self.listbox1.delete(0, self.listbox1.size()) for x in range(0, len(lista["serial"])): if lista["status"][x] == "Riesgo Medio": self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) else: self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) def buscMax(self): f = open("config.txt", "r") f.seek(7) maxi = f.readline() f.close() return maxi def load1(self, listbox3, label1, label2, label3): asca = ManagementJson("Helloword.json") lista = asca.searchError(listbox3.get()) try: if lista == 0: label1.configure(text="No se encontro") label2.configure(text="No se encontro") label3.configure(text="No se encontro") return 0 except Exception as e: raise e label1.configure(text=lista[0]) label2.configure(text=lista[1]) label3.configure(text=lista[2])
class ChooseNameUI(Frame): def __init__(self, parent,names=["1","2","3"]): Frame.__init__(self, parent) self.parent = parent self.names = names self.initUI() self.centerWindow() def initUI(self): self.parent.title("选择角色名字") self.pack(fill=BOTH, expand=1) "source list" self.lb = Listbox(self) for i in self.names: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.place(x=80, y=20) "right list" self.lbRight = Listbox(self) #self.lbRight.bind("<<ListboxSelect>>", self.onSelect) self.lbRight.place(x=150, y=240) "left list" self.lbLeft = Listbox(self) #self.lbLeft.bind("<<ListboxSelect>>", self.onSelect) self.lbLeft.place(x=20, y=240) "label" self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=120, y=400) "left button" leftButton = Button(self, text="增加到自己的名字", command=self.leftClick) leftButton.place(x=20,y=180) "left add all button" leftAddAllBtn = Button(self, text="添加剩下的名字到自己", command=self.leftAddAllClick) leftAddAllBtn.place(x=20,y=210) "right button" rightButton = Button(self, text="增加到对方的名字", command=self.rightClick) rightButton.place(x = 150, y = 180) "right add all button" rightAddAllBtn = Button(self, text="添加剩下的名字到对方", command=self.rightAddAllClick) rightAddAllBtn.place(x=150,y=210) "move to right button" left2RightBtn = Button(self, text="移动到自己", command=self.move2Left) left2RightBtn.place(x=150,y=380) "move to left button" left2RightBtn = Button(self, text="移动到对方", command=self.move2Right) left2RightBtn.place(x=20,y=380) "finish button" self.finishBtn = Button(self, text="选择完毕", command = self.finishClick) self.finishBtn.place(x = 120 , y = 420) def onSelect(self, val): sender = val.widget idx = sender.curselection() if idx: value = sender.get(idx) self.var.set(value) def leftClick(self): str = self.var.get() if str is not None and str != "": self.lbLeft.insert(END,str) self.removeSelection() def rightClick(self): str = self.var.get() if str is not None and str != "": self.lbRight.insert(END,str) self.removeSelection() def removeSelection(self): index = self.lb.curselection() self.lb.delete(index,index) self.var.set("") "if select all data finish" if not self.lb.get(0): self.finishClick() def finishClick(self): if self.lb.get(0): box.showerror("错误", "还有名字没加入") else: if not self.lbLeft.get(0): box.showerror("错误", "没有自己的名字,请选择") elif not self.lbRight.get(0): box.showerror("错误", "没有对方的名字,请选择") else: "get the two list and generate json" myList = [self.lbLeft.get(i) for i in xrange(self.lbLeft.size())] herList = [self.lbRight.get(i) for i in xrange(self.lbRight.size())] #conversationtool.generateJSON(myList,herList) t = conversationtool.generateThread(myList,herList) t.start() t.join() def rightAddAllClick(self): while self.lb.get(0): value = self.lb.get(0) self.lb.delete(0) self.lbRight.insert(END , value) self.var.set("") def leftAddAllClick(self): while self.lb.get(0): value = self.lb.get(0) self.lb.delete(0) self.lbLeft.insert(END,value) self.var.set("") def move2Right(self): index = self.lbLeft.curselection() if index: value = self.lbLeft.get(index) self.lbLeft.delete(index) self.lbRight.insert(END, value) else: box.showerror("错误", "请选择自己的名字") def move2Left(self): index = self.lbRight.curselection() if index: value = self.lbRight.get(index) self.lbRight.delete(index) self.lbLeft.insert(END , value) else: box.showerror("错误", "请选择对方的名字") def centerWindow(self): w = 300 h = 450 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented") else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError("If not guiven complete function, list_of_items can't be 'None'") if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index +=1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
class LintGui: """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=E) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, columnspan=2, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I' : lambda : self.information_box.get() == 1, 'C' : lambda : self.convention_box.get() == 1, 'R' : lambda : self.refactor_box.get() == 1, 'E' : lambda : self.error_box.get() == 1, 'W' : lambda : self.warning_box.get() == 1, 'F' : lambda : self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) for msg in self.msgs: if (self.msg_type_dict.get(msg[0])()): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def convert_to_string(self, msg): """make a string representation of a message""" if (msg[2] != ""): return "(" + msg[0] + ") " + msg[1] + "." + msg[2] + " [" + msg[3] + "]: " + msg[4] else: return "(" + msg[0] + ") " + msg[1] + " [" + msg[3] + "]: " + msg[4] def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg[0])()): msg_str = self.convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename+'\n' in self.filenames: index = self.filenames.index(filename+'\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename+'\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME+HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=(module, self.reporter, self,)) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME+HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='')
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol('WM_DELETE_WINDOW', self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", \ self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, \ text="init", \ command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, \ text="next slide", \ command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, \ text="previous slide", \ command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, \ text="start timer", \ command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, \ text="pause", \ command=self.pauseTimer) self.stopButton = Button(self.controlPanel, \ text="stop", \ command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, \ text="delay:") self.timerInput = Entry(self.controlPanel, \ width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, \ text="fade:") self.fadeInput = Entry(self.controlPanel, \ width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, \ text="standby", \ command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, \ text="sync", \ command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, \ text="reconnect", \ command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton(self.controlPanel, \ text="use all projectors", \ variable=self.cycle, \ command=self.cycleToggled) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, \ label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, \ from_=0, to=self.controller.maxTray, \ label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W , expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", \ command=self.interpretHEXDialog) self.helpmenu.add_command(label="About EktaproGUI", \ command=lambda:tkMessageBox.showinfo("About EktaproGUI", \ "EktaproGUI 1.0 (C)opyright Julian Hoch 2010")) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, \ "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness \ and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) #@UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" \ and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class JobList(Frame): # NOTE: job_params contains information about a Job in the Joblist # NOTE: plot_args contains information about plotting information, which occurs after the jobs have been and the data files have been created def __init__(self, parent=None, **kwargs): Frame.__init__(self, parent) self.parent = parent self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL) self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL) self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll) self.job_list_xscroll['command'] = self.job_list.xview self.job_list_yscroll['command'] = self.job_list.yview self.new_job_frame = Frame(self) add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None if add_icon_filename == None: self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add) else: add_icon = PhotoImage(file=add_icon_filename) self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add) self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove) self.progress_frame = Frame(self) self.progress_value = Tkinter.IntVar() self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value) self.button_frame = Frame(self) self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs) self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows) self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs) self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs) self.bind('<<CreatePlotGUI>>', self.create_plot_gui) self.parent.bind('<ButtonPress>', self.on_press) self.parent.bind('<Configure>', self.on_resize) self.reinit_variables() self.top_level_windows = list() # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized, # the resize option will be disabled for this window self.parent.resizable(width=False, height=False) self.lift() def reinit_variables(self): self.job_params = dict() self.last_job_id = -1 self.job_outcomes = list() self.plot_args = list() self.on_button = False def add_job_params(self, input_args): self.job_params = input_args # Add each element to the job list for job in self.job_params: self.add_job(job) def add_job(self, job): try: index_end = job['input_directory'].rindex('/') index_start = job['input_directory'].rindex('/', 0, index_end) input_directory_text = job['input_directory'] list_text = 'Job ' + str(job['job_id']) + ' \'' + input_directory_text + '\'' if job['start'] != None: list_text += ' ' + str(job['start']) if job['end'] != None: list_text += ' to' if job['end'] != None: list_text += ' ' + str(job['end']) if job['job_id'] > self.last_job_id: self.last_job_id = job['job_id'] self.job_list.insert(Tkinter.END, list_text) # Add the list text to the job params as an optional parameter to read later to display in a future Graph GUI (or for any other useful purpose) job['list_text'] = list_text # The line number is used wrt the GUI to indicate which job in the job list is being currently executed. job['line_number'] = self.job_list.size() - 1 #print str(job['line_number']) self.job_params[job['job_id']] = job except KeyError as ke: # Should show some error message indicating that there is a problem. pass #print str(self.job_params) #print 'Added Job ' + str(job['job_id']) def ask_to_clear_jobs(self, event): for job in self.job_params.itervalues(): line_number = job['line_number'] self.job_list.itemconfig(line_number, foreground='black') # Update parent to refresh widget appearance self.parent.update() # Reactivate process button self.process_button.config(state = Tkinter.NORMAL) # Note: Display a pop-up that tells the user that the job is done and asks if the job list should be cleared. clearList = msg.askyesno(title='Jobs Finished', message='All jobs have been completed. Would you like to clear the job list?', master=self) if clearList: self.clear_list() def ask_to_plot_graphs(self, event): # TODO: Add a dialog that also asks to create a graph of the 'Other Type Of Plot' plotGraphs = msg.askyesno(title='Plot Graphs', message='Create plots of data?', master=self) if not plotGraphs: return # TODO: Iterate through the jobs to display to the user an interface that asks if they want to graphs of the outputs if self.create_plots != None: output_files_list = list() for job_outcome in self.job_outcomes: for output_outcomes in job_outcome[2]: (station, output_directory, output_files) = output_outcomes for output_files_tuple in output_files: for output_file_tuple in output_files_tuple: (output_file, output_file_success) = output_file_tuple if output_file_success: # If there is a list text variable (the 4th (or 3rd by 0 based index) variable), then add it to our output list if len(job_outcome) == 4: output_files_list.append([output_file, job_outcome[3]]) else: output_files_list.append([output_file]) plots_thread = PlotsThread(self.create_plots, output_files_list, self) plots_thread.start() def add_plot(self, args=dict()): self.plot_args.append(args) def finished_adding_plots(self): self.event_generate('<<CreatePlotGUI>>', when='tail') def create_plot_gui(self, event): # TODO: This should be replaced with a new window that allows the user to drag and drop the icons from one frame to another graph_names = list() for args in self.plot_args: graph_name = args['output_file'] graph_names.append(graph_name) dnd_graphs_frame = Dnd.createFrame(self, 'Drag and Drop Output Plots', graph_names, self.finish_creating_plot_gui) # This is the entry point for the def finish_creating_plot_gui(self, plot_labels): graph_count = 1 for plot_label in plot_labels: for args in self.plot_args: #print 'Looking in ' + args['plot_title'] + ' for ' + plot_label #print 'The plot label is: ' + plot_label #print 'The output file is: ' + args['output_file'] if plot_label == args['output_file']: #print 'Creating graph ' + str(graph_count) graph_count += 1 graph_window = ModelRunnerGraphGUI.GraphWindow(parent=self, title=args['window_title'], df=args['df'], plot=args['plot'], plot_title=args['plot_title'], y_label=args['y_label'], log_filename=self.log_filename) graph_window.set_grid() self.top_level_windows.append(graph_window) #print 'Creating plot GUI # Have to clear out list here instead of clear_list because clear_list() removes plot_args before this method has a chance to read # them and create the appropriate plot graph windows self.reinit_variables() # Clear all the elements in the list def clear_list(self): # Save plot args because they are need later in this run plot_args = self.plot_args self.reinit_variables() # Restore the plot args self.plot_args = plot_args self.job_list.delete(0, self.job_list.size()) self.progress_value.set(0) # Update parent to refresh widget appearance self.parent.update() def on_add(self): single_job = JobParameters(parent=self.parent, beginning_year=1950, ending_year=2100, job_id=self.last_job_id + 1, entry=self) single_job.set_grid() def on_remove(self): selection = self.job_list.curselection() for line_number in selection: line_text = self.job_list.get(line_number) job_id = int(line_text[4:line_text.index(' ', 4)]) job = self.job_params.pop(job_id) self.job_list.delete(line_number) print 'Removed Job ' + str(job['job_id']) # Fix line number for line_number in range(self.job_list.size()): line_text = self.job_list.get(line_number) job_id = int(line_text[4:line_text.index(' ', 4)]) #print 'Job ' + str(job_id) + ' is now on line ' + str(line_number) self.job_params[job_id]['line_number'] = line_number def set_grid(self): self.grid(sticky=Tkinter.N + Tkinter.S + Tkinter.W + Tkinter.E, padx=4, pady=4) self.columnconfigure(0, minsize=600) self.rowconfigure(0, minsize=300) self.job_list.grid(row=0, column=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W) self.job_list_yscroll.grid(row=0, column=1, sticky=Tkinter.N + Tkinter.S + Tkinter.W) self.job_list_xscroll.grid(row=1, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N) self.new_job_frame.grid(row=2, column=0, pady=3, sticky=Tkinter.W) self.remove_job_button.grid(row=0, column=0) self.add_job_button.grid(row=0, column=1) self.progress_frame.grid(row=3, column=0, pady=3) self.progress_frame.columnconfigure(0, minsize=600) self.progress_bar.grid(row=0, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S) self.button_frame.grid(row=4, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S) self.button_frame.columnconfigure(0, minsize=300) self.button_frame.columnconfigure(1, minsize=300) self.process_button.pack(side=Tkinter.RIGHT) self.quit_button.pack(side=Tkinter.RIGHT) def start_jobs(self): # If there are no queued jobs then simply return if len(self.job_params) == 0 or len(self.job_list.get(0)) == 0: return # Deactivate the process button self.process_button.config(state = Tkinter.DISABLED) # Initialize the progress bar self.progress_value.set(0) # Update parent to refresh widget appearance self.parent.update() # Start process thread jobs_thread = JobsThread(self.job_params, self.run_job, self.on_update, self.on_resume) jobs_thread.start() self['cursor'] = 'wait' def on_update(self, status, line_number, step): if status == 'init': self.job_list.itemconfig(line_number, foreground='green') self.job_list.activate(line_number) elif status == 'success': self.job_list.itemconfig(line_number, foreground='blue') elif status == 'fail': self.job_list.itemconfig(line_number, foreground='red') self.progress_value.set(step) # Update parent to refresh widget appearance self.parent.update() def on_resume(self, job_outcomes=list()): self.progress_value.set(100) self.job_outcomes = job_outcomes self.event_generate('<<AskToClearJobs>>', when='tail') self.event_generate('<<AskToPlotGraphs>>', when='tail') self['cursor'] = 'arrow' def close_top_level_windows(self): #print 'Closing other top level windows' for top_level_window in self.top_level_windows: if top_level_window: top_level_window.withdraw() top_level_window.destroy() def notify_of_close(self, top_level_window): if top_level_window in self.top_level_windows: #print 'Removing top level window' self.top_level_windows.remove(top_level_window) def on_press(self, event): self.on_button = True self.release_pattern = "<B%d-ButtonRelease-%d>" % (event.num, event.num) self.parent.bind(self.release_pattern, self.on_release) def on_release(self, event): self.on_button = False def on_resize(self, event): self.parent.lift() if self.on_button: self.set_grid() def on_close(self): self.plot_args = list() self.withdraw() self.destroy()
class ServerAddressView: def __init__(self, container, application): self.container = container self.application = application # LEFT CONTAINER self.frame_left = Frame(container) self.frame_left.pack(side=LEFT, padx=20, pady=20) exchange_label = Label(self.frame_left, text="Server info") exchange_label.pack(side=TOP, pady=10) # Exchange name row frame_row1 = Frame(self.frame_left) frame_row1.pack(side=TOP, padx=20, pady=5) exchange_label = Label(frame_row1, text="Name:") exchange_label.pack(side=LEFT) self.exchangeEntry = Entry(frame_row1, bd=5) self.exchangeEntry.pack(side=LEFT) # Hostname row frame_row2 = Frame(self.frame_left) frame_row2.pack(side=TOP, padx=20, pady=5) host_label = Label(frame_row2, text="Host: ") host_label.pack(side=LEFT) self.hostEntry = Entry(frame_row2, bd=5) self.hostEntry.pack(side=LEFT) # Port row frame_row3 = Frame(self.frame_left) frame_row3.pack(side=TOP, padx=20, pady=5) port_label = Label(frame_row3, text="Port: ") port_label.pack(side=LEFT) self.portEntry = Entry(frame_row3, bd=5) self.portEntry.pack(side=LEFT) # Connect button self.enterButton = Button(self.frame_left, text="Connect", command=self.handle_enter) self.enterButton.pack(side=BOTTOM, padx=20, pady=20) # RIGHT CONTAINER self.frame_right = Frame(container) self.frame_right.pack(side=LEFT, padx=20, pady=20) servers_label = Label(self.frame_right, text="Available servers:") servers_label.pack(pady=10) self.servers_lb = Listbox(self.frame_right) self.servers_lb.pack() self.servers_lb.bind('<<ListboxSelect>>', self.fill_serverinfo) pad = Label(self.frame_right, text="") pad.pack(side=BOTTOM, pady=10) # Default values self.exchangeEntry.insert(0, "sudoku") self.hostEntry.insert(0, "127.0.0.1") self.portEntry.insert(0, "5672") # Automatic server discovery self.servers_list = [] self.announce_listener = AnnounceListener(self.servers_lb, self.servers_list) self.announce_listener.start() def handle_enter(self): # Handle proceed button exchange = self.exchangeEntry.get() host = self.hostEntry.get() port = self.portEntry.get() self.application.rmq_exchange = exchange self.application.rmq_host = host self.application.rmq_port = port self.application.connect() def fill_nickname(self, evt): w = evt.widget idx = int(w.curselection()[0]) self.entry.delete(0, END) self.entry.insert(0, w.get(idx)) def fill_serverinfo(self, evt): if self.servers_lb.size() == 0: return w = evt.widget idx = int(w.curselection()[0]) # Exchange name self.exchangeEntry.delete(0, END) self.exchangeEntry.insert(0, self.servers_list[idx][0]) # Host name self.hostEntry.delete(0, END) self.hostEntry.insert(0, self.servers_list[idx][1]) # Port self.portEntry.delete(0, END) self.portEntry.insert(0, self.servers_list[idx][2])
class DrtGlueDemo(object): def __init__(self, examples): # Set up the main window. self._top = Tk() self._top.title('DRT Glue Demo') # Set up key bindings. self._init_bindings() # Initialize the fonts.self._error = None self._init_fonts(self._top) self._examples = examples self._readingCache = [None for example in examples] # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Set the data to None self._curExample = -1 self._readings = [] self._drs = None self._drsWidget = None self._error = None self._init_glue() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_exampleListbox(self._top) self._init_readingListbox(self._top) self._init_canvas(self._top) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_glue(self): tagger = RegexpTagger([ ('^(David|Mary|John)$', 'NNP'), ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$', 'VB'), ('^(go|order|vanish|find|approach)$', 'VB'), ('^(a)$', 'ex_quant'), ('^(every)$', 'univ_quant'), ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'), ('^(big|gray|former)$', 'JJ'), ('^(him|himself)$', 'PRP') ]) depparser = MaltParser(tagger=tagger) self._glue = DrtGlue(depparser=depparser, remove_duplicates=False) def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = Font(family='helvetica', weight='bold', size=self._size.get()) self._font = Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get() - 2 else: big = self._size.get() + 2 self._bigfont = Font(family='helvetica', weight='bold', size=big) def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill='both', side='left', padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text='Examples') self._exampleList_label.pack() self._exampleList = Listbox(self._exampleFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._exampleList.pack(side='right', fill='both', expand=1) for example in self._examples: self._exampleList.insert('end', (' %s' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient='vertical') self._exampleList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side='left', fill='y') # If they select a example, apply it. self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select) def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill='both', side='left', padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text='Readings') self._readingList_label.pack() self._readingList = Listbox(self._readingFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._readingList.pack(side='right', fill='both', expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient='vertical') self._readingList.config(yscrollcommand=listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side='right', fill='y') self._populate_readingListbox() def _populate_readingListbox(self): # Populate the listbox with integers self._readingList.delete(0, 'end') for i in range(len(self._readings)): self._readingList.insert('end', (' %s' % (i + 1))) self._readingList.config(height=min(len(self._readings), 25), width=5) # If they select a example, apply it. self._readingList.bind('<<ListboxSelect>>', self._readingList_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('n', self.next) self._top.bind('<space>', self.next) self._top.bind('p', self.prev) self._top.bind('<BackSpace>', self.prev) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button( buttonframe, text='Prev', background='#90c0d0', foreground='black', command=self.prev, ).pack(side='left') Button( buttonframe, text='Next', background='#90c0d0', foreground='black', command=self.next, ).pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1, y1, x2, y2) self._redraw() def _init_canvas(self, parent): self._cframe = CanvasFrame( parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='q') menubar.add_cascade(label='File', underline=0, menu=filemenu) actionmenu = Menu(menubar, tearoff=0) actionmenu.add_command(label='Next', underline=0, command=self.next, accelerator='n, Space') actionmenu.add_command(label='Previous', underline=0, command=self.prev, accelerator='p, Backspace') menubar.add_cascade(label='Action', underline=0, menu=actionmenu) optionmenu = Menu(menubar, tearoff=0) optionmenu.add_checkbutton(label='Remove Duplicates', underline=0, variable=self._glue.remove_duplicates, command=self._toggle_remove_duplicates, accelerator='r') menubar.add_cascade(label='Options', underline=0, menu=optionmenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old DRS, widgets, etc. if self._drsWidget is not None: self._drsWidget.clear() if self._drs: self._drsWidget = DrsWidget(self._canvas, self._drs) self._drsWidget.draw() if self._error: self._drsWidget = DrsWidget(self._canvas, self._error) self._drsWidget.draw() ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def prev(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or before) the first item if index <= 0: self._select_previous_example() else: self._readingList_store_selection(index - 1) else: #select its first reading self._readingList_store_selection(readingListSize - 1) else: self._select_previous_example() def _select_previous_example(self): #if the current example is not the first example if self._curExample > 0: self._exampleList_store_selection(self._curExample - 1) else: #go to the last example self._exampleList_store_selection(len(self._examples) - 1) def next(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # if there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or past) the last item if index >= (readingListSize - 1): self._select_next_example() else: self._readingList_store_selection(index + 1) else: #select its first reading self._readingList_store_selection(0) else: self._select_next_example() def _select_next_example(self): #if the current example is not the last example if self._curExample < len(self._examples) - 1: self._exampleList_store_selection(self._curExample + 1) else: #go to the first example self._exampleList_store_selection(0) def about(self, *e): ABOUT = ( "NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n" + "Written by Daniel H. Garrette") TITLE = 'About: NLTK DRT Glue Demo' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size + 2))) self._redraw() def _toggle_remove_duplicates(self): self._glue.remove_duplicates = not self._glue.remove_duplicates self._exampleList.selection_clear(0, 'end') self._readings = [] self._populate_readingListbox() self._readingCache = [None for ex in self._examples] self._curExample = -1 self._error = None self._drs = None self._redraw() def _exampleList_select(self, event): selection = self._exampleList.curselection() if len(selection) != 1: return self._exampleList_store_selection(int(selection[0])) def _exampleList_store_selection(self, index): self._curExample = index example = self._examples[index] self._exampleList.selection_clear(0, 'end') if example: cache = self._readingCache[index] if cache: if isinstance(cache, list): self._readings = cache self._error = None else: self._readings = [] self._error = cache else: try: self._readings = self._glue.parse_to_meaning(example) self._error = None self._readingCache[index] = self._readings except Exception as e: self._readings = [] self._error = DrtVariableExpression( Variable('Error: ' + str(e))) self._readingCache[index] = self._error #add a star to the end of the example self._exampleList.delete(index) self._exampleList.insert(index, (' %s *' % example)) self._exampleList.config(height=min( len(self._examples), 25), width=40) self._populate_readingListbox() self._exampleList.selection_set(index) self._drs = None self._redraw() def _readingList_select(self, event): selection = self._readingList.curselection() if len(selection) != 1: return self._readingList_store_selection(int(selection[0])) def _readingList_store_selection(self, index): reading = self._readings[index] self._readingList.selection_clear(0, 'end') if reading: self._readingList.selection_set(index) self._drs = reading.simplify().normalize().resolve_anaphora() self._redraw()
class EngineGui(): def __init__(self, communicationProtocal): self.communicationProtocal = communicationProtocal def StartGui(self): self.tkRoot = Tk(baseName="") self.tkRoot.geometry("350x300+0+0") self.tkRoot.title("Engine SAPI GUI") self.GUIVisible = True frame = Frame(self.tkRoot) frame.style = Style() frame.style.theme_use("alt") frame.pack(fill=BOTH, expand=1) frame.columnconfigure(1, weight=1) frame.columnconfigure(7, pad=7) frame.rowconfigure(13, weight=1) frame.rowconfigure(13, pad=7) Label(frame, text="Start:").grid(row = 0, column=0) self.labelStart = Label(frame, text="0") self.labelStart.grid(row = 1, column=0) Label(frame, text="Length:").grid(row = 0, column=1) self.labelLength = Label(frame, text="0") self.labelLength.grid(row = 1, column=1) Label(frame, text="Total:").grid(row = 0, column=2) self.labelTotal = Label(frame, text="0") self.labelTotal.grid(row = 1, column=2) self.labelSentenceLeft = Label(frame, text="...") self.labelSentenceLeft.grid(row = 2, column=0, sticky=E) self.labelSentenceSpoken = Label(frame, text="...", foreground="red") self.labelSentenceSpoken.grid(row = 2, column=1) self.labelSentenceRight = Label(frame, text="...") self.labelSentenceRight.grid(row = 2, column=2, sticky=W, columnspan=2) scrollbar = Scrollbar(frame, orient=VERTICAL) self.labelQueueToSpeak = Label(frame, text="Queue to speak:").grid(row = 3, column=0, pady=4, padx=5, sticky=W) self.listboxQueueToSpeak = Listbox(frame, width=50, height=3, yscrollcommand=scrollbar.set) scrollbar.config(command=self.listboxQueueToSpeak.yview) self.listboxQueueToSpeak.grid( sticky=N+S+E+W, row = 4, column = 0, columnspan = 2 ,rowspan = 3, padx=3) scrollbar.grid(sticky=N+S+W, row = 4, column = 2, rowspan = 3) self.buttonPauze = Button(frame, text="Pauze", command=self.communicationProtocal.handlePauze) self.buttonPauze.grid(row = 4, column=3) self.buttonStop = Button(frame, text="Stop", command=self.communicationProtocal.restartProcess) self.buttonStop.grid(row = 5, column=3) self.buttonResume = Button(frame, text="Resume", command=self.communicationProtocal.handleResume) self.buttonResume.grid(row = 6, column=3) Label(frame, text="Text to say:").grid(row = 7, column=0, padx=3, sticky=W) self.stringVarTextToSay = StringVar() self.entryTextToSay = Entry(frame, textvariable=self.stringVarTextToSay, width=500) self.entryTextToSay.grid(row=8, column=0, columnspan=3, padx=3, sticky=W) self.stringVarTextToSay.set("Hello SAPI Speak Engine") self.entryTextToSay.bind('<Return>', self.CallBackReturnSay) self.buttonSay = Button(frame, text="Say", command=self.CallBackButtonSay) self.buttonSay.grid(row = 8, column=3) Label(frame, text="Recover action:").grid(row = 9, column=0, padx=3, sticky=W) self.recoverActionLabelText = "None" self.labelRecoverAction = Label(frame, text=self.recoverActionLabelText, foreground="blue") self.labelRecoverAction.grid(row = 10, column=0) Label(frame, text="Voice speed:").grid(row = 9, column=1, sticky=W) self.buttonSpeedDown = Button(frame, text="Speed down", command=self.communicationProtocal.handleSpeedDown) self.buttonSpeedDown.grid(row = 10, column=1, padx=3, sticky=E) self.speedValue = 0 self.intVarSpeed = IntVar() vcmd = (self.tkRoot.register(self.OnValidateEntrySpeakSpeed), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.entrySpeakSpeed = Entry(frame, textvariable=self.intVarSpeed, validate="key", validatecommand=vcmd, width=5) self.entrySpeakSpeed.grid(row=10,column=2) self.entrySpeakSpeed.bind('<Return>', self.CallBackSetSpeed) self.buttonSpeedUp = Button(frame, text="Speed up", command=self.communicationProtocal.handleSpeedUp) self.buttonSpeedUp.grid(row = 10, column=3) Label(frame, text="voice:").grid(row = 11, column=0, padx=3, sticky=W) self.buttonPrevVoice = Button(frame, text="Prev voice", command=self.communicationProtocal.handlePrevVoice) self.buttonPrevVoice.grid(row = 12, column=0, padx=3, sticky=W) self.buttonNextVoice = Button(frame, text="Next voice", command=self.communicationProtocal.handleNextVoice) self.buttonNextVoice.grid(row = 12, column=3) self.currentVoice = StringVar(self.tkRoot) self.currentVoice.set(self.communicationProtocal.CurrentVoiceName) engine = pyttsx.init() voices = engine.getProperty("voices") voiceNames = list() for x in xrange(0, len(voices)): voiceNames.append(voices[x].name) self.optionMenuVoices = OptionMenu(frame, self.currentVoice, *tuple(voiceNames), command=self.CallBackOptionMenuVoices) self.optionMenuVoices.config(width=500) self.optionMenuVoices.grid(sticky=W, row = 12, column = 1) #hide if close button is clicked self.tkRoot.protocol("WM_DELETE_WINDOW", self.HideGui) self.tkRoot.after(1000/32, self.Update) self.tkRoot.mainloop() def Update(self): wordLocation = self.communicationProtocal.OnWordStartLocation wordLength = self.communicationProtocal.OnWordLength wordTotal = self.communicationProtocal.OnWordTotal if wordLocation: self.labelStart.configure(text=wordLocation) else: self.labelStart.configure(text="0") self.labelLength.configure(text=wordLength) if wordLength != 0 and wordTotal == 0: self.labelTotal.configure(text="Introduce") else: self.labelTotal.configure(text=wordTotal) if len(self.communicationProtocal.SpeakQueue) != 0: if (wordLocation < 25): self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[0:wordLocation]) else: self.labelSentenceLeft.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation-25:wordLocation]) self.labelSentenceSpoken.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation:wordLocation+wordLength]) if (wordTotal - wordLocation - wordLength < 25): self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordTotal]) else: self.labelSentenceRight.configure(text=str(self.communicationProtocal.SpeakQueue[0])[wordLocation+wordLength:wordLocation+wordLength+25]) else: self.labelSentenceLeft.configure(text="...") self.labelSentenceSpoken.configure(text="...") self.labelSentenceRight.configure(text="...") if (self.communicationProtocal.SpeakQueue != None and self.listboxQueueToSpeak.size() != len(self.communicationProtocal.SpeakQueue)): self.listboxQueueToSpeak.delete(0,self.listboxQueueToSpeak.size()) for x in xrange(0,len(self.communicationProtocal.SpeakQueue)): self.listboxQueueToSpeak.insert(x, str(x)+": "+self.communicationProtocal.SpeakQueue[x]) if (self.currentVoice.get() != self.communicationProtocal.CurrentVoiceName): self.currentVoice.set(self.communicationProtocal.CurrentVoiceName) if self.speedValue != self.communicationProtocal.CurrentRate: self.intVarSpeed.set(self.communicationProtocal.CurrentRate) self.speedValue = self.communicationProtocal.CurrentRate if self.recoverActionLabelText != self.communicationProtocal.recoveryTask: self.recoverActionLabelText = self.communicationProtocal.recoveryTask self.labelRecoverAction.configure(text=self.recoverActionLabelText) if self.GUIVisible != self.communicationProtocal.GUIVisible: # self.GUIVisible ? self.HideGui : self.ShowGui self.HideGui() if self.GUIVisible else self.ShowGui() self.tkRoot.after(1000/32,self.Update) def OnValidateEntrySpeakSpeed(self, d, i, P, s, S, v, V, W): try : int(S) return True except ValueError: return False def CallBackSetSpeed(self): self.communicationProtocal.handleSetSpeed(self.intVarSpeed.get()) def CallBackReturnSay(self, event): self.CallBackButtonSay() def CallBackButtonSay(self): self.communicationProtocal.handleSay(self.stringVarTextToSay.get()) def CallBackOptionMenuVoices(self, selectedItem): self.communicationProtocal.handleSetVoice(selectedItem) def Close(self): self.tkRoot.quit() def HideGui(self): self.GUIVisible = False self.communicationProtocal.GUIVisible = False self.tkRoot.withdraw() def ShowGui(self): self.GUIVisible = True self.communicationProtocal.GUIVisible = True self.tkRoot.deiconify()
class ConditionalsEditor: def __init__(self, my_window, conditionals, close_callback): #Tk.__init__(self) self.my_window = my_window self.my_window.title("Condition Editor") self.close_callback = close_callback self.conditionals = conditionals shared_pad_x = 3 shared_pad_y = 3 main_frame = Frame(self.my_window) main_frame.grid(column=0, row=0, sticky=(N, W, E, S)) image_path = "images" image_files = [ f for f in os.listdir(image_path) if os.path.isfile(os.path.join(image_path, f)) and f.endswith(".png") ] self.icons = {} for image_file in image_files: self.icons[os.path.splitext( os.path.basename(image_file))[0]] = PhotoImage( file=os.path.join(image_path, image_file)) up_down_button_frame = Frame(main_frame) self.up_button = Button(up_down_button_frame, state="disabled", text="Move up", image=self.icons["gtk-go-up"], command=self.up_pressed) self.up_button.grid(column=0, row=0, sticky=(E)) self.down_button = Button(up_down_button_frame, state="disabled", text="Move down", image=self.icons["gtk-go-down"], command=self.down_pressed) self.down_button.grid(column=0, row=1, sticky=(E)) up_down_button_frame.grid(column=0, row=0, sticky=(E)) condition_list = Frame(main_frame, relief=SUNKEN, borderwidth=1) condition_list.grid(column=1, row=0, sticky=(N, S, E, W), padx=shared_pad_x, pady=shared_pad_y, columnspan=1) self.condition_list_scrollbar = Scrollbar(condition_list) self.state_listbox = Listbox(condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.state_listbox_scroll, activestyle="none") self.state_listbox.grid(column=0, row=0, padx=0, sticky=(N, S)) self.state_listbox.bind("<<ListboxSelect>>", self.state_listbox_selected) self.condition_listbox = Listbox( condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.condition_listbox_scroll, activestyle="none") self.condition_listbox.grid(column=1, row=0, sticky=(N, S, E, W), padx=0) self.condition_listbox.bind("<<ListboxSelect>>", self.condition_listbox_selected) self.execution_target_listbox = Listbox( condition_list, relief=FLAT, exportselection=False, borderwidth=0, highlightthickness=0, yscrollcommand=self.execution_target_listbox_scroll, activestyle="none") self.execution_target_listbox.grid(column=2, row=0, padx=0, sticky=(N, S)) self.execution_target_listbox.bind( "<<ListboxSelect>>", self.execution_target_listbox_selected) self.condition_list_scrollbar.grid(column=3, row=0, sticky=(N, S)) self.condition_list_scrollbar.config( command=self.condition_list_scrollbar_callback) condition_list.grid_rowconfigure(0, weight=1) for conditional in self.conditionals: self.state_listbox.insert(END, conditional[0]) self.condition_listbox.insert(END, conditional[1]) self.execution_target_listbox.insert(END, conditional[2]) #for i in range(5): # self.state_listbox.insert(END, "Foo %d"%i) # self.condition_listbox.insert(END, "Bar %d"%i) # self.execution_target_listbox.insert(END, "Baz %d"%i) if_label = Label(main_frame, text="If:", padx=10) if_label.grid(column=0, row=1, sticky=(N, E)) self.if_text_variable = StringVar() if_entry = Entry(main_frame, textvariable=self.if_text_variable) if_entry.grid( column=1, row=1, sticky=(E, W), padx=shared_pad_x, pady=shared_pad_y, ) then_label = Label(main_frame, text="Then:", padx=10) then_label.grid(column=0, row=2, sticky=(N, E)) self.then_entry = Text(main_frame) self.then_entry.grid( column=1, row=2, sticky=(N, S, E, W), padx=shared_pad_x, rowspan=2, ) option_frame = Frame(main_frame) execution_target_label = Label(option_frame, text="Execution target:") execution_target_label.grid(column=0, row=0, sticky=(N, W), pady=(10, shared_pad_y)) self.execution_target = StringVar() self.execution_target.set("Debugger") debugger_radiobutton = Radiobutton(option_frame, text="Debugger", variable=self.execution_target, value="Debugger") debugger_radiobutton.grid(column=0, row=1, sticky=(N, W)) python_radiobutton = Radiobutton(option_frame, text="Python", variable=self.execution_target, value="Python") python_radiobutton.grid(column=0, row=2, sticky=(N, W)) state_label = Label(option_frame, text="State") state_label.grid(column=0, row=3, sticky=(N, W), pady=(10, shared_pad_y)) self.active_checkbutton = StringVar() self.active_checkbutton.set("Enabled") active_checkbutton = Checkbutton(option_frame, text="Enabled", variable=self.active_checkbutton, onvalue="Enabled", offvalue="Disabled") active_checkbutton.grid(column=0, row=4, sticky=(N, W)) option_frame.grid(column=0, row=3, sticky=(N, S, E, W), pady=5) button_frame = Frame(main_frame) self.add_button = Button(button_frame, state="disabled", text="Add", image=self.icons["gtk-add"], compound=LEFT) self.add_button.grid(column=0, row=0, sticky=(E)) self.update_button = Button(button_frame, state="disabled", text="Update", image=self.icons["gtk-edit"], compound=LEFT) self.update_button.grid(column=1, row=0, sticky=(E)) self.delete_button = Button(button_frame, state="disabled", text="Delete", image=self.icons["gtk-remove"], compound=LEFT) self.delete_button.grid(column=2, row=0, sticky=(E)) button_frame.grid(column=0, row=4, columnspan=2, sticky=(E), padx=shared_pad_x, pady=shared_pad_y) close_frame = Frame(main_frame) close_button = Button(close_frame, text="Close", image=self.icons["gtk-close"], compound=LEFT, command=self.on_closing) close_button.grid(column=0, row=0, sticky=(S, E)) close_frame.grid(column=0, row=5, columnspan=2, sticky=(S, E), padx=shared_pad_x, pady=(15, shared_pad_y)) self.my_window.grid_columnconfigure(0, weight=1) self.my_window.grid_rowconfigure(0, weight=1) main_frame.grid_columnconfigure(1, weight=1) main_frame.grid_rowconfigure(0, weight=1) main_frame.grid_rowconfigure(2, weight=0) main_frame.grid_rowconfigure(3, weight=1) main_frame.grid_rowconfigure(4, weight=1) main_frame.grid_rowconfigure(5, weight=1) condition_list.grid_columnconfigure(1, weight=1) button_frame.grid_rowconfigure(0, weight=1) self.my_window.protocol("WM_DELETE_WINDOW", self.on_closing) def on_closing(self): if self.close_callback is not None: self.close_callback() self.my_window.destroy() def up_pressed(self): index = self.state_listbox.curselection()[0] state_current = self.state_listbox.get(index) condition_current = self.condition_listbox.get(index) execution_target_current = self.execution_target_listbox.get(index) self.state_listbox.delete(index) self.condition_listbox.delete(index) self.execution_target_listbox.delete(index) self.state_listbox.insert(index - 1, state_current) self.condition_listbox.insert(index - 1, condition_current) self.execution_target_listbox.insert(index - 1, execution_target_current) self.conditionals.insert(index - 1, self.conditionals.pop(index)) self.state_listbox.selection_set(index - 1) self.condition_listbox.selection_set(index - 1) self.execution_target_listbox.selection_set(index - 1) self.state_listbox.see(index - 1) if index - 1 == 0: self.up_button.config(state="disabled") self.down_button.config(state="normal") def down_pressed(self): index = self.state_listbox.curselection()[0] state_current = self.state_listbox.get(index) condition_current = self.condition_listbox.get(index) execution_target_current = self.execution_target_listbox.get(index) self.state_listbox.delete(index) self.condition_listbox.delete(index) self.execution_target_listbox.delete(index) self.state_listbox.insert(index + 1, state_current) self.condition_listbox.insert(index + 1, condition_current) self.execution_target_listbox.insert(index + 1, execution_target_current) self.conditionals.insert(index + 1, self.conditionals.pop(index)) self.state_listbox.selection_set(index + 1) self.condition_listbox.selection_set(index + 1) self.execution_target_listbox.selection_set(index + 1) self.state_listbox.see(index + 1) if index + 1 == self.state_listbox.size() - 1: self.down_button.config(state="disabled") self.up_button.config(state="normal") def condition_list_scrollbar_callback(self, *args): self.state_listbox.yview(*args) self.condition_listbox.yview(*args) self.execution_target_listbox.yview(*args) def state_listbox_scroll(self, *args): self.condition_listbox.yview_moveto(args[0]) self.execution_target_listbox.yview_moveto(args[0]) self.condition_list_scrollbar.set(*args) def condition_listbox_scroll(self, *args): self.state_listbox.yview_moveto(args[0]) self.execution_target_listbox.yview_moveto(args[0]) def execution_target_listbox_scroll(self, *args): self.state_listbox.yview_moveto(args[0]) self.condition_listbox.yview_moveto(args[0]) def any_listbox_selected(self): self.up_button.config(state="normal") self.down_button.config(state="normal") if self.state_listbox.curselection( )[0] == self.state_listbox.size() - 1: self.down_button.config(state="disabled") if self.state_listbox.curselection()[0] == 0: self.up_button.config(state="disabled") self.delete_button.config(state="normal") self.then_entry.delete("1.0", END) self.then_entry.insert( END, self.conditionals[self.state_listbox.curselection()[0]][3]) self.if_text_variable.set( self.conditionals[self.state_listbox.curselection()[0]][1]) self.execution_target.set( self.conditionals[self.state_listbox.curselection()[0]][2]) self.active_checkbutton.set( self.conditionals[self.state_listbox.curselection()[0]][0]) def state_listbox_selected(self, event): index = self.state_listbox.curselection()[0] try: self.condition_listbox.selection_clear( self.condition_listbox.curselection()[0]) except IndexError: pass self.condition_listbox.selection_set(index) try: self.execution_target_listbox.selection_clear( self.execution_target_listbox.curselection()[0]) except IndexError: pass self.execution_target_listbox.selection_set(index) self.any_listbox_selected() def condition_listbox_selected(self, event): index = self.condition_listbox.curselection()[0] try: self.state_listbox.selection_clear( self.state_listbox.curselection()[0]) except IndexError: pass self.state_listbox.selection_set(index) try: self.execution_target_listbox.selection_clear( self.execution_target_listbox.curselection()[0]) except IndexError: pass self.execution_target_listbox.selection_set(index) self.any_listbox_selected() def execution_target_listbox_selected(self, event): index = self.execution_target_listbox.curselection()[0] try: self.state_listbox.selection_clear( self.state_listbox.curselection()[0]) except IndexError: pass self.state_listbox.selection_set(index) try: self.condition_listbox.selection_clear( self.condition_listbox.curselection()[0]) except IndexError: pass self.condition_listbox.selection_set(index) self.any_listbox_selected()
class PPEditor(object): # *************************************** # INIT # *************************************** def __init__(self): self.editor_issue="1.3" # get command options self.command_options=ed_options() # get directory holding the code self.pp_dir=sys.path[0] if not os.path.exists(self.pp_dir+os.sep+"pp_editor.py"): tkMessageBox.showwarning("Pi Presents","Bad Application Directory") exit() # Initialise logging Monitor.log_path=self.pp_dir self.mon=Monitor() self.mon.init() Monitor.classes = ['PPEditor','EditItem','Validator'] Monitor.log_level = int(self.command_options['debug']) self.mon.log (self, "Pi Presents Editor is starting") self.mon.log (self," OS and separator " + os.name +' ' + os.sep) self.mon.log(self,"sys.path[0] - location of code: code "+sys.path[0]) # set up the gui # root is the Tkinter root widget self.root = Tk() self.root.title("Editor for Pi Presents") # self.root.configure(background='grey') self.root.resizable(False,False) # define response to main window closing self.root.protocol ("WM_DELETE_WINDOW", self.app_exit) # bind some display fields self.filename = StringVar() self.display_selected_track_title = StringVar() self.display_show = StringVar() # define menu menubar = Menu(self.root) profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black") profilemenu.add_command(label='Open', command = self.open_existing_profile) profilemenu.add_command(label='Validate', command = self.validate_profile) menubar.add_cascade(label='Profile', menu = profilemenu) ptypemenu = Menu(profilemenu, tearoff=0, bg="grey", fg="black") ptypemenu.add_command(label='Exhibit', command = self.new_exhibit_profile) ptypemenu.add_command(label='Media Show', command = self.new_mediashow_profile) ptypemenu.add_command(label='Art Media Show', command = self.new_artmediashow_profile) ptypemenu.add_command(label='Menu', command = self.new_menu_profile) ptypemenu.add_command(label='Presentation', command = self.new_presentation_profile) ptypemenu.add_command(label='Interactive', command = self.new_interactive_profile) ptypemenu.add_command(label='Live Show', command = self.new_liveshow_profile) ptypemenu.add_command(label='Art Live Show', command = self.new_artliveshow_profile) ptypemenu.add_command(label='RadioButton Show', command = self.new_radiobuttonshow_profile) ptypemenu.add_command(label='Hyperlink Show', command = self.new_hyperlinkshow_profile) ptypemenu.add_command(label='Blank', command = self.new_blank_profile) profilemenu.add_cascade(label='New from Template', menu = ptypemenu) showmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") showmenu.add_command(label='Delete', command = self.remove_show) showmenu.add_command(label='Edit', command = self.m_edit_show) showmenu.add_command(label='Copy To', command = self.copy_show) menubar.add_cascade(label='Show', menu = showmenu) stypemenu = Menu(showmenu, tearoff=0, bg="grey", fg="black") stypemenu.add_command(label='Menu', command = self.add_menushow) stypemenu.add_command(label='MediaShow', command = self.add_mediashow) stypemenu.add_command(label='LiveShow', command = self.add_liveshow) stypemenu.add_command(label='HyperlinkShow', command = self.add_hyperlinkshow) stypemenu.add_command(label='RadioButtonShow', command = self.add_radiobuttonshow) stypemenu.add_command(label='ArtMediaShow', command = self.add_artmediashow) stypemenu.add_command(label='ArtLiveShow', command = self.add_artliveshow) showmenu.add_cascade(label='Add', menu = stypemenu) medialistmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='MediaList', menu = medialistmenu) medialistmenu.add_command(label='Add', command = self.add_medialist) medialistmenu.add_command(label='Delete', command = self.remove_medialist) medialistmenu.add_command(label='Copy To', command = self.copy_medialist) trackmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") trackmenu.add_command(label='Delete', command = self.remove_track) trackmenu.add_command(label='Edit', command = self.m_edit_track) trackmenu.add_command(label='Add from Dir', command = self.add_tracks_from_dir) trackmenu.add_command(label='Add from File', command = self.add_track_from_file) menubar.add_cascade(label='Track', menu = trackmenu) typemenu = Menu(trackmenu, tearoff=0, bg="grey", fg="black") typemenu.add_command(label='Video', command = self.new_video_track) typemenu.add_command(label='Audio', command = self.new_audio_track) typemenu.add_command(label='Image', command = self.new_image_track) typemenu.add_command(label='Web', command = self.new_web_track) typemenu.add_command(label='Message', command = self.new_message_track) typemenu.add_command(label='Show', command = self.new_show_track) typemenu.add_command(label='Menu Track', command = self.new_menu_track) trackmenu.add_cascade(label='New', menu = typemenu) oscmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='OSC', menu = oscmenu) oscmenu.add_command(label='Create OSC configuration', command = self.create_osc) oscmenu.add_command(label='Edit OSC Configuration', command = self.edit_osc) oscmenu.add_command(label='Delete OSC Configuration', command = self.delete_osc) toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Tools', menu = toolsmenu) toolsmenu.add_command(label='Update All', command = self.update_all) optionsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Options', menu = optionsmenu) optionsmenu.add_command(label='Edit', command = self.edit_options) helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Help', menu = helpmenu) helpmenu.add_command(label='Help', command = self.show_help) helpmenu.add_command(label='About', command = self.about) self.root.config(menu=menubar) top_frame=Frame(self.root) top_frame.pack(side=TOP) bottom_frame=Frame(self.root) bottom_frame.pack(side=TOP, fill=BOTH, expand=1) left_frame=Frame(bottom_frame, padx=5) left_frame.pack(side=LEFT) middle_frame=Frame(bottom_frame,padx=5) middle_frame.pack(side=LEFT) right_frame=Frame(bottom_frame,padx=5,pady=10) right_frame.pack(side=LEFT) updown_frame=Frame(bottom_frame,padx=5) updown_frame.pack(side=LEFT) tracks_title_frame=Frame(right_frame) tracks_title_frame.pack(side=TOP) tracks_label = Label(tracks_title_frame, text="Tracks in Selected Medialist") tracks_label.pack() tracks_frame=Frame(right_frame) tracks_frame.pack(side=TOP) shows_title_frame=Frame(left_frame) shows_title_frame.pack(side=TOP) shows_label = Label(shows_title_frame, text="Shows") shows_label.pack() shows_frame=Frame(left_frame) shows_frame.pack(side=TOP) shows_title_frame=Frame(left_frame) shows_title_frame.pack(side=TOP) medialists_title_frame=Frame(left_frame) medialists_title_frame.pack(side=TOP) medialists_label = Label(medialists_title_frame, text="Medialists") medialists_label.pack() medialists_frame=Frame(left_frame) medialists_frame.pack(side=LEFT) # define buttons add_button = Button(middle_frame, width = 5, height = 2, text='Edit\nShow', fg='black', command = self.m_edit_show, bg="light grey") add_button.pack(side=RIGHT) add_button = Button(updown_frame, width = 5, height = 1, text='Add', fg='black', command = self.add_track_from_file, bg="light grey") add_button.pack(side=TOP) add_button = Button(updown_frame, width = 5, height = 1, text='Edit', fg='black', command = self.m_edit_track, bg="light grey") add_button.pack(side=TOP) add_button = Button(updown_frame, width = 5, height = 1, text='Up', fg='black', command = self.move_track_up, bg="light grey") add_button.pack(side=TOP) add_button = Button(updown_frame, width = 5, height = 1, text='Down', fg='black', command = self.move_track_down, bg="light grey") add_button.pack(side=TOP) # define display of showlist scrollbar = Scrollbar(shows_frame, orient=VERTICAL) self.shows_display = Listbox(shows_frame, selectmode=SINGLE, height=12, width = 40, bg="white",activestyle=NONE, fg="black", yscrollcommand=scrollbar.set) scrollbar.config(command=self.shows_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.shows_display.pack(side=LEFT, fill=BOTH, expand=1) self.shows_display.bind("<ButtonRelease-1>", self.e_select_show) # define display of medialists scrollbar = Scrollbar(medialists_frame, orient=VERTICAL) self.medialists_display = Listbox(medialists_frame, selectmode=SINGLE, height=12, width = 40, bg="white",activestyle=NONE, fg="black",yscrollcommand=scrollbar.set) scrollbar.config(command=self.medialists_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.medialists_display.pack(side=LEFT, fill=BOTH, expand=1) self.medialists_display.bind("<ButtonRelease-1>", self.select_medialist) # define display of tracks scrollbar = Scrollbar(tracks_frame, orient=VERTICAL) self.tracks_display = Listbox(tracks_frame, selectmode=SINGLE, height=25, width = 40, bg="white",activestyle=NONE, fg="black",yscrollcommand=scrollbar.set) scrollbar.config(command=self.tracks_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.tracks_display.pack(side=LEFT,fill=BOTH, expand=1) self.tracks_display.bind("<ButtonRelease-1>", self.e_select_track) # initialise editor options class and OSC config class self.options=Options(self.pp_dir) # creates options file in code directory if necessary self.osc_config=OSCConfig() # initialise variables self.init() # and enter Tkinter event loop self.root.mainloop() # *************************************** # INIT AND EXIT # *************************************** def app_exit(self): self.root.destroy() exit() def init(self): self.options.read() self.pp_home_dir = self.options.pp_home_dir self.pp_profiles_offset = self.options.pp_profiles_offset self.initial_media_dir = self.options.initial_media_dir self.mon.log(self,"Data Home from options is "+self.pp_home_dir) self.mon.log(self,"Current Profiles Offset from options is "+self.pp_profiles_offset) self.mon.log(self,"Initial Media from options is "+self.initial_media_dir) self.pp_profile_dir='' self.osc_config_file = '' self.current_medialist=None self.current_showlist=None self.current_show=None self.shows_display.delete(0,END) self.medialists_display.delete(0,END) self.tracks_display.delete(0,END) # *************************************** # MISCELLANEOUS # *************************************** def edit_options(self): """edit the options then read them from file""" eo = OptionsDialog(self.root, self.options.options_file,'Edit Options') if eo.result is True: self.init() def show_help (self): tkMessageBox.showinfo("Help","Read 'manual.pdf'") def about (self): tkMessageBox.showinfo("About","Editor for Pi Presents Profiles\n" +"For profile version: " + self.editor_issue + "\nAuthor: Ken Thompson" +"\nWebsite: http://pipresents.wordpress.com/") def validate_profile(self): val =Validator() val.validate_profile(self.root,self.pp_dir,self.pp_home_dir,self.pp_profile_dir,self.editor_issue,True) # ************** # OSC CONFIGURATION # ************** def create_osc(self): if self.pp_profile_dir=='': return if self.osc_config.read(self.osc_config_file) is False: iodir=self.pp_profile_dir+os.sep+'pp_io_config' if not os.path.exists(iodir): os.makedirs(iodir) self.osc_config.create(self.osc_config_file) def edit_osc(self): if self.osc_config.read(self.osc_config_file) is False: # print 'no config file' return osc_ut=OSCUnitType(self.root,self.osc_config.this_unit_type) self.req_unit_type=osc_ut.result if self.req_unit_type != None: # print self.req_unit_type eosc = OSCEditor(self.root, self.osc_config_file,self.req_unit_type,'Edit OSC Configuration') def delete_osc(self): if self.osc_config.read(self.osc_config_file) is False: return os.rename(self.osc_config_file,self.osc_config_file+'.bak') # ************** # PROFILES # ************** def open_existing_profile(self): initial_dir=self.pp_home_dir+os.sep+"pp_profiles"+self.pp_profiles_offset if os.path.exists(initial_dir) is False: self.mon.err(self,"Profiles directory not found: " + initial_dir + "\n\nHint: Data Home option must end in pp_home") return dir_path=tkFileDialog.askdirectory(initialdir=initial_dir) # dir_path="C:\Users\Ken\pp_home\pp_profiles\\ttt" if len(dir_path)>0: self.open_profile(dir_path) def open_profile(self,dir_path): showlist_file = dir_path + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err(self,"Not a Profile: " + dir_path + "\n\nHint: Have you opened the profile directory?") return self.pp_profile_dir = dir_path self.root.title("Editor for Pi Presents - "+ self.pp_profile_dir) if self.open_showlist(self.pp_profile_dir) is False: self.init() return self.open_medialists(self.pp_profile_dir) self.refresh_tracks_display() self.osc_config_file=self.pp_profile_dir+os.sep+'pp_io_config'+os.sep+'osc.cfg' def new_profile(self,profile): d = Edit1Dialog(self.root,"New Profile","Name", "") if d .result is None: return name=str(d.result) if name == "": tkMessageBox.showwarning("New Profile","Name is blank") return to = self.pp_home_dir + os.sep + "pp_profiles"+ self.pp_profiles_offset + os.sep + name if os.path.exists(to) is True: tkMessageBox.showwarning( "New Profile","Profile exists\n(%s)" % to ) return shutil.copytree(profile, to, symlinks=False, ignore=None) self.open_profile(to) def new_exhibit_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_exhibit_1p3' self.new_profile(profile) def new_interactive_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_interactive_1p3' self.new_profile(profile) def new_menu_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_menu_1p3' self.new_profile(profile) def new_presentation_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_presentation_1p3' self.new_profile(profile) def new_blank_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep +"ppt_blank_1p3" self.new_profile(profile) def new_mediashow_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_mediashow_1p3' self.new_profile(profile) def new_liveshow_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_liveshow_1p3' self.new_profile(profile) def new_artmediashow_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_artmediashow_1p3' self.new_profile(profile) def new_artliveshow_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_artliveshow_1p3' self.new_profile(profile) def new_radiobuttonshow_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_radiobuttonshow_1p3' self.new_profile(profile) def new_hyperlinkshow_profile(self): profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_hyperlinkshow_1p3' self.new_profile(profile) # *************************************** # Shows # *************************************** def open_showlist(self,profile_dir): showlist_file = profile_dir + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err(self,"showlist file not found at " + profile_dir + "\n\nHint: Have you opened the profile directory?") self.app_exit() self.current_showlist=ShowList() self.current_showlist.open_json(showlist_file) if float(self.current_showlist.sissue())<float(self.editor_issue) or (self.command_options['forceupdate'] is True and float(self.current_showlist.sissue()) == float(self.editor_issue)): self.update_profile() self.mon.err(self,"Version of profile has been updated to "+self.editor_issue+", please re-open") return False if float(self.current_showlist.sissue())>float(self.editor_issue): self.mon.err(self,"Version of profile is greater than editor, must exit") self.app_exit() self.refresh_shows_display() return True def save_showlist(self,showlist_dir): if self.current_showlist is not None: showlist_file = showlist_dir + os.sep + "pp_showlist.json" self.current_showlist.save_list(showlist_file) def add_mediashow(self): self.add_show(PPdefinitions.new_shows['mediashow']) def add_liveshow(self): self.add_show(PPdefinitions.new_shows['liveshow']) def add_radiobuttonshow(self): self.add_show(PPdefinitions.new_shows['radiobuttonshow']) def add_hyperlinkshow(self): self.add_show(PPdefinitions.new_shows['hyperlinkshow']) def add_artliveshow(self): self.add_show(PPdefinitions.new_shows['artliveshow']) def add_artmediashow(self): self.add_show(PPdefinitions.new_shows['artmediashow']) def add_menushow(self): self.add_show(PPdefinitions.new_shows['menu']) def add_start(self): self.add_show(PPdefinitions.new_shows['start']) def add_show(self,default): # append it to the showlist and then add the medialist if self.current_showlist is not None: d = Edit1Dialog(self.root,"AddShow","Show Reference", "") if d.result is None: return name=str(d.result) if name == "": tkMessageBox.showwarning("Add Show","Name is blank") return if self.current_showlist.index_of_show(name) != -1: tkMessageBox.showwarning("Add Show","A Show with this name already exists") return copied_show=self.current_showlist.copy(default,name) mediafile=self.add_medialist(name) if mediafile != '': copied_show['medialist']=mediafile self.current_showlist.append(copied_show) self.save_showlist(self.pp_profile_dir) self.refresh_shows_display() def remove_show(self): if self.current_showlist is not None and self.current_showlist.length()>0 and self.current_showlist.show_is_selected(): if tkMessageBox.askokcancel("Delete Show","Delete Show"): index= self.current_showlist.selected_show_index() self.current_showlist.remove(index) self.save_showlist(self.pp_profile_dir) self.refresh_shows_display() def show_refs(self): _show_refs=[] for index in range(self.current_showlist.length()): if self.current_showlist.show(index)['show-ref'] != "start": _show_refs.append(copy.deepcopy(self.current_showlist.show(index)['show-ref'])) return _show_refs def refresh_shows_display(self): self.shows_display.delete(0,self.shows_display.size()) for index in range(self.current_showlist.length()): self.shows_display.insert(END, self.current_showlist.show(index)['title']+" ["+self.current_showlist.show(index)['show-ref']+"]") if self.current_showlist.show_is_selected(): self.shows_display.itemconfig(self.current_showlist.selected_show_index(),fg='red') self.shows_display.see(self.current_showlist.selected_show_index()) def e_select_show(self,event): if self.current_showlist is not None and self.current_showlist.length()>0: mouse_item_index=int(event.widget.curselection()[0]) self.current_showlist.select(mouse_item_index) self.refresh_shows_display() def copy_show(self): if self.current_showlist is not None and self.current_showlist.show_is_selected(): self.add_show(self.current_showlist.selected_show()) def m_edit_show(self): self.edit_show(PPdefinitions.show_types,PPdefinitions.show_field_specs) def edit_show(self,show_types,field_specs): if self.current_showlist is not None and self.current_showlist.show_is_selected(): d=EditItem(self.root,"Edit Show",self.current_showlist.selected_show(),show_types,field_specs,self.show_refs(), self.initial_media_dir,self.pp_home_dir,'show') if d.result is True: self.save_showlist(self.pp_profile_dir) self.refresh_shows_display() # *************************************** # Medialists # *************************************** def open_medialists(self,profile_dir): self.medialists = [] for this_file in os.listdir(profile_dir): if this_file.endswith(".json") and this_file not in ('pp_showlist.json','schedule.json'): self.medialists = self.medialists + [this_file] self.medialists_display.delete(0,self.medialists_display.size()) for index in range (len(self.medialists)): self.medialists_display.insert(END, self.medialists[index]) self.current_medialists_index=-1 self.current_medialist=None def add_medialist(self,name=None): if name is None: d = Edit1Dialog(self.root,"Add Medialist","File", "") if d.result is None: return '' name=str(d.result) if name == "": tkMessageBox.showwarning("Add medialist","Name is blank") return '' if not name.endswith(".json"): name=name+(".json") path = self.pp_profile_dir + os.sep + name if os.path.exists(path) is True: tkMessageBox.showwarning("Add medialist","Medialist file exists\n(%s)" % path) return '' nfile = open(path,'wb') nfile.write("{") nfile.write("\"issue\": \""+self.editor_issue+"\",\n") nfile.write("\"tracks\": [") nfile.write("]") nfile.write("}") nfile.close() # append it to the list self.medialists.append(copy.deepcopy(name)) # add title to medialists display self.medialists_display.insert(END, name) # and set it as the selected medialist self.refresh_medialists_display() return name def copy_medialist(self,to_file=None): if self.current_medialist is not None: #from_file= self.current_medialist from_file= self.medialists[self.current_medialists_index] if to_file is None: d = Edit1Dialog(self.root,"Copy Medialist","File", "") if d.result is None: return '' to_file=str(d.result) if to_file == "": tkMessageBox.showwarning("Copy medialist","Name is blank") return '' success_file = self.copy_medialist_file(from_file,to_file) if success_file =='': return '' # append it to the list self.medialists.append(copy.deepcopy(success_file)) # add title to medialists display self.medialists_display.insert(END, success_file) # and reset selected medialist self.current_medialist=None self.refresh_medialists_display() self.refresh_tracks_display() return success_file else: return '' def copy_medialist_file(self,from_file,to_file): if not to_file.endswith(".json"): to_file+=(".json") to_path = self.pp_profile_dir + os.sep + to_file if os.path.exists(to_path) is True: tkMessageBox.showwarning("Copy medialist","Medialist file exists\n(%s)" % to_path) return '' from_path= self.pp_profile_dir + os.sep + from_file if os.path.exists(from_path) is False: tkMessageBox.showwarning("Copy medialist","Medialist file not found\n(%s)" % from_path) return '' shutil.copy(from_path,to_path) return to_file def remove_medialist(self): if self.current_medialist is not None: if tkMessageBox.askokcancel("Delete Medialist","Delete Medialist"): os.remove(self.pp_profile_dir+ os.sep + self.medialists[self.current_medialists_index]) self.open_medialists(self.pp_profile_dir) self.refresh_medialists_display() self.refresh_tracks_display() def select_medialist(self,event): """ user clicks on a medialst in a profile so try and select it. """ # needs forgiving int for possible tkinter upgrade if len(self.medialists)>0: self.current_medialists_index=int(event.widget.curselection()[0]) self.current_medialist=MediaList('ordered') if not self.current_medialist.open_list(self.pp_profile_dir+ os.sep + self.medialists[self.current_medialists_index],self.current_showlist.sissue()): self.mon.err(self,"medialist is a different version to showlist: "+ self.medialists[self.current_medialists_index]) self.app_exit() self.refresh_tracks_display() self.refresh_medialists_display() def refresh_medialists_display(self): self.medialists_display.delete(0,len(self.medialists)) for index in range (len(self.medialists)): self.medialists_display.insert(END, self.medialists[index]) if self.current_medialist is not None: self.medialists_display.itemconfig(self.current_medialists_index,fg='red') self.medialists_display.see(self.current_medialists_index) def save_medialist(self): basefile=self.medialists[self.current_medialists_index] # print type(basefile) # basefile=str(basefile) # print type(basefile) medialist_file = self.pp_profile_dir+ os.sep + basefile self.current_medialist.save_list(medialist_file) # *************************************** # Tracks # *************************************** def refresh_tracks_display(self): self.tracks_display.delete(0,self.tracks_display.size()) if self.current_medialist is not None: for index in range(self.current_medialist.length()): if self.current_medialist.track(index)['track-ref'] != '': track_ref_string=" ["+self.current_medialist.track(index)['track-ref']+"]" else: track_ref_string="" self.tracks_display.insert(END, self.current_medialist.track(index)['title']+track_ref_string) if self.current_medialist.track_is_selected(): self.tracks_display.itemconfig(self.current_medialist.selected_track_index(),fg='red') self.tracks_display.see(self.current_medialist.selected_track_index()) def e_select_track(self,event): if self.current_medialist is not None and self.current_medialist.length()>0: mouse_item_index=int(event.widget.curselection()[0]) self.current_medialist.select(mouse_item_index) self.refresh_tracks_display() def m_edit_track(self): self.edit_track(PPdefinitions.track_types,PPdefinitions.track_field_specs) def edit_track(self,track_types,field_specs): if self.current_medialist is not None and self.current_medialist.track_is_selected(): d=EditItem(self.root,"Edit Track",self.current_medialist.selected_track(),track_types,field_specs, self.show_refs(),self.initial_media_dir,self.pp_home_dir,'track') if d.result is True: self.save_medialist() self.refresh_tracks_display() def move_track_up(self): if self.current_medialist is not None and self.current_medialist.track_is_selected(): self.current_medialist.move_up() self.refresh_tracks_display() self.save_medialist() def move_track_down(self): if self.current_medialist is not None and self.current_medialist.track_is_selected(): self.current_medialist.move_down() self.refresh_tracks_display() self.save_medialist() def new_track(self,fields,values): if self.current_medialist is not None: # print '\nfields ', fields # print '\nvalues ', values new_track=copy.deepcopy(fields) # print ',\new track ',new_track self.current_medialist.append(new_track) # print '\nbefore values ',self.current_medialist.print_list() if values is not None: self.current_medialist.update(self.current_medialist.length()-1,values) self.current_medialist.select(self.current_medialist.length()-1) self.refresh_tracks_display() self.save_medialist() def new_message_track(self): self.new_track(PPdefinitions.new_tracks['message'],None) def new_video_track(self): self.new_track(PPdefinitions.new_tracks['video'],None) def new_audio_track(self): self.new_track(PPdefinitions.new_tracks['audio'],None) def new_web_track(self): self.new_track(PPdefinitions.new_tracks['web'],None) def new_image_track(self): self.new_track(PPdefinitions.new_tracks['image'],None) def new_show_track(self): self.new_track(PPdefinitions.new_tracks['show'],None) def new_menu_track(self): self.new_track(PPdefinitions.new_tracks['menu'],None) def remove_track(self): if self.current_medialist is not None and self.current_medialist.length()>0 and self.current_medialist.track_is_selected(): if tkMessageBox.askokcancel("Delete Track","Delete Track"): index= self.current_medialist.selected_track_index() self.current_medialist.remove(index) self.save_medialist() self.refresh_tracks_display() def add_track_from_file(self): if self.current_medialist is None: return # print "initial directory ", self.options.initial_media_dir files_path=tkFileDialog.askopenfilename(initialdir=self.options.initial_media_dir, multiple=True) # fix for tkinter bug files_path = self.root.tk.splitlist(files_path) for file_path in files_path: file_path=os.path.normpath(file_path) # print "file path ", file_path self.add_track(file_path) self.save_medialist() def add_tracks_from_dir(self): if self.current_medialist is None: return image_specs =[PPdefinitions.IMAGE_FILES,PPdefinitions.VIDEO_FILES,PPdefinitions.AUDIO_FILES, PPdefinitions.WEB_FILES,('All files', '*')] # last one is ignored in finding files in directory, for dialog box only directory=tkFileDialog.askdirectory(initialdir=self.options.initial_media_dir) # deal with tuple returned on Cancel if len(directory) == 0: return # make list of exts we recognise exts = [] for image_spec in image_specs[:-1]: image_list=image_spec[1:] for ext in image_list: exts.append(copy.deepcopy(ext)) for this_file in os.listdir(directory): (root_file,ext_file)= os.path.splitext(this_file) if ext_file.lower() in exts: file_path=directory+os.sep+this_file # print "file path before ", file_path file_path=os.path.normpath(file_path) # print "file path after ", file_path self.add_track(file_path) self.save_medialist() def add_track(self,afile): relpath = os.path.relpath(afile,self.pp_home_dir) # print "relative path ",relpath common = os.path.commonprefix([afile,self.pp_home_dir]) # print "common ",common if common.endswith("pp_home") is False: location = afile else: location = "+" + os.sep + relpath location = string.replace(location,'\\','/') # print "location ",location (root,title)=os.path.split(afile) (root,ext)= os.path.splitext(afile) if ext.lower() in PPdefinitions.IMAGE_FILES: self.new_track(PPdefinitions.new_tracks['image'],{'title':title,'track-ref':'','location':location}) elif ext.lower() in PPdefinitions.VIDEO_FILES: self.new_track(PPdefinitions.new_tracks['video'],{'title':title,'track-ref':'','location':location}) elif ext.lower() in PPdefinitions.AUDIO_FILES: self.new_track(PPdefinitions.new_tracks['audio'],{'title':title,'track-ref':'','location':location}) elif ext.lower() in PPdefinitions.WEB_FILES: self.new_track(PPdefinitions.new_tracks['web'],{'title':title,'track-ref':'','location':location}) else: self.mon.err(self,afile + " - cannot determine track type, use menu track>new") # ********************************************* # UPDATE PROFILE # ********************************************** def update_all(self): self.init() for profile_file in os.listdir(self.pp_home_dir+os.sep+'pp_profiles'+self.pp_profiles_offset): # self.mon.log (self,"Updating "+profile_file) self.pp_profile_dir = self.pp_home_dir+os.sep+'pp_profiles'+self.pp_profiles_offset + os.sep + profile_file if not os.path.exists(self.pp_profile_dir+os.sep+"pp_showlist.json"): tkMessageBox.showwarning("Pi Presents","Not a profile, skipping "+self.pp_profile_dir) else: self.current_showlist=ShowList() self.current_showlist.open_json(self.pp_profile_dir+os.sep+"pp_showlist.json") self.mon.log (self,"Version of profile "+ profile_file + ' is ' + self.current_showlist.sissue()) if float(self.current_showlist.sissue())<float(self.editor_issue): self.mon.log(self,"Version of profile "+profile_file+ " is being updated to "+self.editor_issue) self.update_profile() elif (self.command_options['forceupdate'] is True and float(self.current_showlist.sissue()) == float(self.editor_issue)): self.mon.log(self, "Forced updating of " + profile_file + ' to '+self.editor_issue) self.update_profile() elif float(self.current_showlist.sissue())>float(self.editor_issue): tkMessageBox.showwarning("Pi Presents", "Version of profile " +profile_file+ " is greater than editor, skipping") else: self.mon.log(self," Skipping Profile " + profile_file + " It is already up to date ") self.init() tkMessageBox.showwarning("Pi Presents","All profiles updated") def update_profile(self): self.update_medialists() # medialists and their tracks self.update_shows() #shows in showlist, also creates menu tracks for 1.2>1.3 def update_shows(self): # open showlist into a list of dictionaries self.mon.log (self,"Updating show ") ifile = open(self.pp_profile_dir + os.sep + "pp_showlist.json", 'rb') shows = json.load(ifile)['shows'] ifile.close() # special 1.2>1.3 create menu medialists with menu track from show #go through shows - if type = menu and version is greater copy its medialist to a new medialist with name = <show-ref>-menu1p3.json for show in shows: #create a new medialist medialist != show-ref as menus can't now share medialists if show['type']=='menu' and float(self.current_showlist.sissue())<float(self.editor_issue): to_file=show['show-ref']+'-menu1p3.json' from_file = show['medialist'] if to_file != from_file: self.copy_medialist_file(from_file,to_file) else: self.mon.warn(self, 'medialist file' + to_file + ' already exists, must exit with incomplete update') return False #update the reference to the medialist show['medialist']=to_file #delete show fields so they are recreated with new default content del show['controls'] # open the medialist and add the menu track then populate some of its fields from the show ifile = open(self.pp_profile_dir + os.sep + to_file, 'rb') tracks = json.load(ifile)['tracks'] ifile.close() new_track=copy.deepcopy(PPdefinitions.new_tracks['menu']) tracks.append(copy.deepcopy(new_track)) # copy menu parameters from menu show to menu track and init values of some self.transfer_show_params(show,tracks,'menu-track',("entry-colour","entry-font", "entry-select-colour", "hint-colour", "hint-font", "hint-text", "hint-x","hint-y", "menu-bullet", "menu-columns", "menu-direction", "menu-guidelines", "menu-horizontal-padding", "menu-horizontal-separation", "menu-icon-height", "menu-icon-mode", "menu-icon-width", "menu-rows", "menu-strip", "menu-strip-padding", "menu-text-height", "menu-text-mode", "menu-text-width", "menu-vertical-padding", "menu-vertical-separation", "menu-window")) # and save the medialist dic={'issue':self.editor_issue,'tracks':tracks} ofile = open(self.pp_profile_dir + os.sep + to_file, "wb") json.dump(dic,ofile,sort_keys=True,indent=1) # end for show in shows #update the fields in all shows replacement_shows=self.update_shows_in_showlist(shows) dic={'issue':self.editor_issue,'shows':replacement_shows} ofile = open(self.pp_profile_dir + os.sep + "pp_showlist.json", "wb") json.dump(dic,ofile,sort_keys=True,indent=1) return True def transfer_show_params(self,show,tracks,track_ref,fields): # find the menu track in medialist for index,track in enumerate(tracks): if track['track-ref']== 'menu-track': break #update some fields with new default content tracks[index]['links']=PPdefinitions.new_tracks['menu']['links'] #transfer values from show to track for field in fields: tracks[index][field]=show[field] # print show[field], tracks[index][field] pass def update_medialists(self): # UPDATE MEDIALISTS AND THEIR TRACKS for this_file in os.listdir(self.pp_profile_dir): if this_file.endswith(".json") and this_file not in ('pp_showlist.json','schedule.json'): self.mon.log (self,"Updating medialist " + this_file) # open a medialist and update its tracks ifile = open(self.pp_profile_dir + os.sep + this_file, 'rb') tracks = json.load(ifile)['tracks'] ifile.close() replacement_tracks=self.update_tracks(tracks) dic={'issue':self.editor_issue,'tracks':replacement_tracks} ofile = open(self.pp_profile_dir + os.sep + this_file, "wb") json.dump(dic,ofile,sort_keys=True,indent=1) def update_tracks(self,old_tracks): # get correct spec from type of field replacement_tracks=[] for old_track in old_tracks: # print '\nold track ',old_track track_type=old_track['type'] #update if new tracks has the track type otherwise skip if track_type in PPdefinitions.new_tracks: spec_fields=PPdefinitions.new_tracks[track_type] left_overs=dict() # go through track and delete fields not in spec for key in old_track.keys(): if key in spec_fields: left_overs[key]=old_track[key] # print '\n leftovers',left_overs replacement_track=copy.deepcopy(PPdefinitions.new_tracks[track_type]) # print '\n before update', replacement_track replacement_track.update(left_overs) # print '\nafter update',replacement_track replacement_tracks.append(copy.deepcopy(replacement_track)) return replacement_tracks def update_shows_in_showlist(self,old_shows): # get correct spec from type of field replacement_shows=[] for old_show in old_shows: show_type=old_show['type'] ## menu to menushow spec_fields=PPdefinitions.new_shows[show_type] left_overs=dict() # go through track and delete fields not in spec for key in old_show.keys(): if key in spec_fields: left_overs[key]=old_show[key] # print '\n leftovers',left_overs replacement_show=copy.deepcopy(PPdefinitions.new_shows[show_type]) replacement_show.update(left_overs) replacement_shows.append(copy.deepcopy(replacement_show)) return replacement_shows
class FoodGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Food List Editor") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.columnconfigure(1, weight=1) self.columnconfigure(3, pad=7) self.rowconfigure(4, weight=1) self.rowconfigure(5, pad=7) lbl = Label(self, text="Food List") lbl.grid(sticky=W, pady=4, padx=5) abtn = Button(self, text="Add Food", command=self.sequence) abtn.grid(row=1, column=3) dbtn = Button(self, text="Delete Food", command=self.delete_food) dbtn.grid(row=2, column=3, pady=4) upbtn = Button(self, text="Refresh", command=self.update_list) upbtn.grid(row=3, column=3) cbtn = Button(self, text="Close", command=self.close_program) cbtn.grid(row=5, column=3) scrollbar = Scrollbar(self, orient="vertical") self.lb = Listbox(self, width=50, height=20,\ yscrollcommand=scrollbar.set) scrollbar.config(command=self.lb.yview) self.make_list() def make_list(self): while self.lb.size(): self.lb.delete(0) try: acts1 = open("food_list.txt") acts = acts1.readlines() acts1.close() except IOError: new_list = open("food_list.txt", 'w') new_list.close() acts1 = open("food_list.txt") acts = acts1.readlines() acts1.close() for i in acts: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>") self.lb.place(x=5, y=25) def sequence(self): self.add_food() self.update_list() def update_list(self): del_list = open('food_list.txt') del_list2 = del_list.readlines() del_list.close() new_food_list = open('food_list.txt', 'w') for line in del_list2: if line != "\n": new_food_list.writelines(line) new_food_list.close() self.make_list() def add_food(self): if __name__ == '__main__': root2 = Tk() root2.geometry("500x200+500+300") app2 = AddFood(root2, self) root2.mainloop() def delete_food(self): del_f = self.lb.get(ACTIVE) del_list = open('food_list.txt') del_list2 = del_list.readlines() del_list.close() new_food_list = open('food_list.txt', 'w') for line in del_list2: if line != del_f: new_food_list.writelines(line) new_food_list.close() self.update_list() def close_program(self): exit(0)
class OSCRemote(object): def __init__(self): self.editor_issue="1.3" # get command options self.command_options=remote_options() # get directory holding the code self.pp_dir=sys.path[0] if not os.path.exists(self.pp_dir+os.sep+"pp_oscremote.py"): tkMessageBox.showwarning("Pi Presents","Bad Application Directory") exit() # Initialise logging Monitor.log_path=self.pp_dir self.mon=Monitor() self.mon.init() Monitor.classes = ['OSCRemote','OSCConfig','OSCEditor'] Monitor.log_level = int(self.command_options['debug']) self.mon.log (self, "Pi Presents Remote is starting") self.mon.log (self," OS and separator " + os.name +' ' + os.sep) self.mon.log(self,"sys.path[0] - location of code: code "+sys.path[0]) self.setup_gui() # OSC config class self.osc_config=OSCConfig() self.init() #and start the system self.root.after(1000,self.run_app) self.root.mainloop() def init(self): self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscremote.cfg' self.read_create_osc() self.pp_home_dir = self.osc_config.pp_home_dir self.pp_profiles_offset = self.osc_config.pp_profiles_offset self.mon.log(self,"Data Home from options is "+self.pp_home_dir) self.mon.log(self,"Current Profiles Offset from options is "+self.pp_profiles_offset) self.pp_profile_dir='' self.current_showlist=None self.current_show=None self.current_show_ref='' self.shows_display.delete(0,END) self.results.set('') def add_status(self,text): self.status_display.insert(END,text+'\n') self.status_display.see(END) def run_app(self): self.client=None self.server=None self.st=None # initialise OSC variables self.prefix='/pipresents' self.this_unit='/' + self.osc_config.this_unit_name self.add_status('this unit is: '+self.this_unit) self.controlled_unit='/'+self.osc_config.controlled_unit_1_name self.add_status('controlled unit is: '+self.controlled_unit) #connect client then start server to listen for replies self.init_client() self.add_status('connecting to controlled unit: '+self.osc_config.controlled_unit_1_ip+':'+self.osc_config.controlled_unit_1_port +' '+self.osc_config.controlled_unit_1_name) self.connect_client(self.osc_config.controlled_unit_1_ip,self.osc_config.controlled_unit_1_port) self.add_status('listening for replies on:'+self.osc_config.this_unit_ip+':'+self.osc_config.this_unit_port) self.init_server(self.osc_config.this_unit_ip,self.osc_config.this_unit_port,self.client) self.add_initial_handlers() self.start_server() # *************************************** # RESPOND TO BUTTONS # *************************************** def open_show(self): self.msg_path= '/core/open ' self.msg_arg_text= self.current_show_ref self.display_msg_text() def close_show(self): self.msg_path= '/core/close ' self.msg_arg_text=self.current_show_ref self.display_msg_text() def exit_pipresents(self): self.msg_path= '/core/exitpipresents' self.msg_arg_text='' self.display_msg_text() def play_event(self): self.msg_path= '/core/event' self.msg_arg_text = 'pp-play' self.display_msg_text() def pause_event(self): self.msg_path= '/core/event' self.msg_arg_text='pp-pause' self.display_msg_text() pass def stop_event(self): self.msg_path= '/core/event' self.msg_arg_text='pp-stop' self.display_msg_text() pass def up_event(self): self.msg_path= '/core/event' self.msg_arg_text='pp-up' self.display_msg_text() def down_event(self): self.msg_path= '/core/event' self.msg_arg_text='pp-down' self.display_msg_text() def output(self): self.msg_path= '/core/output' self.msg_arg_text='' self.display_msg_text() def loopback(self): self.msg_path= '/system/loopback' self.msg_arg_text='' self.display_msg_text() def server_info(self): self.msg_path= '/system/server-info' self.msg_arg_text='' self.display_msg_text() # and put the created text in the results box in the gui def display_msg_text(self): self.results.set(self.prefix+self.controlled_unit+self.msg_path+' '+self.msg_arg_text) #calback from the Send button # parses the message string into fields and sends - NO error checking def send_message(self): msg_text=self.results.get() self.add_status('Send message:'+msg_text) self.mon.log(self,'send message: ' + msg_text ) fields=msg_text.split() address = fields[0] arg_list=fields[1:] self.send(address,arg_list) # *************************************** # OSC CLIENT TO SEND MESSAGES # *************************************** def init_client(self): self.client = OSC.OSCClient() def connect_client(self,ip,port): self.mon.log(self,'connect to: '+ip+':'+str(port)) self.client.connect( (ip, int(port)) ) def send(self,address,arg_list): msg = OSC.OSCMessage() msg.setAddress(address) for arg in arg_list: msg.append(arg) self.client.send(msg) def disconnect_client(self): self.client.close() return # *************************************** # OSC SERVER TO LISTEN TO REPLIES # *************************************** def init_server(self,ip,port_text,client): self.mon.log(self,'Start Server: '+ip+':'+port_text) self.server = OSC.OSCServer((ip,int(port_text)),client) def start_server(self): self.st = threading.Thread( target = self.server.serve_forever ) self.st.start() def close_server(self): if self.server != None: self.server.close() self.mon.log(self, 'Waiting for Server-thread to finish') if self.st != None: self.st.join() ##!!! self.mon.log(self,'server thread closed') def add_initial_handlers(self): self.server.addMsgHandler('default', self.no_match_handler) self.server.addMsgHandler(self.prefix+self.this_unit+"/system/loopback-reply", self.loopback_reply_handler) self.server.addMsgHandler(self.prefix+self.this_unit+"/system/server-info-reply", self.server_info_reply_handler) def no_match_handler(self,addr, tags, stuff, source): text='' text+= "no match for new osc msg from %s" % OSC.getUrlStr(source)+'\n' text+= "with addr : %s" % addr+'\n' text+= "typetags %s" % tags+'\n' text+= "data %s" % stuff+'\n' self.add_status(text+'\n') def loopback_reply_handler(self,addr, tags, stuff, source): self.add_status('Loopback reply received from: '+ self.pretty_list(source)) def server_info_reply_handler(self,addr, tags, stuff, source): self.add_status('Server Information from: '+ self.pretty_list(source) + '\n ' + self.pretty_list(stuff)) def pretty_list(self,fields): text=' ' for field in fields: text += str(field) + ' ' return text # *************************************** # INIT EXIT MISC # *************************************** def e_edit_osc(self): self.disconnect_client() self.close_server() self.edit_osc() self.init() self.add_status('\n\n\nRESTART') self.run_app() def app_exit(self): self.disconnect_client() self.close_server() if self.root is not None: self.root.destroy() self.mon.finish() sys.exit() def show_help (self): tkMessageBox.showinfo("Help","Read 'manual.pdf'") def about (self): tkMessageBox.showinfo("About","Simple Remote Control for Pi Presents\n" +"Author: Ken Thompson" +"\nWebsite: http://pipresents.wordpress.com/") def setup_gui(self): # set up the gui # root is the Tkinter root widget self.root = Tk() self.root.title("Remote Control for Pi Presents") # self.root.configure(background='grey') self.root.resizable(False,False) # define response to main window closing self.root.protocol ("WM_DELETE_WINDOW", self.app_exit) # bind some display fields self.filename = StringVar() self.display_show = StringVar() self.results = StringVar() self.status = StringVar() # define menu menubar = Menu(self.root) profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black") profilemenu.add_command(label='Select', command = self.open_existing_profile) menubar.add_cascade(label='Profile', menu = profilemenu) toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Tools', menu = toolsmenu) osc_configmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='OSC', menu = osc_configmenu) osc_configmenu.add_command(label='Edit', command = self.e_edit_osc) helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Help', menu = helpmenu) helpmenu.add_command(label='Help', command = self.show_help) helpmenu.add_command(label='About', command = self.about) self.root.config(menu=menubar) #top frame top_frame=Frame(self.root,padx=5,pady=5) top_frame.pack(side=TOP) results_label = Label(top_frame, text="Message to Send",font="arial 12 bold") results_label.pack(side=LEFT) results_display=Entry(top_frame, textvariable=self.results, width=70) results_display.pack(side=LEFT,fill=BOTH, expand=1) send_button = Button(top_frame, width = 5, height = 1, text='Send', fg='black', command = self.send_message, bg="light grey") send_button.pack(side=RIGHT) #bottom frame bottom_frame=Frame(self.root,padx=5,pady=5) bottom_frame.pack(side=TOP, fill=BOTH, expand=1) left_frame=Frame(bottom_frame, padx=5) left_frame.pack(side=LEFT) right_frame=Frame(bottom_frame,padx=5,pady=5) right_frame.pack(side=LEFT) suplabel_frame=Frame(right_frame,pady=5) suplabel_frame.pack(side=TOP) commands_label = Label(suplabel_frame, text="Show Control",font="arial 12 bold") commands_label.pack() supervisor_frame=Frame(right_frame,pady=5) supervisor_frame.pack(side=TOP) # supervisor buttons add_button = Button(supervisor_frame, width = 5, height = 1, text='Open\nShow', fg='black', command = self.open_show, bg="light grey") add_button.pack(side=LEFT) add_button = Button(supervisor_frame, width = 5, height = 1, text='Close\nShow', fg='black', command = self.close_show, bg="light grey") add_button.pack(side=LEFT) add_button = Button(supervisor_frame, width = 10, height = 1, text='Exit\nPi Presents', fg='black', command = self.exit_pipresents, bg="light grey") add_button.pack(side=LEFT) # events buttons oplabel_frame=Frame(right_frame,pady=5) oplabel_frame.pack(side=TOP) operations_label = Label(oplabel_frame, text="Input Events", font="arial 12 bold") operations_label.pack() operations_frame=Frame(right_frame,pady=5) operations_frame.pack(side=TOP) add_button = Button(operations_frame, width = 5, height = 1, text='Play', fg='black', command = self.play_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width = 5, height = 1, text='Pause', fg='black', command = self.pause_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width = 5, height = 1, text='Stop', fg='black', command = self.stop_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width = 5, height = 1, text='Up', fg='black', command = self.up_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width = 5, height = 1, text='Down', fg='black', command = self.down_event, bg="light grey") add_button.pack(side=LEFT) # animate buttons animate_frame=Frame(right_frame,pady=5) animate_frame.pack(side=TOP) animate_label = Label(animate_frame, text="Control Outputs", font="arial 12 bold") animate_label.pack() animate_frame=Frame(right_frame,pady=5) animate_frame.pack(side=TOP) add_button = Button(animate_frame, width = 5, height = 1, text='Output', fg='black', command = self.output, bg="light grey") add_button.pack(side=LEFT) # system buttons systemlabel_frame=Frame(right_frame,pady=5) systemlabel_frame.pack(side=TOP) system_label = Label(systemlabel_frame, text="System", font="arial 12 bold") system_label.pack() system_frame=Frame(right_frame,pady=5) system_frame.pack(side=TOP) add_button = Button(system_frame, width = 5, height = 1, text='Loopback', fg='black', command = self.loopback, bg="light grey") add_button.pack(side=LEFT) add_button = Button(system_frame, width = 10, height = 1, text='Server Info', fg='black', command = self.server_info, bg="light grey") add_button.pack(side=LEFT) # define display of showlist shows_title_frame=Frame(left_frame) shows_title_frame.pack(side=TOP) shows_label = Label(shows_title_frame, text="Shows") shows_label.pack() shows_frame=Frame(left_frame) shows_frame.pack(side=TOP) scrollbar = Scrollbar(shows_frame, orient=VERTICAL) self.shows_display = Listbox(shows_frame, selectmode=SINGLE, height=12, width = 40, bg="white",activestyle=NONE, fg="black", yscrollcommand=scrollbar.set) scrollbar.config(command=self.shows_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.shows_display.pack(side=LEFT, fill=BOTH, expand=1) self.shows_display.bind("<ButtonRelease-1>", self.e_select_show) # status_frame status_frame=Frame(self.root,padx=5,pady=5) status_frame.pack(side=TOP, fill=BOTH, expand=1) status_label = Label(status_frame, text="Status",font="arial 12 bold") status_label.pack(side=LEFT) scrollbar = Scrollbar(status_frame, orient=VERTICAL) self.status_display=Text(status_frame,height=10, yscrollcommand=scrollbar.set) scrollbar.config(command=self.status_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.status_display.pack(side=LEFT,fill=BOTH, expand=1) # *************************************** # SHOWLIST # *************************************** def open_existing_profile(self): initial_dir=self.pp_home_dir+os.sep+"pp_profiles"+self.pp_profiles_offset if os.path.exists(initial_dir) is False: self.mon.err(self,"Profiles directory not found: " + initial_dir + "\n\nHint: Data Home option must end in pp_home") return dir_path=tkFileDialog.askdirectory(initialdir=initial_dir) # dir_path="C:\Users\Ken\pp_home\pp_profiles\\ttt" if len(dir_path)>0: self.open_profile(dir_path) def open_profile(self,dir_path): showlist_file = dir_path + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err(self,"Not a Profile: " + dir_path + "\n\nHint: Have you opened the profile directory?") return self.pp_profile_dir = dir_path self.root.title("Remote for Pi Presents - "+ self.pp_profile_dir) self.open_showlist(self.pp_profile_dir) def open_showlist(self,profile_dir): showlist_file = profile_dir + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err(self,"showlist file not found at " + profile_dir + "\n\nHint: Have you opened the profile directory?") self.app_exit() self.current_showlist=ShowList() self.current_showlist.open_json(showlist_file) if float(self.current_showlist.sissue()) != float(self.editor_issue): self.mon.err(self,"Version of profile does not match Remote: "+self.editor_issue) self.app_exit() self.refresh_shows_display() def refresh_shows_display(self): self.shows_display.delete(0,self.shows_display.size()) for index in range(self.current_showlist.length()): self.shows_display.insert(END, self.current_showlist.show(index)['title']+" ["+self.current_showlist.show(index)['show-ref']+"]") if self.current_showlist.show_is_selected(): self.shows_display.itemconfig(self.current_showlist.selected_show_index(),fg='red') self.shows_display.see(self.current_showlist.selected_show_index()) def e_select_show(self,event): print 'select show', self.current_showlist.length() if self.current_showlist is not None and self.current_showlist.length()>0: mouse_item_index=int(event.widget.curselection()[0]) self.current_showlist.select(mouse_item_index) self.current_show_ref=self.current_showlist.selected_show()['show-ref'] self.refresh_shows_display() else: self.current_show_ref='' # *************************************** # OSC CONFIGURATION # *************************************** def read_create_osc(self): if self.osc_config.read(self.osc_config_file) is False: self.osc_config.create(self.osc_config_file) eosc = OSCEditor(self.root, self.osc_config_file,'remote','Create OSC Remote Configuration') self.osc_config.read(self.osc_config_file) def edit_osc(self): if self.osc_config.read(self.osc_config_file) is False: self.osc_config.create(self.osc_config_file) eosc = OSCEditor(self.root, self.osc_config_file,'remote','Edit OSC Reomote Configuration')
class EktaproGUI(Tk): """ Constructs the main program window and interfaces with the EktaproController and the TimerController to access the slide projectors. """ def __init__(self): self.controller = EktaproController() self.controller.initDevices() Tk.__init__(self) self.protocol("WM_DELETE_WINDOW", self.onQuit) self.wm_title("EktaproGUI") self.bind("<Prior>", self.priorPressed) self.bind("<Next>", self.nextPressed) self.brightness = 0 self.slide = 1 self.timerController = TimerController(self.controller, self) self.controlPanel = Frame(self) self.manualPanel = Frame(self) self.projektorList = Listbox(self, selectmode=SINGLE) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) self.projektorList.bind("<ButtonRelease>", self.projektorSelectionChanged) self.projektorList.config(width=50) self.initButton = Button(self.controlPanel, text="init", command=self.initButtonPressed) self.nextButton = Button(self.controlPanel, text="next slide", command=self.nextSlidePressed) self.nextButton.config(state=DISABLED) self.prevButton = Button(self.controlPanel, text="previous slide", command=self.prevSlidePressed) self.prevButton.config(state=DISABLED) self.startButton = Button(self.controlPanel, text="start timer", command=self.startTimer) self.startButton.config(state=DISABLED) self.pauseButton = Button(self.controlPanel, text="pause", command=self.pauseTimer) self.stopButton = Button(self.controlPanel, text="stop", command=self.stopTimer) self.stopButton.config(state=DISABLED) self.timerLabel = Label(self.controlPanel, text="delay:") self.timerInput = Entry(self.controlPanel, width=3) self.timerInput.insert(0, "5") self.timerInput.config(state=DISABLED) self.timerInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.timerInput.bind("<ButtonRelease>", self.updateGUI) self.fadeLabel = Label(self.controlPanel, text="fade:") self.fadeInput = Entry(self.controlPanel, width=3) self.fadeInput.insert(0, "1") self.fadeInput.config(state=DISABLED) self.fadeInput.bind("<KeyPress-Return>", self.inputValuesChanged) self.fadeInput.bind("<ButtonRelease>", self.updateGUI) self.standbyButton = Button(self.controlPanel, text="standby", command=self.toggleStandby) self.standbyButton.config(state=DISABLED) self.syncButton = Button(self.controlPanel, text="sync", command=self.sync) self.syncButton.config(state=DISABLED) self.reconnectButton = Button(self.controlPanel, text="reconnect", command=self.reconnect) self.cycle = IntVar() self.cycleButton = Checkbutton( self.controlPanel, text="use all projectors", variable=self.cycle, command=self.cycleToggled ) self.brightnessScale = Scale(self.manualPanel, from_=0, to=100, resolution=1, label="brightness") self.brightnessScale.set(self.brightness) self.brightnessScale.bind("<ButtonRelease>", self.brightnessChanged) self.brightnessScale.config(state=DISABLED) self.brightnessScale.config(orient=HORIZONTAL) self.brightnessScale.config(length=400) self.gotoSlideScale = Scale(self.manualPanel, from_=0, to=self.controller.maxTray, label="goto slide") self.gotoSlideScale.set(1) self.gotoSlideScale.bind("<ButtonRelease>", self.gotoSlideChanged) self.gotoSlideScale.config(state=DISABLED) self.gotoSlideScale.config(orient=HORIZONTAL) self.gotoSlideScale.config(length=400) self.controlPanel.pack(side=BOTTOM, anchor=W, fill=X) self.projektorList.pack(side=LEFT, fill=BOTH) self.manualPanel.pack(side=RIGHT, expand=1, fill=BOTH) self.initButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.prevButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.nextButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.cycleButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.startButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.pauseButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.stopButton.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.timerInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeLabel.pack(side=LEFT, anchor=N, padx=4, pady=4) self.fadeInput.pack(side=LEFT, anchor=N, padx=4, pady=4) self.syncButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.standbyButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.reconnectButton.pack(side=RIGHT, anchor=N, padx=4, pady=4) self.brightnessScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.gotoSlideScale.pack(side=TOP, anchor=W, expand=1, fill=X) self.menubar = Menu(self) self.toolsmenu = Menu(self.menubar) self.helpmenu = Menu(self.menubar) self.filemenu = Menu(self.menubar) self.toolsmenu.add_command(label="Interpret HEX Sequence", command=self.interpretHEXDialog) self.helpmenu.add_command( label="About EktaproGUI", command=lambda: tkMessageBox.showinfo("About EktaproGUI", "EktaproGUI 1.0 (C)opyright Julian Hoch 2010"), ) self.filemenu.add_command(label="Exit", command=self.onQuit) self.menubar.add_cascade(label="File", menu=self.filemenu) self.menubar.add_cascade(label="Tools", menu=self.toolsmenu) self.menubar.add_cascade(label="Help", menu=self.helpmenu) self.configure(menu=self.menubar) def initButtonPressed(self): self.controller.resetDevices() self.updateGUI() self.brightnessScale.config(state=NORMAL) self.gotoSlideScale.config(state=NORMAL) self.nextButton.config(state=NORMAL) self.prevButton.config(state=NORMAL) self.startButton.config(state=NORMAL) self.timerInput.config(state=NORMAL) self.fadeInput.config(state=NORMAL) self.syncButton.config(state=NORMAL) self.standbyButton.config(state=NORMAL) def inputValuesChanged(self, event): try: fadeDelay = int(self.fadeInput.get()) slideshowDelay = int(self.timerInput.get()) if fadeDelay in range(0, 60): self.timerController.fadeDelay = fadeDelay if slideshowDelay in range(1, 60): self.timerController.slideshowDelay = slideshowDelay except Exception: pass self.updateGUI() def sync(self): self.controller.syncDevices() self.updateGUI() def reconnect(self): self.controller.cleanUp() self.controller.initDevices() self.updateGUI() self.projektorList.delete(0, END) for i in range(len(self.controller.devices)): self.projektorList.insert(END, "[" + str(i) + "] " + str(self.controller.devices[i])) if self.projektorList.size >= 1: self.projektorList.selection_set(0) def projektorSelectionChanged(self, event): items = map(int, self.projektorList.curselection()) if self.controller.setActiveDevice(items): self.updateGUI() def updateGUI(self, event=None): if self.controller.activeDevice == None: return self.brightness = self.controller.activeDevice.brightness self.brightnessScale.set(self.brightness) self.slide = self.controller.activeDevice.slide self.gotoSlideScale.set(self.slide) for i in range(self.projektorList.size()): if i == self.controller.activeIndex: self.projektorList.selection_set(i) else: self.projektorList.selection_clear(i) def brightnessChanged(self, event): newBrightness = self.brightnessScale.get() if not self.brightness == newBrightness and not self.controller.activeDevice == None: self.controller.activeDevice.setBrightness(newBrightness) self.brightness = self.brightnessScale.get() def gotoSlideChanged(self, event): if self.controller.activeDevice is None: return newSlide = self.gotoSlideScale.get() if not self.slide == newSlide: self.controller.activeDevice.gotoSlide(newSlide) self.slide = newSlide def nextSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.nextSlide() self.updateGUI() def prevSlidePressed(self): if self.controller.activeDevice is None: return self.timerController.fadePaused = False self.timerController.previousSlide() self.updateGUI() def startTimer(self): self.stopButton.config(state=NORMAL) self.startButton.config(state=DISABLED) self.timerController.startSlideshow() def pauseTimer(self): if self.timerController.fadePaused or self.timerController.slideshowPaused: self.pauseButton.config(text="pause") self.timerController.resume() self.updateGUI() else: self.pauseButton.config(text="resume") self.timerController.pause() self.updateGUI() def stopTimer(self): self.pauseButton.config(text="pause") self.stopButton.config(state=DISABLED) self.startButton.config(state=NORMAL) self.timerController.stopSlideshow() self.updateGUI() def cycleToggled(self): self.timerController.cycle = True if self.cycle.get() == 1 else False def interpretHEXDialog(self): interpretDialog = InterpretHEXDialog(self) # @UnusedVariable def toggleStandby(self): if self.pauseButton.config()["text"][4] == "pause" and self.pauseButton.config()["state"][4] == "normal": self.pauseTimer() self.controller.toggleStandby() def nextPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.pauseTimer() else: self.nextSlidePressed() def priorPressed(self, event): if self.startButton.config()["state"][4] == "disabled": self.toggleStandby() else: self.prevSlidePressed() def onQuit(self): self.controller.cleanUp() self.destroy()
class DrtGlueDemo(object): def __init__(self, examples): # Set up the main window. self._top = Tk() self._top.title('DRT Glue Demo') # Set up key bindings. self._init_bindings() # Initialize the fonts.self._error = None self._init_fonts(self._top) self._examples = examples self._readingCache = [None for example in examples] # The user can hide the grammar. self._show_grammar = IntVar(self._top) self._show_grammar.set(1) # Set the data to None self._curExample = -1 self._readings = [] self._drs = None self._drsWidget = None self._error = None self._init_glue() # Create the basic frames. self._init_menubar(self._top) self._init_buttons(self._top) self._init_exampleListbox(self._top) self._init_readingListbox(self._top) self._init_canvas(self._top) # Resize callback self._canvas.bind('<Configure>', self._configure) ######################################### ## Initialization Helpers ######################################### def _init_glue(self): tagger = RegexpTagger( [('^(David|Mary|John)$', 'NNP'), ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$', 'VB'), ('^(go|order|vanish|find|approach)$', 'VB'), ('^(a)$', 'ex_quant'), ('^(every)$', 'univ_quant'), ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'), ('^(big|gray|former)$', 'JJ'), ('^(him|himself)$', 'PRP') ]) depparser = MaltParser(tagger=tagger) self._glue = DrtGlue(depparser=depparser, remove_duplicates=False) def _init_fonts(self, root): # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html> self._sysfont = Font(font=Button()["font"]) root.option_add("*Font", self._sysfont) # TWhat's our font size (default=same as sysfont) self._size = IntVar(root) self._size.set(self._sysfont.cget('size')) self._boldfont = Font(family='helvetica', weight='bold', size=self._size.get()) self._font = Font(family='helvetica', size=self._size.get()) if self._size.get() < 0: big = self._size.get()-2 else: big = self._size.get()+2 self._bigfont = Font(family='helvetica', weight='bold', size=big) def _init_exampleListbox(self, parent): self._exampleFrame = listframe = Frame(parent) self._exampleFrame.pack(fill='both', side='left', padx=2) self._exampleList_label = Label(self._exampleFrame, font=self._boldfont, text='Examples') self._exampleList_label.pack() self._exampleList = Listbox(self._exampleFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._exampleList.pack(side='right', fill='both', expand=1) for example in self._examples: self._exampleList.insert('end', (' %s' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) # Add a scrollbar if there are more than 25 examples. if len(self._examples) > 25: listscroll = Scrollbar(self._exampleFrame, orient='vertical') self._exampleList.config(yscrollcommand = listscroll.set) listscroll.config(command=self._exampleList.yview) listscroll.pack(side='left', fill='y') # If they select a example, apply it. self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select) def _init_readingListbox(self, parent): self._readingFrame = listframe = Frame(parent) self._readingFrame.pack(fill='both', side='left', padx=2) self._readingList_label = Label(self._readingFrame, font=self._boldfont, text='Readings') self._readingList_label.pack() self._readingList = Listbox(self._readingFrame, selectmode='single', relief='groove', background='white', foreground='#909090', font=self._font, selectforeground='#004040', selectbackground='#c0f0c0') self._readingList.pack(side='right', fill='both', expand=1) # Add a scrollbar if there are more than 25 examples. listscroll = Scrollbar(self._readingFrame, orient='vertical') self._readingList.config(yscrollcommand = listscroll.set) listscroll.config(command=self._readingList.yview) listscroll.pack(side='right', fill='y') self._populate_readingListbox() def _populate_readingListbox(self): # Populate the listbox with integers self._readingList.delete(0, 'end') for i in range(len(self._readings)): self._readingList.insert('end', (' %s' % (i+1))) self._readingList.config(height=min(len(self._readings), 25), width=5) # If they select a example, apply it. self._readingList.bind('<<ListboxSelect>>', self._readingList_select) def _init_bindings(self): # Key bindings are a good thing. self._top.bind('<Control-q>', self.destroy) self._top.bind('<Control-x>', self.destroy) self._top.bind('<Escape>', self.destroy) self._top.bind('n', self.next) self._top.bind('<space>', self.next) self._top.bind('p', self.prev) self._top.bind('<BackSpace>', self.prev) def _init_buttons(self, parent): # Set up the frames. self._buttonframe = buttonframe = Frame(parent) buttonframe.pack(fill='none', side='bottom', padx=3, pady=2) Button(buttonframe, text='Prev', background='#90c0d0', foreground='black', command=self.prev,).pack(side='left') Button(buttonframe, text='Next', background='#90c0d0', foreground='black', command=self.next,).pack(side='left') def _configure(self, event): self._autostep = 0 (x1, y1, x2, y2) = self._cframe.scrollregion() y2 = event.height - 6 self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2) self._redraw() def _init_canvas(self, parent): self._cframe = CanvasFrame(parent, background='white', #width=525, height=250, closeenough=10, border=2, relief='sunken') self._cframe.pack(expand=1, fill='both', side='top', pady=2) canvas = self._canvas = self._cframe.canvas() # Initially, there's no tree or text self._tree = None self._textwidgets = [] self._textline = None def _init_menubar(self, parent): menubar = Menu(parent) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label='Exit', underline=1, command=self.destroy, accelerator='q') menubar.add_cascade(label='File', underline=0, menu=filemenu) actionmenu = Menu(menubar, tearoff=0) actionmenu.add_command(label='Next', underline=0, command=self.next, accelerator='n, Space') actionmenu.add_command(label='Previous', underline=0, command=self.prev, accelerator='p, Backspace') menubar.add_cascade(label='Action', underline=0, menu=actionmenu) optionmenu = Menu(menubar, tearoff=0) optionmenu.add_checkbutton(label='Remove Duplicates', underline=0, variable=self._glue.remove_duplicates, command=self._toggle_remove_duplicates, accelerator='r') menubar.add_cascade(label='Options', underline=0, menu=optionmenu) viewmenu = Menu(menubar, tearoff=0) viewmenu.add_radiobutton(label='Tiny', variable=self._size, underline=0, value=10, command=self.resize) viewmenu.add_radiobutton(label='Small', variable=self._size, underline=0, value=12, command=self.resize) viewmenu.add_radiobutton(label='Medium', variable=self._size, underline=0, value=14, command=self.resize) viewmenu.add_radiobutton(label='Large', variable=self._size, underline=0, value=18, command=self.resize) viewmenu.add_radiobutton(label='Huge', variable=self._size, underline=0, value=24, command=self.resize) menubar.add_cascade(label='View', underline=0, menu=viewmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label='About', underline=0, command=self.about) menubar.add_cascade(label='Help', underline=0, menu=helpmenu) parent.config(menu=menubar) ######################################### ## Main draw procedure ######################################### def _redraw(self): canvas = self._canvas # Delete the old DRS, widgets, etc. if self._drsWidget is not None: self._drsWidget.clear() if self._drs: self._drsWidget = DrsWidget( self._canvas, self._drs ) self._drsWidget.draw() if self._error: self._drsWidget = DrsWidget( self._canvas, self._error ) self._drsWidget.draw() ######################################### ## Button Callbacks ######################################### def destroy(self, *e): self._autostep = 0 if self._top is None: return self._top.destroy() self._top = None def prev(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or before) the first item if index <= 0: self._select_previous_example() else: self._readingList_store_selection(index-1) else: #select its first reading self._readingList_store_selection(readingListSize-1) else: self._select_previous_example() def _select_previous_example(self): #if the current example is not the first example if self._curExample > 0: self._exampleList_store_selection(self._curExample-1) else: #go to the last example self._exampleList_store_selection(len(self._examples)-1) def next(self, *e): selection = self._readingList.curselection() readingListSize = self._readingList.size() # if there are readings if readingListSize > 0: # if one reading is currently selected if len(selection) == 1: index = int(selection[0]) # if it's on (or past) the last item if index >= (readingListSize-1): self._select_next_example() else: self._readingList_store_selection(index+1) else: #select its first reading self._readingList_store_selection(0) else: self._select_next_example() def _select_next_example(self): #if the current example is not the last example if self._curExample < len(self._examples)-1: self._exampleList_store_selection(self._curExample+1) else: #go to the first example self._exampleList_store_selection(0) def about(self, *e): ABOUT = ("NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n"+ "Written by Daniel H. Garrette") TITLE = 'About: NLTK DRT Glue Demo' try: from tkMessageBox import Message Message(message=ABOUT, title=TITLE).show() except: ShowText(self._top, TITLE, ABOUT) def postscript(self, *e): self._autostep = 0 self._cframe.print_to_file() def mainloop(self, *args, **kwargs): """ Enter the Tkinter mainloop. This function must be called if this demo is created from a non-interactive program (e.g. from a secript); otherwise, the demo will close as soon as the script completes. """ if in_idle(): return self._top.mainloop(*args, **kwargs) def resize(self, size=None): if size is not None: self._size.set(size) size = self._size.get() self._font.configure(size=-(abs(size))) self._boldfont.configure(size=-(abs(size))) self._sysfont.configure(size=-(abs(size))) self._bigfont.configure(size=-(abs(size+2))) self._redraw() def _toggle_remove_duplicates(self): self._glue.remove_duplicates = not self._glue.remove_duplicates self._exampleList.selection_clear(0, 'end') self._readings = [] self._populate_readingListbox() self._readingCache = [None for ex in self._examples] self._curExample = -1 self._error = None self._drs = None self._redraw() def _exampleList_select(self, event): selection = self._exampleList.curselection() if len(selection) != 1: return self._exampleList_store_selection(int(selection[0])) def _exampleList_store_selection(self, index): self._curExample = index example = self._examples[index] self._exampleList.selection_clear(0, 'end') if example: cache = self._readingCache[index] if cache: if isinstance(cache, list): self._readings = cache self._error = None else: self._readings = [] self._error = cache else: try: self._readings = self._glue.parse_to_meaning(example) self._error = None self._readingCache[index] = self._readings except Exception, e: self._readings = [] self._error = DrtVariableExpression(Variable('Error: ' + str(e))) self._readingCache[index] = self._error #add a star to the end of the example self._exampleList.delete(index) self._exampleList.insert(index, (' %s *' % example)) self._exampleList.config(height=min(len(self._examples), 25), width=40) self._populate_readingListbox() self._exampleList.selection_set(index) self._drs = None self._redraw()
class InputDevice(object): def __init__(self): # root is the Tkinter root widget self.root = Tk() self.root.title("Input Device Utility") # self.root.configure(background='grey') self.root.resizable(False, False) # define response to main window closing self.root.protocol("WM_DELETE_WINDOW", self.app_exit) self.my_device = '' self.my_device_display = StringVar() self.device_list = [] self.matches = 0 # overall display root_frame = Frame(self.root) root_frame.pack(side=LEFT) devices_frame = Frame(root_frame, padx=5, pady=10) devices_frame.pack(side=LEFT) devices_label = Label(devices_frame, text="Devices in dev/input") devices_label.pack(side=TOP) devices_list_frame = Frame(devices_frame, padx=5, pady=10) devices_list_frame.pack(side=TOP) selected_device_title = Label(devices_frame, text='Selected device') selected_device_title.pack(side=TOP) self.selected_device_var = StringVar() selected_device = Label(devices_frame, textvariable=self.selected_device_var, fg="red") selected_device.pack(side=TOP) events_frame = Frame(root_frame, padx=5, pady=10) events_frame.pack(side=LEFT) events_title = Label(events_frame, text='Received Events') events_title.pack(side=TOP) events_list_frame = Frame(events_frame, padx=5, pady=10) events_list_frame.pack(side=TOP) # list of devices scrollbar = Scrollbar(devices_list_frame, orient=VERTICAL) self.devices_display = Listbox(devices_list_frame, selectmode=SINGLE, height=20, width=60, bg="white", activestyle=NONE, fg="black", yscrollcommand=scrollbar.set) scrollbar.config(command=self.devices_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.devices_display.pack(side=LEFT, fill=BOTH, expand=1) self.devices_display.bind("<ButtonRelease-1>", self.e_select_device) # events display scrollbar = Scrollbar(events_list_frame, orient=VERTICAL) self.events_display = Text(events_list_frame, width=40, height=20, wrap='word', font="arial 11", padx=5, yscrollcommand=scrollbar.set) scrollbar.config(command=self.events_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.events_display.pack(side=LEFT, fill=BOTH, expand=1) self.events_display.config(state=NORMAL) self.events_display.delete(1.0, END) self.events_display.config(state=DISABLED) self.selected_device_index = -1 self.matches = 0 self.get_all_devices() self.refresh_devices_display() self.root.after(10, self.event_loop) # and enter Tkinter event loop self.root.mainloop() # *************************************** # INIT AND EXIT # *************************************** def app_exit(self): self.root.destroy() exit() def event_loop(self): if self.matches > 0: self.get_events() self.root.after(10, self.event_loop) def refresh_devices_display(self): self.devices_display.delete(0, self.devices_display.size()) for device in self.all_devices: self.devices_display.insert(END, device[0] + ' ' + device[1]) if self.selected_device_index >= 0: self.devices_display.itemconfig(self.selected_device_index, fg='red') self.devices_display.see(self.selected_device_index) def e_select_device(self, event): self.selected_device_index = -1 if len(self.all_devices) > 0: self.selected_device_index = int(event.widget.curselection()[0]) selected_device = self.all_devices[self.selected_device_index] self.selected_device_name = selected_device[0] self.selected_device_var.set(self.selected_device_name) self.get_matching_devices() self.refresh_devices_display() def get_all_devices(self): self.all_devices = [] devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: self.all_devices.append([device.name, device.fn]) def get_matching_devices(self): self.matches = 0 self.matching_devices = [] devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: if self.selected_device_name in device.name: device_ref = evdev.InputDevice(device.fn) self.matching_devices.append(device_ref) self.matches += 1 def get_events(self): r, w, x = select(self.matching_devices, [], [], 0) if r == []: return for event in r[0].read(): if event.type == evdev.ecodes.EV_KEY: key_event = evdev.categorize(event) if key_event.keystate == 1: key_text = 'Down' else: key_text = 'Up' # print key_event.keycode,key_text if type(key_event.keycode) is list: code_text = ', '.join(key_event.keycode) else: code_text = key_event.keycode self.events_display.config(state=NORMAL) self.events_display.insert(END, '\n' + code_text + ' ' + key_text) self.events_display.config(state=DISABLED) self.events_display.see(END)
class SelectPaths(MyFrame): def __init__(self, topframe=None): MyFrame.__init__(self, topframe=topframe) style = Style() style.theme_use('clam') self.patient_foler_path = "" self.patients = [] self.set_title('Brain segmentation GUI') self.add_ui_components() def add_ui_components(self): # Creating the frames. self.sub_frame1 = Frame(self) self.sub_frame1.grid(column=0, row=0) sub_frame2 = Frame(self) sub_frame2.grid(column=0, row=1) sub_frame3 = Frame(self) sub_frame3.grid(column=0, row=2) sub_frame21 = Frame(sub_frame2) sub_frame21.grid(column=0, row=0) sub_frame22 = Frame(sub_frame2) sub_frame22.grid(padx=20, column=1, row=0) sub_frame221 = Frame(sub_frame22) sub_frame221.grid(row=1, column=0) # Creating the top-menu buttons. self.visualise_button = Button(self.sub_frame1, text="Visualise", command=self.start_visualisation) self.visualise_button.grid(row=0, column=1) self.help_button = Button(self.sub_frame1, text="Help", command=self.open_help) self.help_button.grid(row=0, column=2) # Creating the select modality path. self.modality_label = Label(sub_frame21, text="Path to patient folders", relief=FLAT) self.modality_label.grid(row=1, column=1) self.modality_path_entry = Entry(sub_frame21) self.modality_path_entry.grid(row=2, column=1) #self.modality_path_entry.set(self.patient_folder_path) self.modality_path_button = Button( sub_frame21, text="Choose", command=self.choose_directory_and_import) self.modality_path_button.grid(row=2, column=2) # Creating the patients listbox. self.label_patients = Label(sub_frame22, text="Patients") self.label_patients.grid(row=0, column=0) self.listbox_patients = Listbox(sub_frame221, selectmode='multiple', width=50, height=10) self.listbox_patients.pack(side=LEFT, fill=Y) #self.listbox_patients.grid(row=1, column=0) self.listbox_patients.bind("<Button-1>", self.listbox_changed) self.scrollbar = Scrollbar(sub_frame221) self.scrollbar.pack(side=RIGHT, fill=Y) # attach listbox to scrollbar self.listbox_patients.config(yscrollcommand=self.scrollbar.set) self.scrollbar.config(command=self.listbox_patients.yview) # Creating the status console. self.status_text = Text(sub_frame3, height=5) self.status_text.grid(column=0, row=0) self.status_text.tag_configure('title', justify='center', font="Arial 10 bold") self.status_text.tag_configure('entry', justify='left', font="Arial 9") self.status_text.insert(END, 'Status Console', 'title') self.status_text_entry_number = 1 self.status_text.configure(state='disabled') # ***** EVENTS - START******************************** def start_visualisation(self): """ Launch visualisation module. Linked to self.visualise_button (Button). """ patient_path = os.path.join(self.patient_folder_path, 'processed_' + self.patients[0]) segmentation_path = os.path.join( patient_path, SEGM_PREFIX + '_' + self.patients[0] + '.nii.gz') supervoxel_path = os.path.join( patient_path, SUPERVOXEL_PREFIX + '_' + self.patients[0] + '.nii.gz') # check if the supervoxels and the segmentation exist if not os.path.exists(supervoxel_path): supervoxel_path = None if not os.path.exists(segmentation_path): segmentation_path = None mod_paths = [] for mod in MODALITY_PREFIXES: mod_paths.append(\ os.path.join(patient_path, mod+'_'+self.patients[0]+'.nii.gz')) vis = vv.VisualVolumes(image_paths=mod_paths, segm_path=segmentation_path, supervoxel_id_path=supervoxel_path, topframe=self.master) vis.tkraise() def listbox_changed(self, event): """ Add a patient upon selection in the listbox. Linked to self.listbox_patients (Listbox). """ indices = list(self.listbox_patients.curselection()) selected_idx = self.listbox_patients.nearest(event.y) if selected_idx == -1: return # remove or add a patient index if selected_idx not in indices: indices.append(selected_idx) else: indices.remove(selected_idx) # set self.patients based on the new patient indices and enable visualisation if only one is selected. self.patients = [] for idx in indices: self.patients.append(self.listbox_patients.get(idx).split(' ')[0]) if len(self.patients) == 1: self.visualise_button['state'] = 'enabled' else: self.visualise_button['state'] = 'disabled' def choose_directory_and_import(self): """ Allow the user to select an import path. Linked to self.modality_path_button (Button), and sets self.modality_path_entry (Entry). """ initialdir = DATA_PATH msg = 'Select directory containing patients' path = askdirectory(title=msg, initialdir=initialdir) # update the text box. self.modality_path_entry.delete(0, END) self.modality_path_entry.insert(0, str(path)) # Adding the modality paths after the folder is selected. self.patient_folder_path = self.modality_path_entry.get() if os.path.exists(self.patient_folder_path): patients_validation = os.listdir(self.patient_folder_path) # Checking if the patient has the right modalities and importing the patient. for i, patient in enumerate(patients_validation): # Checking if the patient was already processed. if patient.startswith('processed_') or os.path.exists( os.path.join(self.patient_folder_path, 'processed_' + patient)): print("The files of the patient " + patient + " are already copied") continue # If everything is fine, then it continues to makign folders and copying files # Copying the files into the new folder. valid = self._convert_and_copy_files(patient) if not valid: patients_validation[i] = None # We make a list of patients with only ids for the listbox. valid_patients = [p for p in patients_validation if p is not None] self.list_existing_patients(valid_patients) def _convert_and_copy_files(self, patient): """ Check if all valid files exist for this patient and return True if so. """ # Getting the list of modalities for every patient. patient_path = os.path.join(self.patient_folder_path, patient) modalities = os.listdir(patient_path) # Look for paths valid_paths = {} prefices = [SEGM_PREFIX, SUPERVOXEL_PREFIX] + MODALITY_PREFIXES for prefix in prefices: candidates = [modality \ for modality in modalities \ if modality.startswith(prefix+'.')] if len(candidates) != 1: err = '%s file not identified. Look for ambiguities in %s.' \ % (prefix, patient_path) print(err) return False modality = candidates[0] if not any([ modality.endswith(ext) for ext in ['.mha', '.nii', '.nii.gz'] ]): err = "Image format not recognized: %s. In %s" \ % (modality, patient_path) print(err) return False valid_paths[prefix] = modality # Creating a processed patient folder. os.mkdir(os.path.join(self.patient_folder_path, 'processed_' + patient)) for prefix, basename in valid_paths.iteritems(): shutil.copyfile( os.path.join(self.patient_folder_path, patient, basename), os.path.join(self.patient_folder_path, 'processed_' + patient, prefix + '_' + patient + '.nii.gz')) return True def open_help(self): self.help_window = help_window.HelpWindow() self.help_window.tkraise() # ***** EVENTS - END*************************** def list_existing_patients(self, patients=None): print("Importing existing patients") # We make a list of patients with only ids for the listbox. if patients is None: patients = os.listdir(self.patient_folder_path) self.patients = [] for patient in patients: if not patient.startswith('processed_'): self.patients.append(patient) self.patients.sort() self.populate_patient_listbox(self.patients) if self.listbox_patients.size() > 0: self.listbox_patients.selection_set(0) self.status_text.configure(state='normal') self.status_text.insert( END, '\n' + str(self.status_text_entry_number) + '- Patients are imported.', 'entry') self.status_text_entry_number += 1 self.status_text.insert( END, '\n' + str(self.status_text_entry_number) + '- Please select a patient to proceed', 'entry') self.status_text_entry_number += 1 self.status_text.configure(state='disabled') def populate_patient_listbox(self, patients): self.listbox_patients.delete(0, END) for patient in patients: patient_path = os.path.join(self.patient_folder_path, 'processed_' + patient) #check if a given patient has a label if os.path.exists( os.path.join( patient_path, 'corrected_' + SEGM_PREFIX + '_' + patient + '.nii.gz')): patient = patient + ' - segmentation corrected' self.listbox_patients.insert(END, patient)
class Gamelist(): def __init__(self, drive, platform): GameListData.game_list_data_json = GameListData().get_game_list() self.json_game_list_data = GameListData.game_list_data_json if drive == 'USB(*)': self.drive_to_show = '/dev_' + drive.lower().replace('(*)', '') else: self.drive_to_show = '/dev_' + drive.lower() + '/' self.platform_to_show = platform + '_games' self.WCM_BASE_PATH = AppPaths.wcm_gui self.last_selection = (None, 0) self.list_of_items = [] self.selected_title_id = None self.selected_title = None self.selected_path = None self.selected_filename = None self.drive_system_path_array = None self.is_cleared = False def create_main_frame(self, entry_field_title_id, entry_field_title, entry_field_filename, entry_field_iso_path, entry_field_platform, drive_system_array): self.entry_field_title_id = entry_field_title_id self.entry_field_title = entry_field_title self.entry_field_filename = entry_field_filename self.entry_field_iso_path = entry_field_iso_path self.entry_field_platform = entry_field_platform self.drive_system_path_array = drive_system_array self.corrected_index = [] self.main_frame = Frame() self.popup_menu = Menu(self.main_frame, tearoff=0) self.popup_menu.add_command(label="Delete", command=self.delete_selected) self.popup_menu.add_command(label="Rename", command=self.rename_selected) # self.popup_menu.add_command(label="Refetch", # command=self.refetch) # self.popup_menu.add_command(label="Select All", # command=self.select_all) s = Scrollbar(self.main_frame) self._listbox = Listbox(self.main_frame, width=465) self._listbox.bind('<Enter>', self._bound_to_mousewheel) self._listbox.bind('<Leave>', self._unbound_to_mousewheel) self._listbox.bind("<Button-3>", self.popup) # Button-2 on Aqua s.pack(side=RIGHT, fill=Y) self._listbox.pack(side=LEFT, fill=Y) s['command'] = self._listbox.yview self._listbox['yscrollcommand'] = s.set # default filters if 'ALL_games' == self.platform_to_show: # iterate all platforms for platform in self.json_game_list_data: for list_game in self.json_game_list_data[platform]: # titles in the list has been designed to be unique if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']: self.add_item(list_game['title']) else: for list_game in self.json_game_list_data[self.platform_to_show]: if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']: self.add_item(list_game['title']) for x in range(19 - self._listbox.size()): self.add_item('') # adding shade to every other row of the list for x in range(0, self._listbox.size()): if x % 2 == 0: self._listbox.itemconfig(x, {'fg': 'white'}, background='#001738') else: self._listbox.itemconfig(x, {'fg': 'white'}, background='#001F4C') self.label = Label(self.main_frame) self.selection_poller() return self.main_frame def selection_poller(self): self.label.after(200, self.selection_poller) self.new_selection = self._listbox.curselection() # cursor har been initiated if self._listbox.curselection() is not (): if self.new_selection[0] is not self.last_selection[0] or self.is_cleared: self.entry_fields_update(self.new_selection) self.is_cleared = False self.last_selection = self.new_selection def entry_fields_update(self, new_selection): for platform in self.json_game_list_data: for list_game in self.json_game_list_data[platform]: self.selected_title = self._listbox.get(new_selection[0]) tmp_title = list_game['title'] match = self.selected_title == str(tmp_title) if match: self.selected_title_id = str(list_game['title_id']).replace('-', '') self.selected_title = str(list_game['title']) self.selected_path = str(list_game['path']) self.selected_filename = str(list_game['filename']) self.selected_platform = str(list_game['platform']) # parse drive and system from json data path_array = filter(None, self.selected_path.split('/')) self.drive_system_path_array[0] = path_array[0] self.drive_system_path_array[1] = path_array[1] self.drive_system_path_array[2] = '/'.join(path_array[2:len(path_array)]).replace('//', '') self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1) self.entry_field_title_id.delete(0, END) self.entry_field_title_id.insert(0, self.selected_title_id) self.entry_field_title.delete(0, END) self.entry_field_title.insert(0, self.selected_title) self.entry_field_filename.delete(0, END) self.entry_field_filename.insert(0, self.selected_filename) self.entry_field_platform.delete(0, END) self.entry_field_platform.insert(0, self.selected_platform) return True def get_selected_path(self): return self.current_iso_path def get_listbox(self): return self._listbox def get_ascending_index(self, list_of_items, item, ignore_case=True): lo = 0 hi = len(list_of_items) if ignore_case: item = item.lower() while lo < hi: mid = (lo + hi) // 2 if item < list_of_items[mid].lower(): hi = mid else: lo = mid + 1 else: while lo < hi: mid = (lo + hi) // 2 if item < list_of_items[mid]: hi = mid else: lo = mid + 1 return lo def add_item(self, item): if item != '': self.list_of_items = self._listbox.get(0, END) # getting ascending index in order to sort alphabetically index = self.get_ascending_index(self.list_of_items, item) self._listbox.insert(index, item) else: self._listbox.insert(END, item) def get_items(self): return self.list_of_items def _bound_to_mousewheel(self, event): self._listbox.bind_all("<MouseWheel>", self._on_mousewheel) def _unbound_to_mousewheel(self, event): self._listbox.unbind_all("<MouseWheel>") def _on_mousewheel(self, event): self._listbox.yview_scroll(int(-1*(event.delta/30)), "units") def popup(self, event): try: self._listbox.selection_clear(0, END) self._listbox.selection_set(self._listbox.nearest(event.y)) self._listbox.activate(self._listbox.nearest(event.y)) finally: if self._listbox.get(self._listbox.curselection()[0]) is not '': self.popup_menu.tk_popup(event.x_root + 43, event.y_root + 12, 0) self.popup_menu.grab_release() self.popup_menu.focus_set() def delete_selected(self): import tkMessageBox game_folder_path = os.path.join(AppPaths.game_work_dir, '..') response = tkMessageBox.askyesno('Delete game folder', 'Delete \'' + self.entry_field_title.get() + '\'?\n\nFolder path: ' + os.path.realpath(game_folder_path)) # yes if response: # remove game from visual game list for i in self._listbox.curselection()[::-1]: self._listbox.delete(i) removed_index = i # remove game from json game list platform_key = self.entry_field_platform.get() + '_games' self.json_game_list_data[platform_key] = [x for x in self.json_game_list_data[platform_key] if x['title'] != self.selected_title] # update the json game list file with open(GameListData.GAME_LIST_DATA_PATH, 'w') as newFile: json_text = json.dumps(self.json_game_list_data, indent=4, separators=(",", ":")) newFile.write(json_text) # remove the game build folder too if AppPaths.game_work_dir != os.path.join(AppPaths.wcm_gui, 'work_dir'): if os.path.isdir(game_folder_path): if 'webman-classics-maker' in game_folder_path: shutil.rmtree(game_folder_path) # clear entry_fields self.clear_entries_and_path() # set cursor self._listbox.select_set(removed_index) #This only sets focus on the first item. def rename_selected(self): self.entry_field_title.selection_range(0, END) self.entry_field_title.focus_set() def select_all(self): self._listbox.selection_set(0, 'end') def clear_entries_and_path(self): self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1) self.entry_field_title_id.delete(0, END) self.entry_field_title.delete(0, END) self.entry_field_platform.delete(0, END) self.entry_field_filename.delete(0, END) self.is_cleared = True def get_selected_build_dir_path(self): self.build_dir_path = '' if self.selected_filename not in {'', None}: filename = self.selected_filename title_id = self.selected_title_id.replace('-', '') build_base_path = AppPaths.builds tmp_filename = filename # removes the file extension from tmp_filename for file_ext in GlobalVar.file_extensions: if filename.upper().endswith(file_ext): tmp_filename = filename[0:len(filename)-len(file_ext)] break game_folder_name = tmp_filename.replace(' ', '_') + '_(' + title_id.replace('-', '') + ')' self.build_dir_path = os.path.join(build_base_path, game_folder_name) return self.build_dir_path
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError( "Combobox_Autocomplete subclass has 'autocomplete_function' implemented" ) else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError( "If not guiven complete function, list_of_items can't be 'None'" ) if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [ item for item in self.list_of_items if matches_function(entry_data, item) ] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [ item for item in self.list_of_items if matches_function(escaped_entry_data, item) ] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command=self._listbox.yview) vbar.grid(row=0, column=1, sticky=N + S) self._listbox.configure( yscrollcommand=lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command=self._listbox.xview) hbar.grid(row=1, column=0, sticky=E + W) self._listbox.configure( xscrollcommand=lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight=1) listbox_frame.grid_rowconfigure(0, weight=1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height() - self.cget("borderwidth") - self.cget( "highlightthickness") if self._listbox_width: width = self._listbox_width else: width = self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index += 1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
class InputDevice(object): def __init__(self): # root is the Tkinter root widget self.root = Tk() self.root.title("Input Device Utility") # self.root.configure(background='grey') self.root.resizable(False,False) # define response to main window closing self.root.protocol ("WM_DELETE_WINDOW", self.app_exit) self.my_device ='' self.my_device_display = StringVar() self.device_list=[] self.matches=0 # overall display root_frame=Frame(self.root) root_frame.pack(side=LEFT) devices_frame=Frame(root_frame,padx=5,pady=10) devices_frame.pack(side=LEFT) devices_label = Label(devices_frame, text="Devices in dev/input") devices_label.pack(side=TOP) devices_list_frame=Frame(devices_frame,padx=5,pady=10) devices_list_frame.pack(side=TOP) selected_device_title=Label(devices_frame,text='Selected device') selected_device_title.pack(side=TOP) self.selected_device_var=StringVar() selected_device=Label(devices_frame,textvariable=self.selected_device_var,fg="red") selected_device.pack(side=TOP) events_frame=Frame(root_frame,padx=5,pady=10) events_frame.pack(side=LEFT) events_title=Label(events_frame,text='Received Events') events_title.pack(side=TOP) events_list_frame=Frame(events_frame,padx=5,pady=10) events_list_frame.pack(side=TOP) # list of devices scrollbar = Scrollbar(devices_list_frame, orient=VERTICAL) self.devices_display = Listbox(devices_list_frame, selectmode=SINGLE, height=20, width = 60, bg="white",activestyle=NONE, fg="black", yscrollcommand=scrollbar.set) scrollbar.config(command=self.devices_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.devices_display.pack(side=LEFT, fill=BOTH, expand=1) self.devices_display.bind("<ButtonRelease-1>", self.e_select_device) # events display scrollbar = Scrollbar(events_list_frame, orient=VERTICAL) self.events_display = Text(events_list_frame,width=40,height=20, wrap='word', font="arial 11",padx=5,yscrollcommand=scrollbar.set) scrollbar.config(command=self.events_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.events_display.pack(side=LEFT, fill=BOTH, expand=1) self.events_display.config(state=NORMAL) self.events_display.delete(1.0, END) self.events_display.config(state=DISABLED) self.selected_device_index=-1 self.matches=0 self.get_all_devices() self.refresh_devices_display() self.root.after(10,self.event_loop) # and enter Tkinter event loop self.root.mainloop() # *************************************** # INIT AND EXIT # *************************************** def app_exit(self): self.root.destroy() exit() def event_loop(self): if self.matches>0: self.get_events() self.root.after(10,self.event_loop) def refresh_devices_display(self): self.devices_display.delete(0,self.devices_display.size()) for device in self.all_devices: self.devices_display.insert(END, device[0]+ ' ' +device[1]) if self.selected_device_index >= 0: self.devices_display.itemconfig(self.selected_device_index,fg='red') self.devices_display.see(self.selected_device_index) def e_select_device(self,event): self.selected_device_index=-1 if len(self.all_devices)>0: self.selected_device_index=int(event.widget.curselection()[0]) selected_device=self.all_devices[self.selected_device_index] self.selected_device_name=selected_device[0] self.selected_device_var.set(self.selected_device_name) self.get_matching_devices() self.refresh_devices_display() def get_all_devices(self): self.all_devices=[] devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: self.all_devices.append([device.name,device.fn]) def get_matching_devices(self): self.matches=0 self.matching_devices=[] devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: if self.selected_device_name in device.name: device_ref = evdev.InputDevice(device.fn) self.matching_devices.append(device_ref) self.matches+=1 def get_events(self): r,w,x = select(self.matching_devices, [], [],0) if r == []: return for event in r[0].read(): if event.type == evdev.ecodes.EV_KEY: key_event = evdev.categorize(event) if key_event.keystate == 1: key_text='Down' else: key_text='Up' # print key_event.keycode,key_text if type(key_event.keycode) is list: code_text=', '.join(key_event.keycode) else: code_text=key_event.keycode self.events_display.config(state=NORMAL) self.events_display.insert(END,'\n'+ code_text + ' ' + key_text) self.events_display.config(state=DISABLED) self.events_display.see(END)
class OSCRemote(object): def __init__(self): self.editor_issue = "1.3" # get command options self.command_options = remote_options() # get directory holding the code self.pp_dir = sys.path[0] if not os.path.exists(self.pp_dir + os.sep + "pp_oscremote.py"): tkMessageBox.showwarning("Pi Presents", "Bad Application Directory") exit() # Initialise logging Monitor.log_path = self.pp_dir self.mon = Monitor() self.mon.init() Monitor.classes = ['OSCRemote', 'OSCConfig', 'OSCEditor'] Monitor.log_level = int(self.command_options['debug']) self.mon.log(self, "Pi Presents Remote is starting") self.mon.log(self, " OS and separator " + os.name + ' ' + os.sep) self.mon.log(self, "sys.path[0] - location of code: code " + sys.path[0]) self.setup_gui() # OSC config class self.osc_config = OSCConfig() self.init() #and start the system self.root.after(1000, self.run_app) self.root.mainloop() def init(self): self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscremote.cfg' self.read_create_osc() self.pp_home_dir = self.osc_config.pp_home_dir self.pp_profiles_offset = self.osc_config.pp_profiles_offset self.mon.log(self, "Data Home from options is " + self.pp_home_dir) self.mon.log( self, "Current Profiles Offset from options is " + self.pp_profiles_offset) self.pp_profile_dir = '' self.current_showlist = None self.current_show = None self.current_show_ref = '' self.shows_display.delete(0, END) self.results.set('') def add_status(self, text): self.status_display.insert(END, text + '\n') self.status_display.see(END) def run_app(self): self.client = None self.server = None self.st = None # initialise OSC variables self.prefix = '/pipresents' self.this_unit = '/' + self.osc_config.this_unit_name self.add_status('this unit is: ' + self.this_unit) self.controlled_unit = '/' + self.osc_config.controlled_unit_1_name self.add_status('controlled unit is: ' + self.controlled_unit) #connect client then start server to listen for replies self.init_client() self.add_status('connecting to controlled unit: ' + self.osc_config.controlled_unit_1_ip + ':' + self.osc_config.controlled_unit_1_port + ' ' + self.osc_config.controlled_unit_1_name) self.connect_client(self.osc_config.controlled_unit_1_ip, self.osc_config.controlled_unit_1_port) self.add_status('listening for replies on:' + self.osc_config.this_unit_ip + ':' + self.osc_config.this_unit_port) self.init_server(self.osc_config.this_unit_ip, self.osc_config.this_unit_port, self.client) self.add_initial_handlers() self.start_server() # *************************************** # RESPOND TO BUTTONS # *************************************** def open_show(self): self.msg_path = '/core/open ' self.msg_arg_text = self.current_show_ref self.display_msg_text() def close_show(self): self.msg_path = '/core/close ' self.msg_arg_text = self.current_show_ref self.display_msg_text() def exit_pipresents(self): self.msg_path = '/core/exitpipresents' self.msg_arg_text = '' self.display_msg_text() def play_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-play' self.display_msg_text() def pause_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-pause' self.display_msg_text() pass def stop_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-stop' self.display_msg_text() pass def up_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-up' self.display_msg_text() def down_event(self): self.msg_path = '/core/event' self.msg_arg_text = 'pp-down' self.display_msg_text() def output(self): self.msg_path = '/core/output' self.msg_arg_text = '' self.display_msg_text() def loopback(self): self.msg_path = '/system/loopback' self.msg_arg_text = '' self.display_msg_text() def server_info(self): self.msg_path = '/system/server-info' self.msg_arg_text = '' self.display_msg_text() # and put the created text in the results box in the gui def display_msg_text(self): self.results.set(self.prefix + self.controlled_unit + self.msg_path + ' ' + self.msg_arg_text) #calback from the Send button # parses the message string into fields and sends - NO error checking def send_message(self): msg_text = self.results.get() self.add_status('Send message:' + msg_text) self.mon.log(self, 'send message: ' + msg_text) fields = msg_text.split() address = fields[0] arg_list = fields[1:] self.send(address, arg_list) # *************************************** # OSC CLIENT TO SEND MESSAGES # *************************************** def init_client(self): self.client = OSC.OSCClient() def connect_client(self, ip, port): self.mon.log(self, 'connect to: ' + ip + ':' + str(port)) self.client.connect((ip, int(port))) def send(self, address, arg_list): msg = OSC.OSCMessage() msg.setAddress(address) for arg in arg_list: msg.append(arg) self.client.send(msg) def disconnect_client(self): self.client.close() return # *************************************** # OSC SERVER TO LISTEN TO REPLIES # *************************************** def init_server(self, ip, port_text, client): self.mon.log(self, 'Start Server: ' + ip + ':' + port_text) self.server = OSC.OSCServer((ip, int(port_text)), client) def start_server(self): self.st = threading.Thread(target=self.server.serve_forever) self.st.start() def close_server(self): if self.server != None: self.server.close() self.mon.log(self, 'Waiting for Server-thread to finish') if self.st != None: self.st.join() ##!!! self.mon.log(self, 'server thread closed') def add_initial_handlers(self): self.server.addMsgHandler('default', self.no_match_handler) self.server.addMsgHandler( self.prefix + self.this_unit + "/system/loopback-reply", self.loopback_reply_handler) self.server.addMsgHandler( self.prefix + self.this_unit + "/system/server-info-reply", self.server_info_reply_handler) def no_match_handler(self, addr, tags, stuff, source): text = '' text += "no match for new osc msg from %s" % OSC.getUrlStr( source) + '\n' text += "with addr : %s" % addr + '\n' text += "typetags %s" % tags + '\n' text += "data %s" % stuff + '\n' self.add_status(text + '\n') def loopback_reply_handler(self, addr, tags, stuff, source): self.add_status('Loopback reply received from: ' + self.pretty_list(source)) def server_info_reply_handler(self, addr, tags, stuff, source): self.add_status('Server Information from: ' + self.pretty_list(source) + '\n ' + self.pretty_list(stuff)) def pretty_list(self, fields): text = ' ' for field in fields: text += str(field) + ' ' return text # *************************************** # INIT EXIT MISC # *************************************** def e_edit_osc(self): self.disconnect_client() self.close_server() self.edit_osc() self.init() self.add_status('\n\n\nRESTART') self.run_app() def app_exit(self): self.disconnect_client() self.close_server() if self.root is not None: self.root.destroy() self.mon.finish() sys.exit() def show_help(self): tkMessageBox.showinfo("Help", "Read 'manual.pdf'") def about(self): tkMessageBox.showinfo( "About", "Simple Remote Control for Pi Presents\n" + "Author: Ken Thompson" + "\nWebsite: http://pipresents.wordpress.com/") def setup_gui(self): # set up the gui # root is the Tkinter root widget self.root = Tk() self.root.title("Remote Control for Pi Presents") # self.root.configure(background='grey') self.root.resizable(False, False) # define response to main window closing self.root.protocol("WM_DELETE_WINDOW", self.app_exit) # bind some display fields self.filename = StringVar() self.display_show = StringVar() self.results = StringVar() self.status = StringVar() # define menu menubar = Menu(self.root) profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black") profilemenu.add_command(label='Select', command=self.open_existing_profile) menubar.add_cascade(label='Profile', menu=profilemenu) toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Tools', menu=toolsmenu) osc_configmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='OSC', menu=osc_configmenu) osc_configmenu.add_command(label='Edit', command=self.e_edit_osc) helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black") menubar.add_cascade(label='Help', menu=helpmenu) helpmenu.add_command(label='Help', command=self.show_help) helpmenu.add_command(label='About', command=self.about) self.root.config(menu=menubar) #top frame top_frame = Frame(self.root, padx=5, pady=5) top_frame.pack(side=TOP) results_label = Label(top_frame, text="Message to Send", font="arial 12 bold") results_label.pack(side=LEFT) results_display = Entry(top_frame, textvariable=self.results, width=70) results_display.pack(side=LEFT, fill=BOTH, expand=1) send_button = Button(top_frame, width=5, height=1, text='Send', fg='black', command=self.send_message, bg="light grey") send_button.pack(side=RIGHT) #bottom frame bottom_frame = Frame(self.root, padx=5, pady=5) bottom_frame.pack(side=TOP, fill=BOTH, expand=1) left_frame = Frame(bottom_frame, padx=5) left_frame.pack(side=LEFT) right_frame = Frame(bottom_frame, padx=5, pady=5) right_frame.pack(side=LEFT) suplabel_frame = Frame(right_frame, pady=5) suplabel_frame.pack(side=TOP) commands_label = Label(suplabel_frame, text="Show Control", font="arial 12 bold") commands_label.pack() supervisor_frame = Frame(right_frame, pady=5) supervisor_frame.pack(side=TOP) # supervisor buttons add_button = Button(supervisor_frame, width=5, height=1, text='Open\nShow', fg='black', command=self.open_show, bg="light grey") add_button.pack(side=LEFT) add_button = Button(supervisor_frame, width=5, height=1, text='Close\nShow', fg='black', command=self.close_show, bg="light grey") add_button.pack(side=LEFT) add_button = Button(supervisor_frame, width=10, height=1, text='Exit\nPi Presents', fg='black', command=self.exit_pipresents, bg="light grey") add_button.pack(side=LEFT) # events buttons oplabel_frame = Frame(right_frame, pady=5) oplabel_frame.pack(side=TOP) operations_label = Label(oplabel_frame, text="Input Events", font="arial 12 bold") operations_label.pack() operations_frame = Frame(right_frame, pady=5) operations_frame.pack(side=TOP) add_button = Button(operations_frame, width=5, height=1, text='Play', fg='black', command=self.play_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Pause', fg='black', command=self.pause_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Stop', fg='black', command=self.stop_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Up', fg='black', command=self.up_event, bg="light grey") add_button.pack(side=LEFT) add_button = Button(operations_frame, width=5, height=1, text='Down', fg='black', command=self.down_event, bg="light grey") add_button.pack(side=LEFT) # animate buttons animate_frame = Frame(right_frame, pady=5) animate_frame.pack(side=TOP) animate_label = Label(animate_frame, text="Control Outputs", font="arial 12 bold") animate_label.pack() animate_frame = Frame(right_frame, pady=5) animate_frame.pack(side=TOP) add_button = Button(animate_frame, width=5, height=1, text='Output', fg='black', command=self.output, bg="light grey") add_button.pack(side=LEFT) # system buttons systemlabel_frame = Frame(right_frame, pady=5) systemlabel_frame.pack(side=TOP) system_label = Label(systemlabel_frame, text="System", font="arial 12 bold") system_label.pack() system_frame = Frame(right_frame, pady=5) system_frame.pack(side=TOP) add_button = Button(system_frame, width=5, height=1, text='Loopback', fg='black', command=self.loopback, bg="light grey") add_button.pack(side=LEFT) add_button = Button(system_frame, width=10, height=1, text='Server Info', fg='black', command=self.server_info, bg="light grey") add_button.pack(side=LEFT) # define display of showlist shows_title_frame = Frame(left_frame) shows_title_frame.pack(side=TOP) shows_label = Label(shows_title_frame, text="Shows") shows_label.pack() shows_frame = Frame(left_frame) shows_frame.pack(side=TOP) scrollbar = Scrollbar(shows_frame, orient=VERTICAL) self.shows_display = Listbox(shows_frame, selectmode=SINGLE, height=12, width=40, bg="white", activestyle=NONE, fg="black", yscrollcommand=scrollbar.set) scrollbar.config(command=self.shows_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.shows_display.pack(side=LEFT, fill=BOTH, expand=1) self.shows_display.bind("<ButtonRelease-1>", self.e_select_show) # status_frame status_frame = Frame(self.root, padx=5, pady=5) status_frame.pack(side=TOP, fill=BOTH, expand=1) status_label = Label(status_frame, text="Status", font="arial 12 bold") status_label.pack(side=LEFT) scrollbar = Scrollbar(status_frame, orient=VERTICAL) self.status_display = Text(status_frame, height=10, yscrollcommand=scrollbar.set) scrollbar.config(command=self.status_display.yview) scrollbar.pack(side=RIGHT, fill=Y) self.status_display.pack(side=LEFT, fill=BOTH, expand=1) # *************************************** # SHOWLIST # *************************************** def open_existing_profile(self): initial_dir = self.pp_home_dir + os.sep + "pp_profiles" + self.pp_profiles_offset if os.path.exists(initial_dir) is False: self.mon.err( self, "Profiles directory not found: " + initial_dir + "\n\nHint: Data Home option must end in pp_home") return dir_path = tkFileDialog.askdirectory(initialdir=initial_dir) # dir_path="C:\Users\Ken\pp_home\pp_profiles\\ttt" if len(dir_path) > 0: self.open_profile(dir_path) def open_profile(self, dir_path): showlist_file = dir_path + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err( self, "Not a Profile: " + dir_path + "\n\nHint: Have you opened the profile directory?") return self.pp_profile_dir = dir_path self.root.title("Remote for Pi Presents - " + self.pp_profile_dir) self.open_showlist(self.pp_profile_dir) def open_showlist(self, profile_dir): showlist_file = profile_dir + os.sep + "pp_showlist.json" if os.path.exists(showlist_file) is False: self.mon.err( self, "showlist file not found at " + profile_dir + "\n\nHint: Have you opened the profile directory?") self.app_exit() self.current_showlist = ShowList() self.current_showlist.open_json(showlist_file) if float(self.current_showlist.sissue()) != float(self.editor_issue): self.mon.err( self, "Version of profile does not match Remote: " + self.editor_issue) self.app_exit() self.refresh_shows_display() def refresh_shows_display(self): self.shows_display.delete(0, self.shows_display.size()) for index in range(self.current_showlist.length()): self.shows_display.insert( END, self.current_showlist.show(index)['title'] + " [" + self.current_showlist.show(index)['show-ref'] + "]") if self.current_showlist.show_is_selected(): self.shows_display.itemconfig( self.current_showlist.selected_show_index(), fg='red') self.shows_display.see(self.current_showlist.selected_show_index()) def e_select_show(self, event): print 'select show', self.current_showlist.length() if self.current_showlist is not None and self.current_showlist.length( ) > 0: mouse_item_index = int(event.widget.curselection()[0]) self.current_showlist.select(mouse_item_index) self.current_show_ref = self.current_showlist.selected_show( )['show-ref'] self.refresh_shows_display() else: self.current_show_ref = '' # *************************************** # OSC CONFIGURATION # *************************************** def read_create_osc(self): if self.osc_config.read(self.osc_config_file) is False: self.osc_config.create(self.osc_config_file) eosc = OSCEditor(self.root, self.osc_config_file, 'remote', 'Create OSC Remote Configuration') self.osc_config.read(self.osc_config_file) def edit_osc(self): if self.osc_config.read(self.osc_config_file) is False: self.osc_config.create(self.osc_config_file) eosc = OSCEditor(self.root, self.osc_config_file, 'remote', 'Edit OSC Reomote Configuration')
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented") else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError("If not guiven complete function, list_of_items can't be 'None'") if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) #self.bind("<FocusOut>", lambda event: self.unpost_listbox()) def _on_tab(self, event): #self.post_listbox() self.unpost_listbox() #frmbill.cbouom.focus() #self._update_entry_from_listbox() #self.unpost_listbox() # if self._listbox is not None: # self._listbox.master.destroy() # self._listbox = None return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': #print('test111') self.unpost_listbox() self.focus() else: if len(entry_data) < 3: return True values = finditem(entry_data) #kk #self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) if len(text) > 0: find_price(text) #kk def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index +=1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break" # if __name__ == '__main__': # try: # from Tkinter import Tk # except ImportError: # from tkinter import Tk # list_of_items = ["Cordell Cannata", "Lacey Naples", "Zachery Manigault", "Regan Brunt", "Mario Hilgefort", "Austin Phong", "Moises Saum", "Willy Neill", "Rosendo Sokoloff", "Salley Christenberry", "Toby Schneller", "Angel Buchwald", "Nestor Criger", "Arie Jozwiak", "Nita Montelongo", "Clemencia Okane", "Alison Scaggs", "Von Petrella", "Glennie Gurley", "Jamar Callender", "Titus Wenrich", "Chadwick Liedtke", "Sharlene Yochum", "Leonida Mutchler", "Duane Pickett", "Morton Brackins", "Ervin Trundy", "Antony Orwig", "Audrea Yutzy", "Michal Hepp", "Annelle Hoadley", "Hank Wyman", "Mika Fernandez", "Elisa Legendre", "Sade Nicolson", "Jessie Yi", "Forrest Mooneyhan", "Alvin Widell", "Lizette Ruppe", "Marguerita Pilarski", "Merna Argento", "Jess Daquila", "Breann Bevans", "Melvin Guidry", "Jacelyn Vanleer", "Jerome Riendeau", "Iraida Nyquist", "Micah Glantz", "Dorene Waldrip", "Fidel Garey", "Vertie Deady", "Rosalinda Odegaard", "Chong Hayner", "Candida Palazzolo", "Bennie Faison", "Nova Bunkley", "Francis Buckwalter", "Georgianne Espinal", "Karleen Dockins", "Hertha Lucus", "Ike Alberty", "Deangelo Revelle", "Juli Gallup", "Wendie Eisner", "Khalilah Travers", "Rex Outman", "Anabel King", "Lorelei Tardiff", "Pablo Berkey", "Mariel Tutino", "Leigh Marciano", "Ok Nadeau", "Zachary Antrim", "Chun Matthew", "Golden Keniston", "Anthony Johson", "Rossana Ahlstrom", "Amado Schluter", "Delila Lovelady", "Josef Belle", "Leif Negrete", "Alec Doss", "Darryl Stryker", "Michael Cagley", "Sabina Alejo", "Delana Mewborn", "Aurelio Crouch", "Ashlie Shulman", "Danielle Conlan", "Randal Donnell", "Rheba Anzalone", "Lilian Truax", "Weston Quarterman", "Britt Brunt", "Leonie Corbett", "Monika Gamet", "Ingeborg Bello", "Angelique Zhang", "Santiago Thibeau", "Eliseo Helmuth"] # root = Tk() # root.geometry("300x200") # combobox_autocomplete = Combobox_Autocomplete(root, list_of_items, highlightthickness=1) # combobox_autocomplete.pack() # combobox_autocomplete.focus() # root.mainloop()
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) self.differ = differ.Differ() #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I': lambda: self.information_box.get() == 1, 'C': lambda: self.convention_box.get() == 1, 'R': lambda: self.refactor_box.get() == 1, 'E': lambda: self.error_box.get() == 1, 'W': lambda: self.warning_box.get() == 1, 'F': lambda: self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename + '\n' in self.filenames: index = self.filenames.index(filename + '\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename + '\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME + HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=( module, self.reporter, self, )) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME + HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] scroll = msg.line - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(msg.abspath, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(msg.line - 1) def show_messages_context(self, event): """Show the message listbox's context menu""" # Select the item that was clicked index = self.lbMessages.nearest(event.y) self.lbMessages.selection_clear(0, END) self.lbMessages.selection_set(index) self.lbMessages.activate(index) self.mnMessages.tk_popup(event.x_root, event.y_root) def add_to_ignore_patchfile(self, event=None): """ Add the selected message to the ignore patchfile. This means that this message will now be ignored by pylint-patcher. """ selected = self.lbMessages.curselection() if not selected: return selected_index = int(selected[0]) msg = self.visible_msgs[selected_index] self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol) self.differ.diff() del self.msgs[self.msgs.index(msg)] del self.visible_msgs[selected_index] self.lbMessages.delete(selected_index)
class TextureFrame(Frame): def __init__(self, master): Frame.__init__(self, master) self.master = master self.__list_label = [] self.__list_listbox = [] self.__list_scrollbar = [] self.__list_button = [] self.__texture = [] self.__loadIMG() #Precarga las texturas para despuer ser recortadas def __loadIMG(self): try: if sys.platform.startswith('win32'): ruta = "image\\texture.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/texture.png" self.__texture.append(Image.open(ruta)) except Exception as e: pass #Permite configurar un frame creado def ConfigureF(self, ax=600, ay=52, x=0, y=0, bg="#353535"): self.configure(height=ay, width=ax, background=bg) self.place(x=x, y=y) def addButtonI(self, dim=(0, 0, 206, 109), x=0, y=0, command=0): try: crop = self.__texture[0].crop(dim) render = ImageTk.PhotoImage(crop) nbutton = Button(self, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1") nbutton.image = render nbutton.place(x=x, y=y) self.__list_button.append(nbutton) if command == 1: nbutton.configure(command=self.showOne) elif command == 2: nbutton.configure(command=self.showAll) elif command == 3: pass elif command == 4: nbutton.configure(command=self.master.destroy) return nbutton except Exception as e: self.Error("Error al cargar Texturas") return -1 def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def yview(self, *args): self.listbox1.yview(*args) def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar") def Switch(self, root, Ventana2): root.deiconify() Ventana2.destroy() def load50(self, Poss, mode="a"): maxi = self.buscMax() I = Poss[0] F = Poss[1] if mode == "+": Poss[1] = Poss[1] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) Poss[0] = Poss[1] - 50 if Poss[0] < 0: Poss[0] = 0 elif mode == "-" and Poss[0] != 0: Poss[0] = Poss[0] - 50 if Poss[0] < 0: Poss[0] = 0 Poss[1] = Poss[0] + 50 if Poss[1] > int(maxi): Poss[1] = int(maxi) if mode == "a" or Poss[0] != I or Poss[1] != F: asca = ManagementJson("Helloword.json") lista = asca.intervaloIF(Poss[0], Poss[1]) #cargando texto self.listbox1.delete(0, self.listbox1.size()) for x in range(0, len(lista["serial"])): if lista["status"][x] == "Riesgo Medio": self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) else: self.listbox1.insert( END, lista["serial"][x] + " " + lista["status"][x] + " " + lista["date"][x]) def buscMax(self): f = open("config.txt", "r") f.seek(7) maxi = f.readline() f.close() return maxi def load1(self, listbox3, label1, label2, label3): asca = ManagementJson("Helloword.json") lista = asca.searchError(listbox3.get()) try: if lista == 0: label1.configure(text="No se encontro") label2.configure(text="No se encontro") label3.configure(text="No se encontro") return 0 except Exception as e: raise e label1.configure(text=lista[0]) label2.configure(text=lista[1]) label3.configure(text=lista[2])