예제 #1
0
class SelectionDialog(_TkDialog):
    def __init__(self, message, values):
        _TkDialog.__init__(self, message, values)

    def _create_selector(self, parent, values):
        self._listbox = Listbox(parent)
        for item in values:
            self._listbox.insert(END, item)
        return self._listbox

    def _validate_value(self):
        return bool(self._listbox.curselection())

    def _get_value(self):
        return self._listbox.get(self._listbox.curselection())
예제 #2
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))
예제 #3
0
class SelectionDialog(_TkDialog):

    def __init__(self, message, values):
        _TkDialog.__init__(self, message, values)

    def _create_selector(self, parent, values):
        self._listbox = Listbox(parent)
        for item in values:
            self._listbox.insert(END, item)
        return self._listbox

    def _validate_value(self):
        return bool(self._listbox.curselection())

    def _get_value(self):
        return self._listbox.get(self._listbox.curselection())
예제 #4
0
class LBChoice(object):
    '''This is a listbox for returning projects to be unarchived.'''
    def __init__(self, list_=None, master=None, title=None):
        '''Must have master, title is optional, li is too.'''
        self.master = master
        if self.master is not None:
            self.top = Toplevel(self.master)
        else:
            return
        self.v = None
        if list_ is None or not isinstance(list_, list):
            self.list = []
        else:
            self.list = list_[:]
        self.top.transient(self.master)
        self.top.grab_set()
        self.top.bind("<Return>", self._choose)
        self.top.bind("<Escape>", self._cancel)
        if title:
            self.top.title(title)
        lf = Frame(self.top)  #Sets up the list.
        lf.pack(side=TOP)
        scroll_bar = Scrollbar(lf)
        scroll_bar.pack(side=RIGHT, fill=Y)
        self.lb = Listbox(lf, selectmode=SINGLE)
        self.lb.pack(side=LEFT, fill=Y)
        scroll_bar.config(command=self.lb.yview)
        self.lb.config(yscrollcommand=scroll_bar.set)
        self.list.sort()
        for item in self.list:
            self.lb.insert(END, item)  #Inserts items into the list.
        bf = Frame(self.top)
        bf.pack(side=BOTTOM)
        Button(bf, text="Select", command=self._choose).pack(side=LEFT)
        Button(bf, text="New", command=self._new).pack(side=LEFT)
        Button(bf, text="Cancel", command=self._cancel).pack(side=LEFT)

    def _choose(self, event=None):
        try:
            first = self.lb.curselection()[0]
            self.v = self.list[int(first)]
        except IndexError:
            self.v = None
        self.top.destroy()

    def _new(self, event=None):
        self.v = "NEW"
        self.top.destroy()

    def _cancel(self, event=None):
        self.top.destroy()

    def return_value(self):
        self.master.wait_window(self.top)
        return self.v
예제 #5
0
파일: notes.py 프로젝트: Ghalko/noteTaker
class LBChoice(object):
    '''This is a listbox for returning projects to be unarchived.'''
    def __init__(self, list_=None, master=None, title=None):
        '''Must have master, title is optional, li is too.'''
        self.master = master
        if self.master is not None:
            self.top = Toplevel(self.master)
        else:
            return
        self.v = None
        if list_ is None or not isinstance(list_, list):
            self.list = []
        else:
            self.list = list_[:]
        self.top.transient(self.master)
        self.top.grab_set()
        self.top.bind("<Return>", self._choose)
        self.top.bind("<Escape>", self._cancel)
        if title:
            self.top.title(title)
        lf = Frame(self.top)         #Sets up the list.
        lf.pack(side=TOP)
        scroll_bar = Scrollbar(lf)
        scroll_bar.pack(side=RIGHT, fill=Y)
        self.lb = Listbox(lf, selectmode=SINGLE)
        self.lb.pack(side=LEFT, fill=Y)
        scroll_bar.config(command=self.lb.yview)
        self.lb.config(yscrollcommand=scroll_bar.set)
        self.list.sort()
        for item in self.list:
            self.lb.insert(END, item)     #Inserts items into the list.
        bf = Frame(self.top)
        bf.pack(side=BOTTOM)
        Button(bf, text="Select", command=self._choose).pack(side=LEFT)
        Button(bf, text="New", command=self._new).pack(side=LEFT)
        Button(bf, text="Cancel", command=self._cancel).pack(side=LEFT)

    def _choose(self, event=None):
        try:
            first = self.lb.curselection()[0]
            self.v = self.list[int(first)]
        except IndexError:
            self.v = None
        self.top.destroy()

    def _new(self, event=None):
        self.v = "NEW"
        self.top.destroy()

    def _cancel(self, event=None):
        self.top.destroy()

    def return_value(self):
        self.master.wait_window(self.top)
        return self.v
예제 #6
0
파일: gui.py 프로젝트: sangyf/ktailFSM
 def set_listTop(Listbox,sMap):
         try:
             index=Listbox.curselection()[0]
             #Check if there is an existing entry in the listbox
         except IndexError:
             index=END
         for i,listbox_entry in enumerate(Listbox.get(0, END)):
             if listbox_entry == sMap:
                 tkMessageBox.showinfo("Entry", "There is already an entry for this transition.")
                 return
 
         Listbox.insert(index, sMap)
예제 #7
0
    class SelectionDialog(_AbstractTkDialog):
        _left_button = 'OK'
        _right_button = 'Cancel'

        def __init__(self, message, values):
            self._message = message
            self._values = values
            _AbstractTkDialog.__init__(self, "Select one option")

        def create_components(self, parent):
            Label(parent, text=self._message).pack(fill=BOTH)
            self._listbox = Listbox(parent)
            self._listbox.pack(fill=BOTH)
            for item in self._values:
                self._listbox.insert(END, item)
            return self._listbox

        def validate(self):
            return bool(self._listbox.curselection())

        def apply(self):
            self.result = self._listbox.get(self._listbox.curselection())
예제 #8
0
    class SelectionDialog(_AbstractTkDialog):
        _left_button = 'OK'
        _right_button = 'Cancel'

        def __init__(self, message, values):
            self._message = message
            self._values = values
            _AbstractTkDialog.__init__(self, "Select one option")

        def create_components(self, parent):
            Label(parent, text=self._message).pack(fill=BOTH)
            self._listbox = Listbox(parent)
            self._listbox.pack(fill=BOTH)
            for item in self._values:
                self._listbox.insert(END, item)
            return self._listbox

        def validate(self):
            return bool(self._listbox.curselection())

        def apply(self):
            self.result = self._listbox.get(self._listbox.curselection())
예제 #9
0
class MultipleSelectionDialog(_TkDialog):

    def __init__(self, message, values):
        _TkDialog.__init__(self, message, values)

    def _create_selector(self, parent, values):
        self._listbox = Listbox(parent, selectmode='multiple')
        for item in values:
            self._listbox.insert(END, item)
        self._listbox.config(width=0)
        return self._listbox

    def _get_value(self):
        selected_values = [self._listbox.get(i) for i in self._listbox.curselection()]
        return selected_values
예제 #10
0
class MultipleSelectionDialog(_TkDialog):
    def __init__(self, message, values):
        _TkDialog.__init__(self, message, values)

    def _create_selector(self, parent, values):
        self._listbox = Listbox(parent, selectmode='multiple')
        for item in values:
            self._listbox.insert(END, item)
        self._listbox.config(width=0)
        return self._listbox

    def _get_value(self):
        selected_values = [
            self._listbox.get(i) for i in self._listbox.curselection()
        ]
        return selected_values
예제 #11
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)
예제 #12
0
class ABFChannelSelector(Toplevel):
    def __init__(self, pathname, channels):
        Toplevel.__init__(self)
        x = (self.winfo_screenwidth() - 200) / 2
        y = (self.winfo_screenheight() - 200) / 2
        self.geometry("+%d+%d" % (x, y))
        self.channels = channels
        header = Label(self,
                       text="Select channel from '%s':" %
                       os.path.basename(pathname),
                       width=30,
                       anchor='w')
        self.chanbox = Listbox(self, width=30, height=5, bg='white')
        ok_button = Button(self, text="OK", command=self.ok)
        cancel_button = Button(self, text="Cancel", command=self.cancel)
        header.pack(side='top', padx=10, pady=10)
        self.chanbox.pack(side='top', padx=10)
        cancel_button.pack(side='right', padx=10, pady=10)
        ok_button.pack(side='right')
        for n, name, units in channels:
            self.chanbox.insert('end',
                                "%d  %-10s  %-8s" % (n + 1, name, units))
        self.channel = None
        self.tkraise()
        self.focus_set()

    def present(self):
        self.wait_window()

    def ok(self):
        sel = self.chanbox.curselection()
        if sel:
            self.channel = self.channels[int(sel[0])][0]
        self.destroy()

    def cancel(self):
        self.destroy()
예제 #13
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)
예제 #14
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()
예제 #15
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
예제 #16
0
파일: gui.py 프로젝트: akiress/idt4243
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)
예제 #17
0
class hillGUI(Frame):
    """The base class for the hill_calc GUI"""
    
    # This is the constructor for the GUI
    def __init__(self,master=None):
        # We begin by calling the base class's constructor first
        Frame.__init__(self,master)
    
        # We now have an empty window!
        
        # This command sets up a grid structure in the window
        self.grid()
        
        # This loop generates rows and columns in the grid
        for i in range(10):
            self.rowconfigure(i,minsize=10)
        for i in range(3):
            self.columnconfigure(i,minsize=10)
        
        # These are methods which appear below the constructor
        #self.defineUnits() # this sets up the units I'll be using in the converter
        self.createWidgets() # this places the elements (or widgets) in the grid
        
        # This command "binds" the user's click to a method (varChoice)
        # This method will determine which variable the user wants (Distance, Mass, Time)
        self.inputlist.bind("<Button-1>",self.__varChoice)
    
        # This is a similar command for the selection of unit
        self.unitlist.bind("<Button-1>",self.__unitChoice)
    
        # Finally, this bind reads in whatever value is in the text box when the user hits return
        # and carries out the unit conversion
        
        for i in range(len(self.inputfield)):
            self.inputfield[i].bind("<Return>",self.__calcConversion)
               
    def createUnitDict(self,mydict,mykeys,myvalues):
        '''This method takes a set of units and values, and creates a dictionary to store them in'''
        for i in range(len(myvalues)):
            mydict[mykeys[i]] = myvalues[i]
            
    def createWidgets(self):
        '''This method creates all widgets and adds them to the GUI'''
        
        # Create Widgets in order of appearance
        # This is not necessary, but makes code easier to read
        
        # Start with text telling user what to do
        self.varlabel = Text(self,height=1, width=20)
        self.varlabel.insert(END,"Which Variable?")
        
        # Place widget on the Frame according to a grid
        self.varlabel.grid(row=0,column=0,sticky=W)
        
        # Second text label asking user which units are being used
        self.unitlabel = Text(self,height=2,width=20)
        self.unitlabel.insert(END,"Planet Mass Units?\n (a=AU, Ms=Msol)")
        self.unitlabel.grid(row=0,column=1,sticky=W)
        
        # Third text label asking user for numerical value
        
        self.numlabel = Text(self,height=1, width=20)
        self.numlabel.insert(END,"Enter Variable Values")
        self.numlabel.grid(row=0,column=2,sticky=W)
        
        # This creates a list of options for the user to select
        self.inputlist = Listbox(self, height=4, selectmode=SINGLE)
      
        # Tuple of choices we're going to put in this list
        self.paramlist = ('Semi Major Axis', 'Planet Mass', 'Star Mass','Hill Radius')
        
        # Add each item separately
        for item in self.paramlist:
            self.inputlist.insert(END,item)
            
        # Add it to the grid    
        self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W)
        
        # Add a unit list (several combinations of units allowed)
        
        self.unitlist = Listbox(self, height=4,selectmode=SINGLE)
        self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W)
        
        self.massunits = ('Earth Masses','Neptune Masses', 'Jupiter Masses', 'Solar Masses') 
        self.massvalues = ( 3.00343905235e-06, 5.1500311727e-5, 0.000954588419846,1.0)
    
        self.massdict = {}
        self.createUnitDict(self.massdict, self.massunits,self.massvalues)
    
        for item in self.massunits:
            self.unitlist.insert(END,item)
    
        # Number Entry Boxes (and Text Labels)
        
        self.inputfield = []
        self.inputlabels = []
    
        irow = 0
        for i in range(len(self.paramlist)):
            
            irow = irow+1
            self.inputlabels.append(Text(self,height=1,width=20))
            self.inputlabels[i].insert(END,self.paramlist[i])
            self.inputlabels[i].grid(row=irow,column=2,sticky='N')
            irow = irow+1
            self.inputfield.append(Entry(self))
            self.inputfield[i].insert(END, "1.0")
            self.inputfield[i].grid(row =irow, column=2,sticky='N')
        
        # Text Output Box
        self.outputtext = Text(self, height=1, width=40)
        self.outputtext.grid(row=7,column=0,columnspan=2,sticky=W)
        self.outputtext.insert(END, "WAITING: ")
        # Create the Quit Button
        self.quitButton=Button(self,text='Quit',command=self.quit)
        self.quitButton.grid(row =8, column=0, sticky=W)
             

    # Event handler functions begin here    
    # This handler defines the choice of units available to the user, 
    # depending on selected variable
    
    def __varChoice(self, event):
        '''Handles the selection of variable: updates the list of units'''
        # Firstly, delete anything already in the units column
