Esempio n. 1
0
class ScrolledList(object):
    # TODO add columns to the Scrolled list:
    #   http://stackoverflow.com/questions/5286093/display-listbox-with-columns-using-tkinter

    def __init__(self, parent_frame):
        self._vsbar = Scrollbar(parent_frame)
        self._hsbar = Scrollbar(parent_frame, orient='horizontal')
        self._list = Listbox(parent_frame, relief=SUNKEN, font=('courier', 12))

        self._vsbar.config(command=self._list.yview, relief=SUNKEN)
        self._hsbar.config(command=self._list.xview, relief=SUNKEN)
        self._list.config(yscrollcommand=self._vsbar.set, relief=SUNKEN)
        self._list.config(xscrollcommand=self._hsbar.set)

        self._vsbar.pack(side=RIGHT, fill=Y)
        self._hsbar.pack(side=BOTTOM, fill=X)
        self._list.pack(side=LEFT, expand=YES, fill=BOTH)
        #self._list.bind('<Double-1>', self.handlelist)

        self._list_pos = 0

    def clear(self):
        self._list.delete(0, END)
        self._list_pos = 0

    def append_list_entry(self, entry_str, fg=None):
        pos = self._list_pos
        self._list_pos += 1
        self._list.insert(END, entry_str)
        if fg:
            self._list.itemconfig(pos, fg=fg)
        return pos

    def highlight_entry(self, entry_index, bg):
        self._list.itemconfig(index=entry_index, bg=bg)
Esempio n. 2
0
class LintGui:
    """Build and control a window to interact with pylint"""
    
    def __init__(self, root=None):
        self.root = root or Tk()
        self.root.title('Pylint')
        top_frame = Frame(self.root)
        res_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)
        
        Label(top_frame, text='Module or package').pack(side=LEFT)
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)
        Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT)

        scrl = Scrollbar(res_frame)
        self.results = Listbox(res_frame,
                               background='white',
                               font='fixedsys',
                               selectmode='browse',
                               yscrollcommand=scrl.set)
        scrl.configure(command=self.results.yview)
        self.results.pack(side=LEFT, expand=True, fill=BOTH)
        scrl.pack(side=RIGHT, fill=Y)
        
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)
        #self.root.bind('<ctrl-q>', self.quit)
        self.txtModule.focus_set()
        
    def mainloop(self):
        """lauch the mainloop of the application"""
        self.root.mainloop()

    def quit(self, _=None):
        """quit the application"""
        self.root.quit()

    def run_lint(self, _=None):
        """lauches pylint"""
        colors = {'W:':'red1', 'E:': 'red4',
                  'W:': 'red3', '**': 'navy'}
        
        self.root.configure(cursor='watch')
        self.results.focus_set()
        self.results.delete(0, END)
        self.results.update()
        module = self.txtModule.get()
        pout = os.popen('%s %s' % (PYLINT, module), 'r')
        for line in  pout.xreadlines():
            line = line.rstrip()
            self.results.insert(END, line)
            fg_color = colors.get(line[:2], 'black')
            self.results.itemconfigure(END, fg=fg_color)
            self.results.update()
        self.root.configure(cursor='')
class LintGui:
    """Build and control a window to interact with pylint"""
    
    def __init__(self, root=None):
        self.root = root or Tk()
        self.root.title('Pylint')
        top_frame = Frame(self.root)
        res_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)
        
        Label(top_frame, text='Module or package').pack(side=LEFT)
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)
        Button(top_frame, text='Run', command=self.run_lint).pack(side=LEFT)

        scrl = Scrollbar(res_frame)
        self.results = Listbox(res_frame,
                               background='white',
                               font='fixedsys',
                               selectmode='browse',
                               yscrollcommand=scrl.set)
        scrl.configure(command=self.results.yview)
        self.results.pack(side=LEFT, expand=True, fill=BOTH)
        scrl.pack(side=RIGHT, fill=Y)
        
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)
        #self.root.bind('<ctrl-q>', self.quit)
        self.txtModule.focus_set()
        
    def mainloop(self):
        """launch the mainloop of the application"""
        self.root.mainloop()

    def quit(self, _=None):
        """quit the application"""
        self.root.quit()

    def run_lint(self, _=None):
        """launches pylint"""
        colors = {'W:':'red1', 'E:': 'red4',
                  'W:': 'red3', '**': 'navy'}
        
        self.root.configure(cursor='watch')
        self.results.focus_set()
        self.results.delete(0, END)
        self.results.update()
        module = self.txtModule.get()
        pout = os.popen('%s %s' % (PYLINT, module), 'r')
        for line in  pout.xreadlines():
            line = line.rstrip()
            self.results.insert(END, line)
            fg_color = colors.get(line[:2], 'black')
            self.results.itemconfigure(END, fg=fg_color)
            self.results.update()
        self.root.configure(cursor='')
class Window(object):
    def __init__(self, master):

        self.master = master
        self.master.wm_title('PEP8 checker')
        self.master.resizable(False, True)

        self.frame = Frame(master)
        self.frame.pack(fill=BOTH, expand=1)

        home_dir = expanduser("~")
        self.directory = StringVar(value=home_dir)

        directory_frame = Frame(self.frame)
        directory_frame.grid()
        self.frame.grid_rowconfigure(2, weight=1)

        self.entry_directory = Entry(directory_frame, textvariable=self.directory)
        self.entry_directory.pack(anchor=W, side=LEFT)

        self.select_directory = Button(directory_frame, text="Select directory to scan", command=self.select_directory)
        self.select_directory.pack(anchor=E, side=RIGHT)

        self.run_button = Button(self.frame, text='Run PEP8!', command=self.run_pep)
        self.run_button.grid(sticky=W + E)

        self.errors_list = Listbox(self.frame)
        self.errors_list.grid(sticky=W + E)

        self.status_label = Label(self.frame)

    def select_directory(self):
        directory = askdirectory(initialdir=self.directory.get())
        if directory:
            self.directory.set(directory)

    def run_pep(self):
        self.errors_list.delete(0, END)
        process = Popen('$(which pep8) {}'.format(self.directory.get()), shell=True, stderr=PIPE, stdout=PIPE)
        output = process.communicate()[0]
        selected_dir = ''.join((self.directory.get(), '/'))
        if output:
            self.errors_list.configure(background='red')
            for i, error in enumerate(output.split('\n')):
                self.errors_list.insert(i, error.replace(selected_dir, ''))
        else:
            self.errors_list.configure(background='green')
            self.errors_list.insert(0, 'Directory is OK!')
Esempio n. 5
0
class ScrolledList(Frame):
    def __init__(self, master,a_function):
        Frame.__init__(self,master)
        
        scrl_bar = Scrollbar(self)
        self.listbox = Listbox(self)
        
        scrl_bar.config(command=self.listbox.yview)                   
        scrl_bar.pack(side=RIGHT, fill=Y)                     
        
        self.listbox.config(yscrollcommand=scrl_bar.set)              
        self.listbox.pack(side=LEFT, expand=YES, fill=BOTH)       
        

        # link double click to the processList
        self.listbox.bind('<Double-1>', self.processList)  
        # attach a function passed form the master
        # not this si done as passd function so it could be anything       
        self.passed_function = a_function
        
    # get the index of the double clicked itenm and pass the item to
    # the passed function    
    def processList(self, event):
        index = self.listbox.curselection()               
        label = self.listbox.get(index)  
        self.passed_function((index,label))
        
    def load_data(self,d_list):
        #load the listbox
        idx = 0
        for item in d_list:      
            fparts = item.split('.')
            # DEBUG print fparts
            if fparts[-1] == 'csv':
                # only display thoes files that have not been processed
                if not(item.startswith("done-")):
                    self.listbox.insert(idx, item)                       
                    idx += 1
        
    def remove_item(self,idx):
        self.listbox.delete(idx)
Esempio n. 6
0
class ScrolledList(Frame):
    def __init__(self, master, a_function):
        Frame.__init__(self, master)

        scrl_bar = Scrollbar(self)
        self.listbox = Listbox(self)

        scrl_bar.config(command=self.listbox.yview)
        scrl_bar.pack(side=RIGHT, fill=Y)

        self.listbox.config(yscrollcommand=scrl_bar.set)
        self.listbox.pack(side=LEFT, expand=YES, fill=BOTH)

        # link double click to the processList
        self.listbox.bind('<Double-1>', self.processList)
        # attach a function passed form the master
        # not this si done as passd function so it could be anything
        self.passed_function = a_function

    # get the index of the double clicked itenm and pass the item to
    # the passed function
    def processList(self, event):
        index = self.listbox.curselection()
        label = self.listbox.get(index)
        self.passed_function((index, label))

    def load_data(self, d_list):
        #load the listbox
        idx = 0
        for item in d_list:
            fparts = item.split('.')
            # DEBUG print fparts
            if fparts[-1] == 'csv':
                # only display thoes files that have not been processed
                if not (item.startswith("done-")):
                    self.listbox.insert(idx, item)
                    idx += 1

    def remove_item(self, idx):
        self.listbox.delete(idx)
Esempio n. 7
0
class GUIListbox:
    def __init__(self, parent, items=None, **kwargs):
        self.listbox = Listbox(parent, **kwargs)

        if items:
            self.setItems(items)

    def setItems(self, items):
        self.listbox.delete(0, END)
        for item in items:
            self.listbox.insert(END, item)

    def getSelected(self):
        return self.listbox.get(ACTIVE)

    def bindDoubleClick(self, func):
        self.listbox.bind("<Double-Button-1>", func)

    def grid(self, **kwargs):
        self.listbox.grid(kwargs)

    def pack(self, **kwargs):
        self.listbox.pack(kwargs)
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))
Esempio n. 9
0
class App(tk.Frame):
    def __init__(self, master, *args, **kw):
        super().__init__(master, *args, **kw)
        self.root = master
        self.master.title('Rebuild List')
        # Width, Height of application
        self.master.geometry("575x600")
        self.store = Combobox_Autocomplete
        self.alldicts = {}
        self.create_widgets()
        self.create_widgets1()

    def create_widgets(self, *args):
        # Image
        self.imgtitle = ImageTk.PhotoImage(Image.open('snapsrebuild.png'))
        self.lab = tk.Label(image=self.imgtitle)
        self.lab.grid(row=0, column=0, columnspan=6, padx=20, pady=20)
        # Supplies Label
        self.consume_label = tk.Label(self.root, text='Supplies:', font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=0, columnspan=2, padx=50)
        # AutoCompleteBox
        self.entry_0 = tk.StringVar()
        self.combobox_autocomplete = Combobox_Autocomplete(self.root, list_of_items, textvariable=self.entry_0,
                                                           width=32, highlightthickness=1)
        self.combobox_autocomplete.grid(row=2, column=0, sticky="W", padx=20, pady=10)
        # Insert Button
        self.insert_butt = tk.Button(self.root, text='Insert', command=lambda: self.commando())
        self.insert_butt.place(x=220, y=155)
        # List Box
        self.list_box = Listbox(self.root, border=1, width=40, height=20, justify='center')
        self.list_box.grid(row=3, rowspan=5, column=0, padx=20)
        # Delete Button
        self.del_button = tk.Button(self.root, text='Delete', command=lambda: self.delbutton())
        self.del_button.place(x=175, y=520)
        # Check Button
        self.check_button = tk.Button(self.root, text='Check', command=lambda: self.checkbutton())
        self.check_button.place(x=50, y=520)
        # Uncheck Button
        self.uncheck_button = tk.Button(self.root, text='Uncheck', command=lambda: self.uncheckbutton())
        self.uncheck_button.place(x=105, y=520)

        self.list_box.insert(END, "Dragon Claws")
        self.list_box.insert(END, "Super Combat Potions")
    def delbutton(self):
        self.list_box.delete(ACTIVE)

    def checkbutton(self):
        self.list_box.itemconfig(ACTIVE, {'bg': 'green'})

    def uncheckbutton(self):
        self.list_box.itemconfig(ACTIVE, {'bg': '#ffffff'})


    # def commando(self):
    #     x = 'Consumables'
    #     self.alldicts.update({x: (self.entry_0.get())})
    #     self.list_box.insert(END, self.entry_0.get())
    #     for (key, value) in self.alldicts.items():
    #         print(key, "::", value)
    #     return ()

    #######################################################################################################################

    def create_widgets1(self):
        # Gear Label
        self.consume_label1 = tk.Label(self.root, text='Gear', font=('Arial', 12, 'bold'))
        self.consume_label1.grid(row=1, column=2, padx=50)
        self.entry_1 = tk.StringVar()
        self.combobox_autocomplete1 = Combobox_Autocomplete(self.root, list_of_items, textvariable=self.entry_1,
                                                            width=32,
                                                            highlightthickness=1)
        self.combobox_autocomplete1.grid(row=2, column=2, padx=20, pady=10, sticky="W")
        # Insert Button
        self.insert_butt1 = tk.Button(self.root, text='Insert', command=lambda: self.commando1())
        self.insert_butt1.place(x=505, y=155)
        # List Box
        self.list_box1 = Listbox(self.root, border=1, width=40, height=20)
        self.list_box1.grid(row=3, rowspan=5, column=2, padx=20)
        # Delete Button
        self.del_button1 = tk.Button(self.root, text='Delete', command=lambda: self.delbutton1())
        self.del_button1.place(x=502, y=520)
        # Check Button
        self.check_button1 = tk.Button(self.root, text='Check', command=lambda: self.checkbutton1())
        self.check_button1.place(x=305, y=520)
        # Uncheck Button
        self.uncheck_button1 = tk.Button(self.root, text='Uncheck', command=lambda: self.uncheckbutton1())
        self.uncheck_button1.place(x=400, y=520)


        self.headers = [" ITEM", "                                            PRICE"]
        self.row_format = "{:<8}  {:>8}"
        self.list_box1.insert(0, self.row_format.format(*self.headers, sp="       " * 6))
        self.list_box1.insert(1, '-----------------------------------------------------------')

    def delbutton1(self):
        self.list_box1.delete(ACTIVE)

    def checkbutton1(self):
        self.list_box1.itemconfig(ACTIVE, {'bg': 'green'})

    def uncheckbutton1(self):
        self.list_box1.itemconfig(ACTIVE, {'bg': '#ffffff'})




    def commando1(self):
        x = 'Gear'
        self.alldicts.update({x: (self.entry_1.get())})
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        for item in names:
            if item in self.entry_1.get():
                indexNumber = names.index(self.entry_1.get())
                print(indexNumber)
                self.priceIndex = prices[indexNumber]
                self.ent = self.entry_1.get()
                self.headers1 = [self.ent,'                            ', f"{self.priceIndex:,d}"]
                self.row_format1 = "{:<8}  {:>8} {:>8}"
                self.list_box1.insert(END, self.row_format1.format(*self.headers1))
        return ()
