gui.py 19.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2003-2013 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16
"""Tkinker gui for pylint"""
17
from __future__ import print_function
18 19 20 21 22

import os
import sys
import re
from threading import Thread
23 24 25 26 27

import six

from six.moves.tkinter import (
    Tk, Frame, Listbox, Entry, Label, Button, Scrollbar,
28
    Checkbutton, Radiobutton, IntVar, StringVar, PanedWindow,
29 30 31 32 33 34
    TOP, LEFT, RIGHT, BOTTOM, END, X, Y, BOTH, SUNKEN, W,
    HORIZONTAL, DISABLED, NORMAL, W,
)
from six.moves.tkinter_tkfiledialog import (
    askopenfilename, askdirectory,
)
35 36 37 38 39 40 41 42 43 44 45

import pylint.lint
from pylint.reporters.guireporter import GUIReporter

HOME = os.path.expanduser('~/')
HISTORY = '.pylint-gui-history'
COLORS = {'(I)':'lightblue',
          '(C)':'blue', '(R)':'darkblue',
          '(W)':'black', '(E)':'darkred',
          '(F)':'red'}

46 47 48 49 50 51 52 53 54

def convert_to_string(msg):
    """make a string representation of a message"""
    module_object = msg.module
    if msg.obj:
        module_object += ".%s" % msg.obj
    return "(%s) %s [%d]: %s" % (msg.C, module_object, msg.line, msg.msg)

class BasicStream(object):
55 56 57 58 59 60 61 62 63 64 65
    '''
    used in gui reporter instead of writing to stdout, it is written to
    this stream and saved in contents
    '''
    def __init__(self, gui):
        """init"""
        self.curline = ""
        self.gui = gui
        self.contents = []
        self.outdict = {}
        self.currout = None
66
        self.next_title = None
67 68 69 70 71

    def write(self, text):
        """write text to the stream"""
        if re.match('^--+$', text.strip()) or re.match('^==+$', text.strip()):
            if self.currout:
72
                self.outdict[self.currout].remove(self.next_title)
73
                self.outdict[self.currout].pop()
74
            self.currout = self.next_title
75 76 77
            self.outdict[self.currout] = ['']

        if text.strip():
78
            self.next_title = text.strip()
79

80
        if text.startswith(os.linesep):
81
            self.contents.append('')
82 83 84 85 86 87
            if self.currout:
                self.outdict[self.currout].append('')
        self.contents[-1] += text.strip(os.linesep)
        if self.currout:
            self.outdict[self.currout][-1] += text.strip(os.linesep)
        if text.endswith(os.linesep) and text.strip():
88
            self.contents.append('')
89 90
            if self.currout:
                self.outdict[self.currout].append('')
91 92 93 94

    def fix_contents(self):
        """finalize what the contents of the dict should look like before output"""
        for item in self.outdict:
95
            num_empty = self.outdict[item].count('')
96
            for _ in range(num_empty):
97 98 99 100 101 102 103 104 105 106
                self.outdict[item].remove('')
            if self.outdict[item]:
                self.outdict[item].pop(0)

    def output_contents(self):
        """output contents of dict to the gui, and set the rating"""
        self.fix_contents()
        self.gui.tabs = self.outdict
        try:
            self.gui.rating.set(self.outdict['Global evaluation'][0])
107
        except KeyError:
108 109 110 111 112 113 114
            self.gui.rating.set('Error')
        self.gui.refresh_results_window()

        #reset stream variables for next run
        self.contents = []
        self.outdict = {}
        self.currout = None
115
        self.next_title = None
116 117


118
class LintGui(object):
119 120 121 122 123 124 125 126 127
    """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
128
        self.msg_queue = six.moves.queue.Queue()
129
        self.msgs = []
130
        self.visible_msgs = []
131 132 133 134 135
        self.filenames = []
        self.rating = StringVar()
        self.tabs = {}
        self.report_stream = BasicStream(self)
        #gui objects
136
        self.lb_messages = None
137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        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"""
153 154 155 156 157 158 159 160 161 162 163

        window = PanedWindow(self.root, orient="vertical")
        window.pack(side=TOP, fill=BOTH, expand=True)

        top_pane = Frame(window)
        window.add(top_pane)
        mid_pane = Frame(window)
        window.add(mid_pane)
        bottom_pane = Frame(window)
        window.add(bottom_pane)