#        self.unitlist.delete(first=0,last=len(self.myvalues))
        num = 0
        
        # Identify which option was clicked on
        try:
            num = self.inputlist.curselection()[0]       
            self.varchoice = int(num)
            
        except:
            self.varchoice = 0
            return
        
        # Get the string associated with this choice
        selection= self.inputlist.get(self.varchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.inputlist.itemconfig(self.varchoice, selectbackground='red')

    def __unitChoice(self,event):
        '''Handles the selection of units'''
        num = 0
        # Find which number is selected
        try:
            num = self.unitlist.curselection()[0]       
            self.unitchoice = int(num)
            
        except:
            self.unitchoice = 0
            return
        
        # Get the string (i.e. which unit is selected)
        selection= self.unitlist.get(self.unitchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.unitlist.itemconfig(self.unitchoice, selectbackground='red')
        
        # If statement defines units being used
        
        self.massconvert = self.massdict[selection]
        
        
        # Remove all text in the output box, and tell user to define units
        self.outputtext.delete("1.0",index2=END)
        self.outputtext.insert(END, "Now Enter Values")
        
    # Handler takes current state of GUI, and calculates results
    def __calcConversion(self,event):
        '''This method takes the current state of all GUI variables, calculates one of four equations'''
        print 'Calculating'
        # Which variable has been selected for calculation?
        # This decides what equation to use
        
        a = self.inputfield[0].get()
        a=float(a)
        
        mp = self.inputfield[1].get()
        mp=float(mp)*self.massconvert
        
        ms = self.inputfield[2].get()
        ms = float(ms)
        
        rh = self.inputfield[3].get()
        rh = float(rh)
        
        if self.varchoice==0:
            a = rh*(3*ms/mp)*0.3333
            value = a
        elif self.varchoice==1:
            mp = 3*ms*rh**3/a**3
            value = mp
        elif self.varchoice==2:
            ms = mp*a**3/(3*rh**3)
            value = ms
        elif self.varchoice==3:
            rh = a *(mp/(3*ms))**0.3333
            value = rh
            
        
        # Remove all text in the output box and insert new stuff
        self.outputtext.delete("1.0",index2=END)
        self.outputtext.insert(END,str(self.paramlist[self.varchoice])+":    "+str(value))
예제 #18
0
class TkApp:
    def __init__(self, master, mech):
        self.mech = mech
        frame = Frame(master)
        frame.grid()
        rct_label = Label(frame, text='Select Reactants')
        rct_label.grid(column=1, row=1)
        and_or = Label(frame, text='AND/OR')
        and_or.grid(column=3, row=1)
        prod_label = Label(frame, text='Select Products')
        prod_label.grid(column=4, row=1)
        what_to_do = Label(frame, text='Execute')
        what_to_do.grid(column=6, row=1)
        reactants_scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.reactants = Listbox(frame,
                                 selectmode=EXTENDED,
                                 exportselection=0,
                                 yscrollcommand=reactants_scrollbar.set)
        self.reactants.grid(column=1, row=2)
        reactants_scrollbar.config(command=self.reactants.yview)
        reactants_scrollbar.grid(column=2, row=2, sticky=N + S)

        self.logical_and = IntVar()
        self.logical_and.set(1)
        c = Checkbutton(frame, text="AND", variable=self.logical_and)
        c.grid(column=3, row=2)

        products_scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.products = Listbox(frame, selectmode=EXTENDED, exportselection=0)
        self.products.grid(column=4, row=2)
        products_scrollbar.config(command=self.products.yview)
        products_scrollbar.grid(column=5, row=2, sticky=N + S)

        self.method_list = Listbox(frame,
                                   selectmode=EXTENDED,
                                   exportselection=0)
        self.method_list.grid(column=6, row=2)
        #self.methods = [k for k in dir(self.mech) if k[:1] != '_' and isinstance(getattr(self.mech, k), MethodType)]
        self.methods = [
            'plot_rxns', 'find_rxns', 'print_rxns', 'print_irrs',
            'print_net_rxn', 'plot_proc'
        ]
        method_labels = [
            'Plot Reactions', 'Show Rxn Ids', 'Print Rxns', 'Print IRRs',
            'Print Net Rxn', 'Process Plot'
        ]
        for method in method_labels:
            self.method_list.insert(END, method)

        species_keys = self.mech.species_dict.keys()
        species_keys.sort()
        self.species_objects = [
            self.mech.species_dict[spc] for spc in species_keys
        ]

        for spc in species_keys:
            self.reactants.insert(END, spc)
            self.products.insert(END, spc)
        self.execute_button = Button(frame, text="go", command=self.execute)
        self.execute_button.grid(column=6, row=4)

    def _get_species(self, list):
        items = list.curselection()
        try:
            items = map(int, items)
        except:
            pass
        items = map(lambda i, d=self.species_objects: d[i], items)
        return items

    def get_reactants(self):
        return self._get_species(self.reactants)

    def get_products(self):
        return self._get_species(self.products)

    def get_methods(self):
        items = self.method_list.curselection()
        try:
            items = map(int, items)
        except:
            pass
        items = map(lambda i, d=self.methods: d[i], items)
        return items

    def execute(self):
        os.system('clear')
        reactants = self.get_reactants()
        products = self.get_products()
        logical_and = bool(self.logical_and.get())
        methods = self.get_methods()
        kwds = dict(reactants=reactants,
                    products=products,
                    logical_and=logical_and)
        for method in methods:
            if method == 'plot_proc':
                thiskwds = {}
                thiskwds['species'] = (reactants + products)[0]
            else:
                thiskwds = kwds.copy()
            getattr(self.mech, method)(**thiskwds)
class ConstraintsView(Frame):
    "Presents all constraints created by user"

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

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

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

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

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

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

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

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

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

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

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

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

        self.constraint_name_list.append(constraint_name)

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

        self.constraints_output.append(output)

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

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

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

            # clear all output constraints
            self.constraints_output = []

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

            #clear all constraints
            self.constraint_name_list = []

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

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

            # clear constraints from the class
            deletion_list = []
            for j in selected_indices:
                #print(self.constraint_name_list)
                #print(self.constraints_output)
                deletion_list.append(self.constraint_name_list.pop(int(j)))
                self.constraints_output.pop(int(j))
            # clear selected constraints from the scheduler object
            globs.mainScheduler.delete_list_constraints(deletion_list)
예제 #20
0
class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Optistruct to Abaqus")
        #minusImage = PhotoImage(file="minus_svg.gif")
        #plusImage = ImageTk.PhotoImage(Image.open('plus_svg.png'))
        #minusImage = ImageTk.PhotoImage(Image.open('minus_svg.gif'))
        #plusImage=PhotoImage(file="plus.gif")
        #minusImage=PhotoImage(file="minus.gif")

        self.fileList = []

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

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

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

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

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

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

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

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

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

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

    def addFile(self):
        files = tkFileDialog.askopenfilenames(initialdir="/",
                                              title="Select file",
                                              filetypes=(("Optistruct Mesh",
                                                          "*.fem"),
                                                         ("All Files", "*.*")))
        if files != None:
            for file in files:
                if not file in self.fileList:
                    self.fileList.append(file)
                    self.listbox.insert(END, file)
예제 #21
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
예제 #22
0
파일: window.py 프로젝트: timpauls/raypy
class Window(Frame):
    RENDER_PROCESSES = 2

    def __init__(self, width, height, scene, tracer, calculate=None):
        Frame.__init__(self, master=None)

        if calculate is None:
            calculate = [0, 0]

        self.d = calculate
        self.scene = scene
        self.after_id = 0
        self.tracer = tracer
        self.width = width
        self.height = height

        self.__init_window(height, width)

        self.master.mainloop()

    def __init_window(self, height, width):
        self.master.title = "Ray Py"
        canvas = Canvas(self.master, width=width, height=height)
        canvas.pack(side=TOP)
        self.img = PhotoImage(width=width, height=height)
        canvas.create_image((width / 2, height / 2),
                            image=self.img,
                            state="normal")
        self.startButton = Button(self.master,
                                  text="Render",
                                  command=lambda: self.__onStartPressed())
        self.startButton.pack(side=RIGHT)
        self.resetButton = Button(self.master,
                                  text="Reset",
                                  command=lambda: self.__onResetPressed())
        self.resetButton.config(state="disabled")
        self.resetButton.pack(side=RIGHT)

        self.listbox = Listbox(self.master, height=5)
        self.listbox.bind('<<ListboxSelect>>', self.__selectTracer)
        self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow",
                            "Recursive", "PathTracer")
        self.listbox.pack(side=LEFT)

        self.listbox.selection_set(0)
        self.listbox.activate(0)
        self.listbox.focus_set()

    def __selectTracer(self, evt):
        value = self.listbox.get(self.listbox.curselection())
        if value == "Simple":
            self.tracer = SimpleRayTracer()
        elif value == "Shadow":
            self.tracer = SimpleShadowRayTracer()
        elif value == "ShadingShadow":
            self.tracer = ShadingShadowRayTracer(self.scene.eye)
        elif value == "Recursive":
            self.tracer = RecursiveRayTracer(self.scene.eye)
        elif value == "PathTracer":
            self.tracer = PathTracer(self.scene.eye)

    def __onStartPressed(self):
        self.startButton.config(state="disabled")
        self.listbox.config(state="disabled")
        self.__draw()

    def __update(self):
        if self.finishedQueue.qsize() >= self.RENDER_PROCESSES:
            self.finishedThreads = self.RENDER_PROCESSES
            while not self.finishedQueue.empty():
                self.finishedQueue.get()

        if not self.dataQueue.empty():
            item = self.dataQueue.get()
            self.img.put(item[1], item[0])
            self.master.update()
        elif self.finishedThreads == self.RENDER_PROCESSES:
            for t in self.threads:
                t.join()

            self.master.after_cancel(self.after_id)
            self.resetButton.config(state="active")
            return

        self.after_id = self.master.after(0, self.__update)

    def __draw(self):
        from processes import BlockProcess
        from multiprocessing import Queue
        self.finishedQueue = Queue()
        self.dataQueue = Queue()
        self.finishedThreads = 0

        self.threads = BlockProcess.forCount(self.RENDER_PROCESSES, self.width,
                                             self.height, self.tracer,
                                             self.scene, self.dataQueue,
                                             self.finishedQueue)

        for t in self.threads:
            t.start()

        self.__update()

        self.after_id = self.master.after(0, self.__update)

    def __onResetPressed(self):
        self.img.blank()
        self.d = [0, 0]
        self.resetButton.config(state="disabled")
        self.startButton.config(state="active")
        self.listbox.config(state="normal")
예제 #23
0
파일: GUI.py 프로젝트: WsanjaW/FingersGame
class ChatMainForm(Template):
    '''
    Class for graphic presentation of chat client.
    Main form with chat, list of created games, button for creating game.
    If you created game button becomes start game.
    ChatMainForm form with textbox, entry, listbox and button.
    '''
  
    def __init__(self, parent,name):
        '''
        Initialize all gui components...
        
        parent represents root of tk window
        name is  name that client entered
        
        Creates instance of client class and starts thread for receiving messages
        '''
        Template.__init__(self, parent)  
        
        self.client = ChatClient.ChatClient()
        #where to put try block here or in connect method
        self.client.connect_to_server()
          
        self.end = False #for stopping receiving thread 
        self.name = name
      
        #start new thread
        self.thread=thread.start_new_thread( self.receive_server_messages, (1,) )#!!!doesn't work without second argument
        
        #send first message with name
        self.client.send_message(self.name)
        
        self.parent = parent  
        
        
             
        self.initUI()
        
    def initUI(self):
        '''
        Initialize all gui components
        '''
        
        self.nameText = Label(self, text="Chat")
        self.nameText.place(x=270, y=10)
        self.nameText3 = Label(self, text="Players in game")
        self.nameText3.place(x=50,y=10)
        self.nameText2 = Label(self, text="Game list            ")# **********Popravi ovo!!!!!!********
        self.nameText2.place(x=50,y=10)
       
        
        #display chat messages
        self.messageDispley = Text(self,font=tkFont.Font(family="Calibri",size=10),width=28,height=13)
        self.messageDispley.place(x=270, y=40)
        self.messageDispley.insert(END,"Welcome...\n")
        
        #write text messages
        self.message = StringVar()
        self.messageText =Entry(self, textvariable=self.message, width=28)
        self.messageText.place(x=270, y=275)
        
        #send chat massage
        self.nameButton = Button(self, text="Send", width=26, command=self.send_chat_message)
        self.nameButton.place(x=270, y=300)
        
        #lists players in specific game
        self.playersList = Listbox(self)
        self.playersList.place(x=50, y=30)
        
        #lists all games
        self.gameList = Listbox(self)
        self.gameList.place(x=50, y=30)

        #join created game
        self.joinGameButton = Button(self,text="Join game",width=15, command=self.send_join_message)
        self.joinGameButton.place(x=50, y=230)
        
        #start created game
        self.startGameButton = Button(self,text="Start game",width=15, command=self.send_game_start_message)
        self.startGameButton.place(x=50, y=270)
        
        #create new game
        self.createGameButton = Button(self,text="Create new game",width=15, command=self.create_new_game)
        self.createGameButton.place(x=50, y=270)
        
     
    def send_game_start_message(self):
        '''
        Sends signal to server that game is starting
        '''        
        self.startGameButton.config(state=DISABLED)
        self.client.send_message("Start game")
        
    def send_join_message(self):
        '''
        Hides 'create new game' and 'Join game'  buttons and 
        shows 'Players list' listbox.
        Send message with selected game to server
        '''
        #first we think you can join
        self.canJoin = True
        
        items = self.gameList.curselection()  
        #if nothing is selected
        if items == tuple():
            return
        # creating xml document to be send
        root2 = etree.Element("JoinGame")
        ge = etree.SubElement(root2, "game").text =  self.gameList.get(items[0])  
        
        self.client.send_message(etree.tostring(root2))
        #join massage send 
        self.joinEvent.clear()
        #first receive_server_messages thread needs to finish processing message from server        
        self.joinEvent.wait()
        print "BUHA"
        #if we don't receive message from server we hide fields 
        if self.canJoin:
            self.joinGameButton.place_forget()
            self.createGameButton.place_forget()
            self.gameList.place_forget()
            self.nameText2.place_forget()
            self.startGameButton.place_forget()
                 
    def create_new_game(self):
        '''
        Hides 'create new game' and 'Join game'  buttons and 
        shows 'Start game' button and 'Players list' listbox.
        '''
        self.joinGameButton.place_forget()
        self.createGameButton.place_forget()
        self.gameList.place_forget()
        self.nameText2.place_forget()
        self.startGameButton.place(x=50, y=270)
        #can't start until somebody joins
        self.startGameButton.config(state=DISABLED)
        self.client.send_message("Create game")
        
         
    def send_chat_message(self):
        '''
        sends chat message to server
        if message is 'Bye' ends program**to be changed**
         
        '''
        
        # creating xml document to be send
        root2 = etree.Element("ChatMessage")
        etree.SubElement(root2, "message").text = self.message.get()
        
        self.client.send_message(etree.tostring(root2))
        
        if self.message.get() =='Bye':
            print 'sss'
            self.client.comSocket.close
            self.end = True
            self.parent.destroy()   
                     
        self.message.set('')   
        
    
    def find_next_player_index(self,currentPlayerIndex):
        '''
        finds index of next player on turn in playersList
        '''
        index = currentPlayerIndex + 1
        if index == len(self.game.playersList):
            index = 0
        
        while index != currentPlayerIndex:
            #print self.game.playersList[index].isOut
            #print type(self.game.playersList[index].isOut)
            if index ==  len(self.game.playersList):
                index = 0
            if str(self.game.playersList[index].isOut) == 'false':
                #print 'aaaaaaaaa'
                break
            else:
                index += 1;
        #print index
        return index
            
   
    def start_game(self,id):
        
        try:
            white = (255, 255, 255)
            # Call this function so the Pygame library can initialize itself
            pygame.init()
            # Create an 800x600 sized screen
            self.screen = pygame.display.set_mode([800, 600])
            # This sets the name of the window
            pygame.display.set_caption('Fingers game')
            clock = pygame.time.Clock()
            done = False
            firstClick = True
            secondClick = False
            # waits until process_message finish with game object   
            self.gameStateEvent.wait()
                     
            currentPlayer = self.game.playersList[self.game.ourIndex];
            ourField = currentPlayer.field
            nextField = None
                         
            
            hitting = None
            hitted  = None
          
            print "AAAAAAAAAAA"
            while done == False:
              
                clock.tick(10)
                nextIndex = self.find_next_player_index(self.game.ourIndex)
                nextPlayer = self.game.playersList[nextIndex]
                nextField = nextPlayer.field
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        #enable all filed for choosing game
                      
                        self.createGameButton.place(x=50, y=270)
                        self.joinGameButton.place(x=50, y=230)
                        self.nameText2.place(x=50,y=10)
                        self.gameList.place(x=50, y=30)
                        self.initialGameState = True
                        self.game = None
                        
                        self.client.send_message("QUIT")
                        pygame.quit()
                    
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        x, y = event.pos
                        # if game is over we can't play
                       
                        if self.game.gameOver == 'false':
                        
                            if self.client.comSocket.getsockname()[1] == self.game.playerTurn:
                                if firstClick:
                                    # check if left hand picture is clicked
                                    if ourField.image1.get_rect(center=ourField.get_centers()[0]).collidepoint(x, y):
                                        hitting = 'left'
                                        firstClick = False
                                        secondClick = True
                                    # check if right hand picture is clicked
                                    elif ourField.image2.get_rect(center=ourField.get_centers()[1]).collidepoint(x, y):
                                        hitting = 'right'
                                        firstClick = False
                                        secondClick = True
                                elif secondClick:
                                    # check if left hand picture is clicked
                                    if nextField.image1.get_rect(center=nextField.get_centers()[0]).collidepoint(x, y) and nextPlayer.fingersLeft != 0:
                                        hitted = 'left'
                                        secondClick = False
                                        #this turn over reset firstClick and secondClick
                                        firstClick = True
                                        secondClick = False
                                        
                                        self.send_move_message(hitting, hitted)
                                    # check if right hand picture is clicked
                                    elif nextField.image2.get_rect(center=nextField.get_centers()[1]).collidepoint(x, y) and nextPlayer.fingersRight != 0:
                                        
                                        hitted = 'right'
                                        secondClick = False
                                        #this turn over reset firstClick and secondClick
                                        firstClick = True
                                        secondClick = False
                                        self.send_move_message(hitting, hitted)
                                    #check if second hand is from same player and if separation is possible
                                    elif ourField.image1.get_rect(center=ourField.get_centers()[0]).collidepoint(x, y):
                                                                            
                                        if currentPlayer.fingersRight == 0 and (currentPlayer.fingersLeft == 2 or currentPlayer.fingersLeft == 4):                                       
                                            hitted = 'separation'
                                            secondClick = False 
                                            print "SANJA"
                                            #this turn over reset firstClick and secondClick
                                            firstClick = True
                                            secondClick = False
                                            self.send_move_message(hitting, hitted)
                                        else:
                                            firstClick = True
                                    elif ourField.image2.get_rect(center=ourField.get_centers()[1]).collidepoint(x, y):
                                        print "BUHA1"
                                        print currentPlayer.fingersLeft
                                        
                                        if currentPlayer.fingersLeft == 0 and (currentPlayer.fingersRight== 2 or currentPlayer.fingersRight == 4):                                       
                                            print "SANJA"
                                            hitted = 'separation'
                                            secondClick = False 
                                            #this turn over reset firstClick and secondClick
                                            firstClick = True
                                            secondClick = False
                                            self.send_move_message(hitting, hitted)
                                        else:
                                            firstClick = True
                                    
                                    
                                                                
                       
                #write text on screen
                myfont = pygame.font.SysFont("Comic Sans MS", 20)
                winnerFont = pygame.font.SysFont("Comic Sans MS", 36)
                #refresh screen
                self.screen.fill((0, 0, 0))
                
                if self.game.gameOver == 'true':
                    if not self.all_out():
                        labelWinner = winnerFont.render("**** Game over ****", 1, white)
                        labelWinner2 = winnerFont.render("**** somebody left :( *****", 1, white)
                    else:
                        labelWinner = winnerFont.render("*****Winner is " + self.return_winner_name() + " *****", 1, white)
                        labelWinner2 = winnerFont.render(" ", 1, white)
                    self.screen.blit(labelWinner, (180, 220))
                    self.screen.blit(labelWinner2, (180, 250))
                label1 = myfont.render("You: " + self.game.playersList[self.game.ourIndex].playerName, 1, white)
                label2 = myfont.render("Players turn: " + self.game.playersList[self.game.find_index(self.game.playerTurn)].playerName, 1, white)
                
                #add text
                self.screen.blit(label1, (40, 450))
                self.screen.blit(label2, (40, 480))       
                #draw hands         
                self.game.draw_state(self.screen)
                pygame.display.flip()
                
        except:
            traceback.print_exc()
            
    
    def all_out(self):
        '''
        checks if only one player
        is left in game
        '''
        return len([x for x in self.game.playersList if x.isOut == 'false']) == 1
    
    def return_winner_name(self):
        '''
        returns winers name
        '''
        return next(x.playerName for x in self.game.playersList if x.isOut == 'false')
    
    def send_move_message(self,hitting,hitted):
        '''
        creates and sends move message
        based on hitting and hitted hands
        '''
        xmlroot = etree.Element("Move")
        etree.SubElement(xmlroot, "playerPlayed").text = str(self.game.playerTurn)
        etree.SubElement(xmlroot, "hittingHand").text = hitting
        etree.SubElement(xmlroot, "hittedHand").text = hitted
        print etree.tostring(xmlroot)
        self.client.send_message(etree.tostring(xmlroot))
        
    def process_message(self):
        '''
        
        Recieve xml data as parameter and calls appropriate methods 
        for specific type of messges
        '''
                
        messageType = self.root.tag
        
        if messageType == "ChatMessage":
            self.messageDispley.insert(END,self.root[0].text+'\n')
            # if game is full we receive message and set shared object canJoin to false 
            if self.root[0].text.startswith('Unable to join'):
                print "SANJA"
                self.canJoin = False
                #unable to join massage processed so enable joinEvent, 
                self.joinEvent.set()
                
            #trying to start game ****TO BE CHANGED***
            if self.root[0].text.startswith('Start game'):
                self.game = None
                self.gameThread = thread.start_new_thread(self.start_game, (2,))
                
        elif messageType == "ListOfGames":
            #****Mora posebna metoda koja nema parametre jedino tako radi***
            self.list_all_games(self.gameList)
        elif messageType == "ListOfPlayers":
            
            self.list_all_games(self.playersList)
            #if there is more then tow players in game enable startGameButton
            if len(self.playersList.get(0, END)) > 1:
                self.startGameButton.config(state=NORMAL)
         
        elif messageType == "GameState":
            if self.initialGameState:
                self.gameStateEvent.clear()
                self.game = GameState(self.root,self.client.comSocket.getsockname()[1])
                self.gameStateEvent.set()
                self.initialGameState = False
            else:
               
                self.game.changeGameState(self.root)
                print str(self.game.playersList[self.game.ourIndex].fingersRight) + '->' + self.game.playersList[self.game.ourIndex].playerName
                
            
        else:
            print "Error while processing massages"
        
    def list_all_games(self,listBox):
        '''
        Reads all <game> elements from xml
        and shows them in gameList listbox
        '''
        #******Ovov nekad radi nekad ne*********
        lis = []
        print self.root[0]
        for el in iter(self.root[0]):
            lis.append(el.text)
        
        listBox.delete(0, END)
        for e in lis:
            #t = e.text
            listBox.insert(END,e)
        
    
    def receive_server_messages(self,id):
        '''
        receives messages while main thread is running
        
        '''
        
        #event must be defined here because in process_message we 
        # create another event for every message, no good.
        self.gameStateEvent = threading.Event()
        #creating event for disabling thread while event is not set
        self.joinEvent = threading.Event()
        
        self.initialGameState = True
        
        while not self.end:
            try:
                mes = self.client.comSocket.recv(1024)
                # http://lxml.de/tutorial.html
                print mes + '*****'
                self.root = etree.fromstring(mes) 
                
                self.gameStateEvent.clear()
                self.process_message()
                #massage processed so enable joinEvent,
                self.joinEvent.set()
              
                
            except:
                
                traceback.print_exc()
예제 #24
0
파일: gui.py 프로젝트: brownjm/praisetex
class PraiseTexGUI(object):
    """Graphical interface for selecting songs and compiling them"""
    def __init__(self, songdir="songs"):
        # data
        self.songs = []
        self.praisetex = PraiseTex(songdir)
        self.root = Tk()
        
        button_width = 6
        button_padx = "2m"
        button_pady = "1m"
        frame_padx = "3m"
        frame_pady = "2m"
        label_padx = "3m"
        label_pady = "2m"
        listbox_width = 30
        listbox_height = 20
        frame_title_font = ("TkDefaultFont", 14)
        text_font = ("TkDefaultFont", 12)
        menu_font = ("TkDefaultFont", 12)
        button_font = ("TkDefaultFont", 12)

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

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

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

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

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

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

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

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

        self.refreshSongList()

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

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

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

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

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

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


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


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

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

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

    def updateStatus(self, message):
        """Update the status bar"""
        self.status.config(text=message)
예제 #25
0
class GUI(Frame):
    # In intialize the object, taking in the parent as in input parameter
    def __init__(self, parent):
        Frame.__init__(self, parent)
        # Initialize the api
        self.api = API()
        # Set the ip and port to communicate with the master server
        self.SERVER_IP = config.masterip
        self.SERVER_PORT = config.port
        # Set the initial server status to 0, will change to 1 if server is active
        # self.serverStatus = 0
        # Declare a list which will hold the files that have been flagged for deletion
        self.toDelete = []

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            # Update the toDelete list
            self.toDelete = temp

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

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

        except Exception as e:
            raise e

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

    # An exit function that quits the UI (any additional clean up pre-close should go in here)
    def exitProgram(self):
        self.quit()
예제 #26
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()
예제 #27
0
class AttributesDialog(Toplevel):
    """
    Dialog window for creating and assigning attributes to objects
    :param root: The parent frame
    :param shape: The ShapeManager being edited
    """
    def __init__(self, root, shape):
        """
        Initialize root tkinter window and master GUI window
        """
        Toplevel.__init__(self, root, width=200, height=200)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def close(self):
        """
        Closes window
        """
        logger.info('Closing window')
        self.destroy()
예제 #28
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()
예제 #29
0
class GUI:
	def __init__(self, master):
		self.master = master
		self.conf = Config()
		self.student_list = None
		self.save_filetype = StringVar()
		self.save_filetype.set('.txt')
		self.selected_section = StringVar()
		self.selected_section.set('ENGR 102 01')
		self.week = StringVar()
		self.week.set('42')
		self.student_listbox_contents = []
		self.attended_students = []

		# Set title
		master.title(self.conf.TITLE)

		# Header Label
		self.header_label_text = StringVar()
		self.header_label_text.set(self.conf.PROG_NAME)
		self.header_label = Label(master, textvariable=self.header_label_text, font=('Arial', 25))

		# File Import Label
		self.file_label_text = StringVar()
		self.file_label_text.set("Select student list Excel file:")
		self.file_label = Label(master, textvariable=self.file_label_text, font=('Arial', 15, 'bold'))

		# File Import Button
		self.file_button = Button(master, text="Import List", command=self.select_list)


		self.header_label.grid(row=0, column=1, columnspan=4, sticky=W+E)
		self.file_label.grid(row=1, column=0, columnspan=2, sticky=W)
		self.file_button.grid(row=1, column=2, columnspan=1, sticky=W+E)
		#self.reset_button.grid(row=3, column=1)
		self.render_student_listbox()
		self.render_attended_students_listbox()
		self.render_section_combobox()
		self.render_add_remove()
		self.render_export_section()

	def render_student_listbox(self):
		self.student_listbox_contents = []
		# Students Label
		self.student_label = Label(self.master, text="Select a Student:", font=('Arial', 15, 'bold'))

		# Students Listbox
		self.students_listbox = Listbox(self.master,
										selectmode=MULTIPLE,
										height=10)
		selected_section = self.selected_section.get()
		if self.student_list != None:
			for i,s in enumerate(self.student_list.students):
				if s.section == selected_section:
					self.students_listbox.insert(i, str(s))
					self.student_listbox_contents.append(s)
		self.student_label.grid(row=2, column=0, columnspan=1, sticky=W)
		self.students_listbox.grid(row=3, rowspan=13, column=0, columnspan=2, sticky=W+E)

	def render_attended_students_listbox(self):
		# Attended Students Label
		self.attended_students_label = Label(self.master, text="Attended Students:", font=('Arial', 15, 'bold'))
		
		# Attended Students Listbox
		self.attended_students_listbox = Listbox(self.master,
												 selectmode=MULTIPLE,
												 height=10,
												 width=20)
		for i,s in enumerate(self.attended_students):
			self.attended_students_listbox.insert(i, str(s))
		self.attended_students_label.grid(row=2, column=3, sticky=W)
		self.attended_students_listbox.grid(row=3, rowspan=13, column=3, columnspan=7, sticky=W+E)
			

	def render_section_combobox(self):
		sections = self.student_list.sections if self.student_list != None else []
		self.section_label = Label(self.master, text="Section:", font=('Arial', 15, 'bold'))
		self.section_combobox = ttk.Combobox(self.master,
											 textvariable=self.selected_section,
											 values=sections)
		self.section_combobox.bind("<<ComboboxSelected>>", self.sectionchange)
		self.section_label.grid(row=2, column=2)
		self.section_combobox.grid(row=3, column=2, sticky=W+E+N+S)

	def render_add_remove(self):
		self.add_button = Button(self.master, text="Add ->", command=self.add_students)
		self.remove_button = Button(self.master, text="<- Remove", command=self.remove_students)

		self.add_button.grid(row=4, column=2, sticky=W+E+N+S)
		self.remove_button.grid(row=5, column=2, sticky=W+E+N+S)

	def render_export_section(self):
		self.filetype_label = Label(self.master, text="Please select file type:", font=('Arial', 13, 'bold'))
		self.filetype_combobox = ttk.Combobox(self.master,
											  height=3,
											  textvariable=self.save_filetype,
											  values=['.xls', '.csv', '.txt'])
		self.filetype_combobox.bind("<<ComboboxSelected>>", self.save_filetype_change)
		self.week_label = Label(self.master, text="Please enter week:", font=('Arial', 13, 'bold'))
		self.week_entry = Entry(self.master, textvariable=self.week)
		self.export_button = Button(self.master, text="Export as File", command=self.export_list)

		self.filetype_label.grid(row=18, column=0, sticky=W)
		self.filetype_combobox.grid(row=18, column=1, sticky=E)
		self.week_label.grid(row=18, column=2)
		self.week_entry.grid(row=18, column=3, sticky=W+E)
		self.export_button.grid(row=18, column=4, sticky=W+E)


	def start(self):
		self.master.mainloop()

	def add_students(self):
		ixs = self.students_listbox.curselection()
		for i in ixs:
			self.attended_students.append(self.student_listbox_contents[i])
		self.attended_students = list(set(self.attended_students))
		self.render_attended_students_listbox()
		self.students_listbox.selection_clear(0, END)

	def remove_students(self):
		ixs = list(self.attended_students_listbox.curselection())
		ixs.reverse()
		for i in ixs:
			del self.attended_students[i]
		self.render_attended_students_listbox()

	def export_list(self):
		save_filename = "{}{}{}".format(self.selected_section.get(), self.week.get(), self.save_filetype.get())
		if self.save_filetype.get() == '.txt':
			try:
				with open(save_filename, 'w') as fd:
					for i,s in enumerate(self.attended_students):
						fd.write("{}\t{}\t{}\n".format(s.id, s.name, s.dept))
				fd.close()
			except:
				print("Unable to open file.")
		elif self.save_filetype.get() == '.xls':
			book = xlwt.Workbook()
			sheet = book.add_sheet('Sheet 1')
			sheet.write(0, 0, 'Id')
			sheet.write(0, 1, 'Name')
			sheet.write(0, 2, 'Dept.')
			for i,s in enumerate(self.attended_students):
				sheet.write(i+1, 0, s.id)
				sheet.write(i+1, 1, s.name_unicode)
				sheet.write(i+1, 2, s.dept)
			book.save(save_filename)
		else:
			raise BaseException('Filetype is not supported.')

	def select_list(self):
		self.list_file = tkFileDialog.askopenfilename(initialdir="~",
													  title="Import List",
													  filetypes = (("Excel Files","*.xls*"),("all files","*.*")))
		if self.list_file:
			self.student_list = Studentlist(self.list_file)
			self.render_student_listbox()
			self.render_attended_students_listbox()
			self.render_section_combobox()
			self.render_add_remove()
			self.render_export_section()

	def sectionchange(self, event):
		self.selected_section.set(self.section_combobox.get())
		self.attended_students = []
		self.render_student_listbox()
		self.render_attended_students_listbox()

	def save_filetype_change(self, event):
		self.save_filetype.set(self.filetype_combobox.get())
예제 #30
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()
예제 #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)
예제 #32
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'
예제 #33
0
class TkApp:
    def __init__(self, ncffile, options):
        try:
            from Tkinter import Checkbutton, Frame, Label, Scrollbar
            from Tkinter import Listbox, Button, IntVar, Tk, VERTICAL
            from Tkinter import EXTENDED, END, N, S, SINGLE, Entry
            from Tkinter import StringVar, Text, DISABLED, LEFT
        except Exception:
            try:
                from tkinter import Checkbutton, Frame, Label, Scrollbar
                from tkinter import Listbox, Button, IntVar, Tk, VERTICAL
                from tkinter import EXTENDED, END, N, S, SINGLE, Entry
                from tkinter import StringVar, Text, DISABLED, LEFT
            except Exception:
                warn('tkinter unavailable')

        master = self.root = Tk()
        self.ncffile = ncffile
        self.options = options
        self.plotted_variables = set()
        frame = Frame(master)
        frame.grid(row=0)
        codeframe = Frame(master)
        codeframe.grid(row=1)
        metaframe = Frame(master)
        metaframe.grid(row=2)
        goframe = Frame(frame)
        goframe.grid(column=3, row=1)

        var_label = Label(frame, text='Select Variable')
        var_label.grid(column=0, row=0)
        var_scrollbar = Scrollbar(frame, orient=VERTICAL)
        var_scrollbar.grid(column=1, row=1, sticky=N + S)
        self.var = Listbox(frame, selectmode=EXTENDED,
                           exportselection=0,
                           yscrollcommand=var_scrollbar.set)
        self.var.grid(column=0, row=1)
        var_scrollbar.config(command=self.var.yview)

        what_to_do = Label(frame, text='Execute')
        what_to_do.grid(column=2, row=0)
        self.method_list = Listbox(frame, selectmode=SINGLE, exportselection=0)
        self.method_list.grid(column=2, row=1)
        self.pre_txt = StringVar()
        pre_label = Label(codeframe, text='Before any figures, execute code')
        self.pre_txt.set(_pre_code)
        pre_label.grid(row=2, sticky='W')
        self.pre = Entry(codeframe, width=120, textvariable=self.pre_txt)
        self.pre.grid(row=3, sticky='E')

        self.before_txt = StringVar()
        self.before_txt.set(_before_code)
        before_label = Label(
            codeframe, text='Before each figure, execute code')
        before_label.grid(row=4, sticky='W')
        self.before = Entry(codeframe, width=120, textvariable=self.before_txt)
        self.before.grid(row=5, sticky='E')

        self.after_txt = StringVar()
        self.after_txt.set(_after_code)
        after_label = Label(codeframe, text='After each figure, execute code')
        after_label.grid(row=6, sticky='W')
        self.after = Entry(codeframe, width=120, textvariable=self.after_txt)
        self.after.grid(row=7, sticky='E')

        self.post_txt = StringVar()
        self.post_txt.set(_post_code)
        post_label = Label(codeframe, text='After all figures, execute code')
        post_label.grid(row=8, sticky='W')
        self.post = Entry(codeframe, width=120, textvariable=self.post_txt)
        self.post.grid(row=9, sticky='E')

        options_label = Label(goframe, text='Options:')
        options_label.grid(column=0, row=1, sticky='W')
        self.logscale = IntVar()
        self.logscale.set(0)
        c = Checkbutton(goframe, text="log-scale?", variable=self.logscale)
        c.grid(column=0, row=2, sticky='W')

        self.coastlines = IntVar()
        self.coastlines.set(_coastlines_opt)
        coastlines = Checkbutton(
            goframe, text="coastlines?", variable=self.coastlines,
            justify=LEFT)
        coastlines.grid(column=0, row=3, sticky='W')

        self.countries = IntVar()
        self.countries.set(_countries_opt)
        countries = Checkbutton(
            goframe, text="countries?", variable=self.countries, justify=LEFT)
        countries.grid(column=0, row=4, sticky='W')

        self.states = IntVar()
        self.states.set(_states_opt)
        states = Checkbutton(goframe, text="states?",
                             variable=self.states, justify=LEFT)
        states.grid(column=0, row=5, sticky='W')

        self.counties = IntVar()
        self.counties.set(_counties_opt)
        counties = Checkbutton(goframe, text="counties?",
                               variable=self.counties, justify=LEFT)
        counties.grid(column=0, row=6, sticky='W')

        self.execute_button = Button(
            goframe, text="Make Figure", command=self.execute)
        self.execute_button.grid(row=0, column=0, sticky='W')

        self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat',
                        'profile', 'timeseries', 'pressx', 'tileplot', 'plot']
        method_labels = ['lat-lon', 'press-lat', 'press-lon', 'time-lat',
                         'Vertical Profile', 'Time Series', 'press-? (2-D)',
                         'Tile Plot (2-D)', 'Plot (1-D)']
        for method in method_labels:
            self.method_list.insert(END, method)
        var_keys = [k for k, v in self.ncffile.variables.items()
                    if k not in _coordkeys]
        var_keys.sort()
        self.vars = []
        for spc in var_keys:
            self.var.insert(END, spc)
            self.vars.append(spc)

        meta_label = Label(metaframe, text='Common Data Language Header:')
        meta_label.grid(column=0, row=0, sticky='W')
        meta_scrollbar = Scrollbar(metaframe, orient=VERTICAL)
        meta_scrollbar.grid(column=1, row=1, sticky=N + S)
        self.meta = Text(metaframe, height=10, width=118, bg='white',
                         relief='flat', yscrollcommand=meta_scrollbar.set)
        self.meta.grid(column=0, row=1, sticky='W')
        from PseudoNetCDF.pncdump import pncdump
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        pdump = StringIO("")
        pncdump(self.ncffile, header=True, outfile=pdump, )
        pdump.seek(0, 0)
        self.meta.insert(END, pdump.read())
        self.meta.config(state=DISABLED)
        help = Button(goframe, text='Help', command=self.help)
        help.grid(column=0, row=7)
        quit = Button(goframe, text='Quit', command=self.quit)
        quit.grid(column=0, row=8)
        master.mainloop()

    def help(self):
        print("pl is pylab: details at matplotlib;")

    def quit(self):
        self.root.destroy()

    def _get_var(self, list):
        items = list.curselection()
        try:
            items = map(int, items)
        except Exception:
            pass
        items = [self.vars[i] for i in items]
        return items

    def get_var(self):
        return self._get_var(self.var)

    def get_methods(self):
        items = self.method_list.curselection()
        try:
            items = map(int, items)
        except Exception:
            pass
        items = [self.methods[i] for i in items]
        return items

    def execute(self):
        os.system('clear')
        vars = self.get_var()
        self.plotted_variables = self.plotted_variables.union(vars)
        methods, = self.get_methods()
        self.options.logscale = bool(self.logscale.get())
        self.options.coastlines = bool(self.coastlines.get())
        self.options.countries = bool(self.countries.get())
        self.options.states = bool(self.states.get())
        self.options.counties = bool(self.counties.get())
        self.options.pre_txt = self.pre_txt.get()
        self.options.before_txt = self.before_txt.get()
        self.options.after_txt = self.after_txt.get()
        self.options.post_txt = self.post_txt.get()
        plotwithopts(self.ncffile, methods, vars, self.options)
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))
예제 #35
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"
예제 #36
0
class TrackSelect(tkSimpleDialog.Dialog):

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

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

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

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

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

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

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

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

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

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

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

        box.pack()
