Exemple #1
0
class GUI:
    def _run(self):
        self.saveBtn.config(state=DISABLED)
        self.progressTxt.config(state=NORMAL)
        self.progressTxt.delete('1.0', END)
        self.progressTxt.update()
        self.progressTxt.config(state=DISABLED)
        inputId = self.txEntry.get()
        item = map(int, self.dbLbox.curselection())
        db = self.dbids[item[0]]
        self.runBtn.config(state=DISABLED)
        self.inputId, self.inputName, self.hprobes = main(inputId,
                                                          db,
                                                          debug=self.debug,
                                                          txt=self.progressTxt)
        self.runBtn.config(state=NORMAL)
        if self.hprobes is not None:
            self.saveBtn.config(state=NORMAL)

    def _quitGUI(self):
        #rpath = self.progressTxt.get('8.0','end-1c')
        #if rpath.startswith('Your results'):
        #  tkMessageBox.showinfo("Quit", self.progressTxt.get('8.0','end-1c'))
        self.master.destroy()

    def _save(self):
        hps = filter_probes(self.hprobes, self.spec.get(), self.mingc.get(),
                            self.multiexon.get(), self.mintm.get(),
                            self.maxtm.get(), self.mindimer.get(),
                            self.minfold.get(), self.maxduplex.get())
        result_csv = write_probesCSV(self.inputId, self.inputName, hps,
                                     self.progressTxt)
        result_fna = write_probesFNA(self.inputId, self.inputName, hps,
                                     self.progressTxt)
        tkMessageBox.showinfo('Result file',
                              'Details on ' + str(len(hps)) + \
                              ' hybridization probe(s) were exported to ' + \
                              result_csv + "\n\n" + \
                              'Sequences of '+ str(len(hps)) + \
                              ' hybridization probe(s) were exported to ' + \
                              result_fna)

    def __init__(self, master, dbnames, dbids, debug, version):
        self.dbids = dbids
        self.debug = debug

        self.master = master
        master.title('Plish Probe Designer')

        self.logoImg = PhotoImage(file=get_script_path() +
                                  '/img/plishLogo.gif')
        self.logoLbl = Label(master, image=self.logoImg)
        self.logoLbl.grid(row=0, columnspan=3)
        self.logoLbl.img = self.logoImg

        self.dbLbl = Label(master, text='Database')
        self.dbLbl.grid(row=1, sticky=W + N)
        self.dbLbox = Listbox(master, width=63, height=4)
        self.dbLbox.configure(exportselection=False)

        for i in range(len(dbnames)):
            self.dbLbox.insert(i, dbnames[i])
        self.dbLbox.select_set(0)
        self.dbLbox.grid(row=1, column=1, columnspan=2, sticky=N)

        self.txLbl = Label(master, text='Transcript ID')
        self.txLbl.grid(row=2, sticky=W + N)
        self.txEntry = Entry(master, width=39)
        self.txEntry.grid(row=2, column=1, sticky=W + N)

        self.runBtn = Button(master, text='Run', command=self._run, width=15)
        self.runBtn.grid(row=2, column=2)

        self.progressLbl = Label(master, text='Progress')
        self.progressLbl.grid(row=4, sticky=W + N)
        self.progressTxt = Text(bg="#263238",
                                fg="#ffffff",
                                state=DISABLED,
                                width=51,
                                height=16)
        self.progressTxt.grid(row=4, column=1)

        self.saveBtn = Button(master,
                              text='Save',
                              command=self._save,
                              state=DISABLED,
                              width=15)
        self.saveBtn.grid(row=5, column=2, sticky=N)

        self.quitBtn = Button(master,
                              text='Quit',
                              command=self._quitGUI,
                              width=15)
        self.quitBtn.grid(row=6, column=2, sticky=N)

        self.aboutLF = LabelFrame(master, text='About', width=300)
        self.aboutLF.grid(row=5,
                          column=0,
                          rowspan=2,
                          columnspan=2,
                          sticky=N + W)
        self.versionLbl = Label(self.aboutLF, text='PLISH Probe Designer, Version ' + version + '\n' + \
                          '(c) Heller lab, Stanford University School of Medicine\n' + \
                          '     Daniel C. Ellwanger <*****@*****.**>                       ',
                          justify=LEFT)
        self.versionLbl.grid(row=0, column=0, sticky=N)

        # Filter
        self.filterLF = LabelFrame(master, text='Filter')
        self.filterLF.grid(row=4, column=2, rowspan=2, sticky=N + W)

        self.mingc = DoubleVar()
        self.mingc.set(_defaultGC)
        self.mingcLbl = Label(self.filterLF, text='Min. GC')
        self.mingcLbl.grid(row=0, column=0, sticky=N + W)
        self.mingcEntry = Entry(self.filterLF, width=5, text=self.mingc)
        self.mingcEntry.grid(row=0, column=1, sticky=N + W)
        self.mingcLbl2 = Label(self.filterLF, text='%')
        self.mingcLbl2.grid(row=0, column=2, sticky=N + W)

        self.spec = StringVar(master)
        self.spec.set("isoform")
        self.specLbl = Label(self.filterLF, text='Specificity')
        self.specLbl.grid(row=1, column=0, sticky=N + W)
        self.specOm = OptionMenu(self.filterLF, self.spec, "isoform", "gene",
                                 "none")
        self.specOm.grid(row=1, column=1, sticky=N + W, columnspan=2)

        self.mintm = DoubleVar()
        self.mintm.set(_defaultMinTm)
        self.mintmLbl = Label(self.filterLF, text='Min. Tm')
        self.mintmLbl.grid(row=2, column=0, sticky=N + W)
        self.mintmEntry = Entry(self.filterLF, width=5, text=self.mintm)
        self.mintmEntry.grid(row=2, column=1, sticky=N + W)
        self.mintmLbl2 = Label(self.filterLF, text=u'\N{DEGREE SIGN}' + 'C')
        self.mintmLbl2.grid(row=2, column=2, sticky=N + W)

        self.maxtm = DoubleVar()
        self.maxtm.set(_defaultMaxTm)
        self.maxtmLbl = Label(self.filterLF, text='Max. Tm')
        self.maxtmLbl.grid(row=3, column=0, sticky=N + W)
        self.maxtmEntry = Entry(self.filterLF, width=5, text=self.maxtm)
        self.maxtmEntry.grid(row=3, column=1, sticky=N + W)
        self.maxtmLbl2 = Label(self.filterLF, text=u'\N{DEGREE SIGN}' + 'C')
        self.maxtmLbl2.grid(row=3, column=2, sticky=N + W)

        self.minfold = DoubleVar()
        self.minfold.set(_defaultMinFold)
        self.minfoldLbl = Label(self.filterLF, text='Min. Fold')
        self.minfoldLbl.grid(row=4, column=0, sticky=N + W)
        self.minfoldEntry = Entry(self.filterLF, width=5, text=self.minfold)
        self.minfoldEntry.grid(row=4, column=1, sticky=N + W)
        self.minfoldLbl2 = Label(self.filterLF, text='kcal/mol')
        self.minfoldLbl2.grid(row=4, column=2, sticky=N + W)

        self.mindimer = DoubleVar()
        self.mindimer.set(_defaultMinDimer)
        self.mindimerLbl = Label(self.filterLF, text='Min. Dimer')
        self.mindimerLbl.grid(row=5, column=0, sticky=N + W)
        self.mindimerEntry = Entry(self.filterLF, width=5, text=self.mindimer)
        self.mindimerEntry.grid(row=5, column=1, sticky=N + W)
        self.mindimerLbl2 = Label(self.filterLF, text='kcal/mol')
        self.mindimerLbl2.grid(row=5, column=2, sticky=N + W)

        self.maxduplex = DoubleVar()
        self.maxduplex.set(_defaultMaxDuplex)
        self.maxduplexLbl = Label(self.filterLF, text='Max. Duplex')
        self.maxduplexLbl.grid(row=6, column=0, sticky=N + W)
        self.maxduplexEntry = Entry(self.filterLF,
                                    width=5,
                                    text=self.maxduplex)
        self.maxduplexEntry.grid(row=6, column=1, sticky=N + W)
        self.maxduplexLbl2 = Label(self.filterLF, text='kcal/mol')
        self.maxduplexLbl2.grid(row=6, column=2, sticky=N + W)

        self.multiexon = BooleanVar()
        self.multiexon.set(_defaultMultiExon)
        self.multiexonCb = Checkbutton(self.filterLF,
                                       text='Multi-exon',
                                       variable=self.multiexon,
                                       onvalue=True,
                                       offvalue=False)
        self.multiexonCb.grid(row=7, column=0, sticky=N + W)