Esempio n. 10
0
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """

    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title("Shift Reduce Parser Application")

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10)  # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1["text"] = ""

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkFont.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 = tkFont.Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = tkFont.Font(family="helvetica", size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill="both", side="left", padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont, text="Available Reductions")
        self._prodlist_label.pack()
        self._prodlist = Listbox(
            self._prodframe,
            selectmode="single",
            relief="groove",
            background="white",
            foreground="#909090",
            font=self._font,
            selectforeground="#004040",
            selectbackground="#c0f0c0",
        )

        self._prodlist.pack(side="right", fill="both", expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert("end", (" %s" % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:  # len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient="vertical")
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side="left", fill="y")

        # If they select a production, apply it.
        self._prodlist.bind("<<ListboxSelect>>", self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind("<Motion>", self._highlight_hover)
        self._prodlist.bind("<Leave>", self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind("<Control-q>", self.destroy)
        self._top.bind("<Control-x>", self.destroy)
        self._top.bind("<Alt-q>", self.destroy)
        self._top.bind("<Alt-x>", self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind("<space>", self.step)
        self._top.bind("<s>", self.shift)
        self._top.bind("<Alt-s>", self.shift)
        self._top.bind("<Control-s>", self.shift)
        self._top.bind("<r>", self.reduce)
        self._top.bind("<Alt-r>", self.reduce)
        self._top.bind("<Control-r>", self.reduce)
        self._top.bind("<Delete>", self.reset)
        self._top.bind("<u>", self.undo)
        self._top.bind("<Alt-u>", self.undo)
        self._top.bind("<Control-u>", self.undo)
        self._top.bind("<Control-z>", self.undo)
        self._top.bind("<BackSpace>", self.undo)

        # Misc
        self._top.bind("<Control-p>", self.postscript)
        self._top.bind("<Control-h>", self.help)
        self._top.bind("<F1>", self.help)
        self._top.bind("<Control-g>", self.edit_grammar)
        self._top.bind("<Control-t>", self.edit_sentence)

        # Animation speed control
        self._top.bind("-", lambda e, a=self._animate: a.set(20))
        self._top.bind("=", lambda e, a=self._animate: a.set(10))
        self._top.bind("+", lambda e, a=self._animate: a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill="none", side="bottom")
        Button(buttonframe, text="Step", background="#90c0d0", foreground="black", command=self.step).pack(side="left")
        Button(
            buttonframe, text="Shift", underline=0, background="#90f090", foreground="black", command=self.shift
        ).pack(side="left")
        Button(
            buttonframe, text="Reduce", underline=0, background="#90f090", foreground="black", command=self.reduce
        ).pack(side="left")
        Button(buttonframe, text="Undo", underline=0, background="#f0a0a0", foreground="black", command=self.undo).pack(
            side="left"
        )

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Reset Parser", underline=0, command=self.reset, accelerator="Del")
        filemenu.add_command(label="Print to Postscript", underline=0, command=self.postscript, accelerator="Ctrl-p")
        filemenu.add_command(label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-x")
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Edit Grammar", underline=5, command=self.edit_grammar, accelerator="Ctrl-g")
        editmenu.add_command(label="Edit Text", underline=5, command=self.edit_sentence, accelerator="Ctrl-t")
        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label="Step", underline=1, command=self.step, accelerator="Space")
        rulemenu.add_separator()
        rulemenu.add_command(label="Shift", underline=0, command=self.shift, accelerator="Ctrl-s")
        rulemenu.add_command(label="Reduce", underline=0, command=self.reduce, accelerator="Ctrl-r")
        rulemenu.add_separator()
        rulemenu.add_command(label="Undo", underline=0, command=self.undo, accelerator="Ctrl-u")
        menubar.add_cascade(label="Apply", underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(
            label="Show Grammar", underline=0, variable=self._show_grammar, command=self._toggle_grammar
        )
        viewmenu.add_separator()
        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)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0, variable=self._animate, value=0)
        animatemenu.add_radiobutton(
            label="Slow Animation", underline=0, variable=self._animate, value=20, accelerator="-"
        )
        animatemenu.add_radiobutton(
            label="Normal Animation", underline=0, variable=self._animate, value=10, accelerator="="
        )
        animatemenu.add_radiobutton(
            label="Fast Animation", underline=0, variable=self._animate, value=4, accelerator="+"
        )
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", underline=0, command=self.about)
        helpmenu.add_command(label="Instructions", underline=0, command=self.help, accelerator="F1")
        menubar.add_cascade(label="Help", underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill="x", side="bottom", padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text="Last Operation:", font=self._font)
        self._lastoper_label.pack(side="left")
        lastoperframe = Frame(feedbackframe, relief="sunken", border=1)
        lastoperframe.pack(fill="x", side="right", expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground="#007070", background="#f0f0f0", font=self._font)
        self._lastoper2 = Label(
            lastoperframe, anchor="w", width=30, foreground="#004040", background="#f0f0f0", font=self._font
        )
        self._lastoper1.pack(side="left")
        self._lastoper2.pack(side="left", fill="x", expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background="white", width=525, closeenough=10, border=2, relief="sunken")
        self._cframe.pack(expand=1, fill="both", side="top", pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(0, 0, 0, 0, fill="#c0f0f0", outline="black")
        self._exprline = canvas.create_line(0, 0, 0, 0, dash=".")
        self._stacktop = canvas.create_line(0, 0, 0, 0, fill="#408080")
        size = self._size.get() + 4
        self._stacklabel = TextWidget(canvas, "Stack", color="#004040", font=self._boldfont)
        self._rtextlabel = TextWidget(canvas, "Remaining Text", color="#004040", font=self._boldfont)
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas["scrollregion"].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2 - y1 + 10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4)
        self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5 - x1, 3 - y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2 - x2 - 5, 3 - y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {
                    "tree_color": "#4080a0",
                    "tree_width": 2,
                    "node_font": self._boldfont,
                    "node_color": "#006060",
                    "leaf_color": "#006060",
                    "leaf_font": self._font,
                }
                widget = tree_to_treesegment(self._canvas, tok, **attribs)
                widget.node()["color"] = "#000000"
            else:
                widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas, tok, color="#000000", font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width() + 25)
        rlabelwidth = self._rtextlabel.width() + 10
        if stackx >= cx2 - max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4 + cx2 - rtextwidth, 0)
        self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0)

        midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:

            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx:
                    self.shift()
                else:
                    self._redraw()

            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2] + 50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, "end")
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        if self._top is None:
            return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1["text"] = "Reset App"
        self._lastoper2["text"] = ""
        self._redraw()

    def step(self, *e):
        if self.reduce():
            return 1
        elif self.shift():
            return 1
        else:
            if len(self._parser.parses()) > 0:
                self._lastoper1["text"] = "Finished:"
                self._lastoper2["text"] = "Success"
            else:
                self._lastoper1["text"] = "Finished:"
                self._lastoper2["text"] = "Failure"

    def shift(self, *e):
        if self._animating_lock:
            return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1["text"] = "Shift:"
            self._lastoper2["text"] = "%r" % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return 1
        return 0

    def reduce(self, *e):
        if self._animating_lock:
            return
        production = self._parser.reduce()
        if production:
            self._lastoper1["text"] = "Reduce:"
            self._lastoper2["text"] = "%s" % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock:
            return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        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)

    #########################################
    ##  Menubar callbacks
    #########################################

    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._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        # self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        # self._lastoper_label['font'] = ('helvetica', -size)
        # self._lastoper1['font'] = ('helvetica', -size)
        # self._lastoper2['font'] = ('helvetica', -size)
        # self._prodlist['font'] = ('helvetica', -size)
        # self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, "Help: Shift-Reduce Parser Application", (__doc__).strip(), width=75, font="fixed")
        except:
            ShowText(self._top, "Help: Shift-Reduce Parser Application", (__doc__).strip(), width=75)

    def about(self, *e):
        ABOUT = "NLTK Shift-Reduce Parser Application\n" + "Written by Edward Loper"
        TITLE = "About: Shift-Reduce Parser Application"
        try:
            from tkMessageBox import Message

            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, "end")
        for production in self._productions:
            self._prodlist.insert("end", (" %s" % production))

    def edit_sentence(self, *e):
        sentence = string.join(self._sent)
        title = "Edit Text"
        instr = "Enter a new sentence to parse."
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split()  # [XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill="both", side="left", padx=2, after=self._feedbackframe)
            self._lastoper1["text"] = "Show Grammar"
        else:
            self._prodframe.pack_forget()
            self._lastoper1["text"] = "Hide Grammar"
        self._lastoper2["text"] = ""

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1:
            return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1["text"] = "Reduce:"
            self._lastoper2["text"] = "%s" % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, "end")
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0:
            return

        self._reduce_menu.delete(0, "end")
        for production in productions:
            self._reduce_menu.add_command(label=str(production), command=self.reduce)
        self._reduce_menu.post(self._canvas.winfo_pointerx(), self._canvas.winfo_pointery())

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0:
            left = 5
        else:
            left = self._stackwidgets[-1].bbox()[2] + 10

        # Start animating.
        dt = self._animate.get()
        dx = (left - right) * 1.0 / dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame, frame - 1, widget, dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1])  # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].node().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist * 2.0 / dt
        self._animate_reduce_frame(dt / 2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame, frame - 1, widgets, dy)
        else:
            del self._stackwidgets[-len(widgets) :]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree):
                raise ValueError()
            label = TextWidget(self._canvas, str(tok.node), color="#006060", font=self._boldfont)
            widget = TreeSegmentWidget(self._canvas, label, widgets, width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2 - y1 + 10
            if not self._stackwidgets:
                x = 5
            else:
                x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

            #             # Delete the old widgets..
            #             del self._stackwidgets[-len(widgets):]
            #             for widget in widgets:
            #                 self._cframe.destroy_widget(widget)
            #
            #             # Make a new one.
            #             tok = self._parser.stack()[-1]
            #             if isinstance(tok, Tree):
            #                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
            #                            'node_font': bold, 'node_color': '#006060',
            #                            'leaf_color': '#006060', 'leaf_font':self._font}
            #                 widget = tree_to_treesegment(self._canvas, tok.type(),
            #                                              **attribs)
            #                 widget.node()['color'] = '#000000'
            #             else:
            #                 widget = TextWidget(self._canvas, tok.type(),
            #                                     color='#000000', font=self._font)
            #             widget.bind_click(self._popup_reduce)
            #             (x1, y1, x2, y2) = self._stacklabel.bbox()
            #             y = y2-y1+10
            #             if not self._stackwidgets: x = 5
            #             else: x = self._stackwidgets[-1].bbox()[2] + 10
            #             self._cframe.add_widget(widget, x, y)
            #             self._stackwidgets.append(widget)

            # self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index:
            return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.node()["color"] = "#00a000"
                else:
                    stackwidget["color"] = "#00a000"

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1:
            return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.node()["color"] = "black"
            else:
                stackwidget["color"] = "black"
Esempio n. 11
0
class App(object):
    def __init__(self):

        self.w_window = Tk()

        self.w_listbox_tracks = Listbox(self.w_window)
        self.w_label_base_path = Label(
            self.w_window,
            highlightbackground='red',
            highlightthickness=1,
        )
        self.w_btn_next = Button(
            self.w_window,
            text=u'Следующая',
            command=self.btn_next,
        )
        self.w_btn_pause = Button(
            self.w_window,
            text=u'Пауза/Играть',
            command=self.btn_pause,
        )
        self.w_btn_stop = Button(
            self.w_window,
            text=u'Стоп',
            command=self.btn_stop,
        )
        self.w_btn_plus = Button(
            self.w_window,
            text=u'+',
            command=self.btn_plus,
        )
        self.w_btn_minus = Button(
            self.w_window,
            text=u'-',
            command=self.btn_minus,
        )
        self.buttons = (
            self.w_btn_next,
            self.w_btn_pause,
            self.w_btn_stop,
            self.w_btn_plus,
            self.w_btn_minus,
        )

        self.music_path = ''
        self.musics = getattr(settings, 'musics', {})

        self.musics_map = {}

        self.media_instance = vlc.get_default_instance()
        self.player = self.media_instance.media_player_new()

        self.media = self.media_instance.media_new(u'')
        self.mediaManager = self.media.event_manager()

        self.mark5 = self.mark4 = self.mark3 = self.mark2 = 0
        self.current_play_path = u''

        # для исключения ошибки, get_position не всегда равен 1
        self._last_pos = 2

        self.worked = False

    def _nur_configure(self):
        self.w_window.protocol('WM_DELETE_WINDOW', self.end)
        self.w_label_base_path.bind('<Double-Button-1>', self.set_new_path)
        self.w_listbox_tracks.bind('<Double-Button-1>', self.select_music)

        self.w_window.minsize(width=settings.MAIN_WINDOW_MIN_WIDTH,
                              height=settings.MAIN_WINDOW_MIN_HEIGHT)
        self.w_window.geometry(u'{0}x{1}+{2}+{3}'.format(
            settings.MAIN_WINDOW_WIDTH, settings.MAIN_WINDOW_HEIGHT,
            settings.MAIN_WINDOW_X, settings.MAIN_WINDOW_Y))

    def _nur_layout(self):
        rel_label_height = 0.1
        rel_btns_height = 0.1
        rel_btns_width = 1.0 / len(self.buttons)
        rel_btns_y = 1 - rel_btns_height
        rel_listbox_heigth = 1 - rel_label_height - rel_btns_height

        self.w_label_base_path.place(
            relx=0,
            rely=0,
            relwidth=1,
            relheight=rel_label_height,
        )
        self.w_listbox_tracks.place(
            relx=0,
            rely=rel_label_height,
            relwidth=1,
            relheight=rel_listbox_heigth,
        )
        x = 0
        for btn in self.buttons:

            btn.place(
                relx=x,
                rely=rel_btns_y,
                relwidth=rel_btns_width,
                relheight=rel_btns_height,
            )
            x += rel_btns_width

    def start(self):
        self._nur_configure()
        self._nur_layout()
        self.set_new_path()
        self.w_window.mainloop()

    def end(self):
        self.write_settings()
        self.w_window.destroy()

    def write_settings(self):
        with open(settings.CONFIG_FILE_PATH, 'w') as f:
            json.dump(
                {
                    'MUSIC_PATH': self.music_path,
                    'musics': self.musics,
                    'VOLUME': self.player.audio_get_volume()
                },
                f,
                indent=4)

    def set_new_path(self, event=None):
        if event:
            self.music_path = askdirectory(
                title=u'Выберите папку с музыкой',
                initialdir=self.music_path) or self.music_path
        else:
            self.music_path = settings.MUSIC_PATH

        self.w_label_base_path['text'] = self.music_path
        self._load_musics()

    def _get_musics(self):
        _musics = {}
        for root, dirs, files in os.walk(self.music_path):
            for fil in files:
                if fil.endswith('.mp3'):
                    file_path = os.path.join(root, fil)
                    _musics[file_path] = {
                        'file_name':
                        fil,
                        'album': (file_path.replace(self.music_path,
                                                    '').replace(fil, '')),
                    }
        return _musics

    def _load_musics(self):
        for mus_path, meta in self._get_musics().iteritems():
            if mus_path not in self.musics:
                self.musics[mus_path] = meta
                meta['last_positions'] = [1.0]

        self.__load_musics()

    def __load_musics(self):
        self.musics_map = [(mus_path, u'{album}{file_name}'.format(**mus_meta))
                           for mus_path, mus_meta in self.musics.iteritems()]
        self.musics_map.sort(key=lambda x: x[1])

        self.musics_map = [(item[0], u'{0} - {2} - {1}'.format(
            index, item[1], (sum(self.musics[item[0]]['last_positions']) /
                             len(self.musics[item[0]]['last_positions']))))
                           for index, item in enumerate(self.musics_map)]
        self.w_listbox_tracks.delete(0, END)

        self.w_listbox_tracks.insert(
            END, *(title for mus_path, title in self.musics_map))

    def select_music(self, event=None):
        self.calculate_mark()
        try:
            index = self.w_listbox_tracks.curselection()[0]
            self.current_play_path, music_title = self.musics_map[index]
        except IndexError:
            return
        else:
            self.player.stop()

            self.media = self.media_instance.media_new(self.current_play_path)
            self.mediaManager = self.media.event_manager()

            self.player.set_media(self.media)
            self.player.play()
            self.player.audio_set_volume(settings.VOLUME)
            if not self.worked:
                self.worked = True
                self.w_window.after(3000, self.after)
            # self.player.set_position(0.9)

    def btn_pause(self):
        self.player.pause()
        self.worked = not self.worked
        print self.worked
        if self.worked:
            self.w_window.after(3000, self.after)

    def btn_stop(self):
        self.player.stop()
        self.worked = False

    def btn_plus(self):
        volume = self.player.audio_get_volume()
        if volume < 100:
            self.player.audio_set_volume(volume + 10)

    def btn_minus(self):
        volume = self.player.audio_get_volume()
        if volume > 0:
            self.player.audio_set_volume(volume - 10)

    def btn_next(self):
        if not self.musics:
            return

        self.calculate_mark()

        if self.mark5 < 10:
            mark = 0.8
            self.mark5 += 1
        elif self.mark4 < 8:
            mark = 0.6
            self.mark4 += 1
        elif self.mark3 < 6:
            mark = 0.4
            self.mark3 += 1
        elif self.mark2 < 4:
            mark = 0.2
            self.mark2 += 1
        else:
            mark = 0
            self.mark5 = self.mark4 = self.mark3 = self.mark2 = 0
            self.write_settings()
            self.__load_musics()

        music_path = random.choice([
            path for path, meta in self.musics.iteritems()
            if sum(meta['last_positions']) / len(meta['last_positions']) > mark
        ])
        for index, music in enumerate(self.musics_map):
            if music[0] == music_path:
                break
        self.w_listbox_tracks.selection_clear(0, END)
        self.w_listbox_tracks.activate(index)
        self.w_listbox_tracks.selection_set(index)
        self.w_listbox_tracks.see(index)
        self.select_music()

    def calculate_mark(self):
        try:
            self.musics[self.current_play_path]['last_positions'].append(
                self.player.get_position())
        except KeyError:
            pass
        else:
            self.musics[self.current_play_path]['last_positions'] = (
                self.musics[self.current_play_path]['last_positions'][-10:])

    def after(self):
        pos = self.player.get_position()
        if pos in (1.0, self._last_pos):
            self.btn_next()

        self._last_pos = pos
        if self.worked:
            self.w_window.after(3000, self.after)
Esempio n. 12
0
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)
Esempio n. 13
0
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
Esempio n. 14
0
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)
Esempio n. 15
0
File: booru.py Progetto: Reyuu/abd
class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.current_image = posts[0]
        self.posts = posts
        self.initUI()
        self.current_booru = None

    def initUI(self):
        self.parent.title("Booru")
        self.pack(fill=Y, expand=0, side=LEFT)
        myicon = ImageTk.PhotoImage(file="sbooru.ico")
        self.current_booru_var = StringVar()
        self.mb = Menubutton(self,
                             textvariable=self.current_booru_var,
                             relief=RAISED,
                             image=myicon,
                             compound=LEFT)
        self.mb.image = myicon
        self.mb.pack(side=TOP)
        self.mb.menu = Menu(self.mb, tearoff=0)
        self.mb["menu"] = self.mb.menu
        self.current_booru_var.set("Safebooru")

        def change_booru(booru):
            self.current_booru = booru
            if self.current_booru == 0:
                self.current_booru_var.set("Danbooru")
            if self.current_booru == 1:
                self.current_booru_var.set("Safebooru")

        self.mb.menu.add_command(label="Danbooru",
                                 command=lambda: change_booru(0))
        self.mb.menu.add_command(label="Safebooru",
                                 command=lambda: change_booru(1))

        self.mb.pack()

        image = Image.open(
            get_image_from_internet_binary(
                u"%s%s" % (main_url, self.posts[0][u"preview_file_url"])))
        photo = ImageTk.PhotoImage(image)
        self.label = Label(self, image=photo)
        self.label.image = photo
        self.label.pack(fill=Y, expand=0, side=TOP)

        self.lb = Listbox(self)
        for i in self.posts:
            self.lb.insert(END, i["id"])
        self.lb.bind("<<ListboxSelect>>", self.onSelect)
        self.lb.pack(pady=15, fill=Y, expand=0, side=LEFT)

        self.description = Labelframe(self,
                                      text="Description",
                                      height=350,
                                      width=350)
        self.description.pack(pady=15, expand=0)
        #artist
        self.artist_v = StringVar()
        self.artist = Label(self.description,
                            textvariable=self.artist_v,
                            justify=LEFT,
                            wraplength=350,
                            anchor=W)
        self.artist.pack()
        #md5
        self.md5_v = StringVar()
        self.md5 = Label(self.description,
                         textvariable=self.md5_v,
                         justify=LEFT,
                         wraplength=350,
                         anchor=W)
        self.md5.pack()
        #source
        self.source_v = StringVar()
        self.source = Label(self.description,
                            textvariable=self.source_v,
                            justify=LEFT,
                            wraplength=350,
                            anchor=W)
        self.source.pack()
        #wxh
        self.wxh_v = StringVar()
        self.wxh = Label(self.description,
                         textvariable=self.wxh_v,
                         justify=LEFT,
                         wraplength=350,
                         anchor=W)
        self.wxh.pack()
        #tags (for now all)
        self.tags_v = StringVar()
        self.tags = Label(self.description,
                          textvariable=self.tags_v,
                          justify=LEFT,
                          wraplength=350,
                          anchor=W)
        self.tags.pack()
        #uploader
        self.uploader_v = StringVar()
        self.uploader = Label(self.description,
                              textvariable=self.uploader_v,
                              justify=LEFT,
                              wraplength=350,
                              anchor=W)
        self.uploader.pack()
        idx = (0, 0)
        try:
            self.artist_v.set(u"Artist:\t%s" %
                              self.posts[idx[0]][u"tag_string_artist"])
        except KeyError:
            self.artist_v.set(u"Artist:\t")
        try:
            self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"])
        except KeyError:
            self.md5_v.set(u"MD5:\t")
        try:
            self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"])
        except KeyError:
            self.source_v.set(u"Source:\t")
        try:
            self.wxh_v.set(u"Size:\t%sx%s" %
                           (self.posts[idx[0]][u"image_width"],
                            self.posts[idx[0]][u"image_height"]))
        except KeyError:
            self.wxh_v.set(u"Size:\t")
        try:
            self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"])
        except KeyError:
            self.tags_v.set(u"Tags:\t")
        try:
            self.uploader_v.set(u"Uploader:\t%s" %
                                self.posts[idx[0]][u"uploader_name"])
        except KeyError:
            self.uploader_v.set(u"Uploader:\t")

        self.button_frame = Frame(self.description)
        self.button_frame.pack(fill=Y, expand=0, side=LEFT)

        def download_image_current():
            def download():
                urllib.urlretrieve(
                    "%s%s" % (main_url, self.current_image[u"file_url"]),
                    "%s_%s.%s" %
                    (self.current_image[u"id"], self.current_image[u"md5"],
                     self.current_image[u"file_ext"]))

            t1 = Thread(target=download, args=())
            t1.start()

        self.download_button = Button(self.button_frame,
                                      text="Download",
                                      command=download_image_current)
        self.download_button.pack(side=LEFT)

        def bigger_preview():
            image = Image.open(
                get_image_from_internet_binary(
                    u"%s%s" % (main_url, self.current_image[u"file_url"])))
            photo = ImageTk.PhotoImage(image)
            self.bigpreview = Toplevel(self)
            labelu = Label(self.bigpreview, image=photo)
            labelu.image = photo
            labelu.pack(fill=Y, expand=0, side=LEFT)

        self.preview_button = Button(self.button_frame,
                                     text="Preview",
                                     command=bigger_preview)
        self.preview_button.pack(side=RIGHT)

        def onRefresh():
            def method():
                query_args["page"] = self.current_page.get()
                self.posts = get_posts("posts.json", query_args)
                self.lb.delete(0, END)
                for i in self.posts:
                    self.lb.insert(END, i["id"])

            t1 = Thread(target=method, args=())
            t1.start()

        self.refresh = Button(self.button_frame,
                              text="Refresh posts",
                              command=onRefresh)
        self.refresh.pack(side=LEFT)

        page_control = Frame(self)
        page_control.pack(pady=15, side=BOTTOM)
        self.current_page = IntVar()
        self.current_page.set(1)

        def forward_f():
            self.current_page.set(self.current_page.get() + 1)
            onRefresh()

        forward = Button(page_control, text=">>", command=forward_f)
        forward.pack(side=RIGHT)

        def backward_f():
            self.current_page.set((self.current_page.get() - 1) if (
                self.current_page.get() - 1 > 0) else self.current_page.get())
            onRefresh()

        backward = Button(page_control, text="<<", command=backward_f)
        backward.pack(side=LEFT)
        curpaglabl = Label(page_control,
                           textvariable=self.current_page,
                           background="orange")
        curpaglabl.pack(pady=15, side=BOTTOM)

    def onSelectFileBrowser(self, val):
        sender = val.widget
        idx = sender.curselection()

        def get_image_and_cover_it(self):
            with open(sender.get(idx), "r") as fre:
                image = Image.open(fre.read())
                photo = ImageTk.PhotoImage(image)
                self.label.configure(image=photo)
                self.label.image = photo

        t1 = Thread(target=get_image_and_cover_it, args=(self, ))
        t1.start()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        self.current_image = self.posts[idx[0]]
        try:
            self.artist_v.set(u"Artist:\t%s" %
                              self.posts[idx[0]][u"tag_string_artist"])
        except KeyError:
            self.artist_v.set(u"Artist:\t")
        try:
            self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"])
        except KeyError:
            self.md5_v.set(u"MD5:\t")
        try:
            self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"])
        except KeyError:
            self.source_v.set(u"Source:\t")
        try:
            self.wxh_v.set(u"Size:\t%sx%s" %
                           (self.posts[idx[0]][u"image_width"],
                            self.posts[idx[0]][u"image_height"]))
        except KeyError:
            self.wxh_v.set(u"Size:\t")
        try:
            self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"])
        except KeyError:
            self.tags_v.set(u"Tags:\t")
        try:
            self.uploader_v.set(u"Uploader:\t%s" %
                                self.posts[idx[0]][u"uploader_name"])
        except KeyError:
            self.uploader_v.set(u"Uploader:\t")

        def get_image_and_cover_it(self):
            image = Image.open(
                get_image_from_internet_binary(
                    u"%s%s" %
                    (main_url, self.posts[idx[0]][u"preview_file_url"])))
            photo = ImageTk.PhotoImage(image)
            self.label.configure(image=photo)
            self.label.image = photo

        t1 = Thread(target=get_image_and_cover_it, args=(self, ))
        t1.start()
Esempio n. 16
0
class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Optistruct to Abaqus")
        #minusImage = PhotoImage(file="minus_svg.gif")
        #plusImage = ImageTk.PhotoImage(Image.open('plus_svg.png'))
        #minusImage = ImageTk.PhotoImage(Image.open('minus_svg.gif'))
        #plusImage=PhotoImage(file="plus.gif")
        #minusImage=PhotoImage(file="minus.gif")

        self.fileList = []

        self.label = Label(master, text="Optistruct to Abaqus Conversion")
        self.label.pack()

        self.listbox = Listbox(master, width=100)
        self.listbox.pack(side=LEFT)

        self.plus_button = Button(master,
                                  text='+',
                                  width="1",
                                  height="1",
                                  command=self.addFile)
        self.plus_button.grid(row=0, column=0)
        self.plus_button.pack(side=RIGHT)

        self.minus_button = Button(master,
                                   text='-',
                                   width="1",
                                   height="1",
                                   command=self.removeFile)
        self.minus_button.grid(row=1, column=0)
        self.minus_button.pack(side=RIGHT)

        self.convert_button = Button(master,
                                     text="Convert",
                                     command=self.convertFiles)
        self.convert_button.grid(row=1, column=0)
        self.convert_button.pack()

        self.clear_button = Button(master, text="Clear", command=self.clear)
        self.clear_button.grid(row=2, column=0)
        self.clear_button.pack(side=BOTTOM)

        self.close_button = Button(master, text="Close", command=master.quit)
        self.close_button.grid(row=2, column=1)
        self.close_button.pack(side=BOTTOM)

    def removeFile(self):
        self.listbox.delete(self.listbox.curselection()[0])
        self.fileList.pop(self.listbox.curselection()[0])

    def clear(self):
        self.fileList = []
        self.listbox.delete(0, END)

    def convertFiles(self):
        for mesh in self.fileList:
            print 'Processing {}'.format(mesh)
            currMesh = Mesh.fromOptistruct(mesh)
            currMesh.toAbaqus()
            print 'Finished converting {}'.format(mesh)

    def addFile(self):
        files = tkFileDialog.askopenfilenames(initialdir="/",
                                              title="Select file",
                                              filetypes=(("Optistruct Mesh",
                                                          "*.fem"),
                                                         ("All Files", "*.*")))
        if files != None:
            for file in files:
                if not file in self.fileList:
                    self.fileList.append(file)
                    self.listbox.insert(END, file)
Esempio n. 17
0
class Troop:
    @classmethod
    def init_troop(cls, name, nation):
        strength = random.randint(1, 3)
        health = random.randint(1, 3)
        ranged = random.choice([False, True]) #Starting troops are always melee random.choice([False, True])

        speed = random.randint(2, 4)

        discipline = random.randint(1, 2)

        rank_size = random.randint(4, 15)
        ranks = random.randint(4, 6)

        elite = random.randint(2, 6)

        if ranged:
            weapons = [random.choice(nation.basic_ranged_weapon_list), random.choice(nation.sidearm_list)]
        else:
            weapons = [random.choice(nation.basic_weapon_list), random.choice(nation.basic_weapon_list)]

        #weapons = [random.choice(nation.ranged_weapon_list), random.choice(nation.sidearm_list)]

        armor = random.choice(nation.basic_armor_list)

        mount = nation.mount_none

        if random.randint(0, 100) < elite + 5:
            mount = random.choice(nation.basic_mount_list)


        tier = 1

        # print "Unknown nation has created a new unit: " + str(name) + ", armed with: " + str(weapons[0].name) +", " + str(weapons[1].name) + ", "+str(armor.name)+", "+str(mount.name)+" elite: "+str(elite)

        return cls(name, strength, health, 0, ranged, speed, discipline, rank_size, ranks, weapons, armor, elite, tier, [], mount, troop_nation=nation)

    def __init__(self, name, strength, health, number, ranged, speed, discipline, rank_size, ranks, weapons, armor, elite, tier, upgrades, mount,
                 stats_history=None, arms_history=None, troop_nation=None):
        if arms_history is None:
            arms_history = []
        if stats_history is None:
            stats_history = []
        self.name = name
        self.strength = strength
        self.health = health
        self.number = number

        self.speed = speed

        self.originally_ranged = ranged #This one won't change when the unit swiches to melee mode.
        self.ranged = ranged

        self.discipline = discipline

        self.rank_size = rank_size
        self.ranks = ranks

        self.weapons = weapons
        self.armor = armor
        self.mount = mount

        self.upgrades = upgrades

        self.elite = elite

        self.tier = tier

        self.nation = troop_nation

        if not arms_history:
            self.arms_history = [(self.weapons, self.armor)]
        else:
            self.arms_history = arms_history

        if not stats_history:
            self.stats_history = [utility.base_soldier_stats()]
        else:
            self.stats_history = stats_history

        self.quality = 0

        if self.nation is not None:
            self.nation.troop_tree.append(self)

        self.experience = 1

    #Creates another troop to add to the troop tree
    @classmethod
    def new_troop(cls, self, nation):
        name = nation.language.make_word(nation.language.name_length, True)

        ranged = random.choice([False, True])

        strength = self.strength + random.randint(1, 10 if not ranged else 5)
        health = self.health + random.randint(1, 4 if not ranged else 2)
        discipline = self.discipline + random.randint(0, 1)

        speed = self.speed + random.randint(1, 2)

        rank_size = random.randint(3, 15)
        ranks = random.randint(3, 5)

        if ranged:
            weapons = [random.choice(nation.ranged_weapon_list), random.choice(nation.sidearm_list)]
        else:
            weapons = [random.choice(nation.weapon_list), random.choice(nation.sidearm_list)]

        armor = random.choice(nation.armor_list)

        mount = nation.mount_none

        elite = random.randint(2, 6)

        if random.randint(0, 100) < (elite * 2) + 5:
            mount = random.choice(nation.mount_list)

        # print str(nation.name) + " created a new unit: " + str(name) + ", armed with: " + str(weapons[0].name) +", " + str(weapons[1].name) + ", "+str(armor.name)+", "+str(mount.name)
        #e.append(events.EventTroopCreated('TroopCreated', {'nation_a': nation.name, 'army_a': name, 'equip_a':weapons, 'armor_a':armor}, s_parent.get_current_date()))

        return cls(name, strength, health, 0, ranged, speed, discipline, rank_size, ranks, weapons, armor, elite, self.tier + 1, [], mount, troop_nation=nation)

    def get_info(self):
        res = {}
        res['name'] = self.name
        res['strength'] = self.strength
        res['health'] = self.health
        res['number'] = self.number
        res['speed'] = self.speed
        res['ranged'] = self.ranged
        res['discipline'] = self.discipline
        res['rank_size'] = self.rank_size
        res['ranks'] = self.ranks
        res['weapons'] = map(lambda eqp: eqp.get_info(), self.weapons)
        res['armor'] = self.armor.get_info()
        res['elite'] = self.elite
        res['tier'] = self.tier
        res['mount'] = self.mount

        res['upgrades'] = []
        for upgrade in self.upgrades:
            res['upgrades'].append(upgrade.get_info())

        res['arms_history'] = []
        for weapons, armor in self.arms_history:
            res['arms_history'].append((map(lambda eqp: eqp.get_info(), weapons), armor.get_info()))

        res['stats_history'] = self.stats_history

        return res

    # TODO: Make these actually do something
    def train(self, amount):
        return 0
        #self.elite += random.randint(0, amount)
        #print self.elite

    def upgrade_gear(self):
        return 0
        # if self.quality > 6:
        #     return

        # self.quality += 1

        # #print "upgrading " + str(self.weapons[0].attack)

        # self.weapons[0].upgrade(1)
        # self.weapons[0].upgrade_skill(1)

        # #Sprint "upgrading to" + str(self.weapons[0].attack)

        # self.weapons[1].upgrade(1)
        # self.weapons[1].upgrade_skill(1)

        # self.armor.upgrade(1)
        # self.armor.upgrade_skill(1)

    def save(self, path):
        with open(path + 'army_structure.txt', 'w') as f:
            f.write(str(self.get_info()))

    def handle_battle_end(self, stats):
        self.stats_history[-1] = utility.zip_dict_with(lambda a,b: a + b, self.stats_history[-1], stats)

    def do_rearm(self, nation):
        if self.tier == 1:
            if self.ranged:
                weapons = [random.choice(nation.basic_ranged_weapon_list), random.choice(nation.sidearm_list)]
            else:
                weapons = [random.choice(nation.basic_weapon_list), random.choice(nation.basic_weapon_list)]

            armor = random.choice(nation.basic_armor_list)

            mount = nation.mount_none

            if random.randint(0, 100) < self.elite + 5:
                mount = random.choice(nation.basic_mount_list)
        else:
            if self.ranged:
                weapons = [random.choice(nation.ranged_weapon_list), random.choice(nation.sidearm_list)]
            else:
                weapons = [random.choice(nation.weapon_list), random.choice(nation.sidearm_list)]

            armor = random.choice(nation.armor_list)

            mount = nation.mount_none

            if random.randint(0, 100) < (self.elite * 2) + 5:
                mount = random.choice(nation.mount_list)

        self.weapons = weapons
        self.armor = armor
        self.mount = mount

        self.arms_history.append((self.weapons, self.armor, self.mount))
        self.stats_history.append(utility.base_soldier_stats())

        return self

    def rearm(self, name, new_weapons, new_armor, new_mount):
        if self.name == name:
            self.weapons = new_weapons
            self.armor = new_armor
            self.mount = new_mount
        else:
            for upgrade in self.upgrades:
                upgrade.rearm(name, new_weapons, new_armor, new_mount)

    def show_information_gui(self):
        self.gui_window = Tk()
        self.gui_window.title(self.name)
        self.gui_window.geometry("400x625+0+0")
        self.gui_window.config(background='white')

        self.ranged_label = gui.Label(self.gui_window, text='Is ranged: {}'.format(self.ranged))
        self.ranged_label.grid(row=0, sticky=W)

        self.mount_label = gui.Label(self.gui_window, text='Mount: {}'.format(self.mount.name))
        self.mount_label.grid(row=1, sticky=W)

        self.strength_label = gui.Label(self.gui_window, text='Strength: {}'.format(self.strength))
        self.strength_label.grid(row=2, sticky=W)

        self.health_label = gui.Label(self.gui_window, text='Health: {}'.format(self.health))
        self.health_label.grid(row=3, sticky=W)

        self.discipline_label = gui.Label(self.gui_window, text='Discipline: {}'.format(self.discipline))
        self.discipline_label.grid(row=4, sticky=W)


        self.discipline_label = gui.Label(self.gui_window, text='Cost: {}'.format(self.get_soldier_cost()))
        self.discipline_label.grid(row=5, sticky=W)

        self.arrangement = gui.Label(self.gui_window, text='Arrangement: {}x{}'.format(self.rank_size, self.ranks))
        self.arrangement.grid(row=6, sticky=W)

        self.arrangement_canvas = Canvas(self.gui_window, width = (self.rank_size + 1) * (TROOP_RADIUS + 1), height= (self.ranks + 1) * (TROOP_RADIUS + 1))
        self.arrangement_canvas.config(background='white')
        self.arrangement_canvas.grid(row=7, sticky=W)

        for x in xrange(1, self.rank_size + 1):
            for y in xrange(1, self.ranks + 1):
                base_x, base_y = x * (TROOP_RADIUS + 1), y * (TROOP_RADIUS + 1)
                self.arrangement_canvas.create_oval(base_x, base_y, base_x + TROOP_RADIUS, base_y + TROOP_RADIUS)

        self.upgrade_label = gui.Label(self.gui_window, text='Upgrades:')
        self.upgrade_label.grid(row=8, sticky=W)

        self.upgrade_buttons = []
        for (i, upgrade) in enumerate(self.upgrades):
            new_upgrade_button = gui.Button(self.gui_window, text=upgrade.name, command=upgrade.show_information_gui)
            new_upgrade_button.grid(row=9, column=i, sticky=W)

            self.upgrade_buttons.append(new_upgrade_button)

        self.history_choice = StringVar()
        self.history_choice.set(self.stringify_history(0))

        self.stats_label = gui.Label(self.gui_window, text='Stats:')
        self.stats_label.grid(row=10, column=0, sticky=W)

        self.stats_choice = OptionMenu(self.gui_window, self.history_choice, *map(self.stringify_history, range(len(self.arms_history))))
        self.stats_choice.config(background='white')
        self.stats_choice['menu'].config(background='white')
        self.stats_choice.grid(row=10, column=1, sticky=W)

        self.stats_select = gui.Button(self.gui_window, text='Select', command=self.select_history)
        self.stats_select.grid(row=10, column=2, sticky=W)

        self.stats_display = Listbox(self.gui_window)
        self.stats_display.grid(row=11, column=0, columnspan=3, sticky=W+E)

        self.select_history()

    def get_soldier_cost(self):
        amount = 0
        for weapon in self.weapons:
            amount += weapon.cost

        amount += self.armor.cost
        amount += self.mount.cost

        return amount

    def stringify_history(self, i):
        weapon_str = ', '.join(map(lambda i: i.name, self.arms_history[i][0]))
        armor_str = self.arms_history[i][1].name
        mount_str = self.mount.name
        return '{}: ({}, {}), {}'.format(i, weapon_str, armor_str, mount_str)

    def select_history(self):
        history_index = int(self.history_choice.get().split(':')[0])

        self.stats_display.delete(0, END)
        for stat in self.stats_history[history_index]:
            self.stats_display.insert(END, '{}: {}'.format(utility.displayify_text(stat), self.stats_history[history_index][stat]))

    def add_number(self, number, nation):
        self.number += number
        #e.append(events.EventArmyRaised('ArmyRaised', {'nation_a': nation.name, 'army_a': self.name, 'raised_a':number}, s_parent.get_current_date()))

        if self.number > self.elite** math.sqrt(self.tier): #If we have enough troops, we will create another, better, rank of troops
            if len(self.upgrades) < 3:
                self.upgrades.append(Troop.new_troop(self, nation))

                self.upgrades[-1].upgrades = [] #Because it wants to put itself as an upgrade, for some reason. TODO

        if self.number < 0:
            self.number = 0

        #Upgrade troops if possible.
        if self.number > (self.elite * self.tier) and len(self.upgrades) > 0:
            upgrading = random.randint(1, self.number // self.elite)
            self.number -= upgrading

            per_upgrade = upgrading // len(self.upgrades)
            for upgrade in self.upgrades:
                total_cost = nation.get_soldier_cost(upgrade)

                if nation.money > total_cost:
                    upgrade.add_number(per_upgrade, nation)
                    #print str(nation.name) + " raised an army of " + str(number) + " " + str(self.name)
                else:
                    self.number += per_upgrade #Add these people back, because they weren't actually upgraded.

        nation.update_tree(self)

        return self

    def reset(self):
        return self.zero().reset_stats()

    def reset_stats(self):
        self.stats_history = [utility.base_soldier_stats()]

        return self

    def zero(self):
        return self.copy().remove_number('', self.size())

    def add_army(self, other):
        self.add_to(other.name, other.number)

        for i in other.upgrades:
            self.add_army(i)

    def add_to(self, type, number):
        if self.name == type:
            self.number += number

            return self
        else:
            for upgrade in self.upgrades:
                if upgrade.name == type:
                    upgrade.number += number

                    return self

            for upgrade in self.upgrades:
                val = upgrade.add_to(type, number)

                if val is not None:
                    return self

            return None

    #Returns a list of the unit + it's upgrades
    def make_upgrade_list(self):
        return sorted([self] + reduce(lambda a, b: a + b, [i.make_upgrade_list() for i in self.upgrades], []), key=lambda a: a.strength * a.health)

    def copy(self):
        return Troop(self.name, self.strength, self.health, 0, self.ranged, self.speed, self.discipline, self.rank_size, self.ranks, [i.copy() for i in self.weapons], self.armor.copy(), self.elite, self.tier, map(lambda i: i.copy(), self.upgrades), self.mount, stats_history=map(dict, self.stats_history), arms_history=list(self.arms_history))

    def is_empty(self):
        return all(map(lambda i: i.is_empty(), self.upgrades)) and self.number == 0

    def trim_empty(self):
        i = 0
        while i < len(self.upgrades):
            if self.upgrades[i].is_empty():
                self.upgrades.pop(i)
            else:
                self.upgrades[i] = self.upgrades[i].trim_empty()

                i += 1

        return self

    def take_number(self, number):
        upgrade_list = self.make_upgrade_list()

        result = self.copy()

        for upgrade in upgrade_list:
            upgraded_amount = 0

            if upgrade.number > number:
                upgrade.number -= number
                upgraded_amount = number

                number = 0
            else:
                upgraded_amount = upgrade.number
                number -= upgrade.number

                upgrade.number = 0

            result.add_to(upgrade.name, upgraded_amount)

            if number == 0:
                break

        return result.trim_empty()

    def remove_number(self, type, number):
        if type == '':
            upgrade_list = self.make_upgrade_list()

            for upgrade in upgrade_list:
                if upgrade.number > number:
                    upgrade.number -= number

                    number = 0

                    return self
                else:
                    number -= upgrade.number

                    upgrade.number = 0

            return self
        else:
            if type == self.name:
                self.number -= number

                return self.number

            for i in self.upgrades:
                if i.name == type:
                    i.number -= number

                    return i.number

            #If not found in any of them, let's check all the children
            for i in self.upgrades:
                val = i.remove_number(type, number)

                if val >= 0:
                    return val

            return -1

    def size(self):
        return self.number + sum(map(lambda t: t.size(), self.upgrades))

    def merge_all(self, other):
        if self.name == other.name:
            self.number += other.number

            for index, upgrade in enumerate(other.upgrades):
                if not upgrade in self.upgrades:
                    self.upgrades.append(upgrade.copy())

                    self.upgrades[-1] = self.upgrades[-1].merge_all(upgrade)
                else:
                    self_upgrade = self.upgrades.index(upgrade)

                    self.upgrades[self_upgrade] = self.upgrades[self_upgrade].merge_all(upgrade)

            return self

    def merge_structure(self, other):
        result = self.zero()

        if result.name == other.name:
            for index, upgrade in enumerate(other.upgrades):
                if not upgrade in result.upgrades:
                    result.upgrades.append(upgrade.zero())

                    result.upgrades[-1] = result.upgrades[-1].merge_structure(upgrade)
                else:
                    self_upgrade = self.upgrades.index(upgrade)

                    result.upgrades[self_upgrade] = result.upgrades[self_upgrade].merge_structure(upgrade)

        return result

    def __eq__(self, other):
        try:
            return self.name == other.name
        except:
            return False

    def __repr__(self):
        return "{0}({1}, {2}): {3} {4}".format(self.name, self.strength, self.health, self.number, self.upgrades)
Esempio n. 18
0
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                
Esempio n. 19
0
class ListPane(Frame):
    """A ListPane is a widget for holding a list of words, incorporating a scrollbar"""
    
    def __init__(self, parent, height=35, width=40):
        Frame.__init__(self, parent)
        
        #Create a scrollbar so that list can be of arbitrary length
        scrollbar = Scrollbar(self)
        #Create a listbox to hold/display the word list
        self.listbox  = Listbox(self, height = height, width = width, 
        yscrollcommand = scrollbar.set)
        scrollbar.config(command = self.listbox.yview)
        self.listbox.pack(side=LEFT, fill = BOTH)
        scrollbar.pack(side=RIGHT, fill = Y)
        
        #Allow the widget to react to single or double clicks
        self.listbox.bind("<Double-Button-1>", self.doubleclicked)
        self.listbox.bind("<Button-1>", self.singleclicked)

    def remove(self, itemindex):
        """Removes the word at the given index of the list"""
        self.listbox.delete(itemindex, itemindex)

    def get(self, index=None):
        """Get the currently selected word"""
        try:
            if index!=None:
                return self.listbox.get(index)
            else: return self.get(self.listbox.curselection())
        except TclError:
            return None

    def getDisplayed(self):
        """Get a list of all words currently contained in the ListPane"""
        return self.listbox.get(0,END)

    def insert(self, item):
        """Insert a word into the list"""
        self.listbox.insert(END, item) 

    def display(self, itemlist):
        """Pass a list to this method and the contents will be displayed in the ListPane"""
        self.listbox.delete(0, END)
        for item in itemlist:
            self.listbox.insert(END, item)

    def doubleclicked(self, event):
        """Called when widget is double-clicked. Template method that calls doubleClickFunc"""
        try:
            itemindex = self.listbox.curselection()
            self.doubleClickFunc(itemindex)
        except TclError:
            pass
    
    def doubleClickFunc(self, itemindex):
        """This method should be replaced on specific instances of ListPane. 
           Defines the behaviour of widget when double-clicked"""
        pass
    
    def singleclicked(self, event):
        """Called when widget is single-clicked. Template method that calls singleClickFunc"""
        self.singleClickFunc(self.listbox.index("@%d,%d" % (event.x, event.y)))

    def singleClickFunc(self, itemindex):
        """This method should be replaced on specific instances of ListPane
           Defines the behaviour of widget when single-clicked"""
        pass
Esempio n. 20
0
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()
Esempio n. 21
0
class Automation(Frame):
    """The Automation class is a GUI that provides radio automation."""
    _state = None
    _button_text = None
    _button = None

    _meter = None
    _cart_queue = None

    _list_time = None
    _list_track = None
    _list_artist = None

    def __init__(self):
        """Construct an Automation window."""
        Frame.__init__(self)

        # initialize title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=3)

        # initialize button and state
        self._state = STATE_STOPPED

        self._button_text = StringVar()

        self._button = Button(self.master, textvariable=self._button_text, command=self._update_state, width=16, height=2)
        self._button.config(bd=2)
        self._button.grid(row=0, column=3)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=4)

        # initialize playlist view
        playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=16, text=TEXT_PLAYLIST_TIME).grid(row=0, column=0)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1)
        Label(playlist, font=FONT, anchor=Tkinter.CENTER, width=32, text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2)

        inner_playlist = Frame(playlist)
        scroll = Scrollbar(inner_playlist, orient=Tkinter.VERTICAL, command=self._scroll_playlist)
        self._list_time = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=16, height=20)
        self._list_track = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20)
        self._list_artist = Listbox(inner_playlist, selectmode=Tkinter.SINGLE, yscrollcommand=scroll.set, exportselection=0, width=32, height=20)

        scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
        self._list_time.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)
        self._list_track.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)
        self._list_artist.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True, padx=2, pady=2)

        inner_playlist.grid(row=1, column=0, columnspan=3)
        playlist.grid(row=4, column=0, columnspan=4)

        # initialize cart queue
        self._cart_queue = CartQueue(self._cart_start, self._cart_stop)
        self._cart_queue.add_tracks()
        self._update_ui()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()

    def _scroll_playlist(self, *args):
        """Scroll the playlist view.

        :param args
        """
        self._list_time.yview(*args)
        self._list_track.yview(*args)
        self._list_artist.yview(*args)

    def _update_state(self):
        """Move Automation to the next state.

        The state machine is as follows:
        STATE_STOPPED -> STATE_PLAYING -> STATE_STOPPING -> STATE_STOPPED
        """
        if self._state is STATE_STOPPED:
            print "Starting Automation..."
            self._cart_queue.start()
            self._state = STATE_PLAYING
        elif self._state is STATE_PLAYING:
            print "Stopping Automation after this track..."
            self._cart_queue.stop_soft()
            self._state = STATE_STOPPING
        elif self._state is STATE_STOPPING:
            print "Stopping Automation immediately."
            self._cart_queue.transition()
            self._state = STATE_STOPPED
        self._update_ui()

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()
        self._update_ui()

    def _cart_stop(self):
        """Reset the meter when a cart stops.

        Also, if a soft stop occured, update the button state.
        """
        self._meter.reset()

        if self._state is STATE_STOPPING:
            self._state = STATE_STOPPED
            self._update_ui()

    def _update_ui(self):
        """Update the button and playlist."""
        self._button_text.set(TEXT_BUTTON[self._state])
        self._button.config(bg=COLOR_BUTTON[self._state], highlightbackground=COLOR_BUTTON[self._state])

        self._list_time.delete(0, Tkinter.END)
        self._list_track.delete(0, Tkinter.END)
        self._list_artist.delete(0, Tkinter.END)

        for cart in self._cart_queue.get_queue():
            self._list_time.insert(Tkinter.END, cart.start_time.strftime("%I:%M:%S %p"))
            self._list_track.insert(Tkinter.END, cart.title)
            self._list_artist.insert(Tkinter.END, cart.issuer)

    def _get_meter_data(self):
        """Get meter data for the first track in the queue."""
        queue = self._cart_queue.get_queue()

        if len(queue) > 0:
            return queue[0].get_meter_data()
        else:
            return None
Esempio n. 22
0
class RecursiveDescentApp(object):
    """
    A graphical tool for exploring the recursive descent parser.  The tool
    displays the parser's tree and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can expand subtrees on the frontier, match tokens on the frontier
    against the text, and backtrack.  A "step" button simply steps
    through the parsing process, performing the operations that
    ``RecursiveDescentParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingRecursiveDescentParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Recursive Descent Parser Application')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.
        self._init_fonts(self._top)

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animation_frames = IntVar(self._top)
        self._animation_frames.set(5)
        self._animating_lock = 0
        self._autostep = 0

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # Initialize the parser.
        self._parser.initialize(self._sent)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkFont.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 = tkFont.Font(family='helvetica',
                                     weight='bold',
                                     size=self._size.get())
        self._font = tkFont.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 = tkFont.Font(family='helvetica',
                                    weight='bold',
                                    size=big)

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe,
                                     font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe,
                                 selectmode='single',
                                 relief='groove',
                                 background='white',
                                 foreground='#909090',
                                 font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient='vertical')
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_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('e', self.expand)
        #self._top.bind('<Alt-e>', self.expand)
        #self._top.bind('<Control-e>', self.expand)
        self._top.bind('m', self.match)
        self._top.bind('<Alt-m>', self.match)
        self._top.bind('<Control-m>', self.match)
        self._top.bind('b', self.backtrack)
        self._top.bind('<Alt-b>', self.backtrack)
        self._top.bind('<Control-b>', self.backtrack)
        self._top.bind('<Control-z>', self.backtrack)
        self._top.bind('<BackSpace>', self.backtrack)
        self._top.bind('a', self.autostep)
        #self._top.bind('<Control-a>', self.autostep)
        self._top.bind('<Control-space>', self.autostep)
        self._top.bind('<Control-c>', self.cancel_autostep)
        self._top.bind('<space>', self.step)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<Control-p>', self.postscript)
        #self._top.bind('<h>', self.help)
        #self._top.bind('<Alt-h>', self.help)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        #self._top.bind('<g>', self.toggle_grammar)
        #self._top.bind('<Alt-g>', self.toggle_grammar)
        #self._top.bind('<Control-g>', self.toggle_grammar)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

    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='Step',
            background='#90c0d0',
            foreground='black',
            command=self.step,
        ).pack(side='left')
        Button(
            buttonframe,
            text='Autostep',
            background='#90c0d0',
            foreground='black',
            command=self.autostep,
        ).pack(side='left')
        Button(buttonframe,
               text='Expand',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.expand).pack(side='left')
        Button(buttonframe,
               text='Match',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.match).pack(side='left')
        Button(buttonframe,
               text='Backtrack',
               underline=0,
               background='#f0a0a0',
               foreground='black',
               command=self.backtrack).pack(side='left')
        # Replace autostep...
