Example #1
2
    def __bookmarks(self, master):
        panel = Frame(master)
        panel.grid_rowconfigure(0, weight=1)

        bookmarks = Frame(panel)
        bookmarks.grid_columnconfigure(0, weight=1)
        bookmarks.grid_rowconfigure(0, weight=1)

        li = Listbox(bookmarks, width=40)
        li.grid(column=0, row=0, sticky=(N, E, S, W))
        self.bookmarks_list = li

        sb = Scrollbar(bookmarks, orient=VERTICAL, command=li.yview)
        sb.grid(column=1, row=0, sticky=(N, S))

        li.config(yscrollcommand=sb.set)
        def _lbox_selected(*args):
            selected_idx = int(li.curselection()[0])
            self.render_start.set(self.bookmarks_values[selected_idx])
            self.canvas.xview_moveto(0)
            if not self.render_auto.get():
                self.update()
        li.bind('<Double-Button-1>', _lbox_selected)
        bookmarks.grid(column=0, row=0, sticky=(N, E, S, W))

        buttons = Frame(panel)
        Button(buttons, image=self.img_start, command=self.start_event).pack(side="left")
        Button(buttons, image=self.img_prev, command=self.prev_event).pack(side="left")
        Button(buttons, image=self.img_end, command=self.end_event).pack(side="right")
        Button(buttons, image=self.img_next, command=self.next_event).pack(side="right")
        buttons.grid(column=0, row=1, sticky=(E, W))

        return panel
Example #2
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']
        #This is a list of actresses to be shown in the listbox.

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
        #We create an instance of the Listbox and insert all the items from the above mentioned list.
            
        lb.bind("<<ListboxSelect>>", self.onSelect)
        #When we select an item in the listbox, the <<ListboxSelect>> event is generated. 
        #We bind the onSelect() method to this event.
        
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        #A label and its value holder is created. 
        #In this label we will display the currently selected item.
        self.label.place(x=20, y=210)
Example #3
0
class ScrolledList(Frame):
    def __init__(self, master, d_list, 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)

        #load the listbox
        idx = 0
        for item in d_list:
            fparts = item.split('.')
            # DEBUG print fparts
            if fparts[-1] == 'csv':
                self.listbox.insert(idx, item)
                idx += 1

        # 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))
Example #4
0
    def __init__(self, container, main_ui):
        self.main_ui = main_ui

        self.nicknameLabel = Label(container, text="Welcome to Sudoku!")
        self.nicknameLabel.pack(side=TOP)

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

        self.nicknameLabel = Label(self.frame_left, text="Enter nickname: ")
        self.nicknameLabel.pack(side=LEFT)

        self.entry = Entry(self.frame_left, bd=5)
        self.entry.pack(side=LEFT)

        self.enterButton = Button(self.frame_left,
                                  text="Proceed",
                                  command=self.handle_enter)
        self.enterButton.pack(side=LEFT, padx=20, pady=20)

        self.frame_right = Frame(container)
        self.frame_right.pack(side=RIGHT)

        self.nicknameLabel = Label(self.frame_right,
                                   text="Previously used names:")
        self.nicknameLabel.pack()

        nickname_lb = Listbox(self.frame_right)
        for idx, val in enumerate(read_usernames(
        )):  # Insert all previously used usernames to list
            nickname_lb.insert(idx, val)
        nickname_lb.pack()
        nickname_lb.bind('<<ListboxSelect>>', self.fill_nickname)
 def setPixelList(self):
     if "pixelListBox" in self.widgetDict.keys():
         pixelListBox = self.widgetDict["pixelListBox"]
         pixelListBox.delete(0, "end")
         self.widgetDict["kernelListbox"].config(text="Pixels: %s" % len(
             self.RepLine.getKernel(self.activeCob,
                                    self.activeKernel).keys()))
     else:
         pixelListbox = Listbox(self)
         self.widgetDict["pixelListbox"] = pixelListbox
         scrollbar = Scrollbar(pixelListbox, orient="vertical")
         pixelListbox.config(yscrollcommand=scrollbar.set)
         scrollbar.config(command=pixelListbox.yview)
         self.widgetDict["pixelsLabel"].config(text="Pixels: %s" % len(
             self.RepLine.getKernel(self.activeCob,
                                    self.activeKernel).keys()))
         pixelListbox.grid(row=3, column=2, rowspan=3, sticky="nsew")
         pixelListbox.columnconfigure(0, weight=1)
         pixelListbox.bind("<<ListboxSelect>>", self.updateActivePixel)
         scrollbar.grid(column=2, sticky="e")
     cobNumber = self.activeCob[:self.activeCob.index("_")]
     kernelNumber = self.activeKernel[self.activeKernel.index(" ") + 1:]
     kernel = self.RepLine.getKernel(int(cobNumber), int(kernelNumber))
     for pixelNumber in xrange(len(kernel.keys())):
         pixelListbox.insert(pixelNumber, "Pixel: %s" % pixelNumber)
Example #6
0
    def initUI(self):

        self.parent.title("Listbox + Scale + ChkBtn")
        self.pack(fill=BOTH, expand=1)
        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=190)

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.place(x=20, y=220)

        self.var_scale = IntVar()
        self.label_scale = Label(self, text=0, textvariable=self.var_scale)
        self.label_scale.place(x=180, y=220)

        self.var_chk = IntVar()
        cb = Checkbutton(self, text="Test", variable=self.var_chk,
                command=self.onClick)
        cb.select()
        cb.place(x=220, y=60)
Example #7
0
def documentation(version, w, h):
    def _setdoc(evt):
        w = evt.widget
        index = int(w.curselection()[0])
        doc = w.get(index)
        textfield.config(state=NORMAL)
        textfield.delete('1.0', END)
        textfield.insert('1.0', docdic[doc])
        textfield.config(state=DISABLED)
    r = Toplevel()
    w = int(w/2)
    h = int(h/2)
    r.geometry('{}x{}+{}+{}'.format(w, h, int(w/2), int(h/2)))
    r.wm_title('Documentation accpy version {}'.format(version))

    lf = Frame(r)
    lf.pack(side=LEFT, fill=BOTH, expand=False)
    rf = Frame(r)
    rf.pack(side=RIGHT, fill=BOTH, expand=True)

    docmenuopts = ['General',
                   'Lattice editor',
                   'Citation']
    docmenu = Listbox(lf)
    for entry in docmenuopts:
        docmenu.insert(END, entry)
    docmenu.pack(fill=BOTH, expand=True)
    docmenu.bind('<<ListboxSelect>>', _setdoc)

    scrollbar = Scrollbar(orient="vertical")
    textfield = Text(rf, xscrollcommand=scrollbar.set)
    textfield.pack(fill=BOTH, expand=True)
Example #8
0
    def initUI(self):
        self.parent.title("ListBox")
        self.pack(fill=BOTH, expand=1)

        eagles = ["Sam Bradford", "Jordan Matthews", "LeBron James", "Donnie Jones"]
        lb = Listbox(self)
        for i in eagles:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)
        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()
    def printAnts(self):
        frameAnts = Frame(self.FrameInfo)
        Text_A = Label(frameAnts, text="Fourmie :")
        s1 = Scrollbar(frameAnts)
        l1 = Listbox(frameAnts)
        id_ants = self.checkAnts()
        for i in id_ants: l1.insert(i, str(i))
        s1.config(command = l1.yview)
        l1.config(yscrollcommand = s1.set)
        l1.bind('<ButtonRelease-1>',self.choiceAnt)
        self.listbox = l1
        Text_A.pack(side = TOP)
        l1.pack(side = LEFT)
        s1.pack(side = RIGHT)
        frameAnts.pack()

        self.printInfoAnt(id_ants[0])
        self.frameAnts = frameAnts
Example #10
0
    def initUI(self):
      
        self.parent.title("Listbox")          
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
            
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.pack()
    def printAnts(self):
        frameAnts = Frame(self.FrameInfo)
        Text_A = Label(frameAnts, text="Fourmie :")
        s1 = Scrollbar(frameAnts)
        l1 = Listbox(frameAnts)
        id_ants = self.checkAnts()
        for i in id_ants:
            l1.insert(i, str(i))
        s1.config(command=l1.yview)
        l1.config(yscrollcommand=s1.set)
        l1.bind('<ButtonRelease-1>', self.choiceAnt)
        self.listbox = l1
        Text_A.pack(side=TOP)
        l1.pack(side=LEFT)
        s1.pack(side=RIGHT)
        frameAnts.pack()

        self.printInfoAnt(id_ants[0])
        self.frameAnts = frameAnts
Example #12
0
def run():
  roboveroConfig()
  
  # draw a listbox
  root = Tk()
  root.title("Tone Generator")
  
  # populate the list with available frequencies
  tone_listbox = Listbox(root)
  
  tone_listbox.insert(END, "OFF")
  for freq in range(100, 1000, 100):
     tone_listbox.insert(END, "%d Hz" % freq)
  tone_listbox.pack()
  
  # set the callback function for left button clicks
  tone_listbox.bind('<ButtonRelease-1>', playSelection)
  
  root.mainloop()
Example #13
0
def tk_main():
    candidates = make_transform(make_candidate_dict())
    sorted_dict = sorted(candidates.items(),
                         key=lambda x: float(x[1][0]),
                         reverse=True)

    def on_select(evt):
        w = evt.widget
        index = int(w.curselection()[0])
        txt = ''

        for n in range(len(sorted_dict[index][1][1])):
            #txt += sorted_dict[index][1][1][n]
            #txt += '\n'
            #txt += repr(sorted_dict[index][1][4][n])
            #txt += '\n'
            #txt += repr(sorted_dict[index][1][5][n])
            #txt += '\n\n'
            txt1 = ''
            txt2 = ''
            if sorted_dict[index][1][4][n]:
                txt1 += 'A'
                txt2 += 'N: ' + ', '.join(sorted_dict[index][1][4][n]) + '\n'
            if sorted_dict[index][1][5][n]:
                txt1 += 'N'
                txt2 += 'A: ' + ', '.join(sorted_dict[index][1][5][n]) + '\n'
            if txt1:
                txt1 = '[' + txt1 + ']' + sorted_dict[index][1][1][n].upper()
                txt += txt1 + '\n' + txt2 + '\n'

        textbox = Label(root, name='textbox', text=txt, width=125)
        textbox.pack(side=LEFT)

    root = Tk()
    listbox = Listbox(root, name='listbox', width=50, exportselection=0)
    listbox.bind('<<ListboxSelect>>', on_select)
    for i, c in enumerate(sorted_dict):
        listbox.insert(i, c[0] + '    ' + c[1][0])
    listbox.pack(side=LEFT)

    txt = 'Hola Mundo Cruel!'
    textbox = Label(root, name='textbox', text=txt, width=125)
    textbox.pack(side=LEFT)
Example #14
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
            
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=210)
Example #15
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)
Example #16
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        # put our data in from our global data object
        lb = Listbox(self)
        for i in data:
            lb.insert(END, i)
            
        # add event listener with call back to show
        # when the list object is selected, show visual feedback
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        # absolute positioning
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=210)
Example #17
0
    def initUI(self):

        self.parent.title("Listbox")

        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba', 'Someone Else']

        with open('test.txt', 'rb') as f:

            lb = Listbox(self)
            for i in f:
                lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)

        lb.pack(pady=15)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.pack()
 def setKernelList(self):
     self.kernelList = []
     for i in xrange(len(self.RepLine.cobs[self.activeCob])):
         self.kernelList.append("Kernel: " + str(i + 1))
     if "kernelListbox" in self.widgetDict.keys():
         kernelListbox = self.widgetDict["kernelListbox"]
         kernelListbox.delete(0, "end")
         self.widgetDict["kernelsLabel"].config(text="Kernels: %s" %
                                                len(self.kernelList))
     else:
         kernelListbox = Listbox(self)
         self.widgetDict["kernelListbox"] = kernelListbox
         scrollbar = Scrollbar(kernelListbox, orient="vertical")
         kernelListbox.config(yscrollcommand=scrollbar.set)
         scrollbar.config(command=kernelListbox.yview)
         self.widgetDict["kernelsLabel"].config(text="Kernels: %s" %
                                                len(self.kernelList))
         kernelListbox.grid(row=3, column=1, rowspan=3, sticky="nsew")
         kernelListbox.columnconfigure(0, weight=1)
         kernelListbox.bind("<<ListboxSelect>>", self.updateActiveKernel)
         scrollbar.grid(column=1, sticky="e")
     for kernel in self.kernelList:
         kernelListbox.insert(self.kernelList.index(kernel), kernel)
Example #19
0
    def create_file_list_widgets(self):
        frmFsList = self._wm['frmFsList']
        self._lbfs_var = StringVar()
        lbFs = Listbox(frmFsList, listvariable=self._lbfs_var)
        lbFs.pack(side=LEFT, expand=1, fill=BOTH)
        frmSbY = self._wm['frmSbY']
        sbY = Scrollbar(frmSbY)
        sbY.pack(side=TOP, expand=1, fill=Y)
        frmSbX = self._wm['frmSbX']
        sbX = Scrollbar(frmSbX, orient=HORIZONTAL)
        sbX.pack(side=TOP, expand=1, fill=X)

        lbFs['yscrollcommand'] = sbY.set
        sbY['command'] = lbFs.yview
        lbFs['xscrollcommand'] = sbX.set
        sbX['command'] = lbFs.xview

        self.create_file_list_popmenu()
        lbFs.bind("<Button-3>", self.pop_fs_menu)

        self._wm['lbFs'] = lbFs
        self._wm['sbY'] = sbY
        self._wm['sbX'] = sbX
Example #20
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)
 def setCobList(self):
     self.cobList = []
     for cob in xrange(len(self.RepLine.cobs.keys())):
         self.cobList.append(
             str(cob + 1) + "_" + self.RepLine.accessionName)
     if "cobListbox" in self.widgetDict.keys():
         cobListbox = self.widgetDict["cobListbox"]
         cobListbox.delete(0, "end")
         self.widgetDict["cobsLabel"].config(text="Cobs: %s" %
                                             len(self.cobList))
     else:
         cobListbox = Listbox(self)
         self.widgetDict["cobListbox"] = cobListbox
         scrollbar = Scrollbar(cobListbox, orient="vertical")
         cobListbox.config(yscrollcommand=scrollbar.set)
         scrollbar.config(command=cobListbox.yview)
         self.widgetDict["cobsLabel"].config(text="Cobs: %s" %
                                             len(self.cobList))
         cobListbox.grid(row=3, column=0, rowspan=3, sticky="nsew")
         cobListbox.columnconfigure(0, weight=1)
         cobListbox.bind("<<ListboxSelect>>", self.updateActiveCob)
         scrollbar.grid(column=0, sticky="e")
     for cob in self.cobList:
         cobListbox.insert(self.cobList.index(cob), cob)
