class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError( "Combobox_Autocomplete subclass has 'autocomplete_function' implemented" ) else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError( "If not guiven complete function, list_of_items can't be 'None'" ) if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [ item for item in self.list_of_items if matches_function(entry_data, item) ] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [ item for item in self.list_of_items if matches_function(escaped_entry_data, item) ] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0, sticky=N + E + W + S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command=self._listbox.yview) vbar.grid(row=0, column=1, sticky=N + S) self._listbox.configure( yscrollcommand=lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command=self._listbox.xview) hbar.grid(row=1, column=0, sticky=E + W) self._listbox.configure( xscrollcommand=lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight=1) listbox_frame.grid_rowconfigure(0, weight=1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height() - self.cget("borderwidth") - self.cget( "highlightthickness") if self._listbox_width: width = self._listbox_width else: width = self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection) == 0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index += 1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) self.differ = differ.Differ() #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda: self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I': lambda: self.information_box.get() == 1, 'C': lambda: self.convention_box.get() == 1, 'R': lambda: self.refactor_box.get() == 1, 'E': lambda: self.error_box.get() == 1, 'W': lambda: self.warning_box.get() == 1, 'F': lambda: self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename + '\n' in self.filenames: index = self.filenames.index(filename + '\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename + '\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME + HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=( module, self.reporter, self, )) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME + HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] scroll = msg.line - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(msg.abspath, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(msg.line - 1) def show_messages_context(self, event): """Show the message listbox's context menu""" # Select the item that was clicked index = self.lbMessages.nearest(event.y) self.lbMessages.selection_clear(0, END) self.lbMessages.selection_set(index) self.lbMessages.activate(index) self.mnMessages.tk_popup(event.x_root, event.y_root) def add_to_ignore_patchfile(self, event=None): """ Add the selected message to the ignore patchfile. This means that this message will now be ignored by pylint-patcher. """ selected = self.lbMessages.curselection() if not selected: return selected_index = int(selected[0]) msg = self.visible_msgs[selected_index] self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol) self.differ.diff() del self.msgs[self.msgs.index(msg)] del self.visible_msgs[selected_index] self.lbMessages.delete(selected_index)
class JobList(Frame): # NOTE: job_params contains information about a Job in the Joblist # NOTE: plot_args contains information about plotting information, which occurs after the jobs have been and the data files have been created def __init__(self, parent=None, **kwargs): Frame.__init__(self, parent) self.parent = parent self.job_list_yscroll = Scrollbar(self, orient=Tkinter.VERTICAL) self.job_list_xscroll = Scrollbar(self, orient=Tkinter.HORIZONTAL) self.job_list = Listbox(self, xscrollcommand=self.job_list_xscroll, yscrollcommand=self.job_list_yscroll) self.job_list_xscroll['command'] = self.job_list.xview self.job_list_yscroll['command'] = self.job_list.yview self.new_job_frame = Frame(self) add_icon_filename = kwargs['add_icon_filename'] if 'add_icon_filename' in kwargs else None if add_icon_filename == None: self.add_job_button = Button(self.new_job_frame, text='Add Job', command=self.on_add) else: add_icon = PhotoImage(file=add_icon_filename) self.add_job_button = Button(self.new_job_frame, text='Add Job', compound='bottom', image=add_icon, command=self.on_add) self.remove_job_button = Button(self.new_job_frame, text='Remove Job', command=self.on_remove) self.progress_frame = Frame(self) self.progress_value = Tkinter.IntVar() self.progress_bar = Progressbar(self.progress_frame, variable=self.progress_value) self.button_frame = Frame(self) self.process_button = ProcessButton(parent=self.button_frame, start_jobs=self.start_jobs) self.quit_button = QuitButton(parent=self.button_frame, close_other_windows=self.close_top_level_windows) self.run_job = kwargs['run_job'] if 'run_job' in kwargs else None self.create_plots = kwargs['create_plots'] if 'create_plots' in kwargs else None self.log_filename = kwargs['log_filename'] if 'log_filename' in kwargs else None self.bind('<<AskToClearJobs>>', self.ask_to_clear_jobs) self.bind('<<AskToPlotGraphs>>', self.ask_to_plot_graphs) self.bind('<<CreatePlotGUI>>', self.create_plot_gui) self.parent.bind('<ButtonPress>', self.on_press) self.parent.bind('<Configure>', self.on_resize) self.reinit_variables() self.top_level_windows = list() # NOTE: Because there seems to be an issue resizing child widgets when the top level (Tk) widget is being resized, # the resize option will be disabled for this window self.parent.resizable(width=False, height=False) self.lift() def reinit_variables(self): self.job_params = dict() self.last_job_id = -1 self.job_outcomes = list() self.plot_args = list() self.on_button = False def add_job_params(self, input_args): self.job_params = input_args # Add each element to the job list for job in self.job_params: self.add_job(job) def add_job(self, job): try: index_end = job['input_directory'].rindex('/') index_start = job['input_directory'].rindex('/', 0, index_end) input_directory_text = job['input_directory'] list_text = 'Job ' + str(job['job_id']) + ' \'' + input_directory_text + '\'' if job['start'] != None: list_text += ' ' + str(job['start']) if job['end'] != None: list_text += ' to' if job['end'] != None: list_text += ' ' + str(job['end']) if job['job_id'] > self.last_job_id: self.last_job_id = job['job_id'] self.job_list.insert(Tkinter.END, list_text) # Add the list text to the job params as an optional parameter to read later to display in a future Graph GUI (or for any other useful purpose) job['list_text'] = list_text # The line number is used wrt the GUI to indicate which job in the job list is being currently executed. job['line_number'] = self.job_list.size() - 1 #print str(job['line_number']) self.job_params[job['job_id']] = job except KeyError as ke: # Should show some error message indicating that there is a problem. pass #print str(self.job_params) #print 'Added Job ' + str(job['job_id']) def ask_to_clear_jobs(self, event): for job in self.job_params.itervalues(): line_number = job['line_number'] self.job_list.itemconfig(line_number, foreground='black') # Update parent to refresh widget appearance self.parent.update() # Reactivate process button self.process_button.config(state = Tkinter.NORMAL) # Note: Display a pop-up that tells the user that the job is done and asks if the job list should be cleared. clearList = msg.askyesno(title='Jobs Finished', message='All jobs have been completed. Would you like to clear the job list?', master=self) if clearList: self.clear_list() def ask_to_plot_graphs(self, event): # TODO: Add a dialog that also asks to create a graph of the 'Other Type Of Plot' plotGraphs = msg.askyesno(title='Plot Graphs', message='Create plots of data?', master=self) if not plotGraphs: return # TODO: Iterate through the jobs to display to the user an interface that asks if they want to graphs of the outputs if self.create_plots != None: output_files_list = list() for job_outcome in self.job_outcomes: for output_outcomes in job_outcome[2]: (station, output_directory, output_files) = output_outcomes for output_files_tuple in output_files: for output_file_tuple in output_files_tuple: (output_file, output_file_success) = output_file_tuple if output_file_success: # If there is a list text variable (the 4th (or 3rd by 0 based index) variable), then add it to our output list if len(job_outcome) == 4: output_files_list.append([output_file, job_outcome[3]]) else: output_files_list.append([output_file]) plots_thread = PlotsThread(self.create_plots, output_files_list, self) plots_thread.start() def add_plot(self, args=dict()): self.plot_args.append(args) def finished_adding_plots(self): self.event_generate('<<CreatePlotGUI>>', when='tail') def create_plot_gui(self, event): # TODO: This should be replaced with a new window that allows the user to drag and drop the icons from one frame to another graph_names = list() for args in self.plot_args: graph_name = args['output_file'] graph_names.append(graph_name) dnd_graphs_frame = Dnd.createFrame(self, 'Drag and Drop Output Plots', graph_names, self.finish_creating_plot_gui) # This is the entry point for the def finish_creating_plot_gui(self, plot_labels): graph_count = 1 for plot_label in plot_labels: for args in self.plot_args: #print 'Looking in ' + args['plot_title'] + ' for ' + plot_label #print 'The plot label is: ' + plot_label #print 'The output file is: ' + args['output_file'] if plot_label == args['output_file']: #print 'Creating graph ' + str(graph_count) graph_count += 1 graph_window = ModelRunnerGraphGUI.GraphWindow(parent=self, title=args['window_title'], df=args['df'], plot=args['plot'], plot_title=args['plot_title'], y_label=args['y_label'], log_filename=self.log_filename) graph_window.set_grid() self.top_level_windows.append(graph_window) #print 'Creating plot GUI # Have to clear out list here instead of clear_list because clear_list() removes plot_args before this method has a chance to read # them and create the appropriate plot graph windows self.reinit_variables() # Clear all the elements in the list def clear_list(self): # Save plot args because they are need later in this run plot_args = self.plot_args self.reinit_variables() # Restore the plot args self.plot_args = plot_args self.job_list.delete(0, self.job_list.size()) self.progress_value.set(0) # Update parent to refresh widget appearance self.parent.update() def on_add(self): single_job = JobParameters(parent=self.parent, beginning_year=1950, ending_year=2100, job_id=self.last_job_id + 1, entry=self) single_job.set_grid() def on_remove(self): selection = self.job_list.curselection() for line_number in selection: line_text = self.job_list.get(line_number) job_id = int(line_text[4:line_text.index(' ', 4)]) job = self.job_params.pop(job_id) self.job_list.delete(line_number) print 'Removed Job ' + str(job['job_id']) # Fix line number for line_number in range(self.job_list.size()): line_text = self.job_list.get(line_number) job_id = int(line_text[4:line_text.index(' ', 4)]) #print 'Job ' + str(job_id) + ' is now on line ' + str(line_number) self.job_params[job_id]['line_number'] = line_number def set_grid(self): self.grid(sticky=Tkinter.N + Tkinter.S + Tkinter.W + Tkinter.E, padx=4, pady=4) self.columnconfigure(0, minsize=600) self.rowconfigure(0, minsize=300) self.job_list.grid(row=0, column=0, sticky=Tkinter.N + Tkinter.S + Tkinter.E + Tkinter.W) self.job_list_yscroll.grid(row=0, column=1, sticky=Tkinter.N + Tkinter.S + Tkinter.W) self.job_list_xscroll.grid(row=1, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N) self.new_job_frame.grid(row=2, column=0, pady=3, sticky=Tkinter.W) self.remove_job_button.grid(row=0, column=0) self.add_job_button.grid(row=0, column=1) self.progress_frame.grid(row=3, column=0, pady=3) self.progress_frame.columnconfigure(0, minsize=600) self.progress_bar.grid(row=0, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S) self.button_frame.grid(row=4, column=0, sticky=Tkinter.E + Tkinter.W + Tkinter.N + Tkinter.S) self.button_frame.columnconfigure(0, minsize=300) self.button_frame.columnconfigure(1, minsize=300) self.process_button.pack(side=Tkinter.RIGHT) self.quit_button.pack(side=Tkinter.RIGHT) def start_jobs(self): # If there are no queued jobs then simply return if len(self.job_params) == 0 or len(self.job_list.get(0)) == 0: return # Deactivate the process button self.process_button.config(state = Tkinter.DISABLED) # Initialize the progress bar self.progress_value.set(0) # Update parent to refresh widget appearance self.parent.update() # Start process thread jobs_thread = JobsThread(self.job_params, self.run_job, self.on_update, self.on_resume) jobs_thread.start() self['cursor'] = 'wait' def on_update(self, status, line_number, step): if status == 'init': self.job_list.itemconfig(line_number, foreground='green') self.job_list.activate(line_number) elif status == 'success': self.job_list.itemconfig(line_number, foreground='blue') elif status == 'fail': self.job_list.itemconfig(line_number, foreground='red') self.progress_value.set(step) # Update parent to refresh widget appearance self.parent.update() def on_resume(self, job_outcomes=list()): self.progress_value.set(100) self.job_outcomes = job_outcomes self.event_generate('<<AskToClearJobs>>', when='tail') self.event_generate('<<AskToPlotGraphs>>', when='tail') self['cursor'] = 'arrow' def close_top_level_windows(self): #print 'Closing other top level windows' for top_level_window in self.top_level_windows: if top_level_window: top_level_window.withdraw() top_level_window.destroy() def notify_of_close(self, top_level_window): if top_level_window in self.top_level_windows: #print 'Removing top level window' self.top_level_windows.remove(top_level_window) def on_press(self, event): self.on_button = True self.release_pattern = "<B%d-ButtonRelease-%d>" % (event.num, event.num) self.parent.bind(self.release_pattern, self.on_release) def on_release(self, event): self.on_button = False def on_resize(self, event): self.parent.lift() if self.on_button: self.set_grid() def on_close(self): self.plot_args = list() self.withdraw() self.destroy()
class 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))
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()
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented") else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError("If not guiven complete function, list_of_items can't be 'None'") if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) def _on_tab(self, event): self.post_listbox() return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': self.unpost_listbox() self.focus() else: values = self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index +=1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break"
class Combobox_Autocomplete(Entry, object): def __init__(self, master, list_of_items=None, autocomplete_function=None, listbox_width=None, listbox_height=7, ignorecase_match=False, startswith_match=True, vscrollbar=True, hscrollbar=True, **kwargs): if hasattr(self, "autocomplete_function"): if autocomplete_function is not None: raise ValueError("Combobox_Autocomplete subclass has 'autocomplete_function' implemented") else: if autocomplete_function is not None: self.autocomplete_function = autocomplete_function else: if list_of_items is None: raise ValueError("If not guiven complete function, list_of_items can't be 'None'") if ignorecase_match: if startswith_match: def matches_function(entry_data, item): return item.startswith(entry_data) else: def matches_function(entry_data, item): return item in entry_data self.autocomplete_function = lambda entry_data: [item for item in self.list_of_items if matches_function(entry_data, item)] else: if startswith_match: def matches_function(escaped_entry_data, item): if re.match(escaped_entry_data, item, re.IGNORECASE): return True else: return False else: def matches_function(escaped_entry_data, item): if re.search(escaped_entry_data, item, re.IGNORECASE): return True else: return False def autocomplete_function(entry_data): escaped_entry_data = re.escape(entry_data) return [item for item in self.list_of_items if matches_function(escaped_entry_data, item)] self.autocomplete_function = autocomplete_function self._listbox_height = int(listbox_height) self._listbox_width = listbox_width self.list_of_items = list_of_items self._use_vscrollbar = vscrollbar self._use_hscrollbar = hscrollbar kwargs.setdefault("background", "white") if "textvariable" in kwargs: self._entry_var = kwargs["textvariable"] else: self._entry_var = kwargs["textvariable"] = StringVar() Entry.__init__(self, master, **kwargs) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) self._listbox = None self.bind("<Tab>", self._on_tab) self.bind("<Up>", self._previous) self.bind("<Down>", self._next) self.bind('<Control-n>', self._next) self.bind('<Control-p>', self._previous) self.bind("<Return>", self._update_entry_from_listbox) self.bind("<Escape>", lambda event: self.unpost_listbox()) #self.bind("<FocusOut>", lambda event: self.unpost_listbox()) def _on_tab(self, event): #self.post_listbox() self.unpost_listbox() #frmbill.cbouom.focus() #self._update_entry_from_listbox() #self.unpost_listbox() # if self._listbox is not None: # self._listbox.master.destroy() # self._listbox = None return "break" def _on_change_entry_var(self, name, index, mode): entry_data = self._entry_var.get() if entry_data == '': #print('test111') self.unpost_listbox() self.focus() else: if len(entry_data) < 3: return True values = finditem(entry_data) #kk #self.autocomplete_function(entry_data) if values: if self._listbox is None: self._build_listbox(values) else: self._listbox.delete(0, END) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) else: self.unpost_listbox() self.focus() def _build_listbox(self, values): listbox_frame = Frame() self._listbox = Listbox(listbox_frame, background="white", selectmode=SINGLE, activestyle="none", exportselection=False) self._listbox.grid(row=0, column=0,sticky = N+E+W+S) self._listbox.bind("<ButtonRelease-1>", self._update_entry_from_listbox) self._listbox.bind("<Return>", self._update_entry_from_listbox) self._listbox.bind("<Escape>", lambda event: self.unpost_listbox()) self._listbox.bind('<Control-n>', self._next) self._listbox.bind('<Control-p>', self._previous) if self._use_vscrollbar: vbar = Scrollbar(listbox_frame, orient=VERTICAL, command= self._listbox.yview) vbar.grid(row=0, column=1, sticky=N+S) self._listbox.configure(yscrollcommand= lambda f, l: autoscroll(vbar, f, l)) if self._use_hscrollbar: hbar = Scrollbar(listbox_frame, orient=HORIZONTAL, command= self._listbox.xview) hbar.grid(row=1, column=0, sticky=E+W) self._listbox.configure(xscrollcommand= lambda f, l: autoscroll(hbar, f, l)) listbox_frame.grid_columnconfigure(0, weight= 1) listbox_frame.grid_rowconfigure(0, weight= 1) x = -self.cget("borderwidth") - self.cget("highlightthickness") y = self.winfo_height()-self.cget("borderwidth") - self.cget("highlightthickness") if self._listbox_width: width = self._listbox_width else: width=self.winfo_width() listbox_frame.place(in_=self, x=x, y=y, width=width) height = min(self._listbox_height, len(values)) self._listbox.configure(height=height) for item in values: self._listbox.insert(END, item) def post_listbox(self): if self._listbox is not None: return entry_data = self._entry_var.get() if entry_data == '': return values = self.autocomplete_function(entry_data) if values: self._build_listbox(values) def unpost_listbox(self): if self._listbox is not None: self._listbox.master.destroy() self._listbox = None def get_value(self): return self._entry_var.get() def set_value(self, text, close_dialog=False): self._set_var(text) if close_dialog: self.unpost_listbox() self.icursor(END) self.xview_moveto(1.0) def _set_var(self, text): self._entry_var.trace_vdelete("w", self._trace_id) self._entry_var.set(text) self._trace_id = self._entry_var.trace('w', self._on_change_entry_var) if len(text) > 0: find_price(text) #kk def _update_entry_from_listbox(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if current_selection: text = self._listbox.get(current_selection) self._set_var(text) self._listbox.master.destroy() self._listbox = None self.focus() self.icursor(END) self.xview_moveto(1.0) return "break" def _previous(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == 0: index = END else: index -= 1 self._listbox.see(index) self._listbox.selection_set(first=index) self._listbox.activate(index) return "break" def _next(self, event): if self._listbox is not None: current_selection = self._listbox.curselection() if len(current_selection)==0: self._listbox.selection_set(0) self._listbox.activate(0) else: index = int(current_selection[0]) self._listbox.selection_clear(index) if index == self._listbox.size() - 1: index = 0 else: index +=1 self._listbox.see(index) self._listbox.selection_set(index) self._listbox.activate(index) return "break" # if __name__ == '__main__': # try: # from Tkinter import Tk # except ImportError: # from tkinter import Tk # list_of_items = ["Cordell Cannata", "Lacey Naples", "Zachery Manigault", "Regan Brunt", "Mario Hilgefort", "Austin Phong", "Moises Saum", "Willy Neill", "Rosendo Sokoloff", "Salley Christenberry", "Toby Schneller", "Angel Buchwald", "Nestor Criger", "Arie Jozwiak", "Nita Montelongo", "Clemencia Okane", "Alison Scaggs", "Von Petrella", "Glennie Gurley", "Jamar Callender", "Titus Wenrich", "Chadwick Liedtke", "Sharlene Yochum", "Leonida Mutchler", "Duane Pickett", "Morton Brackins", "Ervin Trundy", "Antony Orwig", "Audrea Yutzy", "Michal Hepp", "Annelle Hoadley", "Hank Wyman", "Mika Fernandez", "Elisa Legendre", "Sade Nicolson", "Jessie Yi", "Forrest Mooneyhan", "Alvin Widell", "Lizette Ruppe", "Marguerita Pilarski", "Merna Argento", "Jess Daquila", "Breann Bevans", "Melvin Guidry", "Jacelyn Vanleer", "Jerome Riendeau", "Iraida Nyquist", "Micah Glantz", "Dorene Waldrip", "Fidel Garey", "Vertie Deady", "Rosalinda Odegaard", "Chong Hayner", "Candida Palazzolo", "Bennie Faison", "Nova Bunkley", "Francis Buckwalter", "Georgianne Espinal", "Karleen Dockins", "Hertha Lucus", "Ike Alberty", "Deangelo Revelle", "Juli Gallup", "Wendie Eisner", "Khalilah Travers", "Rex Outman", "Anabel King", "Lorelei Tardiff", "Pablo Berkey", "Mariel Tutino", "Leigh Marciano", "Ok Nadeau", "Zachary Antrim", "Chun Matthew", "Golden Keniston", "Anthony Johson", "Rossana Ahlstrom", "Amado Schluter", "Delila Lovelady", "Josef Belle", "Leif Negrete", "Alec Doss", "Darryl Stryker", "Michael Cagley", "Sabina Alejo", "Delana Mewborn", "Aurelio Crouch", "Ashlie Shulman", "Danielle Conlan", "Randal Donnell", "Rheba Anzalone", "Lilian Truax", "Weston Quarterman", "Britt Brunt", "Leonie Corbett", "Monika Gamet", "Ingeborg Bello", "Angelique Zhang", "Santiago Thibeau", "Eliseo Helmuth"] # root = Tk() # root.geometry("300x200") # combobox_autocomplete = Combobox_Autocomplete(root, list_of_items, highlightthickness=1) # combobox_autocomplete.pack() # combobox_autocomplete.focus() # root.mainloop()
class 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)
class AutocompleteEntry(Entry): def __init__(self, *args, **kwargs): Entry.__init__(self, width=100, *args, **kwargs) self.focus_set() self.pack() self.var = self["textvariable"] if self.var == '': self.var = self["textvariable"] = StringVar() self.var.trace('w', self.changed) self.bind("<Right>", self.selection) self.bind("<Up>", self.up) self.bind("<Down>", self.down) self.bind("<Return>", self.enter) self.lb_up = False self.lb = None def enter(self, event): print event def changed(self, name, index, mode): if self.var.get() == '': if self.lb: self.lb.destroy() self.lb_up = False else: words = self.comparison() if words: if not self.lb_up: self.lb = Listbox(master=root, width=100) self.lb.bind("<Double-Button-1>", self.selection) self.lb.bind("<Right>", self.selection) self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height()) self.lb_up = True self.lb.delete(0, END) for w in words: self.lb.insert(END,w) else: if self.lb_up: self.lb.destroy() self.lb_up = False def selection(self, _): if self.lb_up: self.var.set(self.lb.get(ACTIVE)) self.lb.destroy() self.lb_up = False self.icursor(END) def up(self, _): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != '0': self.lb.selection_clear(first=index) index = str(int(index)-1) self.lb.selection_set(first=index) self.lb.activate(index) def down(self, _): if self.lb_up: if self.lb.curselection() == (): index = '0' else: index = self.lb.curselection()[0] if index != END: self.lb.selection_clear(first=index) index = str(int(index)+1) self.lb.selection_set(first=index) self.lb.activate(index) def comparison(self): q = self.var.get() q = unicode(q.decode('utf8')) for hit in searcher.search(qp.parse(q), limit=50): if hit['author']: yield '%s. "%s"' % (hit['author'], hit['title']) else: yield hit['title']
class Gamelist(): def __init__(self, drive, platform): GameListData.game_list_data_json = GameListData().get_game_list() self.json_game_list_data = GameListData.game_list_data_json if drive == 'USB(*)': self.drive_to_show = '/dev_' + drive.lower().replace('(*)', '') else: self.drive_to_show = '/dev_' + drive.lower() + '/' self.platform_to_show = platform + '_games' self.WCM_BASE_PATH = AppPaths.wcm_gui self.last_selection = (None, 0) self.list_of_items = [] self.selected_title_id = None self.selected_title = None self.selected_path = None self.selected_filename = None self.drive_system_path_array = None self.is_cleared = False def create_main_frame(self, entry_field_title_id, entry_field_title, entry_field_filename, entry_field_iso_path, entry_field_platform, drive_system_array): self.entry_field_title_id = entry_field_title_id self.entry_field_title = entry_field_title self.entry_field_filename = entry_field_filename self.entry_field_iso_path = entry_field_iso_path self.entry_field_platform = entry_field_platform self.drive_system_path_array = drive_system_array self.corrected_index = [] self.main_frame = Frame() self.popup_menu = Menu(self.main_frame, tearoff=0) self.popup_menu.add_command(label="Delete", command=self.delete_selected) self.popup_menu.add_command(label="Rename", command=self.rename_selected) # self.popup_menu.add_command(label="Refetch", # command=self.refetch) # self.popup_menu.add_command(label="Select All", # command=self.select_all) s = Scrollbar(self.main_frame) self._listbox = Listbox(self.main_frame, width=465) self._listbox.bind('<Enter>', self._bound_to_mousewheel) self._listbox.bind('<Leave>', self._unbound_to_mousewheel) self._listbox.bind("<Button-3>", self.popup) # Button-2 on Aqua s.pack(side=RIGHT, fill=Y) self._listbox.pack(side=LEFT, fill=Y) s['command'] = self._listbox.yview self._listbox['yscrollcommand'] = s.set # default filters if 'ALL_games' == self.platform_to_show: # iterate all platforms for platform in self.json_game_list_data: for list_game in self.json_game_list_data[platform]: # titles in the list has been designed to be unique if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']: self.add_item(list_game['title']) else: for list_game in self.json_game_list_data[self.platform_to_show]: if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']: self.add_item(list_game['title']) for x in range(19 - self._listbox.size()): self.add_item('') # adding shade to every other row of the list for x in range(0, self._listbox.size()): if x % 2 == 0: self._listbox.itemconfig(x, {'fg': 'white'}, background='#001738') else: self._listbox.itemconfig(x, {'fg': 'white'}, background='#001F4C') self.label = Label(self.main_frame) self.selection_poller() return self.main_frame def selection_poller(self): self.label.after(200, self.selection_poller) self.new_selection = self._listbox.curselection() # cursor har been initiated if self._listbox.curselection() is not (): if self.new_selection[0] is not self.last_selection[0] or self.is_cleared: self.entry_fields_update(self.new_selection) self.is_cleared = False self.last_selection = self.new_selection def entry_fields_update(self, new_selection): for platform in self.json_game_list_data: for list_game in self.json_game_list_data[platform]: self.selected_title = self._listbox.get(new_selection[0]) tmp_title = list_game['title'] match = self.selected_title == str(tmp_title) if match: self.selected_title_id = str(list_game['title_id']).replace('-', '') self.selected_title = str(list_game['title']) self.selected_path = str(list_game['path']) self.selected_filename = str(list_game['filename']) self.selected_platform = str(list_game['platform']) # parse drive and system from json data path_array = filter(None, self.selected_path.split('/')) self.drive_system_path_array[0] = path_array[0] self.drive_system_path_array[1] = path_array[1] self.drive_system_path_array[2] = '/'.join(path_array[2:len(path_array)]).replace('//', '') self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1) self.entry_field_title_id.delete(0, END) self.entry_field_title_id.insert(0, self.selected_title_id) self.entry_field_title.delete(0, END) self.entry_field_title.insert(0, self.selected_title) self.entry_field_filename.delete(0, END) self.entry_field_filename.insert(0, self.selected_filename) self.entry_field_platform.delete(0, END) self.entry_field_platform.insert(0, self.selected_platform) return True def get_selected_path(self): return self.current_iso_path def get_listbox(self): return self._listbox def get_ascending_index(self, list_of_items, item, ignore_case=True): lo = 0 hi = len(list_of_items) if ignore_case: item = item.lower() while lo < hi: mid = (lo + hi) // 2 if item < list_of_items[mid].lower(): hi = mid else: lo = mid + 1 else: while lo < hi: mid = (lo + hi) // 2 if item < list_of_items[mid]: hi = mid else: lo = mid + 1 return lo def add_item(self, item): if item != '': self.list_of_items = self._listbox.get(0, END) # getting ascending index in order to sort alphabetically index = self.get_ascending_index(self.list_of_items, item) self._listbox.insert(index, item) else: self._listbox.insert(END, item) def get_items(self): return self.list_of_items def _bound_to_mousewheel(self, event): self._listbox.bind_all("<MouseWheel>", self._on_mousewheel) def _unbound_to_mousewheel(self, event): self._listbox.unbind_all("<MouseWheel>") def _on_mousewheel(self, event): self._listbox.yview_scroll(int(-1*(event.delta/30)), "units") def popup(self, event): try: self._listbox.selection_clear(0, END) self._listbox.selection_set(self._listbox.nearest(event.y)) self._listbox.activate(self._listbox.nearest(event.y)) finally: if self._listbox.get(self._listbox.curselection()[0]) is not '': self.popup_menu.tk_popup(event.x_root + 43, event.y_root + 12, 0) self.popup_menu.grab_release() self.popup_menu.focus_set() def delete_selected(self): import tkMessageBox game_folder_path = os.path.join(AppPaths.game_work_dir, '..') response = tkMessageBox.askyesno('Delete game folder', 'Delete \'' + self.entry_field_title.get() + '\'?\n\nFolder path: ' + os.path.realpath(game_folder_path)) # yes if response: # remove game from visual game list for i in self._listbox.curselection()[::-1]: self._listbox.delete(i) removed_index = i # remove game from json game list platform_key = self.entry_field_platform.get() + '_games' self.json_game_list_data[platform_key] = [x for x in self.json_game_list_data[platform_key] if x['title'] != self.selected_title] # update the json game list file with open(GameListData.GAME_LIST_DATA_PATH, 'w') as newFile: json_text = json.dumps(self.json_game_list_data, indent=4, separators=(",", ":")) newFile.write(json_text) # remove the game build folder too if AppPaths.game_work_dir != os.path.join(AppPaths.wcm_gui, 'work_dir'): if os.path.isdir(game_folder_path): if 'webman-classics-maker' in game_folder_path: shutil.rmtree(game_folder_path) # clear entry_fields self.clear_entries_and_path() # set cursor self._listbox.select_set(removed_index) #This only sets focus on the first item. def rename_selected(self): self.entry_field_title.selection_range(0, END) self.entry_field_title.focus_set() def select_all(self): self._listbox.selection_set(0, 'end') def clear_entries_and_path(self): self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1) self.entry_field_title_id.delete(0, END) self.entry_field_title.delete(0, END) self.entry_field_platform.delete(0, END) self.entry_field_filename.delete(0, END) self.is_cleared = True def get_selected_build_dir_path(self): self.build_dir_path = '' if self.selected_filename not in {'', None}: filename = self.selected_filename title_id = self.selected_title_id.replace('-', '') build_base_path = AppPaths.builds tmp_filename = filename # removes the file extension from tmp_filename for file_ext in GlobalVar.file_extensions: if filename.upper().endswith(file_ext): tmp_filename = filename[0:len(filename)-len(file_ext)] break game_folder_name = tmp_filename.replace(' ', '_') + '_(' + title_id.replace('-', '') + ')' self.build_dir_path = os.path.join(build_base_path, game_folder_name) return self.build_dir_path
class LintGui(object): """Build and control a window to interact with pylint""" def __init__(self, root=None): """init""" self.root = root or Tk() self.root.title('Pylint') #reporter self.reporter = None #message queue for output from reporter self.msg_queue = Queue.Queue() self.msgs = [] self.visible_msgs = [] self.filenames = [] self.rating = StringVar() self.tabs = {} self.report_stream = BasicStream(self) self.differ = differ.Differ() #gui objects self.lbMessages = None self.showhistory = None self.results = None self.btnRun = None self.information_box = None self.convention_box = None self.refactor_box = None self.warning_box = None self.error_box = None self.fatal_box = None self.txtModule = None self.status = None self.msg_type_dict = None self.init_gui() def init_gui(self): """init helper""" #setting up frames top_frame = Frame(self.root) mid_frame = Frame(self.root) radio_frame = Frame(self.root) res_frame = Frame(self.root) msg_frame = Frame(self.root) check_frame = Frame(self.root) history_frame = Frame(self.root) btn_frame = Frame(self.root) rating_frame = Frame(self.root) top_frame.pack(side=TOP, fill=X) mid_frame.pack(side=TOP, fill=X) history_frame.pack(side=TOP, fill=BOTH, expand=True) radio_frame.pack(side=TOP, fill=BOTH, expand=True) rating_frame.pack(side=TOP, fill=BOTH, expand=True) res_frame.pack(side=TOP, fill=BOTH, expand=True) check_frame.pack(side=TOP, fill=BOTH, expand=True) msg_frame.pack(side=TOP, fill=BOTH, expand=True) btn_frame.pack(side=TOP, fill=X) # Binding F5 application-wide to run lint self.root.bind('<F5>', self.run_lint) #Message ListBox rightscrollbar = Scrollbar(msg_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.lbMessages = Listbox(msg_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white") self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile) self.lbMessages.pack(expand=True, fill=BOTH) rightscrollbar.config(command=self.lbMessages.yview) bottomscrollbar.config(command=self.lbMessages.xview) #Message context menu self.mnMessages = Menu(self.lbMessages, tearoff=0) self.mnMessages.add_command(label="View in sourcefile", command=self.show_sourcefile) self.mnMessages.add_command(label="Add to ignore patchfile", command=self.add_to_ignore_patchfile) self.lbMessages.bind("<Button-3>", self.show_messages_context) #History ListBoxes rightscrollbar2 = Scrollbar(history_frame) rightscrollbar2.pack(side=RIGHT, fill=Y) bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL) bottomscrollbar2.pack(side=BOTTOM, fill=X) self.showhistory = Listbox(history_frame, yscrollcommand=rightscrollbar2.set, xscrollcommand=bottomscrollbar2.set, bg="white") self.showhistory.pack(expand=True, fill=BOTH) rightscrollbar2.config(command=self.showhistory.yview) bottomscrollbar2.config(command=self.showhistory.xview) self.showhistory.bind('<Double-Button-1>', self.select_recent_file) self.set_history_window() #status bar self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W) self.status.pack(side=BOTTOM, fill=X) #labels self.lblRatingLabel = Label(rating_frame, text='Rating:') self.lblRatingLabel.pack(side=LEFT) self.lblRating = Label(rating_frame, textvariable=self.rating) self.lblRating.pack(side=LEFT) Label(mid_frame, text='Recently Used:').pack(side=LEFT) Label(top_frame, text='Module or package').pack(side=LEFT) #file textbox self.txtModule = Entry(top_frame, background='white') self.txtModule.bind('<Return>', self.run_lint) self.txtModule.pack(side=LEFT, expand=True, fill=X) #results box rightscrollbar = Scrollbar(res_frame) rightscrollbar.pack(side=RIGHT, fill=Y) bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL) bottomscrollbar.pack(side=BOTTOM, fill=X) self.results = Listbox(res_frame, yscrollcommand=rightscrollbar.set, xscrollcommand=bottomscrollbar.set, bg="white", font="Courier") self.results.pack(expand=True, fill=BOTH, side=BOTTOM) rightscrollbar.config(command=self.results.yview) bottomscrollbar.config(command=self.results.xview) #buttons Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT) Button(top_frame, text='Open Package', command=(lambda : self.file_open(package=True))).pack(side=LEFT) self.btnRun = Button(top_frame, text='Run', command=self.run_lint) self.btnRun.pack(side=LEFT) Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM) #radio buttons self.information_box = IntVar() self.convention_box = IntVar() self.refactor_box = IntVar() self.warning_box = IntVar() self.error_box = IntVar() self.fatal_box = IntVar() i = Checkbutton(check_frame, text="Information", fg=COLORS['(I)'], variable=self.information_box, command=self.refresh_msg_window) c = Checkbutton(check_frame, text="Convention", fg=COLORS['(C)'], variable=self.convention_box, command=self.refresh_msg_window) r = Checkbutton(check_frame, text="Refactor", fg=COLORS['(R)'], variable=self.refactor_box, command=self.refresh_msg_window) w = Checkbutton(check_frame, text="Warning", fg=COLORS['(W)'], variable=self.warning_box, command=self.refresh_msg_window) e = Checkbutton(check_frame, text="Error", fg=COLORS['(E)'], variable=self.error_box, command=self.refresh_msg_window) f = Checkbutton(check_frame, text="Fatal", fg=COLORS['(F)'], variable=self.fatal_box, command=self.refresh_msg_window) i.select() c.select() r.select() w.select() e.select() f.select() i.pack(side=LEFT) c.pack(side=LEFT) r.pack(side=LEFT) w.pack(side=LEFT) e.pack(side=LEFT) f.pack(side=LEFT) #check boxes self.box = StringVar() # XXX should be generated report = Radiobutton(radio_frame, text="Report", variable=self.box, value="Report", command=self.refresh_results_window) rawMet = Radiobutton(radio_frame, text="Raw metrics", variable=self.box, value="Raw metrics", command=self.refresh_results_window) dup = Radiobutton(radio_frame, text="Duplication", variable=self.box, value="Duplication", command=self.refresh_results_window) ext = Radiobutton(radio_frame, text="External dependencies", variable=self.box, value="External dependencies", command=self.refresh_results_window) stat = Radiobutton(radio_frame, text="Statistics by type", variable=self.box, value="Statistics by type", command=self.refresh_results_window) msgCat = Radiobutton(radio_frame, text="Messages by category", variable=self.box, value="Messages by category", command=self.refresh_results_window) msg = Radiobutton(radio_frame, text="Messages", variable=self.box, value="Messages", command=self.refresh_results_window) sourceFile = Radiobutton(radio_frame, text="Source File", variable=self.box, value="Source File", command=self.refresh_results_window) report.select() report.grid(column=0, row=0, sticky=W) rawMet.grid(column=1, row=0, sticky=W) dup.grid(column=2, row=0, sticky=W) msg.grid(column=3, row=0, sticky=W) stat.grid(column=0, row=1, sticky=W) msgCat.grid(column=1, row=1, sticky=W) ext.grid(column=2, row=1, sticky=W) sourceFile.grid(column=3, row=1, sticky=W) #dictionary for check boxes and associated error term self.msg_type_dict = { 'I' : lambda : self.information_box.get() == 1, 'C' : lambda : self.convention_box.get() == 1, 'R' : lambda : self.refactor_box.get() == 1, 'E' : lambda : self.error_box.get() == 1, 'W' : lambda : self.warning_box.get() == 1, 'F' : lambda : self.fatal_box.get() == 1 } self.txtModule.focus_set() def select_recent_file(self, event): """adds the selected file in the history listbox to the Module box""" if not self.showhistory.size(): return selected = self.showhistory.curselection() item = self.showhistory.get(selected) #update module self.txtModule.delete(0, END) self.txtModule.insert(0, item) def refresh_msg_window(self): """refresh the message window with current output""" #clear the window self.lbMessages.delete(0, END) self.visible_msgs = [] for msg in self.msgs: if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) def refresh_results_window(self): """refresh the results window with current output""" #clear the window self.results.delete(0, END) try: for res in self.tabs[self.box.get()]: self.results.insert(END, res) except: pass def process_incoming(self): """process the incoming messages from running pylint""" while self.msg_queue.qsize(): try: msg = self.msg_queue.get(0) if msg == "DONE": self.report_stream.output_contents() return False #adding message to list of msgs self.msgs.append(msg) #displaying msg if message type is selected in check box if (self.msg_type_dict.get(msg.C)()): self.visible_msgs.append(msg) msg_str = convert_to_string(msg) self.lbMessages.insert(END, msg_str) fg_color = COLORS.get(msg_str[:3], 'black') self.lbMessages.itemconfigure(END, fg=fg_color) except Queue.Empty: pass return True def periodic_call(self): """determine when to unlock the run button""" if self.process_incoming(): self.root.after(100, self.periodic_call) else: #enabling button so it can be run again self.btnRun.config(state=NORMAL) def mainloop(self): """launch the mainloop of the application""" self.root.mainloop() def quit(self, _=None): """quit the application""" self.root.quit() def halt(self): """program halt placeholder""" return def file_open(self, package=False, _=None): """launch a file browser""" if not package: filename = askopenfilename(parent=self.root, filetypes=[('pythonfiles', '*.py'), ('allfiles', '*')], title='Select Module') else: filename = askdirectory(title="Select A Folder", mustexist=1) if filename == (): return self.txtModule.delete(0, END) self.txtModule.insert(0, filename) def update_filenames(self): """update the list of recent filenames""" filename = self.txtModule.get() if not filename: filename = os.getcwd() if filename+'\n' in self.filenames: index = self.filenames.index(filename+'\n') self.filenames.pop(index) #ensure only 10 most recent are stored if len(self.filenames) == 10: self.filenames.pop() self.filenames.insert(0, filename+'\n') def set_history_window(self): """update the history window with info from the history file""" #clear the window self.showhistory.delete(0, END) # keep the last 10 most recent files try: view_history = open(HOME+HISTORY, 'r') for hist in view_history.readlines(): if not hist in self.filenames: self.filenames.append(hist) self.showhistory.insert(END, hist.split('\n')[0]) view_history.close() except IOError: # do nothing since history file will be created later return def run_lint(self, _=None): """launches pylint""" self.update_filenames() self.root.configure(cursor='watch') self.reporter = GUIReporter(self, output=self.report_stream) module = self.txtModule.get() if not module: module = os.getcwd() #cleaning up msgs and windows self.msgs = [] self.visible_msgs = [] self.lbMessages.delete(0, END) self.tabs = {} self.results.delete(0, END) self.btnRun.config(state=DISABLED) #setting up a worker thread to run pylint worker = Thread(target=lint_thread, args=(module, self.reporter, self,)) self.periodic_call() worker.start() # Overwrite the .pylint-gui-history file with all the new recently added files # in order from filenames but only save last 10 files write_history = open(HOME+HISTORY, 'w') write_history.writelines(self.filenames) write_history.close() self.set_history_window() self.root.configure(cursor='') def show_sourcefile(self, event=None): selected = self.lbMessages.curselection() if not selected: return msg = self.visible_msgs[int(selected[0])] scroll = msg.line - 3 if scroll < 0: scroll = 0 self.tabs["Source File"] = open(msg.abspath, "r").readlines() self.box.set("Source File") self.refresh_results_window() self.results.yview(scroll) self.results.select_set(msg.line - 1) def show_messages_context(self, event): """Show the message listbox's context menu""" # Select the item that was clicked index = self.lbMessages.nearest(event.y) self.lbMessages.selection_clear(0, END); self.lbMessages.selection_set(index) self.lbMessages.activate(index) self.mnMessages.tk_popup(event.x_root, event.y_root) def add_to_ignore_patchfile(self, event=None): """ Add the selected message to the ignore patchfile. This means that this message will now be ignored by pylint-patcher. """ selected = self.lbMessages.curselection() if not selected: return selected_index = int(selected[0]) msg = self.visible_msgs[selected_index] self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol) self.differ.diff() del self.msgs[self.msgs.index(msg)] del self.visible_msgs[selected_index] self.lbMessages.delete(selected_index)
class 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")
class ListFrame(LabelFrame): """ A Frame representing one of the search term lists (e.g. Hashtags, Excluded Users). Displays all the items in the list, and allows the user to add or remove items. Methods should not be called directly; instead they should be bound as event handlers. """ def __init__(self, name, add_handler, remove_handler, master=None): """ Creates a ListFrame with the given name as its title. add_handler and remove_handler are functions to be called when items are added or removed, and should relay the information back to the Searcher (or whatever object actually uses the list). """ LabelFrame.__init__(self, master) self['text'] = name self.add_handler = add_handler self.remove_handler = remove_handler self.list = Listbox(self) self.list.grid(row=0, columnspan=2) # Tkinter does not automatically close the right-click menu for us, # so we must close it when the user clicks away from the menu. self.list.bind("<Button-1>", lambda event: self.context_menu.unpost()) self.list.bind("<Button-3>", self.open_menu) self.context_menu = Menu(self, tearoff=0) self.context_menu.add_command(label="Remove", command=self.remove) self.input = Entry(self) self.input.bind("<Return>", lambda event: self.add()) self.input.grid(row=1, columnspan=2) self.add_button = Button(self) self.add_button['text'] = "Add" self.add_button['command'] = self.add self.add_button.grid(row=2, column=0, sticky=W + E) self.remove_button = Button(self) self.remove_button['text'] = "Remove" self.remove_button['command'] = self.remove self.remove_button.grid(row=2, column=1, sticky=W + E) def add(self): """ Add the item in the input line to the list. """ self.list.insert(END, self.input.get()) self.add_handler(self.input.get()) self.input.delete(0, END) def remove(self): """ Remove the active (highlighted) item from the list. """ deleted = self.list.get(ACTIVE) self.list.delete(ACTIVE) self.remove_handler(deleted) def open_menu(self, event): """ Opens a right-click menu for the selected item. Currently the menu only has an option for removing the item. """ index = self.list.index("@" + str(event.x) + "," + str(event.y)) if index < 0: return self.context_menu.post(event.x_root, event.y_root) self.list.activate(index) self.list.selection_clear(0, END) self.list.selection_set(ACTIVE)
class AutocompleteEntry(Entry): def __init__(self, autocompleteList, *args, **kwargs): # Listbox length self.listboxLength = kwargs.pop('listboxLength', 12) self.listboxFontSize = tkFont.Font(size=18) # Custom matches function if 'matchesFunction' in kwargs: self.matchesFunction = kwargs['matchesFunction'] del kwargs['matchesFunction'] else: def matches(fieldValue, acListEntry): pattern = re.compile('.*' + re.escape(fieldValue) + '.*', re.IGNORECASE) return re.match(pattern, acListEntry) self.matchesFunction = matches Entry.__init__(self, *args, **kwargs) self.focus() self.autocompleteList = autocompleteList self.var = self["textvariable"] if self.var == '': self.var = self["textvariable"] = StringVar() self.var.trace('w', self.changed) self.bind("<Return>", self.selection) self.bind("<Up>", self.moveUp) self.bind("<Down>", self.moveDown) self.listboxUp = False def update_content_text(self, event): w = event.widget try: index = int(w.curselection()[0]) except IndexError: return value = w.get(index) clipboard_content = autocompleteList.get(value)[0] content['text'] = clipboard_content def changed(self, name, index, mode): if self.var.get() == '': if self.listboxUp: content['text'] = '' self.listbox.destroy() self.listboxUp = False else: words = self.comparison() if words: if not self.listboxUp: self.listbox = Listbox(width=self["width"], height=self.listboxLength, font=self.listboxFontSize) self.listbox.bind('<<ListboxSelect>>', self.update_content_text) self.listbox.bind("<Return>", self.selection) self.listbox.place(x=self.winfo_x(), y=self.winfo_y() + self.winfo_height()) self.listboxUp = True self.listbox.delete(0, END) for w in words: self.listbox.insert(END, w) self.listbox.see(0) # Scroll! self.listbox.selection_set(first=0) value = self.listbox.get(ACTIVE) clipboard_content = autocompleteList.get(value)[0] content['text'] = clipboard_content else: if self.listboxUp: content['text'] = '' self.listbox.destroy() self.listboxUp = False def selection(self, event): if self.listboxUp: self.var.set(self.listbox.get(ACTIVE)) value = self.listbox.get(ACTIVE) data = autocompleteList.get(value) content = data[0] is_command = data[1] is_website = data[2] if is_command == '1': self.execute(content) elif is_website == '1': self.open_website(content) self.listbox.destroy() self.listboxUp = False self.icursor(END) self.copy_value(content) self.quit() def open_website(self, url): webbrowser.open(url) def execute(self, command): p = subprocess.Popen(command, bufsize=2048, shell=True, stdin=subprocess.PIPE) (output, err) = p.communicate() p_status = p.wait() def copy_value(self, value): clipboard.copy(value) def moveUp(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] if index != '0': self.listbox.selection_clear(first=index) index = str(int(index) - 1) self.listbox.see(index) # Scroll! self.listbox.selection_set(first=index) self.listbox.activate(index) self.listbox.event_generate("<<ListboxSelect>>", when="tail") def moveDown(self, event): if self.listboxUp: if self.listbox.curselection() == (): index = '0' else: index = self.listbox.curselection()[0] if index != END: self.listbox.selection_clear(first=index) index = str(int(index) + 1) self.listbox.see(index) self.listbox.selection_set(first=index) self.listbox.activate(index) self.listbox.event_generate("<<ListboxSelect>>", when="tail") def quit(self): root.quit() def comparison(self): return [ w for w in self.autocompleteList if self.matchesFunction(self.var.get(), w) ]
class ListFrame(LabelFrame): """ A Frame representing one of the search term lists (e.g. Hashtags, Excluded Users). Displays all the items in the list, and allows the user to add or remove items. Methods should not be called directly; instead they should be bound as event handlers. """ def __init__(self, name, add_handler, remove_handler, master=None): """ Creates a ListFrame with the given name as its title. add_handler and remove_handler are functions to be called when items are added or removed, and should relay the information back to the Searcher (or whatever object actually uses the list). """ LabelFrame.__init__(self, master) self['text'] = name self.add_handler = add_handler self.remove_handler = remove_handler self.list = Listbox(self) self.list.grid(row=0, columnspan=2) # Tkinter does not automatically close the right-click menu for us, # so we must close it when the user clicks away from the menu. self.list.bind("<Button-1>", lambda event: self.context_menu.unpost()) self.list.bind("<Button-3>", self.open_menu) self.context_menu = Menu(self, tearoff=0) self.context_menu.add_command(label="Remove", command=self.remove) self.input = Entry(self) self.input.bind("<Return>", lambda event: self.add()) self.input.grid(row=1, columnspan=2) self.add_button = Button(self) self.add_button['text'] = "Add" self.add_button['command'] = self.add self.add_button.grid(row=2, column=0, sticky=W+E) self.remove_button = Button(self) self.remove_button['text'] = "Remove" self.remove_button['command'] = self.remove self.remove_button.grid(row=2, column=1, sticky=W+E) def add(self): """ Add the item in the input line to the list. """ self.list.insert(END, self.input.get()) self.add_handler(self.input.get()) self.input.delete(0, END) def remove(self): """ Remove the active (highlighted) item from the list. """ deleted = self.list.get(ACTIVE) self.list.delete(ACTIVE) self.remove_handler(deleted) def open_menu(self, event): """ Opens a right-click menu for the selected item. Currently the menu only has an option for removing the item. """ index = self.list.index("@" + str(event.x) + "," + str(event.y)) if index < 0: return self.context_menu.post(event.x_root, event.y_root) self.list.activate(index) self.list.selection_clear(0, END) self.list.selection_set(ACTIVE)