예제 #37
0
class ConditionalsEditor:
    def __init__(self, my_window, conditionals, close_callback):
        #Tk.__init__(self)
        self.my_window = my_window
        self.my_window.title("Condition Editor")
        self.close_callback = close_callback
        self.conditionals = conditionals

        shared_pad_x = 3
        shared_pad_y = 3

        main_frame = Frame(self.my_window)
        main_frame.grid(column=0, row=0, sticky=(N, W, E, S))
        image_path = "images"
        image_files = [
            f for f in os.listdir(image_path) if
            os.path.isfile(os.path.join(image_path, f)) and f.endswith(".png")
        ]
        self.icons = {}
        for image_file in image_files:
            self.icons[os.path.splitext(
                os.path.basename(image_file))[0]] = PhotoImage(
                    file=os.path.join(image_path, image_file))

        up_down_button_frame = Frame(main_frame)

        self.up_button = Button(up_down_button_frame,
                                state="disabled",
                                text="Move up",
                                image=self.icons["gtk-go-up"],
                                command=self.up_pressed)
        self.up_button.grid(column=0, row=0, sticky=(E))

        self.down_button = Button(up_down_button_frame,
                                  state="disabled",
                                  text="Move down",
                                  image=self.icons["gtk-go-down"],
                                  command=self.down_pressed)
        self.down_button.grid(column=0, row=1, sticky=(E))

        up_down_button_frame.grid(column=0, row=0, sticky=(E))

        condition_list = Frame(main_frame, relief=SUNKEN, borderwidth=1)
        condition_list.grid(column=1,
                            row=0,
                            sticky=(N, S, E, W),
                            padx=shared_pad_x,
                            pady=shared_pad_y,
                            columnspan=1)
        self.condition_list_scrollbar = Scrollbar(condition_list)

        self.state_listbox = Listbox(condition_list,
                                     relief=FLAT,
                                     exportselection=False,
                                     borderwidth=0,
                                     highlightthickness=0,
                                     yscrollcommand=self.state_listbox_scroll,
                                     activestyle="none")
        self.state_listbox.grid(column=0, row=0, padx=0, sticky=(N, S))
        self.state_listbox.bind("<<ListboxSelect>>",
                                self.state_listbox_selected)

        self.condition_listbox = Listbox(
            condition_list,
            relief=FLAT,
            exportselection=False,
            borderwidth=0,
            highlightthickness=0,
            yscrollcommand=self.condition_listbox_scroll,
            activestyle="none")
        self.condition_listbox.grid(column=1,
                                    row=0,
                                    sticky=(N, S, E, W),
                                    padx=0)
        self.condition_listbox.bind("<<ListboxSelect>>",
                                    self.condition_listbox_selected)

        self.execution_target_listbox = Listbox(
            condition_list,
            relief=FLAT,
            exportselection=False,
            borderwidth=0,
            highlightthickness=0,
            yscrollcommand=self.execution_target_listbox_scroll,
            activestyle="none")
        self.execution_target_listbox.grid(column=2,
                                           row=0,
                                           padx=0,
                                           sticky=(N, S))
        self.execution_target_listbox.bind(
            "<<ListboxSelect>>", self.execution_target_listbox_selected)

        self.condition_list_scrollbar.grid(column=3, row=0, sticky=(N, S))
        self.condition_list_scrollbar.config(
            command=self.condition_list_scrollbar_callback)
        condition_list.grid_rowconfigure(0, weight=1)

        for conditional in self.conditionals:
            self.state_listbox.insert(END, conditional[0])
            self.condition_listbox.insert(END, conditional[1])
            self.execution_target_listbox.insert(END, conditional[2])
        #for i in range(5):
        #    self.state_listbox.insert(END, "Foo %d"%i)
        #    self.condition_listbox.insert(END, "Bar %d"%i)
        #    self.execution_target_listbox.insert(END, "Baz %d"%i)

        if_label = Label(main_frame, text="If:", padx=10)
        if_label.grid(column=0, row=1, sticky=(N, E))
        self.if_text_variable = StringVar()
        if_entry = Entry(main_frame, textvariable=self.if_text_variable)
        if_entry.grid(
            column=1,
            row=1,
            sticky=(E, W),
            padx=shared_pad_x,
            pady=shared_pad_y,
        )

        then_label = Label(main_frame, text="Then:", padx=10)
        then_label.grid(column=0, row=2, sticky=(N, E))
        self.then_entry = Text(main_frame)
        self.then_entry.grid(
            column=1,
            row=2,
            sticky=(N, S, E, W),
            padx=shared_pad_x,
            rowspan=2,
        )

        option_frame = Frame(main_frame)
        execution_target_label = Label(option_frame, text="Execution target:")
        execution_target_label.grid(column=0,
                                    row=0,
                                    sticky=(N, W),
                                    pady=(10, shared_pad_y))
        self.execution_target = StringVar()
        self.execution_target.set("Debugger")
        debugger_radiobutton = Radiobutton(option_frame,
                                           text="Debugger",
                                           variable=self.execution_target,
                                           value="Debugger")
        debugger_radiobutton.grid(column=0, row=1, sticky=(N, W))
        python_radiobutton = Radiobutton(option_frame,
                                         text="Python",
                                         variable=self.execution_target,
                                         value="Python")
        python_radiobutton.grid(column=0, row=2, sticky=(N, W))
        state_label = Label(option_frame, text="State")
        state_label.grid(column=0,
                         row=3,
                         sticky=(N, W),
                         pady=(10, shared_pad_y))

        self.active_checkbutton = StringVar()
        self.active_checkbutton.set("Enabled")
        active_checkbutton = Checkbutton(option_frame,
                                         text="Enabled",
                                         variable=self.active_checkbutton,
                                         onvalue="Enabled",
                                         offvalue="Disabled")
        active_checkbutton.grid(column=0, row=4, sticky=(N, W))
        option_frame.grid(column=0, row=3, sticky=(N, S, E, W), pady=5)

        button_frame = Frame(main_frame)
        self.add_button = Button(button_frame,
                                 state="disabled",
                                 text="Add",
                                 image=self.icons["gtk-add"],
                                 compound=LEFT)
        self.add_button.grid(column=0, row=0, sticky=(E))
        self.update_button = Button(button_frame,
                                    state="disabled",
                                    text="Update",
                                    image=self.icons["gtk-edit"],
                                    compound=LEFT)
        self.update_button.grid(column=1, row=0, sticky=(E))
        self.delete_button = Button(button_frame,
                                    state="disabled",
                                    text="Delete",
                                    image=self.icons["gtk-remove"],
                                    compound=LEFT)
        self.delete_button.grid(column=2, row=0, sticky=(E))
        button_frame.grid(column=0,
                          row=4,
                          columnspan=2,
                          sticky=(E),
                          padx=shared_pad_x,
                          pady=shared_pad_y)

        close_frame = Frame(main_frame)
        close_button = Button(close_frame,
                              text="Close",
                              image=self.icons["gtk-close"],
                              compound=LEFT,
                              command=self.on_closing)
        close_button.grid(column=0, row=0, sticky=(S, E))
        close_frame.grid(column=0,
                         row=5,
                         columnspan=2,
                         sticky=(S, E),
                         padx=shared_pad_x,
                         pady=(15, shared_pad_y))

        self.my_window.grid_columnconfigure(0, weight=1)
        self.my_window.grid_rowconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)
        main_frame.grid_rowconfigure(2, weight=0)
        main_frame.grid_rowconfigure(3, weight=1)
        main_frame.grid_rowconfigure(4, weight=1)
        main_frame.grid_rowconfigure(5, weight=1)
        condition_list.grid_columnconfigure(1, weight=1)
        button_frame.grid_rowconfigure(0, weight=1)

        self.my_window.protocol("WM_DELETE_WINDOW", self.on_closing)

    def on_closing(self):
        if self.close_callback is not None:
            self.close_callback()
        self.my_window.destroy()

    def up_pressed(self):
        index = self.state_listbox.curselection()[0]
        state_current = self.state_listbox.get(index)
        condition_current = self.condition_listbox.get(index)
        execution_target_current = self.execution_target_listbox.get(index)
        self.state_listbox.delete(index)
        self.condition_listbox.delete(index)
        self.execution_target_listbox.delete(index)
        self.state_listbox.insert(index - 1, state_current)
        self.condition_listbox.insert(index - 1, condition_current)
        self.execution_target_listbox.insert(index - 1,
                                             execution_target_current)

        self.conditionals.insert(index - 1, self.conditionals.pop(index))

        self.state_listbox.selection_set(index - 1)
        self.condition_listbox.selection_set(index - 1)
        self.execution_target_listbox.selection_set(index - 1)
        self.state_listbox.see(index - 1)

        if index - 1 == 0:
            self.up_button.config(state="disabled")
        self.down_button.config(state="normal")

    def down_pressed(self):
        index = self.state_listbox.curselection()[0]
        state_current = self.state_listbox.get(index)
        condition_current = self.condition_listbox.get(index)
        execution_target_current = self.execution_target_listbox.get(index)
        self.state_listbox.delete(index)
        self.condition_listbox.delete(index)
        self.execution_target_listbox.delete(index)
        self.state_listbox.insert(index + 1, state_current)
        self.condition_listbox.insert(index + 1, condition_current)
        self.execution_target_listbox.insert(index + 1,
                                             execution_target_current)

        self.conditionals.insert(index + 1, self.conditionals.pop(index))

        self.state_listbox.selection_set(index + 1)
        self.condition_listbox.selection_set(index + 1)
        self.execution_target_listbox.selection_set(index + 1)
        self.state_listbox.see(index + 1)

        if index + 1 == self.state_listbox.size() - 1:
            self.down_button.config(state="disabled")
        self.up_button.config(state="normal")

    def condition_list_scrollbar_callback(self, *args):
        self.state_listbox.yview(*args)
        self.condition_listbox.yview(*args)
        self.execution_target_listbox.yview(*args)

    def state_listbox_scroll(self, *args):
        self.condition_listbox.yview_moveto(args[0])
        self.execution_target_listbox.yview_moveto(args[0])
        self.condition_list_scrollbar.set(*args)

    def condition_listbox_scroll(self, *args):
        self.state_listbox.yview_moveto(args[0])
        self.execution_target_listbox.yview_moveto(args[0])

    def execution_target_listbox_scroll(self, *args):
        self.state_listbox.yview_moveto(args[0])
        self.condition_listbox.yview_moveto(args[0])

    def any_listbox_selected(self):
        self.up_button.config(state="normal")
        self.down_button.config(state="normal")
        if self.state_listbox.curselection(
        )[0] == self.state_listbox.size() - 1:
            self.down_button.config(state="disabled")
        if self.state_listbox.curselection()[0] == 0:
            self.up_button.config(state="disabled")
        self.delete_button.config(state="normal")
        self.then_entry.delete("1.0", END)
        self.then_entry.insert(
            END, self.conditionals[self.state_listbox.curselection()[0]][3])
        self.if_text_variable.set(
            self.conditionals[self.state_listbox.curselection()[0]][1])

        self.execution_target.set(
            self.conditionals[self.state_listbox.curselection()[0]][2])

        self.active_checkbutton.set(
            self.conditionals[self.state_listbox.curselection()[0]][0])

    def state_listbox_selected(self, event):
        index = self.state_listbox.curselection()[0]
        try:
            self.condition_listbox.selection_clear(
                self.condition_listbox.curselection()[0])
        except IndexError:
            pass
        self.condition_listbox.selection_set(index)
        try:
            self.execution_target_listbox.selection_clear(
                self.execution_target_listbox.curselection()[0])
        except IndexError:
            pass
        self.execution_target_listbox.selection_set(index)
        self.any_listbox_selected()

    def condition_listbox_selected(self, event):
        index = self.condition_listbox.curselection()[0]
        try:
            self.state_listbox.selection_clear(
                self.state_listbox.curselection()[0])
        except IndexError:
            pass
        self.state_listbox.selection_set(index)
        try:
            self.execution_target_listbox.selection_clear(
                self.execution_target_listbox.curselection()[0])
        except IndexError:
            pass
        self.execution_target_listbox.selection_set(index)
        self.any_listbox_selected()

    def execution_target_listbox_selected(self, event):
        index = self.execution_target_listbox.curselection()[0]
        try:
            self.state_listbox.selection_clear(
                self.state_listbox.curselection()[0])
        except IndexError:
            pass
        self.state_listbox.selection_set(index)
        try:
            self.condition_listbox.selection_clear(
                self.condition_listbox.curselection()[0])
        except IndexError:
            pass
        self.condition_listbox.selection_set(index)
        self.any_listbox_selected()