Example #22
0
File: CTA.py Project: Panumy/CTA-DB
def menu_press_acc_reqs():
    global row, listbox, lab
    root.geometry('220x170')
    F1 = Frame()
    lab = Label(root)
    s = Scrollbar(F1)
    listbox = Listbox(F1)
    s.pack(side=RIGHT, fill=Y)
    listbox.bind('<<ListboxSelect>>', onselect)
    listbox.pack(side=LEFT, fill=Y)
    F1.grid(column=0, row=0)
    s['command'] = listbox.yview
    listbox['yscrollcommand'] = s.set
    apprbtt = Button(root, text="Approved", command=app_acc)
    denybtt = Button(root, text="Denied")
    lab.place(relx=0.77, x=1, y=30, anchor=W)
    apprbtt.place(relx=0.67, x=1, y=60, anchor=W)
    denybtt.place(relx=0.7, x=1, y=100, anchor=W)
    forget_all()
    cursor.execute('''SELECT `username` FROM db_REQ''')
    while row is not None:
        for item in [row]:
            listbox.insert(END, row)
        row = cursor.fetchone()
Example #23
0
    def __init__(self, master, columns, cnf={}, **kw):
        """
        Construct a listbox widget with one or many column and label field for header

        Valid resource names: background, bd, bg, borderwidth, class, colormap,
        fg, font, foreground, height, highlightbackground,
        """
        Frame.__init__(self, master)
        if not columns:
            raise Exception('2 or many Columns required')

        # Construct label containers
        self.libelle = Frame(self)
        self.libelle.pack(side='top')
        # Construct Listbox containers
        self.listboxs = Frame(self)
        self.listboxs.pack(side='bottom', expand='yes', fill='both')
        self.columns = []

        # Contruct all columns (listbox) with title (label)
        for texte, dimension in columns:
            # Create title
            Label(
                self.libelle,
                kw,
                text=texte,
                width=dimension
            ).pack(side='left', expand='yes')
            # Create columns
            listbox = Listbox(self.listboxs, width=dimension, exportselection='false')
            listbox.pack(expand='yes', fill='both', side='left')
            # Bind all event for override
            listbox.bind('<B1-Motion>', lambda e, s=self: s._select(e.y))
            listbox.bind('<Button-1>', lambda e, s=self: s._select(e.y))
            listbox.bind('<Leave>', lambda e: 'break')
            # Add listbox to list
            self.columns.append(listbox)
Example #24
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()
Example #25
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)
Example #26
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)
Example #27
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']
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)
Example #29
0
class GetKeysDialog(Toplevel):
    def __init__(self,parent,title,action,currentKeySequences,_htest=False):
        """
        action - string, the name of the virtual event these keys will be
                 mapped to
        currentKeys - list, a list of all key sequence lists currently mapped
                 to virtual events, for overlap checking
        _htest - bool, change box location when running htest
        """
        Toplevel.__init__(self, parent)
        self.configure(borderwidth=5)
        self.resizable(height=FALSE,width=FALSE)
        self.title(title)
        self.transient(parent)
        self.grab_set()
        self.protocol("WM_DELETE_WINDOW", self.Cancel)
        self.parent = parent
        self.action=action
        self.currentKeySequences=currentKeySequences
        self.result=''
        self.keyString=StringVar(self)
        self.keyString.set('')
        self.SetModifiersForPlatform() # set self.modifiers, self.modifier_label
        self.modifier_vars = []
        for modifier in self.modifiers:
            variable = StringVar(self)
            variable.set('')
            self.modifier_vars.append(variable)
        self.advanced = False
        self.CreateWidgets()
        self.LoadFinalKeyList()
        self.withdraw() #hide while setting geometry
        self.update_idletasks()
        self.geometry(
                "+%d+%d" % (
                    parent.winfo_rootx() +
                    (parent.winfo_width()/2 - self.winfo_reqwidth()/2),
                    parent.winfo_rooty() +
                    ((parent.winfo_height()/2 - self.winfo_reqheight()/2)
                    if not _htest else 150)
                ) )  #centre dialog over parent (or below htest box)
        self.deiconify() #geometry set, unhide
        self.wait_window()

    def CreateWidgets(self):
        frameMain = Frame(self,borderwidth=2,relief=SUNKEN)
        frameMain.pack(side=TOP,expand=TRUE,fill=BOTH)
        frameButtons=Frame(self)
        frameButtons.pack(side=BOTTOM,fill=X)
        self.buttonOK = Button(frameButtons,text='OK',
                width=8,command=self.OK)
        self.buttonOK.grid(row=0,column=0,padx=5,pady=5)
        self.buttonCancel = Button(frameButtons,text='Cancel',
                width=8,command=self.Cancel)
        self.buttonCancel.grid(row=0,column=1,padx=5,pady=5)
        self.frameKeySeqBasic = Frame(frameMain)
        self.frameKeySeqAdvanced = Frame(frameMain)
        self.frameControlsBasic = Frame(frameMain)
        self.frameHelpAdvanced = Frame(frameMain)
        self.frameKeySeqAdvanced.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
        self.frameKeySeqBasic.grid(row=0,column=0,sticky=NSEW,padx=5,pady=5)
        self.frameKeySeqBasic.lift()
        self.frameHelpAdvanced.grid(row=1,column=0,sticky=NSEW,padx=5)
        self.frameControlsBasic.grid(row=1,column=0,sticky=NSEW,padx=5)
        self.frameControlsBasic.lift()
        self.buttonLevel = Button(frameMain,command=self.ToggleLevel,
                text='Advanced Key Binding Entry >>')
        self.buttonLevel.grid(row=2,column=0,stick=EW,padx=5,pady=5)
        labelTitleBasic = Label(self.frameKeySeqBasic,
                text="New keys for  '"+self.action+"' :")
        labelTitleBasic.pack(anchor=W)
        labelKeysBasic = Label(self.frameKeySeqBasic,justify=LEFT,
                textvariable=self.keyString,relief=GROOVE,borderwidth=2)
        labelKeysBasic.pack(ipadx=5,ipady=5,fill=X)
        self.modifier_checkbuttons = {}
        column = 0
        for modifier, variable in zip(self.modifiers, self.modifier_vars):
            label = self.modifier_label.get(modifier, modifier)
            check=Checkbutton(self.frameControlsBasic,
                command=self.BuildKeyString,
                text=label,variable=variable,onvalue=modifier,offvalue='')
            check.grid(row=0,column=column,padx=2,sticky=W)
            self.modifier_checkbuttons[modifier] = check
            column += 1
        labelFnAdvice=Label(self.frameControlsBasic,justify=LEFT,
                            text=\
                            "Select the desired modifier keys\n"+
                            "above, and the final key from the\n"+
                            "list on the right.\n\n" +
                            "Use upper case Symbols when using\n" +
                            "the Shift modifier.  (Letters will be\n" +
                            "converted automatically.)")
        labelFnAdvice.grid(row=1,column=0,columnspan=4,padx=2,sticky=W)
        self.listKeysFinal=Listbox(self.frameControlsBasic,width=15,height=10,
                selectmode=SINGLE)
        self.listKeysFinal.bind('<ButtonRelease-1>',self.FinalKeySelected)
        self.listKeysFinal.grid(row=0,column=4,rowspan=4,sticky=NS)
        scrollKeysFinal=Scrollbar(self.frameControlsBasic,orient=VERTICAL,
                command=self.listKeysFinal.yview)
        self.listKeysFinal.config(yscrollcommand=scrollKeysFinal.set)
        scrollKeysFinal.grid(row=0,column=5,rowspan=4,sticky=NS)
        self.buttonClear=Button(self.frameControlsBasic,
                text='Clear Keys',command=self.ClearKeySeq)
        self.buttonClear.grid(row=2,column=0,columnspan=4)
        labelTitleAdvanced = Label(self.frameKeySeqAdvanced,justify=LEFT,
                text="Enter new binding(s) for  '"+self.action+"' :\n"+
                "(These bindings will not be checked for validity!)")
        labelTitleAdvanced.pack(anchor=W)
        self.entryKeysAdvanced=Entry(self.frameKeySeqAdvanced,
                textvariable=self.keyString)
        self.entryKeysAdvanced.pack(fill=X)
        labelHelpAdvanced=Label(self.frameHelpAdvanced,justify=LEFT,
            text="Key bindings are specified using Tkinter keysyms as\n"+
                 "in these samples: <Control-f>, <Shift-F2>, <F12>,\n"
                 "<Control-space>, <Meta-less>, <Control-Alt-Shift-X>.\n"
                 "Upper case is used when the Shift modifier is present!\n\n" +
                 "'Emacs style' multi-keystroke bindings are specified as\n" +
                 "follows: <Control-x><Control-y>, where the first key\n" +
                 "is the 'do-nothing' keybinding.\n\n" +
                 "Multiple separate bindings for one action should be\n"+
                 "separated by a space, eg., <Alt-v> <Meta-v>." )
        labelHelpAdvanced.grid(row=0,column=0,sticky=NSEW)

    def SetModifiersForPlatform(self):
        """Determine list of names of key modifiers for this platform.

        The names are used to build Tk bindings -- it doesn't matter if the
        keyboard has these keys, it matters if Tk understands them. The
        order is also important: key binding equality depends on it, so
        config-keys.def must use the same ordering.
        """
        if sys.platform == "darwin":
            self.modifiers = ['Shift', 'Control', 'Option', 'Command']
        else:
            self.modifiers = ['Control', 'Alt', 'Shift']
        self.modifier_label = {'Control': 'Ctrl'} # short name

    def ToggleLevel(self):
        if  self.buttonLevel.cget('text')[:8]=='Advanced':
            self.ClearKeySeq()
            self.buttonLevel.config(text='<< Basic Key Binding Entry')
            self.frameKeySeqAdvanced.lift()
            self.frameHelpAdvanced.lift()
            self.entryKeysAdvanced.focus_set()
            self.advanced = True
        else:
            self.ClearKeySeq()
            self.buttonLevel.config(text='Advanced Key Binding Entry >>')
            self.frameKeySeqBasic.lift()
            self.frameControlsBasic.lift()
            self.advanced = False

    def FinalKeySelected(self,event):
        self.BuildKeyString()

    def BuildKeyString(self):
        keyList = modifiers = self.GetModifiers()
        finalKey = self.listKeysFinal.get(ANCHOR)
        if finalKey:
            finalKey = self.TranslateKey(finalKey, modifiers)
            keyList.append(finalKey)
        self.keyString.set('<' + string.join(keyList,'-') + '>')

    def GetModifiers(self):
        modList = [variable.get() for variable in self.modifier_vars]
        return [mod for mod in modList if mod]

    def ClearKeySeq(self):
        self.listKeysFinal.select_clear(0,END)
        self.listKeysFinal.yview(MOVETO, '0.0')
        for variable in self.modifier_vars:
            variable.set('')
        self.keyString.set('')

    def LoadFinalKeyList(self):
        #these tuples are also available for use in validity checks
        self.functionKeys=('F1','F2','F2','F4','F5','F6','F7','F8','F9',
                'F10','F11','F12')
        self.alphanumKeys=tuple(string.ascii_lowercase+string.digits)
        self.punctuationKeys=tuple('~!@#%^&*()_-+={}[]|;:,.<>/?')
        self.whitespaceKeys=('Tab','Space','Return')
        self.editKeys=('BackSpace','Delete','Insert')
        self.moveKeys=('Home','End','Page Up','Page Down','Left Arrow',
                'Right Arrow','Up Arrow','Down Arrow')
        #make a tuple of most of the useful common 'final' keys
        keys=(self.alphanumKeys+self.punctuationKeys+self.functionKeys+
                self.whitespaceKeys+self.editKeys+self.moveKeys)
        self.listKeysFinal.insert(END, *keys)

    def TranslateKey(self, key, modifiers):
        "Translate from keycap symbol to the Tkinter keysym"
        translateDict = {'Space':'space',
                '~':'asciitilde','!':'exclam','@':'at','#':'numbersign',
                '%':'percent','^':'asciicircum','&':'ampersand','*':'asterisk',
                '(':'parenleft',')':'parenright','_':'underscore','-':'minus',
                '+':'plus','=':'equal','{':'braceleft','}':'braceright',
                '[':'bracketleft',']':'bracketright','|':'bar',';':'semicolon',
                ':':'colon',',':'comma','.':'period','<':'less','>':'greater',
                '/':'slash','?':'question','Page Up':'Prior','Page Down':'Next',
                'Left Arrow':'Left','Right Arrow':'Right','Up Arrow':'Up',
                'Down Arrow': 'Down', 'Tab':'Tab'}
        if key in translateDict.keys():
            key = translateDict[key]
        if 'Shift' in modifiers and key in string.ascii_lowercase:
            key = key.upper()
        key = 'Key-' + key
        return key

    def OK(self, event=None):
        if self.advanced or self.KeysOK():  # doesn't check advanced string yet
            self.result=self.keyString.get()
            self.destroy()

    def Cancel(self, event=None):
        self.result=''
        self.destroy()

    def KeysOK(self):
        '''Validity check on user's 'basic' keybinding selection.

        Doesn't check the string produced by the advanced dialog because
        'modifiers' isn't set.

        '''
        keys = self.keyString.get()
        keys.strip()
        finalKey = self.listKeysFinal.get(ANCHOR)
        modifiers = self.GetModifiers()
        # create a key sequence list for overlap check:
        keySequence = keys.split()
        keysOK = False
        title = 'Key Sequence Error'
        if not keys:
            tkMessageBox.showerror(title=title, parent=self,
                                   message='No keys specified.')
        elif not keys.endswith('>'):
            tkMessageBox.showerror(title=title, parent=self,
                                   message='Missing the final Key')
        elif (not modifiers
              and finalKey not in self.functionKeys + self.moveKeys):
            tkMessageBox.showerror(title=title, parent=self,
                                   message='No modifier key(s) specified.')
        elif (modifiers == ['Shift']) \
                 and (finalKey not in
                      self.functionKeys + self.moveKeys + ('Tab', 'Space')):
            msg = 'The shift modifier by itself may not be used with'\
                  ' this key symbol.'
            tkMessageBox.showerror(title=title, parent=self, message=msg)
        elif keySequence in self.currentKeySequences:
            msg = 'This key combination is already in use.'
            tkMessageBox.showerror(title=title, parent=self, message=msg)
        else:
            keysOK = True
        return keysOK