164
        #setting up frames
165 166 167 168 169 170 171 172 173
        top_frame = Frame(top_pane)
        mid_frame = Frame(top_pane)
        history_frame = Frame(top_pane)
        radio_frame = Frame(mid_pane)
        rating_frame = Frame(mid_pane)
        res_frame = Frame(mid_pane)
        check_frame = Frame(bottom_pane)
        msg_frame = Frame(bottom_pane)
        btn_frame = Frame(bottom_pane)
174 175 176
        top_frame.pack(side=TOP, fill=X)
        mid_frame.pack(side=TOP, fill=X)
        history_frame.pack(side=TOP, fill=BOTH, expand=True)
177 178
        radio_frame.pack(side=TOP, fill=X)
        rating_frame.pack(side=TOP, fill=X)
179
        res_frame.pack(side=TOP, fill=BOTH, expand=True)
180
        check_frame.pack(side=TOP, fill=X)
181 182 183
        msg_frame.pack(side=TOP, fill=BOTH, expand=True)
        btn_frame.pack(side=TOP, fill=X)

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

187 188 189 190 191
        #Message ListBox
        rightscrollbar = Scrollbar(msg_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(msg_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
192 193 194 195 196 197 198 199 200
        self.lb_messages = Listbox(
            msg_frame,
            yscrollcommand=rightscrollbar.set,
            xscrollcommand=bottomscrollbar.set,
            bg="white")
        self.lb_messages.bind("<Double-Button-1>", self.show_sourcefile)
        self.lb_messages.pack(expand=True, fill=BOTH)
        rightscrollbar.config(command=self.lb_messages.yview)
        bottomscrollbar.config(command=self.lb_messages.xview)
201 202 203 204 205 206

        #History ListBoxes
        rightscrollbar2 = Scrollbar(history_frame)
        rightscrollbar2.pack(side=RIGHT, fill=Y)
        bottomscrollbar2 = Scrollbar(history_frame, orient=HORIZONTAL)
        bottomscrollbar2.pack(side=BOTTOM, fill=X)
207 208 209 210 211
        self.showhistory = Listbox(
            history_frame,
            yscrollcommand=rightscrollbar2.set,
            xscrollcommand=bottomscrollbar2.set,
            bg="white")
212 213 214 215 216 217 218 219 220 221
        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)

222 223 224 225 226
        #labelbl_ratingls
        lbl_rating_label = Label(rating_frame, text='Rating:')
        lbl_rating_label.pack(side=LEFT)
        lbl_rating = Label(rating_frame, textvariable=self.rating)
        lbl_rating.pack(side=LEFT)
227 228 229 230
        Label(mid_frame, text='Recently Used:').pack(side=LEFT)
        Label(top_frame, text='Module or package').pack(side=LEFT)

        #file textbox
231 232 233
        self.txt_module = Entry(top_frame, background='white')
        self.txt_module.bind('<Return>', self.run_lint)
        self.txt_module.pack(side=LEFT, expand=True, fill=X)
234 235 236 237 238 239

        #results box
        rightscrollbar = Scrollbar(res_frame)
        rightscrollbar.pack(side=RIGHT, fill=Y)
        bottomscrollbar = Scrollbar(res_frame, orient=HORIZONTAL)
        bottomscrollbar.pack(side=BOTTOM, fill=X)
240 241 242 243 244
        self.results = Listbox(
            res_frame,
            yscrollcommand=rightscrollbar.set,
            xscrollcommand=bottomscrollbar.set,
            bg="white", font="Courier")
245 246 247 248 249 250
        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)