예제 #38
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)
예제 #39
0
 def curselection(self):
     """Return list of indices of currently selected items."""
     return [int(index) for index in Listbox.curselection(self)]
예제 #40
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)
예제 #41
0
class App:
    ########################################################################
    ####################################Interface for PlaNet:
    def __init__(self, master):
        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        analyzemenu = Menu(menu)
        PostAnalysis = Menu(menu)
        Settings = Menu(menu)
        About = Menu(menu)

        menu.add_cascade(label="Start", menu=filemenu)
        filemenu.add_command(label="Select genes for analysis",
                             command=self.SearchGene)
        menu.add_cascade(label="Analyze", menu=analyzemenu)
        analyzemenu.add_command(label="Display probeset specific report",
                                command=self.nvnReport)
        analyzemenu.add_command(
            label="NetworkComparer Step I: Find similar co-expression networks",
            command=self.netComparer)
        analyzemenu.add_command(
            label="NetworkComparer Step II: Extract ancestral network",
            command=self.ancestranNetPipe)
        menu.add_cascade(label="Change organism/database",
                         command=self.UseDatabaseFile)
        menu.add_cascade(label="Help", menu=About)
        About.add_command(label="About GeneCAT", command=self.About)

        self.messenger = Text(root, font=("Courier", 10), wrap=NONE)
        self.printer("Stand alone version of PlaNet\n")
        button = Button(root, text="Clear", fg="red", command=self.clear)
        self.LabVar = StringVar()
        DBLabel = Label(root, relief=SUNKEN, textvariable=self.LabVar)

        ybar = Scrollbar(root)
        xbar = Scrollbar(root, orient=HORIZONTAL)
        DBLabel.pack(side=BOTTOM, anchor=NW)
        button.pack(side=BOTTOM, anchor=E)
        ybar.pack(side=RIGHT, fill=Y)
        xbar.pack(side=BOTTOM, fill=X)
        self.messenger.pack(expand=1, fill=BOTH)
        self.messenger.config(yscrollcommand=ybar.set)
        self.messenger.config(xscrollcommand=xbar.set)
        ybar.config(command=self.messenger.yview)
        xbar.config(command=self.messenger.xview)

        config = open('dbconf.txt', 'r').readlines()
        self.queries = []
        try:
            self.currentDB = codecs.open('%s' % (config[0].rstrip()),
                                         mode='r',
                                         encoding='ASCII',
                                         errors='ignore').readlines()
            self.printer(
                "Currently using database: %s consisting of %d probesets and %d chips.\n"
                % (config[0].rstrip(), len(self.currentDB),
                   (len(self.currentDB[0].split()) - 3)))
            self.LabVar.set(
                "Using database: %s, Columns=%d, rows=%d." %
                (config[0].rstrip(), len(
                    self.currentDB[0].split()), len(self.currentDB)))
            nominator = []
            denominator = []
            self.annoDict = {}
            for i in range(len(self.currentDB)):
                temp = []
                splitta = self.currentDB[i].rstrip().split("\t")
                self.annoDict[i] = splitta[
                    0] + "\t" + splitta[1] + "\t" + splitta[2].replace(
                        "*", " ") + "\t" + splitta[3] + "\t"
                for j in range(5, len(splitta)):
                    temp.append(float(splitta[j]))
                expVector = numpy.array(temp)
                nomi = expVector - (numpy.sum(expVector) / len(expVector))
                denomi = numpy.sqrt(numpy.sum(nomi**2))
                nominator.append(nomi)
                denominator.append(denomi)
            self.nominator = numpy.array(nominator)
            self.denominator = numpy.array(denominator)
        except IOError:
            self.printer("Could not open current database.\n")