Example #30
0
File: booru.py Project: 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()
Example #31
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)
Example #32
0
class Application(Frame):
    def compress(self, sCTRL, dCTRL, eCTRL, gCTRL):

        allCTRL = {
            'Student': sCTRL,
            'Discipline': dCTRL,
            'Enroll': eCTRL,
            'Grade': gCTRL
        }
        pickle.dump(allCTRL, open("save.p", "wb"))

    def compare(self):
        if self.oCont >= self.Max:
            self.Max = self.oCont
            return

    def reader(self, Input, InputNumber):
        try:
            Input.getvar((str(InputNumber)))
        except TclError as tcl:
            s = str(tcl)
            return s.split("\"")[1]

    def clearText(self):
        self.textFrame.delete('1.0', END)

    def Srefresh(self):
        controller = self._studentControl.getCurentRepo().getStudents()
        curList = self.sList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def Drefresh(self):
        controller = self._disciplineControl.getCurentRepo().getDisciplines()
        curList = self.dList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def Erefresh(self):
        controller = self._enrolControl.getCurentRepo().getEnroll()
        curList = self.eList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def Grefresh(self):
        controller = self._gradeControl.getCurentRepo().getGrades()
        curList = self.gList
        curList.delete(0, END)
        controller.sort()
        for index in controller:
            curList.insert(END, index)

    def refreshALL(self):
        self.Srefresh()
        self.Drefresh()
        self.Erefresh()
        self.Grefresh()

    def SreadID(self, string):
        return string[11:string.index('|') - 1]

    def DreadID(self, string):
        return string[15:string.index('|') - 1]

    def EreadID(self, string):
        return [
            string[12:string.index('|') - 1], string[string.index('|') + 15:-2]
        ]

    def sPopup(self, event):
        self.sMenu.post(event.x_root, event.y_root)

    def dPopup(self, event):
        self.dMenu.post(event.x_root, event.y_root)

    def ePopup(self, event):
        self.eMenu.post(event.x_root, event.y_root)

    def gPopup(self, event):
        self.gMenu.post(event.x_root, event.y_root)

    def displayError(self, msg):
        tkMessageBox.showerror('Error', msg)

    def NewFile(self):
        self._studentControl.setRepo(deepcopy(student(1, '')))
        self._disciplineControl.setRepo(deepcopy(discipline(1, '')))
        self._enrolControl.setRepo(deepcopy(enroll(1, 1)))
        self._gradeControl.setRepo(deepcopy(grade(1, 1)))
        self.refreshALL()

    '''
    #============================================#
    :STUDENT:
    #============================================#
    '''

    def add_Student(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = Window2('Enter student ID: ', 'Enter student Name: ', top)
            Input.mainloop()
            top.destroy()

            if not Input.getvar(str(
                    Input.Input1)) == None and not Input.getvar(
                        str(Input.Input2)) == None:

                studentID = Input.getvar(str(Input.Input1))
                name = Input.getvar(str(Input.Input2))

                print studentID
                print name

                Valid().ID(studentID)
                Valid().name(name)

                self._studentControl.getCurentRepo().addStudent(
                    student(int(studentID), name))
                self._studentControl.create(int(studentID), name)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except idError:
            self.displayError('Invalid ID')

    def remove_Student(self):
        try:
            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            name = ''
            eList = []
            gList = []

            for Student in self._studentControl.getCurentRepo().getStudents():
                if int(Student.getId()) == studentID:
                    name = Student.getName()

            for enroll in self._enrolControl.getCurentRepo().getEnroll():
                if enroll.get_student_id() == studentID:
                    eList.append(enroll)

            for grade in self._gradeControl.getCurentRepo().getGrades():
                if int(grade.getStudentID()) == studentID:
                    gList.append(grade)

            try:
                self._studentControl.removeStudent(studentID)
            except classException:
                pass
            try:
                self._enrolControl.removeEnrollStudent(studentID)
            except classException:
                pass
            try:
                self._gradeControl.removeGradeStudent(studentID)
            except classException:
                pass

            self._studentControl.delete(studentID, eList, gList, name)

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_StudentID(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New ID', top)
            Input.mainloop()
            top.destroy()

            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            if not Input.getvar(str(Input.Input1)) == None:
                newID = Input.getvar(str(Input.Input1))
                newID = int(newID)
                self._studentControl.getCurentRepo().updateStudentID(
                    studentID, newID)
                self._enrolControl.getCurentRepo().updateStudentID(
                    studentID, newID)
                self._gradeControl.getCurentRepo().updateGradeStudentID(
                    int(studentID), newID)

                self._studentControl.updateID(studentID, newID)

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_StudentName(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New name', top)
            Input.mainloop()
            top.destroy()

            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            oldName = self.sList.get(index)[self.sList.get(index).index('|') +
                                            9:-2]

            if not Input.getvar(str(Input.Input1)) == None:
                newName = Input.getvar(str(Input.Input1))
                Valid().name(newName)
                self._studentControl.getCurentRepo().updateStudentName(
                    studentID, newName)

                self._studentControl.updateName(studentID, oldName, newName)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #=============================================#
    :DISCIPLINE:
    #=============================================#
    '''

    def add_Discipline(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = Window2('Enter discipline ID: ', 'Enter discipline Name: ',
                            top)
            Input.mainloop()
            top.destroy()

            if not Input.getvar(str(Input.Input1)) == None or not Input.getvar(
                    str(Input.Input2)) == None:
                disciplineID = Input.getvar(str(Input.Input1))
                name = Input.getvar(str(Input.Input2))
                Valid().name(name)
                Valid().ID(disciplineID)
                self._disciplineControl.getCurentRepo().addDiscipline(
                    discipline(int(disciplineID), name))

                self._disciplineControl.create(int(disciplineID), name)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

        except idError:
            self.displayError('Invalid ID')

    def remove_Discipline(self):
        try:
            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            name = ''
            eList = []
            gList = []

            for Discipline in self._disciplineControl.getCurentRepo(
            ).getDisciplines():
                if int(Discipline.getId()) == disciplineID:
                    name = Discipline.getName()

            for enroll in self._enrolControl.getCurentRepo().getEnroll():
                if enroll.get_discipline_id() == disciplineID:
                    eList.append(enroll)

            for grade in self._gradeControl.getCurentRepo().getGrades():
                if grade.getDisciplineID() == disciplineID:
                    gList.append(grade)

            try:
                self._disciplineControl.removeDiscipline(disciplineID)
            except classException:
                pass
            try:
                self._gradeControl.removeGradeDiscipline(disciplineID)
            except classException:
                pass

            try:
                self._enrolControl.removeEnrollDiscipline(disciplineID)
            except classException:
                pass

            try:
                self._disciplineControl.delete(disciplineID, eList, gList,
                                               name)
            except classException:
                pass

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_DisciplineID(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New ID', top)
            Input.mainloop()
            top.destroy()

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            if not Input.getvar(str(Input.Input1)) == None:
                newID = Input.getvar(str(Input.Input1))
                newID = int(newID)
                self._disciplineControl.getCurentRepo().updateDisciplineID(
                    disciplineID, newID)
                self._enrolControl.getCurentRepo().updateDisciplineID(
                    disciplineID, newID)
                self._gradeControl.getCurentRepo().updateGradeDisciplineID(
                    disciplineID, newID)

                self._disciplineControl.updateID(disciplineID, newID)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def update_DisciplineName(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('New name', top)
            Input.mainloop()
            top.destroy()

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            oldName = self.dList.get(index)[self.dList.get(index).index('|') +
                                            8:-2]

            if not Input.getvar(str(Input.Input1)) == None:
                newName = Input.getvar(str(Input.Input1))
                Valid().name(newName)
                self._disciplineControl.getCurentRepo().updateDisciplineName(
                    disciplineID, newName)

                self._disciplineControl.updateName(disciplineID, oldName,
                                                   newName)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #===================================================#
    :ENROLL:
    #===================================================#
    '''

    def remove_Enroll(self):
        try:
            index = self.eList.curselection()
            IDs = self.EreadID(self.eList.get(index))
            studentID = int(IDs[0])
            disicplineID = int(IDs[1])

            self.eList.delete(ANCHOR)
            self._gradeControl.removeGrade(enroll(studentID, disicplineID))
            self._enrolControl.removeEnroll(enroll(studentID, disicplineID))
            self.Erefresh()
            self.Grefresh()

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def add_Enroll(self):
        try:
            index = self.sList.curselection()
            studentID = self.SreadID(self.sList.get(index))
            studentID = int(studentID)

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            #try:
            self._enrolControl.addEnroll(enroll(studentID, disciplineID))
            #except ValueError:
            #self.displayError('Enrollment allready exists')

            self._enrolControl.create(enroll(studentID, disciplineID))

            self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    def add_EnrollGrade(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('Grade: ', top)
            Input.mainloop()
            top.destroy()

            index = self.eList.curselection()
            IDs = self.EreadID(self.eList.get(index))
            studentID = int(IDs[0])
            disciplineID = int(IDs[1])

            if not Input.getvar(str(Input.Input1)) == None:
                gradeValue = Input.getvar(str(Input.Input1))
                gradeValue = float(gradeValue)

                Valid().grade(gradeValue)

                self._gradeControl.addGrade(grade(disciplineID, studentID),
                                            gradeValue)
                self.Grefresh()

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #=======================================================#
    :GRADE:
    #=======================================================#
    '''

    def add_Grade(self):
        try:
            top = tk.Toplevel()
            top.title('Input')
            Input = WindowRemove('Grade: ', top)
            Input.mainloop()
            top.destroy()

            index = self.gList.curselection()
            IDs = self.EreadID(self.eList.get(index))
            studentID = int(IDs[0])
            disciplineID = int(IDs[1])

            if not Input.getvar(str(Input.Input1)) == None:
                gradeValue = Input.getvar(str(Input.Input1))
                gradeValue = float(gradeValue)

                Valid().grade(gradeValue)

                self._gradeControl.addGrade(grade(disciplineID, studentID),
                                            gradeValue)

                self._gradeControl.create(grade(disciplineID, studentID),
                                          gradeValue)

                self.refreshALL()

        except ValueError:
            self.displayError('Invalid Input')

        except NameError:
            self.displayError('Invalid Name')

        except TclError:
            self.displayError('No item selected')

    '''
    #================================================#  
    :SEARCH:
    #================================================#
    '''

    def SearchALL(self):

        top = tk.Toplevel()
        top.title('Input')
        Input = WindowRemove('Search: ', top)
        Input.mainloop()
        top.destroy()

        searchString = Input.getvar(str(Input.Input1))

        top = tk.Toplevel()
        top.title('Serch Results')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        top.text.insert(END, 'Disciplines:')
        for discipline in self._disciplineControl.getCurentRepo(
        ).getDisciplines():
            if searchString.lower() in str(discipline.getId()).lower() or str(
                    discipline.getId()).lower() in searchString.lower(
                    ) or searchString.lower() in discipline.getName().lower(
                    ) or discipline.getName().lower() in searchString.lower():
                top.text.insert(END, discipline)

        top.text.insert(END, 'Students:')
        for student in self._studentControl.getCurentRepo().getStudents():
            if searchString.lower() in str(student.getId()).lower() or str(
                    student.getId()).lower() in searchString.lower(
                    ) or searchString.lower() in student.getName().lower(
                    ) or student.getName().lower() in searchString.lower():
                top.text.insert(END, student)

    '''
    #===============================================#
    :STATISCTICS:
    #===============================================#
    '''

    def StudentEnrollA(self):

        try:

            top = tk.Toplevel()
            top.title('Enrollment List')
            top.text = Listbox(top)
            top.text.grid(row=0, column=0)

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            SList = self._enrolControl.studentEnrollA(disciplineID)

            for index in SList:
                top.text.insert(END, index)

            del SList[:]

        except TclError:
            top.destroy()
            self.displayError('No disicpline Selected')

    def StudentEnrollB(self):

        try:
            top = tk.Toplevel()
            top.title('Enrollment List')
            top.text = Listbox(top)
            top.text.grid(row=0, column=0)

            index = self.dList.curselection()
            disciplineID = self.DreadID(self.dList.get(index))
            disciplineID = int(disciplineID)

            SList = [[' ', -1]]
            for grade in self._gradeControl.getCurentRepo().getGrades():
                if grade.getDisciplineID() == disciplineID:
                    for student in self._studentControl.getCurentRepo(
                    ).getStudents():
                        if student.getId() == grade.getStudentID():
                            if grade.getGrade() != []:
                                gradeAvg = self.listAvg(
                                    grade.getGrade(), grade.getGradeSize())
                                SList.append([student.getName(), gradeAvg])

            SList.sort(key=itemgetter(1), reverse=True)
            del SList[-1]
            for index in SList:
                top.text.insert(END, index)
            del SList[:]

        except TclError:
            top.destroy()
            self.displayError('No disicpline Selected')

    def FailingStudents(self):

        top = tk.Toplevel()
        top.title('Enrollment List')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        sList = [['', '']]
        for grade in self._gradeControl.getCurentRepo().getGrades():
            for student in self._studentControl.getCurentRepo().getStudents():
                for discipline in self._disciplineControl.getCurentRepo(
                ).getDisciplines():
                    if grade.getStudentID() == student.getId():
                        if grade.getDisciplineID() == discipline.getId():
                            if grade.getGrade() != []:
                                gradeAvg = self.listAvg(
                                    grade.getGrade(), grade.getGradeSize())
                                if gradeAvg < 5:
                                    sList.append([
                                        student.getName(),
                                        discipline.getName()
                                    ])

        for index in sList:
            top.text.insert(END, '\n' + index[0] + ' - ' + index[1])
        del sList[:]

    def BestStudents(self):

        top = tk.Toplevel()
        top.title('Enrollment List')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        sList = [['', '']]
        gList = []
        sName = ''
        for student in self._studentControl.getCurentRepo().getStudents():
            for grade in self._gradeControl.getCurentRepo().getGrades():
                if student.getId() == grade.getStudentID():
                    if (grade.getGrade() != []):
                        gAvg = self.listAvg(grade.getGrade(),
                                            grade.getGradeSize())
                        gList.append(gAvg)
                        sName = student.getName()
            if gList != []:
                sAvg = self.listAvg(gList, len(gList))
                sList.append([sName, round(sAvg, 2)])

        sList.sort(key=itemgetter(1), reverse=True)
        for index in range(1, len(sList)):
            top.text.insert(
                END, str(sList[index][0] + ' - ' + str(sList[index][1])))
        del sList[:]

    def DisciplineH(self):

        top = tk.Toplevel()
        top.title('Enrollment List')
        top.text = Listbox(top)
        top.text.grid(row=0, column=0)
        top.text.config(width=50)

        sList = [['', '']]
        gList = []
        dName = ''
        for discipline in self._disciplineControl.getCurentRepo(
        ).getDisciplines():
            for grade in self._gradeControl.getCurentRepo().getGrades():
                if discipline.getId() == grade.getDisciplineID():
                    if (grade.getGrade() != []):
                        gAvg = self.listAvg(grade.getGrade(),
                                            grade.getGradeSize())
                        gList.append(gAvg)
                        dName = discipline.getName()
            if gList != []:
                sAvg = self.listAvg(gList, len(gList))
                sList.append([dName, round(sAvg, 2)])

        sList.sort(key=itemgetter(1), reverse=True)

        for index in range(1, len(sList)):
            top.text.insert(
                END,
                '\n' + str(sList[index][0]) + ' - ' + str(sList[index][1]))
        del sList[:]

    '''
    #======================================#
    :EDIT:
    #======================================#
    '''

    def undo(self, event):

        self._undoControl.undo()
        self.refreshALL()

    def redo(self, event):

        self._undoControl.redo()
        self.refreshALL()

    '''
    #===========================================================================================#
    :Widgets:
    #===========================================================================================#
    '''

    def createWidgets(self):
        '''
        #==================================================#
        :TOPBAR:
        #==================================================#
        '''
        self.fileButton = Menubutton(self, text='File', relief='flat')
        self.fileButton.grid(row=0, column=0)

        self.fileButton.menu = Menu(self.fileButton, tearoff=0)
        self.fileButton["menu"] = self.fileButton.menu

        self.fileButton.menu.add_command(label="New", command=self.NewFile)
        self.fileButton.menu.add_command(label="Exit", command=self.quit)

        self.eButton = Menubutton(self, text="Enrollment", relief='flat')
        self.eButton.grid(row=0, column=1)

        self.eButton.menu = Menu(self.eButton, tearoff=0)
        self.eButton["menu"] = self.eButton.menu

        self.eButton.menu.add_command(label="Add Enrollment",
                                      command=self.add_Enroll)

        self.statButton = Menubutton(self, text="Statistics", relief='flat')
        self.statButton.grid(row=0, column=2)

        self.statButton.menu = Menu(self.statButton, tearoff=0)
        self.statButton["menu"] = self.statButton.menu

        self.discMenu = Menu(tearoff=0)
        self.discMenu.add_command(label="Sort by name",
                                  command=self.StudentEnrollA)
        self.discMenu.add_command(label="Sort by grade",
                                  command=self.StudentEnrollB)

        self.statButton.menu.add_cascade(
            label="Students Enrolled at disicpline", menu=self.discMenu)
        self.statButton.menu.add_command(label="Failing Students",
                                         command=self.FailingStudents)
        self.statButton.menu.add_command(label="Best Students",
                                         command=self.BestStudents)
        self.statButton.menu.add_command(label="Discipline Averages",
                                         command=self.DisciplineH)

        self.searchButton = Menubutton(self, text="Search", relief='flat')
        self.searchButton.grid(row=0, column=3)

        self.searchButton.menu = Menu(self.searchButton, tearoff=0)
        self.searchButton["menu"] = self.searchButton.menu

        self.searchButton.menu.add_command(label="Search",
                                           command=self.SearchALL)

        self.editButton = Menubutton(self, text="Edit", relief='flat')
        self.editButton.grid(row=0, column=4)

        self.editButton.menu = Menu(self.editButton, tearoff=0)
        self.editButton["menu"] = self.editButton.menu

        self.editButton.menu.add_command(label="Undo", command=self.undo)
        self.editButton.menu.add_command(label="Redo", command=self.redo)

        self.root.bind('<Control-z>', self.undo)
        self.root.bind('<Control-y>', self.redo)
        '''
        #===================================================#
        :Student:
        #===================================================#
        '''

        self.sbar = Label(self,
                          text='Student list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.sbar.grid(row=1, column=0, columnspan=16)

        self.sList = Listbox(self, exportselection=0)
        for index in self._studentControl.getCurentRepo().getStudents():
            self.sList.insert(END, index)
        self.sList.grid(row=2, column=0, columnspan=16)
        self.sList.config(width=57, height=40)

        self.sMenu = Menu(self, tearoff=0)
        self.sMenu.add_command(label="Add Student", command=self.add_Student)
        self.sMenu.add_command(label="Remove Student",
                               command=self.remove_Student)
        self.sMenu.add_command(label='Update Student ID',
                               command=self.update_StudentID)
        self.sMenu.add_command(label='Update Student name',
                               command=self.update_StudentName)
        self.sMenu.add_command(label='Refresh', command=self.Srefresh)
        self.sList.bind("<Button-3>", self.sPopup)
        '''
        #===================================================#
        :Discipline:
        #===================================================#
        '''
        self.dbar = Label(self,
                          text='Discipline list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.dbar.grid(row=1, column=16, columnspan=16)

        self.dList = Listbox(self, exportselection=0)
        for index in self._disciplineControl.getCurentRepo().getDisciplines():
            self.dList.insert(END, index)
        self.dList.grid(row=2, column=16, columnspan=16)
        self.dList.config(width=57, height=40)

        self.dMenu = Menu(self, tearoff=0)
        self.dMenu.add_command(label="Add Discipline",
                               command=self.add_Discipline)
        self.dMenu.add_command(label="Remove Discipline",
                               command=self.remove_Discipline)
        self.dMenu.add_command(label='Update Discipline ID',
                               command=self.update_DisciplineID)
        self.dMenu.add_command(label='Update Discipline name',
                               command=self.update_DisciplineName)
        self.dMenu.add_command(label='Refresh', command=self.Drefresh)
        self.dList.bind("<Button-3>", self.dPopup)
        '''
        #===================================================#
        :Enroll:
        #===================================================#
        '''

        self.ebar = Label(self,
                          text='Enroll list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.ebar.grid(row=1, column=32, columnspan=16)

        self.eList = Listbox(self, exportselection=0)
        for index in self._enrolControl.getCurentRepo().getEnroll():
            self.eList.insert(END, '\n' + str(index))
        self.eList.grid(row=2, column=32, columnspan=16)
        self.eList.config(width=57, height=40)

        self.eMenu = Menu(self, tearoff=0)
        self.eMenu.add_command(label="Remove Enrollment",
                               command=self.remove_Enroll)
        self.eMenu.add_command(label="Grade Student",
                               command=self.add_EnrollGrade)
        self.eMenu.add_command(label='Refresh', command=self.Erefresh)
        self.eList.bind("<Button-3>", self.ePopup)
        '''
        #===================================================#
        :Grade:
        #===================================================#
        '''
        self.gbar = Label(self,
                          text='Grade list',
                          fg='white',
                          bg='#3B9C9C',
                          width=49)
        self.gbar.grid(row=1, column=48, columnspan=16)

        self.gList = Listbox(self, exportselection=0)
        for index in self._gradeControl.getCurentRepo().getGrades():
            self.gList.insert(END, '\n' + str(index))
        self.gList.grid(row=2, column=48, columnspan=16)
        self.gList.config(width=57, height=40)

        self.gMenu = Menu(self, tearoff=0)
        self.gMenu.add_command(label="Grade Student", command=self.add_Grade)
        self.gMenu.add_command(label='Refresh', command=self.Grefresh)
        self.gList.bind("<Button-3>", self.gPopup)

    def __init__(self,
                 studentControl,
                 disciplineControl,
                 gradeControl,
                 enrolControl,
                 U1,
                 master=None):
        Frame.__init__(self, master)
        self.pack()
        self.grid()
        self.Max = 0
        self.oCont = 0
        self.root = master

        self._studentControl = studentControl
        self._disciplineControl = disciplineControl
        self._gradeControl = gradeControl
        self._enrolControl = enrolControl
        self._undoControl = U1

        self.createWidgets()

    @staticmethod
    def listAvg(myList, size):
        s = 0.0
        for index in range(size):
            s += myList[index]
        s /= size
        return s
Example #33
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented")
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError("If not guiven complete function, list_of_items can't be 'None'")

                if ignorecase_match:
                    if startswith_match:
                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:
                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)]
                else:
                    if startswith_match:
                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:
                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    
                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items
        
        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        
        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())
        #self.bind("<FocusOut>", lambda event: self.unpost_listbox())
        
    def _on_tab(self, event):
        #self.post_listbox()
        self.unpost_listbox()        
        #frmbill.cbouom.focus() 
             

        #self._update_entry_from_listbox()        
        #self.unpost_listbox()
        # if self._listbox is not None:
        #     self._listbox.master.destroy()
        #     self._listbox = None
        return "break"
   
    def _on_change_entry_var(self, name, index, mode):
        
        entry_data = self._entry_var.get()

        if entry_data == '':
            #print('test111')
            self.unpost_listbox()
            self.focus()
        else:
            if len(entry_data) < 3:
                return True
            values = finditem(entry_data)
            #kk
            #self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)
                
            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False)
        self._listbox.grid(row=0, column=0,sticky = N+E+W+S)

        self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())
        
        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N+S)
            
            self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l))
            
        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E+W)
            
            self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness") 
        y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width=self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)
        
        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)
        
    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        if len(text) > 0:
            find_price(text)
        #kk

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            
            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)
            
        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)
                
                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index +=1
                    
                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"

# if __name__ == '__main__':
#     try:
#         from Tkinter import Tk
#     except ImportError:
#         from tkinter import Tk

#     list_of_items = ["Cordell Cannata", "Lacey Naples", "Zachery Manigault", "Regan Brunt", "Mario Hilgefort", "Austin Phong", "Moises Saum", "Willy Neill", "Rosendo Sokoloff", "Salley Christenberry", "Toby Schneller", "Angel Buchwald", "Nestor Criger", "Arie Jozwiak", "Nita Montelongo", "Clemencia Okane", "Alison Scaggs", "Von Petrella", "Glennie Gurley", "Jamar Callender", "Titus Wenrich", "Chadwick Liedtke", "Sharlene Yochum", "Leonida Mutchler", "Duane Pickett", "Morton Brackins", "Ervin Trundy", "Antony Orwig", "Audrea Yutzy", "Michal Hepp", "Annelle Hoadley", "Hank Wyman", "Mika Fernandez", "Elisa Legendre", "Sade Nicolson", "Jessie Yi", "Forrest Mooneyhan", "Alvin Widell", "Lizette Ruppe", "Marguerita Pilarski", "Merna Argento", "Jess Daquila", "Breann Bevans", "Melvin Guidry", "Jacelyn Vanleer", "Jerome Riendeau", "Iraida Nyquist", "Micah Glantz", "Dorene Waldrip", "Fidel Garey", "Vertie Deady", "Rosalinda Odegaard", "Chong Hayner", "Candida Palazzolo", "Bennie Faison", "Nova Bunkley", "Francis Buckwalter", "Georgianne Espinal", "Karleen Dockins", "Hertha Lucus", "Ike Alberty", "Deangelo Revelle", "Juli Gallup", "Wendie Eisner", "Khalilah Travers", "Rex Outman", "Anabel King", "Lorelei Tardiff", "Pablo Berkey", "Mariel Tutino", "Leigh Marciano", "Ok Nadeau", "Zachary Antrim", "Chun Matthew", "Golden Keniston", "Anthony Johson", "Rossana Ahlstrom", "Amado Schluter", "Delila Lovelady", "Josef Belle", "Leif Negrete", "Alec Doss", "Darryl Stryker", "Michael Cagley", "Sabina Alejo", "Delana Mewborn", "Aurelio Crouch", "Ashlie Shulman", "Danielle Conlan", "Randal Donnell", "Rheba Anzalone", "Lilian Truax", "Weston Quarterman", "Britt Brunt", "Leonie Corbett", "Monika Gamet", "Ingeborg Bello", "Angelique Zhang", "Santiago Thibeau", "Eliseo Helmuth"]

#     root = Tk()
#     root.geometry("300x200")

#     combobox_autocomplete = Combobox_Autocomplete(root, list_of_items, highlightthickness=1)
#     combobox_autocomplete.pack()
    
#     combobox_autocomplete.focus()
    
#     root.mainloop()
Example #34
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)
Example #35
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
Example #36
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.parent = master

        self.dict = scrapeStart()
        self.initUI()


    def initUI(self):
        """ Build the grid """
        self.grid()
        for r in range(66):
            self.parent.rowconfigure (r, weight = 1)
        for c in range(8):
            self.parent.columnconfigure (c, weight = 1)
        """ Center the window on the display """
        width = 768
        height = 1024

        screenWidth = self.parent.winfo_screenwidth()
        screenHeight = self.parent.winfo_screenheight()

        x = (screenWidth - width) / 2
        y = (screenHeight - height) / 2

        self.parent.geometry('%dx%d+%d+%d' % (width, height, x, y))
        self.parent.configure(bg = "grey10")

        status = "home"
        self.drawScreen(status)


    def drawScreen(self, status):
        print ("%s is the status" % status)

        if (status == "home"):
            self.drawHome()
        elif (status == "film"):
            self.drawFilm()
        elif (status == "recipes"):

            self.drawRecipes()
        else:
            print('Bad mojo')


    def drawHome(self):
        infoText = ("Some Louisiana urban environments have a multicultural, multilingual heritage, being so strongly "
            "by an admixture of 18th century French, Spanish, Native American (Indian), and African cultures that they "
            "are considered to be somewhat exceptional in the U.S. Before the American influx and statehood at the "
            "beginning of the 19th century, the territory of current Louisiana State had been both a Spanish and "
            "French colony. In addition, the pattern of development included importing numerous African slaves in "
            "the 18th century, with many from the same region of West Africa, thus concentrating their culture.")

        self.img = ImageTk.PhotoImage(Image.open("louisiana.png"))

        self.title = Label(self.parent, width = 1, height = 1, text = "Louisiana", fg = "white", bg = "grey30",
                        font = ("Times 48 italic"), bd = 5, relief = RAISED)
        self.title.grid(row = 1, column = 2, rowspan = 10, columnspan = 4, sticky = W+E+N+S)

        self.info = Label(self.parent, width = 1, height = 1, text = infoText, fg = "white", bg = "grey30",
                        font = ("Times 14"), bd = 5, relief = RAISED, wraplength = 350, justify = LEFT)
        self.info.grid(row = 23, column = 4, rowspan = 24, columnspan = 4, sticky = W+E+N+S)

        self.image1 = Label(self.parent, width = 1, height = 1, image = self.img, bg = "grey10")
        self.image1.grid(row = 23, column = 0, rowspan = 24, columnspan = 4, sticky = W+E+N+S)

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Recipes", command = lambda: self.drawScreen("recipes"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button3 = Button()
        self.Button3.grid_remove()
        self.Button4 = Button()
        self.Button4.grid_remove()
        self.Button5 = Button()
        self.Button5.grid_remove()
        self.listbox = Listbox()
        self.listbox.grid_remove()
        self.image2 = Label()
        self.image2.grid_remove()


    def drawFilm(self):
        self.title = Label(self.parent, text = "Film", fg="white", bg="grey30", font=("Times 48 italic"),
                        bd = 5, relief = RAISED)
        self.title.grid(row = 1, column = 2, rowspan = 10, columnspan = 4, sticky = W+E+N+S)

        self.Button1 = Button(self.parent, text = "Recipes", command = lambda: self.drawScreen("recipes"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.info.grid_remove()
        self.image1.grid_remove()
        self.image2.grid_remove()
        self.Button3.grid_remove()
        self.Button4.grid_remove()
        self.Button5.grid_remove()
        self.listbox.grid_remove()


    def drawRecipes(self):
        self.title = Label(self.parent, text = "Recipes", fg="white", bg="grey30", font=("Times 48 italic"),
                        bd = 5, relief = RAISED)
        self.title.grid(row = 1, column = 2, rowspan = 10, columnspan = 4, sticky = W+E+N+S)

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button3 = Button(self.parent, text = "Gumbo", command = self.drawRecipeList)
        self.Button3.grid(row = 24, column = 3, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button4 = Button(self.parent, text = "Jambalaya", command = self.quit)
        self.Button4.grid(row = 29, column = 3, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button5= Button(self.parent, text = "Seafood", command = self.quit)
        self.Button5.grid(row = 34, column = 3, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.info.grid_remove()
        self.image1.grid_remove()
        self.listbox.grid_remove()
        self.image2.grid_remove()


    def drawRecipeList(self):
        self.Button3.grid_remove()
        self.Button4.grid_remove()
        self.Button5.grid_remove()
        self.image2.grid_remove()

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.listbox = Listbox(self.parent)
        for key in self.dict:
            index = 1
            self.listbox.insert(index, key)
            index += 1
        self.listbox.grid(row = 29, column = 1, rowspan = 12, columnspan = 6, sticky = W+E+N+S)
        self.listbox.bind("<<ListboxSelect>>", self.get_List)


    def get_List(self, *args):
        self.info.grid_remove()
        self.image1.grid_remove()
        self.image2.grid_remove()
        self.Button3.grid_remove()
        self.Button4.grid_remove()
        self.Button5.grid_remove()
        self.listbox.grid_remove()

        self.index = self.listbox.curselection()

        self.Button1 = Button(self.parent, text = "Film", command = lambda: self.drawScreen("film"))
        self.Button1.grid(row = 61, column = 1, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.Button2 = Button(self.parent, text = "Home", command = lambda: self.drawScreen("home"))
        self.Button2.grid(row = 61, column = 5, rowspan = 3, columnspan = 2, sticky = W+E+N+S)

        self.img2 = ImageTk.PhotoImage(Image.open("creole_gumbo.png"))
        self.image2 = Label(self.parent, width = 1, height = 1, image = self.img2, bg = "grey10")
        self.image2.grid(row = 21, column = 1, rowspan = 34, columnspan = 6, sticky = W+E+N+S)
Example #37
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()
Example #38
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()
Example #39
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)
Example #40
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented")
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError("If not guiven complete function, list_of_items can't be 'None'")

                if ignorecase_match:
                    if startswith_match:
                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:
                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)]
                else:
                    if startswith_match:
                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:
                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item, re.IGNORECASE):
                                return True
                            else:
                                return False
                    
                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items
        
        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)
        
        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())
        
    def _on_tab(self, event):
        self.post_listbox()
        return "break"

    def _on_change_entry_var(self, name, index, mode):
        
        entry_data = self._entry_var.get()

        if entry_data == '':
            self.unpost_listbox()
            self.focus()
        else:
            values = self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)
                
            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False)
        self._listbox.grid(row=0, column=0,sticky = N+E+W+S)

        self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())
        
        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N+S)
            
            self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l))
            
        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E+W)
            
            self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness") 
        y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width=self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)
        
        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)
        
    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()
            
            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)
            
        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection)==0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)
                
                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index +=1
                    
                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"
Example #41
0
class Participant(object):
    """
    Creates the input frame and stores the information regarding the
    participant
    """
    def __init__(self, parent, *args, **kwargs):
        """
        Initialize the input frame and call to inititialize the user
        interface
        """
        # Set the Tk as the parent
        self.parent = parent
        # Initialize the user interface
        self.initUI()

    def initUI(self):
        """
        Initializes the user interface

        Setting up the entry widgets for:
        - Experiment_ID
        - Participant Name
        - Session Day
        - Pupil Size
        - Practice
        - Stereo
        """
        # Set the title
        self.parent.title(EXP_NAME)

        # Create the label for Experiment_ID and set location
        label_id = Label(text='Participant ID:')
        label_id.place(x=20, y=20)

        # Check the DATA_DIR directory for previous participants
        # and choose the next Experiment_ID in line
        self.folders = listdir(DATA_DIR)
        # Initiate Tkinter's StringVar
        self.value_id = StringVar()
        # Set the default value
        self.value_id.set('001')
        # Going in reverse order of the participants' directories in
        # DATA_DIR, find the last participant's Experiment_ID and opt
        # for the next one in line
        for folder in reversed(self.folders):
            try:
                # Check if the value of the first 3 digits of the
                # directory name is greater than the default value
                if int(folder[:3]) >= int(self.value_id.get()):
                    # Get the next Experiment_ID in integer form and
                    # convert to string format
                    num = str(int(folder[:3]) + 1)
                    # Actions to perform in case scenarios for each
                    # of the possibilites of num_length
                    num_length = {3: num, 2: '0%s' % num, 1: '00%s' % num}
                    # Set the value accordingly to the StringVar,
                    # replacing the default
                    self.value_id.set(num_length[len(num)])
            # In case there are other folders in DATA_DIR, for which
            # the first 3 characters are not digits, we must cater
            # for when an exception is thrown up
            except ValueError:
                pass
        # Create the entry widget for Experiment_ID with the preset
        # value and state disabled
        self.input_id = Entry(self.parent,
                              width=5,
                              state=DISABLED,
                              textvariable=self.value_id)
        self.input_id.place(x=150, y=20)

        # Create the label for Participant Name and set location
        label_name = Label(text='Participant Name:')
        label_name.place(x=20, y=50)

        # Initiate Tkinter's StringVar
        self.value_name = StringVar()
        # Set the default value
        self.value_name.set('')
        # Create the entry for Participant Name and set location
        self.input_name = Entry(self.parent,
                                width=35,
                                textvariable=self.value_name)
        self.input_name.place(x=150, y=50)
        self.input_name.focus()

        # Create the label for Session Day and set location
        label_day = Label(text='Session Day:')
        label_day.place(x=20, y=80)

        # Create value holder for Session Day as IntVar and set default
        # value to 1
        self.value_day = IntVar()
        self.value_day.set(1)
        # Create the radiobuttons as required
        for day in range(1, TOTAL_SESSIONS + 1):
            input_day = Radiobutton(self.parent,
                                    text=str(day),
                                    variable=self.value_day,
                                    value=day)
            # Anchor them to the West (W)
            input_day.pack(anchor=W)
            # Choose location for the radiobuttons
            input_day.place(x=150, y=(50 + (day * 25)))

        # Create the label for Pupil Size and set location
        label_pupilsize = Label(text='Pupil Size:')
        label_pupilsize.place(x=20, y=140)

        self.value_pupilsize = StringVar()
        self.value_pupilsize.set('')
        # Create the MaxLengthEntry for Pupil Size and set location
        # The maximum length is set to 3 characters and a float must be
        # provided
        self.input_pupilsize = MaxLengthEntry(self.parent,
                                              width=5,
                                              maxlength=3,
                                              required_type=float)
        self.input_pupilsize.config(textvariable=self.value_pupilsize)
        self.input_pupilsize.place(x=150, y=140)

        # Create value folder for Practice as IntVar
        self.value_practice = IntVar()
        # Create the checkbutton for Practice and set location
        input_practice = Checkbutton(self.parent,
                                     text='Practice',
                                     variable=self.value_practice,
                                     onvalue=1,
                                     offvalue=0)
        input_practice.place(x=150, y=170)

        # Create value holder for Stereo as IntVar
        self.value_stereo = IntVar()
        # Create the checkbutton for Stereo and set location
        input_stereo = Checkbutton(self.parent,
                                   text='Stereo',
                                   variable=self.value_stereo,
                                   onvalue=1,
                                   offvalue=0)
        input_stereo.place(x=150, y=200)

        # Create the label for Previous Subjects and set location
        label_previous = Label(text='Previous Subjects:')
        label_previous.place(x=20, y=250)

        # Create the Listboc containing all the previous participants
        self.input_previous = Listbox(self.parent, width=35, height=10)
        for identifier in self.folders:
            self.input_previous.insert(END, identifier)
        self.input_previous.place(x=150, y=250)
        self.input_previous.bind('<<ListboxSelect>>', self.__select_previous)

        # Create the submit button, give command upon pressing and set
        # location
        submit = Button(text='Submit', width=47, command=self.gather_input)
        submit.pack(padx=8, pady=8)
        submit.place(x=20, y=425)

    def __select_previous(self, event):
        """
        Handle scenario where user selects one of the previous participants
        """
        # Collect from previous subjects, if it was chosen
        self.previous = self.input_previous.curselection()
        if self.previous:
            self.previous = self.folders[int(self.previous[0])]
            with open(join(DATA_DIR, self.previous, 'data.json')) as f:
                data = load(f)
                # Set the value for participant ID
                self.value_id.set(data['ID'])
                # Set the value for name and disable the user from making
                # any more changes
                self.value_name.set(data['Name'])
                self.input_name.config(state=DISABLED)
                # Set the value for pupilsize and disable the user from
                # making any more changes
                self.value_pupilsize.set(data['Pupil Size'])
                self.input_pupilsize.config(state=DISABLED)

    def gather_input(self):
        """
        Gather the input from the Tkinter window and store it as class
        variables of the Participant class

        This module will also create a folder for the participant if
        it does not exist already in DATA_DIR
        NOTE: DATA_DIR is set in settings.py
        """
        # Collect all the values input and convert to their appropriate
        # types
        self.subject_id = self.input_id.get()
        self.name = self.input_name.get().title()
        self.day = int(self.value_day.get())
        try:
            self.pupilsize = float(self.input_pupilsize.get())
        except ValueError:
            pass
        self.practice = bool(self.value_practice.get())
        self.stereo = bool(self.value_stereo.get())

        # Destroy the Tkinter window
        self.parent.destroy()

        # Put together the directory name and path
        self.subject_dir = '%s_%s' % (self.subject_id,
                                      self.name.replace(' ', ''))
        self.subject_dir = join(DATA_DIR, self.subject_dir)
        # If the directory for the participant does not exist, create it
        if not exists(self.subject_dir):
            makedirs(self.subject_dir)
Example #42
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()
Example #43
0
class Combobox_Autocomplete(Entry, object):
    def __init__(self,
                 master,
                 list_of_items=None,
                 autocomplete_function=None,
                 listbox_width=None,
                 listbox_height=7,
                 ignorecase_match=False,
                 startswith_match=True,
                 vscrollbar=True,
                 hscrollbar=True,
                 **kwargs):
        if hasattr(self, "autocomplete_function"):
            if autocomplete_function is not None:
                raise ValueError(
                    "Combobox_Autocomplete subclass has 'autocomplete_function' implemented"
                )
        else:
            if autocomplete_function is not None:
                self.autocomplete_function = autocomplete_function
            else:
                if list_of_items is None:
                    raise ValueError(
                        "If not guiven complete function, list_of_items can't be 'None'"
                    )

                if ignorecase_match:
                    if startswith_match:

                        def matches_function(entry_data, item):
                            return item.startswith(entry_data)
                    else:

                        def matches_function(entry_data, item):
                            return item in entry_data

                    self.autocomplete_function = lambda entry_data: [
                        item for item in self.list_of_items
                        if matches_function(entry_data, item)
                    ]
                else:
                    if startswith_match:

                        def matches_function(escaped_entry_data, item):
                            if re.match(escaped_entry_data, item,
                                        re.IGNORECASE):
                                return True
                            else:
                                return False
                    else:

                        def matches_function(escaped_entry_data, item):
                            if re.search(escaped_entry_data, item,
                                         re.IGNORECASE):
                                return True
                            else:
                                return False

                    def autocomplete_function(entry_data):
                        escaped_entry_data = re.escape(entry_data)
                        return [
                            item for item in self.list_of_items
                            if matches_function(escaped_entry_data, item)
                        ]

                    self.autocomplete_function = autocomplete_function

        self._listbox_height = int(listbox_height)
        self._listbox_width = listbox_width

        self.list_of_items = list_of_items

        self._use_vscrollbar = vscrollbar
        self._use_hscrollbar = hscrollbar

        kwargs.setdefault("background", "white")

        if "textvariable" in kwargs:
            self._entry_var = kwargs["textvariable"]
        else:
            self._entry_var = kwargs["textvariable"] = StringVar()

        Entry.__init__(self, master, **kwargs)

        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

        self._listbox = None

        self.bind("<Tab>", self._on_tab)
        self.bind("<Up>", self._previous)
        self.bind("<Down>", self._next)
        self.bind('<Control-n>', self._next)
        self.bind('<Control-p>', self._previous)

        self.bind("<Return>", self._update_entry_from_listbox)
        self.bind("<Escape>", lambda event: self.unpost_listbox())

    def _on_tab(self, event):
        self.post_listbox()
        return "break"

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

        entry_data = self._entry_var.get()

        if entry_data == '':
            self.unpost_listbox()
            self.focus()
        else:
            values = self.autocomplete_function(entry_data)
            if values:
                if self._listbox is None:
                    self._build_listbox(values)
                else:
                    self._listbox.delete(0, END)

                    height = min(self._listbox_height, len(values))
                    self._listbox.configure(height=height)

                    for item in values:
                        self._listbox.insert(END, item)

            else:
                self.unpost_listbox()
                self.focus()

    def _build_listbox(self, values):
        listbox_frame = Frame()

        self._listbox = Listbox(listbox_frame,
                                background="white",
                                selectmode=SINGLE,
                                activestyle="none",
                                exportselection=False)
        self._listbox.grid(row=0, column=0, sticky=N + E + W + S)

        self._listbox.bind("<ButtonRelease-1>",
                           self._update_entry_from_listbox)
        self._listbox.bind("<Return>", self._update_entry_from_listbox)
        self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())

        self._listbox.bind('<Control-n>', self._next)
        self._listbox.bind('<Control-p>', self._previous)

        if self._use_vscrollbar:
            vbar = Scrollbar(listbox_frame,
                             orient=VERTICAL,
                             command=self._listbox.yview)
            vbar.grid(row=0, column=1, sticky=N + S)

            self._listbox.configure(
                yscrollcommand=lambda f, l: autoscroll(vbar, f, l))

        if self._use_hscrollbar:
            hbar = Scrollbar(listbox_frame,
                             orient=HORIZONTAL,
                             command=self._listbox.xview)
            hbar.grid(row=1, column=0, sticky=E + W)

            self._listbox.configure(
                xscrollcommand=lambda f, l: autoscroll(hbar, f, l))

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

        x = -self.cget("borderwidth") - self.cget("highlightthickness")
        y = self.winfo_height() - self.cget("borderwidth") - self.cget(
            "highlightthickness")

        if self._listbox_width:
            width = self._listbox_width
        else:
            width = self.winfo_width()

        listbox_frame.place(in_=self, x=x, y=y, width=width)

        height = min(self._listbox_height, len(values))
        self._listbox.configure(height=height)

        for item in values:
            self._listbox.insert(END, item)

    def post_listbox(self):
        if self._listbox is not None: return

        entry_data = self._entry_var.get()
        if entry_data == '': return

        values = self.autocomplete_function(entry_data)
        if values:
            self._build_listbox(values)

    def unpost_listbox(self):
        if self._listbox is not None:
            self._listbox.master.destroy()
            self._listbox = None

    def get_value(self):
        return self._entry_var.get()

    def set_value(self, text, close_dialog=False):
        self._set_var(text)

        if close_dialog:
            self.unpost_listbox()

        self.icursor(END)
        self.xview_moveto(1.0)

    def _set_var(self, text):
        self._entry_var.trace_vdelete("w", self._trace_id)
        self._entry_var.set(text)
        self._trace_id = self._entry_var.trace('w', self._on_change_entry_var)

    def _update_entry_from_listbox(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if current_selection:
                text = self._listbox.get(current_selection)
                self._set_var(text)

            self._listbox.master.destroy()
            self._listbox = None

            self.focus()
            self.icursor(END)
            self.xview_moveto(1.0)

        return "break"

    def _previous(self, event):
        if self._listbox is not None:
            current_selection = self._listbox.curselection()

            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == 0:
                    index = END
                else:
                    index -= 1

                self._listbox.see(index)
                self._listbox.selection_set(first=index)
                self._listbox.activate(index)

        return "break"

    def _next(self, event):
        if self._listbox is not None:

            current_selection = self._listbox.curselection()
            if len(current_selection) == 0:
                self._listbox.selection_set(0)
                self._listbox.activate(0)
            else:
                index = int(current_selection[0])
                self._listbox.selection_clear(index)

                if index == self._listbox.size() - 1:
                    index = 0
                else:
                    index += 1

                self._listbox.see(index)
                self._listbox.selection_set(index)
                self._listbox.activate(index)
        return "break"
Example #44
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
Example #45
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"
Example #46
0
class ServerAddressView:
    def __init__(self, container, application):
        self.container = container
        self.application = application

        # LEFT CONTAINER
        self.frame_left = Frame(container)
        self.frame_left.pack(side=LEFT, padx=20, pady=20)
        exchange_label = Label(self.frame_left, text="Server info")
        exchange_label.pack(side=TOP, pady=10)

        # Exchange name row
        frame_row1 = Frame(self.frame_left)
        frame_row1.pack(side=TOP, padx=20, pady=5)
        exchange_label = Label(frame_row1, text="Name:")
        exchange_label.pack(side=LEFT)
        self.exchangeEntry = Entry(frame_row1, bd=5)
        self.exchangeEntry.pack(side=LEFT)

        # Hostname row
        frame_row2 = Frame(self.frame_left)
        frame_row2.pack(side=TOP, padx=20, pady=5)
        host_label = Label(frame_row2, text="Host:  ")
        host_label.pack(side=LEFT)
        self.hostEntry = Entry(frame_row2, bd=5)
        self.hostEntry.pack(side=LEFT)

        # Port row
        frame_row3 = Frame(self.frame_left)
        frame_row3.pack(side=TOP, padx=20, pady=5)
        port_label = Label(frame_row3, text="Port:  ")
        port_label.pack(side=LEFT)
        self.portEntry = Entry(frame_row3, bd=5)
        self.portEntry.pack(side=LEFT)

        # Connect button
        self.enterButton = Button(self.frame_left,
                                  text="Connect",
                                  command=self.handle_enter)
        self.enterButton.pack(side=BOTTOM, padx=20, pady=20)

        # RIGHT CONTAINER
        self.frame_right = Frame(container)
        self.frame_right.pack(side=LEFT, padx=20, pady=20)

        servers_label = Label(self.frame_right, text="Available servers:")
        servers_label.pack(pady=10)
        self.servers_lb = Listbox(self.frame_right)
        self.servers_lb.pack()
        self.servers_lb.bind('<<ListboxSelect>>', self.fill_serverinfo)

        pad = Label(self.frame_right, text="")
        pad.pack(side=BOTTOM, pady=10)

        # Default values
        self.exchangeEntry.insert(0, "sudoku")
        self.hostEntry.insert(0, "127.0.0.1")
        self.portEntry.insert(0, "5672")

        # Automatic server discovery
        self.servers_list = []
        self.announce_listener = AnnounceListener(self.servers_lb,
                                                  self.servers_list)
        self.announce_listener.start()

    def handle_enter(self):  # Handle proceed button
        exchange = self.exchangeEntry.get()
        host = self.hostEntry.get()
        port = self.portEntry.get()

        self.application.rmq_exchange = exchange
        self.application.rmq_host = host
        self.application.rmq_port = port

        self.application.connect()

    def fill_nickname(self, evt):
        w = evt.widget
        idx = int(w.curselection()[0])
        self.entry.delete(0, END)
        self.entry.insert(0, w.get(idx))

    def fill_serverinfo(self, evt):
        if self.servers_lb.size() == 0: return
        w = evt.widget
        idx = int(w.curselection()[0])
        # Exchange name
        self.exchangeEntry.delete(0, END)
        self.exchangeEntry.insert(0, self.servers_list[idx][0])
        # Host name
        self.hostEntry.delete(0, END)
        self.hostEntry.insert(0, self.servers_list[idx][1])
        # Port
        self.portEntry.delete(0, END)
        self.portEntry.insert(0, self.servers_list[idx][2])
Example #47
0
    def __init__(self, master, columns, column_weights=None, cnf={}, **kw):
        """
        Construct a new multi-column listbox widget.

        :param master: The widget that should contain the new
            multi-column listbox.
            
        :param columns: Specifies what columns should be included in
            the new multi-column listbox.  If ``columns`` is an integer,
            the it is the number of columns to include.  If it is
            a list, then its length indicates the number of columns
            to include; and each element of the list will be used as
            a label for the corresponding column.

        :param cnf, kw: Configuration parameters for this widget.
            Use ``label_*`` to configure all labels; and ``listbox_*``
            to configure all listboxes.  E.g.:

                >>> mlb = MultiListbox(master, 5, label_foreground='red')
        """
        # If columns was specified as an int, convert it to a list.
        if isinstance(columns, int):
            columns = range(columns)
            include_labels = False
        else:
            include_labels = True

        if len(columns) == 0:
            raise ValueError("Expected at least one column")

        # Instance variables
        self._column_names = tuple(columns)
        self._listboxes = []
        self._labels = []

        # Pick a default value for column_weights, if none was specified.
        if column_weights is None:
            column_weights = [1] * len(columns)
        elif len(column_weights) != len(columns):
            raise ValueError('Expected one column_weight for each column')
        self._column_weights = column_weights

        # Configure our widgets.
        Frame.__init__(self, master, **self.FRAME_CONFIG)
        self.grid_rowconfigure(1, weight=1)
        for i, label in enumerate(self._column_names):
            self.grid_columnconfigure(i, weight=column_weights[i])

            # Create a label for the column
            if include_labels:
                l = Label(self, text=label, **self.LABEL_CONFIG)
                self._labels.append(l)
                l.grid(column=i, row=0, sticky='news', padx=0, pady=0)
                l.column_index = i

            # Create a listbox for the column
            lb = Listbox(self, **self.LISTBOX_CONFIG)
            self._listboxes.append(lb)
            lb.grid(column=i, row=1, sticky='news', padx=0, pady=0)
            lb.column_index = i

            # Clicking or dragging selects:
            lb.bind('<Button-1>', self._select)
            lb.bind('<B1-Motion>', self._select)
            # Scroll whell scrolls:
            lb.bind('<Button-4>', lambda e: self._scroll(-1))
            lb.bind('<Button-5>', lambda e: self._scroll(+1))
            lb.bind('<MouseWheel>', lambda e: self._scroll(e.delta))
            # Button 2 can be used to scan:
            lb.bind('<Button-2>', lambda e: self.scan_mark(e.x, e.y))
            lb.bind('<B2-Motion>', lambda e: self.scan_dragto(e.x, e.y))
            # Dragging outside the window has no effect (diable
            # the default listbox behavior, which scrolls):
            lb.bind('<B1-Leave>', lambda e: 'break')
            # Columns can be resized by dragging them:
            l.bind('<Button-1>', self._resize_column)

        # Columns can be resized by dragging them.  (This binding is
        # used if they click on the grid between columns:)
        self.bind('<Button-1>', self._resize_column)

        # Set up key bindings for the widget:
        self.bind('<Up>', lambda e: self.select(delta=-1))
        self.bind('<Down>', lambda e: self.select(delta=1))
        self.bind('<Prior>', lambda e: self.select(delta=-self._pagesize()))
        self.bind('<Next>', lambda e: self.select(delta=self._pagesize()))

        # Configuration customizations
        self.configure(cnf, **kw)
Example #48
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_)
Example #49
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"
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")
Example #51
0
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0)
        self.hex_color = '#0000ff'
        self.color_list = ["red","blue","green","orange","purple"]
        self.parent = parent
        print "Loading model..."
        self.lux = Lux()
        fp = open(curdir+"/gauss_model.pkl"); self.gm = pickle.load(fp); fp.close()
        fp = open(curdir+"/memoized_binomial_data.pkl"); self.curve_data = pickle.load(fp); fp.close()
        fp = open(curdir+"/sampling_normalizer.pkl"); self.normalizer = pickle.load(fp); fp.close()
        print "Creating UI"
        self.initUI()
        self.update_output()
        self.replot()

    def update_output(self):
        (h, s, v) = self.hsv_color
        self.hsv_var.set("Hue: \t %2.1f \nSat:\t %2.1f \nValue:\t %2.1f" % (h*360,s*100,v*100))
        items = self.lux.full_posterior((h * 360, s * 100, v * 100))
        self.current_post = items
        desc = [ '{:<25} ({:.3f})\n'.format(items[i][0], items[i][1]) for i in range(25) ]
        self.display.config(state=NORMAL)
        self.display.delete(0, END)

        for i in range(25): self.display.insert(END, '{:<20} ({:.3f})'.format(items[i][0], items[i][1]))

        self.display.select_set(0, 0)

    def plot_lux_model(self, params,ax1,label,support,dim):
        cur_color='black'
        mu1,sh1,sc1,mu2,sh2,sc2 = params
        left_stach=gam_dist(sh1,scale=sc1); lbounds=left_stach.interval(0.99)
        right_stach=gam_dist(sh2,scale=sc2); rbounds=right_stach.interval(0.99)
        lx=np.linspace(mu1,-180); rx=np.linspace(mu2,360)
        s=3;
        ax1.plot(rx, [right_stach.sf(abs(y-mu2)) for y in rx],linewidth=s,c=cur_color);
        ax1.plot([1.01*mu1,0.99*mu2], [1.,1.], linewidth=s,c=cur_color)
        return ax1.plot(lx,[left_stach.sf(abs(y-mu1)) for y in lx],c=cur_color, linewidth=s);

    def plot_gm_model(self, params, ax, label, support):
        s=3
        x = np.linspace(support[0],support[1],360)

        return ax.plot(x,norm.pdf(x,params[0],params[1]),c='red', linewidth=s), norm.pdf([params[0]],params[0],[params[1]])[0]


    def initUI(self):

        self.parent.title("Interactive LUX visualization")
        self.pack(fill=BOTH, expand=1)

        self.color_frame = Frame(self, border=1)
        self.color_frame.pack(side=LEFT)

        probe_title_var = StringVar(); probe_title_label = Label(self.color_frame, textvariable=probe_title_var, justify=CENTER,  font = "Helvetica 16 bold italic")
        probe_title_var.set("Color Probe X"); probe_title_label.pack(side=TOP)

        self.hsv_var = StringVar()
        self.hsv_label = Label(self.color_frame, textvariable=self.hsv_var,justify=LEFT)
        h,s,v = self.hsv_color
        self.hsv_var.set("Hue: %2.1f \nSaturation: %2.1f \nValue: %2.1f" % (h*360,s*100,v*100))
        self.hsv_label.pack(side=TOP)

        self.frame = Frame(self.color_frame, border=1,
            relief=SUNKEN, width=200, height=200)

        self.frame.pack(side=TOP)
        self.frame.config(bg=self.hex_color)
        self.frame.bind("<Button-1>",self.onChoose)


        self.btn = Button(self.color_frame, text="Select Color",
            command=self.onChoose)
        self.btn.pack(side=TOP)

        posterior_title_var = StringVar(); posterior_title_label = Label(self.color_frame, textvariable=posterior_title_var, justify=CENTER, font = "Helvetica 16 bold italic")
        posterior_title_var.set("\n\nLUX's Posterior"); posterior_title_label.pack(side=TOP)

        Label(self.color_frame, text="Double click to show details \n(Wait time dependent on computer)").pack(side=TOP)



        my_font = tkFont.Font(family="Courier", size=10)
        self.display = Listbox(self.color_frame, border=1,
            relief=SUNKEN, width=30, height=25, font=my_font)
        self.display.pack(side=TOP,fill=Y,expand=1)
        self.display.bind("<Double-Button-1>",self.onSelect)
        self.display_btn = Button(self.color_frame, text="Show details", command=self.onSelect)
        self.display_btn.pack(side=TOP)

        self.update_output()



        self.fig = Figure(figsize=(10,4), dpi=100)

        self.canvas = FigureCanvasTkAgg(self.fig, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=LEFT, fill=BOTH, expand=1)
        self.canvas._tkcanvas.pack(side='top', fill='both', expand=1)

    def replot(self):

        def gb(x,i,t):
            #t is max value, i in number of bins, x is the thing to be binned
            if x==t:
                return i-1
            elif x==0.0:
                return 0
            return int(floor(float(x)*i/t))
        hsv_title = []
        j=self.display.curselection()[0]
        name = self.current_post[j][0]
        mult = lambda x: reduce(operator.mul, x)
        g_labels = []; lux_labels=[]; all_g_params=[]
        for i in range(3):

            def align_yaxis(ax1, v1, ax2, v2):
                """adjust ax2 ylimit so that v2 in ax2 is aligned to v1 in ax1"""
                _, y1 = ax1.transData.transform((0, v1))
                _, y2 = ax2.transData.transform((0, v2))
                inv = ax2.transData.inverted()
                _, dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
                miny, maxy = ax2.get_ylim()

                ax2.set_ylim(miny, maxy+dy)

            subplot = self.fig.add_subplot(4,1,i+1)
            dim_label = ["H", "S","V"][i]
            subplot.set_ylabel(r"$P(k^{true}_{%s}|x)$" % ["H", "S","V"][i] )

            curve_data = self.curve_data[name][i]

            scale = lambda x,a=0.3,b=0.9: (b-a)*(x)+a
            p_x = lambda x: self.normalizer[i][gb(x,len(self.normalizer[i]),[360,100,100][i])]
            max_p_x = max(self.normalizer[i])
            #1 is white, 0 is black. so we want highly probable thigns to be black..


            if self.lux.get_adj(self.current_post[j][0]):
                support = [[-180,180], [0,100],[0,100]][i]
                pp = lambda x,i: x-360 if i==0 and x>180 else x
                hacky_solution = [360,100,100][i]
                w = 1.5 if i==0 else 1

                conv = lambda x: x*support[1]/len(curve_data)
                bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))]
                bar1 = subplot.bar([pp(atan2(sin((x*hacky_solution/len(curve_data))*pi/180),cos((x*hacky_solution/len(curve_data))*pi/180))*180/pi,i) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % j,ec="black",width=w,linewidth=0,color=bar_colors)
            else:
                support = [[0,360], [0,100],[0,100]][i]
                w = 1.5 if i==0 else 1
                conv = lambda x: x*support[1]/len(curve_data)
                bar_colors = ["%s" % (scale(1-p_x(conv(x))/max_p_x)) for x in range(len(curve_data))]
                bar1 = subplot.bar([x*support[1]/len(curve_data) for x in range(len(curve_data))],[x/max(curve_data) for x in curve_data], label="%s data" % name[0],ec="black",width=w,linewidth=0,color=bar_colors)
                pp = lambda x,*args: x

            point = pp(self.hsv_color[i]*[360,100,100][i],i)
            hsv_title.append(point)
            probeplot = subplot.plot([point,point], [0,1],linewidth=3,c='blue',label="Probe")

            #for j in range(5):
            lux_plot = self.plot_lux_model(self.lux.get_params(self.current_post[j][0])[i], subplot, self.current_post[j][0],support, i)
            subplot2 = subplot.twinx()
            gm_plot,gm_height = self.plot_gm_model([pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]], subplot2, self.current_post[j][0], support)
            extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)

            subplot.legend([extra], [["Hue", "Saturation", "Value"][i]],loc=2,frameon=False)


            if i==0: legend_set=lux_plot+[extra,extra,extra]+gm_plot+[extra,extra,extra]
            lux_params = self.lux.get_params(self.current_post[j][0])[i]
            g_params = [pp(g_param,i) for g_param in self.gm[self.current_post[j][0]][0][i]]
            all_g_params.append(g_params)

            g_labels.append(r"$\mu^{%s}=$%2.2f, $\sigma^{%s}$=%2.2f" % (dim_label, g_params[0],dim_label,g_params[1]))
            #lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f, $E[\tau^{L,%s}]$=%2.2f, $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, (lux_params[0]-lux_params[1]*lux_params[2]),dim_label,lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,(lux_params[3]+lux_params[4]*lux_params[5]),dim_label, lux_params[4],dim_label,lux_params[5]))
            lux_labels.append(r"$\mu^{L,%s}=$%2.2f, $\alpha^{L,%s}$=%2.2f, $\beta^{L,%s}$=%2.2f, $\mu^{U,%s}=$%2.2f,  $\alpha^{U,%s}$=%2.2f, $\beta^{U,%s}$=%2.2f" % (dim_label, lux_params[0],dim_label, lux_params[1],dim_label, lux_params[2],dim_label,lux_params[3],dim_label,lux_params[4],dim_label,lux_params[5]))

            subplot.set_xlim(support[0],support[1])
            subplot.set_ylim(0,1.05)
            subplot2.set_xlim(support[0],support[1])
            subplot2.set_ylabel(r"$P(x|Gaussian_{%s})$" % ["H", "S","V"][i])
            align_yaxis(subplot, 1., subplot2, gm_height)


        leg_loc =(0.9,0.2)

        datum = [x*[360,100,100][i] for i,x in enumerate(self.hsv_color)];  phi_value = self.lux.get_phi(datum,self.current_post[j][0])
        #gauss_value = mult([norm.pdf(datum[i],all_g_params[i][0],all_g_params[i][1]) for i in range(3)])
        leg=self.fig.legend(probeplot+legend_set, ["Probe X"]+ [r"$\mathbf{\phi}_{%s}(X)=\mathbf{%2.5f}$; $\mathbf{\alpha}=\mathbf{%2.4f}$" % (self.current_post[j][0],phi_value,self.lux.get_avail(self.current_post[j][0]))]+lux_labels+
                                     [r"$Normal^{Hue}_{%s}$; $prior(%s)=%2.4f$" % (self.current_post[j][0],self.current_post[j][0], self.gm[self.current_post[j][0]][2])]+[g_labels[0]+"; "+g_labels[1]+"; "+g_labels[2]]
                                     , loc=8, handletextpad=4,labelspacing=0.1)


        self.fig.suptitle("%s" % name, size=30)

        print "done replotting"

    def onChoose(self, *args):
        try:
            ((red,green,blue), hx) = tkColorChooser.askcolor()
        except:
            print "I think you hit cancel"
            return
        self.hex_color = hx
        self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0)
        self.frame.config(bg=hx)
        self.update_output()
        self.fig.clear()
        self.replot()
        self.canvas.draw()

    def onSelect(self, *args):
        self.fig.clear()
        self.replot()
        self.canvas.draw()
Example #52
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'
Example #53
0
class OSCRemote(object):
    def __init__(self):

        self.editor_issue = "1.3"

        # get command options
        self.command_options = remote_options()

        # get directory holding the code
        self.pp_dir = sys.path[0]

        if not os.path.exists(self.pp_dir + os.sep + "pp_oscremote.py"):
            tkMessageBox.showwarning("Pi Presents",
                                     "Bad Application Directory")
            exit()

        # Initialise logging
        Monitor.log_path = self.pp_dir
        self.mon = Monitor()
        self.mon.init()

        Monitor.classes = ['OSCRemote', 'OSCConfig', 'OSCEditor']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log(self, "Pi Presents Remote is starting")
        self.mon.log(self, " OS and separator " + os.name + '  ' + os.sep)
        self.mon.log(self,
                     "sys.path[0] -  location of code: code " + sys.path[0])

        self.setup_gui()

        # OSC config class
        self.osc_config = OSCConfig()

        self.init()

        #and start the system
        self.root.after(1000, self.run_app)
        self.root.mainloop()

    def init(self):
        self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscremote.cfg'
        self.read_create_osc()
        self.pp_home_dir = self.osc_config.pp_home_dir
        self.pp_profiles_offset = self.osc_config.pp_profiles_offset
        self.mon.log(self, "Data Home from options is " + self.pp_home_dir)
        self.mon.log(
            self, "Current Profiles Offset from options is " +
            self.pp_profiles_offset)
        self.pp_profile_dir = ''

        self.current_showlist = None
        self.current_show = None
        self.current_show_ref = ''
        self.shows_display.delete(0, END)
        self.results.set('')

    def add_status(self, text):
        self.status_display.insert(END, text + '\n')
        self.status_display.see(END)

    def run_app(self):
        self.client = None
        self.server = None
        self.st = None

        # initialise OSC variables
        self.prefix = '/pipresents'
        self.this_unit = '/' + self.osc_config.this_unit_name
        self.add_status('this unit is: ' + self.this_unit)
        self.controlled_unit = '/' + self.osc_config.controlled_unit_1_name
        self.add_status('controlled unit is: ' + self.controlled_unit)

        #connect client then start server to listen for replies
        self.init_client()
        self.add_status('connecting to controlled unit: ' +
                        self.osc_config.controlled_unit_1_ip + ':' +
                        self.osc_config.controlled_unit_1_port + ' ' +
                        self.osc_config.controlled_unit_1_name)
        self.connect_client(self.osc_config.controlled_unit_1_ip,
                            self.osc_config.controlled_unit_1_port)
        self.add_status('listening for replies on:' +
                        self.osc_config.this_unit_ip + ':' +
                        self.osc_config.this_unit_port)
        self.init_server(self.osc_config.this_unit_ip,
                         self.osc_config.this_unit_port, self.client)
        self.add_initial_handlers()
        self.start_server()

# ***************************************
#  RESPOND TO BUTTONS
# ***************************************

    def open_show(self):
        self.msg_path = '/core/open '
        self.msg_arg_text = self.current_show_ref
        self.display_msg_text()

    def close_show(self):
        self.msg_path = '/core/close '
        self.msg_arg_text = self.current_show_ref
        self.display_msg_text()

    def exit_pipresents(self):
        self.msg_path = '/core/exitpipresents'
        self.msg_arg_text = ''
        self.display_msg_text()

    def play_event(self):
        self.msg_path = '/core/event'
        self.msg_arg_text = 'pp-play'
        self.display_msg_text()

    def pause_event(self):
        self.msg_path = '/core/event'
        self.msg_arg_text = 'pp-pause'
        self.display_msg_text()
        pass

    def stop_event(self):
        self.msg_path = '/core/event'
        self.msg_arg_text = 'pp-stop'
        self.display_msg_text()
        pass

    def up_event(self):
        self.msg_path = '/core/event'
        self.msg_arg_text = 'pp-up'
        self.display_msg_text()

    def down_event(self):
        self.msg_path = '/core/event'
        self.msg_arg_text = 'pp-down'
        self.display_msg_text()

    def output(self):
        self.msg_path = '/core/output'
        self.msg_arg_text = ''
        self.display_msg_text()

    def loopback(self):
        self.msg_path = '/system/loopback'
        self.msg_arg_text = ''
        self.display_msg_text()

    def server_info(self):
        self.msg_path = '/system/server-info'
        self.msg_arg_text = ''
        self.display_msg_text()

    # and put the created text in the results box in the gui
    def display_msg_text(self):
        self.results.set(self.prefix + self.controlled_unit + self.msg_path +
                         ' ' + self.msg_arg_text)

    #calback from the Send button
    # parses the message string into fields and sends - NO error checking
    def send_message(self):
        msg_text = self.results.get()
        self.add_status('Send message:' + msg_text)
        self.mon.log(self, 'send message: ' + msg_text)
        fields = msg_text.split()
        address = fields[0]
        arg_list = fields[1:]
        self.send(address, arg_list)

    # ***************************************
    # OSC CLIENT TO SEND MESSAGES
    # ***************************************

    def init_client(self):
        self.client = OSC.OSCClient()

    def connect_client(self, ip, port):
        self.mon.log(self, 'connect to: ' + ip + ':' + str(port))
        self.client.connect((ip, int(port)))

    def send(self, address, arg_list):
        msg = OSC.OSCMessage()
        msg.setAddress(address)
        for arg in arg_list:
            msg.append(arg)
        self.client.send(msg)

    def disconnect_client(self):
        self.client.close()
        return

    # ***************************************
    # OSC SERVER TO LISTEN TO REPLIES
    # ***************************************

    def init_server(self, ip, port_text, client):
        self.mon.log(self, 'Start Server: ' + ip + ':' + port_text)
        self.server = OSC.OSCServer((ip, int(port_text)), client)

    def start_server(self):
        self.st = threading.Thread(target=self.server.serve_forever)
        self.st.start()

    def close_server(self):
        if self.server != None:
            self.server.close()
        self.mon.log(self, 'Waiting for Server-thread to finish')
        if self.st != None:
            self.st.join()  ##!!!
        self.mon.log(self, 'server thread closed')

    def add_initial_handlers(self):
        self.server.addMsgHandler('default', self.no_match_handler)
        self.server.addMsgHandler(
            self.prefix + self.this_unit + "/system/loopback-reply",
            self.loopback_reply_handler)
        self.server.addMsgHandler(
            self.prefix + self.this_unit + "/system/server-info-reply",
            self.server_info_reply_handler)

    def no_match_handler(self, addr, tags, stuff, source):
        text = ''
        text += "no match for new osc msg from %s" % OSC.getUrlStr(
            source) + '\n'
        text += "with addr : %s" % addr + '\n'
        text += "typetags %s" % tags + '\n'
        text += "data %s" % stuff + '\n'
        self.add_status(text + '\n')

    def loopback_reply_handler(self, addr, tags, stuff, source):
        self.add_status('Loopback reply  received from: ' +
                        self.pretty_list(source))

    def server_info_reply_handler(self, addr, tags, stuff, source):
        self.add_status('Server Information from: ' +
                        self.pretty_list(source) + '\n   ' +
                        self.pretty_list(stuff))

    def pretty_list(self, fields):
        text = ' '
        for field in fields:
            text += str(field) + ' '
        return text

    # ***************************************
    # INIT EXIT MISC
    # ***************************************

    def e_edit_osc(self):
        self.disconnect_client()
        self.close_server()
        self.edit_osc()
        self.init()
        self.add_status('\n\n\nRESTART')
        self.run_app()

    def app_exit(self):
        self.disconnect_client()
        self.close_server()
        if self.root is not None:
            self.root.destroy()
        self.mon.finish()
        sys.exit()

    def show_help(self):
        tkMessageBox.showinfo("Help", "Read 'manual.pdf'")

    def about(self):
        tkMessageBox.showinfo(
            "About", "Simple Remote Control for Pi Presents\n" +
            "Author: Ken Thompson" +
            "\nWebsite: http://pipresents.wordpress.com/")

    def setup_gui(self):
        # set up the gui

        # root is the Tkinter root widget
        self.root = Tk()
        self.root.title("Remote Control for Pi Presents")

        # self.root.configure(background='grey')

        self.root.resizable(False, False)

        # define response to main window closing
        self.root.protocol("WM_DELETE_WINDOW", self.app_exit)

        # bind some display fields
        self.filename = StringVar()
        self.display_show = StringVar()
        self.results = StringVar()
        self.status = StringVar()

        # define menu
        menubar = Menu(self.root)

        profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        profilemenu.add_command(label='Select',
                                command=self.open_existing_profile)
        menubar.add_cascade(label='Profile', menu=profilemenu)

        toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Tools', menu=toolsmenu)

        osc_configmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='OSC', menu=osc_configmenu)
        osc_configmenu.add_command(label='Edit', command=self.e_edit_osc)

        helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Help', menu=helpmenu)
        helpmenu.add_command(label='Help', command=self.show_help)
        helpmenu.add_command(label='About', command=self.about)

        self.root.config(menu=menubar)

        #top frame
        top_frame = Frame(self.root, padx=5, pady=5)
        top_frame.pack(side=TOP)

        results_label = Label(top_frame,
                              text="Message to Send",
                              font="arial 12 bold")
        results_label.pack(side=LEFT)
        results_display = Entry(top_frame, textvariable=self.results, width=70)
        results_display.pack(side=LEFT, fill=BOTH, expand=1)
        send_button = Button(top_frame,
                             width=5,
                             height=1,
                             text='Send',
                             fg='black',
                             command=self.send_message,
                             bg="light grey")
        send_button.pack(side=RIGHT)

        #bottom frame
        bottom_frame = Frame(self.root, padx=5, pady=5)
        bottom_frame.pack(side=TOP, fill=BOTH, expand=1)
        left_frame = Frame(bottom_frame, padx=5)
        left_frame.pack(side=LEFT)
        right_frame = Frame(bottom_frame, padx=5, pady=5)
        right_frame.pack(side=LEFT)

        suplabel_frame = Frame(right_frame, pady=5)
        suplabel_frame.pack(side=TOP)
        commands_label = Label(suplabel_frame,
                               text="Show Control",
                               font="arial 12 bold")
        commands_label.pack()

        supervisor_frame = Frame(right_frame, pady=5)
        supervisor_frame.pack(side=TOP)

        # supervisor buttons
        add_button = Button(supervisor_frame,
                            width=5,
                            height=1,
                            text='Open\nShow',
                            fg='black',
                            command=self.open_show,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(supervisor_frame,
                            width=5,
                            height=1,
                            text='Close\nShow',
                            fg='black',
                            command=self.close_show,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(supervisor_frame,
                            width=10,
                            height=1,
                            text='Exit\nPi Presents',
                            fg='black',
                            command=self.exit_pipresents,
                            bg="light grey")
        add_button.pack(side=LEFT)

        # events buttons
        oplabel_frame = Frame(right_frame, pady=5)
        oplabel_frame.pack(side=TOP)
        operations_label = Label(oplabel_frame,
                                 text="Input Events",
                                 font="arial 12 bold")
        operations_label.pack()

        operations_frame = Frame(right_frame, pady=5)
        operations_frame.pack(side=TOP)

        add_button = Button(operations_frame,
                            width=5,
                            height=1,
                            text='Play',
                            fg='black',
                            command=self.play_event,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(operations_frame,
                            width=5,
                            height=1,
                            text='Pause',
                            fg='black',
                            command=self.pause_event,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(operations_frame,
                            width=5,
                            height=1,
                            text='Stop',
                            fg='black',
                            command=self.stop_event,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(operations_frame,
                            width=5,
                            height=1,
                            text='Up',
                            fg='black',
                            command=self.up_event,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(operations_frame,
                            width=5,
                            height=1,
                            text='Down',
                            fg='black',
                            command=self.down_event,
                            bg="light grey")
        add_button.pack(side=LEFT)

        # animate buttons
        animate_frame = Frame(right_frame, pady=5)
        animate_frame.pack(side=TOP)
        animate_label = Label(animate_frame,
                              text="Control Outputs",
                              font="arial 12 bold")
        animate_label.pack()

        animate_frame = Frame(right_frame, pady=5)
        animate_frame.pack(side=TOP)

        add_button = Button(animate_frame,
                            width=5,
                            height=1,
                            text='Output',
                            fg='black',
                            command=self.output,
                            bg="light grey")
        add_button.pack(side=LEFT)

        # system buttons
        systemlabel_frame = Frame(right_frame, pady=5)
        systemlabel_frame.pack(side=TOP)
        system_label = Label(systemlabel_frame,
                             text="System",
                             font="arial 12 bold")
        system_label.pack()

        system_frame = Frame(right_frame, pady=5)
        system_frame.pack(side=TOP)

        add_button = Button(system_frame,
                            width=5,
                            height=1,
                            text='Loopback',
                            fg='black',
                            command=self.loopback,
                            bg="light grey")
        add_button.pack(side=LEFT)
        add_button = Button(system_frame,
                            width=10,
                            height=1,
                            text='Server Info',
                            fg='black',
                            command=self.server_info,
                            bg="light grey")
        add_button.pack(side=LEFT)

        # define display of showlist
        shows_title_frame = Frame(left_frame)
        shows_title_frame.pack(side=TOP)
        shows_label = Label(shows_title_frame, text="Shows")
        shows_label.pack()
        shows_frame = Frame(left_frame)
        shows_frame.pack(side=TOP)
        scrollbar = Scrollbar(shows_frame, orient=VERTICAL)
        self.shows_display = Listbox(shows_frame,
                                     selectmode=SINGLE,
                                     height=12,
                                     width=40,
                                     bg="white",
                                     activestyle=NONE,
                                     fg="black",
                                     yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.shows_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.shows_display.pack(side=LEFT, fill=BOTH, expand=1)
        self.shows_display.bind("<ButtonRelease-1>", self.e_select_show)

        # status_frame
        status_frame = Frame(self.root, padx=5, pady=5)
        status_frame.pack(side=TOP, fill=BOTH, expand=1)
        status_label = Label(status_frame, text="Status", font="arial 12 bold")
        status_label.pack(side=LEFT)
        scrollbar = Scrollbar(status_frame, orient=VERTICAL)
        self.status_display = Text(status_frame,
                                   height=10,
                                   yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.status_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.status_display.pack(side=LEFT, fill=BOTH, expand=1)

    # ***************************************
    # SHOWLIST
    # ***************************************

    def open_existing_profile(self):
        initial_dir = self.pp_home_dir + os.sep + "pp_profiles" + self.pp_profiles_offset
        if os.path.exists(initial_dir) is False:
            self.mon.err(
                self, "Profiles directory not found: " + initial_dir +
                "\n\nHint: Data Home option must end in pp_home")
            return
        dir_path = tkFileDialog.askdirectory(initialdir=initial_dir)
        # dir_path="C:\Users\Ken\pp_home\pp_profiles\\ttt"
        if len(dir_path) > 0:
            self.open_profile(dir_path)

    def open_profile(self, dir_path):
        showlist_file = dir_path + os.sep + "pp_showlist.json"
        if os.path.exists(showlist_file) is False:
            self.mon.err(
                self, "Not a Profile: " + dir_path +
                "\n\nHint: Have you opened the profile directory?")
            return
        self.pp_profile_dir = dir_path
        self.root.title("Remote for Pi Presents - " + self.pp_profile_dir)
        self.open_showlist(self.pp_profile_dir)

    def open_showlist(self, profile_dir):
        showlist_file = profile_dir + os.sep + "pp_showlist.json"
        if os.path.exists(showlist_file) is False:
            self.mon.err(
                self, "showlist file not found at " + profile_dir +
                "\n\nHint: Have you opened the profile directory?")
            self.app_exit()
        self.current_showlist = ShowList()
        self.current_showlist.open_json(showlist_file)
        if float(self.current_showlist.sissue()) != float(self.editor_issue):
            self.mon.err(
                self, "Version of profile does not match Remote: " +
                self.editor_issue)
            self.app_exit()
        self.refresh_shows_display()

    def refresh_shows_display(self):
        self.shows_display.delete(0, self.shows_display.size())
        for index in range(self.current_showlist.length()):
            self.shows_display.insert(
                END,
                self.current_showlist.show(index)['title'] + "   [" +
                self.current_showlist.show(index)['show-ref'] + "]")
        if self.current_showlist.show_is_selected():
            self.shows_display.itemconfig(
                self.current_showlist.selected_show_index(), fg='red')
            self.shows_display.see(self.current_showlist.selected_show_index())

    def e_select_show(self, event):
        print 'select show', self.current_showlist.length()
        if self.current_showlist is not None and self.current_showlist.length(
        ) > 0:
            mouse_item_index = int(event.widget.curselection()[0])
            self.current_showlist.select(mouse_item_index)
            self.current_show_ref = self.current_showlist.selected_show(
            )['show-ref']
            self.refresh_shows_display()
        else:
            self.current_show_ref = ''


# ***************************************
#  OSC CONFIGURATION
# ***************************************

    def read_create_osc(self):
        if self.osc_config.read(self.osc_config_file) is False:
            self.osc_config.create(self.osc_config_file)
            eosc = OSCEditor(self.root, self.osc_config_file, 'remote',
                             'Create OSC Remote Configuration')
            self.osc_config.read(self.osc_config_file)

    def edit_osc(self):
        if self.osc_config.read(self.osc_config_file) is False:
            self.osc_config.create(self.osc_config_file)
        eosc = OSCEditor(self.root, self.osc_config_file, 'remote',
                         'Edit OSC Reomote Configuration')
class ActionModulation(Frame):
    def __init__(self,parent):
        Frame.__init__(self,parent)
        self.parent = parent
        self.intensityValue = 0.0
        self.initUI()
        
    def initUI(self):
        self.frame = Frame(self.parent, relief=RAISED,borderwidth=1)
        #panel with the information to be introduced
        #self.grid(row=0,column=0)
        self.position = PanelInformation.PanelInformation(self.frame)
        self.position.getFrame().grid(row=0,column=0)
        self.position.setLabelXLabel("Position X:")
        self.position.setLabelYLabel("Position Y:")
        self.position.setLabelThetaLabel("Position Theta:")
        self.velocity = PanelInformation.PanelInformation(self.frame)
        self.velocity.getFrame().grid(row=1,column=0)
        self.velocity.setLabelXLabel("Walk Shoulder:")
        self.velocity.setLabelYLabel("Walk torso:")
        self.velocity.setLabelThetaLabel("Pose:")
        #panel for the emotion intensity
        self.frameIntensity =  Frame(self.frame, relief=RAISED,borderwidth=1)
        self.frameIntensity.grid(row = 4, column = 0)
        self.labelIntensity = Label(self.frameIntensity,text="Intensity:")
        self.labelIntensity.grid(row=0,column=0)
        self.intensity = Scale(self.frameIntensity, from_=0, to = 1,command=self.onScale)
        self.intensity.grid(row = 1, column = 0)
        self.var = IntVar()
        self.labelInfoIntensity = Label(self.frameIntensity, text=0, textvariable=self.var)
        self.labelInfoIntensity.grid(row = 2, column = 0)
        
        #panel with the robot's information
        self.positionInfo = PanelInformation.PanelInformation(self.frame)
        self.positionInfo.setDisableEntry()
        self.positionInfo.getFrame().grid(row=0,column=2)
        self.positionInfo.setLabelXLabel("Position X:")
        self.positionInfo.setLabelYLabel("Position Y:")
        self.positionInfo.setLabelThetaLabel("Position Theta:")
        self.velocityInfo = PanelInformation.PanelInformation(self.frame)
        self.velocityInfo.setDisableEntry()
        self.velocityInfo.getFrame().grid(row=1,column=2)
        self.velocityInfo.setLabelXLabel("Velocity X:")
        self.velocityInfo.setLabelYLabel("Velocity Y:")
        self.velocityInfo.setLabelThetaLabel("Velocity Theta:")
        #emotions and actions
        self.frameEmotionAction = Frame(self.frame, relief=RAISED,borderwidth=1)
        self.frameEmotionAction.grid(row=2,column=0,columnspan=3)
        self.labelEmotion = Label(self.frameEmotionAction,text="Emotion:")
        self.labelEmotion.grid(row=0,column=0)
        scrollbar = Scrollbar(self.frameEmotionAction, orient=VERTICAL)
        scrollbar.grid(row=0,column=3)
        self.listEmotion = Listbox(self.frameEmotionAction,height=4)
        self.listEmotion.grid(row=0,column=2)
        self.listEmotion.bind("<<ListboxSelect>>", self.onSelectEmotion)
        #the new emotions should be added here
        self.emotions = ['neutral','angry','happy','sad','fear','content']
        for item in self.emotions:
            self.listEmotion.insert(END,item)
        self.listEmotion.config(yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.listEmotion.yview)
        self.labelAction = Label(self.frameEmotionAction,text="Action:")
        self.labelAction.grid(row=0,column=4)
        scrollbar2 = Scrollbar(self.frameEmotionAction, orient=VERTICAL)
        scrollbar2.grid(row=0,column=6)
        self.listAction = Listbox(self.frameEmotionAction,height=4)
        self.listAction.grid(row=0,column=5)
        #the new actions should be added here
        self.actions = ['not_do_anything','oscillate_shoulder','oscillate_body','move_shoulder','move_body','move_torso','oscillate_torso','walk']
        for item in self.actions:
            self.listAction.insert(END,item)
        self.listAction.config(yscrollcommand=scrollbar2.set)
        self.listAction.bind("<<ListboxSelect>>", self.onSelectAction)
        scrollbar2.config(command=self.listAction.yview)
        
        self.actionSelected = "do_nothing"
        self.emotionSelected = "neutral"
    
    def getFrame(self):
        return self.frame
    
    def onScale(self, val): 
        v = format(float(val),'.2f')
        self.intensityValue = v
        self.var.set(v) 
        
    def getIntensity(self):
        return self.intensityValue
        
    def onSelectAction(self,val):
        sender = val.widget
        idx = sender.curselection()
        self.actionSelected = sender.get(idx)
        
    def onSelectEmotion(self,val):
        sender = val.widget
        idx = sender.curselection()
        self.emotionSelected = sender.get(idx)
    
    def getListEmotion(self):
        return self.emotionSelected
        
    def getListAction(self):
        return self.actionSelected
    
    def getPanelPosition(self):
        return self.position
    
    def getPanelVelocity(self):
        return self.velocity    
    
    def getPanelInfoPosition(self):
        return self.positionInfo
    
    def getPanelInfoVelocity(self):
        return self.velocityInfo
Example #55
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()
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))
Example #57
0
File: gui.py Project: 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='')
Example #58
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()
Example #59
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)
Example #60
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