Exemple #2
0
class LintGui(object):
    """Build and control a window to interact with pylint"""
    def __init__(self, root=None):
        """init"""
        self.root = root or Tk()
        self.root.title('Pylint')
        #reporter
        self.reporter = None
        #message queue for output from reporter
        self.msg_queue = Queue.Queue()
        self.msgs = []
        self.visible_msgs = []
        self.filenames = []
        self.rating = StringVar()
        self.tabs = {}
        self.report_stream = BasicStream(self)
        self.differ = differ.Differ()
        #gui objects
        self.lbMessages = None
        self.showhistory = None
        self.results = None
        self.btnRun = None
        self.information_box = None
        self.convention_box = None
        self.refactor_box = None
        self.warning_box = None
        self.error_box = None
        self.fatal_box = None
        self.txtModule = None
        self.status = None
        self.msg_type_dict = None
        self.init_gui()

    def init_gui(self):
        """init helper"""
        #setting up frames
        top_frame = Frame(self.root)
        mid_frame = Frame(self.root)
        radio_frame = Frame(self.root)
        res_frame = Frame(self.root)
        msg_frame = Frame(self.root)
        check_frame = Frame(self.root)
        history_frame = Frame(self.root)
        btn_frame = Frame(self.root)
        rating_frame = Frame(self.root)
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
        radio_frame.pack(side=TOP, fill=BOTH, expand=True)
        rating_frame.pack(side=TOP, fill=BOTH, expand=True)
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
        check_frame.pack(side=TOP, fill=BOTH, expand=True)
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

        # Binding F5 application-wide to run lint
        self.root.bind('<F5>', self.run_lint)

        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.lbMessages = Listbox(msg_frame,
                                  yscrollcommand=rightscrollbar.set,
                                  xscrollcommand=bottomscrollbar.set,
                                  bg="white")
        self.lbMessages.bind("<Double-Button-1>", self.show_sourcefile)
        self.lbMessages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lbMessages.yview)
        bottomscrollbar.config(command=self.lbMessages.xview)

        #Message context menu
        self.mnMessages = Menu(self.lbMessages, tearoff=0)
        self.mnMessages.add_command(label="View in sourcefile",
                                    command=self.show_sourcefile)
        self.mnMessages.add_command(label="Add to ignore patchfile",
                                    command=self.add_to_ignore_patchfile)
        self.lbMessages.bind("<Button-3>", self.show_messages_context)

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
        self.showhistory = Listbox(history_frame,
                                   yscrollcommand=rightscrollbar2.set,
                                   xscrollcommand=bottomscrollbar2.set,
                                   bg="white")
        self.showhistory.pack(expand=True, fill=BOTH)
        rightscrollbar2.config(command=self.showhistory.yview)
        bottomscrollbar2.config(command=self.showhistory.xview)
        self.showhistory.bind('<Double-Button-1>', self.select_recent_file)
        self.set_history_window()

        #status bar
        self.status = Label(self.root, text="", bd=1, relief=SUNKEN, anchor=W)
        self.status.pack(side=BOTTOM, fill=X)

        #labels
        self.lblRatingLabel = Label(rating_frame, text='Rating:')
        self.lblRatingLabel.pack(side=LEFT)
        self.lblRating = Label(rating_frame, textvariable=self.rating)
        self.lblRating.pack(side=LEFT)
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
        self.txtModule = Entry(top_frame, background='white')
        self.txtModule.bind('<Return>', self.run_lint)
        self.txtModule.pack(side=LEFT, expand=True, fill=X)

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
        self.results = Listbox(res_frame,
                               yscrollcommand=rightscrollbar.set,
                               xscrollcommand=bottomscrollbar.set,
                               bg="white",
                               font="Courier")
        self.results.pack(expand=True, fill=BOTH, side=BOTTOM)
        rightscrollbar.config(command=self.results.yview)
        bottomscrollbar.config(command=self.results.xview)

        #buttons
        Button(top_frame, text='Open', command=self.file_open).pack(side=LEFT)
        Button(top_frame,
               text='Open Package',
               command=(lambda: self.file_open(package=True))).pack(side=LEFT)

        self.btnRun = Button(top_frame, text='Run', command=self.run_lint)
        self.btnRun.pack(side=LEFT)
        Button(btn_frame, text='Quit', command=self.quit).pack(side=BOTTOM)

        #radio buttons
        self.information_box = IntVar()
        self.convention_box = IntVar()
        self.refactor_box = IntVar()
        self.warning_box = IntVar()
        self.error_box = IntVar()
        self.fatal_box = IntVar()
        i = Checkbutton(check_frame,
                        text="Information",
                        fg=COLORS['(I)'],
                        variable=self.information_box,
                        command=self.refresh_msg_window)
        c = Checkbutton(check_frame,
                        text="Convention",
                        fg=COLORS['(C)'],
                        variable=self.convention_box,
                        command=self.refresh_msg_window)
        r = Checkbutton(check_frame,
                        text="Refactor",
                        fg=COLORS['(R)'],
                        variable=self.refactor_box,
                        command=self.refresh_msg_window)
        w = Checkbutton(check_frame,
                        text="Warning",
                        fg=COLORS['(W)'],
                        variable=self.warning_box,
                        command=self.refresh_msg_window)
        e = Checkbutton(check_frame,
                        text="Error",
                        fg=COLORS['(E)'],
                        variable=self.error_box,
                        command=self.refresh_msg_window)
        f = Checkbutton(check_frame,
                        text="Fatal",
                        fg=COLORS['(F)'],
                        variable=self.fatal_box,
                        command=self.refresh_msg_window)
        i.select()
        c.select()
        r.select()
        w.select()
        e.select()
        f.select()
        i.pack(side=LEFT)
        c.pack(side=LEFT)
        r.pack(side=LEFT)
        w.pack(side=LEFT)
        e.pack(side=LEFT)
        f.pack(side=LEFT)

        #check boxes
        self.box = StringVar()
        # XXX should be generated
        report = Radiobutton(radio_frame,
                             text="Report",
                             variable=self.box,
                             value="Report",
                             command=self.refresh_results_window)
        rawMet = Radiobutton(radio_frame,
                             text="Raw metrics",
                             variable=self.box,
                             value="Raw metrics",
                             command=self.refresh_results_window)
        dup = Radiobutton(radio_frame,
                          text="Duplication",
                          variable=self.box,
                          value="Duplication",
                          command=self.refresh_results_window)
        ext = Radiobutton(radio_frame,
                          text="External dependencies",
                          variable=self.box,
                          value="External dependencies",
                          command=self.refresh_results_window)
        stat = Radiobutton(radio_frame,
                           text="Statistics by type",
                           variable=self.box,
                           value="Statistics by type",
                           command=self.refresh_results_window)
        msgCat = Radiobutton(radio_frame,
                             text="Messages by category",
                             variable=self.box,
                             value="Messages by category",
                             command=self.refresh_results_window)
        msg = Radiobutton(radio_frame,
                          text="Messages",
                          variable=self.box,
                          value="Messages",
                          command=self.refresh_results_window)
        sourceFile = Radiobutton(radio_frame,
                                 text="Source File",
                                 variable=self.box,
                                 value="Source File",
                                 command=self.refresh_results_window)
        report.select()
        report.grid(column=0, row=0, sticky=W)
        rawMet.grid(column=1, row=0, sticky=W)
        dup.grid(column=2, row=0, sticky=W)
        msg.grid(column=3, row=0, sticky=W)
        stat.grid(column=0, row=1, sticky=W)
        msgCat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, sticky=W)
        sourceFile.grid(column=3, row=1, sticky=W)

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
            'I': lambda: self.information_box.get() == 1,
            'C': lambda: self.convention_box.get() == 1,
            'R': lambda: self.refactor_box.get() == 1,
            'E': lambda: self.error_box.get() == 1,
            'W': lambda: self.warning_box.get() == 1,
            'F': lambda: self.fatal_box.get() == 1
        }
        self.txtModule.focus_set()

    def select_recent_file(self, event):
        """adds the selected file in the history listbox to the Module box"""
        if not self.showhistory.size():
            return

        selected = self.showhistory.curselection()
        item = self.showhistory.get(selected)
        #update module
        self.txtModule.delete(0, END)
        self.txtModule.insert(0, item)

    def refresh_msg_window(self):
        """refresh the message window with current output"""
        #clear the window
        self.lbMessages.delete(0, END)
        self.visible_msgs = []
        for msg in self.msgs:
            if (self.msg_type_dict.get(msg.C)()):
                self.visible_msgs.append(msg)
                msg_str = convert_to_string(msg)
                self.lbMessages.insert(END, msg_str)
                fg_color = COLORS.get(msg_str[:3], 'black')
                self.lbMessages.itemconfigure(END, fg=fg_color)

    def refresh_results_window(self):
        """refresh the results window with current output"""
        #clear the window
        self.results.delete(0, END)
        try:
            for res in self.tabs[self.box.get()]:
                self.results.insert(END, res)
        except:
            pass

    def process_incoming(self):
        """process the incoming messages from running pylint"""
        while self.msg_queue.qsize():
            try:
                msg = self.msg_queue.get(0)
                if msg == "DONE":
                    self.report_stream.output_contents()
                    return False

                #adding message to list of msgs
                self.msgs.append(msg)

                #displaying msg if message type is selected in check box
                if (self.msg_type_dict.get(msg.C)()):
                    self.visible_msgs.append(msg)
                    msg_str = convert_to_string(msg)
                    self.lbMessages.insert(END, msg_str)
                    fg_color = COLORS.get(msg_str[:3], 'black')
                    self.lbMessages.itemconfigure(END, fg=fg_color)

            except Queue.Empty:
                pass
        return True

    def periodic_call(self):
        """determine when to unlock the run button"""
        if self.process_incoming():
            self.root.after(100, self.periodic_call)
        else:
            #enabling button so it can be run again
            self.btnRun.config(state=NORMAL)

    def mainloop(self):
        """launch the mainloop of the application"""
        self.root.mainloop()

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

    def halt(self):
        """program halt placeholder"""
        return

    def file_open(self, package=False, _=None):
        """launch a file browser"""
        if not package:
            filename = askopenfilename(parent=self.root,
                                       filetypes=[('pythonfiles', '*.py'),
                                                  ('allfiles', '*')],
                                       title='Select Module')
        else:
            filename = askdirectory(title="Select A Folder", mustexist=1)

        if filename == ():
            return

        self.txtModule.delete(0, END)
        self.txtModule.insert(0, filename)

    def update_filenames(self):
        """update the list of recent filenames"""
        filename = self.txtModule.get()
        if not filename:
            filename = os.getcwd()
        if filename + '\n' in self.filenames:
            index = self.filenames.index(filename + '\n')
            self.filenames.pop(index)

        #ensure only 10 most recent are stored
        if len(self.filenames) == 10:
            self.filenames.pop()
        self.filenames.insert(0, filename + '\n')

    def set_history_window(self):
        """update the history window with info from the history file"""
        #clear the window
        self.showhistory.delete(0, END)
        # keep the last 10 most recent files
        try:
            view_history = open(HOME + HISTORY, 'r')
            for hist in view_history.readlines():
                if not hist in self.filenames:
                    self.filenames.append(hist)
                self.showhistory.insert(END, hist.split('\n')[0])
            view_history.close()
        except IOError:
            # do nothing since history file will be created later
            return

    def run_lint(self, _=None):
        """launches pylint"""
        self.update_filenames()
        self.root.configure(cursor='watch')
        self.reporter = GUIReporter(self, output=self.report_stream)
        module = self.txtModule.get()
        if not module:
            module = os.getcwd()

        #cleaning up msgs and windows
        self.msgs = []
        self.visible_msgs = []
        self.lbMessages.delete(0, END)
        self.tabs = {}
        self.results.delete(0, END)
        self.btnRun.config(state=DISABLED)

        #setting up a worker thread to run pylint
        worker = Thread(target=lint_thread,
                        args=(
                            module,
                            self.reporter,
                            self,
                        ))
        self.periodic_call()
        worker.start()

        # Overwrite the .pylint-gui-history file with all the new recently added files
        # in order from filenames but only save last 10 files
        write_history = open(HOME + HISTORY, 'w')
        write_history.writelines(self.filenames)
        write_history.close()
        self.set_history_window()

        self.root.configure(cursor='')

    def show_sourcefile(self, event=None):
        selected = self.lbMessages.curselection()
        if not selected:
            return

        msg = self.visible_msgs[int(selected[0])]
        scroll = msg.line - 3
        if scroll < 0:
            scroll = 0

        self.tabs["Source File"] = open(msg.abspath, "r").readlines()
        self.box.set("Source File")
        self.refresh_results_window()
        self.results.yview(scroll)
        self.results.select_set(msg.line - 1)

    def show_messages_context(self, event):
        """Show the message listbox's context menu"""
        # Select the item that was clicked
        index = self.lbMessages.nearest(event.y)
        self.lbMessages.selection_clear(0, END)
        self.lbMessages.selection_set(index)
        self.lbMessages.activate(index)

        self.mnMessages.tk_popup(event.x_root, event.y_root)

    def add_to_ignore_patchfile(self, event=None):
        """
        Add the selected message to the ignore patchfile.
        This means that this message will now be ignored by pylint-patcher.
        """
        selected = self.lbMessages.curselection()
        if not selected:
            return

        selected_index = int(selected[0])
        msg = self.visible_msgs[selected_index]
        self.differ.add_disable_pragma(msg.abspath, msg.line, msg.symbol)
        self.differ.diff()

        del self.msgs[self.msgs.index(msg)]
        del self.visible_msgs[selected_index]
        self.lbMessages.delete(selected_index)