251 252
        Button(top_frame, text='Open Package',
               command=(lambda: self.file_open(package=True))).pack(side=LEFT)
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292

        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
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
        report = Radiobutton(
            radio_frame, text="Report", variable=self.box,
            value="Report", command=self.refresh_results_window)
        raw_met = 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)
        msg_cat = 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)
        source_file = Radiobutton(
            radio_frame, text="Source File", variable=self.box,
            value="Source File", command=self.refresh_results_window)
320 321
        report.select()
        report.grid(column=0, row=0, sticky=W)
322
        raw_met.grid(column=1, row=0, sticky=W)
323
        dup.grid(column=2, row=0, sticky=W)
324
        msg.grid(column=3, row=0, sticky=W)
325
        stat.grid(column=0, row=1, sticky=W)
326 327 328
        msg_cat.grid(column=1, row=1, sticky=W)
        ext.grid(column=2, row=1, sticky=W)
        source_file.grid(column=3, row=1, sticky=W)
329 330 331

        #dictionary for check boxes and associated error term
        self.msg_type_dict = {
332 333 334 335 336 337
            '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
338
        }
339
        self.txt_module.focus_set()
340 341


342
    def select_recent_file(self, event): # pylint: disable=unused-argument
343 344 345 346 347 348 349
        """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
350 351
        self.txt_module.delete(0, END)
        self.txt_module.insert(0, item)
352 353 354 355

    def refresh_msg_window(self):
        """refresh the message window with current output"""
        #clear the window
356 357
        self.lb_messages.delete(0, END)
        self.visible_msgs = []
358
        for msg in self.msgs:
359 360 361 362
            if self.msg_type_dict.get(msg.C)():
                self.visible_msgs.append(msg)
                msg_str = convert_to_string(msg)
                self.lb_messages.insert(END, msg_str)
363
                fg_color = COLORS.get(msg_str[:3], 'black')
364
                self.lb_messages.itemconfigure(END, fg=fg_color)
365 366 367 368 369 370 371 372

    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)
373
        except KeyError:
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388
            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
389 390 391 392
                if self.msg_type_dict.get(msg.C)():
                    self.visible_msgs.append(msg)
                    msg_str = convert_to_string(msg)
                    self.lb_messages.insert(END, msg_str)
393
                    fg_color = COLORS.get(msg_str[:3], 'black')
394
                    self.lb_messages.itemconfigure(END, fg=fg_color)
395

396
            except six.moves.queue.Empty:
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
                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()

416
    def halt(self): # pylint: disable=no-self-use
417 418 419 420 421 422
        """program halt placeholder"""
        return

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

        if filename == ():
            return

433 434
        self.txt_module.delete(0, END)
        self.txt_module.insert(0, filename)
435 436 437

    def update_filenames(self):
        """update the list of recent filenames"""
438
        filename = self.txt_module.get()
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        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)
471
        module = self.txt_module.get()
472 473 474 475 476
        if not module:
            module = os.getcwd()

        #cleaning up msgs and windows
        self.msgs = []
477 478
        self.visible_msgs = []
        self.lb_messages.delete(0, END)
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
        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='')

497
    def show_sourcefile(self, event=None):  # pylint: disable=unused-argument
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
        selected = self.lb_messages.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.path, "r").readlines()
        self.box.set("Source File")
        self.refresh_results_window()
        self.results.yview(scroll)
        self.results.select_set(msg.line - 1)

513 514 515 516

def lint_thread(module, reporter, gui):
    """thread for pylint"""
    gui.status.text = "processing module(s)"
517
    pylint.lint.Run(args=[module], reporter=reporter, exit=False)
518 519 520 521 522 523
    gui.msg_queue.put("DONE")


def Run(args):
    """launch pylint gui from args"""
    if args:
524
        print('USAGE: pylint-gui\n launch a simple pylint gui using Tk')
525
        sys.exit(1)
526 527
    gui = LintGui()
    gui.mainloop()
528
    sys.exit(0)
529 530 531

if __name__ == '__main__':
    Run(sys.argv[1:])