#         self._autostep_button = Button(buttonframe, text='Autostep',
#                                        underline=0, command=self.autostep)
#         self._autostep_button.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_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe,
                                     text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe,
                                foreground='#007070',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper2 = Label(lastoperframe,
                                anchor='w',
                                width=30,
                                foreground='#004040',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    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='Reset Parser',
                             underline=0,
                             command=self.reset,
                             accelerator='Del')
        filemenu.add_command(label='Print to Postscript',
                             underline=0,
                             command=self.postscript,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar',
                             underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text',
                             underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step',
                             underline=1,
                             command=self.step,
                             accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match',
                             underline=0,
                             command=self.match,
                             accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand',
                             underline=0,
                             command=self.expand,
                             accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack',
                             underline=0,
                             command=self.backtrack,
                             accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar",
                                 underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        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)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=10,
                                    accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=5,
                                    accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation",
                                    underline=0,
                                    variable=self._animation_frames,
                                    value=2,
                                    accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0, command=self.about)
        helpmenu.add_command(label='Instructions',
                             underline=0,
                             command=self.help,
                             accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Helper
    #########################################

    def _get(self, widget, treeloc):
        for i in treeloc:
            widget = widget.subtrees()[i]
        if isinstance(widget, TreeSegmentWidget):
            widget = widget.node()
        return widget

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {
            'tree_color': '#000000',
            'tree_width': 2,
            'node_font': bold,
            'leaf_font': helv,
        }
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [
            TextWidget(canvas, word, font=self._font) for word in self._sent
        ]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom - twidget.bbox()[3] - 5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000,
                                            y - 5,
                                            5000,
                                            y - 5,
                                            dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text()

    def _redraw_quick(self):
        # This should be more-or-less sufficient after an animation.
        self._highlight_nodes()
        self._highlight_prodlist()
        self._position_text()

    def _highlight_nodes(self):
        # Highlight the list of nodes to be checked.
        bold = ('helvetica', -self._size.get(), 'bold')
        for treeloc in self._parser.frontier()[:1]:
            self._get(self._tree, treeloc)['color'] = '#20a050'
            self._get(self._tree, treeloc)['font'] = bold
        for treeloc in self._parser.frontier()[1:]:
            self._get(self._tree, treeloc)['color'] = '#008080'

    def _highlight_prodlist(self):
        # Highlight the productions that can be expanded.
        # Boy, too bad tkinter doesn't implement Listbox.itemconfig;
        # that would be pretty useful here.
        self._prodlist.delete(0, 'end')
        expandable = self._parser.expandable_productions()
        untried = self._parser.untried_expandable_productions()
        productions = self._productions
        for index in range(len(productions)):
            if productions[index] in expandable:
                if productions[index] in untried:
                    self._prodlist.insert(index, ' %s' % productions[index])
                else:
                    self._prodlist.insert(index,
                                          ' %s (TRIED)' % productions[index])
                self._prodlist.selection_set(index)
            else:
                self._prodlist.insert(index, ' %s' % productions[index])

    def _position_text(self):
        # Line up the text widgets that are matched against the tree
        numwords = len(self._sent)
        num_matched = numwords - len(self._parser.remaining_text())
        leaves = self._tree_leaves()[:num_matched]
        xmax = self._tree.bbox()[0]
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            widget['color'] = '#006040'
            leaf['color'] = '#006040'
            widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # Line up the text widgets that are not matched against the tree.
        for i in range(len(leaves), numwords):
            widget = self._textwidgets[i]
            widget['color'] = '#a0a0a0'
            widget.move(xmax - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # If we have a complete parse, make everything green :)
        if self._parser.currently_complete():
            for twidget in self._textwidgets:
                twidget['color'] = '#00a000'

        # Move the matched leaves down to the text.
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
            dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10)
            leaf.move(0, dy)

    def _tree_leaves(self, tree=None):
        if tree is None: tree = self._tree
        if isinstance(tree, TreeSegmentWidget):
            leaves = []
            for child in tree.subtrees():
                leaves += self._tree_leaves(child)
            return leaves
        else:
            return [tree]

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._autostep = 0
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset Application'
        self._lastoper2['text'] = ''
        self._redraw()

    def autostep(self, *e):
        if self._animation_frames.get() == 0:
            self._animation_frames.set(2)
        if self._autostep:
            self._autostep = 0
        else:
            self._autostep = 1
            self._step()

    def cancel_autostep(self, *e):
        #self._autostep_button['text'] = 'Autostep'
        self._autostep = 0

    # Make sure to stop auto-stepping if we get any user input.
    def step(self, *e):
        self._autostep = 0
        self._step()

    def match(self, *e):
        self._autostep = 0
        self._match()

    def expand(self, *e):
        self._autostep = 0
        self._expand()

    def backtrack(self, *e):
        self._autostep = 0
        self._backtrack()

    def _step(self):
        if self._animating_lock: return

        # Try expanding, matching, and backtracking (in that order)
        if self._expand(): pass
        elif self._parser.untried_match() and self._match(): pass
        elif self._backtrack(): pass
        else:
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            self._autostep = 0

        # Check if we just completed a parse.
        if self._parser.currently_complete():
            self._autostep = 0
            self._lastoper2['text'] += '    [COMPLETE PARSE]'

    def _expand(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.expand()
        if rv is not None:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = rv
            self._prodlist.selection_clear(0, 'end')
            index = self._productions.index(rv)
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = '(all expansions tried)'
            return 0

    def _match(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.match()
        if rv is not None:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = rv
            self._animate_match(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = '(failed)'
            return 0

    def _backtrack(self, *e):
        if self._animating_lock: return
        if self._parser.backtrack():
            elt = self._parser.tree()
            for i in self._parser.frontier()[0]:
                elt = elt[i]
            self._lastoper1['text'] = 'Backtrack'
            self._lastoper2['text'] = ''
            if isinstance(elt, Tree):
                self._animate_backtrack(self._parser.frontier()[0])
            else:
                self._animate_match_backtrack(self._parser.frontier()[0])
            return 1
        else:
            self._autostep = 0
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            return 0

    def about(self, *e):
        ABOUT = ("NLTK Recursive Descent Parser Application\n" +
                 "Written by Edward Loper")
        TITLE = 'About: Recursive Descent Parser Application'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top,
                     'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(),
                     width=75,
                     font='fixed')
        except:
            ShowText(self._top,
                     'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(),
                     width=75)

    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()

    #########################################
    ##  Expand Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both',
                                 side='left',
                                 padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''


#     def toggle_grammar(self, *e):
#         self._show_grammar = not self._show_grammar
#         if self._show_grammar:
#             self._prodframe.pack(fill='both', expand='y', side='left',
#                                  after=self._feedbackframe)
#             self._lastoper1['text'] = 'Show Grammar'
#         else:
#             self._prodframe.pack_forget()
#             self._lastoper1['text'] = 'Hide Grammar'
#         self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        old_frontier = self._parser.frontier()
        production = self._parser.expand(self._productions[index])

        if production:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = production
            self._prodlist.selection_clear(0, 'end')
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.expandable_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    #########################################
    ##  Animation
    #########################################

    def _animate_expand(self, treeloc):
        oldwidget = self._get(self._tree, treeloc)
        oldtree = oldwidget.parent()
        top = not isinstance(oldtree.parent(), TreeSegmentWidget)

        tree = self._parser.tree()
        for i in treeloc:
            tree = tree[i]

        widget = tree_to_treesegment(self._canvas,
                                     tree,
                                     node_font=self._boldfont,
                                     leaf_color='white',
                                     tree_width=2,
                                     tree_color='white',
                                     node_color='white',
                                     leaf_font=self._font)
        widget.node()['color'] = '#20a050'

        (oldx, oldy) = oldtree.node().bbox()[:2]
        (newx, newy) = widget.node().bbox()[:2]
        widget.move(oldx - newx, oldy - newy)

        if top:
            self._cframe.add_widget(widget, 0, 5)
            widget.move(30 - widget.node().bbox()[0], 0)
            self._tree = widget
        else:
            oldtree.parent().replace_child(oldtree, widget)

        # Move the children over so they don't overlap.
        # Line the children up in a strange way.
        if widget.subtrees():
            dx = (oldx + widget.node().width() / 2 -
                  widget.subtrees()[0].bbox()[0] / 2 -
                  widget.subtrees()[0].bbox()[2] / 2)
            for subtree in widget.subtrees():
                subtree.move(dx, 0)

        self._makeroom(widget)

        if top:
            self._cframe.destroy_widget(oldtree)
        else:
            oldtree.destroy()

        colors = [
            'gray%d' % (10 * int(10 * x / self._animation_frames.get()))
            for x in range(self._animation_frames.get(), 0, -1)
        ]

        # Move the text string down, if necessary.
        dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
        if dy > 0:
            for twidget in self._textwidgets:
                twidget.move(0, dy)
            self._canvas.move(self._textline, 0, dy)

        self._animate_expand_frame(widget, colors)

    def _makeroom(self, treeseg):
        """
        Make sure that no sibling tree bbox's overlap.
        """
        parent = treeseg.parent()
        if not isinstance(parent, TreeSegmentWidget): return

        index = parent.subtrees().index(treeseg)

        # Handle siblings to the right
        rsiblings = parent.subtrees()[index + 1:]
        if rsiblings:
            dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
            for sibling in rsiblings:
                sibling.move(dx, 0)

        # Handle siblings to the left
        if index > 0:
            lsibling = parent.subtrees()[index - 1]
            dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
            treeseg.move(dx, 0)

        # Keep working up the tree.
        self._makeroom(parent)

    def _animate_expand_frame(self, widget, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            widget['color'] = colors[0]
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.node()['color'] = colors[0]
                else:
                    subtree['color'] = colors[0]
            self._top.after(50, self._animate_expand_frame, widget, colors[1:])
        else:
            widget['color'] = 'black'
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.node()['color'] = 'black'
                else:
                    subtree['color'] = 'black'
            self._redraw_quick()
            widget.node()['color'] = 'black'
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_backtrack(self, treeloc):
        # Flash red first, if we're animating.
        if self._animation_frames.get() == 0: colors = []
        else: colors = ['#a00000', '#000000', '#a00000']
        colors += [
            'gray%d' % (10 * int(10 * x / (self._animation_frames.get())))
            for x in range(1,
                           self._animation_frames.get() + 1)
        ]

        widgets = [self._get(self._tree, treeloc).parent()]
        for subtree in widgets[0].subtrees():
            if isinstance(subtree, TreeSegmentWidget):
                widgets.append(subtree.node())
            else:
                widgets.append(subtree)

        self._animate_backtrack_frame(widgets, colors)

    def _animate_backtrack_frame(self, widgets, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget['color'] = colors[0]
            self._top.after(50, self._animate_backtrack_frame, widgets,
                            colors[1:])
        else:
            for widget in widgets[0].subtrees():
                widgets[0].remove_child(widget)
                widget.destroy()
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack(self, treeloc):
        widget = self._get(self._tree, treeloc)
        node = widget.parent().node()
        dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
              max(1, self._animation_frames.get()))
        self._animate_match_backtrack_frame(self._animation_frames.get(),
                                            widget, dy)

    def _animate_match(self, treeloc):
        widget = self._get(self._tree, treeloc)

        dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) /
              max(1, self._animation_frames.get()))
        self._animate_match_frame(self._animation_frames.get(), widget, dy)

    def _animate_match_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_frame, frame - 1, widget,
                            dy)
        else:
            widget['color'] = '#006040'
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_backtrack_frame, frame - 1,
                            widget, dy)
        else:
            widget.parent().remove_child(widget)
            widget.destroy()
            self._animating_lock = 0
            if self._autostep: self._step()

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = string.join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sentence):
        self._sent = sentence.split()  #[XX] use tagged?
        self.reset()
Esempio n. 23
0
class Ordered_Listbox(Frame):
    def __init__(self, master, data=None, ascending_order = True, ignore_case=False, autoscroll=False, vscrollbar=True, hscrollbar=False, scrollbar_background=None, scrollbar_troughcolor=None, **kwargs):
        Frame.__init__(self, master)

        self._ignore_case = ignore_case
        self._ascending_order = ascending_order

        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        self._listbox = Listbox(self, *kwargs)        
        self._listbox.grid(row=0, column=0, sticky= N+E+W+S)

        scrollbar_kwargs = {}
        if scrollbar_background is not None:
            scrollbar_kwargs["background"] = scrollbar_background
            
        if scrollbar_troughcolor is not None:
            scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor

        if vscrollbar:
            self._vbar=Scrollbar(self,takefocus=0, command=self._listbox.yview, **scrollbar_kwargs)
            self._vbar.grid(row=0, column=1, sticky= N+S)
            
            if autoscroll:
                self._listbox.config(yscrollcommand=lambda f, l: make_autoscroll(self._vbar, f, l))
            else:
                self._listbox.config(yscrollcommand=self._vbar.set)

        if hscrollbar:
            self._hbar=Scrollbar(self,takefocus=0, command=self._listbox.xview, **scrollbar_kwargs)
            self._hbar.grid(row=0, column=1, sticky= E+W)
            
            if autoscroll:
                self._listbox.config(xscrollcommand=lambda f, l: make_autoscroll(self._hbar, f, l))
            else:
                self._listbox.config(xscrollcommand=self._hbar.set)

        if data is not None:
            for item in data:
                self.add_item(item)

    def add_item(self, item):
        list_of_items = self._listbox.get(0, END)

        index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order)
        self._listbox.insert(index, item)

    def delete_item(self, item):
        list_of_items = self._listbox.get(0, END)
        index = bisect(list_of_items, item, ignore_case=self._ignore_case, ascending_order=self._ascending_order)
        self._listbox.delete(index-1)
        
    def selected_items(self):
        list_of_items = []

        for index in self._listbox.curselection():
            list_of_items.append(self._listbox.get(index))
            
        return list_of_items
        
    def selected_item(self):
        return self._listbox.curselection()[0]

    def deselect_all(self):
        self._listbox.selection_clear(0, END)
        
    def select(self, item):
        index = self.index(item)
        
        if index is None:
            return
        
        self._listbox.selection_set(index)

    def deselect(self, item):
        index = self.index(item)
        
        if index is None:
            return
        
        self._listbox.selection_clear(index)

    def index(self, item):
        list_of_items = self._listbox.get(0, END)

        try:
            index = list_of_items.index(item)
        except ValueError:
            return None

        return index

    def bind(self, event, handler):
        self._listbox.bind(event, handler)
    
    def clear(self):
        self._listbox.delete(1,END)

    def __iter__(self):
        return self.items
    
    @property
    def items(self):
        return self._listbox.get(0, END)
Esempio n. 24
0
class WikinewsExplorer:
	def __init__(self, master):
		
		
		self.currentFileName = ""
		self.entDir = "/dev/shm/wikinews/entities/"
		self.llDir= "/dev/shm/wikinews/lang_links/"
		self.boolFileLoad = False
		self.entFiles = []
		self.llFiles = []
		self.wikinewsBaseURL = "http://en.wikinews.org/?curid="

		frame = Frame(master)
		frame.pack()
		
		frame.columnconfigure(1, weight=1)
		frame.columnconfigure(3, pad=7)
		frame.rowconfigure(3, weight=1)
		frame.rowconfigure(5, pad=7)
		
		self.lbEntFile = Label(frame, text="entities dir: ")
		self.lbEntFile.grid(row=0, column=0)
		
		self.lbLLFile = Label(frame, text="lang links dir: ")
		self.lbLLFile.grid(row=1, column=0)
		
		self.txtEntFile =Text(frame, height=1, width=40)
		self.txtEntFile.insert(INSERT, self.entDir)
		self.txtEntFile.grid(row=0, column=1)
		
		self.txtLLFile =Text(frame, height=1, width=40)
		self.txtLLFile.insert(INSERT, self.llDir)
		self.txtLLFile.grid(row=1, column=1)
		
		self.butLoad= Button(frame, text ="Load", command = self.readInputFiles)
		self.butLoad.grid(row=0, column=2, rowspan=2)
		
		
		
		self.scrollbar = Scrollbar(frame)
		self.lstArticles = Listbox(frame, yscrollcommand = self.scrollbar.set, width=50, height=20)
		self.lstArticles.grid( row=2, column=0, columnspan=2, sticky=W)
		self.lstArticles.bind("<<ListboxSelect>>", self.onArticleSelect)
		
		self.scrollbar.grid(row=2, column=3, sticky=W)
		self.scrollbar.config( command = self.lstArticles.yview )
		
		self.butOpenBrowser = Button(frame, text="View article in browser", command=self.openInFirefox)
		self.butOpenBrowser.grid(row=3, column=0)
	
	
	
		self.lblSearchTitle = Label(frame, text="search article ID: ")
		self.lblSearchTitle.grid(row=4, column=0, sticky=E)
		
		self.txtSearchTitle = Text(frame, height=1, width=30)
		self.txtSearchTitle.grid(row=4, column=1)
		
		
		self.butSearchTitle = Button(frame, text="Go", command=self.searchTitle)
		self.butSearchTitle.grid(row=4, column=2, sticky=W)
		
		self.scrollbar2 = Scrollbar(frame)		
		self.lstContent = Listbox(frame, yscrollcommand=self.scrollbar2.set, width=100, height=20)
		self.lstContent.grid(row=0, column=3, rowspan=5)
		self.lstContent.bind("<<ListboxSelect>>", self.onEntitySelect)
		self.scrollbar2.grid(row=0, column=3, sticky=W)
		self.scrollbar2.config( command = self.lstContent.yview )
		
		
		self.scrollbar3 = Scrollbar(frame)		
		self.lstWikiLinks = Listbox(frame, yscrollcommand=self.scrollbar3.set, width=70, height=13)
		self.lstWikiLinks.grid(row=5, column=3, sticky=W)
		self.scrollbar3.grid(row=5, column=3, sticky=W)
		self.scrollbar3.config( command = self.lstWikiLinks.yview )
	
	
	
	def onEntitySelect(self, event):
		""" fetch entity info directly from wikipedia """
		# enpty content box
		self.lstWikiLinks.delete(0, END)
		widg = event.widget
		index = int(widg.curselection()[0])
		entityString = widg.get(index)
		print 'selected entity %d: "%s"' % (index, entityString)	
		
		entityName = extractEntityName(entityString)
		self.lstWikiLinks.insert(END, "en.wikipedia.org/wiki/" + entityName) 
		self.lstWikiLinks.insert(END, "======= links to the following wiki entities: ========================") 
		
		url = "http://en.wikipedia.org/w/api.php?format=xml&action=query&titles=" + entityName +"&prop=links"
		print "HTTP request: ", url
		xmlResponseTree = None
		try:
			response = urllib2.urlopen(url).read()
			xmlResponseTree = ET.fromstring(response)
		except:
			print " \n ERROR: ", str(sys.exc_info()[0])
								
		
		if xmlResponseTree != None:
			for link in xmlResponseTree.iter("pl"):