Exemple #3
0
class LintGui(object):
    """Build and control a window to interact with pylint"""

    def __init__(self, root=None):
        """init"""
        self.root = root or Tk()
        self.root.title('Pylint')
        #reporter
        self.reporter = None
        #message queue for output from reporter
        self.msg_queue = Queue.Queue()
        self.msgs = []
        self.visible_msgs = []
        self.filenames = []
        self.rating = StringVar()
        self.tabs = {}
        self.report_stream = BasicStream(self)
        #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)

        #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:

            # Obtaining message type (pylint's '--include-ids' appends the
            # ID to this letter, so 1 character long is not guaranteed)
            msg_type = msg[0][0]

            if (self.msg_type_dict.get(msg_type)()):
                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)

                # Obtaining message type (pylint's '--include-ids' appends the
                # ID to this letter, so 1 character long is not guaranteed)
                msg_type = msg[0][0]

                #displaying msg if message type is selected in check box
                if (self.msg_type_dict.get(msg_type)()):
                    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])]
        filename = msg[2]
        fileline = int(msg[5])

        scroll = fileline - 3
        if scroll < 0:
            scroll = 0

        self.tabs["Source File"] = open(filename, "r").readlines()
        self.box.set("Source File")
        self.refresh_results_window()
        self.results.yview(scroll)
        self.results.select_set(fileline - 1)