########################################################################
####################################Start menu items:

    def SearchGene(self):  #interface for "Select genes for analysis"
        SearchFrame = Toplevel()
        SearchFrame.title(
            "Data entry. Enter gene identifier, probesets or keywords.\n")
        scrollBar = Scrollbar(SearchFrame)
        self.inputFrame = Text(SearchFrame,
                               font="courier",
                               width=30,
                               wrap=WORD)
        self.inputFrame.pack(side=LEFT, fill=BOTH)
        scrollBar.pack(side=LEFT, fill=Y)
        self.inputFrame.config(yscrollcommand=scrollBar.set)
        scrollBar.config(command=self.inputFrame.yview)
        goButton = Button(SearchFrame,
                          text="Find",
                          fg="red",
                          command=self.SearchGenePipe)
        goButton.pack(side=BOTTOM)
####################################Searches the current database with user specified keywords

    def SearchGenePipe(self):
        if self.inputFrame.get(1.0, END) != "\n":
            queries = self.inputFrame.get(1.0, END).lower().split()
            foundGenes = []
            for i in queries:
                infos = ""
                for j in self.currentDB:
                    if i in j.lower():
                        splitta = j.split("\t")
                        foundGenes.append(j)
                        infos += splitta[0] + "\t" + splitta[
                            1] + "\t" + splitta[2].replace("*", " ") + "\n"
                self.printer("Probesets found for term: " + i + "\n" + infos +
                             "\n")
            if len(infos) == "":
                self.printer("No hits found.\n")
            else:
                self.queries = foundGenes

########################################################################
####################################Data mining menu items

####################"Display probeset specific report"

    def nvnReport(self):  #interface for "Display probeset specific report"
        top = Toplevel()
        top.title("Co-expression analysis")
        self.genelist = []
        for string in self.queries:
            self.genelist.append(string.split())
        self.listbox = Listbox(top, width=40, height=30, exportselection=0)
        for gene in self.genelist:
            self.listbox.insert(END, gene[0] + '   ' + gene[1])

        DescriptionLabel = LabelFrame(top, text="Info")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list to the left.\nThis tool will generate result.html file containing a page similar to\ngene specific pages in PlaNet."
        )
        DescriptionLabel.grid(row=0, column=2)

        ParametersLabel = LabelFrame(top, text="Parameters")
        Steps = Label(ParametersLabel, text="Number of steps")
        ParametersLabel.grid(row=1, column=2)
        Hrr = Label(ParametersLabel, text="HRR cut-off.")

        self.paraSteps = Entry(ParametersLabel)
        self.paraSteps.grid(row=1)
        self.paraSteps.insert(END, 2)
        self.paraHrr = Entry(ParametersLabel)
        self.paraHrr.grid(row=3)
        self.paraHrr.insert(END, 30)
        Description.grid()
        Steps.grid(row=0)
        Hrr.grid(row=2)
        scrollbar = Scrollbar(top)
        scrollbar.grid(row=0, column=1, rowspan=5, sticky=S + N)
        self.listbox.grid(row=0, column=0, rowspan=5)
        scrollbar.config(command=self.listbox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.nvnReportPipe)
        button.grid(row=6, column=0)

    def nvnReportPipe(
            self):  #Executes functions that generate result.html file
        try:
            steps = int(self.paraSteps.get())
            hrr = int(self.paraHrr.get())
        except:
            self.printer(
                "You need to enter integer values for HRR and step parameters.\n"
            )
        if self.listbox.curselection() != ():
            query = self.genelist[int(self.listbox.curselection()[0])][0]

            #### Plot expression profile function
            try:
                plotDatabase = codecs.open(
                    open('dbconf.txt', 'r').read().rstrip().split(".")[0] +
                    ".plt",
                    mode='r',
                    encoding='ASCII',
                    errors='ignore').readlines()
                ticka = [""] + plotDatabase[0].replace(
                    ",", "\n").lstrip().rstrip().split("\t")
                for i in plotDatabase:
                    if query in i:
                        query = i
                data = query.split()[1:]
                temp = []
                for i in range(len(data)):
                    temp.append([
                        map(float, data[i].replace("-",
                                                   "\t").rstrip().split()),
                        average(
                            map(float, data[i].replace("-",
                                                       "\t").rstrip().split()))
                    ])
                fig = plt.figure(figsize=(12, 7))
                ax = fig.add_subplot(111)
                plt.subplots_adjust(left=0.1, right=0.97, top=0.93, bottom=0.3)
                ax.set_ylabel("Signal value")
                ax.set_title(query.split()[0])
                ax.grid(True)
                plt.xticks(range(len(ticka) + 1),
                           ticka,
                           rotation=90,
                           fontsize="small",
                           horizontalalignment="center")
                ax.plot([0], [0])
                crossX = []
                crossY = []
                for i in range(len(temp)):
                    ax.plot([i + 1] * len(temp[i][0]), temp[i][0], "g.")
                    crossX.append([i + 1])
                    crossY.append(temp[i][1])
                ax.plot(crossX, crossY, "-ro")
                ax.plot([i + 2], [0])
                canvas = FigureCanvasAgg(fig)
                canvas.print_figure("profile.png")
                plt.clf()
            except:
                self.printer(
                    "Failed to generate an expression profile of your gene of interes.\nThe expression matrix used for plotting of expression profiles must be present and named "
                    + open('dbconf.txt', 'r').read().rstrip().split(".")[0] +
                    ".plt!")
            ###Call network creator
            try:
                networkViewer.makeNetwork(query.split()[0], steps, hrr)
            except:
                self.printer(
                    "Failed to generate an co-expression network of your gene of interes.\nThe HRR network file used must be present named "
                    + open('dbconf.txt', 'r').read().rstrip().split(".")[0] +
                    ".hrr!")
            ### Calculate PCC of a gene to all genes in database
            try:
                query = self.queries[int(
                    self.listbox.curselection()[0])].split("\t")
                expVector = map(float, query[5:])
                expVector = numpy.array(expVector)
                nomi = expVector - (numpy.sum(expVector) / len(expVector))
                denomi = numpy.sqrt(numpy.sum(nomi**2))
                rValues = numpy.dot(self.nominator, nomi) / numpy.dot(
                    self.denominator, denomi)
                displayList = []
                for i in range(len(rValues)):
                    displayList.append([rValues[i], self.annoDict[i]])
                displayList.sort(reverse=True)
            except:
                displayList = []
                self.printer(
                    "Failed to calculate Pearson correlation co-efficient list.\n"
                )

            ###Create html document with results
            header = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">\n<html>\n<head>\n<!-- blarg -->\n</head>\n<body>\n'
            try:
                header += '<big><b>Summary page for: %s</b></big>\n<br><b>Expression profile:</b>\n<IMG SRC="profile.png"><br>\n' % (
                    displayList[0][1].split()[0] + "\t" +
                    displayList[0][1].split()[1])
            except:
                pass
            header += '<b>HRR based co-expression network:</b>\nGreen, organge and red edges represent HRR values of %s, %s and %s, respectively.</b><br>\n' % (
                int(hrr) / 3, (int(hrr) / 3) * 2, hrr)
            header += '<embed src="network.svg" width="1200" height="1200" type="image/svg+xml" pluginspage="http://www.adobe.com/svg/viewer/install/" />\n<br>'
            #header += '<iframe src="network.svg" width="1500" height="1500">\n</iframe>\n'
            header += "<br><b>MapMan ontology analysis of the above network:</b>\n"
            try:
                header += open("mapRes.mapman", "r").read()
            except:
                pass
            header += "\n<br><b>Pearson correlation based co-expression analysis:</b>\n<pre>"

            v = open("result.html", "w")
            v.close()
            v = open("result.html", "a")
            v.write(header)
            for i in range(len(self.annoDict)):
                v.write(
                    str(displayList[i][0])[:6] + "\t" + displayList[i][1] +
                    "\n")
            v.write("</pre>")
            v.close()
            self.printer(
                "Probeset specific result calculated and available in result.html file.\n"
            )

####################"NetworkComparer step I:"

    def netComparer(self):  #Interface
        top = Toplevel()
        top.title("NetworkComparer")

        self.genelistNC = []
        for string in self.queries:
            if "No hit" not in string:
                self.genelistNC.append(string.split("\t"))
        DescriptionLabel = LabelFrame(
            top, text="Select the gene of interest and specify parameters.")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list below.\nThis tool will generate netComp.html file containing a page similar to\nfirst step of NetworkComparer."
        )
        DescriptionLabel.grid(row=0, column=0)
        Description.grid(row=0)
        ParametersLabel = LabelFrame(DescriptionLabel, text="Parameters")
        Steps = Label(ParametersLabel, text="Number of steps")
        ParametersLabel.grid(row=1, column=2)
        Hrr = Label(ParametersLabel, text="HRR cut-off.")
        Steps.grid(row=0)
        Hrr.grid(row=2)
        self.paraSteps = Entry(ParametersLabel)
        self.paraSteps.grid(row=1)
        self.paraSteps.insert(END, 2)
        self.paraHrr = Entry(ParametersLabel)
        self.paraHrr.grid(row=3)
        self.paraHrr.insert(END, 30)
        self.listbox = Listbox(DescriptionLabel,
                               width=40,
                               height=30,
                               exportselection=0)
        probeName = []
        for gene in self.genelistNC:
            self.listbox.insert(END,
                                gene[0] + '   ' + gene[1] + '   ' + gene[3])
        self.listbox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarG = Scrollbar(DescriptionLabel)
        scrollbarG.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarG.config(command=self.listbox.yview)

        NetworkLabel = LabelFrame(
            top, text="Select the networks/species you want to compare.")
        Network = Label(
            NetworkLabel,
            text=
            "Available networks are displayed in the list below. Check/uncheck networks of interest."
        )
        NetworkLabel.grid(row=0, column=1)
        Network.grid(row=0)
        self.networkBox = Listbox(NetworkLabel,
                                  width=40,
                                  height=30,
                                  selectmode=MULTIPLE,
                                  exportselection=0)
        self.networkList = []
        for i in os.listdir("."):
            if ".hrr" in i:
                self.networkBox.insert(END, i)
                self.networkList.append(i)
        self.networkBox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarN = Scrollbar(NetworkLabel)
        scrollbarN.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarN.config(command=self.networkBox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.netComparerPipe)
        button.grid(row=1, column=0, columnspan=5, sticky=E + W)

    def netComparerPipe(
        self
    ):  #Passess selected query and networks to networkComparer.start function
        error = 0
        try:
            steps = int(self.paraSteps.get())
        except:
            error += 1
            self.printer(
                "You must enter an integer value bigger than 1 for this parameter.\n"
            )
        try:
            hrr = int(self.paraHrr.get())
        except:
            error += 1
            self.printer(
                "You must enter an integer value bigger than 1 for this parameter.\n"
            )
        netList = []
        for i in self.networkBox.curselection():
            netList.append(self.networkList[int(i)])
        if netList == []:
            error += 1
            self.printer(
                "You must at least select one network for this analysis.\n")
        if error == 0:
            #try:
            networkComparer.start(
                steps, hrr, netList,
                self.genelistNC[int(self.listbox.curselection()[0])][0],
                self.genelistNC[int(self.listbox.curselection()[0])][3])
            self.printer(
                "Calculation done and results are available in NetComp.html file.\n"
            )
        #except:
        #self.printer("Something went wrong. Make sure Graphviz is installed.\n")

####################"NetworkComparer step II:"

    def ancestranNetPipe(self):  #Interface
        top = Toplevel()
        top.title("NetworkComparer")
        a = open("NetComp.html", "r").readlines()
        self.queriesAC = []
        quera = 0
        for i in range(len(a)):
            if "START OF QUERIES" in a[i]:
                self.queryOrder = a[i + 1].rstrip().split()
            if "START OF VS. QUERY" in a[i]:
                quera = 1
            if quera == 1:
                self.queriesAC.append(a[i].rstrip().split("\t"))
        self.queriesAC = self.queriesAC[1:len(self.queriesAC) - 1]
        DescriptionLabel = LabelFrame(
            top, text="Select the gene of interest and specify parameters.")
        Description = Label(
            DescriptionLabel,
            text=
            "Select gene of interest from the list below.\nThis tool will generate netComp.html file containing a page similar to\nfirst step of NetworkComparer."
        )
        DescriptionLabel.grid(row=0, column=0)
        Description.grid(row=0)
        self.listbox = Listbox(DescriptionLabel,
                               width=40,
                               height=30,
                               exportselection=0,
                               selectmode=MULTIPLE)
        for gene in self.queriesAC:
            self.listbox.insert(
                END, gene[0] + '   ' + gene[1] + '   ' + gene[2] + '   ' +
                gene[3] + '   ' + gene[4])
        self.listbox.grid(row=1, column=0, rowspan=5, sticky=N + S + E + W)
        scrollbarG = Scrollbar(DescriptionLabel)
        scrollbarG.grid(row=1, column=1, rowspan=5, sticky=S + N)
        scrollbarG.config(command=self.listbox.yview)
        button = Button(top,
                        text="Calculate!",
                        fg="red",
                        font=("Courier", 22),
                        command=self.ancestralNet)
        button.grid(row=1, column=0, columnspan=5, sticky=E + W)

    def ancestralNet(
        self
    ):  #Passess selected query and networks to ancestralNetwork.start function
        selected = []
        for i in self.listbox.curselection():
            selected.append(self.queryOrder.index(self.queriesAC[int(i)][1]))
        ancestralNetwork.start(selected)