# 				item = "en.wikipedia.org/wiki/" + 
				self.lstWikiLinks.insert(END, link.attrib.get("title"))
		else:
			print " xml response tree empty "
		
	def onArticleSelect(self, event):
		
		# enpty content boxes
		self.lstContent.delete(0, END)
		self.lstWikiLinks.delete(0,END)
		
		widg = event.widget
		index = int(widg.curselection()[0])
		fileName = widg.get(index)
		self.currentFileName = fileName
		print 'selected item %d: "%s"' % (index, fileName)	
		
		# load the entity and lang-link files and display in the content box
		entFile = self.entDir + fileName
		llFile = self.llDir + fileName
		ents = open(entFile)
		lls = open(llFile)

		self.lstContent.insert(END, "===== contained Entities =================================")
		
		for ent in ents:
			self.lstContent.insert(END, ent.strip())

		self.lstContent.insert(END, " ")			
		self.lstContent.insert(END, "===== contained Language Links ===========================")
		
		for ll in lls:
			self.lstContent.insert(END, ll.strip())
			
		ents.close()
		lls.close()
		
	def openInFirefox(self):
		wikinewsBase = self.wikinewsBaseURL
		
		articleID = self.lstArticles.get(ACTIVE).split("-")[0]
		
		"""
		commandLinux = "firefox " + wikinewsBase + articleID + " &"	
		commandMacOS = "open -a firefox -g " + wikinewsBase + articleID
		commandWindows = 'firefox.exe \"' +  wikinewsBase + articleID +  '\"'
	
	
		if os.uname()[0] == "Linux":
			print "Linux: starting firefox"
			os.system(commandLinux)
		elif os.uname()[0] == "Mac":
			print "Mac: starting firefox"
			os.system(commandMacOS)
		elif os.name == "Windows":
			print "Windows: starting firefox"
			os.system(commandWindows)
		else:
			tkMessageBox.showinfo("Wikinews Explorer", "Strange OS detected: " + os.uname()[0] + "\n can't start Firefox")
		"""
		if not webbrowser.open_new(wikinewsBase + articleID):
			tkMessageBox.showinfo("Wikinews Explorer", "start browser")
			
		return
	
	def searchTitle(self):
		print "search: files loaded?", self.boolFileLoad
		targetString = self.txtSearchTitle.get(1.0, END).strip()
		if self.boolFileLoad:
			i = 0
			for fileName in self.entFiles:
				if targetString.lower() in fileName.lower():
					# focus first result and exit
					
					self.lstArticles.selection_set(i, i)
					self.lstArticles.see(i)
				
					
					print "--- found: ", i, " ", fileName
					break
				i += 1
				
		else:
			tkMessageBox.showinfo("Wikinews Explorer", "Input files not loaded")
	
	
	def readInputFiles(self):
		self.entDir = self.txtEntFile.get(1.0, END).strip()
		self.llDir = self.txtLLFile.get(1.0, END).strip()

		if not os.path.exists(self.entDir):
			tkMessageBox.showinfo( "Wikinews Explorer", self.entDir + "\ndoes not exist")
			self.boolFileLoad = False
			return
		if not os.path.exists(self.llDir):
			self.boolFileLoad = False
			tkMessageBox.showinfo( "Wikinews Explorer", self.llDir + "\ndoes not exist")
			return	
		
		# no return until here, it's fine
		self.entFiles = os.listdir(self.entDir)
		self.llFiles = os.listdir(self.llDir)
		
		if len(self.entFiles) != len(self.llFiles):
			tkMessageBox.showinfo("Wikinews Explorer", "something's wrong: \n  article number mismatch: " + len(self.entFiles) + " != " + len(self.llFiles))
			self.boolFileLoad = False
			return
		else:
			print "files count ok: ", str(len(self.entFiles)), " == ", str(len(self.llFiles))
			for fileName in self.entFiles:
				self.lstArticles.insert(END, fileName)
			self.boolFileLoad = True # file loading ok
		
		print "files loaded?", self.boolFileLoad
Esempio n. 25
0
class GUI(Frame):
    # In intialize the object, taking in the parent as in input parameter
    def __init__(self, parent):
        Frame.__init__(self, parent)
        # Initialize the api
        self.api = API()
        # Set the ip and port to communicate with the master server
        self.SERVER_IP = config.masterip
        self.SERVER_PORT = config.port
        # Set the initial server status to 0, will change to 1 if server is active
        # self.serverStatus = 0
        # Declare a list which will hold the files that have been flagged for deletion
        self.toDelete = []

        self.parent = parent
        # Initialize the GUI
        self.initUI()

    # Function to initialize UI
    def initUI(self):
        # Set the name of the UI window
        self.parent.title("Bennington File System Client")
        # Set the style using the default theme
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        # Set the "Open File" options
        self.file_opt = options = {}
        # Allow for any file to be choosable
        options["defaultextension"] = ""
        options["filetypes"] = ""
        # Set the directory window will open up to initially
        options["initialdir"] = "C:\\"
        options["parent"] = self

        # Create a label object which holds the text labeling the listbox
        lbl = Label(self, text="Bennington File System Files List", foreground="black")
        # Place the text in the top left
        lbl.grid(column=0, row=0, pady=4, padx=5)

        # Create the listbox, which will contain a list of all the files on the system
        self.area = Listbox(self, height=20)
        # Place the lisbox in the UI frame
        self.area.grid(row=1, column=0, columnspan=1, rowspan=10, padx=5, sticky=N + W + E + S)

        # Ask the master server which files it has, then populate the listbox with the response
        self.getFiles()

        # Create a button labeled 'Upload', and bind the uploadFile() function to it
        uploadbtn = Button(self, text="Upload", command=self.uploadFile)
        # Place the button in the UI frame
        uploadbtn.grid(row=1, column=3)

        # Create a button labeled 'Download', and bind the downloadFile() function to it
        dwnbtn = Button(self, text="Download", command=self.downloadFile)
        # Place the button in the UI frame
        dwnbtn.grid(row=2, column=3)

        # Create a button labeled 'Delete', and bind the deleteFile() function to it
        delbtn = Button(self, text="Delete", command=self.deleteFile)
        # Place the button in the UI frame
        delbtn.grid(row=3, column=3)

        # Create a button labeled 'Undelete', and bind the undeleteFile() function to it
        undelbtn = Button(self, text="Undelete", command=self.undeleteFile)
        # Place the button in the UI frame
        undelbtn.grid(row=4, column=3)

        # Create a button labeled 'Refresh List', and bind the getFiles() function to it
        refbtn = Button(self, text="Refresh List", command=self.getFiles)
        # Place the button in the UI frame
        refbtn.grid(row=5, column=3)

        # Create a button labeled 'Quit', and bind the exitProgram() function to it
        quitButton = Button(self, text="Quit", command=self.exitProgram)
        # Place the button in the UI frame
        quitButton.grid(sticky=W, padx=5, pady=4)

    # Downloads the active selection in the listbox
    def downloadFile(self):
        # Get the filename from the active listbox item
        fileName = self.currentSelectionFileName()
        # Call the API read function to get all the data associated with that file
        self.api.read(fileName, 0, -1, fileName)

    # Get the file name of the active selection in the listbox
    def currentSelectionFileName(self):
        # Get the index of the active selection
        index = self.currentSelectionIndex()
        # From the listbox object, pass in the index to get the filename
        fileName = self.area.get(index)
        return fileName

    # Get the index of the active selection in the listbox
    def currentSelectionIndex(self):
        # Get the index of the active selection
        index = self.area.curselection()[0]
        return index

    # Mark the active selection in the listbox for deletion
    def deleteFile(self):
        # Get the index of the current active selection
        index = self.currentSelectionIndex()
        # Get the filename of the current active selection
        filename = self.area.get(index)
        # Call the API function to mark file for deletion
        self.api.delete(filename)
        # Change the background color of the selection to denote it has been marked for deletion
        self.area.itemconfig(index, {"bg": "salmon"})
        # Append the filename to the toDelete list
        self.toDelete.append(filename)

    # Unmarks the active selection in the listbox for deletion
    def undeleteFile(self):
        # Get the index of the current active selection
        index = self.currentSelectionIndex()
        # Get the filename of the current active selection
        filename = self.area.get(index)
        # See if the file has been marked for deletion
        if filename in self.toDelete:
            # Call the API function to unmark file for deletion
            self.api.undelete(filename)
            # Change the background color of the selection to denote it is no longer marked for deletion
            self.area.itemconfig(index, {"bg": "white"})
            # Remove the filename from the toDelete list
            self.toDelete.remove(filename)

    # Upload a file from local machine to the distributed file system
    def uploadFile(self):
        # Get the file name and file path of the file the user wants to upload
        fileinfo = self.openFile()
        # Create a file with the filename provided
        self.api.create(fileinfo[0])
        # Append the file data from the file at the given file path
        self.api.append(fileinfo[0], fileinfo[1], 1)
        # Once that is complete, refresh the file list in the listbox
        self.getFiles()

    # Prompt the user to select a file
    def openFile(self):
        # Prompt the user to select a file, and store the returned file path
        filepath = tkFileDialog.askopenfilename(**self.file_opt)
        # Parse the filepath, and store the last element of the split as the file name
        filename = filepath.split("/")[-1]
        # Return a list containing the file name and file path
        return [filename, filepath]

    # Get the list of existing files from the master server
    def getFiles(self):
        try:
            # Get the file data using the API's fileList() function
            # At this stage, the data has lots of extra things in it, so it needs to be cleaned up
            data = self.api.fileList()
            # Split the string at every * character
            data = re.split("\*", data)
            # Declare an empty array which will hold the file names found from the parsing
            fileNames = []
            for item in data:
                # Split the element at every ^ character
                tempitem = re.split("\^", item)
                for thing in tempitem:
                    # If the element has a | in it, but is not just a |, then it is the filename
                    if "|" in thing and not thing == "|":
                        # Append the filename (with the | stripped out) to the fileNames list
                        fileNames.append(thing.strip("|"))

            # If the file is marked for deletion and still in the fileNames list
            # keep the file in the toDelete list
            temp = []
            for item in self.toDelete:
                if item in fileNames:
                    temp.append(item)

            # Update the toDelete list
            self.toDelete = temp

            # Remove all entries in the listbox
            self.area.delete(0, END)

            # Populate the listbox with the file names returned from the master
            for item in fileNames:
                self.area.insert(END, item)
                self.checkIfMarked(item)

        except Exception as e:
            raise e

    # Check to see if the provided file name exists in the toDelete list
    def checkIfMarked(self, fileName):
        # If the file name is in the toDelete list
        if fileName in self.toDelete:
            # Change the background color of the element to denote that it has been marked for deletion
            self.area.itemconfig(END, {"bg": "salmon"})

    # An exit function that quits the UI (any additional clean up pre-close should go in here)
    def exitProgram(self):
        self.quit()
Esempio n. 26
0
class PraiseTexGUI(object):
    """Graphical interface for selecting songs and compiling them"""
    def __init__(self, songdir="songs"):
        # data
        self.songs = []
        self.praisetex = PraiseTex(songdir)
        self.root = Tk()
        
        button_width = 6
        button_padx = "2m"
        button_pady = "1m"
        frame_padx = "3m"
        frame_pady = "2m"
        label_padx = "3m"
        label_pady = "2m"
        listbox_width = 30
        listbox_height = 20
        frame_title_font = ("TkDefaultFont", 14)
        text_font = ("TkDefaultFont", 12)
        menu_font = ("TkDefaultFont", 12)
        button_font = ("TkDefaultFont", 12)

        # window properties
        self.root.title("praisetex")
        self.root.option_add("*Font", ("TkDefaultFont", 12))

        # menu
        menubar = Menu(self.root)
        menubar.tk.call('tk', 'scaling', 2.5)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open Directory", command=self.openDirectory)
        filemenu.add_command(label="Exit", command=self.root.quit)
        menubar.add_cascade(label="File", menu=filemenu)
        self.root.config(menu=menubar)

        # left section
        self.availableSongsTitle = Label(self.root, 
                                         text="Available Songs",
                                         font=frame_title_font,
                                         padx=label_padx, 
                                         pady=label_pady)
        self.availableSongsTitle.grid(row=0, column=0)
        self.availableSongsFrame = Frame(self.root)
        self.availableSongsFrame.grid(row=1, column=0,
                                      padx=frame_padx, pady=frame_pady)
        self.availableSongsScroll = Scrollbar(self.availableSongsFrame, 
                                              orient=VERTICAL)
        self.availableSongs = Listbox(self.availableSongsFrame, 
                                      width=listbox_width, 
                                      height=listbox_height, 
                                      selectmode=EXTENDED, 
                                      yscrollcommand=self.availableSongsScroll.set,
                                      exportselection=0)
        self.availableSongsScroll.config(command=self.availableSongs.yview)
        self.availableSongsScroll.pack(side=RIGHT, fill=Y)
        self.availableSongs.pack()

        self.button = Button(self.root, 
                             text="Refresh",  
                             command=self.refreshSongList)
        self.button.grid(row=2, column=0)

        
        # middle section
        self.addRemoveButtonFrame = Frame(self.root)
        self.addRemoveButtonFrame.grid(row=1, column=1)
        self.addSongButton = Button(self.addRemoveButtonFrame,
                                    text="Add", 
                                    command=self.addSong)
        self.addSongButton.pack(side=TOP, padx=button_padx, pady=button_pady)
        self.removeSongButton = Button(self.addRemoveButtonFrame, 
                                       text="Remove", 
                                       command=self.removeSong)
        self.removeSongButton.pack(side=BOTTOM)

        # right section
        self.songsToCompileTitle = Label(self.root, text="Songs to Compile", 
                                         font=frame_title_font,
                                         padx=label_padx, pady=label_pady)
        self.songsToCompileTitle.grid(row=0, column=2)
        self.songsToCompileFrame = Frame(self.root)
        self.songsToCompileFrame.grid(row=1, column=2, 
                                      padx=frame_padx, pady=frame_pady)
        self.songsToCompileScroll = Scrollbar(self.songsToCompileFrame,
                                              orient=VERTICAL)
        self.songsToCompile = Listbox(self.songsToCompileFrame, 
                                      width=listbox_width, 
                                      height=listbox_height, 
                                      selectmode=EXTENDED,
                                      yscrollcommand=self.songsToCompileScroll.set,
                                      exportselection=0,
                                      font=text_font)
        self.songsToCompileScroll.config(command=self.songsToCompile.yview)
        self.songsToCompileScroll.pack(side=RIGHT, fill=Y)
        self.songsToCompile.pack()

        self.compileButtonFrame = Frame(self.root)
        self.compileButtonFrame.grid(row=2, column=2)
        self.chordsButton = Button(self.compileButtonFrame, 
                                   text="Chords", 
                                   command=self.compileChords)
        self.chordsButton.pack(side=LEFT, padx=button_padx, pady=button_pady)
        self.slidesButton = Button(self.compileButtonFrame, 
                                   text="Slides", 
                                   command=self.compileSlides)
        self.slidesButton.pack(side=RIGHT, padx=button_padx, pady=button_pady)

        # status bar
        self.status = Label(self.root, text="Ready", padx="1m")
        self.status.grid(row=3, column=0, columnspan=3, sticky=W)

        self.refreshSongList()

    def run(self):
        """Start event loop of GUI"""
        self.root.mainloop()

    def refreshSongList(self):
        """Sync up the filenames in songlist with files in directory"""
        # clear song list
        self.availableSongs.delete(0, END)

        # add song files
        self.songs = self.praisetex.refreshSongList()
        for song in self.songs:
            self.availableSongs.insert(END, song)
        self.updateStatus("{0} songs found in directory {1}".format(len(self.songs), self.praisetex.getSongDirectory()))

    def openDirectory(self):
        """Selects directory for songs"""
        dirname = filedialog.askdirectory(parent=self.root, initialdir=self.praisetex.getSongDirectory(), title='Please select a directory')
        if len(dirname) > 0:
            self.praisetex.setSongDirectory(dirname)
            self.updateStatus("Song directory set to {0}".format(dirname))

    def addSong(self):
        """Add song to compile list"""
        selectedSongs = self.availableSongs.curselection()

        # get index of where to insert selected songs
        insertIndex = self.songsToCompile.curselection()
        if len(insertIndex) > 0:
            insertIndex = int(insertIndex[0]) # convert to integer
        else:
            insertIndex = -1 # song should be appended


        if len(selectedSongs) == 0: # do nothing
            pass
            
        elif len(selectedSongs) == 1: # insert the one song
            song = selectedSongs[0]
            songtitle = self.availableSongs.get(song)
            if insertIndex == -1:
                end = len(self.praisetex.compile)
                self.praisetex.addSong(end, songtitle)
                self.songsToCompile.insert(END, songtitle)
            else:
                self.praisetex.addSong(insertIndex+1, songtitle)
                self.songsToCompile.insert(insertIndex+1, songtitle)
            
        else: # more than one song  
            songList = [self.availableSongs.get(song) for song in selectedSongs]
            if insertIndex != -1:
                songList.reverse()
                for songtitle in songList:
                    self.praisetex.addSong(insertIndex+1, songtitle)
                    self.songsToCompile.insert(insertIndex+1, songtitle)
            else: # add songs to the end
                for songtitle in songList:
                    end = len(self.praisetex.compile)
                    self.praisetex.addSong(end, songtitle)
                    self.songsToCompile.insert(END, songtitle)
       
        self.updateStatus("{0} songs added".format(len(selectedSongs)))


    def removeSong(self):
        """Remove song from compile list"""
        songindexes = list(self.songsToCompile.curselection())
        songindexes.reverse()
        for index in songindexes:
            self.praisetex.removeSong(index)
            self.songsToCompile.delete(index)
            
        self.updateStatus("{0} songs removed".format(len(songindexes)))

    def compileChords(self):
        """Compile a chord sheet from selected songs"""
        self.updateStatus("Compiling Songs")
        error = self.praisetex.compileChords()
        if error:
            self.updateStatus("pdflatex has failed")
        else:
            self.updateStatus("Compiled chords.pdf")

    def compileSlides(self):
        """Compile slides from selected songs"""
        self.updateStatus("Compiling Songs")
        error = self.praisetex.compileSlides()
        if error:
            self.updateStatus("pdflatex has failed")
        else:
            self.updateStatus("Compiled slides.pdf")

    def updateStatus(self, message):
        """Update the status bar"""
        self.status.config(text=message)
Esempio n. 27
0
class ListHeap(Frame):
    """
    A widget that encapsulates a list box, allow adding and delete and contextual interaction
        with a set of items in a list box
    """

    def __init__(self, parent, populator, max_limit=sys.maxint):
        """

        :param parent:          The parent tk item
        :param max_limit:       The maximum number of items allowed to be added to the listheap
        :return:
        """
        Frame.__init__(self, parent)
        self._items = {}
        self._parent = parent
        self._max_limit = max_limit
        self._listbox = Listbox(self, selectmode=SINGLE)
        self._listbox.grid(row=0, column=0)

        # Bind mouse events
        self._listbox.bind("<Double-Button-1>", self._handle_db_click)
        self._listbox.bind("<Button-2>", self._handle_r_click)

        # Populate the widget with custom params if they are available
        if populator is not None:
            self.populate(populator)

    def populate(self, populator):
        """
        Override to define the population paramaters for this widget
        This allows default values to be provided
        """
        pass

    def add_new(self, item, key):
        """
        Add new item to the list heap

        Adds a new item to the list box and the data structure that defines the heap

        :param item:            The item to be added to the ListHeap
        :param key:             The key that is to be used to identify the item, must be unique
        :throws:                DuplicateListHeapItemException  - duplicate key attempted to add to the heap
        :throws:                MaxItemLimitReachedException    - Attempted item addition when max sized already reached
        """
        if key in self._items:
            raise DuplicateListHeapItemException(key)
        if len(self._items) >= self._max_limit:
            raise MaxItemLimitReachedException()
        self._items[key] = item
        self._listbox.insert(END, key)

    def _remove(self, key):
        """
        Remove an item from the ListHeap
        :param key:             The key of the item that is to be removed
        """
        del self._items[key]
        self._listbox.delete(ANCHOR)

    def _remove_all(self):
        """
        Removes all of the items from the ListHeap
        """
        self._items.clear()
        self._listbox.delete(0, END)

    def _handle_db_click(self, event):
        """
        Override: define a handler for the doubleclick event on the ListHeap
        :param event:           The tk event generated by user input
        """
        pass

    def _handle_r_click(self, event):
        """
        Override: Define a handler for the rightclick event on the ListHeap
        :param event:           The tk event generated by user input
        """
        pass
Esempio n. 28
0
class IniGenGui(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUIGlobals()

    def initUIGlobals(self):

        self.parent.title("Ini Generator")

        Style().configure("TButton", padding=(0, 0, 0, 0), font='serif 10')

        f1 = Frame(self)
        f1.grid(row=0, column=0, padx=10, sticky=N + S + E + W)

        f11 = LabelFrame(f1, text="Algorithms to Run")
        f11.grid(row=0, column=0)
        row = 0

        self.check_algs_value_list = []
        self.check_algs_map = {}
        for alg in algorithms:
            if alg == 'clean':
                continue
            check_alg_value = IntVar()
            check_alg = Checkbutton(f11,
                                    text=alg,
                                    variable=check_alg_value,
                                    justify=LEFT,
                                    width=25)
            check_alg.grid(row=row, column=0, sticky=W + E)
            self.check_algs_value_list.append(check_alg_value)
            self.check_algs_map[alg] = check_alg_value
            row += 1

        f111 = Frame(f11)
        f111.grid(row=row, column=0)

        button_checkall = Button(f111, text="All", command=self.checkall)
        button_checkall.grid(row=0, column=0, sticky=W + E)
        button_uncheckall = Button(f111, text="None", command=self.uncheckall)
        button_uncheckall.grid(row=0, column=1, sticky=W + E)

        row = 0

        f12 = Frame(f1)
        f12.grid(row=1, column=0, pady=20, sticky=S + W + E)

        f121 = LabelFrame(f12, text='Location of uPMU')
        f121.grid(row=0, column=0)

        self.radio_loc_string = StringVar()
        locations.append('Other Location')
        for loc in locations:
            radio_loc = Radiobutton(f121,
                                    text=loc,
                                    variable=self.radio_loc_string,
                                    value=loc,
                                    command=self.set_loc,
                                    justify=LEFT,
                                    width=25)
            radio_loc.grid(row=row, column=0, sticky=W + E)
            row += 1

        self.entry_otherloc = Entry(f121)

        f2 = Frame(self)
        f2.grid(row=0, column=1, padx=10, sticky=N + S + E + W)

        f21 = LabelFrame(f2, text='Name of uPMU (raw)')
        f21.grid(row=0)
        row = 0

        f211 = Frame(f21)
        f211.grid(row=row)
        row += 1

        self.entry_namesearch = Entry(f211)
        self.entry_namesearch.grid(row=0, column=0, sticky=E + W)

        button_namesearch = Button(f211,
                                   text="Search",
                                   command=self.namesearch)
        button_namesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_namelist = Listbox(f21)
        self.lstbx_namelist.bind("<Double-Button-1>", self.namelist_select)
        self.lstbx_namelist.grid(row=row, sticky=W + E)
        row += 1

        f212 = Frame(f21)
        f212.grid(row=row)
        row += 1

        label_nameselected = Label(f212, text="Selected:")
        label_nameselected.grid(row=0, column=0)

        self.entry_nameselected = Entry(f212, state=DISABLED)
        self.entry_nameselected.grid(row=0, column=1, sticky=W + E)

        f22 = LabelFrame(f2, text="Name of uPMU (abbr)")
        f22.grid(row=1, sticky=W + E, pady=10)
        self.entry_name = Entry(f22, width=30)
        self.entry_name.grid(row=0, column=0, sticky=E + W)

        f23 = LabelFrame(f2, text="Name of Reference uPMU (clean)")
        f23.grid(row=2, pady=10)
        row = 0

        f231 = Frame(f23)
        f231.grid(row=row)
        row += 1

        self.entry_refnamesearch = Entry(f231)
        self.entry_refnamesearch.grid(row=0, column=0, sticky=E + W)

        button_refnamesearch = Button(f231,
                                      text="Search",
                                      command=self.refnamesearch)
        button_refnamesearch.grid(row=0, column=1, sticky=W + E)

        self.lstbx_refnamelist = Listbox(f23)
        self.lstbx_refnamelist.bind("<Double-Button-1>",
                                    self.refnamelist_select)
        self.lstbx_refnamelist.grid(row=row, sticky=W + E)
        row += 1

        f232 = Frame(f23)
        f232.grid(row=row)
        row += 1

        label_refnameselected = Label(f232, text="Selected:")
        label_refnameselected.grid(row=0, column=0)

        self.entry_refnameselected = Entry(f232, state=DISABLED)
        self.entry_refnameselected.grid(row=0, column=1, sticky=W + E)

        button_gen = Button(self,
                            text="Generate Files",
                            command=self.generate_files)
        button_gen.grid(row=1, column=0, columnspan=2, sticky=W + E)

        self.pack()

    def generate_files(self):
        algs = []
        for alg in self.check_algs_map:
            if self.check_algs_map[alg].get() == 1:
                algs.append(alg)

        if self.radio_loc_string.get() == "Other Location":
            location = self.entry_otherloc.get()
        else:
            location = self.radio_loc_string.get()

        name_raw = self.entry_nameselected.get()
        name = self.entry_name.get()
        ref_name = self.entry_refnameselected.get()

        uuid_map = self.get_uuid_map(name_raw)
        reference_uuid_map = self.get_ref_uuid_map(ref_name)

        IniGenAutomation(location, name_raw, name, uuid_map, ref_name,
                         reference_uuid_map, algs)

    def namesearch(self):
        searchterm = self.entry_namesearch.get()
        if searchterm.contains("/"):
            loc = searchterm.split('/')
            searchphrase = '/upmu/%{0}%/%{1}%/%'.format(loc[0], loc[1])
        else:
            searchphrase = '/upmu/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_namelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_namelist.insert(END, result)

    def refnamesearch(self):
        searchterm = self.entry_refnamesearch.get()
        searchphrase = '/Clean/%{0}%/%'.format(searchterm)
        search_results = self.search(searchterm, searchphrase)
        self.lstbx_refnamelist.delete(0, END)
        if len(search_results) == 0:
            tkMessageBox.showwarning(
                'Search Error',
                'No matches from search for \'{0}\''.format(searchterm))
        else:
            for result in search_results:
                self.lstbx_refnamelist.insert(END, result)

    def search(self, searchterm, searchphrase):
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '{0}'".format(
                searchphrase))
        results = connection.store_result()
        queried_data = {}
        result = results.fetch_row()
        while result != tuple():
            queried_data[result[0][0]] = result[0][1]
            result = results.fetch_row()
        search_results = set()
        for path in queried_data:
            dirs = path.split('/')
            if searchterm in dirs[2]:
                search_results.add(dirs[2])
        return search_results

    def set_loc(self):
        if self.radio_loc_string.get() == "Other Location":
            self.entry_otherloc.grid(sticky=W + E)
        else:
            self.entry_otherloc.grid_forget()

    def checkall(self):
        for check in self.check_algs_value_list:
            check.set(1)

    def uncheckall(self):
        for check in self.check_algs_value_list:
            check.set(0)

    def namelist_select(self, event):
        selected_index = self.lstbx_namelist.curselection()
        selected = self.lstbx_namelist.get(selected_index)
        self.entry_nameselected.configure(state=NORMAL)
        self.entry_nameselected.delete(0, END)
        self.entry_nameselected.insert(0, selected)
        self.entry_nameselected.configure(state=DISABLED)

    def refnamelist_select(self, event):
        selected_index = self.lstbx_refnamelist.curselection()
        selected = self.lstbx_refnamelist.get(selected_index)
        self.entry_refnameselected.configure(state=NORMAL)
        self.entry_refnameselected.delete(0, END)
        self.entry_refnameselected.insert(0, selected)
        self.entry_refnameselected.configure(state=DISABLED)

    def get_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/upmu/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-1]] = result[0][1]
            result = results.fetch_row()
        return uuid_map

    def get_ref_uuid_map(self, name):
        uuid_map = {}
        connection = _mysql.connect(host="128.32.37.231",
                                    port=3306,
                                    user="******",
                                    passwd="moresecuredataftw",
                                    db='upmu')
        connection.query(
            "SELECT * FROM uuidpathmap WHERE path LIKE '/Clean/{0}/%'".format(
                name))
        results = connection.store_result()
        result = results.fetch_row()
        while result != tuple():
            path = result[0][0].split('/')
            uuid_map[path[-2]] = result[0][1]
            result = results.fetch_row()
        return uuid_map
Esempio n. 29
0
class AttributesDialog(Toplevel):
    """
    Dialog window for creating and assigning attributes to objects
    :param root: The parent frame
    :param shape: The ShapeManager being edited
    """
    def __init__(self, root, shape):
        """
        Initialize root tkinter window and master GUI window
        """
        Toplevel.__init__(self, root, width=200, height=200)

        self.__shape = shape
        if shape is False:
            self.close()
            return
        self.title('Edit Attributes')

        # copies TAGS to avoid aliasing
        self.__available_attributes = TAGS[:]
        self.container = Frame(self)
        self.container.pack(side=TOP, fill=BOTH, expand=True)
        self.top_frame = None
        self.bottom_frame = None
        self.note_text = None
        self.attributes_list = None
        self.selected_list = None

        self.transient(root)
        logger.info('Creating top frame')
        self.create_top_frame()
        logger.info('Creating bottom frame')
        self.create_bottom_frame()

    def create_top_frame(self):
        """
        Initializes the top half of the window
        """
        self.top_frame = Frame(self.container)
        self.top_frame.pack(side=TOP, fill=X, expand=False)

        attributes_string = StringVar()
        attributes_string.set('Attributes:')
        attributes_label = Label(self.top_frame,
                                 textvariable=attributes_string)
        attributes_label.grid(row=0, column=0)

        selected_string = StringVar()
        selected_string.set('Selected:')
        selected_label = Label(self.top_frame, textvariable=selected_string)
        selected_label.grid(row=0, column=3)

        self.attributes_list = Listbox(self.top_frame,
                                       width=30,
                                       height=15,
                                       selectmode=EXTENDED)
        self.attributes_list.grid(row=1, column=0, padx=6)

        self.selected_list = Listbox(self.top_frame,
                                     width=30,
                                     height=15,
                                     selectmode=EXTENDED)
        self.selected_list.grid(row=1, column=3, padx=6)

        logger.info('Loading attributes')
        for tag in self.__available_attributes:
            if self.__shape.is_attribute(tag):
                self.selected_list.insert(END, tag)
            else:
                self.attributes_list.insert(END, tag)

        remove_button = Button(self.top_frame,
                               width=3,
                               height=2,
                               text='<--',
                               command=self.remove_attribute)
        remove_button.grid(row=1, column=1)

        move_button = Button(self.top_frame,
                             width=3,
                             height=2,
                             text='-->',
                             command=self.move_attribute)
        move_button.grid(row=1, column=2)

    def create_bottom_frame(self):
        """
        Initializes the bottom half of the window
        """
        self.bottom_frame = Frame(self.container)
        self.bottom_frame.pack(side=BOTTOM, fill=X, expand=False)

        note_string = StringVar()
        note_string.set('Notes:')
        note_label = Label(self.bottom_frame, textvariable=note_string)
        note_label.grid(row=0, column=1)

        self.note_text = Text(self.bottom_frame, width=55, height=10)
        self.note_text.grid(row=1, column=1, padx=6)
        self.note_text.insert(END, self.__shape.get_notes())

        button_frame = Frame(self.container)
        button_frame.pack(side=BOTTOM, fill=X, expand=False)

        accept_button = Button(button_frame,
                               text='Save',
                               width=9,
                               command=self.save)
        accept_button.pack(side=LEFT, pady=5, padx=2)

        cancel_button = Button(button_frame,
                               text='Clear Note',
                               width=9,
                               command=self.clear)
        cancel_button.pack(side=LEFT, pady=5, padx=2)