Exemple #4
0
class Gamelist():
    def __init__(self, drive, platform):
        GameListData.game_list_data_json = GameListData().get_game_list()
        self.json_game_list_data = GameListData.game_list_data_json

        if drive == 'USB(*)':
            self.drive_to_show = '/dev_' + drive.lower().replace('(*)', '')
        else:
            self.drive_to_show = '/dev_' + drive.lower() + '/'

        self.platform_to_show = platform + '_games'
        self.WCM_BASE_PATH  = AppPaths.wcm_gui
        self.last_selection = (None, 0)
        self.list_of_items = []

        self.selected_title_id   = None
        self.selected_title      = None
        self.selected_path       = None
        self.selected_filename   = None
        self.drive_system_path_array = None

        self.is_cleared = False


    def create_main_frame(self, entry_field_title_id, entry_field_title, entry_field_filename, entry_field_iso_path, entry_field_platform, drive_system_array):
        self.entry_field_title_id       = entry_field_title_id
        self.entry_field_title          = entry_field_title
        self.entry_field_filename       = entry_field_filename
        self.entry_field_iso_path       = entry_field_iso_path
        self.entry_field_platform       = entry_field_platform
        self.drive_system_path_array    = drive_system_array

        self.corrected_index = []
        self.main_frame = Frame()

        self.popup_menu = Menu(self.main_frame, tearoff=0)

        self.popup_menu.add_command(label="Delete",
                                    command=self.delete_selected)
        self.popup_menu.add_command(label="Rename",
                                    command=self.rename_selected)
        # self.popup_menu.add_command(label="Refetch",
        #                             command=self.refetch)
        # self.popup_menu.add_command(label="Select All",
        #                             command=self.select_all)




        s = Scrollbar(self.main_frame)
        self._listbox = Listbox(self.main_frame, width=465)
        self._listbox.bind('<Enter>', self._bound_to_mousewheel)
        self._listbox.bind('<Leave>', self._unbound_to_mousewheel)
        self._listbox.bind("<Button-3>", self.popup) # Button-2 on Aqua

        s.pack(side=RIGHT, fill=Y)
        self._listbox.pack(side=LEFT, fill=Y)

        s['command'] = self._listbox.yview
        self._listbox['yscrollcommand'] = s.set



        # default filters
        if 'ALL_games' == self.platform_to_show:
            # iterate all platforms
            for platform in self.json_game_list_data:
                for list_game in self.json_game_list_data[platform]:
                    # titles in the list has been designed to be unique
                    if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']:
                        self.add_item(list_game['title'])

        else:
            for list_game in self.json_game_list_data[self.platform_to_show]:
                if '/dev_all/' == self.drive_to_show or self.drive_to_show in list_game['path']:
                    self.add_item(list_game['title'])

        for x in range(19 - self._listbox.size()):
            self.add_item('')


        # adding shade to every other row of the list
        for x in range(0, self._listbox.size()):
            if x % 2 == 0:
                self._listbox.itemconfig(x, {'fg': 'white'}, background='#001738')
            else:
                self._listbox.itemconfig(x, {'fg': 'white'}, background='#001F4C')

        self.label = Label(self.main_frame)
        self.selection_poller()

        return self.main_frame

    def selection_poller(self):
        self.label.after(200, self.selection_poller)
        self.new_selection = self._listbox.curselection()
        # cursor har been initiated
        if self._listbox.curselection() is not ():
            if self.new_selection[0] is not self.last_selection[0] or self.is_cleared:
                self.entry_fields_update(self.new_selection)
                self.is_cleared = False
                self.last_selection = self.new_selection


    def entry_fields_update(self, new_selection):
        for platform in self.json_game_list_data:

            for list_game in self.json_game_list_data[platform]:
                self.selected_title = self._listbox.get(new_selection[0])
                tmp_title = list_game['title']

                match = self.selected_title == str(tmp_title)
                if match:
                    self.selected_title_id   = str(list_game['title_id']).replace('-', '')
                    self.selected_title      = str(list_game['title'])
                    self.selected_path       = str(list_game['path'])
                    self.selected_filename   = str(list_game['filename'])
                    self.selected_platform   = str(list_game['platform'])

                    # parse drive and system from json data
                    path_array = filter(None, self.selected_path.split('/'))
                    self.drive_system_path_array[0] = path_array[0]
                    self.drive_system_path_array[1] = path_array[1]
                    self.drive_system_path_array[2] = '/'.join(path_array[2:len(path_array)]).replace('//', '')


                    self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1)
                    self.entry_field_title_id.delete(0, END)
                    self.entry_field_title_id.insert(0, self.selected_title_id)

                    self.entry_field_title.delete(0, END)
                    self.entry_field_title.insert(0, self.selected_title)

                    self.entry_field_filename.delete(0, END)
                    self.entry_field_filename.insert(0, self.selected_filename)

                    self.entry_field_platform.delete(0, END)
                    self.entry_field_platform.insert(0, self.selected_platform)

                    return True



    def get_selected_path(self):
        return self.current_iso_path

    def get_listbox(self):
        return self._listbox

    def get_ascending_index(self, list_of_items, item, ignore_case=True):
        lo = 0
        hi = len(list_of_items)

        if ignore_case:
            item = item.lower()
            while lo < hi:
                mid = (lo + hi) // 2

                if item < list_of_items[mid].lower():
                    hi = mid
                else:
                    lo = mid + 1
        else:
            while lo < hi:
                mid = (lo + hi) // 2

                if item < list_of_items[mid]:
                    hi = mid
                else:
                    lo = mid + 1
        return lo

    def add_item(self, item):
        if item != '':
            self.list_of_items = self._listbox.get(0, END)
            # getting ascending index in order to sort alphabetically
            index = self.get_ascending_index(self.list_of_items, item)

            self._listbox.insert(index, item)
        else:
            self._listbox.insert(END, item)

    def get_items(self):
        return self.list_of_items

    def _bound_to_mousewheel(self, event):
        self._listbox.bind_all("<MouseWheel>", self._on_mousewheel)

    def _unbound_to_mousewheel(self, event):
        self._listbox.unbind_all("<MouseWheel>")

    def _on_mousewheel(self, event):
        self._listbox.yview_scroll(int(-1*(event.delta/30)), "units")

    def popup(self, event):
        try:
            self._listbox.selection_clear(0, END)
            self._listbox.selection_set(self._listbox.nearest(event.y))
            self._listbox.activate(self._listbox.nearest(event.y))
        finally:
            if self._listbox.get(self._listbox.curselection()[0]) is not '':
                self.popup_menu.tk_popup(event.x_root + 43, event.y_root + 12, 0)
                self.popup_menu.grab_release()
                self.popup_menu.focus_set()

    def delete_selected(self):
        import tkMessageBox
        game_folder_path = os.path.join(AppPaths.game_work_dir, '..')
        response = tkMessageBox.askyesno('Delete game folder', 'Delete \'' + self.entry_field_title.get() + '\'?\n\nFolder path: ' + os.path.realpath(game_folder_path))
        # yes
        if response:
            # remove game from visual game list
            for i in self._listbox.curselection()[::-1]:
                self._listbox.delete(i)
                removed_index = i

            # remove game from json game list
            platform_key = self.entry_field_platform.get() + '_games'
            self.json_game_list_data[platform_key] = [x for x in self.json_game_list_data[platform_key] if x['title'] != self.selected_title]

            # update the json game list file
            with open(GameListData.GAME_LIST_DATA_PATH, 'w') as newFile:
                json_text = json.dumps(self.json_game_list_data, indent=4, separators=(",", ":"))
                newFile.write(json_text)

            # remove the game build folder too
            if AppPaths.game_work_dir != os.path.join(AppPaths.wcm_gui, 'work_dir'):
                if os.path.isdir(game_folder_path):
                    if 'webman-classics-maker' in game_folder_path:
                        shutil.rmtree(game_folder_path)
                # clear entry_fields
                self.clear_entries_and_path()
                # set cursor
                self._listbox.select_set(removed_index) #This only sets focus on the first item.

    def rename_selected(self):
        self.entry_field_title.selection_range(0, END)
        self.entry_field_title.focus_set()

    def select_all(self):
        self._listbox.selection_set(0, 'end')


    def clear_entries_and_path(self):
        self.entry_field_title_id.delete(0, len(self.entry_field_title_id.get())-1)
        self.entry_field_title_id.delete(0, END)
        self.entry_field_title.delete(0, END)
        self.entry_field_platform.delete(0, END)
        self.entry_field_filename.delete(0, END)

        self.is_cleared = True



    def get_selected_build_dir_path(self):
        self.build_dir_path = ''
        if self.selected_filename not in {'', None}:
            filename = self.selected_filename
            title_id = self.selected_title_id.replace('-', '')
            build_base_path = AppPaths.builds

            tmp_filename = filename
            # removes the file extension from tmp_filename
            for file_ext in GlobalVar.file_extensions:
                if filename.upper().endswith(file_ext):
                    tmp_filename = filename[0:len(filename)-len(file_ext)]
                    break
            game_folder_name = tmp_filename.replace(' ', '_') + '_(' + title_id.replace('-', '') + ')'

            self.build_dir_path = os.path.join(build_base_path, game_folder_name)
        return self.build_dir_path
