class App(object): def __init__(self): self.window = tk.Tk() self.window.attributes("-fullscreen",True) self.window.minsize(width=320, height=240) self.window.maxsize(width=320, height=240) self.buttonFrame = tk.Frame(self.window) self.printButton=tk.Button(self.buttonFrame, text='PRINT!', height=2, command=self.printTxt) self.printButton.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5) self.loadButton=tk.Button(self.buttonFrame, text='LOAD', height=2, command=self.load) self.loadButton.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5, expand=1) self.exitButton=tk.Button(self.buttonFrame, text='EXIT', height=2, command=self.exitWin) self.exitButton.pack(side=tk.LEFT, fill=tk.X, padx=5, pady=5, expand=1) self.buttonFrame.pack(side=tk.TOP) self.filename = '/home/pi/Desktop/fly.txt' self.txt = ScrolledText(self.window) self.txt.vbar.config(width=18) self.txt.pack(expand=True, fill=tk.BOTH) self.loadFile() self.poll() def poll(self): if(float(self.txt.vbar.get()[1])==1): self.txt.see(1.0) #goto top else: self.txt.yview(tk.SCROLL,1,tk.UNITS) self.window.after(1000, self.poll) def load(self): self.filename = askopenfilename(initialdir="/home/pi/Desktop", title="SELECT TXT", filetypes=(("txt files","*.txt"),("all files","*.*")) ) self.loadFile() def loadFile(self): self.txt.delete(1.0,tk.END) fly = open(self.filename,'r') self.txt.insert(1.0, fly.read()) fly.close() def printTxt(self): call(["lp", self.filename]) tkMessageBox.showinfo("PRINT", "it's printing!") def exitWin(self): result = tkMessageBox.askquestion("EXIT?!", "zomg, u sure?", icon='warning') if result == 'yes': self.window.quit()
class NamedWindow: """ This creates a window for the Tkui which you can then write to programmatically. This allows modules to spin off new named windows and write to them. """ def __init__(self, windowname, master, partk): """ Initializes the window @param windowname: the name of the new window @type windowname: string @param master: the main tk window @type master: toplevel """ self._parent = master self._tk = Toplevel(partk) self._windowname = windowname # map of session -> (bold, foreground, background) self._currcolors = {} # ses -> string self._unfinishedcolor = {} self._do_i_echo = 1 self._tk.geometry("500x300") self._tk.title("Lyntin -- " + self._windowname) self._tk.protocol("WM_DELETE_WINDOW", self.close) if os.name == "posix": fontname = "Courier" else: fontname = "Fixedsys" fnt = tkFont.Font(family=fontname, size=12) self._txt = ScrolledText(self._tk, fg="white", bg="black", font=fnt, height=20) self._txt.pack(side=TOP, fill=BOTH, expand=1) # handles improper keypresses self._txt.bind("<KeyPress>", self._ignoreThis) # initialize color tags self._initColorTags() def convertColor(self, name): """ Tk has this really weird color palatte. So I switched to using color names in most cases and rgb values in cases where I couldn't find a good color name. This method allows me to specify either an rgb or a color name and it converts the color names to rgb. @param name: either an rgb value or a name @type name: string @returns: the rgb color value @rtype: string """ if name[0] == "#": return name rgb = self._tk._getints(self._tk.tk.call("winfo", "rgb", self._txt, name)) rgb = "#%02x%02x%02x" % (rgb[0] / 256, rgb[1] / 256, rgb[2] / 256) print name, "converted to: ", rgb return rgb def _initColorTags(self): """ Sets up Tk tags for the text widget (fg/bg).""" for ck in fg_color_codes.keys(): color = self.convertColor(fg_color_codes[ck]) self._txt.tag_config(ck, foreground=color) for ck in bg_color_codes.keys(): self._txt.tag_config(ck, background=bg_color_codes[ck]) self._txt.tag_config("u", underline=1) def _ignoreThis(self, tkevent): """ This catches keypresses to this window. """ return "break" def close(self): """ Closes and destroys references to this window. """ self._parent.removeWindow(self._windowname) self._tk.destroy() def _yadjust(self): """Handles y scrolling after text insertion.""" self._txt.yview("moveto", "1") # if os.name != 'posix': self._txt.yview("scroll", "20", "units") def _clipText(self): """ Scrolls the text buffer up so that the new text written at the bottom of the text buffer can be seen. """ temp = self._txt.index("end") ind = temp.find(".") temp = temp[:ind] if temp.isdigit() and int(temp) > 800: self._txt.delete("1.0", "100.end") def write(self, msg): """ This writes text to the text buffer for viewing by the user. This is overridden from the 'base.BaseUI'. """ if type(msg) == types.TupleType: msg = msg[0] if type(msg) == types.StringType: msg = message.Message(msg, message.LTDATA) line = msg.data ses = msg.session if line == "": return color, leftover = buffer_write(msg, self._txt, self._currcolors, self._unfinishedcolor) if msg.type == message.MUDDATA: self._unfinishedcolor[ses] = leftover self._currcolors[ses] = color self._clipText() self._yadjust()
class Tkui(base.BaseUI): """ This is a ui class which handles the complete Tk user interface. """ def __init__(self): """ Initializes.""" base.BaseUI.__init__(self) # internal ui queue self._event_queue = Queue.Queue() # map of session -> (bold, foreground, background) self._currcolors = {} # ses -> string self._unfinishedcolor = {} self._viewhistory = 0 self._do_i_echo = 1 # holds a map of window names -> window references self._windows = {} # instantiate all the widgets self._tk = Tk() self._tk.geometry("800x600") self.settitle() if os.name == "posix": fnt = tkFont.Font(family="Courier", size=12) else: fnt = tkFont.Font(family="Fixedsys", size=12) self._entry = CommandEntry( self._tk, self, fg="white", bg="black", insertbackground="yellow", font=fnt, insertwidth="2" ) self._entry.pack(side="bottom", fill="both") self._topframe = Frame(self._tk) self._topframe.pack(side="top", fill="both", expand=1) self._txt = ScrolledText(self._topframe, fg="white", bg="black", font=fnt, height=20) self._txt.pack(side="bottom", fill="both", expand=1) self._txt.bind("<KeyPress>", self._ignoreThis) self._txtbuffer = ScrolledText(self._topframe, fg="white", bg="black", font=fnt, height=20) self._txtbuffer.bind("<KeyPress-Escape>", self.escape) self._txtbuffer.bind("<KeyPress>", self._ignoreThis) self._entry.focus_set() self._initColorTags() self.dequeue() exported.hook_register("config_change_hook", self.configChangeHandler) exported.hook_register("to_user_hook", self.write) # FIXME - fix this explanation. this is just terrible. tc = config.BoolConfig( "saveinputhighlight", 0, 1, "Allows you to change the behavior of the command entry. When " "saveinputhighlight is off, we discard whatever is on the entry " "line. When it is on, we will retain the contents allowing you " "to press the enter key to do whatever you typed again.", ) exported.add_config("saveinputhighlight", tc) self._quit = 0 def runui(self): global HELP_TEXT exported.add_help("tkui", HELP_TEXT) exported.write_message('For tk help type "#help tkui".') exported.add_command("colorcheck", colorcheck_cmd) # run the tk mainloop here self._tk.mainloop() def wantMainThread(self): # The tkui needs the main thread of execution so we return # a 1 here. return 1 def quit(self): if not self._quit: self._quit = 1 self._topframe.quit() def dequeue(self): qsize = self._event_queue.qsize() if qsize > 10: qsize = 10 for i in range(qsize): ev = self._event_queue.get_nowait() ev.execute(self) self._tk.after(25, self.dequeue) def settitle(self, title=""): """ Sets the title bar to the Lyntin title plus the given string. @param title: the title to set @type title: string """ if title: title = constants.LYNTINTITLE + title else: title = constants.LYNTINTITLE self._event_queue.put(_TitleEvent(self._tk, title)) def removeWindow(self, windowname): """ This removes a NamedWindow from our list of NamedWindows. @param windowname: the name of the window to write to @type windowname: string """ if self._windows.has_key(windowname): del self._windows[windowname] def writeWindow(self, windowname, message): """ This writes to the window named "windowname". If the window does not exist, we spin one off. It handles ansi text and messages just like writing to the main window. @param windowname: the name of the window to write to @type windowname: string @param message: the message to write to the window @type message: string or Message instance """ self._event_queue.put(_WriteWindowEvent(windowname, message)) def writeWindow_internal(self, windowname, message): if not self._windows.has_key(windowname): self._windows[windowname] = NamedWindow(windowname, self, self._tk) self._windows[windowname].write(message) def _ignoreThis(self, tkevent): """ This catches keypresses from the history buffer.""" # kludge so that ctrl-c doesn't get caught allowing windows # users to copy the buffer.... if tkevent.keycode == 17 or tkevent.keycode == 67: return self._entry.focus() if tkevent.char: # we do this little song and dance so as to pass events # we don't want to deal with to the entry widget essentially # by creating a new event and tossing it in the event list. # it only sort of works--but it's the best code we've got # so far. args = ("event", "generate", self._entry, "<KeyPress>") args = args + ("-rootx", tkevent.x_root) args = args + ("-rooty", tkevent.y_root) args = args + ("-keycode", tkevent.keycode) args = args + ("-keysym", tkevent.keysym) self._tk.tk.call(args) return "break" def pageUp(self): """ Handles prior (Page-Up) events.""" if self._viewhistory == 0: self._txtbuffer.pack(side="top", fill="both", expand=1) self._viewhistory = 1 self._txtbuffer.delete("1.0", "end") lotofstuff = self._txt.get("1.0", "end") self._txtbuffer.insert("end", lotofstuff) for t in self._txt.tag_names(): taux = None tst = 0 for e in self._txt.tag_ranges(t): if tst == 0: taux = e tst = 1 else: tst = 0 self._txtbuffer.tag_add(t, str(taux), str(e)) self._txtbuffer.yview("moveto", "1") if os.name != "posix": self._txtbuffer.yview("scroll", "20", "units") self._tk.update_idletasks() self._txt.yview("moveto", "1.0") if os.name != "posix": self._txt.yview("scroll", "220", "units") else: # yscroll up stuff self._txtbuffer.yview("scroll", "-15", "units") def pageDown(self): """ Handles next (Page-Down) events.""" if self._viewhistory == 1: # yscroll down stuff self._txtbuffer.yview("scroll", "15", "units") def escape(self, tkevent): """ Handles escape (Escape) events.""" if self._viewhistory == 1: self._txtbuffer.forget() self._viewhistory = 0 else: self._entry.clearInput() def configChangeHandler(self, args): """ This handles config changes including mudecho. """ name = args["name"] newvalue = args["newvalue"] if name == "mudecho": if newvalue == 1: # echo on self._do_i_echo = 1 self._entry.configure(show="") else: # echo off self._do_i_echo = 0 self._entry.configure(show="*") def _yadjust(self): """Handles y scrolling after text insertion.""" self._txt.yview("moveto", "1") # if os.name != 'posix': self._txt.yview("scroll", "20", "units") def _clipText(self): """ Scrolls the text buffer up so that the new text written at the bottom of the text buffer can be seen. """ temp = self._txt.index("end") ind = temp.find(".") temp = temp[:ind] if temp.isdigit() and int(temp) > 800: self._txt.delete("1.0", "100.end") def write(self, args): """ This writes text to the text buffer for viewing by the user. This is overridden from the 'base.BaseUI'. """ self._event_queue.put(_OutputEvent(args)) def write_internal(self, args): mess = args["message"] if type(mess) == types.StringType: mess = message.Message(mess, message.LTDATA) line = mess.data ses = mess.session if line == "" or self.showTextForSession(ses) == 0: return color, leftover = buffer_write(mess, self._txt, self._currcolors, self._unfinishedcolor) if mess.type == message.MUDDATA: self._unfinishedcolor[ses] = leftover self._currcolors[ses] = color self._clipText() self._yadjust() def convertColor(self, name): """ Tk has this really weird color palatte. So I switched to using color names in most cases and rgb values in cases where I couldn't find a good color name. This method allows me to specify either an rgb or a color name and it converts the color names to rgb. @param name: either an rgb value or a name @type name: string @returns: the rgb color value @rtype: string """ if name.startswith("#"): return name rgb = self._tk._getints(self._tk.tk.call("winfo", "rgb", self._txt, name)) rgb = "#%02x%02x%02x" % (rgb[0] / 256, rgb[1] / 256, rgb[2] / 256) print name, "converted to: ", rgb return rgb def _initColorTags(self): """ Sets up Tk tags for the text widget (fg/bg/u).""" for ck in fg_color_codes.keys(): color = self.convertColor(fg_color_codes[ck]) self._txt.tag_config(ck, foreground=color) self._txtbuffer.tag_config(ck, foreground=color) for ck in bg_color_codes.keys(): self._txt.tag_config(ck, background=bg_color_codes[ck]) self._txtbuffer.tag_config(ck, background=bg_color_codes[ck]) self._txt.tag_config("u", underline=1) self._txtbuffer.tag_config("u", underline=1) def colorCheck(self): """ Goes through and displays all the combinations of fg and bg with the text string involved. Purely for debugging purposes. """ fgkeys = ["30", "31", "32", "33", "34", "35", "36", "37"] bgkeys = ["40", "41", "42", "43", "44", "45", "46", "47"] self._txt.insert("end", "color check:\n") for bg in bgkeys: for fg in fgkeys: self._txt.insert("end", str(fg), (fg, bg)) self._txt.insert("end", str("b" + fg), ("b" + fg, bg)) self._txt.insert("end", "\n") for fg in fgkeys: self._txt.insert("end", str(fg), (fg, "b" + bg)) self._txt.insert("end", str("b" + fg), ("b" + fg, "b" + bg)) self._txt.insert("end", "\n") self._txt.insert("end", "\n") self._txt.insert("end", "\n")
class NamedWindow: """ This creates a window for the Tkui which you can then write to programmatically. This allows modules to spin off new named windows and write to them. """ def __init__(self, windowname, master, partk): """ Initializes the window @param windowname: the name of the new window @type windowname: string @param master: the main tk window @type master: toplevel """ self._parent = master self._tk = Toplevel(partk) self._windowname = windowname # map of session -> (bold, foreground, background) self._currcolors = {} # ses -> string self._unfinishedcolor = {} self._do_i_echo = 1 self._tk.geometry("500x300") self._tk.title("Lyntin -- " + self._windowname) self._tk.protocol("WM_DELETE_WINDOW", self.close) if os.name == "posix": fontname = "Courier" else: fontname = "Fixedsys" fnt = tkFont.Font(family=fontname, size=12) self._txt = ScrolledText(self._tk, fg="white", bg="black", font=fnt, height=20) self._txt.pack(side=TOP, fill=BOTH, expand=1) # handles improper keypresses self._txt.bind("<KeyPress>", self._ignoreThis) # initialize color tags self._initColorTags() def convertColor(self, name): """ Tk has this really weird color palatte. So I switched to using color names in most cases and rgb values in cases where I couldn't find a good color name. This method allows me to specify either an rgb or a color name and it converts the color names to rgb. @param name: either an rgb value or a name @type name: string @returns: the rgb color value @rtype: string """ if name[0] == "#": return name rgb = self._tk._getints( self._tk.tk.call('winfo', 'rgb', self._txt, name)) rgb = "#%02x%02x%02x" % (rgb[0] / 256, rgb[1] / 256, rgb[2] / 256) print name, "converted to: ", rgb return rgb def _initColorTags(self): """ Sets up Tk tags for the text widget (fg/bg).""" for ck in fg_color_codes.keys(): color = self.convertColor(fg_color_codes[ck]) self._txt.tag_config(ck, foreground=color) for ck in bg_color_codes.keys(): self._txt.tag_config(ck, background=bg_color_codes[ck]) self._txt.tag_config("u", underline=1) def _ignoreThis(self, tkevent): """ This catches keypresses to this window. """ return "break" def close(self): """ Closes and destroys references to this window. """ self._parent.removeWindow(self._windowname) self._tk.destroy() def _yadjust(self): """Handles y scrolling after text insertion.""" self._txt.yview('moveto', '1') # if os.name != 'posix': self._txt.yview('scroll', '20', 'units') def _clipText(self): """ Scrolls the text buffer up so that the new text written at the bottom of the text buffer can be seen. """ temp = self._txt.index("end") ind = temp.find(".") temp = temp[:ind] if (temp.isdigit() and int(temp) > 800): self._txt.delete("1.0", "100.end") def write(self, msg): """ This writes text to the text buffer for viewing by the user. This is overridden from the 'base.BaseUI'. """ if type(msg) == types.TupleType: msg = msg[0] if type(msg) == types.StringType: msg = message.Message(msg, message.LTDATA) line = msg.data ses = msg.session if line == '': return color, leftover = buffer_write(msg, self._txt, self._currcolors, self._unfinishedcolor) if msg.type == message.MUDDATA: self._unfinishedcolor[ses] = leftover self._currcolors[ses] = color self._clipText() self._yadjust()
class Tkui(base.BaseUI): """ This is a ui class which handles the complete Tk user interface. """ def __init__(self): """ Initializes.""" base.BaseUI.__init__(self) # internal ui queue self._event_queue = Queue.Queue() # map of session -> (bold, foreground, background) self._currcolors = {} # ses -> string self._unfinishedcolor = {} self._viewhistory = 0 self._do_i_echo = 1 # holds a map of window names -> window references self._windows = {} # instantiate all the widgets self._tk = Tk() self._tk.geometry("800x600") self.settitle() if os.name == 'posix': fnt = tkFont.Font(family="Courier", size=12) else: fnt = tkFont.Font(family="Fixedsys", size=12) self._entry = CommandEntry(self._tk, self, fg='white', bg='black', insertbackground='yellow', font=fnt, insertwidth='2') self._entry.pack(side='bottom', fill='both') self._topframe = Frame(self._tk) self._topframe.pack(side='top', fill='both', expand=1) self._txt = ScrolledText(self._topframe, fg='white', bg='black', font=fnt, height=20) self._txt.pack(side='bottom', fill='both', expand=1) self._txt.bind("<KeyPress>", self._ignoreThis) self._txtbuffer = ScrolledText(self._topframe, fg='white', bg='black', font=fnt, height=20) self._txtbuffer.bind("<KeyPress-Escape>", self.escape) self._txtbuffer.bind("<KeyPress>", self._ignoreThis) self._entry.focus_set() self._initColorTags() self.dequeue() exported.hook_register("config_change_hook", self.configChangeHandler) exported.hook_register("to_user_hook", self.write) # FIXME - fix this explanation. this is just terrible. tc = config.BoolConfig( "saveinputhighlight", 0, 1, "Allows you to change the behavior of the command entry. When " "saveinputhighlight is off, we discard whatever is on the entry " "line. When it is on, we will retain the contents allowing you " "to press the enter key to do whatever you typed again.") exported.add_config("saveinputhighlight", tc) self._quit = 0 def runui(self): global HELP_TEXT exported.add_help("tkui", HELP_TEXT) exported.write_message("For tk help type \"#help tkui\".") exported.add_command("colorcheck", colorcheck_cmd) # run the tk mainloop here self._tk.mainloop() def wantMainThread(self): # The tkui needs the main thread of execution so we return # a 1 here. return 1 def quit(self): if not self._quit: self._quit = 1 self._topframe.quit() def dequeue(self): qsize = self._event_queue.qsize() if qsize > 10: qsize = 10 for i in range(qsize): ev = self._event_queue.get_nowait() ev.execute(self) self._tk.after(25, self.dequeue) def settitle(self, title=""): """ Sets the title bar to the Lyntin title plus the given string. @param title: the title to set @type title: string """ if title: title = constants.LYNTINTITLE + title else: title = constants.LYNTINTITLE self._event_queue.put(_TitleEvent(self._tk, title)) def removeWindow(self, windowname): """ This removes a NamedWindow from our list of NamedWindows. @param windowname: the name of the window to write to @type windowname: string """ if self._windows.has_key(windowname): del self._windows[windowname] def writeWindow(self, windowname, message): """ This writes to the window named "windowname". If the window does not exist, we spin one off. It handles ansi text and messages just like writing to the main window. @param windowname: the name of the window to write to @type windowname: string @param message: the message to write to the window @type message: string or Message instance """ self._event_queue.put(_WriteWindowEvent(windowname, message)) def writeWindow_internal(self, windowname, message): if not self._windows.has_key(windowname): self._windows[windowname] = NamedWindow(windowname, self, self._tk) self._windows[windowname].write(message) def _ignoreThis(self, tkevent): """ This catches keypresses from the history buffer.""" # kludge so that ctrl-c doesn't get caught allowing windows # users to copy the buffer.... if tkevent.keycode == 17 or tkevent.keycode == 67: return self._entry.focus() if tkevent.char: # we do this little song and dance so as to pass events # we don't want to deal with to the entry widget essentially # by creating a new event and tossing it in the event list. # it only sort of works--but it's the best code we've got # so far. args = ('event', 'generate', self._entry, "<KeyPress>") args = args + ('-rootx', tkevent.x_root) args = args + ('-rooty', tkevent.y_root) args = args + ('-keycode', tkevent.keycode) args = args + ('-keysym', tkevent.keysym) self._tk.tk.call(args) return "break" def pageUp(self): """ Handles prior (Page-Up) events.""" if self._viewhistory == 0: self._txtbuffer.pack(side='top', fill='both', expand=1) self._viewhistory = 1 self._txtbuffer.delete("1.0", "end") lotofstuff = self._txt.get('1.0', 'end') self._txtbuffer.insert('end', lotofstuff) for t in self._txt.tag_names(): taux = None tst = 0 for e in self._txt.tag_ranges(t): if tst == 0: taux = e tst = 1 else: tst = 0 self._txtbuffer.tag_add(t, str(taux), str(e)) self._txtbuffer.yview('moveto', '1') if os.name != 'posix': self._txtbuffer.yview('scroll', '20', 'units') self._tk.update_idletasks() self._txt.yview('moveto', '1.0') if os.name != 'posix': self._txt.yview('scroll', '220', 'units') else: # yscroll up stuff self._txtbuffer.yview('scroll', '-15', 'units') def pageDown(self): """ Handles next (Page-Down) events.""" if self._viewhistory == 1: # yscroll down stuff self._txtbuffer.yview('scroll', '15', 'units') def escape(self, tkevent): """ Handles escape (Escape) events.""" if self._viewhistory == 1: self._txtbuffer.forget() self._viewhistory = 0 else: self._entry.clearInput() def configChangeHandler(self, args): """ This handles config changes including mudecho. """ name = args["name"] newvalue = args["newvalue"] if name == "mudecho": if newvalue == 1: # echo on self._do_i_echo = 1 self._entry.configure(show='') else: # echo off self._do_i_echo = 0 self._entry.configure(show='*') def _yadjust(self): """Handles y scrolling after text insertion.""" self._txt.yview('moveto', '1') # if os.name != 'posix': self._txt.yview('scroll', '20', 'units') def _clipText(self): """ Scrolls the text buffer up so that the new text written at the bottom of the text buffer can be seen. """ temp = self._txt.index("end") ind = temp.find(".") temp = temp[:ind] if (temp.isdigit() and int(temp) > 800): self._txt.delete("1.0", "100.end") def write(self, args): """ This writes text to the text buffer for viewing by the user. This is overridden from the 'base.BaseUI'. """ self._event_queue.put(_OutputEvent(args)) def write_internal(self, args): mess = args["message"] if type(mess) == types.StringType: mess = message.Message(mess, message.LTDATA) line = mess.data ses = mess.session if line == '' or self.showTextForSession(ses) == 0: return color, leftover = buffer_write(mess, self._txt, self._currcolors, self._unfinishedcolor) if mess.type == message.MUDDATA: self._unfinishedcolor[ses] = leftover self._currcolors[ses] = color self._clipText() self._yadjust() def convertColor(self, name): """ Tk has this really weird color palatte. So I switched to using color names in most cases and rgb values in cases where I couldn't find a good color name. This method allows me to specify either an rgb or a color name and it converts the color names to rgb. @param name: either an rgb value or a name @type name: string @returns: the rgb color value @rtype: string """ if name.startswith("#"): return name rgb = self._tk._getints( self._tk.tk.call('winfo', 'rgb', self._txt, name)) rgb = "#%02x%02x%02x" % (rgb[0] / 256, rgb[1] / 256, rgb[2] / 256) print name, "converted to: ", rgb return rgb def _initColorTags(self): """ Sets up Tk tags for the text widget (fg/bg/u).""" for ck in fg_color_codes.keys(): color = self.convertColor(fg_color_codes[ck]) self._txt.tag_config(ck, foreground=color) self._txtbuffer.tag_config(ck, foreground=color) for ck in bg_color_codes.keys(): self._txt.tag_config(ck, background=bg_color_codes[ck]) self._txtbuffer.tag_config(ck, background=bg_color_codes[ck]) self._txt.tag_config("u", underline=1) self._txtbuffer.tag_config("u", underline=1) def colorCheck(self): """ Goes through and displays all the combinations of fg and bg with the text string involved. Purely for debugging purposes. """ fgkeys = ['30', '31', '32', '33', '34', '35', '36', '37'] bgkeys = ['40', '41', '42', '43', '44', '45', '46', '47'] self._txt.insert('end', 'color check:\n') for bg in bgkeys: for fg in fgkeys: self._txt.insert('end', str(fg), (fg, bg)) self._txt.insert('end', str("b" + fg), ("b" + fg, bg)) self._txt.insert('end', '\n') for fg in fgkeys: self._txt.insert('end', str(fg), (fg, "b" + bg)) self._txt.insert('end', str("b" + fg), ("b" + fg, "b" + bg)) self._txt.insert('end', '\n') self._txt.insert('end', '\n') self._txt.insert('end', '\n')
class Switcher(Tk): def __init__(self): Tk.__init__(self) self.resizable(0, 0) self.title(string=".o0O| TOR IP Switcher |O0o.") self.host = StringVar() self.port = IntVar() self.passwd = StringVar() self.time = DoubleVar() self.host.set('localhost') self.port.set('9051') self.passwd.set('') self.time.set('30') Label(self, text='Host:').grid(row=1, column=1, sticky=E) Label(self, text='Port:').grid(row=2, column=1, sticky=E) Label(self, text='Password:'******'Interval:').grid(row=4, column=1, sticky=E) Entry(self, textvariable=self.host).grid(row=1, column=2, columnspan=2) Entry(self, textvariable=self.port).grid(row=2, column=2, columnspan=2) Entry(self, textvariable=self.passwd, show='*').grid(row=3, column=2, columnspan=2) Entry(self, textvariable=self.time).grid(row=4, column=2, columnspan=2) Button(self, text='Start', command=self.start).grid(row=5, column=2) Button(self, text='Stop', command=self.stop).grid(row=5, column=3) self.output = ScrolledText(self, foreground="white", background="black", highlightcolor="white", highlightbackground="purple", wrap=WORD, height=8, width=40) self.output.grid(row=1, column=4, rowspan=5, padx=4, pady=4) def start(self): self.write('TOR Switcher starting.') self.ident = random() start_new_thread(self.newnym, ()) def stop(self): try: self.write('TOR Switcher stopping.') except: pass self.ident = random() def write(self, message): t = localtime() try: self.output.insert( END, '[%02i:%02i:%02i] %s\n' % (t[3], t[4], t[5], message)) self.output.yview(MOVETO, 1.0) except: print('[%02i:%02i:%02i] %s\n' % (t[3], t[4], t[5], message)) def error(self): showerror('TOR IP Switcher', 'Tor daemon not running!') def newnym(self): key = self.ident host = self.host.get() port = self.port.get() passwd = self.passwd.get() interval = self.time.get() try: telnet = Telnet(host, port) if passwd == '': telnet.write("AUTHENTICATE\r\n") else: telnet.write("AUTHENTICATE \"%s\"\r\n" % (passwd)) res = telnet.read_until('250 OK', 5) if res.find('250 OK') > -1: self.write('AUTHENTICATE accepted.') else: self.write('Control responded,' + "\n" 'Incorrect password: "******"' % (passwd)) key = self.ident + 1 self.write('Quitting.') except Exception: self.write('There was an error!') self.error() key = self.ident + 1 self.write('Quitting.') while key == self.ident: try: telnet.write("signal NEWNYM\r\n") res = telnet.read_until('250 OK', 5) if res.find('250 OK') > -1: try: my_new_ident = load( urlopen( 'https://check.torproject.org/api/ip'))['IP'] except (URLError, ValueError): my_new_ident = getoutput('wget -qO - ifconfig.me') self.write('Your IP is %s' % (my_new_ident)) else: key = self.ident + 1 self.write('Quitting.') sleep(interval) except Exception, ex: self.write('There was an error: %s.' % (ex)) key = self.ident + 1 self.write('Quitting.') try: telnet.write("QUIT\r\n") telnet.close() except: pass
class SourceEditor: def __init__(self,central,name,bodyTopNode,specTopNode): self.dirty = False self.central = central self.name = name self.toplevel = Toplevel() self.toplevel.title(name) self.pw = Pmw.PanedWidget(self.toplevel, orient='vertical') specpane = self.pw.add("spec") bodypane = self.pw.add("body") self.specText = ScrolledText(specpane,font=("monaco",10),height=5,background=Colors.background) self.specText.pack(expand=YES,fill=BOTH) self.bodyText = ScrolledText(bodypane,font=("monaco",10),height=15,background=Colors.background) self.bodyText.pack(expand=YES,fill=BOTH) self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText} self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode} Widget.bind(self.bodyText,'<Any-KeyPress>',self.setDirty) Widget.bind(self.specText,'<Any-KeyPress>',self.setDirty) self.popup = Menu(self.toplevel,tearoff=0) self.popup.add_command(label="Dismiss", command=self.nothing) self.popup.add_command(label="Diagram", command=self.goDiagram) self.popup.add_command(label="Abort", command=self.abort) self.popup.add_command(label="Accept", command=self.accept) self.popup.add_command(label="Recolor", command=self.recolor) def popupMenu(event): self.popup.post(event.x_root,event.y_root) self.toplevel.bind('<Button-3>', popupMenu) self.pw.pack(expand=YES,fill=BOTH) self.toplevel.protocol("WM_DELETE_WINDOW",self.central.doQuit) self.refresh() def nothing(self): pass def setClean(self): if self.dirty: self.dirty = False self.toplevel.title(self.name) self.central.unlockGraphics(self.name) def setDirty(self,event): if event.keysym in ['Shift_L', 'Shift_R', 'Alt_L', 'Alt_R', 'Win_L', 'Win_R']: return if not self.dirty: self.dirty = True self.toplevel.title(self.name+"*") self.central.lockGraphics(self.name) def abort(self): if self.dirty: self.setClean() self.setSource() def getSource(self): return (self.specText.get("1.0",END), self.bodyText.get("1.0",END)) def accept(self): if self.dirty: self.bodyText.config(cursor="watch") self.specText.config(cursor="watch") self.bodyText.update() # so that the cursor will show self.specText.update() self.central.update(self.name, self.specText.get("1.0",END), self.bodyText.get("1.0",END),saveOutput=False) self.central.setChanged(self.name) self.setClean() self.bodyText.config(cursor="xterm") self.specText.config(cursor="xterm") def recolor(self): stext,btext = self.getSource() self.colorize(self.specText,stext) self.colorize(self.bodyText,btext) def show(self, specTopNode, bodyTopNode): self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText} self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode} self.setSource() def setSource(self): oldScroll,dummy = self.specText.yview() self.specText.delete('1.0',END) stext = self.textMap[self.specText].regen(forDisplay=True) self.specText.insert(END,stext) self.colorize(self.specText,stext) self.specText.yview("moveto", oldScroll) oldScroll,dummy = self.bodyText.yview() self.bodyText.delete('1.0',END) btext = self.textMap[self.bodyText].regen(forDisplay=True) self.bodyText.insert(END,btext) self.colorize(self.bodyText,btext) self.bodyText.yview("moveto", oldScroll) def colorize(self,textWidget,progText): def colorizeSub(color,wordList): textWidget.tag_remove(color,'1.0',END) textWidget.tag_configure(color,foreground=color) keywords = re.compile(r'\b(' + string.join(wordList,"|") + r')\b') iter = keywords.finditer(progText) for match in iter: start, stop = match.span() textWidget.tag_add(color,"1.0+%dc" % start, "1.0+%dc" % stop) textWidget.tag_remove('hilite','1.0',END) colorizeSub(Colors.keyword, Lexis.keywords) colorizeSub(Colors.reserved, Lexis.reservedWords) def refresh(self): self.setSource() def goDiagram(self): self.central.showDiagram(self.name) def showSource(self,node): self.makeTop() topNode = node.getTopNode() self.text = self.nodeMap[topNode] self.text.tag_remove('hilite','1.0',END) start, end = node.lineRange() startIdx = '%d.0' % int(start) endIdx = '%d.0' % (int(end)+1) self.text.tag_configure('hilite',background=Colors.locatecolor,foreground='black') self.text.see(startIdx) self.text.tag_add('hilite',startIdx,endIdx) def coolSource(self): self.text.tag_configure('hilite',background='white',foreground=Colors.locatecooledcolor) def makeTop(self): TkWorkaround.raiseWindow(self.toplevel) def rescueResource(self): return repr(self.toplevel.geometry()) def setGeom(self,geom): self.toplevel.geometry(geom) def showError(self, unitType, lineNo): text = {'m': self.bodyText, 'i': self.specText}[unitType] startIdx = '%s.0' % int(lineNo) endIdx = '%s.0' % (int(lineNo)+1) text.tag_remove('hilite','1.0',END) text.tag_configure('hilite',background=Colors.locatecolor,foreground='black') text.see(startIdx) text.tag_add('hilite',startIdx,endIdx) self.makeTop()
class TextBox: def __init__(self): self.WIDTH = 600 self.HEIGHT = 800 self.FONT = "helvetica" self.FONT_SIZE = 12 # colours specified as RGB fractions self.bg_input = [1, 1, 1] self.fg_input = [0, 0, 0] self.bg_article = [0, 0, 0] self.fg_min_article = [0.5, 0.5, 0.5] self.fg_max_article = [0.9, 0.9, 0.9] self.fg_solution_article = [1, 1, 1] #[0.3, 0.5, 1.0] #[1, 0.7, 0.4] invert = False if invert: self.bg_input = [1. - v for v in self.bg_input] self.fg_input = [1. - v for v in self.fg_input] self.bg_article = [1. - v for v in self.bg_article] self.fg_min_article = [1. - v for v in self.fg_min_article] self.fg_max_article = [1. - v for v in self.fg_max_article] self.text = "" # what is shown in the box self.allText = "" # the text for the entire article self.sentences = [] # list of sentences in article # dictionary mapping from size to k-hot encoding indicating # which sentences are in the summary self.solutions = [] # (not used) how much weight is put on each sentence self.weights = [] self.only_summary = True self.summary_size = 1 self.summary_coherence = 0.0 self.summary_independence = 0.8 self.summarizer = Summarizer(parent=self) self.root = Tk() self.draw(init=True) #self.root.mainloop() def draw(self, init=False): if init: # show main article body self.tk_article = ScrolledText(self.root) # let user paste and enter text self.tk_user_input = ScrolledText(self.root) self.tk_summary_size_scale = Scale(self.root) self.tk_summary_size_scale_label = Label(self.root, text="Length") self.tk_summary_coherence_scale = Scale(self.root) self.tk_summary_coherence_scale_label = Label(self.root, text="Coherence") self.tk_summary_independence_scale = Scale(self.root) self.tk_summary_independence_scale_label = Label( self.root, text="Independence") self.tk_toggle_view = Button(self.root, text="more", command=self.handleToggleView) self.tk_recalculate = Button(self.root, text="Update", command=self.handleRecalculate) self.root.geometry("%dx%d" % (self.WIDTH, self.HEIGHT)) self.root.title("QuickReader V4") self.tk_article.configure(width=25, height=6, bd=0, highlightthickness=0, wrap="word", font=self.FONT) self.tk_user_input.configure(width=25, height=3, bd=0, highlightthickness=0, wrap="word", font=self.FONT) self.tk_summary_size_scale.configure( bd=0, from_=0, to=20, orient=HORIZONTAL, sliderrelief=FLAT, command=lambda event: self.handleSlider( self.tk_summary_size_scale.get())) ###### self.tk_summary_coherence_scale.configure( bd=0, from_=0, to=1, orient=HORIZONTAL, sliderrelief=FLAT, resolution=0.05, command=lambda event: self.handleCoherenceSlider( self.tk_summary_coherence_scale.get())) self.tk_summary_coherence_scale.set(self.summary_coherence) ###### self.tk_summary_independence_scale.configure( bd=0, from_=0, to=1.5, orient=HORIZONTAL, sliderrelief=FLAT, resolution=0.05, command=lambda event: self.handleIndependenceSlider( self.tk_summary_independence_scale.get())) self.tk_summary_independence_scale.set(self.summary_independence) # set colours self.root.configure(background="black") self.tk_summary_size_scale.configure(troughcolor="#444444", fg="black", background="white", activebackground="#bbbbbb") self.tk_summary_coherence_scale.configure( troughcolor="#444444", fg="black", background="white", activebackground="#bbbbbb") self.tk_summary_independence_scale.configure( troughcolor="#444444", fg="black", background="white", activebackground="#bbbbbb") self.tk_article.configure(bg=toHex(self.bg_article), fg="white", insertbackground="blue") self.tk_article.vbar.configure(bg="white", width=10, troughcolor="black") self.tk_user_input.configure(bg=toHex(self.bg_input), fg=toHex(self.fg_input), insertbackground="blue") self.tk_user_input.vbar.configure(bg="white", width=10, troughcolor="black") self.tk_user_input.focus() self.tk_user_input.bind("<KeyRelease-Return>", (lambda event: self.handleUserInput( self.tk_user_input.get("0.0", END)))) self.root.bind("<Configure>", self.resize) def setText(self, text, redraw=False): self.text = text if redraw: self.updateArticleInfo() def setSentences(self, sentences, redraw=False): self.sentences = sentences if redraw: self.updateArticleInfo() def setSolutions(self, solutions, redraw=False): self.solutions = solutions if redraw: self.updateArticleInfo() def setWeights(self, weights, redraw=False): self.weights = weights if redraw: self.updateArticleInfo() def handleToggleView(self): print("View toggle!") self.only_summary = not self.only_summary if self.only_summary: self.tk_toggle_view.configure(text="more") else: self.tk_toggle_view.configure(text="less") self.updateSummary() def handleRecalculate(self): print("Update!") self.handleUserInput(self.allText) def handleSlider(self, value): print("Slider:", value) self.summary_size = value self.updateSummary() def handleCoherenceSlider(self, value): print("Coherence Slider:", value) self.summary_coherence = value #self.updateSummary() def handleIndependenceSlider(self, value): print("Independence Slider:", value) self.summary_independence = value #self.updateSummary() def updateSummary(self): l = self.summary_size if self.only_summary and l != 0: self.setText('\n\n'.join([ self.sentences[i] for i in range(len(self.sentences)) if self.solutions[l][i] == 1 ])) else: self.setText(self.allText, redraw=False) self.updateArticleInfo() self.setWeights([0. for _ in self.sentences], redraw=True) self.tk_article.yview_moveto(0) #vbar.set(0, 0) #configure(jump=0) def handleUserInput(self, inStr): self.tk_user_input.delete("0.0", END) if inStr.strip() == "": return text = inStr text = ''.join([ch for ch in text if ord(ch) < 128]) self.setText(text, redraw=False) self.setSolutions([], redraw=False) self.setWeights([], redraw=True) text, sentences, solutions = self.summarizer.summarize( text, coherence_weight=self.summary_coherence, independence_weight=self.summary_independence, size_weight=1., beam_width=3, hard_size_limit=None) self.allText = text self.sentences = sentences self.solutions = solutions self.solutions[0] = [1. for _ in sentences] # get max length for summary max_len = max(solutions.keys()) set_len = min(max_len, 3) self.tk_summary_size_scale.configure(from_=0, to=max_len) self.tk_summary_size_scale.set(set_len) self.summary_size = set_len # text: all the text in one long string # sentences: the text split up into a list of sentences # solution: dictionary mapping summary size to a one-hot vector over the sentences, indicating # which sentences are included in the summarization # the text should be the same, but update it anyways since it needs to contain the # exact same stuff as the sentences self.updateSummary() #self.updateArticleInfo() def resize(self, event=[]): LINEH = 20.0 pixelX = self.root.winfo_width() pixelY = self.root.winfo_height() bf = 5 # buffer size in pixels # update find_icon, wiki_icon, and graph_icon # set toggle and recalculate button toggleW = 50 toggleH = 35 * 1 self.tk_toggle_view.place(x=pixelX - toggleW, y=0, width=toggleW, height=toggleH) updateW = 50 updateH = 35 * 2 self.tk_recalculate.place(x=pixelX - updateW, y=toggleH, width=updateW, height=updateH) buttonH = toggleH + updateH labelW = 90 # set position of size scale scaleW = pixelX - updateW - labelW scaleH = 35 self.tk_summary_size_scale.place(x=labelW, y=0, width=scaleW, height=scaleH) self.tk_summary_size_scale_label.place(x=0, y=0, width=labelW, height=scaleH) # set position of coherence scale coherenceW = pixelX - updateW - labelW coherenceH = 35 self.tk_summary_coherence_scale.place(x=labelW, y=scaleH, width=scaleW, height=scaleH) self.tk_summary_coherence_scale_label.place(x=0, y=scaleH, width=labelW, height=coherenceH) # set position of independence scale independenceW = pixelX - updateW - labelW independenceH = 35 self.tk_summary_independence_scale.place(x=labelW, y=scaleH + coherenceH, width=scaleW, height=scaleH) self.tk_summary_independence_scale_label.place(x=0, y=scaleH + coherenceH, width=labelW, height=independenceH) # update user input inputW = pixelX inputH = int(3.0 * LINEH) self.tk_user_input.place(x=0, y=pixelY - inputH, width=inputW, height=inputH) # update article articleW = pixelX articleH = pixelY - inputH - scaleH - coherenceH - independenceH self.tk_article.place(x=0, y=scaleH + coherenceH + independenceH, width=articleW, height=articleH) def updateArticleInfo(self): self.articleClear() self.articleCat(self.text) if self.weights != []: self.articleColour() self.root.update() def articleClear(self): self.tk_article.delete("1.0", END) self.tk_article.update() self.root.update() return def articleCat(self, inStr): self.tk_article.insert(END, inStr) self.tk_article.yview(END) def articleColour(self): ''' solution = self.solutions[self.summary_size] allText = self.text #self.tk_article.get('1.0', 'end-1c') # make sure weights are normalised maxW = max(self.weights) minW = min(self.weights) weights = self.weights if maxW != minW: weights = [(v-minW)/(maxW-minW) for v in self.weights] for i in range(len(self.sentences)): if self.only_summary and solution[i] != 1.: continue s = self.sentences[i] if len(s.strip()) == 0: continue tagNameA = ''.join([random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10)]) L_Size = 12 # if solution[i] == 1 else 10 L_Colour = blend(self.fg_min_article, self.fg_max_article, weights[i]) L_Colour = self.fg_solution_article if solution[i] == 1 else L_Colour countVar = StringVar(self.root) pos = self.tk_article.search(s, "1.0", stopindex="end", count=countVar) self.tk_article.tag_add(tagNameA, pos, "{} + {}c".format(pos, countVar.get())) bolding = "normal" #"bold" if self.solution[i] == 1 else "normal" # font = (self.FONT, L_Size, bolding) self.tk_article.tag_config(tagNameA, foreground=toHex(L_Colour), font=font)#self.FONT+' %s'%(L_Size)) self.root.update() ''' solution = self.solutions[self.summary_size] allText = self.text #self.tk_article.get('1.0', 'end-1c') #print("=========") for i in range(len(self.sentences)): if self.only_summary and solution[i] != 1.: continue s = self.sentences[i] #if len(s.strip()) == 0: # continue #print("- ", s) tagNameA = ''.join([ random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10) ]) L_Size = self.FONT_SIZE # if solution[i] == 1 else 10 L_Colour = self.fg_solution_article if solution[ i] == 1 else self.fg_min_article #print("\t", L_Colour) countVar = StringVar(self.root) pos = self.tk_article.search(s, "1.0", stopindex="end", count=countVar) self.tk_article.tag_add(tagNameA, pos, "{} + {}c".format(pos, countVar.get())) bolding = "normal" #"bold" if self.solution[i] == 1 else "normal" # font = (self.FONT, L_Size, bolding) self.tk_article.tag_config(tagNameA, foreground=toHex(L_Colour), font=font) #self.FONT+' %s'%(L_Size)) self.root.update()
class LogReader(object): def __init__(self, root, **kwargs): self.root = root self.filenameLog = kwargs.get('filenameLog', None) self.ClearDisplay = kwargs.get('ClearDisplay', False) ''' By default don't display Filenames and directory ''' mainstyle = ttk.Style() # mainstyle.theme_use(mainstyle.theme_names()[0]) mainstyle.configure('My.TFrame', background='gray50', foreground='gray97', font="Monospace 12") Btnstyle = ttk.Style() Btnstyle.configure('My.TButton', background='gray50', foreground='gray97', font="Monospace 12") root.title("Log reader v0.1") Chkstyle = ttk.Style() Chkstyle.configure('My.TCheckbutton', background='gray50', foreground='gray97', font="Monospace 12") Chkstyle = ttk.Style() Chkstyle.configure('My.TLabel', background='gray50', foreground='gray97', font="Monospace 12") root.title("Libretto v0.1") self.initParam() #====================================================================== # Main Frame #====================================================================== self.f0 = ttk.Frame(self.root, style='My.TFrame') self.f0.pack(expand=True, fill='both') LabelUP = ttk.Label( self.f0, text="Please select the log file then click on read", style='My.TLabel') LabelUP.pack(side="top") self.fDisp = ttk.Frame(self.f0, style='My.TFrame') self.fDisp.pack(expand=True, fill='both', side="right") self.fParam = ttk.Frame(self.f0, style='My.TFrame') self.fParam.pack(side="left") #====================================================================== # Frame fDisp #====================================================================== # Display stdout self.customFont = tkFont.Font( family="Helvetica", size=12) self.text_area = ScrolledText( self.fDisp, font=self.customFont, undo=True, background='gray20', foreground="gray92") self.text_area.pack(expand=True, fill='both') self.text_area.configure(state='normal') self.text_area.yview(END) self.text_area.after(0) self.text_area.tag_configure("comment", font="Helvetica 12", foreground="gray60") self.text_area.tag_configure("subsubTitle", font="Helvetica 12 bold") self.text_area.tag_configure("subTitle", font="Helvetica 14 bold") self.text_area.tag_configure("Title", font="Helvetica 16 bold") self.text_area.tag_configure("warn", font="Helvetica 12 bold", foreground="red") self.text_area.tag_configure("File", font="Helvetica 10", foreground="DarkSlateGray1") self.text_area.tag_configure("FileOther", font="Helvetica 10", foreground="plum") self.text_area.tag_configure("Directory", font="Helvetica 10", foreground="goldenrod1") self.text_area.tag_configure("validate", font="Helvetica 12 bold", foreground="OliveDrab1") self.text_area.tag_configure("param", font="Helvetica 12", foreground="wheat") # stdout redirection sys.stdout = StdoutRedirector(self.text_area) #====================================================================== # Parameters #====================================================================== # File Selection button SelectLogFileBtn = ttk.Button( self.fParam, text="Select the log file", style='My.TButton') SelectLogFileBtn.grid(row=0, column=0) SelectLogFileBtn.configure(command=lambda: self.set_LogFile()) Label = ttk.Label(self.fParam, text="", style='My.TLabel') Label.grid(row=1, column=0) # Refresh button SelectLogFileBtn = ttk.Button( self.fParam, text="Refresh", style='My.TButton') SelectLogFileBtn.grid(row=2, column=0) SelectLogFileBtn.configure(command=lambda: self.RefreshLog()) Label = ttk.Label(self.fParam, text="", style='My.TLabel') Label.grid(row=9, column=0) # Display Files button ChkBtnDispFilenames = ttk.Checkbutton( self.fParam, text="Display the filenames", style='My.TCheckbutton') ChkBtnDispFilenames.grid(row=10, column=0) ChkBtnDispFilenames.configure(variable=self.Entry_DispFilenames, command=lambda: self.set_DispFilenames()) # Display Comments button ChkBtnDispCom = ttk.Checkbutton( self.fParam, text="Display the comments", style='My.TCheckbutton') ChkBtnDispCom.grid(row=11, column=0) ChkBtnDispCom.configure(variable=self.Entry_DispComment, command=lambda: self.set_DispComment()) # Display Directories button ChkBtnDispDir = ttk.Checkbutton( self.fParam, text="Display the directories", style='My.TCheckbutton') ChkBtnDispDir.grid(row=12, column=0) ChkBtnDispDir.configure(variable=self.Entry_DispDir, command=lambda: self.set_DispDir()) # Display Warnings button ChkBtnDispWarn = ttk.Checkbutton( self.fParam, text="Display the warnings", style='My.TCheckbutton') ChkBtnDispWarn.grid(row=13, column=0) ChkBtnDispWarn.configure(variable=self.Entry_DispWarn, command=lambda: self.set_DispWarn()) # Display Warnings button ChkBtnDispParam = ttk.Checkbutton( self.fParam, text="Display the parameters", style='My.TCheckbutton') ChkBtnDispParam.grid(row=14, column=0) ChkBtnDispParam.configure(variable=self.Entry_DispParam, command=lambda: self.set_DispParam()) self.RefreshLog() if self.ClearDisplay: self.UpdateAllDisp() def printExample(self): return ["=========================================", "= Welcome in the Log Reader ", "=========================================", "", "=== This is a big title ! ===", " ~ A little bit different of this sub-Title", " * And guess what, now a sub-sub-Title ! ", " # right now I am commenting my example", " p_Dodo is a parameter", " BlablablaAudyIsTheBestBlablabla...", " X_something is a most of the time the filename of " + " an MRI image or created", " Z_something is the filename of a file which is not an " + "mri image (it can be some stats or a matrix)", " D_anotherthing is a directory", " > Well this task seems to be a success", " !! But this is a message you should read"] def initParam(self): self.logExtension = ("*.txt", "*.log") self.LogMessage = None self.listHideBal = [] global DefaultFileNameMRIImage global DefaultFileNameMRIMasks global DefaultFileNameOther global DefaultFileNameMatrix global DefaultDirectory global DefaultName global DefaultWarning global DefaultTitle global DefaultSubTitle global DefaultSubSubTitle global DefaultComment global DefaultValidate global DefaultParameter self.DefaultFileNameMRIImage = DefaultFileNameMRIImage self.DefaultFileNameMRIMasks = DefaultFileNameMRIMasks self.DefaultFileNameOther = DefaultFileNameOther self.DefaultFileNameMatrix = DefaultFileNameMatrix self.DefaultDirectory = DefaultDirectory self.DefaultName = DefaultName self.DefaultWarning = DefaultWarning self.DefaultTitle = DefaultTitle self.DefaultSubTitle = DefaultSubTitle self.DefaultSubSubTitle = DefaultSubSubTitle self.DefaultComment = DefaultComment self.DefaultValidate = DefaultValidate self.DefaultParameter = DefaultParameter self.DispWarn = True self.Entry_DispWarn = IntVar(value=1) self.DispParam = True self.Entry_DispParam = IntVar(value=1) if self.ClearDisplay: self.DispFilenames = False self.Entry_DispFilenames = IntVar(value=0) self.DispComment = False self.Entry_DispComment = IntVar(value=0) self.DispDir = False self.Entry_DispDir = IntVar(value=0) else: self.DispFilenames = True self.Entry_DispFilenames = IntVar(value=1) self.DispComment = True self.Entry_DispComment = IntVar(value=1) self.DispDir = True self.Entry_DispDir = IntVar(value=1) def DispOrHide(self, DispSomething, listHideBal): if DispSomething: # update the balise to hide list listHideBal = [e for e in self.listHideBal if e not in listHideBal] else: listHideBal = listHideBal + self.listHideBal self.listHideBal = listHideBal self.resetDisp() self.watchLog(bal=self.listHideBal) def set_DispFilenames(self): self.DispFilenames = self.Entry_DispFilenames.get() listbal0 = [self.DefaultFileNameMRIImage, self.DefaultFileNameMatrix, self.DefaultFileNameMRIMasks, self.DefaultFileNameOther] self.DispOrHide(self.DispFilenames, listbal0) def set_DispDir(self): self.DispDir = self.Entry_DispDir.get() listbal0 = [self.DefaultDirectory] self.DispOrHide(self.DispDir, listbal0) def set_DispComment(self): self.DispComment = self.Entry_DispComment.get() listbal0 = [self.DefaultComment] self.DispOrHide(self.DispComment, listbal0) def set_DispWarn(self): self.DispWarn = self.Entry_DispWarn.get() listbal0 = [self.DefaultWarning] self.DispOrHide(self.DispWarn, listbal0) def set_DispParam(self): self.DispParam = self.Entry_DispParam.get() listbal0 = [self.DefaultParameter] self.DispOrHide(self.DispParam, listbal0) def UpdateAllDisp(self): self.set_DispComment() self.set_DispDir() self.set_DispFilenames() def set_LogFile(self): self.filenameLog = self.OpenFile( self.OriginalDirectory, self.logExtension) self.RefreshLog() def filterLog(self, str0, bal): ''' delete the lines which contain a specific balise ''' if type(bal) != list: if type(bal) != str: if not bal: return str0 else: bal = [bal] try: str1 = DeleteTabulation(str0) except: str1 = str0 for e in bal: if str1[0:len(e)] == e: return None return str0 def loadLog(self): ''' load a log ''' if self.filenameLog: with open(self.filenameLog) as f: self.LogMessage = f.read().splitlines() else: self.LogMessage = self.printExample() def watchLog(self, bal=None): ''' display the log ''' for line in self.LogMessage: l = self.filterLog(line, bal) if l: print l def resetDisp(self): ''' ''' self.text_area.delete('1.0', END) def RefreshLog(self): self.loadLog() self.resetDisp() self.watchLog(bal=self.listHideBal) def OpenFile(self, initialdir0="", filetype='*.*'): if filetype != '*.*': filetypes0 = (("Files", filetype), ("All Files", "*.*")) name = askopenfilename(initialdir=initialdir0, filetypes=filetypes0, title="Choose a file.") else: name = askopenfilename(initialdir=initialdir0, title="Choose a file.") return name def close(self): print "close" exit()
class Window: def __init__(self): self.nickname = "Matti" ''' Create the base window ''' self.root = Tk() self.root.protocol("WM_DELETE_WINDOW", self.stop) self.root.title('pySpellcast') self.frame = Frame(self.root,background="white") self.frame.pack(fill=BOTH,expand=YES) self.frame.grid_rowconfigure(0,weight=1) self.frame.grid_columnconfigure(0,weight=1) ''' Textframe holds the textbox and entry box ''' self.textframe = Frame(self.frame) self.textframe.grid(row=0,column=0,rowspan=3,sticky=N+S+W+E) self.textframe.grid_rowconfigure(0,weight=1) self.textframe.grid_columnconfigure(0,weight=1) ''' Textbox for server output ''' self.text = ScrolledText(self.textframe,width=40,height=20, wrap=WORD, state=DISABLED, background="white",foreground="black") self.text.grid(row=0,column=0,ipadx=10,sticky=N+S+W+E) ''' entrybox for input ''' self.input = StringVar() self.entry = Entry(self.textframe,textvariable=self.input,background="white",foreground="black", state=NORMAL, insertbackground="black") self.entry.grid(row=1,column=0,sticky=W+E) self.entry.bind("<Return>",self.enter) ''' Creating buttons ''' self.sendbutton = Button(self.frame,text="Send") self.spellbutton = Button(self.frame,text="Spells") self.sendbutton.bind('<Button-1>',self.sendmoves) self.spellbutton.bind('<Button-1>',self.showspells) self.sendbutton.grid(row=1,column=1,sticky=W+E) self.spellbutton.grid(row=1,column=2,sticky=W+E) ''' listbox for characters and hitpoints ''' self.list = Listbox(self.frame,height=10,width=40,font="courier") self.list.grid(row=2,column=1,columnspan=8,sticky=N+S+W+E) ''' Loading the icons ''' self.waveR = PhotoImage(file="graphics/wave-right.gif") self.digitR = PhotoImage(file="graphics/digit-right.gif") self.snapR = PhotoImage(file="graphics/snap-right.gif") self.clapR = PhotoImage(file="graphics/clap-right.gif") self.palmR = PhotoImage(file="graphics/palm-right.gif") self.wiggleR = PhotoImage(file="graphics/wiggle-right.gif") self.knifeR = PhotoImage(file="graphics/knife-right.gif") self.waveL = PhotoImage(file="graphics/wave-left.gif") self.digitL = PhotoImage(file="graphics/digit-left.gif") self.snapL = PhotoImage(file="graphics/snap-left.gif") self.clapL = PhotoImage(file="graphics/clap-left.gif") self.palmL = PhotoImage(file="graphics/palm-left.gif") self.wiggleL = PhotoImage(file="graphics/wiggle-left.gif") self.knifeL = PhotoImage(file="graphics/knife-left.gif") self.antispell = PhotoImage(file="graphics/antispell.gif") self.unknown = PhotoImage(file="graphics/unknown.gif") self.empty = PhotoImage(file="graphics/empty.gif") self.spelllist = PhotoImage(file="graphics/spell-list.gif") self.actiondialog = None ''' Setting up player dictionary, contains player name to player class ''' self.players = {} questions = LabelFrame(self.frame,text="Questions") questions.grid(row=4,column=0,columnspan=10,sticky=W+E) question = Label(questions,text="Test") question.pack(anchor=W,fill=BOTH,expand=1) def sortPlayers(self): for i,(name,player) in enumerate(self.players.items()): player.frame.grid_remove() player.frame.grid(row=0,column=1+i,padx=5) def testPlayers(self): self.players = {'White mage':0,'Black mage':0} def updatePlayers(self,players): for player,history in players: if player not in self.players.keys(): self.players[player] = Player(player,self) self.players[player].updateHistory(history) self.sortPlayers() # Todo, remove nonexisting players.. def updatePlayerFrames(self): # TODO: FIIXIXIXIXIXIIXIXXIIXII playerFrames = self.playerFrames[:] self.playerFrames = [] for name,frame in self.players: if frame not in playerFrames: new = Frame(self.root,background="red") else: self.playerFrames.append(frame) #TODO: remove nonexisting players def stop(self): self.root.destroy() reactor.stop() sys.exit(1) def display_line(self,text,timestamp=None): print "Display",text if not timestamp: timestamp = time.time() print "scroll1:",self.text.yview() if self.text.yview()[1] == 1.0: scroll = True else: scroll = False self.text.config(state=NORMAL) asciitime = time.strftime('[%H:%M:%S]', time.localtime(float(timestamp))) #if owner: self.textarea.mark_set(start, END);self.textarea.mark_gravity(start,LEFT #text = self.wrap(text) text = [['black',text]] ts = ('grey',"%s "%(asciitime)) text.insert(0,ts) for piece in text: self.text.insert(END, piece[1],piece[0]) #if owner: self.textarea.mark_set(end, END);self.textarea.mark_gravity(end,LEFT) self.text.insert(END,'\n') print "scroll2",self.text.yview() if scroll: self.text.yview(END) ''' if owner: print "Checking tag.." a,b= self.textarea.tag_ranges(tag) print dir(a) self.textarea.delete(a,b) ''' self.text.config(state=DISABLED) def selected(self,item): myplayer = self.players[self.nickname] if self.select == 'right': myplayer.history[-1][1] = item else: myplayer.history[-1][0] = item myplayer.updateHistory() def enter(self,event): data=unicode(self.input.get()) if len(data) == 0: return self.input.set("") self.client.write("msg %s"%data) def showspells(self,event): spells = SpellDialog(self.root,self) def sendmoves(self,event): if self.stage == 1: myplayer = self.players[self.nickname] moves = myplayer.history[-1] self.client.write("moves %s"%(json.dumps(moves))) def setStage(self,stage): self.stage = stage