#         closeButton = Button(buttonFrame, text='Close', command=self.close)
#         closeButton.grid(row=3, column=2)

    def move_attribute(self):
        """
        Saves the attributes that the user has selected
        """
        selection = self.attributes_list.curselection()
        if len(selection) == 0:
            return
        for item in selection:
            string = self.attributes_list.get(item)
            logger.info('Adding attribute \'%s\' to shape' % string)
            self.__shape.add_attribute(string)
            self.selected_list.insert(END, string)
        for item in reversed(selection):
            self.attributes_list.delete(item)

    def remove_attribute(self):
        """
        Deletes the attributes that the user has selected
        """
        selection = self.selected_list.curselection()
        if len(selection) == 0:
            return
        for item in selection:
            string = self.selected_list.get(item)
            logger.info('Deleting attribute \'%s\' from shape' % string)
            self.__shape.remove_attribute(string)
            self.attributes_list.insert(END, string)
        for item in reversed(selection):
            self.selected_list.delete(item)

    def save(self):
        """
        Saves the note
        """
        logger.info('Saving note')
        note = self.note_text.get('1.0', 'end-1c')
        self.__shape.set_notes(note)
        self.close()

    def clear(self):
        """
        Deletes the note
        """
        logger.info('Deleting note')
        self.note_text.delete(1.0, END)
        self.__shape.set_notes('')

    def close(self):
        """
        Closes window
        """
        logger.info('Closing window')
        self.destroy()