class GraphAnalyzer(Frame):

    def __init__(self, root):
        Frame.__init__(self, root)
        self.__root = root
        self.__data_manager = DataManager()
        self.__check_button_type = namedtuple('CheckButtonType', 'widget var')

        self.__natures = [
            "Single Carriageway", "Traffic Island Link", "Dual Carriageway",
            "Roundabout", "Traffic Island Link At Junction", "Slip Road"
        ]

        self.__roads = [
            "M3","M40","M4","A1(M)","M11","M23","M20","M25","M1","HIGH STREET",
            "LONDON ROAD","HIGH ROAD","UXBRIDGE ROAD","STATION ROAD",
            "BRIGHTON ROAD","GREEN LANES","FINCHLEY ROAD","HARROW ROAD",
            "NORTH CIRCULAR ROAD","KINGSTON ROAD","PORTSMOUTH ROAD","HERTFORD ROAD",
            "STAINES ROAD","CROYDON ROAD","MAIN ROAD","CHURCH ROAD","PARK ROAD"
        ]

        self.__motorways = ["M3","M40","M4","A1(M)","M11","M23","M20","M25","M1"]

        self.__init_grid()
        self.__draw_grid()

    def __init_grid(self):

        # Road list
        self.__roads_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=27, exportselection=0)
        for road in self.__roads:
            self.__roads_list_box.insert('end', road)

        # Nature list
        self.__natures_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=6, width=22, exportselection=0)
        for nature in self.__natures:
            self.__natures_list_box.insert('end', nature)

        # Start with all natures selected
        self.__natures_list_box.select_set(0, END)\

        # Days list
        self.__days_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=8, width=22, exportselection=0)
        for day in ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']:
            self.__days_list_box.insert('end', day)

        # Hours list
        self.__hours_list_box = Listbox(self.__root, selectmode=MULTIPLE, height=24, width=7, exportselection=0)
        for hour in range(24):
            self.__hours_list_box.insert('end', hour)

        # Check button draw overall
        self.__draw_overall_var = IntVar()
        self.__draw_overall_check_box = \
            Checkbutton(self.__root, text = "Draw Overall Curve?",
                        variable = self.__draw_overall_var, onvalue = 1,
                        offvalue = 0, height=2, width = 20)

        # Check button draw nature
        self.__draw_nature_var = IntVar()
        self.__draw_nature_check_box = \
            Checkbutton(self.__root, text = "Draw Curve Per Nature?",
                        variable = self.__draw_nature_var, onvalue = 1,
                        offvalue = 0, height=2, width = 20)

        # Check button show data
        self.__show_data_var = IntVar()
        self.__show_data_var.set(1)
        self.__show_data_check_box = \
            Checkbutton(self.__root, text = "Show data?",
                        variable = self.__show_data_var, onvalue = 1,
                        offvalue = 0, height=2, width = 20)

        # Go button
        self.__go_button = Button(self.__root, text='GO', command = lambda: self.__generate_graph())

        # Errors text box
        self.__error_text_box = Text(self.__root, height=28, width=18, fg="red")
        self.__error_text_box.tag_config('justified', justify=CENTER)

    def __draw_grid(self):

        # Roads label and list box
        Label(self.__root, text="Roads", justify=CENTER).grid(row=0, column=0)
        self.__roads_list_box.grid(row=1, column=0, rowspan=27)

        # Natures label and list box
        Label(self.__root, text="Natures", justify=CENTER).grid(row=0, column=1)
        self.__natures_list_box.grid(row=1, column=1, rowspan=6)

        # Days label and list box
        Label(self.__root, text="Days", justify=CENTER).grid(row=7, column=1)
        self.__days_list_box.grid(row=8, column=1, rowspan=8)

        # Hours label and list box
        Label(self.__root, text="Hours", justify=CENTER).grid(row=0, column=3)
        self.__hours_list_box.grid(row=1, column=3, rowspan=24)

        # Check boxes
        Label(self.__root, text="Drawing Options", justify=CENTER).grid(row=0, column=4)
        self.__draw_overall_check_box.grid(row=1, column=4, rowspan=2)
        self.__draw_nature_check_box.grid(row=3, column=4, rowspan=2)
        self.__show_data_check_box.grid(row=5, column=4, rowspan=2)

        # Go button
        self.__go_button.grid(row=10, column=4)

        # Error Column
        Label(self.__root, text="Error Report", height=1, width=18, justify=CENTER).grid(row=0, column=5)
        self.__error_text_box.grid(row=1, column=5, rowspan=28)



    def __generate_graph(self):

        # Get parameters
        roads = tuple(self.__roads_list_box.get(road_index) for road_index in self.__roads_list_box.curselection())
        roads = [ ("classification" if road in self.__motorways else "street", road) for road in roads]

        natures = tuple(self.__natures_list_box.get(nature_index) for nature_index in self.__natures_list_box.curselection())
        days = self.__days_list_box.curselection()
        hours = self.__hours_list_box.curselection()

        errors = self.__error_check(roads, natures, days, hours)

        if len(errors):
            self.__error_text_box.delete("1.0",END)
            for e in errors:
                self.__error_text_box.insert(END, e + '\n', 'justified')
        else:
            data = self.__data_manager.get_data("traffic", "rainfall", roads, natures, hours, days)
            self.__plot_data(data)

    def __error_check(self, roads, natures, hours, days):

        errors = []

        if not len(roads):
            errors.append("No roads selected")
        if not len(natures):
            errors.append("No natures selected")
        if not len(hours):
            errors.append("No hours selected")
        if not len(days):
            errors.append("No days selected")
        if not (self.__show_data_var.get() or
                    self.__draw_nature_var.get() or
                    self.__draw_overall_var.get()):
            errors.append("Nothing to draw")

        return errors


    def __plot_data(self, data):

        max_depth = data.depth.max()
        max_speed = data.speed.max()

        dfs_to_plot = []

        if self.__show_data_var.get():
            dfs_to_plot.append(data)

        if self.__draw_overall_var.get():
            dfs_to_plot.append(self.__get_best_fit_curve(data, max_depth, max_speed, "Best fit curve"))

        if self.__draw_nature_var.get():
            for nature, nature_df in data.groupby(['nature']):
                dfs_to_plot.append(self.__get_best_fit_curve(nature_df, max_depth, max_speed, nature))

        data = pd.concat(dfs_to_plot, ignore_index=True)

        fg = sns.FacetGrid(data=data, hue='nature', aspect=1.9, legend_out=False, size=8)

        fg.map(plt.scatter, 'depth', 'speed', s=20).add_legend(None, "Legend")
        axes = fg.axes


        ylim = 120 if max_speed > 200 else max_speed
        xlim = 1.0 if max_depth < 1.0 else 2.0

        axes[0,0].set_ylim(0,ylim)
        axes[0,0].set_xlim(0,xlim)

        sns.plt.show()


    def __get_best_fit_curve(self, data, max_depth, max_speed, nature_str):

        try:
            popt, pcov = curve_fit(self.curve_func, data.depth, data.speed)
        except RuntimeError:
            return pd.DataFrame({'depth':[], 'speed':[], 'nature':[], 'identifier':[]})

        a = popt[0]
        b = popt[1]
        c = popt[2]

        depths = list(np.arange(0, max_depth, max_depth/10000.0))
        speeds = map(lambda x: self.curve_func(x, a, b, c), depths)

        if max(speeds) > max_speed:
            speeds = [s for s in speeds if s <= max_speed]
            depths = depths[0:len(speeds)]

        natures = [nature_str] * len(depths)
        identifiers = [''] * len(depths)

        return pd.DataFrame({'depth':depths, 'speed':speeds, 'nature':natures, 'identifier':identifiers})

    def curve_func(self, x, a, b, c):
        return a * np.exp(-b * x) + c
