Fix for pylint errors

This commit is contained in:
Rnhmjoj 2014-05-31 00:31:27 +02:00
parent b627da25c1
commit af17ef0f47

View File

@ -9,74 +9,74 @@ import tkinter.messagebox
import tkinter.simpledialog import tkinter.simpledialog
class Text(tkinter.Text): class Text(tkinter.Text):
""" '''
Tkinter Text Widget Tkinter Text Widget
Override that allows to highlight words with regex. Override that allows to highlight words with regex.
""" '''
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
tkinter.Text.__init__(self, *args, **kwargs) tkinter.Text.__init__(self, *args, **kwargs)
def highlight(self, pattern, tag, start="1.0", stop="end", regex=True): def highlight(self, pattern, tag, start='1.0', stop='end', regex=True):
""" '''
Highlight text matched by "pattern" and apply it the tag "tag" Highlight text matched by 'pattern' and apply it the tag 'tag'
Specify "start" and "stop" in order to restrict the search and Specify 'start' and 'stop' in order to restrict the search and
regex=False if pattern is not a regex. regex=False if pattern is not a regex.
""" '''
start = self.index(start) start = self.index(start)
stop = self.index(stop) stop = self.index(stop)
self.mark_set("matchStart", start) self.mark_set('matchStart', start)
self.mark_set("matchEnd", start) self.mark_set('matchEnd', start)
self.mark_set("searchLimit", stop) self.mark_set('searchLimit', stop)
occurrences = tkinter.IntVar() occurrences = tkinter.IntVar()
while True: while True:
index = self.search( index = self.search(
pattern, pattern,
"matchEnd", 'matchEnd',
"searchLimit", 'searchLimit',
count=occurrences, count=occurrences,
regexp=regex regexp=regex
) )
if index == "": if index == '':
break break
self.mark_set("matchStart", index) self.mark_set('matchStart', index)
self.mark_set("matchEnd", "%s+%sc" % (index, occurrences.get())) self.mark_set('matchEnd', '%s+%sc' % (index, occurrences.get()))
self.tag_add(tag, "matchStart", "matchEnd") self.tag_add(tag, 'matchStart', 'matchEnd')
class Application(tkinter.Frame): class Application(tkinter.Frame):
"""Application class""" '''Application class'''
def __init__(self): def __init__(self):
tkinter.Frame.__init__(self, window) tkinter.Frame.__init__(self, window)
window.iconify() window.iconify()
#Vars #Vars
self.temp = tempfile.TemporaryFile(mode="w+t") self.temp = tempfile.TemporaryFile(mode='w+t')
self.text = tkinter.StringVar() self.text = tkinter.StringVar()
self.file = "" self.file = ''
self.opzionifile = { self.opzionifile = {
"parent": window, 'parent': window,
"filetypes": [("text files", ".txt")], 'filetypes': [('text files', '.txt')],
"defaultextension": ".txt", 'defaultextension': '.txt',
"initialfile": "file.txt" 'initialfile': 'file.txt'
} }
self.opzionichat = { self.opzionichat = {
"font": ("Monaco", 13), 'font': ('Monaco', 13),
"borderwidth": 2, 'borderwidth': 2,
"highlightthickness": 0 'highlightthickness': 0
} }
#pref management #pref management
try: try:
self.prefs = json.load(open("prefs.json")) self.prefs = json.load(open('prefs.json'))
except FileNotFoundError: except FileNotFoundError:
tkinter.messagebox.showwarning( tkinter.messagebox.showwarning(
"Dropchat", 'Dropchat',
"Preferences file non found!", 'Preferences file non found!',
detail="Default preferences rebuilt.") detail='Default preferences rebuilt.')
self.build_prefs() self.build_prefs()
#Gestione della window #Gestione della window
window.geometry(self.prefs["geometry"]) window.geometry(self.prefs['geometry'])
window.configure(background="#a8a8a8") window.configure(background='#a8a8a8')
window.columnconfigure(1, weight=1) window.columnconfigure(1, weight=1)
window.rowconfigure(0, weight=1) window.rowconfigure(0, weight=1)
window.protocol('WM_DELETE_WINDOW', self.close) window.protocol('WM_DELETE_WINDOW', self.close)
@ -91,13 +91,13 @@ class Application(tkinter.Frame):
#Gestione delle ultime conversazioni #Gestione delle ultime conversazioni
try: try:
self.delete_not_found() self.delete_not_found()
self.file = self.prefs["chat"][-1] self.file = self.prefs['chat'][-1]
except IndexError: except IndexError:
response = tkinter.messagebox.askquestion( response = tkinter.messagebox.askquestion(
"Dropchat", 'Dropchat',
"No conversations found.", 'No conversations found.',
detail="Make a new one?") detail='Make a new one?')
if response == "yes": if response == 'yes':
self.new_file() self.new_file()
#Loop principale #Loop principale
@ -105,136 +105,136 @@ class Application(tkinter.Frame):
#Widget della window #Widget della window
def widgets(self): def widgets(self):
""" '''
Draw window widgets. Draw window widgets.
""" '''
self.menubar = tkinter.Menu(window) self.menubar = tkinter.Menu(window)
self.chat = Text(window, self.chat = Text(window,
width=100, height=30, width=100, height=30,
relief="sunken", relief='sunken',
insertbackground="#fff", insertbackground='#fff',
**self.opzionichat) **self.opzionichat)
self.sidebar = tkinter.Listbox( self.sidebar = tkinter.Listbox(
window, width=20, window, width=20,
borderwidth=0, borderwidth=0,
background="#dce0e8") background='#dce0e8')
self.textbox = tkinter.Entry( self.textbox = tkinter.Entry(
window, textvariable=self.text, window, textvariable=self.text,
**self.opzionichat) **self.opzionichat)
self.chat.grid(column=1, row=0, sticky="nswe", pady=(6, 3), padx=6) self.chat.grid(column=1, row=0, sticky='nswe', pady=(6, 3), padx=6)
self.textbox.grid(column=1, row=1, sticky="nswe", pady=(3, 6), padx=6) self.textbox.grid(column=1, row=1, sticky='nswe', pady=(3, 6), padx=6)
self.sidebar.grid(column=0, row=0, sticky="nswe", rowspan=2) self.sidebar.grid(column=0, row=0, sticky='nswe', rowspan=2)
#Bindings #Bindings
self.chat.bind("<KeyPress>", "break") self.chat.bind('<KeyPress>', 'break')
self.sidebar.bind("<Double-Button-1>", self.switch_file) self.sidebar.bind('<Double-Button-1>', self.switch_file)
self.sidebar.bind("<Button-2>", self.show_menu) self.sidebar.bind('<Button-2>', self.show_menu)
self.textbox.bind("<Return>", self.write) self.textbox.bind('<Return>', self.write)
#Menu bar #Menu bar
self.menubar = tkinter.Menu(self) self.menubar = tkinter.Menu(self)
menu = tkinter.Menu(self.menubar) menu = tkinter.Menu(self.menubar)
#Menu 1 #Menu 1
self.menubar.add_cascade(label="Conversation", menu=menu) self.menubar.add_cascade(label='Conversation', menu=menu)
menu.add_command(label="New file", command=self.new_file) menu.add_command(label='New file', command=self.new_file)
menu.add_command(label="Open file...", command=self.open_file) menu.add_command(label='Open file...', command=self.open_file)
#Menu 2 #Menu 2
menu = tkinter.Menu(self.menubar) menu = tkinter.Menu(self.menubar)
self.menubar.add_cascade(label="Profile", menu=menu) self.menubar.add_cascade(label='Profile', menu=menu)
menu.add_command( menu.add_command(
label="User name", label='User name',
command=lambda: self.edit_prefs( command=lambda: self.edit_prefs(
"username", 'username',
tkinter.simpledialog.askstring( tkinter.simpledialog.askstring(
"User name", 'User name',
"Insert your name:", 'Insert your name:',
initialvalue=self.prefs["username"], initialvalue=self.prefs['username'],
parent=window))) parent=window)))
#Menu 3 #Menu 3
menu = tkinter.Menu(self.menubar) menu = tkinter.Menu(self.menubar)
self.menubar.add_cascade(label="Edit", menu=menu) self.menubar.add_cascade(label='Edit', menu=menu)
menu.add_command(label="Cut", menu.add_command(label='Cut',
command=lambda: window.focus_get().event_generate("<<Cut>>")) command=lambda: window.focus_get().event_generate('<<Cut>>'))
menu.add_command(label="Copy", menu.add_command(label='Copy',
command=lambda: window.focus_get().event_generate("<<Copy>>")) command=lambda: window.focus_get().event_generate('<<Copy>>'))
menu.add_command(label="Paste", menu.add_command(label='Paste',
command=lambda: window.focus_get().event_generate("<<Paste>>")) command=lambda: window.focus_get().event_generate('<<Paste>>'))
window.config(menu=self.menubar) window.config(menu=self.menubar)
#Context menu 1 #Context menu 1
self.menu1 = tkinter.Menu(self) self.menu1 = tkinter.Menu(self)
self.menu1.add_command(label="Open", command=self.switch_file) self.menu1.add_command(label='Open', command=self.switch_file)
self.menu1.add_command(label="Delete", command=self.delete_file) self.menu1.add_command(label='Delete', command=self.delete_file)
self.menu1.add_separator() self.menu1.add_separator()
self.menu1.add_command(label="New file", command=self.new_file) self.menu1.add_command(label='New file', command=self.new_file)
self.menu1.add_command(label="Reload", self.menu1.add_command(label='Reload',
command=lambda: self.sidebar.delete(0, "end")) command=lambda: self.sidebar.delete(0, 'end'))
#Contextmenu 2 #Contextmenu 2
self.menu2 = tkinter.Menu(self) self.menu2 = tkinter.Menu(self)
self.menu2.add_command(label="New file", command=self.new_file) self.menu2.add_command(label='New file', command=self.new_file)
self.menu2.add_command(label="Reload", self.menu2.add_command(label='Reload',
command=lambda: self.sidebar.delete(0, "end")) command=lambda: self.sidebar.delete(0, 'end'))
def read(self): def read(self):
""" '''
Reads the current file from the buffer Reads the current file from the buffer
and writes it into the chat. and writes it into the chat.
""" '''
self.update() self.update()
self.temp.seek(0) self.temp.seek(0)
self.chat.delete(0.0, "end") self.chat.delete(0.0, 'end')
self.chat.insert("end", self.temp.read()) self.chat.insert('end', self.temp.read())
self.highlight() self.highlight()
def write(self, event): def write(self, _):
"""Write a message in the current file""" '''Write a message in the current file'''
if self.file != "": if self.file != '':
with open(self.file, "a") as file: with open(self.file, 'a') as file:
if self.text.get() != "": if self.text.get() != '':
row = "[%s] %s: %s\n" % ( row = '[%s] %s: %s\n' % (
datetime.datetime.now().strftime("%d-%m-%y %H:%M"), datetime.datetime.now().strftime('%d-%m-%y %H:%M'),
self.prefs["username"], self.prefs['username'],
self.text.get()) self.text.get())
self.text.set("") self.text.set('')
file.write(row) file.write(row)
def update(self): def update(self):
"""Copy file into the buffer""" '''Copy file into the buffer'''
self.temp.seek(0) self.temp.seek(0)
self.temp.truncate() self.temp.truncate()
if self.file != "": if self.file != '':
with open(self.file) as text: with open(self.file) as text:
self.temp.write(text.read()) self.temp.write(text.read())
def set_title(self): def set_title(self):
"""Update window's title to match current conversation""" '''Update window's title to match current conversation'''
file = re.search("([^/]*)$", self.file) file = re.search('([^/]*)$', self.file)
if self.file == "": if self.file == '':
window.title("Dropchat") window.title('Dropchat')
else: else:
window.title("Dropchat - " + file.group(0)) window.title('Dropchat - ' + file.group(0))
def highlight(self): def highlight(self):
""" '''
Highlight semantic parts in the text chat. Highlight semantic parts in the text chat.
(Date, username and others) (Date, username and others)
""" '''
self.chat.tag_configure("date", foreground="#005d8f") self.chat.tag_configure('date', foreground='#005d8f')
self.chat.tag_configure("name", foreground="#648f00") self.chat.tag_configure('name', foreground='#648f00')
self.chat.tag_configure("other", foreground="#de7a31") self.chat.tag_configure('other', foreground='#de7a31')
self.chat.highlight("\[\d+-\d+-\d+ \d+:\d+\]", "data") self.chat.highlight(r'\[\d+-\d+-\d+ \d+:\d+\]', 'data')
for name in re.findall(" ([a-zA-Z]+): ", self.chat.get(0.0, "end")): for name in re.findall(' ([a-zA-Z]+): ', self.chat.get(0.0, 'end')):
if name == self.prefs["username"]: if name == self.prefs['username']:
self.chat.highlight(name, "name") self.chat.highlight(name, 'name')
else: else:
self.chat.highlight(name, "other") self.chat.highlight(name, 'other')
def show_menu(self, event): def show_menu(self, event):
"""Manages the opening and positioning of context menu""" '''Manages the opening and positioning of context menu'''
self.sidebar.index = self.sidebar.nearest(event.y) self.sidebar.index = self.sidebar.nearest(event.y)
if self.sidebar.index < 0: if self.sidebar.index < 0:
self.menu2.post(event.x_root, event.y_root) self.menu2.post(event.x_root, event.y_root)
@ -247,109 +247,109 @@ class Application(tkinter.Frame):
self.menu1.post(event.x_root, event.y_root) self.menu1.post(event.x_root, event.y_root)
def recent_files(self): def recent_files(self):
"""Inserts recently opened files into the sidebar""" '''Inserts recently opened files into the sidebar'''
for x, file in enumerate(self.prefs["chat"]): for x, file in enumerate(self.prefs['chat']):
file = " - " + re.search("([^/]*)$", file).group(0) file = ' - ' + re.search('([^/]*)$', file).group(0)
if file not in self.sidebar.get(x): if file not in self.sidebar.get(x):
self.sidebar.insert(x, file) self.sidebar.insert(x, file)
def delete_file(self): def delete_file(self):
"""Removes the currently selected file from the sidebar""" '''Removes the currently selected file from the sidebar'''
if self.prefs["Chat"][self.sidebar.index] == self.file: if self.prefs['Chat'][self.sidebar.index] == self.file:
self.file = "" self.file = ''
del self.prefs["Chat"][self.sidebar.index] del self.prefs['Chat'][self.sidebar.index]
json.dump(self.prefs, open("prefs.json", "w")) json.dump(self.prefs, open('prefs.json', 'w'))
self.read() self.read()
self.set_title() self.set_title()
def switch_file(self, _=None): def switch_file(self, _=None):
"""Opens the currently selected file from the sidebar in the chat""" '''Opens the currently selected file from the sidebar in the chat'''
file = self.prefs["chat"][int(self.sidebar.curselection()[0])] file = self.prefs['chat'][int(self.sidebar.curselection()[0])]
if self.file != file: if self.file != file:
self.file = file self.file = file
self.read() self.read()
self.set_title() self.set_title()
def open_file(self): def open_file(self):
"""Selects a new file and opens it in the chat.""" '''Selects a new file and opens it in the chat.'''
if sys.platform == "darwin": if sys.platform == 'darwin':
file = tkinter.filedialog.askopenfilename( file = tkinter.filedialog.askopenfilename(
title="Choose a file...", title='Choose a file...',
message="Open a conversation.", message='Open a conversation.',
**self.opzionifile) **self.opzionifile)
else: else:
file = tkinter.filedialog.askopenfilename( file = tkinter.filedialog.askopenfilename(
title="Choose a file...", title='Choose a file...',
**self.opzionifile) **self.opzionifile)
if file not in self.prefs["Chat"] and file != "": if file not in self.prefs['Chat'] and file != '':
self.prefs["chat"] += file, self.prefs['chat'] += file,
json.dump(self.prefs, open("prefs.json", "w")) json.dump(self.prefs, open('prefs.json', 'w'))
self.file = file self.file = file
self.read() self.read()
self.set_title() self.set_title()
def new_file(self): def new_file(self):
"""Creates a new file and opens it in the chat""" '''Creates a new file and opens it in the chat'''
if sys.platform == "darwin": if sys.platform == 'darwin':
file = tkinter.filedialog.asksaveasfilename( file = tkinter.filedialog.asksaveasfilename(
title="Create a file...", title='Create a file...',
message="Select the name of the new conversation.", message='Select the name of the new conversation.',
**self.opzionifile) **self.opzionifile)
else: else:
file = tkinter.filedialog.asksaveasfilename( file = tkinter.filedialog.asksaveasfilename(
title="Creates a new file...", title='Creates a new file...',
**self.opzionifile) **self.opzionifile)
if file != "": if file != '':
self.file = file self.file = file
open(self.file, "w").close() open(self.file, 'w').close()
if self.file not in self.prefs["chat"]: if self.file not in self.prefs['chat']:
self.prefs["chat"] += self.file, self.prefs['chat'] += self.file,
json.dump(self.prefs, open("prefs.json", "w")) json.dump(self.prefs, open('prefs.json', 'w'))
self.read() self.read()
self.set_title() self.set_title()
def delete_not_found(self): def delete_not_found(self):
"""Removes files that are no longer available""" '''Removes files that are no longer available'''
for x, file in enumerate(self.prefs["chat"]): for x, file in enumerate(self.prefs['chat']):
try: try:
open(file) open(file)
self.file = file self.file = file
except FileNotFoundError: except FileNotFoundError:
del self.prefs["Chat"][x] del self.prefs['Chat'][x]
continue continue
json.dump(self.prefs, open("prefs.json", "w")) json.dump(self.prefs, open('prefs.json', 'w'))
def build_prefs(self): def build_prefs(self):
"""Rebuild default preferences""" '''Rebuild default preferences'''
default = { default = {
"username": "user", 'username': 'user',
"chat": ["chat.txt"], 'chat': ['chat.txt'],
"geometry": "800x500+500+250" 'geometry': '800x500+500+250'
} }
json.dump(default, open("prefs.json", "w")) json.dump(default, open('prefs.json', 'w'))
self.prefs = json.load(open("prefs.json")) self.prefs = json.load(open('prefs.json'))
def edit_prefs(self, key, pref): def edit_prefs(self, key, pref):
"""Changing a preference and saves it into an external file.""" '''Changing a preference and saves it into an external file.'''
if pref != "": if pref != '':
self.prefs[key] = pref self.prefs[key] = pref
json.dump(self.prefs, open("prefs.json", "w")) json.dump(self.prefs, open('prefs.json', 'w'))
def close(self): def close(self):
""" '''
Save the geometry of the window for the next boot, Save the geometry of the window for the next boot,
closes and deletes the cache, closes and deletes the cache,
closes the window and exits. closes the window and exits.
""" '''
self.edit_prefs("geometry", window.geometry()) self.edit_prefs('geometry', window.geometry())
self.temp.close() self.temp.close()
window.destroy() window.destroy()
def loop(self): def loop(self):
""" '''
Main loop Main loop
Update recent files and current covnersation. Update recent files and current covnersation.
""" '''
self.recent_files() self.recent_files()
self.read() self.read()
self.after(200, self.loop) self.after(200, self.loop)