########################################################################
####################################Settings menu items

####################Change database

    def UseDatabaseFile(self):
        database = askopenfilename(filetypes=[("Expression matrix", ".exp")])
        if database != '':
            self.datafile = database.split('/')[len(database.split('/')) - 1]
            configstring = "%s" % self.datafile
            DB = open(self.datafile, 'r').readlines()
            self.LabVar.set(
                "Using database: %s, Columns=%d, rows=%d." %
                (self.datafile.strip(), len(DB[1].split()), len(DB)))
            newconfig = open('dbconf.txt', 'w')
            newconfig.writelines(configstring)
            newconfig.close()
            self.printer("Using %s database\n" % (self.datafile))
            try:
                config = open('dbconf.txt', 'r').readlines()
                self.currentDB = codecs.open('%s' % (config[0].rstrip()),
                                             mode='r',
                                             encoding='ASCII',
                                             errors='ignore').readlines()
                self.printer(
                    "Currently using database: %s consisting of %d probesets and %d chips.\n"
                    % (config[0].rstrip(), len(self.currentDB),
                       (len(self.currentDB[0].split()) - 3)))
                self.LabVar.set(
                    "Using database: %s, Columns=%d, rows=%d." %
                    (config[0].rstrip(), len(
                        self.currentDB[0].split()), len(self.currentDB)))
                nominator = []
                denominator = []
                self.annoDict = {}
                for i in range(len(self.currentDB)):
                    temp = []
                    splitta = self.currentDB[i].rstrip().split("\t")
                    self.annoDict[i] = splitta[
                        0] + "\t" + splitta[1] + "\t" + splitta[2].replace(
                            "*", " ") + "\t" + splitta[3] + "\t"
                    for j in range(5, len(splitta)):
                        temp.append(float(splitta[j]))
                    expVector = numpy.array(temp)
                    nomi = expVector - (numpy.sum(expVector) / len(expVector))
                    denomi = numpy.sqrt(numpy.sum(nomi**2))
                    nominator.append(nomi)
                    denominator.append(denomi)
                self.nominator = numpy.array(nominator)
                self.denominator = numpy.array(denominator)
            except IOError:
                self.printer("Could not open current database.\n")

    def About(self):
        top = Toplevel()
        top.title("PlaNet standalone")
        label = Label(
            top,
            text=
            "PlaNet standalone\nMarek Mutwil\ncontact: [email protected]",
            width=30)
        OkButton = Button(top, text="OK", command=top.destroy)
        label.pack()
        OkButton.pack()

    def printer(self, text):  #prints text to message box
        #self.messenger.delete(1.0, END)
        self.messenger.insert(END, text)

    def clear(self):  #clears message box
        self.messenger.delete(1.0, END)
예제 #42
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"
예제 #43
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']
예제 #44
0
 def curselection(self):
     """Return list of indices of currently selected items."""
     return [int(index) for index in Listbox.curselection(self)]
예제 #45
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)
예제 #46
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"
예제 #47
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()
예제 #48
0
파일: gui.py 프로젝트: 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='')
예제 #49
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_)
예제 #50
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()
예제 #51
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"
예제 #52
0
class TkApp:
    def __init__(self, ncffile, options):
        master = self.root = Tk()
        self.ncffile = ncffile
        self.options = options
        self.plotted_variables = set()
        frame = Frame(master)
        frame.grid(row = 0)
        codeframe = Frame(master)
        codeframe.grid(row = 1)
        metaframe = Frame(master)
        metaframe.grid(row = 2)
        goframe = Frame(frame)
        goframe.grid(column = 3, row = 1)

        var_label = Label(frame, text = 'Select Variable')
        var_label.grid(column = 0, row = 0)
        var_scrollbar = Scrollbar(frame, orient = VERTICAL)
        var_scrollbar.grid(column = 1, row = 1, sticky = N + S)
        self.var = Listbox(frame, selectmode = EXTENDED, exportselection = 0, yscrollcommand = var_scrollbar.set)
        self.var.grid(column = 0, row = 1)
        var_scrollbar.config(command = self.var.yview)

        what_to_do = Label(frame, text = 'Execute')
        what_to_do.grid(column = 2, row = 0)
        self.method_list = Listbox(frame, selectmode = SINGLE, exportselection = 0)
        self.method_list.grid(column = 2, row = 1)
        self.pre_txt = StringVar()
        pre_label = Label(codeframe, text = 'Before any figures, execute code')
        self.pre_txt.set(_pre_code)
        pre_label.grid(row = 2, sticky = 'W')
        self.pre = Entry(codeframe, width = 120, textvariable = self.pre_txt)
        self.pre.grid(row =3, sticky = 'E')

        self.before_txt = StringVar()
        self.before_txt.set(_before_code)
        before_label = Label(codeframe, text = 'Before each figure, execute code')
        before_label.grid(row = 4, sticky = 'W')
        self.before = Entry(codeframe, width = 120, textvariable = self.before_txt)
        self.before.grid(row =5, sticky = 'E')

        self.after_txt = StringVar()
        self.after_txt.set(_after_code)
        after_label = Label(codeframe, text = 'After each figure, execute code')
        after_label.grid(row = 6, sticky = 'W')
        self.after = Entry(codeframe, width = 120, textvariable = self.after_txt)
        self.after.grid(row =7, sticky = 'E')

        self.post_txt = StringVar()
        self.post_txt.set(_post_code) 
        post_label = Label(codeframe, text = 'After all figures, execute code')
        post_label.grid(row = 8, sticky = 'W')
        self.post = Entry(codeframe, width = 120, textvariable = self.post_txt)
        self.post.grid(row = 9, sticky = 'E')

        options_label = Label(goframe, text = 'Options:')
        options_label.grid(column = 0, row = 1, sticky = 'W')
        self.logscale = IntVar()
        self.logscale.set(0)
        c = Checkbutton(goframe, text = "log-scale?", variable = self.logscale)
        c.grid(column = 0, row = 2, sticky = 'W')

        self.coastlines = IntVar()
        self.coastlines.set(_coastlines_opt)
        coastlines = Checkbutton(goframe, text = "coastlines?", variable = self.coastlines, justify = LEFT)
        coastlines.grid(column = 0, row = 3, sticky = 'W')

        self.countries = IntVar()
        self.countries.set(_countries_opt)
        countries = Checkbutton(goframe, text = "countries?", variable = self.countries, justify = LEFT)
        countries.grid(column = 0, row = 4, sticky = 'W')

        self.states = IntVar()
        self.states.set(_states_opt)
        states = Checkbutton(goframe, text = "states?", variable = self.states, justify = LEFT)
        states.grid(column = 0, row = 5, sticky = 'W')

        self.counties = IntVar()
        self.counties.set(_counties_opt)
        counties = Checkbutton(goframe, text = "counties?", variable = self.counties, justify = LEFT)
        counties.grid(column = 0, row = 6, sticky = 'W')

        self.execute_button = Button(goframe, text = "Make Figure", command = self.execute)
        self.execute_button.grid(row = 0, column = 0, sticky = 'W')
                
        self.methods = ['mapplot', 'presslat', 'presslon', 'time-lat', 'profile', 'timeseries', 'pressx', 'tileplot', 'plot']
        method_labels= ['lat-lon', 'press-lat', 'press-lon', 'time-lat', 'Vertical Profile', 'Time Series', 'press-? (2-D)', 'Tile Plot (2-D)', 'Plot (1-D)']
        for method in method_labels:
            self.method_list.insert(END, method)
            
        var_keys = [k for k, v in self.ncffile.variables.items() if k not in ('time', 'latitude', 'longitude', 'latitude_bounds', 'longitude_bounds', 'time_bounds', 'tau0', 'tau1', 'TFLAG')]
        var_keys.sort()
        self.vars = []
        for spc in var_keys:
            self.var.insert(END, spc)
            self.vars.append(spc)

        meta_label = Label(metaframe, text = 'Common Data Language Header:')
        meta_label.grid(column = 0, row = 0, sticky = 'W')
        meta_scrollbar = Scrollbar(metaframe, orient = VERTICAL)
        meta_scrollbar.grid(column = 1, row = 1, sticky = N + S)
        self.meta = Text(metaframe, height=10, width=118, bg='white', relief='flat', yscrollcommand = meta_scrollbar.set)
        self.meta.grid(column = 0, row = 1, sticky = 'W')
        from PseudoNetCDF.pncdump import pncdump
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        pdump = StringIO("")
        try:
            name = ', '.join(options.ifile)
        except:
            name = 'ifile'
        pncdump(self.ncffile, header = True, outfile = pdump, )
        pdump.seek(0, 0)
        self.meta.insert(END, pdump.read())
        self.meta.config(state=DISABLED)
        help = Button(goframe, text = 'Help', command = self.help)
        help.grid(column = 0, row = 7)
        quit = Button(goframe, text = 'Quit', command = self.quit)
        quit.grid(column = 0, row = 8)
        master.mainloop()
   
    def help(self):
        print("pl is pylab: details at matplotlib;")
        
    def quit(self):
        self.root.destroy()

    def _get_var(self, list):
        items = list.curselection()
        try: items = map(int, items)
        except: pass
        items = [self.vars[i] for i in items]
        return items
        
    def get_var(self):
        return self._get_var(self.var)
        
    def get_methods(self):
        items = self.method_list.curselection()
        try: items = map(int, items)
        except: pass
        items = [self.methods[i] for i in items]
        return items
    def execute(self):
        os.system('clear')
        vars = self.get_var()
        self.plotted_variables = self.plotted_variables.union(vars)
        methods, = self.get_methods()
        self.options.logscale = bool(self.logscale.get())
        self.options.coastlines = bool(self.coastlines.get())
        self.options.countries = bool(self.countries.get())
        self.options.states = bool(self.states.get())
        self.options.counties = bool(self.counties.get())
        self.options.pre_txt = self.pre_txt.get()
        self.options.before_txt = self.before_txt.get()
        self.options.after_txt = self.after_txt.get()
        self.options.post_txt = self.post_txt.get()
        plotwithopts(self.ncffile, methods, vars, self.options)