Exemple #6
0
class GraphAnalyzer(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.__root = root
        self.__data_manager = DataManager()
        self.__check_button_type = namedtuple('CheckButtonType', 'widget var')

        self.__natures = [
            "Single Carriageway", "Traffic Island Link", "Dual Carriageway",
            "Roundabout", "Traffic Island Link At Junction", "Slip Road"
        ]

        self.__roads = [
            "M3", "M40", "M4", "A1(M)", "M11", "M23", "M20", "M25", "M1",
            "HIGH STREET", "LONDON ROAD", "HIGH ROAD", "UXBRIDGE ROAD",
            "STATION ROAD", "BRIGHTON ROAD", "GREEN LANES", "FINCHLEY ROAD",
            "HARROW ROAD", "NORTH CIRCULAR ROAD", "KINGSTON ROAD",
            "PORTSMOUTH ROAD", "HERTFORD ROAD", "STAINES ROAD", "CROYDON ROAD",
            "MAIN ROAD", "CHURCH ROAD", "PARK ROAD"
        ]

        self.__motorways = [
            "M3", "M40", "M4", "A1(M)", "M11", "M23", "M20", "M25", "M1"
        ]

        self.__init_grid()
        self.__draw_grid()

    def __init_grid(self):

        # Road list
        self.__roads_list_box = Listbox(self.__root,
                                        selectmode=MULTIPLE,
                                        height=27,
                                        exportselection=0)
        for road in self.__roads:
            self.__roads_list_box.insert('end', road)

        # Nature list
        self.__natures_list_box = Listbox(self.__root,
                                          selectmode=MULTIPLE,
                                          height=6,
                                          width=22,
                                          exportselection=0)
        for nature in self.__natures:
            self.__natures_list_box.insert('end', nature)

        # Start with all natures selected
        self.__natures_list_box.select_set(0, END)\

        # Days list
        self.__days_list_box = Listbox(self.__root,
                                       selectmode=MULTIPLE,
                                       height=8,
                                       width=22,
                                       exportselection=0)
        for day in [
                'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
                'Friday', 'Saturday'
        ]:
            self.__days_list_box.insert('end', day)

        # Hours list
        self.__hours_list_box = Listbox(self.__root,
                                        selectmode=MULTIPLE,
                                        height=24,
                                        width=7,
                                        exportselection=0)
        for hour in range(24):
            self.__hours_list_box.insert('end', hour)

        # Check button draw overall
        self.__draw_overall_var = IntVar()
        self.__draw_overall_check_box = \
            Checkbutton(self.__root, text = "Draw Overall Curve?",
                        variable = self.__draw_overall_var, onvalue = 1,
                        offvalue = 0, height=2, width = 20)

        # Check button draw nature
        self.__draw_nature_var = IntVar()
        self.__draw_nature_check_box = \
            Checkbutton(self.__root, text = "Draw Curve Per Nature?",
                        variable = self.__draw_nature_var, onvalue = 1,
                        offvalue = 0, height=2, width = 20)

        # Check button show data
        self.__show_data_var = IntVar()
        self.__show_data_var.set(1)
        self.__show_data_check_box = \
            Checkbutton(self.__root, text = "Show data?",
                        variable = self.__show_data_var, onvalue = 1,
                        offvalue = 0, height=2, width = 20)

        # Go button
        self.__go_button = Button(self.__root,
                                  text='GO',
                                  command=lambda: self.__generate_graph())

        # Errors text box
        self.__error_text_box = Text(self.__root,
                                     height=28,
                                     width=18,
                                     fg="red")
        self.__error_text_box.tag_config('justified', justify=CENTER)

    def __draw_grid(self):

        # Roads label and list box
        Label(self.__root, text="Roads", justify=CENTER).grid(row=0, column=0)
        self.__roads_list_box.grid(row=1, column=0, rowspan=27)

        # Natures label and list box
        Label(self.__root, text="Natures", justify=CENTER).grid(row=0,
                                                                column=1)
        self.__natures_list_box.grid(row=1, column=1, rowspan=6)

        # Days label and list box
        Label(self.__root, text="Days", justify=CENTER).grid(row=7, column=1)
        self.__days_list_box.grid(row=8, column=1, rowspan=8)

        # Hours label and list box
        Label(self.__root, text="Hours", justify=CENTER).grid(row=0, column=3)
        self.__hours_list_box.grid(row=1, column=3, rowspan=24)

        # Check boxes
        Label(self.__root, text="Drawing Options",
              justify=CENTER).grid(row=0, column=4)
        self.__draw_overall_check_box.grid(row=1, column=4, rowspan=2)
        self.__draw_nature_check_box.grid(row=3, column=4, rowspan=2)
        self.__show_data_check_box.grid(row=5, column=4, rowspan=2)

        # Go button
        self.__go_button.grid(row=10, column=4)

        # Error Column
        Label(self.__root,
              text="Error Report",
              height=1,
              width=18,
              justify=CENTER).grid(row=0, column=5)
        self.__error_text_box.grid(row=1, column=5, rowspan=28)

    def __generate_graph(self):

        # Get parameters
        roads = tuple(
            self.__roads_list_box.get(road_index)
            for road_index in self.__roads_list_box.curselection())
        roads = [("classification" if road in self.__motorways else "street",
                  road) for road in roads]

        natures = tuple(
            self.__natures_list_box.get(nature_index)
            for nature_index in self.__natures_list_box.curselection())
        days = self.__days_list_box.curselection()
        hours = self.__hours_list_box.curselection()

        errors = self.__error_check(roads, natures, days, hours)

        if len(errors):
            self.__error_text_box.delete("1.0", END)
            for e in errors:
                self.__error_text_box.insert(END, e + '\n', 'justified')
        else:
            data = self.__data_manager.get_data("traffic", "rainfall", roads,
                                                natures, hours, days)
            self.__plot_data(data)

    def __error_check(self, roads, natures, hours, days):

        errors = []

        if not len(roads):
            errors.append("No roads selected")
        if not len(natures):
            errors.append("No natures selected")
        if not len(hours):
            errors.append("No hours selected")
        if not len(days):
            errors.append("No days selected")
        if not (self.__show_data_var.get() or self.__draw_nature_var.get()
                or self.__draw_overall_var.get()):
            errors.append("Nothing to draw")

        return errors

    def __plot_data(self, data):

        max_depth = data.depth.max()
        max_speed = data.speed.max()

        dfs_to_plot = []

        if self.__show_data_var.get():
            dfs_to_plot.append(data)

        if self.__draw_overall_var.get():
            dfs_to_plot.append(
                self.__get_best_fit_curve(data, max_depth, max_speed,
                                          "Best fit curve"))

        if self.__draw_nature_var.get():
            for nature, nature_df in data.groupby(['nature']):
                dfs_to_plot.append(
                    self.__get_best_fit_curve(nature_df, max_depth, max_speed,
                                              nature))

        data = pd.concat(dfs_to_plot, ignore_index=True)

        fg = sns.FacetGrid(data=data,
                           hue='nature',
                           aspect=1.9,
                           legend_out=False,
                           size=8)

        fg.map(plt.scatter, 'depth', 'speed', s=20).add_legend(None, "Legend")
        axes = fg.axes

        ylim = 120 if max_speed > 200 else max_speed
        xlim = 1.0 if max_depth < 1.0 else 2.0

        axes[0, 0].set_ylim(0, ylim)
        axes[0, 0].set_xlim(0, xlim)

        sns.plt.show()

    def __get_best_fit_curve(self, data, max_depth, max_speed, nature_str):

        try:
            popt, pcov = curve_fit(self.curve_func, data.depth, data.speed)
        except RuntimeError:
            return pd.DataFrame({
                'depth': [],
                'speed': [],
                'nature': [],
                'identifier': []
            })

        a = popt[0]
        b = popt[1]
        c = popt[2]

        depths = list(np.arange(0, max_depth, max_depth / 10000.0))
        speeds = map(lambda x: self.curve_func(x, a, b, c), depths)

        if max(speeds) > max_speed:
            speeds = [s for s in speeds if s <= max_speed]
            depths = depths[0:len(speeds)]

        natures = [nature_str] * len(depths)
        identifiers = [''] * len(depths)

        return pd.DataFrame({
            'depth': depths,
            'speed': speeds,
            'nature': natures,
            'identifier': identifiers
        })

    def curve_func(self, x, a, b, c):
        return a * np.exp(-b * x) + c
Exemple #7
0
class HistWin(object):
    def __init__(self, top):
        currentTheme = idleConf.CurrentTheme()
        self.history_frame = Frame(top, height=1)
        self.top = top
        fg = idleConf.GetHighlight(currentTheme, 'normal', fgBg='fg')
        bg = idleConf.GetHighlight(currentTheme, 'normal', fgBg='bg')
        self.lst = Listbox(self.history_frame,
                           foreground=fg,
                           background=bg,
                           height=5,
                           selectmode=EXTENDED,
                           exportselection=False)
        self.scroll = Scrollbar(self.history_frame, command=self.lst.yview)

        self.lst['yscrollcommand'] = self.scroll.set
        self.lst.bind('<ButtonRelease-1>', self.click)

        #self.search_box_text = Variable()
        #self.search_box_text.trace('w', self.search_text_changed)
        #self.search_box = Entry(self.history_frame,
        #    foreground=fg, background=bg,
        #    textvariable=self.search_box_text)
        self.history_frame.pack(side=TOP, fill=X)
        self.is_shown = False

    def attach_history(self, textwidget, hist):
        self.hist = hist
        self.hist.histwin = self
        for h in hist.history:
            self.store(h)
        self.lst.see('end')

        self.textwidget = textwidget
        self.textwidget.bind('<<history-window-toggle>>',
                             self.history_window_toggle_event)

    def click(self, evt):
        selection = sorted(map(int, self.lst.curselection()))
        commands = [self.hist.history[x] for x in selection]
        commands = '\n'.join(commands)
        self.textwidget.delete("iomark", "end-1c")
        self.textwidget.insert("iomark", commands)

    def goto(self, pointer):
        self.lst.select_clear(0, END)
        self.lst.select_set(pointer)
        self.lst.see(0)
        self.lst.see(pointer)

    def hide(self):
        self.lst.pack_forget()
        self.scroll.pack_forget()
        self.history_frame['height'] = 1
        self.is_shown = False

    def show(self):
        self.scroll.pack(side=RIGHT, fill=Y)
        self.lst.pack(side=TOP, fill=X)
        self.is_shown = True

    def toggle(self):
        if self.is_shown:
            self.hide()
        else:
            self.show()

    def store(self, source):
        self.lst.insert(END, source[:60].replace('\n', ' ').replace('\t', ' '))

    def remove(self, idx):
        self.lst.delete(idx)

    def history_window_toggle_event(self, evt):
        """Opens a window containing the entire history of entered commands"""
        self.toggle()
        return "break"