Esempio n. 30
0
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()
Esempio n. 31
0
class ListPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)
        self.mutex = Lock()

    def prepare(self):
        self.deviceList.config(state='normal')
        self.versionList.config(state='disabled')
        self.engList.config(state='disabled')
        self.packageList.config(state='disabled')
        self.ok.config(state='disabled')
        self.setData(self.controller.data)
        self.setDeviceList(self.data.keys())
        self.controller.setDefault(self, self.controller.loadOptions())
        self.deviceList.focus_force()

    def printErr(self, message):
        self.errLog.config(text=message)

    def setData(self, data):
        self.data = data

    def setupView(self, title="Select your flash", data=None):
        if(data):
            self.setData(data)
        self.errLog = Label(self, text="")
        self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE")
        self.desc = Label(self, text=title, font=TITLE_FONT)
        self.desc.grid(row=0, column=0, columnspan=2)
        self.ok = Button(self,
                         text='Next',
                         command=lambda: self.
                         confirm())
        self.ok.grid(row=4, column=3, sticky="E")
        self.ok.config(state="disabled")
        self.deviceLabel = Label(self, text="Device", font=TITLE_FONT)
        self.deviceLabel.grid(row=1, column=0)
        self.deviceList = Listbox(self, exportselection=0)
        self.deviceList.grid(row=2, column=0)
        self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect)
        self.deviceList.config(state="disabled")
        self.versionLabel = Label(self, text="Branch", font=TITLE_FONT)
        self.versionLabel.grid(row=1, column=1)
        self.versionList = Listbox(self, exportselection=0)
        self.versionList.grid(row=2, column=1)
        self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect)
        self.versionList.config(state="disabled")
        self.engLabel = Label(self, text="Build Type", font=TITLE_FONT)
        self.engLabel.grid(row=1, column=2)
        self.engList = Listbox(self, exportselection=0)
        self.engList.grid(row=2, column=2)
        self.engList.bind('<<ListboxSelect>>', self.engOnSelect)
        self.engList.config(state="disabled")
        self.packageLabel = Label(
            self,
            text="Gecko/Gaia/Full",
            font=TITLE_FONT)
        self.packageLabel.grid(row=1, column=3)
        self.packageList = Listbox(self, exportselection=0)
        self.packageList.grid(row=2, column=3)
        self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect)
        self.packageList.config(state="disabled")
        self.bidVar = StringVar()
        Label(self, text="Build ID").grid(row=3, column=0, sticky='E')
        self.bidInput = Entry(
            self,
            textvariable=self.bidVar,
            width="30")
        self.bidInput.grid(
            row=3,
            column=1,
            columnspan=2,
            sticky="W")
        self.bidVar.set('latest')
        # binding unfocus for build id field
        self.bidInput.bind('<FocusOut>', self.updateBuildId)
        # binding the Return Key to each componments
        self.deviceList.bind('<Return>', self.pressReturnKey)
        self.versionList.bind('<Return>', self.pressReturnKey)
        self.engList.bind('<Return>', self.pressReturnKey)
        self.packageList.bind('<Return>', self.pressReturnKey)
        self.bidInput.bind('<Return>', self.pressReturnKey)
        self.ok.bind('<Return>', self.pressReturnKey)

    def selection_all_checked(self):
        result = False
        if len(self.deviceList.curselection()) == 0:
            self.logger.log('Please select device.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.deviceList.focus_set()
        elif len(self.versionList.curselection()) == 0:
            self.logger.log('Please select branch.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.versionList.focus_set()
        elif len(self.engList.curselection()) == 0:
            self.logger.log('Please select user or engineer build.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.engList.focus_set()
        elif len(self.packageList.curselection()) == 0:
            self.logger.log('Please select package to flash.', status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.packageList.focus_set()
        elif len(self.bidVar.get()) == 0:
            self.logger.log('Please enter build ID to flash or use "latest" to get the newest', status_callback=self.printErr)
            self.bidVar.set('latest')
        else:
            result = True
        return result

    def updateBuildId(self, event=None):
        if len(self.engList.curselection()) != 0:
            self.refreshPackageList()

    def pressReturnKey(self, event=None):
        if self.selection_all_checked():
            self.ok.config(state="disabled")
            self.confirm()

    def deviceOnSelect(self, evt):
        self.setVersionList()

    def versionOnSelect(self, evt):
        self.setEngList()

    def engOnSelect(self, evt):
        self.refreshPackageList()  # hard coded right now

    def packageOnSelect(self, evt):
        self.ok.config(state="normal")

    def confirm(self):
        self.mutex.acquire()
        try:
            if self.selection_all_checked():
                self.ok.config(state="disabled")
                params = []
                package = self.packageList.get(self.packageList.curselection()[0])
                self.logger.log('Start to flash [' + package + '].', status_callback=self.printErr)
                if(PathParser._IMAGES in package):
                    params.append(PathParser._IMAGES)
                else:
                    if(PathParser._GAIA in package):
                        params.append(PathParser._GAIA)
                    if(PathParser._GECKO in package):
                        params.append(PathParser._GECKO)
                self.controller.doFlash(params)
                self.packageList.select_clear(0, END)
                self.controller.transition(self)
        finally:
            self.mutex.release()

    def setDeviceList(self, device=[]):
        self.deviceList.delete(0, END)
        for li in device:
            self.deviceList.insert(END, li)

    def setVersionList(self, version=[]):
        if len(version) == 0:
            version = self.data[
                self.deviceList.get(self.deviceList.curselection())
                ]
        self.versionList.config(state="normal")
        self.engList.config(state="disabled")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.versionList.delete(0, END)
        for li in version:
            self.versionList.insert(END, li)

    def setEngList(self, eng=[]):
        if len(eng) == 0:
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.data[device][version]
        self.engList.config(state="normal")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.engList.delete(0, END)
        for li in eng:
            self.engList.insert(END, li)

    def refreshPackageList(self):
        self.mutex.acquire()
        try:
            self.packageList.config(state="normal")
            self.ok.config(state="normal")
            self.packageList.delete(0, END)
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.engList.get(self.engList.curselection())
            # if the value is '' or 'latest', the set the build_id option as ''.
            buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get() == 'latest') else self.bidVar.get()
            package = self.controller.getPackages(self.data[device][version][eng]['src'], build_id=buildId)
            if len(package) == 0:
                package = [PathParser._GAIA_GECKO, PathParser._GAIA, PathParser._GECKO, PathParser._IMAGES]
            for li in package:
                self.packageList.insert(END, li)
        finally:
            self.mutex.release()
Esempio n. 32
0
class TkView(object):
    def __init__(self, root):
        self.root = root
        self.columns = 26
        
        button_play = Button(self.root, 
                             text="Play", 
                             command=self.callback_play)
        
        button_stop = Button(self.root, 
                             text="Stop", 
                             command=self.callback_stop)

        button_shutdown = Button(self.root, 
                                 text="Shut down", 
                                 command=self.callback_shutdown)

        button_close = Button(self.root, 
                              text="Close", 
                              command=self.callback_close)

        self.text = Text(self.root, height=1)
        
        scrollbar = Scrollbar(self.root, width=30)
        font = tkFont.Font(size=15)
        self.listbox = Listbox(self.root, 
                               yscrollcommand=scrollbar.set,
                               selectmode=SINGLE,
                               font=font)
        self.listbox.bind("<<ListboxSelect>>", self.callback_stream_selected)
        
        scrollbar.config(command=self.listbox.yview)
        
        button_stop.place(relx=0, rely=0)
        button_play.place(relx=0.18, rely=0)
        button_close.place(relx=0.5, rely=0)
        button_shutdown.place(relx=0.7, rely=0)
        
        scrollbar.place(relx=0.9, rely=0.2, relheight=0.7)
        
        self.listbox.place(relx=0, rely=0.2, relwidth=0.9, relheight=0.7)
        self.text.place(relx=0, rely=0.9)
        self.root.protocol("WM_DELETE_WINDOW", self.callback_close)
    
    def trim_line(self, line):
        ret = line[:(self.columns-3)]
        if len(line.strip()) > self.columns:
            return  ret + '...'
        else:
            return ret

    def highlight_selected_stream(self):
        if self.selected_stream is not None:
            idx = self.stream_urls.index(self.selected_stream['url'])
            self.listbox.selection_set(idx)
            self.listbox.see(idx)
    
    def display_stream_names(self):
        def _insert_stream_name_txt(idx):
            txt = self.streams[idx]['name']
            if txt != '':
                dbg("insert_stream_name_txt: insert loop: idx: %i" %idx)
                self.listbox.delete(idx)
                self.listbox.insert(idx, self.trim_line(txt))
        for idx,stream in enumerate(self.streams):
            if self.streams[idx].has_key('name'):
                self.root.after_idle(_insert_stream_name_txt, idx)
        self.root.after_idle(self.highlight_selected_stream)
class ConstraintsView(Frame):
    "Presents all constraints created by user"

    def __init__(self, parent):
        Frame.__init__(self, parent)
        # holds all constraints
        self.constraint_name_list = []

        # holds the scrollbox output text for the added constraints
        self.constraints_output = []

        text_label = "Constraints Added:"
        self.text = Label(self, text=text_label)
        self.text.pack(anchor=NW, expand=YES)

        buttons_frame = Frame(self)
        buttons_frame.pack(side=BOTTOM)

        self.delete_all = Button(buttons_frame, text="Delete all",\
                                 command=self.delete_all_constraints)
        self.delete_all.pack(side=RIGHT, pady=10)

        self.delete_selection = Button(buttons_frame,
                                       text="Delete",
                                       command=self.delete_selection)
        self.delete_selection.pack(side=RIGHT, padx=20)

        self.yScroll = Scrollbar(self, orient=VERTICAL)
        self.yScroll.pack(side=RIGHT, fill=Y)

        self.xScroll = Scrollbar(self, orient=HORIZONTAL)
        self.xScroll.pack(side=BOTTOM, fill=X)

        self.listbox = Listbox(self, xscrollcommand = self.xScroll.set,\
                               yscrollcommand = self.yScroll.set,\
                               selectmode = MULTIPLE,\
                               width = 45, height = 20)

        self.xScroll['command'] = self.listbox.xview
        self.yScroll['command'] = self.listbox.yview

        self.listbox.pack(side=LEFT, fill=X, expand=1)

    def add_constraint_listbox(self, constraint_name, priority):
        "Updates the list box with the new constraint created"
        output = constraint_name + " Priority = "

        self.constraint_name_list.append(constraint_name)

        if priority == 10:
            output += 'Low'
        elif priority == 25:
            output += 'Medium'
        elif priority == 50:
            output += 'High'
        elif priority == 0:  # mandatory has a 0 priority
            output += 'Mandatory'

        self.constraints_output.append(output)

        # clear listbox
        self.listbox.delete(0, END)

        for item in self.constraints_output:
            self.listbox.insert(END, item)

    def delete_all_constraints(self):
        "Deletes all constraints from the listbox and the mainScheduler"
        # clear all constraints from list box
        if self.constraint_name_list:
            self.listbox.delete(0, END)

            # clear all output constraints
            self.constraints_output = []

            # clear all constraints from the scheduler object
            globs.mainScheduler.delete_list_constraints(
                self.constraint_name_list)

            #clear all constraints
            self.constraint_name_list = []

    def delete_selection(self):
        selection = self.listbox.curselection()
        selected_indices = list(selection)
        selected_indices.reverse(
        )  # go over the indices backward to prevent mistakes

        if len(selection) > 0:
            #clear constraints selected from list box
            for i in selected_indices:
                self.listbox.delete(i)

            # clear constraints from the class
            deletion_list = []
            for j in selected_indices:
                #print(self.constraint_name_list)
                #print(self.constraints_output)
                deletion_list.append(self.constraint_name_list.pop(int(j)))
                self.constraints_output.pop(int(j))
            # clear selected constraints from the scheduler object
            globs.mainScheduler.delete_list_constraints(deletion_list)
Esempio n. 34
0
class Automation(Frame):
    """The Automation class is a GUI that provides radio automation."""
    _state = None
    _button_text = None
    _button = None

    _meter = None
    _cart_queue = None

    _list_time = None
    _list_track = None
    _list_artist = None

    def __init__(self):
        """Construct an Automation window."""
        Frame.__init__(self)

        # initialize title
        title = Label(self.master, font=FONT_TITLE, text=TEXT_TITLE)
        title.grid(row=0, column=0, columnspan=3)

        # initialize button and state
        self._state = STATE_STOPPED

        self._button_text = StringVar()

        self._button = Button(self.master,
                              textvariable=self._button_text,
                              command=self._update_state,
                              width=16,
                              height=2)
        self._button.config(bd=2)
        self._button.grid(row=0, column=3)

        # initialize the meter
        self._meter = Meter(self.master, METER_WIDTH, self._get_meter_data)
        self._meter.grid(row=1, column=0, columnspan=4)

        # initialize playlist view
        playlist = Frame(self.master, bd=2, relief=Tkinter.SUNKEN)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=16,
              text=TEXT_PLAYLIST_TIME).grid(row=0, column=0)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=32,
              text=TEXT_PLAYLIST_TRACK).grid(row=0, column=1)
        Label(playlist,
              font=FONT,
              anchor=Tkinter.CENTER,
              width=32,
              text=TEXT_PLAYLIST_ARTIST).grid(row=0, column=2)

        inner_playlist = Frame(playlist)
        scroll = Scrollbar(inner_playlist,
                           orient=Tkinter.VERTICAL,
                           command=self._scroll_playlist)
        self._list_time = Listbox(inner_playlist,
                                  selectmode=Tkinter.SINGLE,
                                  yscrollcommand=scroll.set,
                                  exportselection=0,
                                  width=16,
                                  height=20)
        self._list_track = Listbox(inner_playlist,
                                   selectmode=Tkinter.SINGLE,
                                   yscrollcommand=scroll.set,
                                   exportselection=0,
                                   width=32,
                                   height=20)
        self._list_artist = Listbox(inner_playlist,
                                    selectmode=Tkinter.SINGLE,
                                    yscrollcommand=scroll.set,
                                    exportselection=0,
                                    width=32,
                                    height=20)

        scroll.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
        self._list_time.pack(side=Tkinter.LEFT,
                             fill=Tkinter.X,
                             expand=True,
                             padx=2,
                             pady=2)
        self._list_track.pack(side=Tkinter.LEFT,
                              fill=Tkinter.X,
                              expand=True,
                              padx=2,
                              pady=2)
        self._list_artist.pack(side=Tkinter.LEFT,
                               fill=Tkinter.X,
                               expand=True,
                               padx=2,
                               pady=2)

        inner_playlist.grid(row=1, column=0, columnspan=3)
        playlist.grid(row=4, column=0, columnspan=4)

        # initialize cart queue
        self._cart_queue = CartQueue(self._cart_start, self._cart_stop)
        self._cart_queue.add_tracks()
        self._update_ui()

        # begin the event loop
        self.master.protocol("WM_DELETE_WINDOW", self.master.destroy)
        self.master.title(TEXT_TITLE)
        self.master.mainloop()

    def _scroll_playlist(self, *args):
        """Scroll the playlist view.

        :param args
        """
        self._list_time.yview(*args)
        self._list_track.yview(*args)
        self._list_artist.yview(*args)

    def _update_state(self):
        """Move Automation to the next state.

        The state machine is as follows:
        STATE_STOPPED -> STATE_PLAYING -> STATE_STOPPING -> STATE_STOPPED
        """
        if self._state is STATE_STOPPED:
            print "Starting Automation..."
            self._cart_queue.start()
            self._state = STATE_PLAYING
        elif self._state is STATE_PLAYING:
            print "Stopping Automation after this track..."
            self._cart_queue.stop_soft()
            self._state = STATE_STOPPING
        elif self._state is STATE_STOPPING:
            print "Stopping Automation immediately."
            self._cart_queue.transition()
            self._state = STATE_STOPPED
        self._update_ui()

    def _cart_start(self):
        """Start the meter when a cart starts."""
        self._meter.start()
        self._update_ui()

    def _cart_stop(self):
        """Reset the meter when a cart stops.

        Also, if a soft stop occured, update the button state.
        """
        self._meter.reset()

        if self._state is STATE_STOPPING:
            self._state = STATE_STOPPED
            self._update_ui()

    def _update_ui(self):
        """Update the button and playlist."""
        self._button_text.set(TEXT_BUTTON[self._state])
        self._button.config(bg=COLOR_BUTTON[self._state],
                            highlightbackground=COLOR_BUTTON[self._state])

        self._list_time.delete(0, Tkinter.END)
        self._list_track.delete(0, Tkinter.END)
        self._list_artist.delete(0, Tkinter.END)

        for cart in self._cart_queue.get_queue():
            self._list_time.insert(Tkinter.END,
                                   cart.start_time.strftime("%I:%M:%S %p"))
            self._list_track.insert(Tkinter.END, cart.title)
            self._list_artist.insert(Tkinter.END, cart.issuer)

    def _get_meter_data(self):
        """Get meter data for the first track in the queue."""
        queue = self._cart_queue.get_queue()

        if len(queue) > 0:
            return queue[0].get_meter_data()
        else:
            return None
Esempio n. 35
0
class ShiftReduceApp(object):
    """
    A graphical tool for exploring the shift-reduce parser.  The tool
    displays the parser's stack and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can shift tokens onto the stack, and can perform reductions on the
    top elements of the stack.  A "step" button simply steps through
    the parsing process, performing the operations that
    ``nltk.parse.ShiftReduceParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingShiftReduceParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Shift Reduce Parser Application')

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animating_lock = 0
        self._animate = IntVar(self._top)
        self._animate.set(10)  # = medium

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Initialize fonts.
        self._init_fonts(self._top)

        # Set up key bindings.
        self._init_bindings()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # A popup menu for reducing.
        self._reduce_menu = Menu(self._canvas, tearoff=0)

        # Reset the demo, and set the feedback frame to empty.
        self.reset()
        self._lastoper1['text'] = ''

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkFont.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 = tkFont.Font(family='helvetica',
                                     weight='bold',
                                     size=self._size.get())
        self._font = tkFont.Font(family='helvetica', size=self._size.get())

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe,
                                     font=self._boldfont,
                                     text='Available Reductions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe,
                                 selectmode='single',
                                 relief='groove',
                                 background='white',
                                 foreground='#909090',
                                 font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if 1:  #len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe, orient='vertical')
            self._prodlist.config(yscrollcommand=listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select)

        # When they hover over a production, highlight it.
        self._hover = -1
        self._prodlist.bind('<Motion>', self._highlight_hover)
        self._prodlist.bind('<Leave>', self._clear_hover)

    def _init_bindings(self):
        # Quit
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Alt-q>', self.destroy)
        self._top.bind('<Alt-x>', self.destroy)

        # Ops (step, shift, reduce, undo)
        self._top.bind('<space>', self.step)
        self._top.bind('<s>', self.shift)
        self._top.bind('<Alt-s>', self.shift)
        self._top.bind('<Control-s>', self.shift)
        self._top.bind('<r>', self.reduce)
        self._top.bind('<Alt-r>', self.reduce)
        self._top.bind('<Control-r>', self.reduce)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<u>', self.undo)
        self._top.bind('<Alt-u>', self.undo)
        self._top.bind('<Control-u>', self.undo)
        self._top.bind('<Control-z>', self.undo)
        self._top.bind('<BackSpace>', self.undo)

        # Misc
        self._top.bind('<Control-p>', self.postscript)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

        # Animation speed control
        self._top.bind('-', lambda e, a=self._animate: a.set(20))
        self._top.bind('=', lambda e, a=self._animate: a.set(10))
        self._top.bind('+', lambda e, a=self._animate: a.set(4))

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom')
        Button(
            buttonframe,
            text='Step',
            background='#90c0d0',
            foreground='black',
            command=self.step,
        ).pack(side='left')
        Button(buttonframe,
               text='Shift',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.shift).pack(side='left')
        Button(buttonframe,
               text='Reduce',
               underline=0,
               background='#90f090',
               foreground='black',
               command=self.reduce).pack(side='left')
        Button(buttonframe,
               text='Undo',
               underline=0,
               background='#f0a0a0',
               foreground='black',
               command=self.undo).pack(side='left')

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Reset Parser',
                             underline=0,
                             command=self.reset,
                             accelerator='Del')
        filemenu.add_command(label='Print to Postscript',
                             underline=0,
                             command=self.postscript,
                             accelerator='Ctrl-p')
        filemenu.add_command(label='Exit',
                             underline=1,
                             command=self.destroy,
                             accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar',
                             underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text',
                             underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step',
                             underline=1,
                             command=self.step,
                             accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Shift',
                             underline=0,
                             command=self.shift,
                             accelerator='Ctrl-s')
        rulemenu.add_command(label='Reduce',
                             underline=0,
                             command=self.reduce,
                             accelerator='Ctrl-r')
        rulemenu.add_separator()
        rulemenu.add_command(label='Undo',
                             underline=0,
                             command=self.undo,
                             accelerator='Ctrl-u')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar",
                                 underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        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)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=20,
                                    accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=10,
                                    accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation",
                                    underline=0,
                                    variable=self._animate,
                                    value=4,
                                    accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0, command=self.about)
        helpmenu.add_command(label='Instructions',
                             underline=0,
                             command=self.help,
                             accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe,
                                     text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe,
                                foreground='#007070',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper2 = Label(lastoperframe,
                                anchor='w',
                                width=30,
                                foreground='#004040',
                                background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent,
                                   background='white',
                                   width=525,
                                   closeenough=10,
                                   border=2,
                                   relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(0,
                                                 0,
                                                 0,
                                                 0,
                                                 fill='#c0f0f0',
                                                 outline='black')
        self._exprline = canvas.create_line(0, 0, 0, 0, dash='.')
        self._stacktop = canvas.create_line(0, 0, 0, 0, fill='#408080')
        size = self._size.get() + 4
        self._stacklabel = TextWidget(canvas,
                                      'Stack',
                                      color='#004040',
                                      font=self._boldfont)
        self._rtextlabel = TextWidget(canvas,
                                      'Remaining Text',
                                      color='#004040',
                                      font=self._boldfont)
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        scrollregion = self._canvas['scrollregion'].split()
        (cx1, cy1, cx2, cy2) = [int(c) for c in scrollregion]

        # Delete the old stack & rtext widgets.
        for stackwidget in self._stackwidgets:
            self._cframe.destroy_widget(stackwidget)
        self._stackwidgets = []
        for rtextwidget in self._rtextwidgets:
            self._cframe.destroy_widget(rtextwidget)
        self._rtextwidgets = []

        # Position the titlebar & exprline
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        y = y2 - y1 + 10
        self._canvas.coords(self._titlebar, -5000, 0, 5000, y - 4)
        self._canvas.coords(self._exprline, 0, y * 2 - 10, 5000, y * 2 - 10)

        # Position the titlebar labels..
        (x1, y1, x2, y2) = self._stacklabel.bbox()
        self._stacklabel.move(5 - x1, 3 - y1)
        (x1, y1, x2, y2) = self._rtextlabel.bbox()
        self._rtextlabel.move(cx2 - x2 - 5, 3 - y1)

        # Draw the stack.
        stackx = 5
        for tok in self._parser.stack():
            if isinstance(tok, Tree):
                attribs = {
                    'tree_color': '#4080a0',
                    'tree_width': 2,
                    'node_font': self._boldfont,
                    'node_color': '#006060',
                    'leaf_color': '#006060',
                    'leaf_font': self._font
                }
                widget = tree_to_treesegment(self._canvas, tok, **attribs)
                widget.node()['color'] = '#000000'
            else:
                widget = TextWidget(self._canvas,
                                    tok,
                                    color='#000000',
                                    font=self._font)
            widget.bind_click(self._popup_reduce)
            self._stackwidgets.append(widget)
            self._cframe.add_widget(widget, stackx, y)
            stackx = widget.bbox()[2] + 10

        # Draw the remaining text.
        rtextwidth = 0
        for tok in self._parser.remaining_text():
            widget = TextWidget(self._canvas,
                                tok,
                                color='#000000',
                                font=self._font)
            self._rtextwidgets.append(widget)
            self._cframe.add_widget(widget, rtextwidth, y)
            rtextwidth = widget.bbox()[2] + 4

        # Allow enough room to shift the next token (for animations)
        if len(self._rtextwidgets) > 0:
            stackx += self._rtextwidgets[0].width()

        # Move the remaining text to the correct location (keep it
        # right-justified, when possible); and move the remaining text
        # label, if necessary.
        stackx = max(stackx, self._stacklabel.width() + 25)
        rlabelwidth = self._rtextlabel.width() + 10
        if stackx >= cx2 - max(rtextwidth, rlabelwidth):
            cx2 = stackx + max(rtextwidth, rlabelwidth)
        for rtextwidget in self._rtextwidgets:
            rtextwidget.move(4 + cx2 - rtextwidth, 0)
        self._rtextlabel.move(cx2 - self._rtextlabel.bbox()[2] - 5, 0)

        midx = (stackx + cx2 - max(rtextwidth, rlabelwidth)) / 2
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)
        (x1, y1, x2, y2) = self._stacklabel.bbox()

        # Set up binding to allow them to shift a token by dragging it.
        if len(self._rtextwidgets) > 0:

            def drag_shift(widget, midx=midx, self=self):
                if widget.bbox()[0] < midx: self.shift()
                else: self._redraw()

            self._rtextwidgets[0].bind_drag(drag_shift)
            self._rtextwidgets[0].bind_click(self.shift)

        # Draw the stack top.
        self._highlight_productions()

    def _draw_stack_top(self, widget):
        # hack..
        midx = widget.bbox()[2] + 50
        self._canvas.coords(self._stacktop, midx, 0, midx, 5000)

    def _highlight_productions(self):
        # Highlight the productions that can be reduced.
        self._prodlist.selection_clear(0, 'end')
        for prod in self._parser.reducible_productions():
            index = self._productions.index(prod)
            self._prodlist.selection_set(index)

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset App'
        self._lastoper2['text'] = ''
        self._redraw()

    def step(self, *e):
        if self.reduce(): return 1
        elif self.shift(): return 1
        else:
            if len(self._parser.parses()) > 0:
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Success'
            else:
                self._lastoper1['text'] = 'Finished:'
                self._lastoper2['text'] = 'Failure'

    def shift(self, *e):
        if self._animating_lock: return
        if self._parser.shift():
            tok = self._parser.stack()[-1]
            self._lastoper1['text'] = 'Shift:'
            self._lastoper2['text'] = '%r' % tok
            if self._animate.get():
                self._animate_shift()
            else:
                self._redraw()
            return 1
        return 0

    def reduce(self, *e):
        if self._animating_lock: return
        production = self._parser.reduce()
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        return production

    def undo(self, *e):
        if self._animating_lock: return
        if self._parser.undo():
            self._redraw()

    def postscript(self, *e):
        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)

    #########################################
    ##  Menubar callbacks
    #########################################

    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._stacklabel['font'] = ('helvetica', -size-4, 'bold')
        #self._rtextlabel['font'] = ('helvetica', -size-4, 'bold')
        #self._lastoper_label['font'] = ('helvetica', -size)
        #self._lastoper1['font'] = ('helvetica', -size)
        #self._lastoper2['font'] = ('helvetica', -size)
        #self._prodlist['font'] = ('helvetica', -size)
        #self._prodlist_label['font'] = ('helvetica', -size-2, 'bold')
        self._redraw()

    def help(self, *e):
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top,
                     'Help: Shift-Reduce Parser Application', (__doc__
                                                               or '').strip(),
                     width=75,
                     font='fixed')
        except:
            ShowText(self._top,
                     'Help: Shift-Reduce Parser Application', (__doc__
                                                               or '').strip(),
                     width=75)

    def about(self, *e):
        ABOUT = ("NLTK Shift-Reduce Parser Application\n" +
                 "Written by Edward Loper")
        TITLE = 'About: Shift-Reduce Parser Application'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = string.join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sent):
        self._sent = sent.split()  #[XX] use tagged?
        self.reset()

    #########################################
    ##  Reduce Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both',
                                 side='left',
                                 padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        production = self._parser.reduce(self._productions[index])
        if production:
            self._lastoper1['text'] = 'Reduce:'
            self._lastoper2['text'] = '%s' % production
            if self._animate.get():
                self._animate_reduce()
            else:
                self._redraw()
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.reducible_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    def _popup_reduce(self, widget):
        # Remove old commands.
        productions = self._parser.reducible_productions()
        if len(productions) == 0: return

        self._reduce_menu.delete(0, 'end')
        for production in productions:
            self._reduce_menu.add_command(label=str(production),
                                          command=self.reduce)
        self._reduce_menu.post(self._canvas.winfo_pointerx(),
                               self._canvas.winfo_pointery())

    #########################################
    ##  Animations
    #########################################

    def _animate_shift(self):
        # What widget are we shifting?
        widget = self._rtextwidgets[0]

        # Where are we shifting from & to?
        right = widget.bbox()[0]
        if len(self._stackwidgets) == 0: left = 5
        else: left = self._stackwidgets[-1].bbox()[2] + 10

        # Start animating.
        dt = self._animate.get()
        dx = (left - right) * 1.0 / dt
        self._animate_shift_frame(dt, widget, dx)

    def _animate_shift_frame(self, frame, widget, dx):
        if frame > 0:
            self._animating_lock = 1
            widget.move(dx, 0)
            self._top.after(10, self._animate_shift_frame, frame - 1, widget,
                            dx)
        else:
            # but: stacktop??

            # Shift the widget to the stack.
            del self._rtextwidgets[0]
            self._stackwidgets.append(widget)
            self._animating_lock = 0

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

    def _animate_reduce(self):
        # What widgets are we shifting?
        numwidgets = len(self._parser.stack()[-1])  # number of children
        widgets = self._stackwidgets[-numwidgets:]

        # How far are we moving?
        if isinstance(widgets[0], TreeSegmentWidget):
            ydist = 15 + widgets[0].node().height()
        else:
            ydist = 15 + widgets[0].height()

        # Start animating.
        dt = self._animate.get()
        dy = ydist * 2.0 / dt
        self._animate_reduce_frame(dt / 2, widgets, dy)

    def _animate_reduce_frame(self, frame, widgets, dy):
        if frame > 0:
            self._animating_lock = 1
            for widget in widgets:
                widget.move(0, dy)
            self._top.after(10, self._animate_reduce_frame, frame - 1, widgets,
                            dy)
        else:
            del self._stackwidgets[-len(widgets):]
            for widget in widgets:
                self._cframe.remove_widget(widget)
            tok = self._parser.stack()[-1]
            if not isinstance(tok, Tree): raise ValueError()
            label = TextWidget(self._canvas,
                               str(tok.node),
                               color='#006060',
                               font=self._boldfont)
            widget = TreeSegmentWidget(self._canvas, label, widgets, width=2)
            (x1, y1, x2, y2) = self._stacklabel.bbox()
            y = y2 - y1 + 10
            if not self._stackwidgets: x = 5
            else: x = self._stackwidgets[-1].bbox()[2] + 10
            self._cframe.add_widget(widget, x, y)
            self._stackwidgets.append(widget)

            # Display the available productions.
            self._draw_stack_top(widget)
            self._highlight_productions()

            #             # Delete the old widgets..
            #             del self._stackwidgets[-len(widgets):]
            #             for widget in widgets:
            #                 self._cframe.destroy_widget(widget)
            #
            #             # Make a new one.
            #             tok = self._parser.stack()[-1]
            #             if isinstance(tok, Tree):
            #                 attribs = {'tree_color': '#4080a0', 'tree_width': 2,
            #                            'node_font': bold, 'node_color': '#006060',
            #                            'leaf_color': '#006060', 'leaf_font':self._font}
            #                 widget = tree_to_treesegment(self._canvas, tok.type(),
            #                                              **attribs)
            #                 widget.node()['color'] = '#000000'
            #             else:
            #                 widget = TextWidget(self._canvas, tok.type(),
            #                                     color='#000000', font=self._font)
            #             widget.bind_click(self._popup_reduce)
            #             (x1, y1, x2, y2) = self._stacklabel.bbox()
            #             y = y2-y1+10
            #             if not self._stackwidgets: x = 5
            #             else: x = self._stackwidgets[-1].bbox()[2] + 10
            #             self._cframe.add_widget(widget, x, y)
            #             self._stackwidgets.append(widget)

            #self._redraw()
            self._animating_lock = 0

    #########################################
    ##  Hovering.
    #########################################

    def _highlight_hover(self, event):
        # What production are we hovering over?
        index = self._prodlist.nearest(event.y)
        if self._hover == index: return

        # Clear any previous hover highlighting.
        self._clear_hover()

        # If the production corresponds to an available reduction,
        # highlight the stack.
        selection = [int(s) for s in self._prodlist.curselection()]
        if index in selection:
            rhslen = len(self._productions[index].rhs())
            for stackwidget in self._stackwidgets[-rhslen:]:
                if isinstance(stackwidget, TreeSegmentWidget):
                    stackwidget.node()['color'] = '#00a000'
                else:
                    stackwidget['color'] = '#00a000'

        # Remember what production we're hovering over.
        self._hover = index

    def _clear_hover(self, *event):
        # Clear any previous hover highlighting.
        if self._hover == -1: return
        self._hover = -1
        for stackwidget in self._stackwidgets:
            if isinstance(stackwidget, TreeSegmentWidget):
                stackwidget.node()['color'] = 'black'
            else:
                stackwidget['color'] = 'black'
Esempio n. 36
0
class DualBox(Frame):
    """The DualBox class is a pair of Listboxes that has a list of carts."""
    _prev_index = None
    _select_callback = None

    _list_box1 = None
    _list_box2 = None

    def __init__(self, parent):
        """Construct a DualBox.

        :param parent
        """
        Frame.__init__(self)
        self._select_callback = parent.select_cart

        # make scroll bar
        scroll_bar = Scrollbar(self,
                               orient=Tkinter.VERTICAL,
                               command=self._scroll_bar)

        label1 = Label(self, text=TEXT_LABEL1)
        label2 = Label(self, text=TEXT_LABEL2)

        # make two scroll boxes
        self._list_box1 = Listbox(self,
                                  yscrollcommand=scroll_bar.set,
                                  exportselection=0,
                                  width=40)
        self._list_box2 = Listbox(self,
                                  yscrollcommand=scroll_bar.set,
                                  exportselection=0,
                                  width=40)

        # fill the whole screen - pack!
        scroll_bar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)

        label1.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True)
        self._list_box1.pack(side=Tkinter.LEFT,
                             fill=Tkinter.X,
                             expand=True,
                             padx=5,
                             pady=5)
        self._list_box2.pack(side=Tkinter.LEFT,
                             fill=Tkinter.X,
                             expand=True,
                             padx=5,
                             pady=5)
        label2.pack(side=Tkinter.LEFT, fill=Tkinter.X, expand=True)

        # mouse wheel binding
        self._list_box1.bind("<MouseWheel>", self._scroll_wheel)
        self._list_box2.bind("<MouseWheel>", self._scroll_wheel)

        # onclick binding?
        self._list_box1.bind("<<ListboxSelect>>", self.select)
        self._list_box2.bind("<<ListboxSelect>>", self.select)

    def fill(self, carts):
        """Fill the DualBox with a list of carts.

        :param carts: array of carts
        """
        self._list_box1.delete(0, Tkinter.END)
        self._list_box2.delete(0, Tkinter.END)

        for cart in carts:
            self._list_box1.insert(Tkinter.END, cart.title)
            self._list_box2.insert(Tkinter.END, cart.issuer)

    def _get_selected_index(self):
        one = self._list_box1.curselection()
        two = self._list_box2.curselection()

        if len(one) is 0:
            one = None
        else:
            one = one[0]

        if len(two) is 0:
            two = None
        else:
            two = two[0]

        if one is not None and two is not None:
            if one == self._prev_index:
                self._prev_index = two
            elif two == self._prev_index:
                self._prev_index = one
        elif one is not None:
            self._prev_index = one
        elif two is not None:
            self._prev_index = two

        return self._prev_index

    def select(self, *args):
        """Select an item in the DualBox.

        :param args
        """
        index = self._get_selected_index()

        if index is not None:
            self._list_box1.selection_clear(0, Tkinter.END)
            self._list_box2.selection_clear(0, Tkinter.END)
            self._list_box1.selection_set(index, index)
            self._list_box2.selection_set(index, index)

        self._select_callback(index)

    def _scroll_bar(self, *args):
        """Scroll the list boxes with the vertical scroll bar.

        :param args
        """
        self._list_box1.yview(*args)
        self._list_box2.yview(*args)

    def _scroll_wheel(self, event):
        """Scroll the list boxes with the mouse wheel.

        :param event
        """
        self._list_box1.yview("scroll", event.delta, "units")
        self._list_box2.yview("scroll", event.delta, "units")
        # this prevents default bindings from firing, which
        # would end up scrolling the widget twice
        return "break"
Esempio n. 37
0
class GameView:
    def __init__(self, container, main_ui, digits, types, players,
                 game_started):
        self.main_ui = main_ui

        self.frame_left = Frame(container)
        self.frame_left.pack(side=LEFT, padx=20, pady=20)

        self.scoreFont = tkFont.Font(family="Helvetica", size=15)

        self.game = SudokuGame(digits, types)
        self.game.start()  # Start game
        self.UI = SudokuUI(self.frame_left, self.game,
                           main_ui)  # Display sudoku board

        self.frame_right = Frame(container)
        self.frame_right.pack(side=RIGHT, padx=20, pady=10)

        games_txt = Label(self.frame_right, text="Scoreboard")
        games_txt.pack(side=TOP)

        self.games_lb = Listbox(self.frame_right,
                                bg="gray99",
                                selectbackground="gray99",
                                height=6)
        self.games_lb.bind("<<ListboxSelect>>", self.no_selection)
        self.games_lb.pack()
        self.fill_players(players)

        self.waiting_txt = None
        if not game_started:
            self.waiting_txt = Label(
                self.frame_left,
                text="Waiting for players. Game has not started.",
                font=("Arial", 14),
                bg="red")
            self.waiting_txt.pack(fill=X)

        self.exitButton = Button(self.frame_right,
                                 text="Exit game",
                                 command=self.exit_game)
        self.exitButton.pack(padx=10, pady=10)

    def update_board(self, digits, types):
        #ugly hack for handling empty heatmap, not necessary to receive it every time from server
        if (types == ""):
            heatmap_str = ""
            types = self.game.heatmap
            for row in types:
                row = [str(r) for r in row]
                row_str = ",".join(row)
                heatmap_str += row_str + ","
            types = heatmap_str
            types = types[:-1]
        game = SudokuGame(digits, types)
        game.start()
        i, j, number = self.get_updated_digit(game.puzzle, self.game.puzzle)
        if (i != None and j != None and number != None):
            self.game = game
            self.UI.draw_update(i, j, number)

    def get_updated_digit(self, new_digit, old_digit):
        for i in range(0, 9):
            for j in range(0, 9):
                if (new_digit[i][j] != old_digit[i][j]):
                    return i, j, new_digit[i][j]
        return None, None, None

    def show_end(self, content):
        self.UI.draw_victory(content)

    def fill_players(self, players):
        self.games_lb.delete(0, END)
        for idx, val in enumerate(players):  # Insert all games to the list
            self.games_lb.insert(idx, val)
        self.games_lb.pack()

    def add_player(self, player):
        self.games_lb.insert(END, player)
        self.games_lb.pack()

    def hide_waiting_txt(self):
        if self.waiting_txt is not None:
            self.waiting_txt.pack_forget()

    def no_selection(self, event):
        w = event.widget
        cur = w.curselection()
        if len(cur) > 0:
            w.selection_clear(cur)

    def exit_game(self):
        self.main_ui.leave_game()
Esempio n. 38
0
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()
Esempio n. 39
0
class TrackSelect(tkSimpleDialog.Dialog):

    def __init__(self, master, **kwargs):
        self.vid = {'title': "this video"}
        self.tracks = []
        for k in kwargs:
            k = k.lower()
            if k == "master":
                self.master = kwargs[k]
                continue
            if k == "vid":
                self.vid = kwargs[k]
                continue
            if k == "tracks":
                self.tracks = kwargs[k]
                continue

        self.padx = 3
        self.pady = 3
        self.prefl = IntVar()
        self.preft = IntVar()
        self.preflang = None
        self.prefname = None
        tkSimpleDialog.Dialog.__init__(self, master, "Select caption track")

    def body(self, master):
        Label(master, text="%s contains multiple caption tracks" %
              self.vid['title']).grid(row=0, padx=self.padx, pady=self.pady,
                                      sticky=W, columnspan=5)
        self.__langlist(master)
        self.chosenlangbut = Button(master, text="->",
                                    command=self.__chooselang)
        self.chosenlangbut.grid(row=1, column=2, padx=self.padx,
                                pady=self.pady)
        self.__tracklist(master)
        self.__fillLangs()
        return self.langsel  # initial focus

    def __tracklist(self, master):
        self.trackYscroll = Scrollbar(master, orient=HORIZONTAL)
        self.trackXscroll = Scrollbar(master, orient=VERTICAL)
        self.tracksel = Listbox(master,
                               xscrollcommand=self.trackXscroll.set,
                               yscrollcommand=self.trackYscroll.set,
                               selectmode=SINGLE)
        self.tracksel.grid(row=1, column=3, sticky=N + S + E + W)
        self.trackXscroll.grid(row=1, column=4, sticky=W + N + S)
        self.trackYscroll.grid(row=2, column=3, stick=N + E + W)
        self.trackXscroll.config(command=self.tracksel.xview)
        self.trackYscroll.config(command=self.tracksel.yview)
        self.preftracksel = Checkbutton(master,
                                        variable=self.preft,
                                        text="Set default track name")
        self.preftracksel.grid(row=3, column=3, sticky=W)

    def __langlist(self, master):
        self.langYscroll = Scrollbar(master, orient=HORIZONTAL)
        self.langXscroll = Scrollbar(master, orient=VERTICAL)
        self.langsel = Listbox(master,
                               xscrollcommand=self.langXscroll.set,
                               yscrollcommand=self.langYscroll.set,
                               selectmode=SINGLE, width=6)
        self.langsel.grid(row=1, column=0, sticky=N + S + E + W)
        self.langXscroll.grid(row=1, column=1, sticky=W + N + S)
        self.langYscroll.grid(row=2, column=0, stick=N + E + W)
        self.langXscroll.config(command=self.langsel.xview)
        self.langYscroll.config(command=self.langsel.yview)
        self.preflangsel = Checkbutton(master,
                                       variable=self.prefl,
                                       text="Set default language")
        self.preflangsel.grid(row=3, column=0, sticky=W)

    def __fillLangs(self):
        self.langsadded = []
        for track in self.tracks:
            lang = track['lang']
            if lang not in self.langsadded:
                self.langsel.insert(END, lang)
                self.langsadded.append(lang)

    def __chooselang(self):
        lang = self.langsadded[int(self.langsel.curselection()[0])]
        self.langselected = lang
        self.trackoptions = []
        self.tracksel.delete(0, END)
        for track in self.tracks:
            if track['lang'] == lang:
                name = 'Default' if len(track['name']) == 0 else track['name']
                self.tracksel.insert(END, name)
                self.trackoptions.append(track)
        self.tracksel.activate(0)
        self.tracksel.selection_set(0)

    def apply(self):
        selected = int(self.tracksel.curselection()[0])
        self.result = [self.trackoptions[selected]]
        if int(self.prefl.get()) == 1:
            self.preflang = self.langselected
        if int(self.preft.get()) == 1:
            self.prefname = self.trackoptions[
                    int(self.tracksel.curselection()[0])]['name']

    def buttonbox(self):
        box = Frame(self)

        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Skip", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.cancel)

        box.pack()
Esempio n. 40
0
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)
Esempio n. 41
0
class Ordered_Listbox(Frame):
    def __init__(self,
                 master,
                 data=None,
                 ascending_order=True,
                 ignore_case=False,
                 autoscroll=False,
                 vscrollbar=True,
                 hscrollbar=False,
                 scrollbar_background=None,
                 scrollbar_troughcolor=None,
                 **kwargs):
        Frame.__init__(self, master)

        self._ignore_case = ignore_case
        self._ascending_order = ascending_order

        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        self._listbox = Listbox(self, *kwargs)
        self._listbox.grid(row=0, column=0, sticky=N + E + W + S)

        scrollbar_kwargs = {}
        if scrollbar_background is not None:
            scrollbar_kwargs["background"] = scrollbar_background

        if scrollbar_troughcolor is not None:
            scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor

        if vscrollbar:
            self._vbar = Scrollbar(self,
                                   takefocus=0,
                                   command=self._listbox.yview,
                                   **scrollbar_kwargs)
            self._vbar.grid(row=0, column=1, sticky=N + S)

            if autoscroll:
                self._listbox.config(yscrollcommand=lambda f, l:
                                     make_autoscroll(self._vbar, f, l))
            else:
                self._listbox.config(yscrollcommand=self._vbar.set)

        if hscrollbar:
            self._hbar = Scrollbar(self,
                                   takefocus=0,
                                   command=self._listbox.xview,
                                   **scrollbar_kwargs)
            self._hbar.grid(row=0, column=1, sticky=E + W)

            if autoscroll:
                self._listbox.config(xscrollcommand=lambda f, l:
                                     make_autoscroll(self._hbar, f, l))
            else:
                self._listbox.config(xscrollcommand=self._hbar.set)

        if data is not None:
            for item in data:
                self.add_item(item)

    def add_item(self, item):
        list_of_items = self._listbox.get(0, END)

        index = bisect(list_of_items,
                       item,
                       ignore_case=self._ignore_case,
                       ascending_order=self._ascending_order)
        self._listbox.insert(index, item)

    def delete_item(self, item):
        list_of_items = self._listbox.get(0, END)
        index = bisect(list_of_items,
                       item,
                       ignore_case=self._ignore_case,
                       ascending_order=self._ascending_order)
        self._listbox.delete(index - 1)

    def selected_items(self):
        list_of_items = []

        for index in self._listbox.curselection():
            list_of_items.append(self._listbox.get(index))

        return list_of_items

    def selected_item(self):
        return self._listbox.curselection()[0]

    def deselect_all(self):
        self._listbox.selection_clear(0, END)

    def select(self, item):
        index = self.index(item)

        if index is None:
            return

        self._listbox.selection_set(index)

    def deselect(self, item):
        index = self.index(item)

        if index is None:
            return

        self._listbox.selection_clear(index)

    def index(self, item):
        list_of_items = self._listbox.get(0, END)

        try:
            index = list_of_items.index(item)
        except ValueError:
            return None

        return index

    def bind(self, event, handler):
        self._listbox.bind(event, handler)

    def clear(self):
        self._listbox.delete(1, END)

    def __iter__(self):
        return self.items

    @property
    def items(self):
        return self._listbox.get(0, END)
Esempio n. 42
0
class AutocompleteEntry(Entry):

    def __init__(self, *args, **kwargs):
        Entry.__init__(self, width=100, *args, **kwargs)

        self.focus_set()
        self.pack()

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.up)
        self.bind("<Down>", self.down)
        self.bind("<Return>", self.enter)
        self.lb_up = False
        self.lb = None

    def enter(self, event):
        print event

    def changed(self, name, index, mode):

        if self.var.get() == '':
            if self.lb:
                self.lb.destroy()
            self.lb_up = False
        else:
            words = self.comparison()
            if words:
                if not self.lb_up:
                    self.lb = Listbox(master=root, width=100)

                    self.lb.bind("<Double-Button-1>", self.selection)
                    self.lb.bind("<Right>", self.selection)
                    self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height())
                    self.lb_up = True

                self.lb.delete(0, END)
                for w in words:
                    self.lb.insert(END,w)
            else:
                if self.lb_up:
                    self.lb.destroy()
                    self.lb_up = False

    def selection(self, _):

        if self.lb_up:
            self.var.set(self.lb.get(ACTIVE))
            self.lb.destroy()
            self.lb_up = False
            self.icursor(END)

    def up(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != '0':
                self.lb.selection_clear(first=index)
                index = str(int(index)-1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def down(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != END:
                self.lb.selection_clear(first=index)
                index = str(int(index)+1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def comparison(self):
        q = self.var.get()
        q = unicode(q.decode('utf8'))
        for hit in searcher.search(qp.parse(q), limit=50):
            if hit['author']:
                yield '%s. "%s"' % (hit['author'], hit['title'])
            else:
                yield hit['title']
Esempio n. 43
0
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()
Esempio n. 44
0
class ListFrame(LabelFrame):
    """
    A Frame representing one of the search term lists
    (e.g. Hashtags, Excluded Users).

    Displays all the items in the list,
    and allows the user to add or remove items.
    Methods should not be called directly;
    instead they should be bound as event handlers.
    """
    def __init__(self, name, add_handler, remove_handler, master=None):
        """
        Creates a ListFrame with the given name as its title.

        add_handler and remove_handler are functions to be called
        when items are added or removed, and should relay the information
        back to the Searcher (or whatever object actually uses the list).
        """
        LabelFrame.__init__(self, master)
        self['text'] = name
        self.add_handler = add_handler
        self.remove_handler = remove_handler
        self.list = Listbox(self)
        self.list.grid(row=0, columnspan=2)
        # Tkinter does not automatically close the right-click menu for us,
        # so we must close it when the user clicks away from the menu.
        self.list.bind("<Button-1>", lambda event: self.context_menu.unpost())
        self.list.bind("<Button-3>", self.open_menu)
        self.context_menu = Menu(self, tearoff=0)
        self.context_menu.add_command(label="Remove", command=self.remove)
        self.input = Entry(self)
        self.input.bind("<Return>", lambda event: self.add())
        self.input.grid(row=1, columnspan=2)
        self.add_button = Button(self)
        self.add_button['text'] = "Add"
        self.add_button['command'] = self.add
        self.add_button.grid(row=2, column=0, sticky=W + E)
        self.remove_button = Button(self)
        self.remove_button['text'] = "Remove"
        self.remove_button['command'] = self.remove
        self.remove_button.grid(row=2, column=1, sticky=W + E)

    def add(self):
        """
        Add the item in the input line to the list.
        """
        self.list.insert(END, self.input.get())
        self.add_handler(self.input.get())
        self.input.delete(0, END)

    def remove(self):
        """
        Remove the active (highlighted) item from the list.
        """
        deleted = self.list.get(ACTIVE)
        self.list.delete(ACTIVE)
        self.remove_handler(deleted)

    def open_menu(self, event):
        """
        Opens a right-click menu for the selected item.
        Currently the menu only has an option for removing the item.
        """
        index = self.list.index("@" + str(event.x) + "," + str(event.y))
        if index < 0:
            return
        self.context_menu.post(event.x_root, event.y_root)
        self.list.activate(index)
        self.list.selection_clear(0, END)
        self.list.selection_set(ACTIVE)
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 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)
Esempio n. 47
0
class photGUI(Frame):
    """The base class for the phot_calc GUI"""
    
    # This is the constructor for the GUI
    def __init__(self,master=None):
        # We begin by calling the base class's constructor first
        Frame.__init__(self,master)
    
        # We now have an empty window!
        
        # This command sets up a grid structure in the window
        self.grid()
        
        # This loop generates rows and columns in the grid
        for i in range(13):
            self.rowconfigure(i,minsize=10)
        for i in range(3):
            self.columnconfigure(i,minsize=30)
        
        # These are methods which appear below the constructor
        self.defineUnits() # this sets up the units I'll be using in the converter
        self.createWidgets() # this places the elements (or widgets) in the grid
        
        # This command "binds" the user's click to a method (varChoice)
        # This method will determine which variable the user wants (Distance, Mass, Time)
        self.inputlist.bind("<Button-1>",self.__varChoice)
    
        # This is a similar command for the selection of unit
        self.unitlist.bind("<Button-1>",self.__unitChoice)
    
        # Finally, this bind reads in whatever value is in the text box when the user hits return
        # and carries out the unit conversion
        
        self.inputfield.bind("<Return>",self.__calcConversion)
    
    # This function creates and defines the units
    
    def defineUnits(self):
        '''Method defines tuples that carry the various units stored by the converter'''
        
        self.speed = 2.997924580000019e10
        self.h = 6.6260755e-27     
        # Wavelengths
        
        self.wavunits = ('nm','um', 'cm','m')
        self.wavvalues = (1.0e-7, 1.0e-4,1.0,1.0e2)
        
        self.frequnits = ('Hz','MHz','GHz','THz')
        self.freqvalues = (1.0, 1.0e6, 1.0e9, 1.0e12)
        
        self.energunits = ('eV','keV','MeV','GeV','erg')
        self.energvalues = (1.0,1.0e3,1.0e6,1.0e9,1.6e-12)
        
        # Keep the unit values in dictionaries, and use the above strings as keys
        
        self.wavdict = {}        
        self.createUnitDict(self.wavdict,self.wavunits,self.wavvalues) # this method is shown below
        
        self.freqdict = {}
        self.createUnitDict(self.freqdict,self.frequnits,self.freqvalues)
        
        self.energdict = {}
        self.createUnitDict(self.energdict, self.energunits, self.energvalues)  
    
        self.myunits = self.wavunits
        self.myvalues = self.wavvalues
        self.mydict = self.wavdict
    
        
    def createUnitDict(self,mydict,mykeys,myvalues):
        '''This method takes a set of units and values, and creates a dictionary to store them in'''
        for i in range(len(myvalues)):
            mydict[mykeys[i]] = myvalues[i]
               
    def createWidgets(self):
        '''This method creates all widgets and adds them to the GUI'''
        
        # Create Widgets in order of appearance
        # This is not necessary, but makes code easier to read
        
        # Start with text telling user what to do
        self.varlabel = Text(self,height=1, width=20)
        self.varlabel.insert(END,"Which Variable?")
        
        # Place widget on the Frame according to a grid
        self.varlabel.grid(row=0,column=0,sticky=W)
        
        # Second text label asking user which units are being used
        self.unitlabel = Text(self,height=1,width=20)
        self.unitlabel.insert(END,"Which Units?")
        self.unitlabel.grid(row=0,column=1,sticky=W)
        
        # Third text label asking user for numerical value
        
        self.numlabel = Text(self,height=1, width=20)
        self.numlabel.insert(END,"Enter Variable Values")
        self.numlabel.grid(row=0,column=2,sticky=W)
        
        # This creates a list of options for the user to select
        self.inputlist = Listbox(self, height=4, selectmode=SINGLE)
      
        # Tuple of choices we're going to put in this list
        self.paramlist = ('Frequency', 'Wavelength', 'Energy')
        
        # Add each item separately
        for item in self.paramlist:
            self.inputlist.insert(END,item)
            
        # Add it to the grid    
        self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W)
        
        # Add a unit list (several combinations of units allowed)
        
        self.unitlist = Listbox(self, height=4,selectmode=SINGLE)
        self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W)
    
        # Number Entry Boxes (and Text Labels)
        
        self.inputlabel = Text(self,height=1,width=20)
        self.inputlabel.insert(END,"Waiting Selection")
        self.inputlabel.grid(row=1,column=2,sticky=W)
        
        self.inputfield = Entry(self)
        self.inputfield.grid(row=2,column=2,sticky=W)
        
        # Text Output Boxes
        self.wavoutput = Text(self, height=5, width=20)
        self.wavoutput.grid(row=7,column=0,rowspan=5,sticky=W)
        self.wavoutput.insert(END, "Wavelength: \n")
        
        self.freqoutput = Text(self, height=5, width=20)
        self.freqoutput.grid(row=7,column=1,rowspan=5,sticky=W)
        self.freqoutput.insert(END, "Frequency: \n")
        
        self.energoutput = Text(self, height=5, width=20)
        self.energoutput.grid(row=7,column=2,rowspan=5,sticky=W)
        self.energoutput.insert(END, "Energy: \n")
        
        # Create the Quit Button
        self.quitButton=Button(self,text='Quit',command=self.quit)
        self.quitButton.grid(row =13, column=0, sticky=W)
             

    # Event handler functions begin here    
    # This handler defines the choice of units available to the user, 
    # depending on selected variable
    
    def __varChoice(self, event):
        '''Handles the selection of variable: updates the list of units'''
        # Firstly, delete anything already in the units column
        self.unitlist.delete(first=0,last=len(self.myvalues))
        num = 0
        
        # Identify which option was clicked on
        try:
            num = self.inputlist.curselection()[0]       
            self.varchoice = int(num)
            
        except:
            self.varchoice = 0
            return
        
        # Get the string associated with this choice
        selection= self.inputlist.get(self.varchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.inputlist.itemconfig(self.varchoice, selectbackground='red')
        
        # If statement defines units being used
        if selection =='Wavelength':
            self.myunits = self.wavunits
            self.myvalues = self.wavvalues
            self.mydict = self.wavdict
        elif selection == 'Frequency':
            self.myunits = self.frequnits
            self.myvalues = self.freqvalues
            self.mydict = self.freqdict
        elif selection == 'Energy':
            self.myunits = self.energunits
            self.myvalues = self.energvalues
            self.mydict = self.energdict
            
        
        self.inputlabel.delete("1.0",index2=END)
        self.inputlabel.insert(END,selection)
        
        
        for i in range(len(self.myunits)):
            self.unitlist.insert(END,self.myunits[i])
        
    def __unitChoice(self,event):
        '''Handles the selection of units'''
        num = 0
        # Find which number is selected
        try:
            num = self.unitlist.curselection()[0]       
            self.unitchoice = int(num)
            
        except:
            self.unitchoice = 0
            return
        
        # Get the string (i.e. which unit is selected)
        selection= self.unitlist.get(self.unitchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.unitlist.itemconfig(self.unitchoice, selectbackground='red')
        
    # Handler takes current state of GUI, and calculates results
    def __calcConversion(self,event):
        '''This method takes the current state of all GUI variables, calculates one of four equations'''
        
        # Which variable has been selected for calculation?
        # This decides what equation to use
        
        a = self.inputfield.get()
        var = self.unitlist.get(self.unitchoice)
        a=float(a)
        
        freq = 0.0
        wav = 0.0
        energy = 0.0
        
        if self.varchoice==0:
            freq = a
            freq = freq*self.mydict[var]
            wav = self.speed/freq
            energy = self.h*freq/self.energdict['erg']
            
        elif self.varchoice==1:
            wav = a
            wav = wav*self.mydict[var]
            freq = self.speed/wav
            energy = self.speed*self.h/wav
            
        elif self.varchoice==2:
            energy = a
            energy=energy*self.energdict["erg"]
            freq = energy/self.h
            wav = self.speed*self.h/energy
            energy = energy*self.mydict[var]/self.energdict["erg"]
        
        # Remove all text in the output boxes
        self.wavoutput.delete("1.0",index2=END)
        self.freqoutput.delete("1.0",index2=END)
        self.energoutput.delete("1.0",index2=END)
        
        self.wavoutput.insert(END, "Wavelength: \n")
        self.freqoutput.insert(END, "Frequency: \n")
        self.energoutput.insert(END, "Energy: \n")
        
        # Calculate each conversion and output it to the GUI
        for i in range(len(self.wavvalues)):
            # As all units stored in cgs values, conversion is simple
            output = wav/self.wavvalues[i]
            
            # Express output in 
            
            # Add to the output list
            self.wavoutput.insert(END,self.wavunits[i] + ":  %.4e" % output+"\n")  
            
            
        for i in range(len(self.freqvalues)):
            # As all units stored in cgs values, conversion is simple
            output = freq/self.freqvalues[i]
            # Add to the output list
            self.freqoutput.insert(END,self.frequnits[i] + ":  %.4e" % output+"\n")        
            
        for i in range(len(self.energvalues)):
            # As all units stored in cgs values, conversion is simple
            output = energy/self.energvalues[i]
            # Add to the output list
            self.energoutput.insert(END,self.energunits[i] + ":  %.4e" % output+"\n")       
class FindServer(Frame):

    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.selected = "";
        self.controller = controller
        label = Label(self, text="Select server", font=TITLE_FONT, justify=CENTER, anchor=CENTER)
        label.pack(side="top", fill="x", pady=10)
        
        self.button1 = Button(self, text="Next",state="disabled", command=self.callback_choose)
        button2 = Button(self, text="Refresh", command=self.callback_refresh)        
        button3 = Button(self, text="Back", command=self.callback_start)
        
        scrollbar = Scrollbar(self)
        self.mylist = Listbox(self, width=100, yscrollcommand = scrollbar.set )
        self.mylist.bind("<Double-Button-1>", self.twoClick)

        self.button1.pack()
        button2.pack()
        button3.pack()
        # create list with a scroolbar
        scrollbar.pack( side = "right", fill="y" )
        self.mylist.pack( side = "top", fill = "x", ipadx=20, ipady=20, padx=20, pady=20 )
        scrollbar.config( command = self.mylist.yview )
        # create a progress bar
        label2 = Label(self, text="Refresh progress bar", justify='center', anchor='center')
        label2.pack(side="top", fill="x")
        
        self.bar_lenght = 200
        self.pb = Progressbar(self, length=self.bar_lenght, mode='determinate')
        self.pb.pack(side="top", anchor='center', ipadx=20, ipady=20, padx=10, pady=10)
        self.pb.config(value=0)

    # to select he server user must double-click on it
    def twoClick(self, event):
        widget = event.widget
        selection=widget.curselection()
        value = widget.get(selection[0])
        self.selected = value
        self.button1.config(state="normal")
        # save the selected server in a global variable
        SELECTED_SERV = SERVER_LIST[selection[0]]
        set_globvar(SELECTED_SERV)      
    
    # listen for broadcasts from port 8192
    def listen_broadcasts(self, port, timeout):
        # Set the progress bar to 0
        self.pb.config(value=0)
        step_size = ((self.bar_lenght/(MAX_NR_OF_SERVERS+1))/2)
        list_of_servers = []
        # Initialize the listener
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        s.bind(('', port))
        s.settimeout(LISTENING_TIMEOUT)
        # Listen for a number of times to get multiple servers
        for _ in range(MAX_NR_OF_SERVERS + 1):
            # Update the progress bar
            self.pb.step(step_size)
            self.pb.update_idletasks()
            try:
                message, address = s.recvfrom(8192) 
                m_split = message.split(';')
                if m_split[0] == '\HELLO':
                    server_id = (m_split[1], address)
                    # Check if the server has not yet broadcasted itself.
                    if server_id not in list_of_servers:
                        list_of_servers.append(server_id)              
            except:
                pass
        # Close the socket
        s.close()
        if not list_of_servers:
            # If no server found, pop a warning message.
            tkMessageBox.showwarning("Find Servers", "No servers found. Refresh or create a new game.")
        # Set the progress bar back to 0
        self.pb.config(value=0)
        # Return the whole list of available servers
        return list_of_servers
    
    # service the refresh button
    def callback_refresh(self):
        global SERVER_LIST
        self.mylist.delete(0,END)
        SERVER_LIST = self.listen_broadcasts(BROADCASTING_PORT, LISTENING_TIMEOUT)
        for server_el in SERVER_LIST:
            self.mylist.insert(END,(" "+str(server_el[0])+"  IP: "+str(server_el[1])+"  Time: "+str(time.asctime())))
    
    def callback_choose(self):
        self.mylist.delete(0,END)
        self.button1.config(state="disabled")
        self.controller.show_frame("ChooseType")
        
    def callback_start(self):
        self.mylist.delete(0,END)
        self.button1.config(state="disabled")
        self.controller.show_frame("StartPage")
Esempio n. 49
0
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)
Esempio n. 50
0
File: gui.py Progetto: imcj/pybbs
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 App(tk.Frame):
    def __init__(self, master, *args, **kw):
        super().__init__(master, *args, **kw)
        self.root = master
        self.master.title('Rebuild List')
        # Width, Height of application
        self.master.geometry("775x700")
        self.store = Combobox_Autocomplete
        self.alldicts = {}
        self.create_widgets()
        self.create_widgets1()
        self.refresh_button()

    def create_widgets(self, *args):
        # Calculate button
        self.imgtitle = ImageTk.PhotoImage(
            Image.open(
                'C:\\Users\\Chris\\PycharmProjects\\untitled\\snapsrebuild.png'
            ))
        self.lab = tk.Label(image=self.imgtitle)
        self.lab.grid(row=0, column=3, padx=20, pady=20)
        # Heading Labels
        # Consumable Label
        self.consume_label = tk.Label(self.root,
                                      text='Items:',
                                      font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=0, columnspan=3, padx=50)
        # Rebuild List Center Text
        self.consume_label = tk.Label(self.root,
                                      text='Rebuild List',
                                      font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=3, padx=50)
        # Armour Text
        self.consume_label = tk.Label(self.root,
                                      text='items:',
                                      font=('Arial', 12, 'bold'))
        self.consume_label.grid(row=1, column=5, columnspan=3, padx=50)
        #######################################################################################################################
        #                                               Left Side buttons and input
        #######################################################################################################################
        # 111111
        # Check Button Number One
        self.is_checked = IntVar()
        self.option_yes = tk.Checkbutton(self.root,
                                         text="",
                                         onvalue=1,
                                         offvalue=0,
                                         variable=self.is_checked,
                                         command=self.callback)
        self.option_yes.grid(row=2, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_0 = tk.StringVar()
        self.combobox_autocomplete = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_0,
            highlightthickness=1)
        self.combobox_autocomplete.grid(row=2, column=1)
        # Insert button
        self.insert_butt = tk.Button(self.root,
                                     text='Insert',
                                     command=lambda: self.commando())
        self.insert_butt.grid(row=2, column=2, padx=10)
        ########################################################################################################################
        # Check Button Number Two                                                                                22222
        self.is_checked1 = IntVar()
        self.option_yes1 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked1,
                                          command=self.callback1)
        self.option_yes1.grid(row=3, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_1 = tk.StringVar()
        self.combobox_autocomplete1 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_1,
            highlightthickness=1)
        self.combobox_autocomplete1.grid(row=3, column=1)
        # Insert button
        self.insert_butt1 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando1())
        self.insert_butt1.grid(row=3, column=2, padx=10)
        ########################################################################################################################
        # Check Button Number Three                                                                             3333333
        self.is_checked2 = IntVar()
        self.option_yes2 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked2,
                                          command=self.callback2)
        self.option_yes2.grid(row=4, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_2 = tk.StringVar()
        self.combobox_autocomplete2 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_2,
            highlightthickness=1)
        self.combobox_autocomplete2.grid(row=4, column=1)
        # Insert button
        self.insert_butt2 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando2())
        self.insert_butt2.grid(row=4, column=2, padx=10)
        ########################################################################################################################
        # Check Button Number Four                                                                              4444444
        self.is_checked3 = IntVar()
        self.option_yes3 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked3,
                                          command=self.callback3)
        self.option_yes3.grid(row=5, column=0, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_3 = tk.StringVar()
        self.combobox_autocomplete3 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_3,
            highlightthickness=1)
        self.combobox_autocomplete3.grid(row=5, column=1)
        # Insert button
        self.insert_butt3 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando3())
        self.insert_butt3.grid(row=5, column=2, padx=10)
        ########################################################################################################################
        # Parts list (listbox)                                                                                 LISTBOX:
        self.list_box = Listbox(self.root,
                                border=0,
                                width=40,
                                height=20,
                                justify='center')
        self.list_box.grid(row=2, rowspan=5, column=3, pady=5)
        # Create scrollbar
        self.scrollbar = tk.Scrollbar(self.root)
        self.scrollbar.grid(row=3, column=4)
        # Set scrollbar to parts
        self.list_box.configure(yscrollcommand=self.scrollbar.set)
        self.scrollbar.configure(command=self.list_box.yview)

    ########################################################################################################################
    # LEFT SIDE FUNCTIONS
    ########################################################################################################################
    # Insert Button On the left right
    def commando(self):
        x = 'Consumables'
        self.alldicts.update({x: (self.entry_0.get())})
        self.list_box.delete(0)
        self.list_box.insert(0, self.entry_0.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando1(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_1.get())})
        self.list_box.delete(1)
        self.list_box.insert(1, self.entry_1.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()
        # Insert Button On the left right

    def commando2(self):
        x = 'Consumables2'
        self.alldicts.update({x: (self.entry_2.get())})
        self.list_box.delete(2)
        self.list_box.insert(2, self.entry_2.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()
        # Insert Button On the left right

    def commando3(self):
        x = 'Consumables3'
        self.alldicts.update({x: (self.entry_3.get())})
        self.list_box.delete(3)
        self.list_box.insert(3, self.entry_3.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    #######################################################################################################################
    def callback(self):
        if self.is_checked.get():
            self.list_box.itemconfig(0, {'bg': 'green'})
        else:
            self.list_box.itemconfig(0, {'bg': '#ffffff'})

    def callback1(self):
        if self.is_checked1.get():
            self.list_box.itemconfig(1, {'bg': 'green'})
        else:
            self.list_box.itemconfig(1, {'bg': '#ffffff'})

    def callback2(self):
        if self.is_checked2.get():
            self.list_box.itemconfig(2, {'bg': 'green'})
        else:
            self.list_box.itemconfig(2, {'bg': '#ffffff'})

    def callback3(self):
        if self.is_checked3.get():
            self.list_box.itemconfig(3, {'bg': 'green'})
        else:
            self.list_box.itemconfig(3, {'bg': '#ffffff'})

    ########################################################################################################################
    # RIGHT SIDE BUTTONS AND LABELS
    ########################################################################################################################
    # 5555555
    def create_widgets1(self, *args):
        # Check Button Number One
        self.is_checked4 = IntVar()
        self.option_yes4 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked4,
                                          command=self.callback4)
        self.option_yes4.grid(row=2, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_4 = tk.StringVar()
        self.combobox_autocomplete4 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_4,
            highlightthickness=1)
        self.combobox_autocomplete4.grid(row=2, column=6)
        # Insert button
        self.insert_butt4 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando4())
        self.insert_butt4.grid(row=2, column=5, padx=10)
        ########################################################################################################################
        # Check Button Number Two                                                                               666666
        self.is_checked5 = IntVar()
        self.option_yes5 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked5,
                                          command=self.callback5)
        self.option_yes5.grid(row=3, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_5 = tk.StringVar()
        self.combobox_autocomplete5 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_5,
            highlightthickness=1)
        self.combobox_autocomplete5.grid(row=3, column=6)
        # Insert button
        self.insert_butt5 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando5())
        self.insert_butt5.grid(row=3, column=5, padx=10)
        ########################################################################################################################
        # Check Button Number Three                                                                             777777
        self.is_checked6 = IntVar()
        self.option_yes6 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked6,
                                          command=self.callback6)

        self.option_yes6.grid(row=4, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_6 = tk.StringVar()
        self.combobox_autocomplete6 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_6,
            highlightthickness=1)
        self.combobox_autocomplete6.grid(row=4, column=6)
        # Insert button
        self.insert_butt6 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando6())
        self.insert_butt6.grid(row=4, column=5, padx=10)
        ########################################################################################################################
        # Check Button Number Four                                                                             888888
        self.is_checked7 = IntVar()
        self.option_yes7 = tk.Checkbutton(self.root,
                                          text="",
                                          onvalue=1,
                                          offvalue=0,
                                          variable=self.is_checked7,
                                          command=self.callback7)

        self.option_yes7.grid(row=5, column=7, padx=15)
        # Entry Label To the right of the checkbox
        self.entry_7 = tk.StringVar()
        self.combobox_autocomplete7 = Combobox_Autocomplete(
            self.root,
            list_of_items,
            textvariable=self.entry_7,
            highlightthickness=1)
        self.combobox_autocomplete7.grid(row=5, column=6)
        # Insert button
        self.insert_butt7 = tk.Button(self.root,
                                      text='Insert',
                                      command=lambda: self.commando7())
        self.insert_butt7.grid(row=5, column=5, padx=10)

    ########################################################################################################################
    #        FUNCTIONS FOR THE RIGHT SIDE
    ########################################################################################################################
    # Insert Buttons on the right side
    def commando4(self):
        x = 'Consumables'
        self.alldicts.update({x: (self.entry_4.get())})
        self.list_box.delete(4)
        self.list_box.insert(4, self.entry_4.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando5(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_5.get())})
        self.list_box.delete(5)
        self.list_box.insert(5, self.entry_5.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando6(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_6.get())})
        self.list_box.delete(6)
        self.list_box.insert(6, self.entry_6.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    def commando7(self):
        x = 'Consumables1'
        self.alldicts.update({x: (self.entry_7.get())})
        self.list_box.delete(7)
        self.list_box.insert(7, self.entry_7.get())
        for (key, value) in self.alldicts.items():
            print(key, "::", value)
        return ()

    ########################################################################################################################
    def callback4(self):
        if self.is_checked4.get():
            self.list_box.itemconfig(4, {'bg': 'green'})
        else:
            self.list_box.itemconfig(4, {'bg': '#ffffff'})

    def callback5(self):
        if self.is_checked5.get():
            self.list_box.itemconfig(5, {'bg': 'green'})
        else:
            self.list_box.itemconfig(5, {'bg': '#ffffff'})

    def callback6(self):
        if self.is_checked6.get():
            self.list_box.itemconfig(6, {'bg': 'green'})
        else:
            self.list_box.itemconfig(6, {'bg': '#ffffff'})

    def callback7(self):
        if self.is_checked7.get():
            self.list_box.itemconfig(7, {'bg': 'green'})
        else:
            self.list_box.itemconfig(7, {'bg': '#ffffff'})

    #########################################################################################################################
    # Refresh button
    def refresh_button(self, *args):
        self.refresher = tk.Button(self.root,
                                   text='Refresh',
                                   command=lambda: self.refresh())
        self.refresher.grid(row=7, column=3, pady=10)

    # Need to refresh the colours that have been checked already, must clear the list box.
    def refresh(self, *args):
        self.list_box.delete(0, END)
        self.combobox_autocomplete.delete(0, "end")
        self.combobox_autocomplete1.delete(0, "end")
        self.combobox_autocomplete2.delete(0, "end")
        self.combobox_autocomplete3.delete(0, "end")
        self.combobox_autocomplete4.delete(0, "end")
        self.combobox_autocomplete5.delete(0, "end")
        self.combobox_autocomplete6.delete(0, "end")
        self.combobox_autocomplete7.delete(0, "end")
Esempio n. 52
0
class ListPage(BasePage):
    def __init__(self, parent, controller):
        BasePage.__init__(self, parent, controller)
        self.target_keep_profile_var = IntVar()
        self.mutex = Lock()

    def prepare(self):
        self.deviceList.config(state='normal')
        self.versionList.config(state='disabled')
        self.engList.config(state='disabled')
        self.packageList.config(state='disabled')
        self.ok.config(state='disabled')
        self.setData(self.controller.data)
        self.setDeviceList(self.data.keys())
        self.controller.setDefault(self, self.controller.loadOptions())
        self.deviceList.focus_force()

    def printErr(self, message):
        self.errLog.config(text=message)

    def setData(self, data):
        self.data = data

    def setupView(self, title="Select your flash", data=None):
        if (data):
            self.setData(data)
        self.errLog = Label(self, text="")
        self.errLog.grid(row=4, column=1, columnspan=3, sticky="NWSE")
        self.desc = Label(self, text=title, font=TITLE_FONT)
        self.desc.grid(row=0, column=0, columnspan=2)
        self.ok = Button(self, text='Next', command=lambda: self.confirm())
        self.ok.grid(row=4, column=3, sticky="E")
        self.ok.config(state="disabled")
        # bind self.target_keep_profile_var (IntVar) to keepProfileCheckbutton, 1 is True, 0 is Flase
        self.keepProfileCheckbutton = Checkbutton(
            self,
            text="Keep User Profile (BETA)",
            variable=self.target_keep_profile_var)
        self.keepProfileCheckbutton.grid(row=5,
                                         column=0,
                                         columnspan=4,
                                         sticky="W")
        self.deviceLabel = Label(self, text="Device", font=TITLE_FONT)
        self.deviceLabel.grid(row=1, column=0)
        self.deviceList = Listbox(self, exportselection=0)
        self.deviceList.grid(row=2, column=0)
        self.deviceList.bind('<<ListboxSelect>>', self.deviceOnSelect)
        self.deviceList.config(state="disabled")
        self.versionLabel = Label(self, text="Branch", font=TITLE_FONT)
        self.versionLabel.grid(row=1, column=1)
        self.versionList = Listbox(self, exportselection=0)
        self.versionList.grid(row=2, column=1)
        self.versionList.bind('<<ListboxSelect>>', self.versionOnSelect)
        self.versionList.config(state="disabled")
        self.engLabel = Label(self, text="Build Type", font=TITLE_FONT)
        self.engLabel.grid(row=1, column=2)
        self.engList = Listbox(self, exportselection=0)
        self.engList.grid(row=2, column=2)
        self.engList.bind('<<ListboxSelect>>', self.engOnSelect)
        self.engList.config(state="disabled")
        self.packageLabel = Label(self,
                                  text="Gecko/Gaia/Full",
                                  font=TITLE_FONT)
        self.packageLabel.grid(row=1, column=3)
        self.packageList = Listbox(self, exportselection=0)
        self.packageList.grid(row=2, column=3)
        self.packageList.bind('<<ListboxSelect>>', self.packageOnSelect)
        self.packageList.config(state="disabled")
        self.bidVar = StringVar()
        Label(self, text="Build ID").grid(row=3, column=0, sticky='E')
        self.bidInput = Entry(self, textvariable=self.bidVar, width="30")
        self.bidInput.grid(row=3, column=1, columnspan=2, sticky="W")
        self.bidVar.set('latest')
        # binding unfocus for build id field
        self.bidInput.bind('<FocusOut>', self.updateBuildId)
        # binding the Return Key to each componments
        self.deviceList.bind('<Return>', self.pressReturnKey)
        self.versionList.bind('<Return>', self.pressReturnKey)
        self.engList.bind('<Return>', self.pressReturnKey)
        self.packageList.bind('<Return>', self.pressReturnKey)
        self.bidInput.bind('<Return>', self.pressReturnKey)
        self.ok.bind('<Return>', self.pressReturnKey)

    def selection_all_checked(self):
        result = False
        if len(self.deviceList.curselection()) == 0:
            self.logger.log('Please select device.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.deviceList.focus_set()
        elif len(self.versionList.curselection()) == 0:
            self.logger.log('Please select branch.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.versionList.focus_set()
        elif len(self.engList.curselection()) == 0:
            self.logger.log('Please select user or engineer build.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.engList.focus_set()
        elif len(self.packageList.curselection()) == 0:
            self.logger.log('Please select package to flash.',
                            status_callback=self.printErr)
            self.ok.config(state="disabled")
            self.packageList.focus_set()
        elif len(self.bidVar.get()) != 14 and self.bidVar.get() != 'latest':
            self.logger.log(
                'Please enter build ID to flash or use "latest" to get the newest',
                status_callback=self.printErr)
            self.logger.log(self.bidVar.get() + ' is invalid: ' +
                            str(len(self.bidVar.get())))
            self.bidVar.set('latest')
        else:
            result = True
        return result

    def updateBuildId(self, event=None):
        # if the value is '' or 'latest', the set the build_id option as ''.
        buildId = self.bidVar.get()
        if buildId == 'latest':
            buildId = ''
        elif len(buildId) != 14:
            self.printErr("Invalid build ID: " + buildId + ", reset to latest")
            buildId = ''
            self.bidVar.set('latest')
        else:
            if len(self.engList.curselection()) != 0:
                self.refreshPackageList()

    def pressReturnKey(self, event=None):
        if self.selection_all_checked():
            self.ok.config(state="disabled")
            self.confirm()

    def deviceOnSelect(self, evt):
        self.setVersionList()

    def versionOnSelect(self, evt):
        self.setEngList()

    def engOnSelect(self, evt):
        self.refreshPackageList()  # hard coded right now

    def packageOnSelect(self, evt):
        self.ok.config(state="normal")

    def confirm(self):
        self.mutex.acquire()
        try:
            if self.selection_all_checked():
                self.ok.config(state="disabled")
                params = []
                package = self.packageList.get(
                    self.packageList.curselection()[0])
                self.logger.log('Start to flash [' + package + '].',
                                status_callback=self.printErr)
                if (PathParser._IMAGES in package):
                    params.append(PathParser._IMAGES)
                else:
                    if (PathParser._GAIA in package):
                        params.append(PathParser._GAIA)
                    if (PathParser._GECKO in package):
                        params.append(PathParser._GECKO)
                keep_profile = (self.target_keep_profile_var.get() == 1)
                archives = self.controller.do_download(params)
                self.controller.do_flash(params,
                                         archives,
                                         keep_profile=keep_profile)
                self.packageList.select_clear(0, END)
                self.controller.transition(self)
        finally:
            self.mutex.release()

    def setDeviceList(self, device=[]):
        self.deviceList.delete(0, END)
        for li in device:
            self.deviceList.insert(END, li)

    def setVersionList(self, version=[]):
        if len(version) == 0:
            version = self.data[self.deviceList.get(
                self.deviceList.curselection())]
        self.versionList.config(state="normal")
        self.engList.config(state="disabled")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.versionList.delete(0, END)
        for li in version:
            self.versionList.insert(END, li)

    def setEngList(self, eng=[]):
        if len(eng) == 0:
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.data[device][version]
        self.engList.config(state="normal")
        self.packageList.config(state="disabled")
        self.ok.config(state="disabled")
        self.engList.delete(0, END)
        for li in eng:
            self.engList.insert(END, li)

    def refreshPackageList(self):
        self.mutex.acquire()
        try:
            self.packageList.config(state="normal")
            self.ok.config(state="normal")
            self.packageList.delete(0, END)
            device = self.deviceList.get(self.deviceList.curselection())
            version = self.versionList.get(self.versionList.curselection())
            eng = self.engList.get(self.engList.curselection())
            buildId = '' if (len(self.bidVar.get()) == 0 or self.bidVar.get()
                             == 'latest') else self.bidVar.get()
            package = self.controller.getPackages(
                self.data[device][version][eng]['src'], build_id=buildId)
            if len(package) == 0:
                self.logger.log('Invalid build ID: ' + buildId +
                                ', reset to latest',
                                status_callback=self.printErr)
                buildId = ''
                self.bidVar.set('latest')
                package = self.controller.getPackages(
                    self.data[device][version][eng]['src'], build_id=buildId)
            for li in package:
                self.packageList.insert(END, li)
        finally:
            self.mutex.release()
Esempio n. 53
0
class RecursiveDescentApp(object):
    """
    A graphical tool for exploring the recursive descent parser.  The tool
    displays the parser's tree and the remaining text, and allows the
    user to control the parser's operation.  In particular, the user
    can expand subtrees on the frontier, match tokens on the frontier
    against the text, and backtrack.  A "step" button simply steps
    through the parsing process, performing the operations that
    ``RecursiveDescentParser`` would use.
    """
    def __init__(self, grammar, sent, trace=0):
        self._sent = sent
        self._parser = SteppingRecursiveDescentParser(grammar, trace)

        # Set up the main window.
        self._top = Tk()
        self._top.title('Recursive Descent Parser Application')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.
        self._init_fonts(self._top)

        # Animations.  animating_lock is a lock to prevent the demo
        # from performing new operations while it's animating.
        self._animation_frames = IntVar(self._top)
        self._animation_frames.set(5)
        self._animating_lock = 0
        self._autostep = 0

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_feedback(self._top)
        self._init_grammar(self._top)
        self._init_canvas(self._top)

        # Initialize the parser.
        self._parser.initialize(self._sent)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkFont.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 = tkFont.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkFont.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 = tkFont.Font(family='helvetica', weight='bold',
                                    size=big)

    def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._prodlist.pack(side='right', fill='both', expand=1)

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

        # Add a scrollbar if there are more than 25 productions.
        if len(self._productions) > 25:
            listscroll = Scrollbar(self._prodframe,
                                   orient='vertical')
            self._prodlist.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._prodlist.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_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('e', self.expand)
        #self._top.bind('<Alt-e>', self.expand)
        #self._top.bind('<Control-e>', self.expand)
        self._top.bind('m', self.match)
        self._top.bind('<Alt-m>', self.match)
        self._top.bind('<Control-m>', self.match)
        self._top.bind('b', self.backtrack)
        self._top.bind('<Alt-b>', self.backtrack)
        self._top.bind('<Control-b>', self.backtrack)
        self._top.bind('<Control-z>', self.backtrack)
        self._top.bind('<BackSpace>', self.backtrack)
        self._top.bind('a', self.autostep)
        #self._top.bind('<Control-a>', self.autostep)
        self._top.bind('<Control-space>', self.autostep)
        self._top.bind('<Control-c>', self.cancel_autostep)
        self._top.bind('<space>', self.step)
        self._top.bind('<Delete>', self.reset)
        self._top.bind('<Control-p>', self.postscript)
        #self._top.bind('<h>', self.help)
        #self._top.bind('<Alt-h>', self.help)
        self._top.bind('<Control-h>', self.help)
        self._top.bind('<F1>', self.help)
        #self._top.bind('<g>', self.toggle_grammar)
        #self._top.bind('<Alt-g>', self.toggle_grammar)
        #self._top.bind('<Control-g>', self.toggle_grammar)
        self._top.bind('<Control-g>', self.edit_grammar)
        self._top.bind('<Control-t>', self.edit_sentence)

    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='Step',
               background='#90c0d0', foreground='black',
               command=self.step,).pack(side='left')
        Button(buttonframe, text='Autostep',
               background='#90c0d0', foreground='black',
               command=self.autostep,).pack(side='left')
        Button(buttonframe, text='Expand', underline=0,
               background='#90f090', foreground='black',
               command=self.expand).pack(side='left')
        Button(buttonframe, text='Match', underline=0,
               background='#90f090', foreground='black',
               command=self.match).pack(side='left')
        Button(buttonframe, text='Backtrack', underline=0,
               background='#f0a0a0', foreground='black',
               command=self.backtrack).pack(side='left')
        # Replace autostep...
#         self._autostep_button = Button(buttonframe, text='Autostep',
#                                        underline=0, command=self.autostep)
#         self._autostep_button.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_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1)

    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='Reset Parser', underline=0,
                             command=self.reset, accelerator='Del')
        filemenu.add_command(label='Print to Postscript', underline=0,
                             command=self.postscript, accelerator='Ctrl-p')
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-x')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label='Edit Grammar', underline=5,
                             command=self.edit_grammar,
                             accelerator='Ctrl-g')
        editmenu.add_command(label='Edit Text', underline=5,
                             command=self.edit_sentence,
                             accelerator='Ctrl-t')
        menubar.add_cascade(label='Edit', underline=0, menu=editmenu)

        rulemenu = Menu(menubar, tearoff=0)
        rulemenu.add_command(label='Step', underline=1,
                             command=self.step, accelerator='Space')
        rulemenu.add_separator()
        rulemenu.add_command(label='Match', underline=0,
                             command=self.match, accelerator='Ctrl-m')
        rulemenu.add_command(label='Expand', underline=0,
                             command=self.expand, accelerator='Ctrl-e')
        rulemenu.add_separator()
        rulemenu.add_command(label='Backtrack', underline=0,
                             command=self.backtrack, accelerator='Ctrl-b')
        menubar.add_cascade(label='Apply', underline=0, menu=rulemenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_checkbutton(label="Show Grammar", underline=0,
                                 variable=self._show_grammar,
                                 command=self._toggle_grammar)
        viewmenu.add_separator()
        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)

        animatemenu = Menu(menubar, tearoff=0)
        animatemenu.add_radiobutton(label="No Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=0)
        animatemenu.add_radiobutton(label="Slow Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=10, accelerator='-')
        animatemenu.add_radiobutton(label="Normal Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=5, accelerator='=')
        animatemenu.add_radiobutton(label="Fast Animation", underline=0,
                                    variable=self._animation_frames,
                                    value=2, accelerator='+')
        menubar.add_cascade(label="Animate", underline=1, menu=animatemenu)


        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        helpmenu.add_command(label='Instructions', underline=0,
                             command=self.help, accelerator='F1')
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Helper
    #########################################

    def _get(self, widget, treeloc):
        for i in treeloc: widget = widget.subtrees()[i]
        if isinstance(widget, TreeSegmentWidget):
            widget = widget.node()
        return widget

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {'tree_color': '#000000', 'tree_width': 2,
                   'node_font': bold, 'leaf_font': helv,}
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [TextWidget(canvas, word, font=self._font)
                             for word in self._sent]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom-twidget.bbox()[3]-5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text()


    def _redraw_quick(self):
        # This should be more-or-less sufficient after an animation.
        self._highlight_nodes()
        self._highlight_prodlist()
        self._position_text()

    def _highlight_nodes(self):
        # Highlight the list of nodes to be checked.
        bold = ('helvetica', -self._size.get(), 'bold')
        for treeloc in self._parser.frontier()[:1]:
            self._get(self._tree, treeloc)['color'] = '#20a050'
            self._get(self._tree, treeloc)['font'] = bold
        for treeloc in self._parser.frontier()[1:]:
            self._get(self._tree, treeloc)['color'] = '#008080'

    def _highlight_prodlist(self):
        # Highlight the productions that can be expanded.
        # Boy, too bad tkinter doesn't implement Listbox.itemconfig;
        # that would be pretty useful here.
        self._prodlist.delete(0, 'end')
        expandable = self._parser.expandable_productions()
        untried = self._parser.untried_expandable_productions()
        productions = self._productions
        for index in range(len(productions)):
            if productions[index] in expandable:
                if productions[index] in untried:
                    self._prodlist.insert(index, ' %s' % productions[index])
                else:
                    self._prodlist.insert(index, ' %s (TRIED)' %
                                          productions[index])
                self._prodlist.selection_set(index)
            else:
                self._prodlist.insert(index, ' %s' % productions[index])

    def _position_text(self):
        # Line up the text widgets that are matched against the tree
        numwords = len(self._sent)
        num_matched = numwords - len(self._parser.remaining_text())
        leaves = self._tree_leaves()[:num_matched]
        xmax = self._tree.bbox()[0]
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            widget['color'] = '#006040'
            leaf['color'] = '#006040'
            widget.move(leaf.bbox()[0] - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # Line up the text widgets that are not matched against the tree.
        for i in range(len(leaves), numwords):
            widget = self._textwidgets[i]
            widget['color'] = '#a0a0a0'
            widget.move(xmax - widget.bbox()[0], 0)
            xmax = widget.bbox()[2] + 10

        # If we have a complete parse, make everything green :)
        if self._parser.currently_complete():
            for twidget in self._textwidgets:
                twidget['color'] = '#00a000'

        # Move the matched leaves down to the text.
        for i in range(0, len(leaves)):
            widget = self._textwidgets[i]
            leaf = leaves[i]
            dy = widget.bbox()[1] - leaf.bbox()[3] - 10.0
            dy = max(dy, leaf.parent().node().bbox()[3] - leaf.bbox()[3] + 10)
            leaf.move(0, dy)

    def _tree_leaves(self, tree=None):
        if tree is None: tree = self._tree
        if isinstance(tree, TreeSegmentWidget):
            leaves = []
            for child in tree.subtrees(): leaves += self._tree_leaves(child)
            return leaves
        else:
            return [tree]

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def reset(self, *e):
        self._autostep = 0
        self._parser.initialize(self._sent)
        self._lastoper1['text'] = 'Reset Application'
        self._lastoper2['text'] = ''
        self._redraw()

    def autostep(self, *e):
        if self._animation_frames.get() == 0:
            self._animation_frames.set(2)
        if self._autostep:
            self._autostep = 0
        else:
            self._autostep = 1
            self._step()

    def cancel_autostep(self, *e):
        #self._autostep_button['text'] = 'Autostep'
        self._autostep = 0

    # Make sure to stop auto-stepping if we get any user input.
    def step(self, *e): self._autostep = 0; self._step()
    def match(self, *e): self._autostep = 0; self._match()
    def expand(self, *e): self._autostep = 0; self._expand()
    def backtrack(self, *e): self._autostep = 0; self._backtrack()

    def _step(self):
        if self._animating_lock: return

        # Try expanding, matching, and backtracking (in that order)
        if self._expand(): pass
        elif self._parser.untried_match() and self._match(): pass
        elif self._backtrack(): pass
        else:
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            self._autostep = 0

        # Check if we just completed a parse.
        if self._parser.currently_complete():
            self._autostep = 0
            self._lastoper2['text'] += '    [COMPLETE PARSE]'

    def _expand(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.expand()
        if rv is not None:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = rv
            self._prodlist.selection_clear(0, 'end')
            index = self._productions.index(rv)
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = '(all expansions tried)'
            return 0

    def _match(self, *e):
        if self._animating_lock: return
        old_frontier = self._parser.frontier()
        rv = self._parser.match()
        if rv is not None:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = rv
            self._animate_match(old_frontier[0])
            return 1
        else:
            self._lastoper1['text'] = 'Match:'
            self._lastoper2['text'] = '(failed)'
            return 0

    def _backtrack(self, *e):
        if self._animating_lock: return
        if self._parser.backtrack():
            elt = self._parser.tree()
            for i in self._parser.frontier()[0]:
                elt = elt[i]
            self._lastoper1['text'] = 'Backtrack'
            self._lastoper2['text'] = ''
            if isinstance(elt, Tree):
                self._animate_backtrack(self._parser.frontier()[0])
            else:
                self._animate_match_backtrack(self._parser.frontier()[0])
            return 1
        else:
            self._autostep = 0
            self._lastoper1['text'] = 'Finished'
            self._lastoper2['text'] = ''
            return 0

    def about(self, *e):
        ABOUT = ("NLTK Recursive Descent Parser Application\n"+
                 "Written by Edward Loper")
        TITLE = 'About: Recursive Descent Parser Application'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75)

    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()

    #########################################
    ##  Expand Production Selection
    #########################################

    def _toggle_grammar(self, *e):
        if self._show_grammar.get():
            self._prodframe.pack(fill='both', side='left', padx=2,
                                 after=self._feedbackframe)
            self._lastoper1['text'] = 'Show Grammar'
        else:
            self._prodframe.pack_forget()
            self._lastoper1['text'] = 'Hide Grammar'
        self._lastoper2['text'] = ''

#     def toggle_grammar(self, *e):
#         self._show_grammar = not self._show_grammar
#         if self._show_grammar:
#             self._prodframe.pack(fill='both', expand='y', side='left',
#                                  after=self._feedbackframe)
#             self._lastoper1['text'] = 'Show Grammar'
#         else:
#             self._prodframe.pack_forget()
#             self._lastoper1['text'] = 'Hide Grammar'
#         self._lastoper2['text'] = ''

    def _prodlist_select(self, event):
        selection = self._prodlist.curselection()
        if len(selection) != 1: return
        index = int(selection[0])
        old_frontier = self._parser.frontier()
        production = self._parser.expand(self._productions[index])

        if production:
            self._lastoper1['text'] = 'Expand:'
            self._lastoper2['text'] = production
            self._prodlist.selection_clear(0, 'end')
            self._prodlist.selection_set(index)
            self._animate_expand(old_frontier[0])
        else:
            # Reset the production selections.
            self._prodlist.selection_clear(0, 'end')
            for prod in self._parser.expandable_productions():
                index = self._productions.index(prod)
                self._prodlist.selection_set(index)

    #########################################
    ##  Animation
    #########################################

    def _animate_expand(self, treeloc):
        oldwidget = self._get(self._tree, treeloc)
        oldtree = oldwidget.parent()
        top = not isinstance(oldtree.parent(), TreeSegmentWidget)

        tree = self._parser.tree()
        for i in treeloc:
            tree = tree[i]

        widget = tree_to_treesegment(self._canvas, tree,
                                     node_font=self._boldfont,
                                     leaf_color='white',
                                     tree_width=2, tree_color='white',
                                     node_color='white',
                                     leaf_font=self._font)
        widget.node()['color'] = '#20a050'

        (oldx, oldy) = oldtree.node().bbox()[:2]
        (newx, newy) = widget.node().bbox()[:2]
        widget.move(oldx-newx, oldy-newy)

        if top:
            self._cframe.add_widget(widget, 0, 5)
            widget.move(30-widget.node().bbox()[0], 0)
            self._tree = widget
        else:
            oldtree.parent().replace_child(oldtree, widget)

        # Move the children over so they don't overlap.
        # Line the children up in a strange way.
        if widget.subtrees():
            dx = (oldx + widget.node().width()/2 -
                  widget.subtrees()[0].bbox()[0]/2 -
                  widget.subtrees()[0].bbox()[2]/2)
            for subtree in widget.subtrees(): subtree.move(dx, 0)

        self._makeroom(widget)

        if top:
            self._cframe.destroy_widget(oldtree)
        else:
            oldtree.destroy()

        colors = ['gray%d' % (10*int(10*x/self._animation_frames.get()))
                  for x in range(self._animation_frames.get(),0,-1)]

        # Move the text string down, if necessary.
        dy = widget.bbox()[3] + 30 - self._canvas.coords(self._textline)[1]
        if dy > 0:
            for twidget in self._textwidgets: twidget.move(0, dy)
            self._canvas.move(self._textline, 0, dy)

        self._animate_expand_frame(widget, colors)

    def _makeroom(self, treeseg):
        """
        Make sure that no sibling tree bbox's overlap.
        """
        parent = treeseg.parent()
        if not isinstance(parent, TreeSegmentWidget): return

        index = parent.subtrees().index(treeseg)

        # Handle siblings to the right
        rsiblings = parent.subtrees()[index+1:]
        if rsiblings:
            dx = treeseg.bbox()[2] - rsiblings[0].bbox()[0] + 10
            for sibling in rsiblings: sibling.move(dx, 0)

        # Handle siblings to the left
        if index > 0:
            lsibling = parent.subtrees()[index-1]
            dx = max(0, lsibling.bbox()[2] - treeseg.bbox()[0] + 10)
            treeseg.move(dx, 0)

        # Keep working up the tree.
        self._makeroom(parent)

    def _animate_expand_frame(self, widget, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            widget['color'] = colors[0]
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.node()['color'] = colors[0]
                else:
                    subtree['color'] = colors[0]
            self._top.after(50, self._animate_expand_frame,
                            widget, colors[1:])
        else:
            widget['color'] = 'black'
            for subtree in widget.subtrees():
                if isinstance(subtree, TreeSegmentWidget):
                    subtree.node()['color'] = 'black'
                else:
                    subtree['color'] = 'black'
            self._redraw_quick()
            widget.node()['color'] = 'black'
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_backtrack(self, treeloc):
        # Flash red first, if we're animating.
        if self._animation_frames.get() == 0: colors = []
        else: colors = ['#a00000', '#000000', '#a00000']
        colors += ['gray%d' % (10*int(10*x/(self._animation_frames.get())))
                   for x in range(1, self._animation_frames.get()+1)]

        widgets = [self._get(self._tree, treeloc).parent()]
        for subtree in widgets[0].subtrees():
            if isinstance(subtree, TreeSegmentWidget):
                widgets.append(subtree.node())
            else:
                widgets.append(subtree)

        self._animate_backtrack_frame(widgets, colors)

    def _animate_backtrack_frame(self, widgets, colors):
        if len(colors) > 0:
            self._animating_lock = 1
            for widget in widgets: widget['color'] = colors[0]
            self._top.after(50, self._animate_backtrack_frame,
                            widgets, colors[1:])
        else:
            for widget in widgets[0].subtrees():
                widgets[0].remove_child(widget)
                widget.destroy()
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack(self, treeloc):
        widget = self._get(self._tree, treeloc)
        node = widget.parent().node()
        dy = (1.0 * (node.bbox()[3] - widget.bbox()[1] + 14) /
              max(1, self._animation_frames.get()))
        self._animate_match_backtrack_frame(self._animation_frames.get(),
                                            widget, dy)

    def _animate_match(self, treeloc):
        widget = self._get(self._tree, treeloc)

        dy = ((self._textwidgets[0].bbox()[1] - widget.bbox()[3] - 10.0) /
              max(1, self._animation_frames.get()))
        self._animate_match_frame(self._animation_frames.get(), widget, dy)

    def _animate_match_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_frame,
                            frame-1, widget, dy)
        else:
            widget['color'] = '#006040'
            self._redraw_quick()
            self._animating_lock = 0
            if self._autostep: self._step()

    def _animate_match_backtrack_frame(self, frame, widget, dy):
        if frame > 0:
            self._animating_lock = 1
            widget.move(0, dy)
            self._top.after(10, self._animate_match_backtrack_frame,
                            frame-1, widget, dy)
        else:
            widget.parent().remove_child(widget)
            widget.destroy()
            self._animating_lock = 0
            if self._autostep: self._step()

    def edit_grammar(self, *e):
        CFGEditor(self._top, self._parser.grammar(), self.set_grammar)

    def set_grammar(self, grammar):
        self._parser.set_grammar(grammar)
        self._productions = list(grammar.productions())
        self._prodlist.delete(0, 'end')
        for production in self._productions:
            self._prodlist.insert('end', (' %s' % production))

    def edit_sentence(self, *e):
        sentence = " ".join(self._sent)
        title = 'Edit Text'
        instr = 'Enter a new sentence to parse.'
        EntryDialog(self._top, sentence, instr, self.set_sentence, title)

    def set_sentence(self, sentence):
        self._sent = sentence.split() #[XX] use tagged?
        self.reset()
Esempio n. 54
0
class CenterFrame(BasePAFrame):
    """
    фрейм со списком файлов
    """

    def __init__(self, *args, **kwargs):
        self.w_frame_child = kwargs.pop('child_frame')

        BasePAFrame.__init__(self, *args, **kwargs)

        self.w_listbox_files = Listbox(self)
        self.w_scrollbar_files = Scrollbar(self)

        self.catalog = None
        self.catalog_files = []

    def _pa_configure(self):
        BasePAFrame._pa_configure(self)

        self.w_listbox_files.config(yscrollcommand=self.w_scrollbar_files.set)
        self.w_scrollbar_files.config(command=self.w_listbox_files.yview)

        self.w_listbox_files.bind(
            '<<ListboxSelect>>', self.select_listbox_file)

    def _pa_layout(self):
        BasePAFrame._pa_layout(self)

        w_listbox_files_width = 0.95
        self.w_listbox_files.place(
            relx=0,
            rely=0,
            relwidth=w_listbox_files_width,
            relheight=1)
        self.w_scrollbar_files.place(
            relx=w_listbox_files_width,
            rely=0,
            relwidth=1-w_listbox_files_width,
            relheight=1)

    def set_catalog(self, catalog=None):
        """
        задаем новый каталог для отображения

        :param catalog: словарь
            {
                'path': путь к каталогу
            }
        :return:
        """

        try:
            current_index = self.w_listbox_files.curselection()[0]
        except IndexError:
            current_index = 0

        if 0 < current_index < len(self.catalog_files):
            set_index = current_index + 1
        else:
            set_index = current_index

        self.catalog = catalog
        self.catalog_files = []
        self.w_listbox_files.delete(0, END)
        self.w_frame_child.set_file(None)

        if self.catalog is not None:
            catalog_path = self.catalog

            for file_name in os.listdir(catalog_path):
                file_path = os.path.join(catalog_path, file_name)
                if os.path.isfile(file_path):
                    self.catalog_files.append({
                        'name': file_name,
                        'path': file_path})
            self.catalog_files.sort(key=lambda x: x['name'])
            catalog_files = [catalog['name'] for catalog in self.catalog_files]
            self.w_listbox_files.insert(END, *catalog_files)

            self.w_listbox_files.selection_set(set_index)
            self.w_listbox_files.see(set_index)
            self.w_listbox_files.event_generate("<<ListboxSelect>>")

    def update_catalog(self):
        self.set_catalog(self.catalog)

    def select_listbox_file(self, event):
        """
        обработчик выбора файла в списке файлов

        :param event:
        :return:
        """
        try:
            index = self.w_listbox_files.curselection()[0]
            file_ = self.catalog_files[index]
        except IndexError:
            return
        else:
            self.w_frame_child.set_file(file_)
Esempio n. 55
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')
Esempio n. 56
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.padx = 3
        self.pady = 3
        self.grid()
        self.results = []
        self.playlists = []
        self.vids = []
        self.__createWidgets()

    def __createWidgets(self):
        self.__searchFields()
        self.__resultArea()
        self.__buttons()
        self.__markdownArea()
        self.bind('<Return>', self.search_button)

    def __buttons(self):
        self.resultSelect = Button(text='OK', state=DISABLED)
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)
        self.status = Label(text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.grid(row=9, column=0, columnspan=10, sticky=N + E + S + W)
        self.__vidButtons()
        self.__rmVidButtons()
        self.resultSelect.grid_forget()

    def __searchFields(self):
        Label(text="User", anchor=E).grid(row=0, column=0,
                                          padx=self.padx, pady=self.pady,
                                          sticky=W)
        self.user_entry = Entry()
        self.user_entry.grid(row=0, column=1, padx=self.padx, pady=self.pady,
                             sticky=W)
        Label(text="Search terms").grid(row=0, column=3,
                                        padx=self.padx, pady=self.pady,
                                        sticky=W)
        self.search_terms = Entry()
        self.search_terms.grid(row=0, column=4,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        Label(text="playlist id").grid(row=1, column=3,
                                       padx=self.padx, pady=self.pady,
                                       sticky=W)
        self.playlist_id = Entry()
        self.playlist_id.grid(row=1, column=4, padx=self.padx, pady=self.pady,
                              sticky=W)
        self.search_button = Button(text="Search", command=self.__search)
        self.search_button.grid(row=2, column=4,
                                padx=self.padx, pady=self.pady, sticky=E)

    def __resultArea(self):
        self.result_label = Label(text="Results")
        self.result_label.grid(row=2, column=0,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        self.resultshowbut = Button(text="View", command=self.__showResults)
        self.resultshowbut.grid(row=2, column=1, sticky=W)
        self.yScroll = Scrollbar(orient=VERTICAL)
        self.xScroll = Scrollbar(orient=HORIZONTAL)
        self.listbox = Listbox(xscrollcommand=self.xScroll.set,
                                yscrollcommand=self.yScroll.set,
                                selectmode=SINGLE)
        self.xScroll.config(command=self.listbox.xview)
        self.yScroll.config(command=self.listbox.yview)

    def __showResults(self):
        self.resultshowbut.config(text="Hide", command=self.__hideResults)
        self.yScroll.grid(row=3, column=5, sticky=N + S)
        self.xScroll.grid(row=4, column=0, sticky=E + W, columnspan=5)
        self.listbox.grid(row=3, column=0, sticky=N + S + E + W, columnspan=5)
        self.markdownarea.config(height=10)

    def __hideResults(self):
        self.resultshowbut.config(text="View", command=self.__showResults)
        self.yScroll.grid_forget()
        self.xScroll.grid_forget()
        self.listbox.grid_forget()
        self.markdownarea.config(height=30)

    def __markdownArea(self):
        self.markdownlabel = Label(text="Markdown")
        self.mdyScroll = Scrollbar(orient=VERTICAL)
        self.mdxScroll = Scrollbar(orient=HORIZONTAL)
        self.markdownarea = Text(wrap=WORD, height=10,
                                 yscrollcommand=self.mdyScroll.set,
                                 xscrollcommand=self.mdxScroll.set)
        self.copymarkdown = Button(text="Copy To Clipboard",
                                  command=self.__copyMarkdown)
        self.mdxScroll.config(command=self.markdownarea.xview)
        self.mdyScroll.config(command=self.markdownarea.yview)

    def __vidButtons(self):
        self.modtitle = Button(text='Modify titles', command=self.__modTitles)
        #self.modtitle.grid(row=5, column=0, sticky=W, columnspan=2,
        #                   padx=self.padx, pady=self.pady)
        self.getcaps = Button(text="Get captions", command=self.__getCaptions)
        self.getcaps.grid(row=5, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmVidButtons(self):
        self.modtitle.grid_remove()
        self.getcaps.grid_remove()
        self.bind('<Return>', self.search_button)

    def __search(self):
        user = self.user_entry.get()
        playlist = self.playlist_id.get()
        searchterms = self.search_terms.get()
        self.__showResults()
        self.resultSelect.config(state=DISABLED)
        self.__rmVidButtons()
        self.__rmMarkdown()
        if not self.__validparams(user, searchterms, playlist):
            return False

        if len(playlist) > 0:
            self.__searchPlaylist(playlist)
            return

        self.__searchUser(user, searchterms)

    def __showMarkdown(self):
        self.markdownlabel.grid(row=5, column=0,
                                    padx=self.padx, pady=self.pady,
                                    sticky=W)
        self.markdownarea.grid(row=6, column=0, columnspan=5,
                               padx=self.padx, pady=self.pady,
                               sticky=N + S + E + W)
        self.mdyScroll.grid(row=6, column=5, sticky=N + S)
        self.mdxScroll.grid(row=7, column=0, sticky=E + W, columnspan=5)
        self.copymarkdown.grid(row=8, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmMarkdown(self):
        self.markdownarea.grid_forget()
        self.markdownlabel.grid_forget()
        self.copymarkdown.grid_forget()
        self.mdyScroll.grid_forget()
        self.mdxScroll.grid_forget()

    def __searchPlaylist(self, playlistid):
        self.__getvids(playlistid)

    def __searchUser(self, user, searchterms):
        self.listbox.delete(0, END)
        self.__status("Searching for%splaylists by user \"%s\"" % (
                      " \"%s\" " % searchterms if len(searchterms) else " ",
                      user))
        self.playlists = []
        try:
            self.playlists = lib.yt.search.PlaylistSearch(user=user,
                                                 search=searchterms).query()
        except HTTPError:
            self.__status("User %s does not exist at youtube" % user)
            return
        if self.playlists is None or len(self.playlists) == 0:
            self.__status("Search returned no results")
            return
        self.__populateResults([v['title'] for v in self.playlists])
        self.resultSelect.config(command=self.__getVidsFromSelected,
                                 state=NORMAL)
        self.__status("")
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)

    def __populateResults(self, values):
        self.listbox.delete(0, END)
        for i, val in enumerate(values):
            self.listbox.insert(i, val)
        self.listbox.activate(0)
        self.listbox.selection_set(0)

    def __getVidsFromSelected(self):
        selected = int(self.listbox.curselection()[0])
        self.__getvids(self.playlists[selected]['id'])

    def __getvids(self, playlistid):
        self.playlist_id.delete(0, END)
        self.playlist_id.insert(0, playlistid)
        self.resultSelect.grid_forget()
        title = playlistid
        if len(self.playlists) > 0:
            for playlist in self.playlists:
                if playlist['id'] == playlistid:
                    title = playlist['title']
                    break

        self.__status("Getting videos for %s" % title)
        self.listbox.delete(0, END)
        try:
            self.vids = lib.yt.search.PlaylistVideoSearch(
                                                    id=playlistid).query()
            self.__populateResults([v['title'] for v in self.vids])
            self.__status("%d Videos found" % len(self.vids))
            self.__vidButtons()
            self.bind('<Return>', self.getcaps)
        except HTTPError:
            self.__status("No videos found! is %s a valid playlist?" %
                          playlistid)

    def __status(self, msg):
        if len(msg) > 75:
            msg = msg[:70] + '...'
        self.status.config(text=msg)
        self.status.update_idletasks()

    def __trackSelect(self, vid, tracks, preftrack=None):
        pref = self.__prefAvailable(preftrack, tracks)
        if pref is None:
            sel = lib.trackSelect.TrackSelect(self, vid=vid,
                                              tracks=tracks)
            if sel.result is None:
                self.__status("skipped")
                tracks = None
            else:
                tracks = [sel.result[0]]
                if sel.preflang is not None:
                    preftrack['lang'] = sel.preflang
                if sel.prefname is not None:
                    preftrack['name'] = sel.prefname
        else:
            tracks = pref
        return tracks, preftrack

    def __getCaptions(self):
        preftrack = {'name': None, 'lang': None}
        self.listbox.delete(0, END)
        self.markdownarea.delete(1.0, END)
        self.__showMarkdown()
        for i, vid in enumerate(self.vids):
            nocapmsg = '[%02d] --NO CAPTIONS-- %s' % (i + 1, vid['title'])
            tracks = lib.yt.search.CaptionSearch(id=vid['id']).query()
            self.vids[i]['text'] = ''
            if len(tracks) == 0:
                self.__status('No captions available for %s' %
                              self.vids[i]['title'])
                self.listbox.insert(END, nocapmsg)

            elif len(tracks) > 1:
                sel = self.__trackSelect(vid, tracks, preftrack)
                if sel[0] is None:
                    msg = '[%02d] --SKIPPED-- %s' % (i + 1, vid['title'])
                    self.listbox.insert(END, msg)
                    self.listbox.see(END)
                    continue
                tracks = sel[0]

            if len(tracks) == 1:
                self.__trackCaps(i, tracks, nocapmsg)
        self.__status('')
        self.__hideResults()

    def __trackCaps(self, vidIndex, tracks, nocapmsg):
        i = vidIndex
        vid = self.vids[i]
        msg = '%02d of %02d Getting captions for %s' % (
                        i + 1, len(self.vids), self.vids[i]['title'])
        self.__status(msg)
        self.listbox.insert(END, msg)
        self.vids[i]['text'] = lib.markdown.heading(vid['title'])
        captions = lib.yt.search.GetCaptions(id=vid['id'],
                                lang=tracks[0]['lang'],
                                name=tracks[0]['name'])
        captions.query()
        captiontext = captions.textOnly()
        sleep(0.2)
        msg = nocapmsg
        if captiontext is not None and len(captiontext) > 0:
            self.vids[i]['text'] += (lib.markdown.to_utf8(captiontext)
                                     + '\n\n')
            msg = '[%02d] --DONE-- %s' % (i + 1, vid['title'])
        self.listbox.delete(END, END)
        self.listbox.insert(END, msg)
        self.listbox.see(END)
        self.markdownarea.insert(END, self.vids[i]['text'])
        self.markdownarea.see(END)

    def __prefAvailable(self, preftrack, tracks):
        if preftrack['lang'] is None:
            return None

        pref = None
        for track in tracks:
            if (track['lang'] == preftrack['lang'] and
                track['name'] == preftrack['name']):
                return [track]
            if track['lang'] == preftrack['lang'] and pref is None:
                pref = [track]

        return pref

    def __modTitles(self):
        pass

    def __validparams(self, user, searchterms, playlist):
        if len(user) == 0 and len(playlist) == 0:
            msg = "Either a valid youtube user or playlist id must be given."
            tkMessageBox.showwarning("missing information", msg)
            return False

        if len(user) > 0 and not self.__validstring(user):
            msg = "The user given contains invalid characters"
            tkMessageBox.showwarning('Bad user', msg)
            return False

        if len(playlist) > 0 and not self.__validstring(playlist):
            msg = "The playlist given contains invalid characters"
            tkMessageBox.showwarning('Bad playlist', msg)
            return False

        if len(searchterms) > 0 and not self.__validstring(searchterms, True):
            msg = "The search terms given contain invalid characters"
            tkMessageBox.showwarning('Bad search', msg)
            return False

        return True

    def __validstring(self, s, spacechar=False):
        validchars = string.letters + string.digits + string.punctuation
        if spacechar:
            validchars += ' '
        for c in s:
            if c not in validchars:
                return False
        return True

    def __copyMarkdown(self):
        self.markdownarea.clipboard_clear()
        self.markdownarea.clipboard_append(self.markdownarea.get(1.0, END))
Esempio n. 57
0
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()
Esempio n. 58
-1
class ResultList(Frame):
    """
    Result List widget
    """

    def __init__(self, master=None):
        Frame.__init__(self, master, padx=3, pady=3)
        self.columnconfigure(0, weight=1, minsize=50)
        self.columnconfigure(1, weight=1000)
        self.columnconfigure(2, weight=1, minsize=10)
        self.__createWidgets()
        self.show()

    def __createWidgets(self):
        self.lbl = Label(text="")
        self.lbl.grid(row=1, column=0, columnspan=2, in_=self)
        self.__hide_button = Button(text="Hide", command=self.hide)
        self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self)
        self.__yScroll = Scrollbar(orient=VERTICAL)
        self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE)
        self.__yScroll.config(command=self.list.yview)

    def show(self):
        self.__hide_button.config(text="Hide", command=self.hide)
        self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self)
        self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self)

    def hide(self):
        self.__hide_button.config(text="Show", command=self.show)
        self.list.grid_forget()
        self.__yScroll.grid_forget()

    def clear(self):
        self.list.delete(0, END)

    def fill(self, valList):
        self.clear()
        for v in valList:
            self.list.insert(END, v)
        self.list.see(0)
        self.select(0)

    def append(self, val):
        self.list.insert(END, val)
        self.list.see(END)

    def select(self, index=0):
        self.list.selection_set(index)

    def selected(self):
        return int(self.list.curselection()[0])

    def width(self, width):
        self.list.config(width=width)