예제 #53
0
class JobList(Frame):
    # NOTE: job_params contains information about a Job in the Joblist
    # NOTE: plot_args contains information about plotting information, which occurs after the jobs have been and the data files have been created

    def __init__(self, parent=None, **kwargs):
        Frame.__init__(self, parent)
        self.parent = parent
        self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL)
        self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL)
        self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll)
        self.job_list_xscroll['command'] = self.job_list.xview
        self.job_list_yscroll['command'] = self.job_list.yview
        self.new_job_frame = Frame(self)
        add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None
        if add_icon_filename == None:
            self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add)
        else:
            add_icon = PhotoImage(file=add_icon_filename)
            self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add)
        self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove)
        self.progress_frame = Frame(self)
        self.progress_value = Tkinter.IntVar()
        self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value)
        self.button_frame = Frame(self)
        self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs)
        self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows)

        self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None

        self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None

        self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None

        self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs)
        self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs)
        self.bind('<<CreatePlotGUI>>', self.create_plot_gui)
        self.parent.bind('<ButtonPress>', self.on_press)
        self.parent.bind('<Configure>', self.on_resize)

        self.reinit_variables()

        self.top_level_windows = list()

        # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized,
        # the resize option will be disabled for this window
        self.parent.resizable(width=False, height=False)

        self.lift()

    def reinit_variables(self):
        self.job_params = dict()

        self.last_job_id = -1

        self.job_outcomes = list()

        self.plot_args = list()

        self.on_button = False

    def add_job_params(self, input_args):
        self.job_params = input_args
        # Add each element to the job list
        for job in self.job_params:
            self.add_job(job)

    def add_job(self, job):
        try:
            index_end = job['input_directory'].rindex('/')
            index_start = job['input_directory'].rindex('/', 0, index_end)
            input_directory_text = job['input_directory']
            list_text = 'Job ' + str(job['job_id']) + ' \'' + input_directory_text + '\''
            if job['start'] != None:
                list_text += ' ' + str(job['start'])
                if job['end'] != None:
                    list_text += ' to'
            if job['end'] != None:
                list_text += ' ' + str(job['end'])

            if job['job_id'] > self.last_job_id:
                self.last_job_id = job['job_id']

            self.job_list.insert(Tkinter.END, list_text)

            # Add the list text to the job params as an optional parameter to read later to display in a future Graph GUI (or for any other useful purpose)
            job['list_text'] = list_text

            # The line number is used wrt the GUI to indicate which job in the job list is being currently executed.
            job['line_number'] = self.job_list.size() - 1
            #print str(job['line_number'])

            self.job_params[job['job_id']] = job
        except KeyError as ke:
            # Should show some error message indicating that there is a problem.
            pass

        #print str(self.job_params)
        #print 'Added Job ' + str(job['job_id'])

    def ask_to_clear_jobs(self, event):
        for job in self.job_params.itervalues():
            line_number = job['line_number']
            self.job_list.itemconfig(line_number, foreground='black')

        # Update parent to refresh widget appearance
        self.parent.update()

        # Reactivate process button
        self.process_button.config(state = Tkinter.NORMAL)

        # Note: Display a pop-up that tells the user that the job is done and asks if the job list should be cleared.

        clearList = msg.askyesno(title='Jobs Finished', message='All jobs have been completed.  Would you like to clear the job list?', master=self)
        if clearList:
            self.clear_list()

    def ask_to_plot_graphs(self, event):
        # TODO: Add a dialog that also asks to create a graph of the 'Other Type Of Plot'
        plotGraphs = msg.askyesno(title='Plot Graphs', message='Create plots of data?', master=self)

        if not plotGraphs:
            return

        # TODO: Iterate through the jobs to display to the user an interface that asks if they want to graphs of the outputs
        if self.create_plots != None:
            output_files_list = list()
            for job_outcome in self.job_outcomes:
                for output_outcomes in job_outcome[2]:
                    (station, output_directory, output_files) = output_outcomes
                    for output_files_tuple in output_files:
                        for output_file_tuple in output_files_tuple:
                            (output_file, output_file_success) = output_file_tuple
                            if output_file_success:
                                # If there is a list text variable (the 4th (or 3rd by 0 based index) variable), then add it to our output list
                                if len(job_outcome) == 4:
                                    output_files_list.append([output_file, job_outcome[3]])
                                else:
                                    output_files_list.append([output_file])

            plots_thread = PlotsThread(self.create_plots, output_files_list, self)
            plots_thread.start()

    def add_plot(self, args=dict()):
        self.plot_args.append(args)

    def finished_adding_plots(self):
        self.event_generate('<<CreatePlotGUI>>', when='tail')

    def create_plot_gui(self, event):
        # TODO: This should be replaced with a new window that allows the user to drag and drop the icons from one frame to another
        graph_names = list()
        for args in self.plot_args:
            graph_name = args['output_file']
            graph_names.append(graph_name)
        dnd_graphs_frame = Dnd.createFrame(self, 'Drag and Drop Output Plots', graph_names, self.finish_creating_plot_gui)

    # This is the entry point for the
    def finish_creating_plot_gui(self, plot_labels):
        graph_count = 1
        for plot_label in plot_labels:
            for args in self.plot_args:
                #print 'Looking in ' + args['plot_title'] + ' for ' + plot_label
                #print 'The plot label is: ' + plot_label
                #print 'The output file is: ' + args['output_file']
                if plot_label == args['output_file']:
                    #print 'Creating graph ' + str(graph_count)
                    graph_count += 1
                    graph_window = ModelRunnerGraphGUI.GraphWindow(parent=self, title=args['window_title'], df=args['df'], plot=args['plot'], plot_title=args['plot_title'], y_label=args['y_label'], log_filename=self.log_filename)
                    graph_window.set_grid()
                    self.top_level_windows.append(graph_window)
        #print 'Creating plot GUI

        # Have to clear out list here instead of clear_list because clear_list() removes plot_args before this method has a chance to read
        # them and create the appropriate plot graph windows
        self.reinit_variables()

    # Clear all the elements in the list
    def clear_list(self):

        # Save plot args because they are need later in this run
        plot_args = self.plot_args
        self.reinit_variables()
        # Restore the plot args
        self.plot_args = plot_args

        self.job_list.delete(0, self.job_list.size())
        self.progress_value.set(0)
        # Update parent to refresh widget appearance
        self.parent.update()

    def on_add(self):
        single_job = JobParameters(parent=self.parent, beginning_year=1950, ending_year=2100, job_id=self.last_job_id + 1, entry=self)
        single_job.set_grid()

    def on_remove(self):
        selection = self.job_list.curselection()
        for line_number in selection:
            line_text = self.job_list.get(line_number)
            job_id = int(line_text[4:line_text.index(' ', 4)])
            job = self.job_params.pop(job_id)
            self.job_list.delete(line_number)
            print 'Removed Job ' + str(job['job_id'])
        # Fix line number
        for line_number in range(self.job_list.size()):
            line_text = self.job_list.get(line_number)
            job_id = int(line_text[4:line_text.index(' ', 4)])
            #print 'Job ' + str(job_id) + ' is now on line ' + str(line_number)
            self.job_params[job_id]['line_number'] = line_number

    def set_grid(self):
        self.grid(sticky=Tkinter.N + Tkinter.S + Tkinter.W + Tkinter.E, padx=4, pady=4)
        self.columnconfigure(0, minsize=600)
        self.rowconfigure(0, minsize=300)
        self.job_list.grid(row=0, column=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W)
        self.job_list_yscroll.grid(row=0, column=1, sticky=Tkinter.N + Tkinter.S + Tkinter.W)
        self.job_list_xscroll.grid(row=1, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N)
        self.new_job_frame.grid(row=2, column=0, pady=3, sticky=Tkinter.W)
        self.remove_job_button.grid(row=0, column=0)
        self.add_job_button.grid(row=0, column=1)
        self.progress_frame.grid(row=3, column=0, pady=3)
        self.progress_frame.columnconfigure(0, minsize=600)
        self.progress_bar.grid(row=0, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
        self.button_frame.grid(row=4, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S)
        self.button_frame.columnconfigure(0, minsize=300)
        self.button_frame.columnconfigure(1, minsize=300)
        self.process_button.pack(side=Tkinter.RIGHT)
        self.quit_button.pack(side=Tkinter.RIGHT)

    def start_jobs(self):
        # If there are no queued jobs then simply return
        if len(self.job_params) == 0 or len(self.job_list.get(0)) == 0:
            return
        # Deactivate the process button
        self.process_button.config(state = Tkinter.DISABLED)
        # Initialize the progress bar
        self.progress_value.set(0)
        # Update parent to refresh widget appearance
        self.parent.update()
        # Start process thread
        jobs_thread = JobsThread(self.job_params, self.run_job, self.on_update, self.on_resume)
        jobs_thread.start()
        self['cursor'] = 'wait'

    def on_update(self, status, line_number, step):
        if status == 'init':
            self.job_list.itemconfig(line_number, foreground='green')
            self.job_list.activate(line_number)
        elif status == 'success':
            self.job_list.itemconfig(line_number, foreground='blue')
        elif status == 'fail':
            self.job_list.itemconfig(line_number, foreground='red')
        self.progress_value.set(step)
        # Update parent to refresh widget appearance
        self.parent.update()

    def on_resume(self, job_outcomes=list()):
        self.progress_value.set(100)
        self.job_outcomes = job_outcomes
        self.event_generate('<<AskToClearJobs>>', when='tail')
        self.event_generate('<<AskToPlotGraphs>>', when='tail')
        self['cursor'] = 'arrow'

    def close_top_level_windows(self):
        #print 'Closing other top level windows'
        for top_level_window in self.top_level_windows:
            if top_level_window:
                top_level_window.withdraw()
                top_level_window.destroy()

    def notify_of_close(self, top_level_window):
        if top_level_window in self.top_level_windows:
            #print 'Removing top level window'
            self.top_level_windows.remove(top_level_window)

    def on_press(self, event):
        self.on_button = True
        self.release_pattern = "<B%d-ButtonRelease-%d>" % (event.num, event.num)
        self.parent.bind(self.release_pattern, self.on_release)

    def on_release(self, event):
        self.on_button = False

    def on_resize(self, event):
        self.parent.lift()

        if self.on_button:

            self.set_grid()

    def on_close(self):
        self.plot_args = list()
        self.withdraw()
        self.destroy()
예제 #54
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.padx = 3
        self.pady = 3
        self.grid()
        self.results = []
        self.playlists = []
        self.vids = []
        self.__createWidgets()

    def __createWidgets(self):
        self.__searchFields()
        self.__resultArea()
        self.__buttons()
        self.__markdownArea()
        self.bind('<Return>', self.search_button)

    def __buttons(self):
        self.resultSelect = Button(text='OK', state=DISABLED)
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)
        self.status = Label(text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.grid(row=9, column=0, columnspan=10, sticky=N + E + S + W)
        self.__vidButtons()
        self.__rmVidButtons()
        self.resultSelect.grid_forget()

    def __searchFields(self):
        Label(text="User", anchor=E).grid(row=0, column=0,
                                          padx=self.padx, pady=self.pady,
                                          sticky=W)
        self.user_entry = Entry()
        self.user_entry.grid(row=0, column=1, padx=self.padx, pady=self.pady,
                             sticky=W)
        Label(text="Search terms").grid(row=0, column=3,
                                        padx=self.padx, pady=self.pady,
                                        sticky=W)
        self.search_terms = Entry()
        self.search_terms.grid(row=0, column=4,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        Label(text="playlist id").grid(row=1, column=3,
                                       padx=self.padx, pady=self.pady,
                                       sticky=W)
        self.playlist_id = Entry()
        self.playlist_id.grid(row=1, column=4, padx=self.padx, pady=self.pady,
                              sticky=W)
        self.search_button = Button(text="Search", command=self.__search)
        self.search_button.grid(row=2, column=4,
                                padx=self.padx, pady=self.pady, sticky=E)

    def __resultArea(self):
        self.result_label = Label(text="Results")
        self.result_label.grid(row=2, column=0,
                               padx=self.padx, pady=self.pady,
                               sticky=W)
        self.resultshowbut = Button(text="View", command=self.__showResults)
        self.resultshowbut.grid(row=2, column=1, sticky=W)
        self.yScroll = Scrollbar(orient=VERTICAL)
        self.xScroll = Scrollbar(orient=HORIZONTAL)
        self.listbox = Listbox(xscrollcommand=self.xScroll.set,
                                yscrollcommand=self.yScroll.set,
                                selectmode=SINGLE)
        self.xScroll.config(command=self.listbox.xview)
        self.yScroll.config(command=self.listbox.yview)

    def __showResults(self):
        self.resultshowbut.config(text="Hide", command=self.__hideResults)
        self.yScroll.grid(row=3, column=5, sticky=N + S)
        self.xScroll.grid(row=4, column=0, sticky=E + W, columnspan=5)
        self.listbox.grid(row=3, column=0, sticky=N + S + E + W, columnspan=5)
        self.markdownarea.config(height=10)

    def __hideResults(self):
        self.resultshowbut.config(text="View", command=self.__showResults)
        self.yScroll.grid_forget()
        self.xScroll.grid_forget()
        self.listbox.grid_forget()
        self.markdownarea.config(height=30)

    def __markdownArea(self):
        self.markdownlabel = Label(text="Markdown")
        self.mdyScroll = Scrollbar(orient=VERTICAL)
        self.mdxScroll = Scrollbar(orient=HORIZONTAL)
        self.markdownarea = Text(wrap=WORD, height=10,
                                 yscrollcommand=self.mdyScroll.set,
                                 xscrollcommand=self.mdxScroll.set)
        self.copymarkdown = Button(text="Copy To Clipboard",
                                  command=self.__copyMarkdown)
        self.mdxScroll.config(command=self.markdownarea.xview)
        self.mdyScroll.config(command=self.markdownarea.yview)

    def __vidButtons(self):
        self.modtitle = Button(text='Modify titles', command=self.__modTitles)
        #self.modtitle.grid(row=5, column=0, sticky=W, columnspan=2,
        #                   padx=self.padx, pady=self.pady)
        self.getcaps = Button(text="Get captions", command=self.__getCaptions)
        self.getcaps.grid(row=5, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmVidButtons(self):
        self.modtitle.grid_remove()
        self.getcaps.grid_remove()
        self.bind('<Return>', self.search_button)

    def __search(self):
        user = self.user_entry.get()
        playlist = self.playlist_id.get()
        searchterms = self.search_terms.get()
        self.__showResults()
        self.resultSelect.config(state=DISABLED)
        self.__rmVidButtons()
        self.__rmMarkdown()
        if not self.__validparams(user, searchterms, playlist):
            return False

        if len(playlist) > 0:
            self.__searchPlaylist(playlist)
            return

        self.__searchUser(user, searchterms)

    def __showMarkdown(self):
        self.markdownlabel.grid(row=5, column=0,
                                    padx=self.padx, pady=self.pady,
                                    sticky=W)
        self.markdownarea.grid(row=6, column=0, columnspan=5,
                               padx=self.padx, pady=self.pady,
                               sticky=N + S + E + W)
        self.mdyScroll.grid(row=6, column=5, sticky=N + S)
        self.mdxScroll.grid(row=7, column=0, sticky=E + W, columnspan=5)
        self.copymarkdown.grid(row=8, column=2, columnspan=3, sticky=E,
                          padx=self.padx, pady=self.pady)

    def __rmMarkdown(self):
        self.markdownarea.grid_forget()
        self.markdownlabel.grid_forget()
        self.copymarkdown.grid_forget()
        self.mdyScroll.grid_forget()
        self.mdxScroll.grid_forget()

    def __searchPlaylist(self, playlistid):
        self.__getvids(playlistid)

    def __searchUser(self, user, searchterms):
        self.listbox.delete(0, END)
        self.__status("Searching for%splaylists by user \"%s\"" % (
                      " \"%s\" " % searchterms if len(searchterms) else " ",
                      user))
        self.playlists = []
        try:
            self.playlists = lib.yt.search.PlaylistSearch(user=user,
                                                 search=searchterms).query()
        except HTTPError:
            self.__status("User %s does not exist at youtube" % user)
            return
        if self.playlists is None or len(self.playlists) == 0:
            self.__status("Search returned no results")
            return
        self.__populateResults([v['title'] for v in self.playlists])
        self.resultSelect.config(command=self.__getVidsFromSelected,
                                 state=NORMAL)
        self.__status("")
        self.resultSelect.grid(row=5, column=4, sticky=E,
                               padx=self.padx, pady=self.pady)

    def __populateResults(self, values):
        self.listbox.delete(0, END)
        for i, val in enumerate(values):
            self.listbox.insert(i, val)
        self.listbox.activate(0)
        self.listbox.selection_set(0)

    def __getVidsFromSelected(self):
        selected = int(self.listbox.curselection()[0])
        self.__getvids(self.playlists[selected]['id'])

    def __getvids(self, playlistid):
        self.playlist_id.delete(0, END)
        self.playlist_id.insert(0, playlistid)
        self.resultSelect.grid_forget()
        title = playlistid
        if len(self.playlists) > 0:
            for playlist in self.playlists:
                if playlist['id'] == playlistid:
                    title = playlist['title']
                    break

        self.__status("Getting videos for %s" % title)
        self.listbox.delete(0, END)
        try:
            self.vids = lib.yt.search.PlaylistVideoSearch(
                                                    id=playlistid).query()
            self.__populateResults([v['title'] for v in self.vids])
            self.__status("%d Videos found" % len(self.vids))
            self.__vidButtons()
            self.bind('<Return>', self.getcaps)
        except HTTPError:
            self.__status("No videos found! is %s a valid playlist?" %
                          playlistid)

    def __status(self, msg):
        if len(msg) > 75:
            msg = msg[:70] + '...'
        self.status.config(text=msg)
        self.status.update_idletasks()

    def __trackSelect(self, vid, tracks, preftrack=None):
        pref = self.__prefAvailable(preftrack, tracks)
        if pref is None:
            sel = lib.trackSelect.TrackSelect(self, vid=vid,
                                              tracks=tracks)
            if sel.result is None:
                self.__status("skipped")
                tracks = None
            else:
                tracks = [sel.result[0]]
                if sel.preflang is not None:
                    preftrack['lang'] = sel.preflang
                if sel.prefname is not None:
                    preftrack['name'] = sel.prefname
        else:
            tracks = pref
        return tracks, preftrack

    def __getCaptions(self):
        preftrack = {'name': None, 'lang': None}
        self.listbox.delete(0, END)
        self.markdownarea.delete(1.0, END)
        self.__showMarkdown()
        for i, vid in enumerate(self.vids):
            nocapmsg = '[%02d] --NO CAPTIONS-- %s' % (i + 1, vid['title'])
            tracks = lib.yt.search.CaptionSearch(id=vid['id']).query()
            self.vids[i]['text'] = ''
            if len(tracks) == 0:
                self.__status('No captions available for %s' %
                              self.vids[i]['title'])
                self.listbox.insert(END, nocapmsg)

            elif len(tracks) > 1:
                sel = self.__trackSelect(vid, tracks, preftrack)
                if sel[0] is None:
                    msg = '[%02d] --SKIPPED-- %s' % (i + 1, vid['title'])
                    self.listbox.insert(END, msg)
                    self.listbox.see(END)
                    continue
                tracks = sel[0]

            if len(tracks) == 1:
                self.__trackCaps(i, tracks, nocapmsg)
        self.__status('')
        self.__hideResults()

    def __trackCaps(self, vidIndex, tracks, nocapmsg):
        i = vidIndex
        vid = self.vids[i]
        msg = '%02d of %02d Getting captions for %s' % (
                        i + 1, len(self.vids), self.vids[i]['title'])
        self.__status(msg)
        self.listbox.insert(END, msg)
        self.vids[i]['text'] = lib.markdown.heading(vid['title'])
        captions = lib.yt.search.GetCaptions(id=vid['id'],
                                lang=tracks[0]['lang'],
                                name=tracks[0]['name'])
        captions.query()
        captiontext = captions.textOnly()
        sleep(0.2)
        msg = nocapmsg
        if captiontext is not None and len(captiontext) > 0:
            self.vids[i]['text'] += (lib.markdown.to_utf8(captiontext)
                                     + '\n\n')
            msg = '[%02d] --DONE-- %s' % (i + 1, vid['title'])
        self.listbox.delete(END, END)
        self.listbox.insert(END, msg)
        self.listbox.see(END)
        self.markdownarea.insert(END, self.vids[i]['text'])
        self.markdownarea.see(END)

    def __prefAvailable(self, preftrack, tracks):
        if preftrack['lang'] is None:
            return None

        pref = None
        for track in tracks:
            if (track['lang'] == preftrack['lang'] and
                track['name'] == preftrack['name']):
                return [track]
            if track['lang'] == preftrack['lang'] and pref is None:
                pref = [track]

        return pref

    def __modTitles(self):
        pass

    def __validparams(self, user, searchterms, playlist):
        if len(user) == 0 and len(playlist) == 0:
            msg = "Either a valid youtube user or playlist id must be given."
            tkMessageBox.showwarning("missing information", msg)
            return False

        if len(user) > 0 and not self.__validstring(user):
            msg = "The user given contains invalid characters"
            tkMessageBox.showwarning('Bad user', msg)
            return False

        if len(playlist) > 0 and not self.__validstring(playlist):
            msg = "The playlist given contains invalid characters"
            tkMessageBox.showwarning('Bad playlist', msg)
            return False

        if len(searchterms) > 0 and not self.__validstring(searchterms, True):
            msg = "The search terms given contain invalid characters"
            tkMessageBox.showwarning('Bad search', msg)
            return False

        return True

    def __validstring(self, s, spacechar=False):
        validchars = string.letters + string.digits + string.punctuation
        if spacechar:
            validchars += ' '
        for c in s:
            if c not in validchars:
                return False
        return True

    def __copyMarkdown(self):
        self.markdownarea.clipboard_clear()
        self.markdownarea.clipboard_append(self.markdownarea.get(1.0, END))
예제 #55
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)
예제 #56
0
class photGUI(Frame):
    """The base class for the phot_calc GUI"""
    
    # This is the constructor for the GUI
    def __init__(self,master=None):
        # We begin by calling the base class's constructor first
        Frame.__init__(self,master)
    
        # We now have an empty window!
        
        # This command sets up a grid structure in the window
        self.grid()
        
        # This loop generates rows and columns in the grid
        for i in range(13):
            self.rowconfigure(i,minsize=10)
        for i in range(3):
            self.columnconfigure(i,minsize=30)
        
        # These are methods which appear below the constructor
        self.defineUnits() # this sets up the units I'll be using in the converter
        self.createWidgets() # this places the elements (or widgets) in the grid
        
        # This command "binds" the user's click to a method (varChoice)
        # This method will determine which variable the user wants (Distance, Mass, Time)
        self.inputlist.bind("<Button-1>",self.__varChoice)
    
        # This is a similar command for the selection of unit
        self.unitlist.bind("<Button-1>",self.__unitChoice)
    
        # Finally, this bind reads in whatever value is in the text box when the user hits return
        # and carries out the unit conversion
        
        self.inputfield.bind("<Return>",self.__calcConversion)
    
    # This function creates and defines the units
    
    def defineUnits(self):
        '''Method defines tuples that carry the various units stored by the converter'''
        
        self.speed = 2.997924580000019e10
        self.h = 6.6260755e-27     
        # Wavelengths
        
        self.wavunits = ('nm','um', 'cm','m')
        self.wavvalues = (1.0e-7, 1.0e-4,1.0,1.0e2)
        
        self.frequnits = ('Hz','MHz','GHz','THz')
        self.freqvalues = (1.0, 1.0e6, 1.0e9, 1.0e12)
        
        self.energunits = ('eV','keV','MeV','GeV','erg')
        self.energvalues = (1.0,1.0e3,1.0e6,1.0e9,1.6e-12)
        
        # Keep the unit values in dictionaries, and use the above strings as keys
        
        self.wavdict = {}        
        self.createUnitDict(self.wavdict,self.wavunits,self.wavvalues) # this method is shown below
        
        self.freqdict = {}
        self.createUnitDict(self.freqdict,self.frequnits,self.freqvalues)
        
        self.energdict = {}
        self.createUnitDict(self.energdict, self.energunits, self.energvalues)  
    
        self.myunits = self.wavunits
        self.myvalues = self.wavvalues
        self.mydict = self.wavdict
    
        
    def createUnitDict(self,mydict,mykeys,myvalues):
        '''This method takes a set of units and values, and creates a dictionary to store them in'''
        for i in range(len(myvalues)):
            mydict[mykeys[i]] = myvalues[i]
               
    def createWidgets(self):
        '''This method creates all widgets and adds them to the GUI'''
        
        # Create Widgets in order of appearance
        # This is not necessary, but makes code easier to read
        
        # Start with text telling user what to do
        self.varlabel = Text(self,height=1, width=20)
        self.varlabel.insert(END,"Which Variable?")
        
        # Place widget on the Frame according to a grid
        self.varlabel.grid(row=0,column=0,sticky=W)
        
        # Second text label asking user which units are being used
        self.unitlabel = Text(self,height=1,width=20)
        self.unitlabel.insert(END,"Which Units?")
        self.unitlabel.grid(row=0,column=1,sticky=W)
        
        # Third text label asking user for numerical value
        
        self.numlabel = Text(self,height=1, width=20)
        self.numlabel.insert(END,"Enter Variable Values")
        self.numlabel.grid(row=0,column=2,sticky=W)
        
        # This creates a list of options for the user to select
        self.inputlist = Listbox(self, height=4, selectmode=SINGLE)
      
        # Tuple of choices we're going to put in this list
        self.paramlist = ('Frequency', 'Wavelength', 'Energy')
        
        # Add each item separately
        for item in self.paramlist:
            self.inputlist.insert(END,item)
            
        # Add it to the grid    
        self.inputlist.grid(row=1, column=0,rowspan=4,sticky=W)
        
        # Add a unit list (several combinations of units allowed)
        
        self.unitlist = Listbox(self, height=4,selectmode=SINGLE)
        self.unitlist.grid(row=1,column=1,rowspan=4, sticky=W)
    
        # Number Entry Boxes (and Text Labels)
        
        self.inputlabel = Text(self,height=1,width=20)
        self.inputlabel.insert(END,"Waiting Selection")
        self.inputlabel.grid(row=1,column=2,sticky=W)
        
        self.inputfield = Entry(self)
        self.inputfield.grid(row=2,column=2,sticky=W)
        
        # Text Output Boxes
        self.wavoutput = Text(self, height=5, width=20)
        self.wavoutput.grid(row=7,column=0,rowspan=5,sticky=W)
        self.wavoutput.insert(END, "Wavelength: \n")
        
        self.freqoutput = Text(self, height=5, width=20)
        self.freqoutput.grid(row=7,column=1,rowspan=5,sticky=W)
        self.freqoutput.insert(END, "Frequency: \n")
        
        self.energoutput = Text(self, height=5, width=20)
        self.energoutput.grid(row=7,column=2,rowspan=5,sticky=W)
        self.energoutput.insert(END, "Energy: \n")
        
        # Create the Quit Button
        self.quitButton=Button(self,text='Quit',command=self.quit)
        self.quitButton.grid(row =13, column=0, sticky=W)
             

    # Event handler functions begin here    
    # This handler defines the choice of units available to the user, 
    # depending on selected variable
    
    def __varChoice(self, event):
        '''Handles the selection of variable: updates the list of units'''
        # Firstly, delete anything already in the units column
        self.unitlist.delete(first=0,last=len(self.myvalues))
        num = 0
        
        # Identify which option was clicked on
        try:
            num = self.inputlist.curselection()[0]       
            self.varchoice = int(num)
            
        except:
            self.varchoice = 0
            return
        
        # Get the string associated with this choice
        selection= self.inputlist.get(self.varchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.inputlist.itemconfig(self.varchoice, selectbackground='red')
        
        # If statement defines units being used
        if selection =='Wavelength':
            self.myunits = self.wavunits
            self.myvalues = self.wavvalues
            self.mydict = self.wavdict
        elif selection == 'Frequency':
            self.myunits = self.frequnits
            self.myvalues = self.freqvalues
            self.mydict = self.freqdict
        elif selection == 'Energy':
            self.myunits = self.energunits
            self.myvalues = self.energvalues
            self.mydict = self.energdict
            
        
        self.inputlabel.delete("1.0",index2=END)
        self.inputlabel.insert(END,selection)
        
        
        for i in range(len(self.myunits)):
            self.unitlist.insert(END,self.myunits[i])
        
    def __unitChoice(self,event):
        '''Handles the selection of units'''
        num = 0
        # Find which number is selected
        try:
            num = self.unitlist.curselection()[0]       
            self.unitchoice = int(num)
            
        except:
            self.unitchoice = 0
            return
        
        # Get the string (i.e. which unit is selected)
        selection= self.unitlist.get(self.unitchoice)
        
        print selection, " chosen"
        
        # Highlight current choice in red
        self.unitlist.itemconfig(self.unitchoice, selectbackground='red')
        
    # Handler takes current state of GUI, and calculates results
    def __calcConversion(self,event):
        '''This method takes the current state of all GUI variables, calculates one of four equations'''
        
        # Which variable has been selected for calculation?
        # This decides what equation to use
        
        a = self.inputfield.get()
        var = self.unitlist.get(self.unitchoice)
        a=float(a)
        
        freq = 0.0
        wav = 0.0
        energy = 0.0
        
        if self.varchoice==0:
            freq = a
            freq = freq*self.mydict[var]
            wav = self.speed/freq
            energy = self.h*freq/self.energdict['erg']
            
        elif self.varchoice==1:
            wav = a
            wav = wav*self.mydict[var]
            freq = self.speed/wav
            energy = self.speed*self.h/wav
            
        elif self.varchoice==2:
            energy = a
            energy=energy*self.energdict["erg"]
            freq = energy/self.h
            wav = self.speed*self.h/energy
            energy = energy*self.mydict[var]/self.energdict["erg"]
        
        # Remove all text in the output boxes
        self.wavoutput.delete("1.0",index2=END)
        self.freqoutput.delete("1.0",index2=END)
        self.energoutput.delete("1.0",index2=END)
        
        self.wavoutput.insert(END, "Wavelength: \n")
        self.freqoutput.insert(END, "Frequency: \n")
        self.energoutput.insert(END, "Energy: \n")
        
        # Calculate each conversion and output it to the GUI
        for i in range(len(self.wavvalues)):
            # As all units stored in cgs values, conversion is simple
            output = wav/self.wavvalues[i]
            
            # Express output in 
            
            # Add to the output list
            self.wavoutput.insert(END,self.wavunits[i] + ":  %.4e" % output+"\n")  
            
            
        for i in range(len(self.freqvalues)):
            # As all units stored in cgs values, conversion is simple
            output = freq/self.freqvalues[i]
            # Add to the output list
            self.freqoutput.insert(END,self.frequnits[i] + ":  %.4e" % output+"\n")        
            
        for i in range(len(self.energvalues)):
            # As all units stored in cgs values, conversion is simple
            output = energy/self.energvalues[i]
            # Add to the output list
            self.energoutput.insert(END,self.energunits[i] + ":  %.4e" % output+"\n")       
예제 #57
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()
예제 #58
-1
class ResultList(Frame):
    """
    Result List widget
    """

    def __init__(self, master=None):
        Frame.__init__(self, master, padx=3, pady=3)
        self.columnconfigure(0, weight=1, minsize=50)
        self.columnconfigure(1, weight=1000)
        self.columnconfigure(2, weight=1, minsize=10)
        self.__createWidgets()
        self.show()

    def __createWidgets(self):
        self.lbl = Label(text="")
        self.lbl.grid(row=1, column=0, columnspan=2, in_=self)
        self.__hide_button = Button(text="Hide", command=self.hide)
        self.__hide_button.grid(row=0, column=0, columnspan=2, in_=self)
        self.__yScroll = Scrollbar(orient=VERTICAL)
        self.list = Listbox(yscrollcommand=self.__yScroll.set, selectmode=SINGLE)
        self.__yScroll.config(command=self.list.yview)

    def show(self):
        self.__hide_button.config(text="Hide", command=self.hide)
        self.list.grid(row=2, column=0, columnspan=2, sticky=N + S + E + W, in_=self)
        self.__yScroll.grid(row=2, column=2, sticky=W + N + S, in_=self)

    def hide(self):
        self.__hide_button.config(text="Show", command=self.show)
        self.list.grid_forget()
        self.__yScroll.grid_forget()

    def clear(self):
        self.list.delete(0, END)

    def fill(self, valList):
        self.clear()
        for v in valList:
            self.list.insert(END, v)
        self.list.see(0)
        self.select(0)

    def append(self, val):
        self.list.insert(END, val)
        self.list.see(END)

    def select(self, index=0):
        self.list.selection_set(index)

    def selected(self):
        return int(self.list.curselection()[0])

    def width(self, width):
        self.list.config(width=width)
예제 #59
-1
class YTPlaylistGUI(UI):
    LOGIN_COMPLETE_EVENT = "<<LoginComplete>>"
    PLAYLIST_LIST_FETCH_COMPLETE_EVENT = "<<PlalistListFetched>>"
    PLAYLIST_SAVED_EVENT = "<<PlaylistSaved>>"

    def __init__(self, playlist_manager):
        super(YTPlaylistGUI, self).__init__()
        self.playlist_manager = playlist_manager
        self.workerThread = None
        self.last_exception = None
        self.username = None
        self._login_dialog = None
        self._loading_playlists_dialog = None

    def _create_login_window(self):
        self.root = Tk()
        self.root.geometry("280x150")
        self.root.title(self.YTPLAYLIST_LOGIN_WINDOW_TITLE)
        self.root.bind(self.LOGIN_COMPLETE_EVENT, self._login_complete)
        Button(self.root, text=self.YTPLAYLIST_LOGIN_BUTTON_TEXT,
               command=self.login).pack(side=Tkinter.TOP,
                                        pady=20, padx=20, expand=True, fill=Tkinter.BOTH)
        Button(self.root, text=self.YTPLAYLIST_NOLOGIN_BUTTON_TEXT,
               command=self.skip_login).pack(side=Tkinter.TOP,
                                             pady=20, padx=20, expand=True, fill=Tkinter.BOTH)

    def _create_playlists_window(self):
        if self.root:
            self.root.destroy()
        self.root = Tk()
        self.root.geometry("300x{0}".format(280 if self.playlist_manager.is_logged_in else 250))
        self.root.title(self.YTPLAYLIST_PLAYLISTS_WINDOW_TITLE)
        if self.playlist_manager.is_logged_in:
            Button(self.root, text=self.YTPLAYLIST_DESTROY_CREDENTIALS_BUTTON_TEXT,
                   command=self.logout).pack(side=Tkinter.TOP, padx=20, pady=(10, 5), fill=Tkinter.X)
        scrollbar = Scrollbar(self.root, orient=Tkinter.VERTICAL)
        self.playlist_list = Listbox(self.root, yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.playlist_list.yview)
        Button(self.root, text=self.YTPLAYLIST_EXPORT_BUTTON_TEXT,
               command=self._export_playlist_item).pack(side=Tkinter.BOTTOM,
                                                        padx=20, pady=(5, 10), fill=Tkinter.X)
        self.playlist_list.pack(side=Tkinter.LEFT, padx=(5, 0), pady=5, expand=True, fill=Tkinter.BOTH)
        scrollbar.pack(side=Tkinter.LEFT, padx=(0, 5), pady=5, fill=Tkinter.Y)
        self.root.bind(self.PLAYLIST_LIST_FETCH_COMPLETE_EVENT,
                       self._playlist_list_fetched)
        self.root.bind(self.PLAYLIST_SAVED_EVENT, self._playlist_saved)

    def start(self):
        self._create_login_window()
        self.root.mainloop()

    def _login_async(self):
        try:
            self.playlist_manager.login()
        except Exception as e:
            self.last_exception = e
        self.root.event_generate(self.LOGIN_COMPLETE_EVENT, when="tail")

    def login(self):
        self.workerThread = threading.Thread(target=self._login_async)
        self.workerThread.start()
        self._login_dialog = _WorkingDialog(self.root, "Logging in...")

    def logout(self):
        self.playlist_manager.destroy_credentials()
        self.root.destroy()

    def skip_login(self):
        self.username =\
            tkSimpleDialog.askstring(
                "Username", "Specify the playlist owner's username",
                parent=self.root)
        self.playlist_manager.skip_login()
        self._create_playlists_window()
        self.display_playlists()

    def _login_complete(self, _):
        del self._login_dialog
        self.__handle_exceptions()
        self._create_playlists_window()
        self.display_playlists()

    def display_playlists(self):
        self._loading_playlists_dialog =\
            _WorkingDialog(self.root, "Loading playlists")
        self.workerThread =\
            threading.Thread(target=self._fetch_playlists_async)
        self.workerThread.start()

    def _fetch_playlists_async(self):
        try:
            if self.playlist_manager.is_logged_in:
                result = self.playlist_manager.list_playlists()
            else:
                result = self.playlist_manager.list_playlists(self.username)
            self.playlist_data = result
        except Exception as e:
            self.last_exception = e
        self.root.event_generate(self.PLAYLIST_LIST_FETCH_COMPLETE_EVENT, when="tail")

    def _playlist_list_fetched(self, _):
        del self._loading_playlists_dialog
        self.__handle_exceptions()
        if self.playlist_data is None:
            self.display_error("Not found", "No such user or no public playlists.")
            exit(0)
        for item in self.playlist_data:
            self.playlist_list.insert(Tkinter.END, item["snippet"]["title"])
        self.root.mainloop()

    def _export_playlist_item(self):
        selection = map(int, self.playlist_list.curselection())
        playlist_id = self.playlist_data[selection[0]]["id"]
        fname =\
            tkFileDialog.asksaveasfilename(
                defaultextension=".pls",
                filetypes=[("Playlists", "*.pls"), ("All files", "*.*")],
                parent=self.root,
                title=self.YTPLAYLIST_SAVE_AS_TITLE)
        if fname is None or fname == "":
            return
        self._saving_playlist_dialog = \
            _WorkingDialog(self.root, "Saving playlist")
        self.workerThread =\
            threading.Thread(target=self._export_playlist_worker,
                             args=(playlist_id, fname))
        self.workerThread.start()

    def _export_playlist_worker(self, playlist_id, fname):
        try:
            self.playlist_manager.export_playlist(playlist_id, fname)
        except Exception as e:
            self.last_exception = e
        self.root.event_generate(self.PLAYLIST_SAVED_EVENT, when="tail")

    def _playlist_saved(self, _):
        del self._saving_playlist_dialog
        self.__handle_exceptions()
        showinfo("Playlist saved", "Saving playlist complete")

    def display_error(self, title, message):
        showerror(title, message)

    def display_warning(self, title, message):
        showwarning(title, message)

    def __handle_exceptions(self):
        if self.last_exception is not None:
            self.display_error("Error", str(self.last_exception))
            exit(0)