Пример #1
0
    def open_text(self):
        if self.selected_text_title != "[]":

            text_root = tk.Tk()
            popup = tk.Menu(text_root, tearoff=0)
            textWindow = ScrolledText(text_root, wrap="word")
            uw_list = self.uw_lb.get(0, tk.END)
            text_root.bind(
                "<Button-1>", lambda eff: meaning_part(
                    eff, T=textWindow, unknown_words_list=uw_list, popup=popup)
            )
            textWindow.insert(1.0,
                              general_dict["Text"][self.selected_text_title])
            textWindow.tag_config("A", foreground="red", background="white")
            textWindow.pack(expand=True, fill=tk.BOTH)
            for word in general_dict["Unknown"][self.selected_text_title]:
                word = " " + word + " "
                start = 1.0
                search_pos = textWindow.search(word, start, stopindex=tk.END)

                while search_pos:
                    length = len(word)
                    row, col = search_pos.split('.')
                    end = int(col) + length
                    if str(end)[-1] == "0":
                        end += 1

                    end = row + '.' + str(end)

                    textWindow.tag_add("A", search_pos, float(end))
                    start = end
                    search_pos = textWindow.search(word,
                                                   start,
                                                   stopindex=tk.END)
Пример #2
0
    def open_text(self):
        if self.selected_text_title != "[]":

            text_root = tk.Tk()
            textWindow = ScrolledText(text_root, wrap="word")
            textWindow.insert(1.0,
                              general_dict["Text"][self.selected_text_title])
            textWindow.tag_config("A", foreground="red", background="white")
            textWindow.pack(expand=True, fill=tk.BOTH)
            for word in general_dict["Unknown"][self.selected_text_title]:
                word = " " + word + " "
                start = 1.0
                search_pos = textWindow.search(word, start, stopindex=tk.END)

                while search_pos:
                    length = len(word)
                    row, col = search_pos.split('.')
                    end = int(col) + length
                    if str(end)[-1] == "0":
                        end += 1

                    end = row + '.' + str(end)

                    textWindow.tag_add("A", search_pos, float(end))
                    start = end
                    search_pos = textWindow.search(word,
                                                   start,
                                                   stopindex=tk.END)
Пример #3
0
class TraceFrame(Frame):

    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)

        self.t = ScrolledText(self, wrap="word")
        self.t.configure(background="light cyan")
        self.t.configure(height = 10)
        self.t.tag_config("in", foreground="forest green")
        self.t.tag_config("err", foreground="orange red")
        self.t.tag_config("time", foreground="sea green")
        self.t.tag_config("curr", foreground="black")
        self.t.tag_config("out", foreground="firebrick")
        self.t.pack(side="top", fill="both", expand=True)



    def add_To_Trace(self, st, tag):
        '''
        :param st: txte a afficher
        :param tag:  type de texte a afficher
        :return:
        '''
        self.t.insert(INSERT, st, tag)
        self.t.see(END)

    def clear_Trace(self):
        '''
        Efface la zone de texte
        :return:
        '''
        self.t.delete('1.0', 'end')
Пример #4
0
def example():
    import __main__
    from Tkconstants import END

    stext = ScrolledText(bg='white', height=10)
    stext.insert(END, __main__.__doc__)

    f = Font(family="times", size=30, weight="bold")
    stext.tag_config("font", font=f)

    stext.insert(END, "Hello", "font")
    stext.pack(fill=BOTH, side=LEFT, expand=True)
    stext.focus_set()
    stext.mainloop()
Пример #5
0
class CopyableMessageWindow(basicWindow):
    """ Creates a modeless (non-modal) message window that allows the user to copy the presented text. """
    def __init__(self, topLevel, message, title, align, buttons, makeModal):
        self.guiRoot = topLevel

        basicWindow.__init__(self,
                             topLevel,
                             title,
                             resizable=True,
                             topMost=False)

        linesInMessage = len(message.splitlines())
        if linesInMessage > 17: height = 22
        else: height = linesInMessage + 5

        self.messageText = ScrolledText(self.mainFrame,
                                        relief='groove',
                                        wrap='word',
                                        height=height)
        self.messageText.insert('1.0', '\n' + message)
        self.messageText.tag_add('All', '1.0', 'end')
        self.messageText.tag_config('All', justify=align)
        self.messageText.pack(fill='both', expand=1)

        # Add the buttons
        self.buttonsFrame = Tk.Frame(self.mainFrame)
        ttk.Button(self.buttonsFrame, text='Close',
                   command=self.close).pack(side='right', padx=5)
        if buttons:
            for button in buttons:
                buttonText, buttonCommand = button
                ttk.Button(self.buttonsFrame,
                           text=buttonText,
                           command=buttonCommand).pack(side='right', padx=5)
        ttk.Button(self.buttonsFrame,
                   text='Copy text to Clipboard',
                   command=self.copyText).pack(side='right', padx=5)
        self.buttonsFrame.pack(pady=3)

        if makeModal:
            self.window.grab_set()
            self.guiRoot.wait_window(self.window)

    # Button functions
    def copyText(self):
        self.guiRoot.clipboard_clear()
        self.guiRoot.clipboard_append(
            self.messageText.get('1.0', 'end').strip())
class my_form(Frame):
    """Form"""
    def __init__(self, master=None):
        """create elements of form"""
        Frame.__init__(self, master)
        self.pack()
        #self.createWidgets()

        self.textBox = ScrolledText(self, height=15, width=100)
        self.textBox.pack()
        self.textBox.tag_config("b", foreground="blue")
        self.textBox.tag_config("r", foreground="red")
        # insert the msg from lets_rock will display when finished,
        # that's to late
        if os.getenv('LANG')[0:2] == "de":
            self.textBox.insert(END,
                "Es kann eine Weile dauern, "
                + "vielleicht eine Tasse Kaffee geniessen...")
        else:
            self.textBox.insert(END,
            "Working, this can take a while, enjoy a cup of coffee...\n")
        self.pressButton = Button(self,
                text="ID3 easyTAG Editor", command=self.call_id3_editor)
        # the button will appear when finished
        #self.pressButton.pack()

        # registering callback
        self.listenID = self.after(400, self.lets_rock)
        #self.listenID = self.lets_rock

    def display_logging(self, log_message, text_format):
        """display messages in form, loading periodically """
        if text_format is None:
            self.textBox.insert(END, log_message + "\n")
        else:
            self.textBox.insert(END, log_message + "\n", text_format)

    def call_id3_editor(self):
        self.textBox.insert(END, "Click" + "\n")
        # start subprocess
        try:
            subprocess.Popen(["easytag", ac.app_workin_path],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
        except Exception, e:
            self.display_logging("Error: %s" % str(e), "r")

        return None
Пример #7
0
class CopyableMsg(basicWindow):
    """ Creates a modeless (non-modal) message window that allows the user to easily copy the given text. 
		If buttons are provided, they should be an iterable of tuples of the form (buttonText, buttonCallback). """
    def __init__(self,
                 root,
                 message='',
                 title='',
                 alignment='center',
                 buttons=None):
        super(CopyableMsg, self).__init__(root,
                                          title,
                                          resizable=True,
                                          topMost=False)
        self.root = root

        if alignment == 'left':
            height = 22  # Expecting a longer, more formal message
        else:
            height = 14

        # Add the main text display of the window
        self.messageText = ScrolledText(self.window,
                                        relief='groove',
                                        wrap='word',
                                        height=height)
        self.messageText.insert('1.0', message)
        self.messageText.tag_add('All', '1.0', 'end')
        self.messageText.tag_config('All', justify=alignment)
        self.messageText.pack(fill='both', expand=1)

        # Add the buttons
        self.buttonsFrame = Tkinter.Frame(self.window)
        ttk.Button(self.buttonsFrame, text='Close',
                   command=self.close).pack(side='right', padx=5)
        if buttons:
            for buttonText, buttonCommand in buttons:
                ttk.Button(self.buttonsFrame,
                           text=buttonText,
                           command=buttonCommand).pack(side='right', padx=5)
        ttk.Button(self.buttonsFrame,
                   text='Copy text to Clipboard',
                   command=self.copyToClipboard).pack(side='right', padx=5)
        self.buttonsFrame.pack(pady=3)

    def copyToClipboard(self):
        self.root.clipboard_clear()
        self.root.clipboard_append(self.messageText.get('1.0', 'end'))
Пример #8
0
    def open_text(self):
        #in the usage of tags there were 3 problems faced, 1-the markings such as dot, comma but it is solved
        # 2-Uppercases are not matching, this is not solved
        # 3-Words that are shorter than 4 letters take the next words first letter
        if self.selected_text_title != "[]":

            text_root = tk.Tk()
            text_root.title(self.selected_text_title)
            popup = tk.Menu(text_root, tearoff=0)
            textWindow = ScrolledText(text_root, wrap = "word")
            uw_list = self.uw_lb.get(0,tk.END)
            text_root.bind("<Button-1>", lambda eff:meaning_part(eff, T=textWindow, unknown_words_list=uw_list, popup=popup))
            textWindow.insert(1.0, general_dict["Text"][self.selected_text_title])
            textWindow.tag_config("A", foreground="red", background="white")
            textWindow.pack(expand = True, fill = tk.BOTH)
            for pre_word in uw_list:#general_dict["Unknown"][self.selected_text_title]:
                word =  " " + pre_word + " "
                start = 1.0
                search_pos = textWindow.search(word, start, stopindex=tk.END)
                if not search_pos:
                    for x in '"^+%&/()=?_-*,;:.!>#${{[]}\'':
                        word = " " + pre_word + x
                        search_pos = textWindow.search(word, start, stopindex=tk.END)
                        if search_pos: break
                    if not search_pos:
                        for x in '"^+%&/()=?_-*,;:.!>#${{[]}\'':
                            word = x + pre_word + " "
                            search_pos = textWindow.search(word, start, stopindex=tk.END)
                            if search_pos: break
                #print word, search_pos

                while search_pos:
                    length = len(word)
                    row, col = search_pos.split('.')
                    end = int(col) + length
                    #if str(end)[-1]=="0":
                    #    end += 1

                    print end, col
                    end = row + '.' + str(end)

                    print search_pos, end, word
                    textWindow.tag_add("A", search_pos, float(end))
                    start = end
                    search_pos = textWindow.search(word, start, stopindex=tk.END)
Пример #9
0
    class TkTCPWatch(Tkinter.Frame):
        '''The tcpwatch top-level window.
        '''
        def __init__(self, master):
            Tkinter.Frame.__init__(self, master)
            self.createWidgets()
            # connections maps ids to TkConnectionObservers.
            self.connections = {}
            self.showingid = ''
            self.queue = Queue()
            self.processQueue()

        def createWidgets(self):
            listframe = Tkinter.Frame(self)
            listframe.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=1)
            scrollbar = Tkinter.Scrollbar(listframe, orient=Tkinter.VERTICAL)
            self.connectlist = Tkinter.Listbox(listframe,
                                               yscrollcommand=scrollbar.set,
                                               exportselection=0)
            scrollbar.config(command=self.connectlist.yview)
            scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
            self.connectlist.pack(side=Tkinter.LEFT,
                                  fill=Tkinter.BOTH,
                                  expand=1)
            self.connectlist.bind('<Button-1>', self.mouseListSelect)
            self.textbox = ScrolledText(self, background="#ffffff")
            self.textbox.tag_config("message", foreground="#000000")
            self.textbox.tag_config("client", foreground="#007700")
            self.textbox.tag_config("clientesc",
                                    foreground="#007700",
                                    background="#dddddd")
            self.textbox.tag_config("server", foreground="#770000")
            self.textbox.tag_config("serveresc",
                                    foreground="#770000",
                                    background="#dddddd")
            self.textbox.insert(Tkinter.END, startup_text, "message")
            self.textbox.pack(side='right', fill=Tkinter.BOTH, expand=1)
            self.pack(fill=Tkinter.BOTH, expand=1)

        def addConnection(self, id, conn):
            self.connections[id] = conn
            connectlist = self.connectlist
            connectlist.insert(Tkinter.END, id)

        def updateConnection(self, id, output):
            if id == self.showingid:
                textbox = self.textbox
                for data, style in output:
                    textbox.insert(Tkinter.END, data, style)

        def mouseListSelect(self, event=None):
            connectlist = self.connectlist
            idx = connectlist.nearest(event.y)
            sel = connectlist.get(idx)
            connections = self.connections
            if connections.has_key(sel):
                self.showingid = ''
                output = connections[sel].getOutput()
                self.textbox.delete(1.0, Tkinter.END)
                for data, style in output:
                    self.textbox.insert(Tkinter.END, data, style)
                self.showingid = sel

        def processQueue(self):
            try:
                if not self.queue.empty():
                    # Process messages for up to 1/4 second
                    from time import time
                    limit = time() + 0.25
                    while time() < limit:
                        try:
                            f, args = self.queue.get_nowait()
                        except Empty:
                            break
                        f(*args)
            finally:
                self.master.after(50, self.processQueue)
Пример #10
0
class GUI:
    def __init__(self):
        self.makefile()
        self.getDest()
        if not self.valid:
            return
        self.login()
        if self.valid:
            print "Successful login"
            self.startServer()
        else:
            print "Cancel by user"
        return

    def makefile(self):
        proc = subprocess.Popen('make',
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
        while True:
            stdout = proc.stdout.readline()
            stderr = proc.stderr.readline()
            if not (stdout and stderr):
                break
        return

    def getDest(self):
        destDia = Tk()
        destDia.geometry('480x50+300+300')
        host = StringVar()
        host.set('127.0.0.1')
        port = StringVar()
        port.set('21')
        hostEntry = Entry(destDia, textvariable=host, width=20)
        portEntry = Entry(destDia, textvariable=port, width=10)
        hostEntry.grid(column=0, row=0, padx=15, pady=10)
        portEntry.grid(column=1, row=0)

        def confirm():
            self.port = port.get()
            self.host = host.get()
            self.valid = True
            destDia.destroy()
            return

        def cancel():
            self.valid = False
            destDia.destroy()
            return

        confirmButton = Button(destDia, command=confirm, text="Confirm")
        confirmButton.grid(column=2, row=0)
        cancelButton = Button(destDia, command=cancel, text="Cancel")
        cancelButton.grid(column=3, row=0)
        destDia.mainloop()
        return

    def login(self):
        def validInfo(preload, user, word):
            self.buff = open("client.buff", "w+")
            self.getter = open("client.buff", "r")
            wordcont = word.get()
            if wordcont == "":
                wordcont = "\'\'"
            self.client = subprocess.Popen(
                "./client -gui -user " + user.get() + " -pass " + wordcont +
                " -port " + self.port + " -host " + self.host,
                stdin=PIPE,
                stdout=self.buff,
                stderr=STDOUT,
                universal_newlines=True,
                shell=True)
            sleep(.5)
            self.buff.seek(0, 0)
            self.initInfo = self.buff.readlines()
            print self.initInfo
            if self.initInfo[-1][:4] != "230 ":
                self.close()
                self.valid = False
                return
            self.buff.seek(0, 0)
            self.buff.truncate()
            self.valid = True
            preload.destroy()
            return

        def cancelInfo():
            self.valid = False
            preload.destroy()
            return

        preload = Tk()
        preload.geometry('520x80+300+300')
        username = StringVar()
        username.set('anonymous')
        password = StringVar()
        password.set('*****@*****.**')
        usernameEntry = Entry(preload, textvariable=username, width=40)
        passwordEntry = Entry(preload, textvariable=password, width=40)
        confirmButton = Button(
            preload,
            text='login',
            command=lambda: validInfo(preload, username, password))
        cancelButton = Button(preload, text='cancel', command=cancelInfo)
        usernameEntry.grid(column=0, row=0, padx=15, pady=10)
        passwordEntry.grid(column=0, row=1, padx=15)
        confirmButton.grid(column=1, row=0)
        cancelButton.grid(column=1, row=1)
        preload.mainloop()
        return

    def logInfo(self, tag, res):
        if not res:
            return
        if type(res) == str:
            res = [res]
        for line in res:
            self.log.insert(END, line.strip() + '\n')
        self.log.tag_add(tag, "%s.%s" % (self.col, 0),
                         "%s.%s" % (self.col + len(res), len(res[-1])))
        self.col += len(res)

    def logSucc(self, res):
        return self.logInfo("succ", res)

    def logFail(self, res):
        return self.logInfo("fail", res)

    def logWait(self, res):
        return self.logInfo("wait", res)

    def logNorm(self, res):
        return self.logInfo("norm", res)

    def getCmdResponse(self, cmd):
        self.client.stdin.write(cmd + '\n')
        cnt = 1
        if cmd[:4] in ('LIST', 'RETR', 'STOR'):
            cnt += 1
        while True:
            self.getter.seek(0, 0)
            buf = self.getter.readlines()
            if len(
                    filter(
                        lambda x: len(x) > 3 and x[:3].isdigit() and x[3] ==
                        ' ', buf)) == cnt:
                self.getter.seek(0, 0)
                break
        self.buff.seek(0, 0)
        self.logNorm(['Command>>> ' + cmd])
        res = self.buff.readlines()
        self.buff.seek(0, 0)
        self.buff.truncate()
        code = int(
            filter(lambda x: len(x) > 3 and x[:3].isdigit() and x[3] == ' ',
                   buf)[-1][:3])
        if 100 <= code < 300:
            if cmd == 'LIST':
                self.logSucc([res[1], res[-1]])
            else:
                self.logSucc(res)
        if 300 <= code < 400:
            self.logWait(res)
        if 400 <= code < 500:
            self.logFail(res)
        self.log.see(END)
        if cmd.startswith('LIST'):
            return res[2:-2]
        if cmd.startswith('SYST'):
            return res[-1]

    def startServer(self):
        window = Tk()
        window.geometry('800x580+200+100')
        self.log = ScrolledText(window, width=108, height=8)
        self.col = 1
        title = Label(window,
                      text="Lustralisk client connected to " +
                      self.getCmdResponse('SYST')[4:-2])
        title.grid(column=0, row=0, columnspan=12)
        tree = ttk.Treeview(window,
                            selectmode="extended",
                            columns=("path", "type", "A", "B"),
                            displaycolumns=("A", "B"),
                            height="18")
        tree.heading("#0", text="Name")
        tree.column("#0", minwidth=200, width=400, stretch=True)
        tree.heading("A", text="Modified Date")
        tree.column("A", minwidth=200, width=180, stretch=True)
        tree.heading("B", text="Size")
        tree.column("B", minwidth=100, width=200, stretch=True)
        tree.grid(column=0, row=1, columnspan=12, padx=8)
        self.log.grid(column=0, row=2, columnspan=12, pady=10)
        self.log.tag_config("succ", foreground="green")
        self.log.tag_config("wait", foreground="orange")
        self.log.tag_config("fail", foreground="red")
        self.log.tag_config("norm", foreground="blue")
        parent = tree.insert('',
                             END,
                             text='/',
                             values=['/', 'd', '', ''],
                             open=True)

        def quitWindow():
            self.close()
            window.destroy()
            return

        def populateNode(path, parent):
            self.getCmdResponse('CWD ' + path)
            self.getCmdResponse('PASV')
            initFiles = self.getCmdResponse('LIST')
            if len(initFiles) == 0:
                tree.insert(parent, END, text='empty folder')
                return
            for f in initFiles:
                if f.startswith('d'):
                    try:
                        d = tree.insert(
                            parent,
                            END,
                            text=f.split()[-1] + '/',
                            values=[
                                path + f.split()[-1] + '/', 'd',
                                '%4s%3s%6s' % (f.split()[5], int(
                                    f.split()[6]), f.split()[7]), ''
                            ])
                        tree.insert(d, END, text='dummy')
                    except:
                        pass
                else:
                    try:
                        tree.insert(parent,
                                    END,
                                    text=f.split()[-1],
                                    values=[
                                        path + f.split()[-1], 'f',
                                        '%4s%3s%6s' %
                                        (f.split()[5], int(
                                            f.split()[6]), f.split()[7]),
                                        f.split()[4]
                                    ])
                    except:
                        pass
            return

        def updateTree(event):
            nodeId = tree.focus()
            if tree.parent(nodeId) and tree.set(nodeId, 'type') == 'd':
                topChild = tree.get_children(nodeId)[0]
                if tree.item(topChild, option='text') == 'dummy':
                    tree.delete(topChild)
                    populateNode(tree.set(nodeId, 'path'), nodeId)
            return

        def dfsDelete(parent):
            for child in tree.get_children(parent):
                if tree.set(child, 'type') == 'd':
                    dfsDelete(child)
                    tree.delete(child)
                else:
                    tree.delete(child)

        def upload():
            filename = askopenfilename()
            if filename == '':
                self.logFail('Error<<< No filename input, aborted.')
                return
            self.getCmdResponse('PASV')
            if tree.focus():
                if tree.set(tree.focus(), 'type') == 'd':
                    uploadPath = tree.set(tree.focus(), 'path')
                else:
                    uploadPath = tree.set(tree.parent(tree.focus()), 'path')
            else:
                self.logWait(
                    'Warning<<< No path selected, using root as default.')
                uploadPath = '/'
            self.getCmdResponse('CWD ' + uploadPath)
            self.getCmdResponse('STOR ' + filename)
            refresh()
            return

        def download():
            if not tree.focus():
                self.logFail('Error<<< No file selected, aborted.')
                return
            if tree.set(tree.focus(), 'type') == 'f':
                self.getCmdResponse('PASV')
                self.getCmdResponse(
                    'CWD ' + tree.set(tree.parent(tree.focus()), 'path'))
                self.getCmdResponse(
                    'RETR ' + tree.set(tree.focus(), 'path').split('/')[-1])
                dirpath = askdirectory()
                if not dirpath == '':
                    os.rename(
                        tree.set(tree.focus(),
                                 'path').split('/')[-1], dirpath + '/' +
                        tree.set(tree.focus(), 'path').split('/')[-1])
            return

        def remove():
            if not tree.focus():
                self.logFail('Error<<< No file selected, aborted.')
                return
            if tree.set(tree.focus(), 'type') == 'f':
                self.getCmdResponse('DELE ' + tree.set(tree.focus(), 'path'))
            else:
                self.getCmdResponse('RMD ' + tree.set(tree.focus(), 'path'))
            refresh()
            return

        def create():
            filename = askstring("title", "folder name: ")
            if filename == '':
                self.logFail('Error<<< No filename input, aborted.')
                return
            if not tree.focus():
                self.logFail('Error<<< No file selected, aborted.')
                return
            if tree.focus():
                if tree.set(tree.focus(), 'type') == 'd':
                    uploadPath = tree.set(tree.focus(), 'path')
                else:
                    uploadPath = tree.set(tree.parent(tree.focus()), 'path')
            else:
                self.logWait(
                    'Warning<<< No path selected, using root as default.')
                uploadPath = '/'
            self.getCmdResponse('CWD ' + uploadPath)
            self.getCmdResponse('MKD ' + filename)
            refresh()
            return

        def rename():
            if not tree.focus():
                self.logFail('Error<<< No file selected, aborted.')
                return
            name = askstring("title", "rename to: ")
            if name == '':
                self.logFail('Error<<< No filename input, aborted.')
                return
            path = tree.set(tree.focus(), 'path')
            if path[-1] == '/' and len(path) > 1:
                path = path[:-1]
            self.getCmdResponse('RNFR ' + path)
            path = '/'.join(path.split('/')[:-1]) + '/' + name
            self.getCmdResponse('RNTO ' + path)
            refresh()
            return

        def refresh():
            dfsDelete(parent)
            populateNode('/', parent)

        tree.bind('<<TreeviewOpen>>', updateTree)
        populateNode('/', parent)
        Button(window, text="refresh", command=refresh).grid(column=0, row=3)
        Button(window, text="create", command=create).grid(column=1, row=3)
        Button(window, text="upload", command=upload).grid(column=2, row=3)
        Button(window, text="download", command=download).grid(column=3, row=3)
        Button(window, text="remove", command=remove).grid(column=5, row=3)
        Button(window, text="rename", command=rename).grid(column=6, row=3)
        Button(window, text="quit", command=quitWindow).grid(column=11, row=3)
        window.mainloop()
        return

    def close(self):
        self.client.stdin.write('QUIT\r\n')
        self.client.stdin.flush()
        self.client.stdin.close()
        self.client.kill()
        self.getter.close()
        self.buff.close()
        os.remove('client.buff')
        return
Пример #11
0
class app():
    def __init__(self):
        self.root = Tk()
        self.root.title("WebScan")
        self.root.resizable(False, False)
        self.rr = IntVar()

        #self.root.geometry("1000x800")
        self.creat_weaget()

        ##varible to paues the scan##
        self.aa = IntVar()
        self.aa = False
        self.tt = StringVar
        self.va = StringVar
        ###left frame###
        self.left = Frame(self.root)
        self.left.grid(row=0, column=0, sticky=W)
        self.creat_left_weget()

        ###right frame##
        self.right = Frame(self.root)
        self.right.grid(row=0, column=1, sticky=E)
        self.creat_right_weget()

        ##progressbar text##

        self.style = ttk.Style(self.root)

        self.style.layout('text.Horizontal.TProgressbar',
                          [('Horizontal.Progressbar.trough', {
                              'children': [('Horizontal.Progressbar.pbar', {
                                  'side': 'left',
                                  'sticky': 'ns'
                              })],
                              'sticky':
                              'nswe'
                          }), ('Horizontal.Progressbar.label', {
                              'sticky': ''
                          })])

        self.style.configure('text.Horizontal.TProgressbar', text='')

    def creat_weaget(self):

        ##top menu##

        self.menu_bar = Menu(self.root)
        self.root.config(menu=self.menu_bar)
        file_menu = Menu(self.menu_bar, tearoff=0)
        file_menu.add_command(label="About", command=self.he)
        self.menu_bar.add_cascade(label="Help", menu=file_menu)
        conf_menu = Menu(self.menu_bar, tearoff=0)
        conf_menu.add_command(label="User Agent Spoofing", command=self.con)
        self.menu_bar.add_cascade(label="Setting", menu=conf_menu)

        pass

    def creat_left_weget(self):
        ###label##
        label = Label(self.left, text="Entre the target Address")
        label.grid(row=0, column=0, pady=10, sticky=N)

        ##entry##
        self.entry = Entry(self.left)
        self.entry.grid(row=1, column=0, padx=10, pady=5, sticky=W + E)
        self.entry.focus()

        ##radio box##
        self.r = IntVar()

        ba_1 = Radiobutton(self.left, variable=self.r, value=1, text="Scan ")
        ba_1.grid(row=2, column=0, sticky=W)
        tt.create_ToolTip(ba_1, 'Only Scant the target Site')
        ba_2 = Radiobutton(self.left, variable=self.r, value=2, text="Spider")
        ba_2.grid(row=2, column=0, sticky=E)
        tt.create_ToolTip(ba_2, 'Spider the target site')
        ##submit batton##

        self.submit = Button(self.left, text="Start Scan", command=self.th)
        self.submit.grid(row=3, column=0, padx=10, pady=5, sticky=W)

        ##paus button##

        self.stop = Button(self.left, text="Pause Scan", command=self.st)
        self.stop.grid(row=4, column=0, padx=10, pady=5, sticky=W + E)
        self.stop.config(state='disabled')
        ##exit button##
        self.exit = Button(self.left, text="Exit", command=self.exe)
        self.exit.grid(row=3, column=0, padx=10, pady=5, sticky=E)

        ##progress bar##
        self.progre = ttk.Progressbar(self.left,
                                      style='text.Horizontal.TProgressbar',
                                      length=200,
                                      mode='determinate')
        self.progre.grid(row=5, column=0, padx=10)
        self.progre["maximum"] = 100
        self.progre["value"] = 0

        ##scrollbar##
        self.scroll = Scrollbar(self.left)
        self.scroll.grid(row=6, column=0, rowspan=5, sticky=N + E + S)
        xscrollbar = Scrollbar(self.left, orient=HORIZONTAL)
        xscrollbar.grid(row=13, column=0, sticky=E + W)
        ###listbox##

        self.list = Listbox(self.left,
                            width=10,
                            height=20,
                            yscrollcommand=self.scroll.set,
                            xscrollcommand=xscrollbar.set)
        self.list.grid(row=6,
                       column=0,
                       sticky=W + E + N + S,
                       columnspan=1,
                       rowspan=5,
                       pady=5,
                       padx=10)
        xscrollbar.config(command=self.list.xview)

        pass

    def creat_right_weget(self):
        ##textpt##
        self.script = Button(self.right, text="Scrip", command=self.script)
        self.script.grid(row=1, column=1, pady=5, sticky=W + E)
        tt.create_ToolTip(self.script, 'Search for scripts in Seleted Site')
        self.script.config(state='disabled')
        ##comments##
        self.comments = Button(self.right,
                               text="Comments",
                               command=self.comment)
        self.comments.grid(row=1, column=2, pady=5, sticky=W + E)
        self.comments.config(state='disabled')
        tt.create_ToolTip(self.comments, 'Search for Comments in Seleted Site')
        ##Vulnerabilites##
        self.vul = Button(self.right,
                          text="Vulnerabilites",
                          command=self.vul_2)
        self.vul.grid(row=1, column=3, pady=5, sticky=W + E)
        self.vul.config(state='disabled')
        tt.create_ToolTip(self.vul,
                          'Scan passively for Vulnerabilites in Seleted Site')
        ##response header##
        self.response = Button(self.right,
                               text="Response",
                               command=self.head_2)
        self.response.grid(row=1, column=4, pady=5, sticky=W + E)
        self.response.config(state='disabled')
        tt.create_ToolTip(self.response,
                          'Print Response header for Seleted Site')
        ##request header##
        self.request = Button(self.right, text="Request", command=self.req_2)
        self.request.grid(row=1, column=5, pady=5, sticky=W + E)
        self.request.config(state='disabled')
        tt.create_ToolTip(self.request,
                          'Print Request header for textpts in Seleted Site')
        ##scrolltest##

        xscrollbar = Scrollbar(self.right, orient=HORIZONTAL)
        xscrollbar.grid(row=3, column=1, columnspan=6, sticky=E + W)
        self.text = ScrolledText(self.right,
                                 height=30,
                                 state='disabled',
                                 wrap=NONE,
                                 xscrollcommand=xscrollbar.set)
        self.text.grid(row=2,
                       column=1,
                       columnspan=6,
                       padx=10,
                       pady=5,
                       sticky=W + E)
        xscrollbar.config(command=self.text.xview)

        pass

    def st(self):
        if self.aa == False:
            self.aa = True
            self.stop.config(text="resume scan")
        elif self.aa == True:
            self.aa = False
            self.stop.config(text="pause scan")

    def th(self):
        if self.entry.get():
            if self.r.get():
                print self.r.get()
                self.t1 = threading.Thread(target=self.rev, args=[])
                self.t1.setDaemon(True)
                self.t1.start()

                #self.t2 = threading.Thread(target=self.status, args=[])
                #self.t2.start()
            else:
                messagebox.showerror("Error", "First Select the Attack Mode")
        else:

            messagebox.showerror("Error", "First Entre the target site")

##callback function for exit button##

    def exe(self):
        self.root.destroy()

##callback function for help menu##

    def he(self):

        help = mes.message()
        self.text.config(state='normal')
        #help="This is python based tool which crowl the target web site and print scripts and comments present at the target web page. "
        self.text.insert(END, help)
        self.text.config(state='disabled')

##call back function for seting menu bar##

    def con(self):
        self.top = Toplevel()
        self.top.title("User Agents")
        self.top.geometry("200x150")
        self.top.resizable(False, False)

        ba_1 = Radiobutton(self.top,
                           variable=self.rr,
                           value=1,
                           text="Chrome on Windows 8.1")
        ba_1.grid(row=0, column=0, sticky=W)
        tt.create_ToolTip(
            ba_1,
            'User-Agent : Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'
        )
        ba_2 = Radiobutton(self.top,
                           variable=self.rr,
                           value=2,
                           text="Safari on iOS")
        ba_2.grid(row=1, column=0, sticky=W)
        tt.create_ToolTip(
            ba_2,
            'User-Agent : Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B466 Safari/600.1.4'
        )
        ba_3 = Radiobutton(self.top,
                           variable=self.rr,
                           value=3,
                           text="IE6 on Windows XP")
        ba_3.grid(row=2, column=0, sticky=W)
        tt.create_ToolTip(
            ba_3,
            'User-Agent : Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)'
        )
        ba_4 = Radiobutton(self.top,
                           variable=self.rr,
                           value=4,
                           text="Googlebot")
        ba_4.grid(row=3, column=0, sticky=W)
        tt.create_ToolTip(
            ba_4,
            'User-Agent : Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
        )
        bb = Button(self.top, text="Exit", command=self.top.destroy)
        bb.grid(row=4, column=0)

    ##callback function for submitt button##

    def _mess(self):
        messagebox.showerror("Error", "First Select the target from listbox")

    ##print the textpts##
    def comment(self):

        click_item = self.list.curselection()
        self.text.config(state='normal')
        if click_item:
            self.text.delete(1.0, END)
            t = self.list.get(click_item)
            tt = str(comm[t])

            self.text.insert(END, tt)

        else:
            self._mess()
        self.text.config(state='disabled')

    def script(self):
        click_item = self.list.curselection()
        self.text.config(state='normal')
        if click_item:
            self.text.delete(1.0, END)

            t = self.list.get(click_item)
            self.tt = (sc[t])

            self.text.insert(END, self.tt)

        else:
            self._mess()

        self.text.config(state='disabled')

    ##print the request headers##
    def req_2(self):
        click_item = self.list.curselection()
        self.text.config(state='normal')
        if click_item:
            self.text.delete(1.0, END)
            self.text.insert(END, "GET\t")
            self.text.insert(END, self.list.get(click_item))

            t = self.list.get(click_item)
            tt = req[t]
            for ta in tt:
                pa = ta + "\t\t" + ":" + tt[ta] + "\n"
                self.text.insert(END, pa, 'rehead')
        else:
            self._mess()
        self.text.config(state='disabled')

        self.text.tag_config('rehead', foreground='red')

    ##print the response##
    def head_2(self):
        click_item = self.list.curselection()
        self.text.config(state='normal')
        if click_item:
            self.text.delete(1.0, END)
            statue = str(resp[self.list.get(click_item)]) + "\n"
            self.text.insert(END, statue, 'statue')
            t = self.list.get(click_item)
            tt = head[t]
            for ta in tt:
                pa = ta + "\t\t" + ":" + tt[ta] + "\n"
                self.text.insert(END, pa, 'head')
            self.text.insert(END, "\n")
            la = res[self.list.get(click_item)]
            #print la
            self.text.insert(END, la, 'body')

        else:
            self._mess()
        self.text.tag_config('statue', foreground='blue')
        self.text.tag_config('head', foreground='red')
        self.text.tag_config('body', foreground='green')
        self.text.config(state='disabled')

    ##scan for vulnerabilites##
    def vul_2(self):

        click_item = self.list.curselection()
        self.text.config(state='normal')
        if click_item:
            self.text.delete(1.0, END)

            t = self.list.get(click_item)
            tt = head[t]
            try:
                xssprotect = tt['X-XSS-Protection']
                if xssprotect != '1; mode=block':
                    self.text.insert(
                        END,
                        '\nX-XSS-Protection not set properly, XSS may be possible:'
                    )
            except:
                self.text.insert(
                    END, '\nX-XSS-Protection not set, XSS may be possible')

            try:
                contenttype = tt['X-Content-Type-Options']
                if contenttype != 'nosniff':
                    self.text.insert(
                        END, '\nX-Content-Type-Options not set properly:')
            except:
                self.text.insert(END, '\nX-Content-Type-Options not set')
            try:
                hsts = tt['Strict-Transport-Security']
            except:
                self.text.insert(
                    END, '\nHSTS header not set, MITM attacks may be possible')
            try:
                csp = tt['Content-Security-Policy']
                self.text.insert(END, '\nContent-Security-Policy set:')
            except:
                self.text.insert(END, '\nContent-Security-Policy missing')
            try:
                click = tt['x-frame-options']
            except:
                self.text.insert(
                    END,
                    "\nX-Frame-Options Header is not set, Clickjacking may be possible\n"
                )

            self.text.insert(END, "\nCookie Information\n", 'title')
            self.text.tag_config('title', foreground='blue')

            for cookie in sop[t].cookies:
                name = str(cookie.name)
                self.text.insert(END, 'Name :', 'nam')
                self.text.insert(END, name + '\n', 'value')
                self.text.insert(END, 'Value :', 'nam')
                self.text.insert(END, cookie.value + '\n', 'value')
                if not cookie.secure:
                    cookie.secure = "False"
                    self.text.insert(END, 'Secure :', 'nam')
                    self.text.insert(END, cookie.secure + '\n', 'value')

                if 'httponly' in cookie._rest.keys():
                    cookie.httponly = 'True'
                else:
                    cookie.httponly = 'False'

                self.text.insert(END, 'HTTPOnly :', 'nam')
                self.text.insert(END, cookie.httponly + '\n', 'value')
                if cookie.domain_initial_dot:
                    cookie.domain_initial_dot = 'True'
                self.text.insert(END, 'Cookie Scope to parent domain :', 'nam')
                self.text.insert(END,
                                 str(cookie.domain_initial_dot) + '\n',
                                 'value')
                self.text.insert(END, "-------------------------------\n",
                                 'new')

            self.text.tag_config('nam', foreground='red')
            self.text.tag_config('value', foreground='green')
            self.text.tag_config('new', foreground='orange')

        else:
            self._mess()

        self.text.config(state='disabled')

    def rev(self):
        self.text.config(state='normal')
        self.text.delete(1.0, END)
        self.text.config(state='disabled')
        self.menu_bar.entryconfig("Help", state='disabled')
        self.menu_bar.entryconfig("Setting", state='disabled')
        self.script.config(state='normal')
        self.comments.config(state='normal')
        self.request.config(state='normal')
        self.response.config(state='normal')
        self.vul.config(state='normal')
        self.stop.config(state='normal')
        self.submit.config(state='disabled')
        self.entry.config(state='disabled')
        if self.rr.get() == 1:
            headers = {
                'User-Agent':
                'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'
            }
        elif self.rr.get() == 2:
            headers = {
                'User-Agent':
                'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Version/8.0 Mobile/12B466 Safari/600.1.4'
            }
        elif self.rr.get() == 3:
            headers = {
                'User-Agent':
                'Mozilla/5.0 (Windows; U; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727)'
            }
        elif self.rr.get() == 4:
            headers = {
                'User-Agent':
                'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
            }

        else:
            headers = {
                'User-Agent':
                'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'
            }

        print "user agent" + str(self.rr.get())
        content = self.entry.get()
        if (content[:4] == "http") or (content[:5] == "https"):
            L.put(content)
        else:
            content = "https://" + content
            L.put(content)
        print self.entry.get()

        while (L.qsize()):
            ##start progress bar##
            self.progre.start()

            self.style.configure("text.Horizontal.TProgressbar",
                                 text="Scan is running")
            ##pause the scan##
            print self.aa
            while (self.aa):
                self.progre.stop()

                self.style.configure("text.Horizontal.TProgressbar",
                                     text="Scan Paused")
                #print("scan stop")
            trurl = L.get()

            ##check target is previsely scaned or not##
            if trurl in duplic:
                continue
            else:
                duplic.add(str(trurl))

            ## check target address is correct or not##

            try:
                response = requests.get(trurl, headers=headers)
            except:

                self.text.delete(1.0, END)
                self.progre.stop()
                #self.text.insert(END,"Please Entre Valid Address")
                messagebox.showerror("Error", "Please Entre Valid Address")
                break

            ##insert the scaned links in the list box##
            self.list.insert(END, trurl)

            resp[trurl] = response
            head[trurl] = response.headers  # storing response the headers

            req[trurl] = response.request.headers  #storing request headers
            com = " "
            sc[trurl] = com
            ##finding the scripts##

            soup = BeautifulSoup(response.content, "lxml")
            for line in soup.find_all('script'):
                for r in line.text.split(">"):
                    #print r+"\n"
                    sc[trurl] += (r) + "\n"

            ##finding the comments##
            aa = re.compile("\n")
            a = aa.sub(" ", response.text)
            comments = re.findall(r'[^>]<!--(.*?)-->', a)
            sop[trurl] = response
            if comments:
                com = " "
                comm[trurl] = com

                for c in comments:

                    comm[trurl] += "\n" + com + str(c)
            else:
                comm[trurl] = "Comments not avaliable"
        #tt=str(sc[click_item]

        #print soup.prettify()
            res[trurl] = soup.prettify()  #response.text  #storing response
            if (self.r.get() == 2):

                for line in soup.find_all('a'):
                    newline = line.get('href')
                    print newline
                    try:
                        if newline[:4] == "http" or newline[:5] == "https":  #count up to four digits
                            if trurl in newline:
                                L.put(newline)
                                #print L.qsize()

                        elif newline[:1] == "/":
                            combine = trurl + newline
                            L.put(combine)
                            #print L.qsize()
                            #print combine
                        elif newline[:1] != "/":
                            combine = trurl + "/" + newline
                            L.put(combine)

                    except:
                        print "Error"

            elif (self.r.get() == 1):
                L.empty()
        self.progre.stop()
        self.style.configure("text.Horizontal.TProgressbar",
                             text="Scan is completed")
        self.progre['value'] = 200
        self.submit.config(state='normal')
        self.entry.config(state='normal')
        self.entry.delete(0, 'end')
        self.stop.config(state='disabled')
        self.menu_bar.entryconfig("Help", state='normal')
        self.menu_bar.entryconfig("Setting", state='normal')
Пример #12
0
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()
Пример #13
0
class xbbtools_help(Toplevel):
    def __init__(self, *args):
        Toplevel.__init__(self)
        self.tid = ScrolledText(self)
        self.tid.pack(fill=BOTH, expand=1)
        self.Styles()
        self.Show()

    def Styles(self):
        for c in [
                'red', 'blue', 'magenta', 'yellow', 'green', 'red4', 'green4',
                'blue4'
        ]:
            self.tid.tag_configure(c, foreground=c)

        self.tid.tag_config('underline', underline=1)
        self.tid.tag_config('italic', font=('Courier', 6, 'italic'))
        self.tid.tag_config('bold', font=('Courier', 8, 'bold'))
        self.tid.tag_config('title', font=('Courier', 12, 'bold'))
        self.tid.tag_config('small', font=('Courier', 6, ''))
        self.tid.tag_config('highlight', background='gray')

    def Show(self):
        t = self.tid
        t.insert(END, "XBBtools Help\n", 'title')
        t.insert(
            END, """
Copyright 2001 by Thomas Sicheritz-Ponten.  All rights reserved.
This code is part of the Biopython distribution and governed by its
license.  Please see the LICENSE file that should have been included
as part of this package.\n
""", 'italic')
        t.insert(END, '[email protected]\n\n', 'blue')
        t.insert(END, '* Goto Field\n', 'bold')
        t.insert(END, '\tinserting one position moves cursor to position\n')
        t.insert(END, "\tinserting two positions, sperated by ':' ")
        t.insert(END, 'highlights', 'highlight')
        t.insert(END, ' selected range\n')
        t.insert(END, '\n')
        t.insert(END, '* Search\n', 'bold')
        t.insert(END, '\tambiguous dna values are\n')
        t.insert(
            END, """
                A: A
                C: C
                G: G
                T: T
                M: AC
                R: AG
                W: AT
                S: CG
                Y: CT
                K: GT
                V: ACG
                H: ACT
                D: AGT
                B: CGT
                X: GATC
                N: GATC

                """, 'small')
Пример #14
0
class TermWindow(Frame):
    ##
    # constructor method
    def __init__(self, master = None, **cnf):
        apply(Frame.__init__, (self, master), cnf)
        self.__create_widgets__()
        self.rxThread = None
        self.rxWaitEvent = threading.Event()
        self.rxWaitPattern = ""
        self.localEcho = False
        self.logFile = None
        self.textQueue = Queue.Queue()
        self.update_thread_safe()

    def update_thread_safe(self):
        try:
            while 1:
                element = self.textQueue.get_nowait()
                if element is not None:
                    msg,tag = element
                    self.__display__(msg,tag)
                self.st_trm.update_idletasks()
        except Queue.Empty:
            pass
        self.st_trm.after(100, self.update_thread_safe)

    ##
    # worker function for threaded reading from the input of
    # the assigned device
    #
    def __thrd_reader__(self):
        self.waitbuf = ""
        while 1:
            try:
                x = self.device.read()
                if len(x):
                    cmd = self.cmdVar.get()
                    if len(cmd):
                        self.cmdVar.set("")
                    self.write(x)
                    if self.rxWaitEvent.isSet():
                        self.waitbuf += x
                        if self.waitbuf.find(self.rxWaitPattern) > -1:
                            self.rxWaitEvent.clear()
                            while not self.rxWaitEvent.isSet():
                                pass
                            self.rxWaitEvent.clear()
            except:
                traceback.print_exc()
                time.sleep(1)
            else:
                # this infinitesimal sleep keeps the GUI update alive
                time.sleep(.01)

    def waitfor(self, pattern, maxwait=10):
        self.waitbuf = ""
        self.rxWaitPattern = pattern
        self.rxWaitEvent.set()
        self.maxwait = 10
        while self.rxWaitEvent.isSet() and self.maxwait > 0:
            time.sleep(1)
            self.maxwait -= 1
        if self.maxwait == 0:
            self.message("PatternNotFound")
        self.rxWaitEvent.set()

    ##
    #
    def __create_widgets__(self):
        dfl_font = 'Courier 10'

        # the title frame of the terminal
        self.f_title = Frame(self)
        self.f_title.pack(fill=BOTH)
        self.f_title.configure(FRAMEBORDER)
        self.shVar = StringVar()
        # show/hide button
        self.b_sh = Button(self.f_title, textvariable=self.shVar, font=dfl_font)
        self.b_sh.pack(side=RIGHT)
        self.b_sh['command'] = self.show_hide_cont
        # clear screen button
        self.b_cls = Button(self.f_title, text="CLS", font=dfl_font, underline=0)
        self.b_cls.pack(side=RIGHT)
        self.b_cls['command'] = self.clear_screen
        # echo on/off button
        self.al_echo = Label(self.f_title, text = "ECHO", relief = RAISED,
                             font = dfl_font, padx='3m', pady='1m', underline=0)
        self.al_echo.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.al_echo.bind("<Button-1>", self.__echo_handler__)
        # log on/off button
        self.al_log = Label(self.f_title, text = "LOG", relief = RAISED,
                            font = dfl_font, padx='3m', pady='1m', underline=0)
        self.al_log.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.al_log.bind("<Button-1>", self.__log_handler__)
        # device connect button
        self.al_connect = Label(self.f_title, text = "CONNECT", relief = RAISED,
                                font = dfl_font, padx='3m', pady='1m', underline=1)
        self.al_connect.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.al_connect.bind("<Button-1>", self.__connect_handler__)

        self.mb_macros = Menubutton(self.f_title, text = "Macros", relief=RAISED)
        self.mb_macros.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.mb_macros.menu = Menu(self.mb_macros, tearoff = 0)
        self.mb_macros["menu"] = self.mb_macros.menu


        # title of terminal window
        self.tVar = StringVar()
        self.l_title = Label(self.f_title, text="foo", font=dfl_font)
        self.l_title['textvariable'] = self.tVar
        self.l_title.pack(side=LEFT, expand=1, fill=X)
        self.l_title['width'] = 42
        self.update_title("------ XXX ------")
        # frame for scrolled text window
        # (this frame handle needs to be kept fo show_hide_cont())
        self.f_cont = Frame(self)
        # IO data scrolled text window
        self.st_trm = ScrolledText(self.f_cont, height=10, state=DISABLED, wrap=NONE)
        self.st_trm.pack(expand=1,fill=BOTH)
        self.st_trm['font'] = dfl_font
        self.st_trm.tag_config('E', foreground="blue")
        self.st_trm.tag_config('M', foreground="magenta")


        tframe = Frame(self.f_cont)
        tframe.pack(expand = 0, fill = X)
        self.cmdVar = StringVar()
        self.ent_trm = Entry(tframe, textvariable=self.cmdVar, font=dfl_font)
        self.ent_trm.pack(side=LEFT, expand =1, fill = X)
        self.ent_trm.bind("<Control-l>", self.__log_handler__)
        self.ent_trm.bind("<Control-e>", self.__echo_handler__)
        self.ent_trm.bind("<Control-o>", self.__connect_handler__)
        self.ent_trm.bind("<Control-c>", self.clear_screen)
        self.ent_trm.bind("<Control-x>", self.show_hide_cont)
        self.ent_trm.bind("<Control-m>", lambda *args: self.do_macro("M"))
        self.ent_trm.bind("<KeyPress>", self.__input_handler__)

        self.gui_elements = [ self.b_sh,
                              self.b_cls,
                              self.al_echo,
                              self.al_log,
                              self.al_connect,
                              self.mb_macros,
                              self.l_title,
                              self.st_trm,
                              self.ent_trm]
        self.show_cont()

    def add_macro(self, id, title, text = None, function = None, params = None):
        if text:
            cmd = lambda *args: self.do_macro(text)
        if function:
            user_func = eval(function)
            params = eval(str(params))
            cmd = lambda *args: user_func(DEVICES, **params)
        mb = self.mb_macros.menu.add_command(label = title, command = cmd)

    def _configure_(self,**args):
        for e in self.gui_elements:
            e.configure(args)

    def __input_handler__(self, *args):
        for i in args:
            if self.localEcho:
                self.display(i.char, "E")
            if len(i.char):
                if i.char == "\r":
                    self.device.write("\r\n")
                    self.cmdVar.set("")
                else:
                    self.device.write(i.char)

    def __echo_handler__(self, *args):
        if self.localEcho:
            self.localEcho = False
            self.al_echo['relief'] = RAISED
            self.message("Local Echo OFF")
        else:
            self.localEcho = True
            self.al_echo['relief'] = SUNKEN
            self.message("Local Echo ON")

    def __log_handler__(self, *args):
        try:
            do_open = self.logFile.closed
            logname = self.logFile.name
        except:
            do_open = True
            logname = ""
        if do_open:
            if self.device.logname:
                logname = self.device.logname
                self.message("logfile from config file %s " % logname)
            else:
                fd = FileDialog(self)
                logname = fd.go(logname)
            try:
                if self.device.logmode not in "wa":
                    self.device.logmode = "a"
                    print "force _a_ppend"
                self.logFile = open(logname, self.device.logmode)
                self.al_log['relief'] = SUNKEN
                self.message("Logging ON: %s" % self.logFile.name)
            except:
                self.message("Error open logfile: %s" % logname)

        else:
            self.message("Logging OFF: %s" % self.logFile.name)
            self.logFile.flush()
            self.logFile.close()
            self.al_log['relief'] = RAISED

    def __connect_handler__(self, *args):
        if self.device.isConnected:
            self.device.disconnect()
            self.al_connect['relief'] = RAISED
            self.message("Disconnected")
        else:
            try:
                self.device.connect()
                self.al_connect['relief'] = SUNKEN
                self.message("Connected")
                self.al_connect['fg'] = "black"
            except:
                self.device.isConnected = False
                self.message( str(sys.exc_info()[1]) )
                self.al_connect['fg'] = "red"

    def clear_screen(self, *args):
        self.st_trm['state'] = NORMAL
        self.st_trm.delete("0.0",END)
        self.st_trm['state'] = DISABLED

    def set_device(self,device):
        self.device = device
        self.rxThread = threading.Thread(target = self.__thrd_reader__)
        # if a thread is not a daemon, the program needs to join all
        self.rxThread.setDaemon(1)
        print "**",self.device, self.device.name
        self.rxThread.setName("GUI_RX_%s" % self.device.name)
        self.rxThread.start()
        self.update_title(self.device)
        #
        if self.device.echo:
            self.localEcho = 0
            self.__echo_handler__()
        if self.device.log:
            self.__log_handler__()
        if self.device.auto_connect:
            self.__connect_handler__()

    def update_title(self, title):
        self.tVar.set(title)

    def show_cont(self):
        self.shVar.set("X")
        self.f_cont.pack(expand=1,fill=BOTH)

    def hide_cont(self):
        self.shVar.set("+")
        self.f_cont.pack_forget()

    def show_hide_cont(self, *args):
        if self.shVar.get() == "X":
            self.hide_cont()
        else:
            self.show_cont()

    def do_macro(self, *args):
        if self.localEcho:
            self.display(args[0] + "\n", "E")
        self.device.write(args[0]+ "\n")

    def write(self, data):
        self.textQueue.put((data, None))

    def message(self, text, tag='M'):
        msg = "[%s:%s:%s]\n" % (time.asctime(),self.device.name, text)
        if self.st_trm.index(AtInsert()).find(".0")  < 1:
            msg = "\n" + msg
        self.textQueue.put((msg, tag))

    def display(self, text, tag = None):
        self.textQueue.put((text, tag))

    def __display__(self, msg, tag = None):
        self.st_trm['state'] = NORMAL
        here =  self.st_trm.index(AtInsert())
        for d in re.split("([\r\v\t\n])", msg):
            if len(d):
                if d != '\r':
                    self.st_trm.insert(END, d)
        if tag:
            self.st_trm.tag_add(tag, here, AtInsert())
        self.st_trm.see(END)
        self.st_trm['state'] = DISABLED
        try:
            self.logFile.write(msg)
            self.logFile.flush()
        except:
            pass
Пример #15
0
                                  width=11, command=open_file)
button_open_file.grid(column=0, row=0)
button_open_dir = Tkinter.Button(root, text='Open dir...',
                                 width=11, command=open_dir)
button_open_dir.grid(column=1, row=0)
quiet_var = Tkinter.BooleanVar()
button_quiet = Tkinter.Checkbutton(root, text='Quiet', width=11,
                                   command=quiet, indicatoron=False,
                                   variable=quiet_var)
button_quiet.grid(column=2, row=0, sticky='ns')
button_close = Tkinter.Button(root, text='Close', width=11, command=root.quit)
button_close.grid(column=3, row=0, sticky='e')
text = ScrolledText(root, state='disabled',
                    font=font, exportselection=True)
text.grid(column=0, row=1, columnspan=4, sticky='news')
text.tag_config('h2', foreground='blue', font=font_bold)
text.tag_config('h3', foreground='blue')
text.tag_config('h4', font=font_bold)
text.tag_config('good', foreground='#00a000')
text.tag_config('bad', foreground='red')
text.tag_config('txt', background='#e8e8e8')
root.columnconfigure(3, weight=999)
root.rowconfigure(1, weight=999)

def select_all():
    text.tag_remove('sel', 0.0, 'end')
    text.tag_add('sel', 0.0, 'end')

def text_copy():
    #text.event_generate("<<Copy>>")
    text.tk.call("tk_textCopy", text)
class my_form(Frame):
    """Form"""
    def __init__(self, master=None):
        """create elements of form"""
        Frame.__init__(self, master)
        self.pack()

        self.textBox = ScrolledText(self, height=5, width=115)
        #self.textBox.pack()
        self.textBox.tag_config("b", foreground="blue")
        self.textBox.tag_config("r", foreground="red")

        self.label_dummy = Label(self, width=100, text=" ")
        self.label_dummy.pack()

        self.label_dummy1 = Label(self, width=100, text=" ")
        self.pressButton = Button(self,
                text="Write ID3 Tags", command=self.write_id3_tags_prepare)
        #self.pressButton.pack()

        # registering callback
        self.listenID = self.after(400, self.lets_rock)

    def display_logging(self, log_message, text_format):
        """display messages in form, loading periodically """
        if text_format is None:
            self.textBox.insert(END, log_message + "\n")
        else:
            self.textBox.insert(END, log_message + "\n", text_format)

    def write_id3_tags_prepare(self):
        """prepare for writing tags"""
        result = tkMessageBox.askquestion(
                        self.msg[5], self.msg[6], icon='warning')
        if result == 'yes':
            self.display_logging(self.msg[7], None)
            z = 0
            for item in self.mp3_files:
                self.display_logging(self.entry_a[z].get(), "b")
                self.display_logging(self.entry_b[z].get(), "b")
                write_id3_tags(self, item,
                    self.entry_a[z].get(), self.entry_b[z].get())
                self.textBox.see(END)
                z += 1
        else:
            self.display_logging(self.msg[8], None)
            self.textBox.see(END)

    def lets_rock(self):
        """man funktion"""
        print "lets rock"
        switch_lang(self)
        self.display_logging(self.msg[1], None)

        # check packages
        check_package = True
        check_package = check_packages(self,
                                ["sox", "mp3gain", "mp3splt", "easytag"])
        if check_package is None:
            return

        try:
            path_files = (
                os.environ['NAUTILUS_SCRIPT_SELECTED_FILE_PATHS'].splitlines())
        except Exception, e:
            self.display_logging("Error: %s" % str(e), "r")
            self.display_logging(self.err[2], None)
            return

        self.display_logging(self.msg[2], None)
        self.display_logging(os.path.dirname(path_files[0]), None)
        self.display_logging(self.msg[3], None)
        self.mp3_files = []
        for item in path_files:
            if string.rfind(item, ".mp3") == -1:
                # no mp3:
                continue
            self.mp3_files.append(item)
            self.display_logging(extract_filename(item), "b")

        # check for mp3 files
        if len(self.mp3_files) == 0:
            self.display_logging(self.err[3], "r")
            self.display_logging(self.msg[4], None)
            return
        #return
        z = 0
        self.label_dummy = []
        self.label = []
        self.entry_a = []
        self.entry_b = []
        for item in self.mp3_files:
            if z == 10:
                self.display_logging(self.msg[9], "b")
                continue
            #self.display_logging(extract_filename(item), "r")
            author, title = read_id3_tags(self, item)
            try:
                self.my_label = Label(self,
                    width=100, text=extract_filename(item))
                self.label.append(self.my_label)
                self.label[z].pack()

                self.my_entry_a = Entry(self, width=100)
                self.entry_a.append(self.my_entry_a)
                self.entry_a[z].pack()
                self.entry_a[z].insert(0, author)

                self.my_entry_b = Entry(self, width=100)
                self.entry_b.append(self.my_entry_b)
                self.entry_b[z].pack()
                self.entry_b[z].insert(0, title)

                self.my_label_dummy = Label(self, width=100, text=" ")
                self.label_dummy.append(self.my_label_dummy)
                self.label_dummy[z].pack()
                z += 1
            except Exception, e:
                self.display_logging("Error: %s" % str(e), "r")
Пример #17
0
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')
Пример #18
0
class TermWindow(Frame):
    EOL = None

    ##
    # constructor method
    def __init__(self, master=None, **cnf):
        apply(Frame.__init__, (self, master), cnf)
        self.__create_widgets__()
        self.rxWaitPattern = ""
        self.localEcho = False
        self.logFile = None
        self.inQueue = Queue.Queue()
        self.outQueue = Queue.Queue()
        self.update_thread_safe()

    def update_thread_safe(self):
        while not self.inQueue.empty():
            element = self.inQueue.get_nowait()
            if element is not None:
                msg, tag = element
                self.__display__(msg, tag)
            self.st_trm.update_idletasks()
        self.st_trm.after(100, self.update_thread_safe)

    ##
    #
    def __create_widgets__(self):
        dfl_font = 'Courier 10'

        # the title frame of the terminal
        self.f_title = Frame(self)
        self.f_title.pack(fill=BOTH)
        self.f_title.configure(FRAMEBORDER)
        self.shVar = StringVar()
        # show/hide button
        self.b_sh = Button(self.f_title,
                           textvariable=self.shVar,
                           font=dfl_font)
        self.b_sh.pack(side=RIGHT)
        self.b_sh['command'] = self.show_hide_cont
        # clear screen button
        self.b_cls = Button(self.f_title,
                            text="CLS",
                            font=dfl_font,
                            underline=0)
        self.b_cls.pack(side=RIGHT)
        self.b_cls['command'] = self.clear_screen
        # echo on/off button
        self.al_echo = Label(self.f_title,
                             text="ECHO",
                             relief=RAISED,
                             font=dfl_font,
                             padx='3m',
                             pady='1m',
                             underline=0)
        self.al_echo.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.al_echo.bind("<Button-1>", self.__echo_handler__)
        # log on/off button
        self.al_log = Label(self.f_title,
                            text="LOG",
                            relief=RAISED,
                            font=dfl_font,
                            padx='3m',
                            pady='1m',
                            underline=0)
        self.al_log.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.al_log.bind("<Button-1>", self.__log_handler__)
        # device connect button
        self.al_connect = Label(self.f_title,
                                text="CONNECT",
                                relief=RAISED,
                                font=dfl_font,
                                padx='3m',
                                pady='1m',
                                underline=1)
        self.al_connect.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.al_connect.bind("<Button-1>", self.__connect_handler__)

        self.mb_macros = Menubutton(self.f_title, text="Macros", relief=RAISED)
        self.mb_macros.pack(side=RIGHT, padx=1, pady=1, fill=BOTH)
        self.mb_macros.menu = Menu(self.mb_macros, tearoff=0)
        self.mb_macros["menu"] = self.mb_macros.menu

        # title of terminal window
        self.tVar = StringVar()
        self.l_title = Label(self.f_title, text="foo", font=dfl_font)
        self.l_title['textvariable'] = self.tVar
        self.l_title.pack(side=LEFT, expand=1, fill=X)
        self.l_title['width'] = 42
        self.update_title("------ XXX ------")
        # frame for scrolled text window
        # (this frame handle needs to be kept fo show_hide_cont())
        self.f_cont = Frame(self)
        # IO data scrolled text window
        self.st_trm = ScrolledText(self.f_cont,
                                   height=10,
                                   state=DISABLED,
                                   wrap=NONE)
        self.st_trm.pack(expand=1, fill=BOTH)
        self.st_trm['font'] = dfl_font
        self.st_trm.tag_config('E', foreground="blue")
        self.st_trm.tag_config('M', foreground="magenta")

        tframe = Frame(self.f_cont)
        tframe.pack(expand=0, fill=X)
        self.cmdVar = StringVar()
        self.ent_trm = Entry(tframe, textvariable=self.cmdVar, font=dfl_font)
        self.ent_trm.pack(side=LEFT, expand=1, fill=X)
        self.ent_trm.bind("<Control-l>", self.__log_handler__)
        self.ent_trm.bind("<Control-e>", self.__echo_handler__)
        self.ent_trm.bind("<Control-o>", self.__connect_handler__)
        self.ent_trm.bind("<Control-c>", self.clear_screen)
        self.ent_trm.bind("<Control-x>", self.show_hide_cont)
        self.ent_trm.bind("<Control-m>", lambda *args: self.do_macro("M"))
        self.ent_trm.bind("<KeyPress>", self.__input_handler__)

        self.gui_elements = [
            self.b_sh, self.b_cls, self.al_echo, self.al_log, self.al_connect,
            self.mb_macros, self.l_title, self.st_trm, self.ent_trm
        ]
        self.show_cont()

    def add_macro(self, id, title, text=None, function=None, params=None):
        if text:
            cmd = lambda *args: self.do_macro(text)
        if function:
            user_func = eval(function)
            if params:
                params = eval(str(params))
            else:
                params = {}
            cmd = lambda *args: user_func(self, DEVICES, **params)
        mb = self.mb_macros.menu.add_command(label=title, command=cmd)

    def _configure_(self, **args):
        for e in self.gui_elements:
            e.configure(args)

    def __input_handler__(self, *args):
        for i in args:
            self.terminal_device_write(i.char)

    def terminal_device_write(self, *args):
        for i in args:
            if self.localEcho:
                self.display(i, "E")
            if len(i):
                if i == "\r" or i == "\n":
                    self.device.write(self.EOL)
                    self.display(self.EOL, "E")
                    self.cmdVar.set("")
                else:
                    self.device.write(i)
        self.st_trm.update_idletasks()

    def __echo_handler__(self, *args):
        if self.localEcho:
            self.localEcho = False
            self.al_echo['relief'] = RAISED
            self.message("Local Echo OFF")
        else:
            self.localEcho = True
            self.al_echo['relief'] = SUNKEN
            self.message("Local Echo ON")

    def __log_handler__(self, *args):
        try:
            do_open = self.logFile.closed
            logname = self.logFile.name
        except:
            do_open = True
            logname = ""
        if do_open:
            if self.device.logname:
                logname = self.device.logname
                self.message("logfile from config file %s " % logname)
            else:
                fd = FileDialog(self)
                logname = fd.go(logname)
            try:
                if self.device.logmode not in "wa":
                    self.device.logmode = "a"
                    _print(3, "force _a_ppend")
                self.logFile = open(logname, self.device.logmode)
                self.al_log['relief'] = SUNKEN
                self.message("Logging ON: %s" % self.logFile.name)
            except:
                self.message("Error open logfile: %s" % logname)

        else:
            self.message("Logging OFF: %s" % self.logFile.name)
            self.logFile.flush()
            self.logFile.close()
            self.al_log['relief'] = RAISED

    def __connect_handler__(self, *args):
        if self.device.isConnected:
            self.device.disconnect()
            self.al_connect['relief'] = RAISED
            self.message("Disconnected")
        else:
            try:
                self.device.connect()
                self.al_connect['relief'] = SUNKEN
                self.message("Connected")
                self.al_connect['fg'] = "black"
            except:
                self.device.isConnected = False
                self.message(str(sys.exc_info()[1]))
                self.al_connect['fg'] = "red"

    def clear_screen(self, *args):
        self.st_trm['state'] = NORMAL
        self.st_trm.delete("0.0", END)
        self.st_trm['state'] = DISABLED

    def set_device(self, device):
        self.device = device
        self.device.configure(TxQueue=self.outQueue, RxQueue=self.inQueue)
        self.update_title(self.device)

        if self.device.log:
            self.__log_handler__()
        if self.device.auto_connect:
            self.__connect_handler__()

    def update_title(self, title):
        self.tVar.set(title)

    def show_cont(self):
        self.shVar.set("X")
        self.f_cont.pack(expand=1, fill=BOTH)

    def hide_cont(self):
        self.shVar.set("+")
        self.f_cont.pack_forget()

    def show_hide_cont(self, *args):
        if self.shVar.get() == "X":
            self.hide_cont()
        else:
            self.show_cont()

    def do_macro(self, *args):
        if self.localEcho:
            self.display(args[0] + "\n", "E")
        self.device.write(args[0] + "\n")

    def write(self, data):
        self.outQueue.put((data, None))

    def message(self, text, tag='M'):
        msg = "[%s:%s:%s]\n" % (time.asctime(), self.device.name, text)
        if self.st_trm.index(AtInsert()).find(".0") < 1:
            msg = "\n" + msg
        self.inQueue.put((msg, tag))

    def display(self, text, tag=None):
        self.inQueue.put((text, tag))

    def __display__(self, msg, tag=None):
        self.st_trm['state'] = NORMAL
        here = self.st_trm.index(AtInsert())
        for d in re.split("([\r\v\t\n])", msg):
            if len(d):
                if d != '\r':
                    self.st_trm.insert(END, d)
        if tag:
            self.st_trm.tag_add(tag, here, AtInsert())
        self.st_trm.see(END)
        self.st_trm['state'] = DISABLED
        try:
            self.logFile.write(msg)
            self.logFile.flush()
        except:
            pass
Пример #19
0
    def run(self):

        #        help_window()

        #def help_window():
        from ScrolledText import ScrolledText

        def gotosettings(*args):
            text.see(tk.END)
            text.see(setting_index)

        def gotoinfo(*args):
            text.see(tk.END)
            text.see(info_index)

        def gotoprereq(*args):
            text.see(tk.END)
            text.see(prereq_index)

        def gotolc(*args):
            text.see(tk.END)
            text.see(lc_index)

        def gototop(*args):
            text.see(tk.END)
            text.see(top_index)

        def gotospec(*args):
            text.see(tk.END)
            text.see(spec_index)

        def show_tcross_cursor(*args):
            text.config(cursor="tcross")

        def show_arrow_cursor(*args):
            text.config(cursor="arrow")

        self.help_top = tk.Toplevel()
        self.help_top.title("Help")
        text = ScrolledText(self.help_top, bg='white')
        text.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.Y)
        bold_font = tkFont.Font(text, text.cget("font"))
        bold_font.configure(weight='bold')

        txt0 = """

           Contents

    General Information
    Settings Panel
    Prerequisites Panel
    Lightcurve Panel
    Spectrum Panel










\n"""

        text.insert(tk.END, txt0)
        # Define tags
        text.tag_add('settings', "%s-15l+4c" % tk.INSERT,
                     "%s-15l+18c" % tk.INSERT)
        text.tag_bind('settings', '<Enter>', show_arrow_cursor)
        text.tag_bind('settings', '<Leave>', show_tcross_cursor)
        text.tag_config('settings', foreground='blue', underline=1)
        text.tag_bind('settings', '<Button-1>', gotosettings)

        text.tag_add('info', "%s-16l+4c" % tk.INSERT, "%s-16l+24c" % tk.INSERT)
        text.tag_bind('info', '<Enter>', show_arrow_cursor)
        text.tag_bind('info', '<Leave>', show_tcross_cursor)
        text.tag_config('info', foreground='blue', underline=1)
        text.tag_bind('info', '<Button-1>', gotoinfo)

        text.tag_add('prereq', "%s-14l+4c" % tk.INSERT,
                     "%s-14l+24c" % tk.INSERT)
        text.tag_bind('prereq', '<Enter>', show_arrow_cursor)
        text.tag_bind('prereq', '<Leave>', show_tcross_cursor)
        text.tag_config('prereq', foreground='blue', underline=1)
        text.tag_bind('prereq', '<Button-1>', gotoprereq)

        text.tag_add('lc', "%s-13l+4c" % tk.INSERT, "%s-13l+20c" % tk.INSERT)
        text.tag_bind('lc', '<Enter>', show_arrow_cursor)
        text.tag_bind('lc', '<Leave>', show_tcross_cursor)
        text.tag_config('lc', foreground='blue', underline=1)
        text.tag_bind('lc', '<Button-1>', gotolc)

        text.tag_add('spec', "%s-12l+4c" % tk.INSERT, "%s-12l+18c" % tk.INSERT)
        text.tag_bind('spec', '<Enter>', show_arrow_cursor)
        text.tag_bind('spec', '<Leave>', show_tcross_cursor)
        text.tag_config('spec', foreground='blue', underline=1)
        text.tag_bind('spec', '<Button-1>', gotospec)

        setting_index = '70.0'
        info_index = '20.0'
        prereq_index = '100.0'
        lc_index = '140.0'
        spec_index = '167.0'
        top_index = '0.0'

        text.insert(tk.END, "General information\n")
        text.tag_add('tag', "%s-1l" % tk.INSERT, tk.INSERT)
        text.tag_config('tag', font=bold_font, underline=1, justify=tk.CENTER)
        text.insert(tk.END, "\n")

        txt1 = """

Latspec is designed to analyze FERMI/LAT data. The tool allows to perform  all
stages  of  analysis including event filtering, imaging analysis, spectrum and 
lightcurve generation and spectral modeling using single graphical interface.

The core idea behind the  Latspec data analysis  is  to use ancillary response 
to  account  for  the PSF spillover, allowing to use small extraction radii to
minimize  contamination  from nearby sources. The tool gives  reliable results 
for  well isolated and  relatively bright source. However, standard likelihood 
is recommended in the case of a  faint source in a crouded field. Even in this 
case, Latspec can be helpful to  examine your data and to do "quick-and-dirty"
analysis.

The  program allows  user to process the LAT data, starting from the data set, 
extracted from the LAT data  server,  apply  all  necessary  filters,  specify
regions  and  produce intermediary data  products  necessary  for spectral and
lightcurve analysis. For source and background  region selection  the  program
utilizes DS9 image viewer. The LAT data to be analysed along with some  common
analysis parameters can be set using the  "Settings" panel. Preparation  tasks
(filtered event list, galactic cube and image generation) are performed at the
"Prerequisites" panel.
"""
        text.insert(tk.END, txt1)
        text.tag_add('prereq', "%s-1l+0c" % tk.INSERT, "%s-1l+15c" % tk.INSERT)
        text.tag_add('settings', "%s-3l+42c" % tk.INSERT,
                     "%s-3l+52c" % tk.INSERT)

        txt11 = """
For  spectral  analysis  the  program  extracts count  spectra for   specified
source and background regions, creates necessary response files and optionally
fits spectral model to the data. The  application  also  provides interface to
Xspec spectral fitting package for spectral modeling. Lightcurve is calculated
using Xspec spectral fitting, i.e. spectrum is extracted  and  spectral fit is
performed  for  each  time  interval.  Details  on how to generate and analyze 
spectra and lightcurves tasks are given below  in  "Spectrum" and "Lightcurve"
sections respectively.
    """
        text.insert(tk.END, txt11)
        text.tag_add('lc', "%s-2l+62c" % tk.INSERT, "%s-2l+75c" % tk.INSERT)
        text.tag_add('spec', "%s-2l+47c" % tk.INSERT, "%s-2l+56c" % tk.INSERT)
        txt2 = """

The main  window  of the  program has three frames: top, middle (Log) and  the
bottom  frame.  The  top  frame  is  where analysis is performed by using four
panels: "Settings", "Prerequisites", "Lightcurve" and  "Spectrum". Buttons  at 
the bottom of the top frame are used to  switch between  analysis panels.  The
log  window  displays  various  information about analysis steps taken, errors 
occured, warning, etc. Text lines are color coded for convenience. Namely, the
output of different tasks performed  is  shown  in black, errors in red, hints 
for the next step to take is in blue. The  bottom  row  has four  buttons. The
"Save log" writes the contents of the log window in a  file <basename>.log and
the "Clear Log"  button  clears  the log window. "Help" button shows user this
help and the "Quit" button  quits  Latspec.  Quitting  Latspec  may  take some 
noticable time (few seconds) as the program has to perform some clean up steps: shut  down  all active analysis threads, close any open windows, etc.
    """

        text.insert(tk.END, txt2)

        text.insert(
            tk.END,
            "                                                            Back to top"
        )
        text.tag_add('back', "%s-0l-11c" % tk.INSERT, "%s-0l-0c" % tk.INSERT)
        text.tag_bind('back', '<Enter>', show_arrow_cursor)
        text.tag_bind('back', '<Leave>', show_tcross_cursor)
        text.tag_config('back', foreground='red', underline=1)
        text.tag_bind('back', '<Button-1>', gototop)

        text.insert(tk.END, "\n")
        text.insert(tk.END, "Settings Panel\n")

        text.tag_add('tag', "%s-1l" % tk.INSERT, tk.INSERT)
        text.insert(tk.END, "\n")
        txt3 = """

There  are   four   sections  in  this panel:"Data", "Catalog", "Basename" and
"Parameters". The "Data"  section  has the "..." button which allows to change
the data directory. The "Data info" button prints a short synopsis of the data 
in the Log window. The "Catalog" section allows to specify a 2FGL catalog file
using the "..." button. You  need  to  specify catalog only the first time you
start  the  program. Latspec  stores information  about  the  latest data  and 
catalog in the resource file (~/.latspecrc) and will load  them  automatically
next time you start the program.

The "Flux threshold" entry shows the lower flux limit (given in  the  FLUX1000
column of 2FGL catalog) which used to display the catalog sources in  the  DS9
imaging tool (see "Prerequisites"  panel  section  below).  Namely,  when  you 
increase/decrease the  flux  threshold, less/more  sources appear on the image 
and in the 2FGL source  dropdown  menu list in  the  "Image"  section  of  the
"Prerequisites"  panel.
"""
        text.insert(tk.END, txt3)
        text.tag_add('prereq', "%s-1l+0c" % tk.INSERT, "%s-1l+15c" % tk.INSERT)
        txt31 = """
The "Basename" entry specifes the analysis  "basename". It is used as a prefix
to all intermediary files created during analysis (i.e. <basename>_ltcube.fits
for galactic cube,<basename>_roi.fits for  image,etc). The default basename is
"latspec". For each analysed   source  Latspec  creates  individual  directory 
named <basename>_<sourceid> under the current data directory, where <sourceid>
is  either  source  2FGL  catalog  name, if  2FGL catalog is specified, or sky 
location ID ra<RA>_dec<DEC>_rad<radius>. For example, for 3C 273 the directory 
name will be  set to latspec_2FGLJ1229.1+0202 or latspec_r187.35_dec2.00_r3.00
respectiviely.  All  data  products file names, created in the current session 
will have the same <basename>_<sourceID> structure prefix.

The  "Parameters" subpanel allows to set or modify parameters binsz, dcostheta,
thetamax, zmax and set  the IRFS  used  by FERMI Science Tools (gtltcube,gtpsf,
gtrspgen,gtbin,etc.). 
    """

        text.insert(tk.END, txt31)

        text.insert(
            tk.END,
            "                                                            Back to top"
        )
        text.tag_add('back', "%s-0l-11c" % tk.INSERT, "%s-0l-0c" % tk.INSERT)
        text.tag_bind('back', '<Enter>', show_arrow_cursor)
        text.tag_bind('back', '<Leave>', show_tcross_cursor)
        text.tag_config('back', foreground='red', underline=1)
        text.tag_bind('back', '<Button-1>', gototop)

        text.insert(tk.END, "\n")
        text.insert(tk.END, "\n")
        text.insert(tk.END, "\n")
        text.insert(tk.END, "Prerequisites Panel\n")
        text.tag_add('tag', "%s-1l" % tk.INSERT, tk.INSERT)
        #    text.tag_config('tag',foreground='blue',underline=1,justify=tk.CENTER)
        text.insert(tk.END, "\n")
        text.insert(tk.END, "\n")
        txt4 = """    

This panels has three subpanels:"Events","Ltcube" and "Image" used to  create 
or specify filtered event file, galactic cube and image file. These tasks are
achieved by clicking on the "Filter Events","Run GTLTcube" and "Extract Image"
buttons correspondingly. The Latspec then executes a pipeline of Science Tools
to create a specific data product. When the product is created, its name shows
up  on  the  left side of a subpanel. Clicking on a button before the pipeline 
will terminate it and the product will NOT be created. The output event list,
cube or image files will have names with the <basename>_ prefix.

The  "Ltcube"  subpanel has an additional button "Load Cube" to specify a pre-
existing galactic cube file.

The "Image" and "Regions" subpanels present a set of components to extract the
image of the region and  to  specify  the  source  and background regions. The 
entire region image is extracted by clicking  the "Extract image" button. When
image  is  available  (i.e. the  name  of  the image file is shown next to the 
"Extract image"  button),  the source and background extraction regions can be 
set using any of the following three ways. First, region coordinates and radii
can directly set in the corresponding entries of the  "Regions"  panel. Second,
if catalog is specified, the source region can placed over a catalog source by 
choosing its name in the "2FGL Source" menu. Third,  you  can  launch  DS9 and 
modify regions in DS9. Namely, clicking on "Run DS9" will launch DS9, load the 
image, preset the source and background region selection and  show the catalog
sources in the DS9 window. Modifying the regions in the DS9 image  will update
the numbers in the "Regions" panel. In parallel, catalog source identification
is preformed and, if the center of the current source region is idetified with
a catalog source, its name appears in the  catalog  source  menu. (It is worth
noting that source names that are used here are taken from  ASSOC1  column  of
the catalog or from the SOURCE column if  ASSOC1  is  empty.  Also, the source
identification  is  done  with  ANY  2FGL source, while the dropdown menu list 
shows  only  sources  with  2FGL  flux above  the  flux  threshold, set in the 
"Settings" panel).
    """
        text.insert(tk.END, txt4)
        text.tag_add('settings', "%s-1l-4c" % tk.INSERT,
                     "%s-1l+6c" % tk.INSERT)
        txt41 = """

After you are done with producing event/cube/image files and  selecting your 
extraction regions, you can proceed with spectral analysis in the "Spectrum" 
panel or timing analysis in the "Lightcurve" panel. 
                                """
        text.insert(tk.END, txt41)
        text.tag_add('lc', "%s-1l+0c" % tk.INSERT, "%s-1l+12c" % tk.INSERT)
        text.tag_add('spec', "%s-2l+34c" % tk.INSERT, "%s-2l+44c" % tk.INSERT)

        text.insert(
            tk.END,
            "\n                                                               Back to top"
        )
        text.tag_add('back', "%s-0l-11c" % tk.INSERT, "%s-0l-0c" % tk.INSERT)
        text.tag_bind('back', '<Enter>', show_arrow_cursor)
        text.tag_bind('back', '<Leave>', show_tcross_cursor)
        text.tag_config('back', foreground='red', underline=1)
        text.tag_bind('back', '<Button-1>', gototop)

        text.insert(tk.END, "\n")
        text.insert(tk.END, "\n")
        text.insert(tk.END, "Lightcurve Panel\n")
        text.tag_add('tag', "%s-1l" % tk.INSERT, tk.INSERT)

        txt5 = """

The lightcurve calculation is implemented as follows. Photon flux in each time
bin is calcilated via spectrum  fitting,  accounting  for  PSF  spillover. The
spectrum  is  fit  with  pure  power  law. The photon flux with its errors  is 
calculated  using cflux model (see XSPEC documentaion).

 The "Lightcurve" binning dropdown menue sets the bin size of the lightcurve to
month, week or day (Only these three options for  time interval are available).
The energy  range sets the limits for the photon flux calculation in the XSPEC 
fits. In the "Powerlaw index" entry the user can  specify  the starting  value 
of the index and wheather it should be kept fixed  during spectral fits. These
last two sttings should be modified only in rare cases of a very high 
statistics  (or if you really know what you are doing). 

The "Show lightcurve" button opens up  the QPP plot of the lightcurve. In case
the powerlaw  index  was  free  during  the  lightcurve  extraction, the index
evolution is also plotted. "Save lightcurve" button opens a dialog window 
which allows you to save the lightcurve file in a location different from the
default one (i.e. source directory).

 
    """
        text.insert(tk.END, txt5)
        text.insert(tk.END, "\n")
        text.insert(tk.END, "\n")

        text.insert(
            tk.END,
            "                                                            Back to top\n"
        )
        text.tag_add('back', "%s-0l-12c" % tk.INSERT, "%s-0l-0c" % tk.INSERT)
        text.tag_bind('back', '<Enter>', show_arrow_cursor)
        text.tag_bind('back', '<Leave>', show_tcross_cursor)
        text.tag_config('back', foreground='red', underline=1)
        text.tag_bind('back', '<Button-1>', gototop)

        text.insert(tk.END, "Spectrum Panel\n")
        text.tag_add('tag', "%s-1l" % tk.INSERT, tk.INSERT)
        text.insert(tk.END, "\n")

        txt5 = """
    This panel presents a set of tools to extract and analyse Fermi/LAT energy
spectrum. First,  you need  to extract spectrum and all corresponding response 
files  by  clicking on the "Extract Spectrum" button. You can specify the time
ranges  in  the  "Time Ranges"  window.  The  spectral  files are saved in the 
product directory, shown in the top  line  of the  panel.  After extraction is 
finished  you  have  an option  to  examine the spectrum and background versus 
channels   by   pressing  the   "Plot  spectrum/background" button. When first 
calculated,  spectral  files  are  stored  in a source directory with the file 
names, which can not be changed or modified within  Latspec. To  save spectral
and  response  files in location different from the source directory use "Save 
spectrum" button. "Save spectrum" opens a  save  file  dialog window where you
can  specify  the  location and name of the files for spectral  products to be
saved to. Specifically, when using "Save spectrum" dialog you need to select a
directory where you want your files to be stored and in  the "Save as"  window
you  need  to specify <spectrum_name> string WITHOUT ANY EXTENSIONS. The files
will  then  be  saved   as  <spectrum_name>_src.pha,  <spectrum_name>_bkg.pha,
<spectrum_name>.rsp,etc.

On the  "Xspec"  subpanel the user can perform the full Xspec fit using one of 
three  models:  PowerLaw, LogParabola  and  Power Law with Exponential Cutoff.
The fitting  model can be changed  using  the  dropdown menu. If the source is
identified as a 2FGL catalog source, the model is  preselected  by the catalog
model.  The fit  is performed in the energy range specified by the "Fit Energy 
Range".  Moreover,  one  can  apply any  Xspec  model  or  execute  any  Xspec
command  in  the Xspec prompt, designated by "xspec>".Any Xspec output appears
in the Log window.
    """

        text.insert(tk.END, txt5)

        text.insert(
            tk.END,
            "                                                            Back to top\n"
        )
        text.tag_add('back', "%s-0l-12c" % tk.INSERT, "%s-0l-0c" % tk.INSERT)
        text.tag_bind('back', '<Enter>', show_arrow_cursor)
        text.tag_bind('back', '<Leave>', show_tcross_cursor)
        text.tag_config('back', foreground='red', underline=1)
        text.tag_bind('back', '<Button-1>', gototop)

        text.tag_config('tag', font=bold_font)
        text.tag_config('tag', underline=1)
        text.tag_config('tag', justify=tk.CENTER)

        txt_bot = """
Nikolai Shaposhnikov (UMD/CRESST/GSFC/FSSC)
[email protected]
"""
        text.insert(tk.END, txt_bot)
        text.tag_add('bot', "%s-2l-0c" % tk.INSERT, "%s-0l-0c" % tk.INSERT)
        #        text.tag_config('bot',foreground='green',underline=0)

        button = tk.Button(self.help_top, text="Dismiss", command=self.stop)
        button.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.Y, padx=20)
        text["state"] = tk.DISABLED
class hand_gesture_detector:
    def __init__(self, video_streaming_obj):

        ####################################
        ########GLOBAL VARIABLES############
        ####################################
        global control_command
        control_command = {}
        control_command['ARM_TAKEOFF'] = 0
        control_command['MOVE'] = 1
        control_command['FLYTING_RIGHT'] = 2
        control_command['FLYTING_LEFT'] = 3
        control_command['FLYTING_BACK'] = 4
        control_command['LAND_DISARM'] = 5

        ####################################
        ###########Streaming################
        ####################################
        self.video_streaming_obj = video_streaming_obj
        self.frame = None
        self.streaming_thread = None
        self.stopEvent = threading.Event()

        self.streaming_thread = threading.Thread(target=self.videoLoop,
                                                 args=())
        self.streaming_thread.start()
        ####################################
        ####################################

        ####################################
        ###########Autpilot#################
        ####################################
        self.autopilot_thread = None
        self.autopilot_obj = None
        self.is_connected_to_autopilot = False
        self.autopilot_sending_msgs_stack = []
        self.autopilot_move_x_y_stack = []
        self.autopilot_speed_shift = []
        self.autopilot_log = []

        ####################################
        ####################################

        ####################################
        ########initialize UI window########
        ####################################
        self.root = tk.Tk()

        self.panel = None
        self.image = None

        self.panel = tk.Label(image=self.image)
        self.panel.image = self.image
        self.panel.grid(row=0, column=3, rowspan=3, sticky=tk.NSEW)

        self.ip_lbl = tk.Label(self.root, text='IP',
                               justify=tk.LEFT).grid(row=0,
                                                     column=0,
                                                     sticky=tk.NW,
                                                     padx=5)
        self.port_lbl = tk.Label(self.root, text='Port',
                                 justify=tk.LEFT).grid(row=0,
                                                       column=1,
                                                       sticky=tk.NW)

        self.ip_entry_text = tk.StringVar()
        self.ip_entry = tk.Entry(self.root,
                                 width=10,
                                 textvariable=self.ip_entry_text)
        self.ip_entry_text.set("127.0.0.1")
        self.ip_entry.grid(row=1, column=0, sticky=tk.NW, padx=5)
        self.port_entry_text = tk.StringVar()
        self.port_entry = tk.Entry(self.root,
                                   width=5,
                                   textvariable=self.port_entry_text)
        self.port_entry_text.set("14559")
        self.port_entry.grid(row=1, column=1, sticky=tk.NW)
        self.connect_btn = tk.Button(self.root,
                                     text="Connect",
                                     command=self.connect_to_autopilot).grid(
                                         row=1, column=2, sticky=tk.NW, padx=5)

        self.scrolled_text = ScrolledText(self.root,
                                          wrap=tk.WORD,
                                          width=40,
                                          bg='black')
        self.scrolled_text.grid(row=2, column=0, columnspan=3)
        self.scrolled_text.tag_config('normal', foreground='white')
        self.scrolled_text.tag_config('telemetry', foreground='green')
        self.scrolled_text.tag_config('error', foreground='red')

        # set a callback to handle when the window is closed
        self.root.wm_title("Hand Gestures Detector")
        self.root.wm_protocol("WM_DELETE_WINDOW", self.onClose)
        ####################################
        ####################################

        ####################################
        #########Detection Variables########
        ####################################

        self.log = []

        # max number of hands we want to detect/track
        self.num_hands_detect = 2

        #

        self.prev_first_sample_points_xy = [(0, 0), (0, 0), (0, 0), (0, 0),
                                            (0, 0)]
        self.first_sample_points_xy = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]

        self.prev_second_sample_points_xy = [(0, 0), (0, 0), (0, 0), (0, 0),
                                             (0, 0)]
        self.second_sample_points_xy = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)]

        im_width, im_height = (int(self.video_streaming_obj.get(3)),
                               int(self.video_streaming_obj.get(4)))
        self.start_x = int(im_width)
        self.start_y = int(im_height)

        self.prev_first_hand_shape = -1
        self.prev_second_hand_shape = -1

        self.prev_box_1 = None
        self.prev_box_2 = None

        self.box_1 = None
        self.box_2 = None

        self.first_hand_shape = -1
        self.second_hand_shape = -1

        self.gestures_queue_first = Queue.Queue()
        self.gestures_queue_second = Queue.Queue()

        self.is_connected = False
        self.arm_pattern = [1, 0, 1]
        self.backward_forward_pattern = [1, 0, 1]
        self.score_thresh = 0.7

        self.output_img = np.zeros((700, 1200, 3), dtype=np.uint8)

        self.num_of_frames_without_hands = 0
        self.same_hand_shape_counter = 0
        self.num_of_frames_before_flip_hand_boxes = 0
        self.bg_frame = None

        self.lock_wheel = False
        self.num_of_frames_lock_wheel = 0

        self.is_moving_forward = True
        self.change_moving_counter = 0

        self.arrow_shift = 0

        #ini_magic_re
        for _ in range(3):
            self.gestures_queue_first.put(-1)
            self.gestures_queue_second.put(-1)
        ####################################
        ####################################

    def connect_to_autopilot(self):
        if not self.ip_entry.get() == "" and not self.port_entry.get() == "":
            if self.is_connected_to_autopilot:
                self.scrolled_text.insert(tk.END,
                                          "Already Connected to Vehcile! \n",
                                          'error')
            else:
                self.autopilot_thread = threading.Thread(
                    target=self.handle_autopilot, args=())
                self.autopilot_thread.start()
        else:
            self.scrolled_text.insert(tk.END, "Enter IP:Port \n", 'error')

    def handle_autopilot(self):
        if not self.is_connected_to_autopilot:
            self.autopilot_obj = autopilot()
            self.autopilot_obj.connect(self.ip_entry.get(),
                                       int(self.port_entry.get()))
            if not self.autopilot_obj is None:
                self.is_connected_to_autopilot = True
            #just for test
            # self.is_connected_to_autopilot = True
            # #

        while self.is_connected_to_autopilot:

            incoming_msg = self.autopilot_obj.pop_from_feedback_stack()
            if not incoming_msg is None:
                self.scrolled_text.insert(tk.END, incoming_msg + "\n",
                                          'telemetry')

            if len(self.autopilot_sending_msgs_stack) > 0:
                global control_command
                command = self.autopilot_sending_msgs_stack.pop()
                if command == control_command['ARM_TAKEOFF']:
                    self.autopilot_obj.change_flight_mode('guided')
                    self.autopilot_obj.arm()
                    self.autopilot_obj.takeoff(1)
                elif command == control_command['MOVE']:
                    if len(self.autopilot_move_x_y_stack) > 0:
                        (x, y, z) = self.autopilot_move_x_y_stack.pop()
                        self.autopilot_obj.move(x / 2, y / 2, z / 2, 1)
                        print 'move ', x, y, z
                self.scrolled_text.insert(tk.END,
                                          self.autopilot_log.pop() + "\n",
                                          'normal')

    def onClose(self):
        # set the stop event, cleanup the camera, and allow the rest of
        # the quit process to continue
        print("[INFO] closing...")
        self.stopEvent.set()
        self.video_streaming_obj.release()
        self.root.quit()

    def videoLoop(self):
        im_width, im_height = (int(self.video_streaming_obj.get(3)),
                               int(self.video_streaming_obj.get(4)))

        try:
            while not self.stopEvent.is_set():
                _, image_np = self.video_streaming_obj.read()
                image_np = cv2.flip(image_np, 1)

                # image_np = cv2.flip(image_np, 1)
                try:
                    image_np = cv2.cvtColor(image_np, cv2.COLOR_BGR2RGB)
                except:
                    print("Error converting to RGB")

                boxes, scores, classes = detector_utils.detect_objects(
                    image_np, detection_graph, sess)
                self.image = cv2.cvtColor(self.output_img, cv2.COLOR_BGR2RGB)
                self.image = Image.fromarray(self.image)
                self.image = ImageTk.PhotoImage(self.image)
                self.panel.configure(image=self.image)
                self.panel.image = self.image

                #filter by score
                tmp_scores = []
                tmp_classes = []
                tmp_boxes = []

                for i in range(self.num_hands_detect):
                    if (scores[i] > self.score_thresh):
                        tmp_scores.append(scores[i])
                        tmp_classes.append(classes[i])
                        tmp_boxes.append(boxes[i])

                #filter by score
                filtered_scores = []
                filtered_classes = []
                filtered_boxes = []
                # image_np=detector_utils.draw_left_arrow(image_np)
                for i in range(len(tmp_scores)):
                    redundant = False
                    (left_1, right_1, top_1,
                     bottom_1) = (tmp_boxes[i][1] * im_width,
                                  tmp_boxes[i][3] * im_width,
                                  tmp_boxes[i][0] * im_height,
                                  tmp_boxes[i][2] * im_height)
                    area_1 = (right_1 - left_1) * (bottom_1 - top_1)
                    for j in range(i + 1, len(tmp_scores)):
                        (left_2, right_2, top_2,
                         bottom_2) = (tmp_boxes[j][1] * im_width,
                                      tmp_boxes[j][3] * im_width,
                                      tmp_boxes[j][0] * im_height,
                                      tmp_boxes[j][2] * im_height)
                        area_2 = (right_2 - left_2) * (bottom_2 - top_2)
                        x = max(left_1, left_2)
                        y = max(top_1, top_2)
                        w = min(right_1, right_2) - x
                        h = min(bottom_1, bottom_2) - y
                        if w < 0 or h < 0:
                            continue
                        else:
                            print 'There is intersection'
                            if w * h > 0.8 * area_1:
                                print 'redundant'
                                self.log.insert(0,
                                                "Remove redundant detection!")
                                redundant = True
                                break
                    if not redundant:
                        filtered_scores.append(tmp_scores[i])
                        filtered_classes.append(tmp_classes[i])
                        filtered_boxes.append(tmp_boxes[i])

                ##If No hands appeared for 3 frames, reset the pattern Queues
                if len(filtered_scores) == 0:
                    self.num_of_frames_without_hands += 1
                    print 'No Hands...'
                else:
                    self.num_of_frames_without_hands = 0

                if self.num_of_frames_without_hands > 3:
                    self.gestures_queue_second.queue.clear()
                    self.gestures_queue_first.queue.clear()
                    print 'Reset Patterns...'
                    for _ in range(3):
                        self.gestures_queue_second.put(-1)
                        self.gestures_queue_first.put(-1)

                if self.arrow_shift > 3:
                    self.arrow_shift = 0
                else:
                    self.arrow_shift += 1

                # Lock wheel for 3 frames in case of noise
                if self.lock_wheel and self.num_of_frames_lock_wheel < 3:
                    if len(filtered_scores) == 2 and (
                        (filtered_classes[0] == 6.0
                         and not filtered_classes[1] == 6.0) or
                        (not filtered_classes[0] == 6.0
                         and filtered_classes[1] == 6.0)):
                        print 'LOCK 2 HAND...'
                        self.num_of_frames_lock_wheel += 1
                        if self.num_of_frames_lock_wheel >= 3:
                            self.lock_wheel = False
                            self.num_of_frames_lock_wheel = 0
                        image_np = detector_utils.draw_steering_wheel(
                            image_np, self.first_sample_points_xy[0][1] -
                            self.second_sample_points_xy[0][1])
                        if self.is_moving_forward:
                            cv2.putText(image_np, 'Forward',
                                        (int(image_np.shape[1]) - 65,
                                         int(image_np.shape[0]) - 5),
                                        cv2.FONT_HERSHEY_SIMPLEX, 0.4,
                                        (255, 255, 0))
                        else:
                            cv2.putText(image_np, 'Backward',
                                        (int(image_np.shape[1]) - 65,
                                         int(image_np.shape[0]) - 5),
                                        cv2.FONT_HERSHEY_SIMPLEX, 0.4,
                                        (255, 255, 0))
                        # if self.first_sample_points_xy[0][0]>self.second_sample_points_xy[0][0]:
                        # 	image_np = detector_utils.draw_steering_wheel(image_np,self.first_sample_points_xy[0][1]-self.second_sample_points_xy[0][1])
                        # else:
                        # 	image_np = detector_utils.draw_steering_wheel(image_np,self.second_sample_points_xy[0][1]-self.first_sample_points_xy[0][1])
                    elif len(filtered_scores
                             ) == 1 and filtered_classes[0] == 6.0:
                        image_np = detector_utils.draw_steering_wheel(
                            image_np, 0)
                        print 'LOCK 1 HAND...'
                        self.num_of_frames_lock_wheel += 1
                        if self.num_of_frames_lock_wheel >= 3:
                            self.lock_wheel = False
                            self.num_of_frames_lock_wheel = 0

                if len(filtered_scores) == 1:
                    (left_1, right_1, top_1,
                     bottom_1) = (filtered_boxes[0][1] * im_width,
                                  filtered_boxes[0][3] * im_width,
                                  filtered_boxes[0][0] * im_height,
                                  filtered_boxes[0][2] * im_height)

                    width_1 = right_1 - left_1
                    height_1 = bottom_1 - top_1

                    self.prev_box_1 = self.box_1
                    self.box_1 = filtered_boxes[0]
                    self.prev_first_hand_shape = self.first_hand_shape
                    self.first_hand_shape = filtered_classes[0]

                    self.prev_first_sample_points_xy = self.first_sample_points_xy
                    self.first_sample_points_xy = [
                        (int(left_1 + width_1 / 4), int(top_1 + height_1 / 4)),
                        (int(right_1 - width_1 / 4),
                         int(top_1 + height_1 / 4)),
                        (int(left_1 + width_1 / 4),
                         int(bottom_1 - height_1 / 4)),
                        (int(right_1 - width_1 / 4),
                         int(bottom_1 - height_1 / 4)),
                        (int(right_1 - width_1 / 2),
                         int(bottom_1 - height_1 / 2))
                    ]

                    if not list(self.gestures_queue_first.queue
                                )[2] == detector_utils.is_hand_opened(
                                    filtered_classes[0]):
                        self.gestures_queue_first.get()
                        self.gestures_queue_first.put(
                            detector_utils.is_hand_opened(filtered_classes[0]))
                        self.same_hand_shape_counter = 0
                        print list(self.gestures_queue_first.queue)
                        if detector_utils.check_pattern(
                                self.gestures_queue_first.queue,
                                self.arm_pattern, self.arm_pattern):
                            global control_command
                            self.autopilot_sending_msgs_stack.insert(
                                0, control_command['ARM_TAKEOFF'])
                            self.autopilot_log.insert(0, "ARM Command is Sent")
                            self.is_connected = True
                            print("arm sent")
                    else:
                        self.same_hand_shape_counter += 1

                    if self.same_hand_shape_counter > 4:
                        self.same_hand_shape_counter = 0
                        print 'Reset Patterns because of latency...'
                        self.gestures_queue_first.queue.clear()
                        for j in range(3):
                            self.gestures_queue_first.put(-1)

                    cv2.rectangle(image_np, (int(left_1), int(top_1)),
                                  (int(right_1), int(bottom_1)), (0, 0, 255),
                                  1)
                    cv2.putText(image_np, 'H1',
                                (int(right_1) - 15, int(top_1) - 5),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0))
                    cv2.putText(image_np, str(filtered_classes[0]),
                                (int(left_1) - 5, int(top_1) - 5),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))
                    for k in range(5):
                        cv2.circle(image_np, self.first_sample_points_xy[k], 2,
                                   (0, 0, 255), -1)
                        if not self.prev_first_sample_points_xy[k] == (0, 0):
                            cv2.line(image_np,
                                     self.prev_first_sample_points_xy[k],
                                     self.first_sample_points_xy[k],
                                     (255, 0, 0), 1)

                    self.prev_box_2 = None
                    self.box_2 = None
                    self.prev_second_hand_shape = None
                    self.second_hand_shape = None
                    self.gestures_queue_second.queue.clear()
                    for j in range(3):
                        self.gestures_queue_second.put(-1)

                    self.change_moving_counter = 0
                    # self.prev_second_sample_points_xy = [(0,0),(0,0),(0,0),(0,0),(0,0)]
                    # self.second_sample_points_xy = [(0,0),(0,0),(0,0),(0,0),(0,0)]

                elif len(filtered_scores) == 2:
                    (left_1, right_1, top_1,
                     bottom_1) = (filtered_boxes[0][1] * im_width,
                                  filtered_boxes[0][3] * im_width,
                                  filtered_boxes[0][0] * im_height,
                                  filtered_boxes[0][2] * im_height)

                    width_1 = right_1 - left_1
                    height_1 = bottom_1 - top_1

                    (left_2, right_2, top_2,
                     bottom_2) = (filtered_boxes[1][1] * im_width,
                                  filtered_boxes[1][3] * im_width,
                                  filtered_boxes[1][0] * im_height,
                                  filtered_boxes[1][2] * im_height)

                    width_2 = right_2 - left_2
                    height_2 = bottom_2 - top_2

                    coordinates = [[
                        left_1, right_1, top_1, bottom_1, width_1, height_1
                    ], [left_2, right_2, top_2, bottom_2, width_2, height_2]]

                    left_box_index = 0
                    rigth_box_index = 1
                    if left_1 > left_2:
                        left_box_index = 1
                        rigth_box_index = 0
                    self.prev_box_1 = self.box_1
                    self.box_1 = filtered_boxes[left_box_index]
                    self.prev_first_hand_shape = self.first_hand_shape
                    self.first_hand_shape = filtered_classes[left_box_index]

                    self.prev_first_sample_points_xy = self.first_sample_points_xy
                    # [(int(left_1+width_1/4),int(top_1+height_1/4)),
                    #  (int(right_1-width_1/4),int(top_1+height_1/4)),
                    #  (int(left_1+width_1/4),int(bottom_1-height_1/4)),
                    #  (int(right_1-width_1/4),int(bottom_1-height_1/4)),
                    #  (int(right_1-width_1/2),int(bottom_1-height_1/2))]
                    self.first_sample_points_xy = [
                        (int(coordinates[left_box_index][0] +
                             coordinates[left_box_index][4] / 4),
                         int(coordinates[left_box_index][2] +
                             coordinates[left_box_index][5] / 4)),
                        (int(coordinates[left_box_index][1] -
                             coordinates[left_box_index][4] / 4),
                         int(coordinates[left_box_index][2] +
                             coordinates[left_box_index][5] / 4)),
                        (int(coordinates[left_box_index][0] +
                             coordinates[left_box_index][4] / 4),
                         int(coordinates[left_box_index][3] -
                             coordinates[left_box_index][5] / 4)),
                        (int(coordinates[left_box_index][1] -
                             coordinates[left_box_index][4] / 4),
                         int(coordinates[left_box_index][3] -
                             coordinates[left_box_index][5] / 4)),
                        (int(coordinates[left_box_index][1] -
                             coordinates[left_box_index][4] / 2),
                         int(coordinates[left_box_index][3] -
                             coordinates[left_box_index][5] / 2))
                    ]

                    if not list(self.gestures_queue_first.queue
                                )[2] == detector_utils.is_hand_opened(
                                    filtered_classes[left_box_index]):
                        self.gestures_queue_first.get()
                        self.gestures_queue_first.put(
                            detector_utils.is_hand_opened(
                                filtered_classes[left_box_index]))
                        # print '2 first hand: ',list(self.gestures_queue_first.queue)

                    cv2.rectangle(image_np,
                                  (int(coordinates[left_box_index][0]),
                                   int(coordinates[left_box_index][2])),
                                  (int(coordinates[left_box_index][1]),
                                   int(coordinates[left_box_index][3])),
                                  (0, 0, 255), 1)
                    cv2.putText(image_np, 'H1',
                                (int(coordinates[left_box_index][1]) - 20,
                                 int(coordinates[left_box_index][2]) - 5),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 255, 0))
                    cv2.putText(image_np,
                                str(filtered_classes[left_box_index]),
                                (int(coordinates[left_box_index][0]) - 5,
                                 int(coordinates[left_box_index][2]) - 5),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))

                    self.prev_box_2 = self.box_2
                    self.box_2 = filtered_boxes[rigth_box_index]
                    self.prev_second_hand_shape = self.second_hand_shape
                    self.second_hand_shape = filtered_classes[rigth_box_index]

                    self.prev_second_sample_points_xy = self.second_sample_points_xy
                    self.second_sample_points_xy = [
                        (int(coordinates[rigth_box_index][0] +
                             coordinates[rigth_box_index][4] / 4),
                         int(coordinates[rigth_box_index][2] +
                             coordinates[rigth_box_index][5] / 4)),
                        (int(coordinates[rigth_box_index][1] -
                             coordinates[rigth_box_index][4] / 4),
                         int(coordinates[rigth_box_index][2] +
                             coordinates[rigth_box_index][5] / 4)),
                        (int(coordinates[rigth_box_index][0] +
                             coordinates[rigth_box_index][4] / 4),
                         int(coordinates[rigth_box_index][3] -
                             coordinates[rigth_box_index][5] / 4)),
                        (int(coordinates[rigth_box_index][1] -
                             coordinates[rigth_box_index][4] / 4),
                         int(coordinates[rigth_box_index][3] -
                             coordinates[rigth_box_index][5] / 4)),
                        (int(coordinates[rigth_box_index][1] -
                             coordinates[rigth_box_index][4] / 2),
                         int(coordinates[rigth_box_index][3] -
                             coordinates[rigth_box_index][5] / 2))
                    ]

                    if not list(self.gestures_queue_second.queue
                                )[2] == detector_utils.is_hand_opened(
                                    filtered_classes[rigth_box_index]):
                        self.gestures_queue_second.get()
                        self.gestures_queue_second.put(
                            detector_utils.is_hand_opened(
                                filtered_classes[rigth_box_index]))
                        # print '2 second hand: ',list(self.gestures_queue_second.queue)
                    if filtered_classes[
                            left_box_index] == 3.0 and filtered_classes[
                                left_box_index] == 3.0:
                        self.change_moving_counter += 1
                    else:
                        self.change_moving_counter = 0

                    if self.change_moving_counter >= 6:
                        self.change_moving_counter = 0
                        if self.is_moving_forward:
                            self.is_moving_forward = False
                        else:
                            self.is_moving_forward = True

                    #HERE
                    '''
					if  list(self.gestures_queue_first.queue)[2] == detector_utils.is_hand_opened(filtered_classes[left_box_index]) and  list(self.gestures_queue_second.queue)[2] == detector_utils.is_hand_opened(filtered_classes[rigth_box_index]):
							self.gestures_queue_first.get()
							self.gestures_queue_first.put(detector_utils.is_hand_opened(filtered_classes[left_box_index]))

							self.gestures_queue_second.get()
							self.gestures_queue_second.put(detector_utils.is_hand_opened(filtered_classes[rigth_box_index]))

							self.same_hand_shape_counter=0
							print 'left: ',list(self.gestures_queue_first.queue)
							print 'right: ',list(self.gestures_queue_second.queue)
							if detector_utils.check_pattern(self.gestures_queue_first.queue,self.arm_pattern,self.arm_pattern) and detector_utils.check_pattern(self.gestures_queue_second.queue,self.arm_pattern,self.arm_pattern):
								global control_command
								self.autopilot_sending_msgs_stack.insert(0,control_command['MOVE'])
								self.autopilot_log.insert(0,"MOVE Command is Sent")
								print("MOVE sent")
					else:
						self.same_hand_shape_counter+=1
						print list(self.gestures_queue_first.queue),list(self.gestures_queue_second.queue),detector_utils.is_hand_opened(filtered_classes[rigth_box_index]),detector_utils.is_hand_opened(filtered_classes[left_box_index])

					if self.same_hand_shape_counter >4:
						self.same_hand_shape_counter=0
						print 'Reset Patterns because of latency...'
						self.gestures_queue_first.queue.clear()
						self.gestures_queue_second.queue.clear()
						for j in range(3):
							self.gestures_queue_first.put(-1)
							self.gestures_queue_second.put(-1)
					'''

                    cv2.rectangle(image_np,
                                  (int(coordinates[rigth_box_index][0]),
                                   int(coordinates[rigth_box_index][2])),
                                  (int(coordinates[rigth_box_index][1]),
                                   int(coordinates[rigth_box_index][3])),
                                  (255, 0, 0), 1)
                    cv2.putText(image_np, 'H2',
                                (int(coordinates[rigth_box_index][1]) - 20,
                                 int(coordinates[rigth_box_index][2]) - 5),
                                cv2.FONT_HERSHEY_SIMPLEX, 0.4, (255, 0, 0))
                    cv2.putText(image_np,
                                str(filtered_classes[rigth_box_index]),
                                (int(coordinates[rigth_box_index][0]) - 5,
                                 int(coordinates[rigth_box_index][2]) - 5),
                                cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0))

                    #show moving direction
                    forward = 1
                    if self.is_moving_forward:
                        cv2.putText(image_np, 'Forward',
                                    (int(image_np.shape[1]) - 65,
                                     int(image_np.shape[0]) - 5),
                                    cv2.FONT_HERSHEY_SIMPLEX, 0.4,
                                    (255, 255, 0))
                        self.log.insert(0, "Direction Changed to Forward!")
                    else:
                        forward = -1
                        cv2.putText(image_np, 'Backward',
                                    (int(image_np.shape[1]) - 65,
                                     int(image_np.shape[0]) - 5),
                                    cv2.FONT_HERSHEY_SIMPLEX, 0.4,
                                    (255, 255, 0))
                        self.log.insert(0, "Direction Changed to Backward!")

                    #show Wheel when shapes: close close
                    global control_command
                    if not detector_utils.is_hand_opened(
                            self.first_hand_shape
                    ) and not detector_utils.is_hand_opened(
                            self.second_hand_shape):
                        self.lock_wheel = True
                        self.num_of_frames_lock_wheel = 0
                        shift = self.first_sample_points_xy[0][
                            1] - self.second_sample_points_xy[0][1]

                        if shift < -75:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 0.5, 2, 0))
                        elif shift > -75 and shift < -50:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 1, 1.5, 0))
                        elif shift > -50 and shift < -25:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 1.5, 1, 0))
                        elif shift > -25 and shift < -15:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 2, 0.5, 0))
                        elif shift > -15 and shift < 15:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 2, 0, 0))
                        elif shift > 15 and shift < 25:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 2, -0.5, 0))
                        elif shift > 25 and shift < 50:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 1.5, -1, 0))
                        elif shift > 50 and shift < 75:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 1, -1.5, 0))
                        elif shift > 75:
                            self.autopilot_speed_shift.insert(
                                0, (forward * 0.5, -2, 0))

                        if len(self.autopilot_speed_shift) > 0:
                            while len(self.autopilot_move_x_y_stack) > 3:
                                self.autopilot_sending_msgs_stack.pop()
                                self.autopilot_move_x_y_stack.pop()
                                self.autopilot_log.pop()
                            self.autopilot_sending_msgs_stack.insert(
                                0, control_command['MOVE'])
                            self.autopilot_move_x_y_stack.insert(
                                0, self.autopilot_speed_shift[0])
                            self.autopilot_log.insert(
                                0, "MOVE Command is Sent X " +
                                str(self.autopilot_speed_shift[0][0]) + " Y " +
                                str(self.autopilot_speed_shift[0][1]) + " Z " +
                                str(self.autopilot_speed_shift[0][2]))
                            # print("MOVE Command is Sent X "+str(self.autopilot_speed_shift[0][0])+" Y "+str(self.autopilot_speed_shift[0][1]))
                        image_np = detector_utils.draw_steering_wheel(
                            image_np, self.first_sample_points_xy[0][1] -
                            self.second_sample_points_xy[0][1])

                        # if self.first_sample_points_xy[0][0]>self.second_sample_points_xy[0][0]:
                        # 	image_np = detector_utils.draw_steering_wheel(image_np,self.first_sample_points_xy[0][1]-self.second_sample_points_xy[0][1])
                        # else:
                        # 	image_np = detector_utils.draw_steering_wheel(image_np,self.second_sample_points_xy[0][1]-self.first_sample_points_xy[0][1])

                    #show arrow when shapes: open close - Move Right - Left
                    if detector_utils.is_hand_opened(
                            self.first_hand_shape
                    ) == 1 and detector_utils.is_hand_opened(
                            self.second_hand_shape) == 0:
                        self.lock_wheel = False
                        self.autopilot_speed_shift.insert(0, (0, 2, 0))
                        while len(self.autopilot_move_x_y_stack) > 3:
                            self.autopilot_sending_msgs_stack.pop()
                            self.autopilot_move_x_y_stack.pop()
                            self.autopilot_log.pop()
                        self.autopilot_sending_msgs_stack.insert(
                            0, control_command['MOVE'])
                        self.autopilot_move_x_y_stack.insert(
                            0, self.autopilot_speed_shift[0])
                        self.autopilot_log.insert(
                            0, "MOVE RIGHT Command is Sent X " +
                            str(self.autopilot_speed_shift[0][0]) + " Y " +
                            str(self.autopilot_speed_shift[0][1]) + " Z " +
                            str(self.autopilot_speed_shift[0][2]))
                        image_np = detector_utils.draw_right_arrow(
                            image_np, self.arrow_shift)
                    elif detector_utils.is_hand_opened(
                            self.first_hand_shape
                    ) == 0 and detector_utils.is_hand_opened(
                            self.second_hand_shape) == 1:
                        self.lock_wheel = False
                        self.autopilot_speed_shift.insert(0, (0, -2, 0))
                        while len(self.autopilot_move_x_y_stack) > 3:
                            self.autopilot_sending_msgs_stack.pop()
                            self.autopilot_move_x_y_stack.pop()
                            self.autopilot_log.pop()
                        self.autopilot_sending_msgs_stack.insert(
                            0, control_command['MOVE'])
                        self.autopilot_move_x_y_stack.insert(
                            0, self.autopilot_speed_shift[0])
                        self.autopilot_log.insert(
                            0, "MOVE LEFT Command is Sent X " +
                            str(self.autopilot_speed_shift[0][0]) + " Y " +
                            str(self.autopilot_speed_shift[0][1]) + " Z " +
                            str(self.autopilot_speed_shift[0][2]))
                        image_np = detector_utils.draw_left_arrow(
                            image_np, self.arrow_shift)
                    elif detector_utils.is_hand_opened(
                            self.first_hand_shape
                    ) == 0 and detector_utils.is_hand_opened(
                            self.second_hand_shape) == -1:
                        self.lock_wheel = False
                        self.autopilot_speed_shift.insert(0, (0, 0, 1))
                        while len(self.autopilot_move_x_y_stack) > 3:
                            self.autopilot_sending_msgs_stack.pop()
                            self.autopilot_move_x_y_stack.pop()
                            self.autopilot_log.pop()
                        self.autopilot_sending_msgs_stack.insert(
                            0, control_command['MOVE'])
                        self.autopilot_move_x_y_stack.insert(
                            0, self.autopilot_speed_shift[0])
                        self.autopilot_log.insert(
                            0, "MOVE DOWN Command is Sent X " +
                            str(self.autopilot_speed_shift[0][0]) + " Y " +
                            str(self.autopilot_speed_shift[0][1]) + " Z " +
                            str(self.autopilot_speed_shift[0][2]))
                        image_np = detector_utils.draw_down_arrow(
                            image_np, self.arrow_shift)
                    elif detector_utils.is_hand_opened(
                            self.first_hand_shape
                    ) == -1 and detector_utils.is_hand_opened(
                            self.second_hand_shape) == 0:
                        self.lock_wheel = False
                        self.autopilot_speed_shift.insert(0, (0, 0, -1))
                        while len(self.autopilot_move_x_y_stack) > 3:
                            self.autopilot_sending_msgs_stack.pop()
                            self.autopilot_move_x_y_stack.pop()
                            self.autopilot_log.pop()
                        self.autopilot_sending_msgs_stack.insert(
                            0, control_command['MOVE'])
                        self.autopilot_move_x_y_stack.insert(
                            0, self.autopilot_speed_shift[0])
                        self.autopilot_log.insert(
                            0, "MOVE UP Command is Sent X " +
                            str(self.autopilot_speed_shift[0][0]) + " Y " +
                            str(self.autopilot_speed_shift[0][1]) + " Z " +
                            str(self.autopilot_speed_shift[0][2]))
                        image_np = detector_utils.draw_up_arrow(
                            image_np, self.arrow_shift)
                    elif detector_utils.is_hand_opened(
                            self.first_hand_shape
                    ) == 1 and detector_utils.is_hand_opened(
                            self.second_hand_shape) == 1:
                        # Clear movement
                        self.lock_wheel = False
                        self.autopilot_speed_shift.insert(0, (0, 0, 0))
                        while len(self.autopilot_move_x_y_stack) > 3:
                            self.autopilot_sending_msgs_stack.pop()
                            self.autopilot_move_x_y_stack.pop()
                            self.autopilot_log.pop()
                        self.autopilot_sending_msgs_stack.insert(
                            0, control_command['MOVE'])
                        self.autopilot_move_x_y_stack.insert(
                            0, self.autopilot_speed_shift[0])
                        self.autopilot_log.insert(
                            0, "PAUSE MOVEMENT Command is Sent X " +
                            str(self.autopilot_speed_shift[0][0]) + " Y " +
                            str(self.autopilot_speed_shift[0][1]) + " Z " +
                            str(self.autopilot_speed_shift[0][2]))

                    #show sample points for each detected hand
                    for k in range(5):
                        cv2.circle(image_np, self.first_sample_points_xy[k], 2,
                                   (0, 0, 255), -1)
                        if not self.prev_first_sample_points_xy[k] == (0, 0):
                            cv2.line(image_np,
                                     self.prev_first_sample_points_xy[k],
                                     self.first_sample_points_xy[k],
                                     (255, 0, 0), 1)

                        cv2.circle(image_np, self.second_sample_points_xy[k],
                                   2, (0, 0, 255), -1)
                        if not self.prev_second_sample_points_xy[k] == (0, 0):
                            cv2.line(image_np,
                                     self.prev_second_sample_points_xy[k],
                                     self.second_sample_points_xy[k],
                                     (255, 0, 0), 1)
                # else:
                # 	print 'No HANDS *_*', len(filtered_boxes)

                # image_np = detector_utils.draw_steering_wheel(image_np,50)
                image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR)
                self.output_img = image_np  #[0:image_np.shape[0],0:image_np.shape[1],:]=image_np
                # now = datetime.datetime.now()
                # cv2.imwrite('/Users/Soubhi/Desktop/results/'+str(now.second)+'.png',image_np)

        except RuntimeError, e:
            print("[INFO] caught a RuntimeError", str(e))
Пример #21
0
    def confirm_change(self, old_line, new_line, old_tuple=(), new_tuple=(), filepath=""):
        self.confirm_frame = Tkinter.Toplevel(self.parent_frame, padx=10, pady=10)
        # self.confirm_frame.grid(padx=10,pady=10)

        self.confirm_frame.protocol("WM_DELETE_WINDOW", self.confirm_decline)

        # set screen position...
        ##x = config.get('dialog_x', (self.parent_frame.winfo_rootx() + 50))
        ##y = config.get('dialog_y', (self.parent_frame.winfo_rooty() + 50))
        x = self.parent_frame.winfo_rootx() + 50
        y = self.parent_frame.winfo_rooty() + 50
        if x and y:
            self.confirm_frame.geometry("+%s+%s" % (x, y))

        # bind enter to ok and escape to cancel buttons...
        self.confirm_frame.bind("<Return>", self.confirm_accept)
        self.confirm_frame.bind("<Escape>", self.confirm_decline)
        self.confirm_frame.bind("<Configure>", self.save_pos)
        # make the new dialog a part of the parent...
        self.confirm_frame.transient(self.parent_frame)
        # focus onto the dialog...
        self.confirm_frame.focus_set()

        label = Tkinter.Label(self.confirm_frame, text=filepath)
        label.pack()

        label = Tkinter.Label(self.confirm_frame, text="Change:")
        # label.grid(row=row_i, column=0, sticky=W)
        label.pack()

        # entry = Tkinter.Text(self.confirm_frame, width=75, height=5)
        # entry = ScrolledText(self.confirm_frame, width=75, height=5)
        entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3)
        entry.insert(Tkinter.INSERT, old_line.encode("utf-8"))
        # highlight the text to be changed...
        if len(old_tuple) == 2:
            entry.tag_add("found", "1.%s" % (old_tuple[0]), "1.%s+%sc" % (old_tuple[0], old_tuple[1] - old_tuple[0]))
            entry.tag_config("found", foreground="red")

        entry.config(state=DISABLED)
        entry.pack(fill=BOTH, expand=Y)

        label = Tkinter.Label(self.confirm_frame, text="To:")
        label.pack()

        self.new_entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3)
        self.new_entry.insert(Tkinter.INSERT, new_line.encode("utf-8"))
        # highlight the text to be changed...
        if len(new_tuple) == 2:
            self.new_entry.tag_add(
                "found", "1.%s" % (new_tuple[0]), "1.%s+%sc" % (new_tuple[0], new_tuple[1] - new_tuple[0])
            )
            self.new_entry.tag_config("found", foreground="red")

        self.new_entry.config(state=DISABLED)
        self.new_entry.pack(fill=BOTH, expand=Y)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes", command=self.confirm_accept, default=ACTIVE)
        # btnDisplay.grid(row=row_i, column=0)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="No", command=self.confirm_decline)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Cancel", command=self.confirm_cancel)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes to All", command=self.confirm_silence)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        self.confirm_frame.update()
        try:
            self.parent_frame.wait_window(self.confirm_frame)
        except Tkinter.TclError:
            # sometimes the wait_window fails, I'm not sure why, but it seems to be
            # safe to just ignore it *shrug*
            pass

        self.confirm_frame = None
Пример #22
0
class Dialog(ui.Dialog):
    def __init__(self, frame=None):
        self.parent_frame = frame  # set the parent frame
        self.confirm_frame = None
        self.make_change = False
        self.new_line = u""
        self.status_text = u""
        self.make_silent = False
        self.cancel = False

        # set screen position...
        x = 0
        y = 0
        ##x = config.get('status_x',0)
        ##y = config.get('status_y',0)
        ##if x and y:
        ##    self.parent_frame.geometry("+%d+%d" % (int(x),int(y)))

        # create a status message widget and bind it to the parent...
        # self.status_text = ScrolledText(self.parent_frame, height=20, width=80, state=DISABLED)
        # self.status_text.pack()
        self.status_text = ScrolledText(self.parent_frame, wrap=WORD, pady=2, padx=3, state=DISABLED)
        self.status_text.pack(fill=BOTH, expand=Y)
        self.parent_frame.protocol("WM_DELETE_WINDOW", self.destroy)
        self.parent_frame.bind("<Escape>", self.destroy)
        self.parent_frame.bind("<Configure>", self.save_pos)
        self.status_text.update()

    def confirm_change(self, old_line, new_line, old_tuple=(), new_tuple=(), filepath=""):
        self.confirm_frame = Tkinter.Toplevel(self.parent_frame, padx=10, pady=10)
        # self.confirm_frame.grid(padx=10,pady=10)

        self.confirm_frame.protocol("WM_DELETE_WINDOW", self.confirm_decline)

        # set screen position...
        ##x = config.get('dialog_x', (self.parent_frame.winfo_rootx() + 50))
        ##y = config.get('dialog_y', (self.parent_frame.winfo_rooty() + 50))
        x = self.parent_frame.winfo_rootx() + 50
        y = self.parent_frame.winfo_rooty() + 50
        if x and y:
            self.confirm_frame.geometry("+%s+%s" % (x, y))

        # bind enter to ok and escape to cancel buttons...
        self.confirm_frame.bind("<Return>", self.confirm_accept)
        self.confirm_frame.bind("<Escape>", self.confirm_decline)
        self.confirm_frame.bind("<Configure>", self.save_pos)
        # make the new dialog a part of the parent...
        self.confirm_frame.transient(self.parent_frame)
        # focus onto the dialog...
        self.confirm_frame.focus_set()

        label = Tkinter.Label(self.confirm_frame, text=filepath)
        label.pack()

        label = Tkinter.Label(self.confirm_frame, text="Change:")
        # label.grid(row=row_i, column=0, sticky=W)
        label.pack()

        # entry = Tkinter.Text(self.confirm_frame, width=75, height=5)
        # entry = ScrolledText(self.confirm_frame, width=75, height=5)
        entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3)
        entry.insert(Tkinter.INSERT, old_line.encode("utf-8"))
        # highlight the text to be changed...
        if len(old_tuple) == 2:
            entry.tag_add("found", "1.%s" % (old_tuple[0]), "1.%s+%sc" % (old_tuple[0], old_tuple[1] - old_tuple[0]))
            entry.tag_config("found", foreground="red")

        entry.config(state=DISABLED)
        entry.pack(fill=BOTH, expand=Y)

        label = Tkinter.Label(self.confirm_frame, text="To:")
        label.pack()

        self.new_entry = ScrolledText(self.confirm_frame, height=5, wrap=WORD, pady=2, padx=3)
        self.new_entry.insert(Tkinter.INSERT, new_line.encode("utf-8"))
        # highlight the text to be changed...
        if len(new_tuple) == 2:
            self.new_entry.tag_add(
                "found", "1.%s" % (new_tuple[0]), "1.%s+%sc" % (new_tuple[0], new_tuple[1] - new_tuple[0])
            )
            self.new_entry.tag_config("found", foreground="red")

        self.new_entry.config(state=DISABLED)
        self.new_entry.pack(fill=BOTH, expand=Y)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes", command=self.confirm_accept, default=ACTIVE)
        # btnDisplay.grid(row=row_i, column=0)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="No", command=self.confirm_decline)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Cancel", command=self.confirm_cancel)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        btnDisplay = Tkinter.Button(self.confirm_frame, text="Yes to All", command=self.confirm_silence)
        # btnDisplay.grid(row=row_i, column=1)
        btnDisplay.pack(side=LEFT, padx=5, pady=5)

        self.confirm_frame.update()
        try:
            self.parent_frame.wait_window(self.confirm_frame)
        except Tkinter.TclError:
            # sometimes the wait_window fails, I'm not sure why, but it seems to be
            # safe to just ignore it *shrug*
            pass

        self.confirm_frame = None

    def confirm_silence(self):
        self.make_change = True
        self.make_silent = True
        self.clean_up()

    def confirm_cancel(self):
        self.make_change = False
        self.cancel = True
        self.clean_up()

    def confirm_accept(self):
        # self.new_line = self.new_entry.get(1.0, END)
        self.make_change = True
        self.clean_up()

    def confirm_decline(self):
        self.make_change = False
        self.clean_up()

    def clean_up(self, event=None):
        self.save_pos()
        # print self.screen_pos_x,self.screen_pos_y
        self.parent_frame.focus_set()
        self.confirm_frame.destroy()

    def destroy(self, event=None):
        self.parent_frame.destroy()

    def save_pos(self, event=None):
        return
        ## save the screen position of the dialog box
        # if self.confirm_frame:
        # try:
        # config.add('dialog_x',(self.confirm_frame.winfo_rootx() - 4))
        # config.add('dialog_y',(self.confirm_frame.winfo_rooty() - 30))
        # except:
        # pass

        ## save the status box's position
        # if self.parent_frame:
        # try:
        # config.add('status_x',self.parent_frame.winfo_rootx() - 4)
        # config.add('status_y',self.parent_frame.winfo_rooty() - 30)
        # except:
        # pass

    def update(self, msg):
        # if the window no longer exists, its text can't be updated
        try:
            self.status_text.config(state=NORMAL)
            # Add the new message
            self.status_text.insert(END, msg.encode("utf-8") + os.linesep)
            # Scroll down to the bottom again
            self.status_text.see(END)
            # Make the display uneditable
            self.status_text.config(state=DISABLED)
            self.status_text.update()
        except:
            pass
Пример #23
0
class Interactive(object):
    def __init__(self):
        self.printQueue = Queue()
        # Tkinter components:
        self.root = Tk()
        self.root.title = "PGF API App"
        self.text_box = ScrolledText(self.root)
        self.runPrintQueue = True
        self.is_running = False
        self.prompt_var = StringVar()
        self.user_input = StringVar()
        self.of = RediOrderFactory()
        self.google_sheet = None

    def gui_start(self):
        printer_thread = Thread(target=self.queue_printer)
        printer_thread.daemon = True
        printer_thread.start()
        # start printer_thread

        self.text_box.pack()
        self.text_box.config(state=DISABLED)

        user_prompt_entry = Entry(self.root, textvariable=self.prompt_var)
        user_prompt_entry.pack(fill=BOTH)

        entry_var = StringVar()
        entry_box = Entry(self.root, textvariable=entry_var)

        def enter_pressed(event):
            print event
            self.user_input = entry_box.get()

            self.print_user_input(self.user_input)
            request_thread = Thread(target=self.process_user_input,
                                    args=[entry_box.get()])
            # self.process_user_input(entry_box.get())
            request_thread.start()
            entry_box.delete(0, 'end')

        entry_box.bind("<Return>", enter_pressed)
        entry_box.pack(fill=BOTH)
        entry_box.focus_set()

        self.user_input.set('')

        mainloop()
        self.runPrintQueue = False

    def queue_printer(self):
        while True:
            item = self.printQueue.get()

            self.text_box.config(state=NORMAL)
            self.text_box.insert(END, item)
            if isinstance(item, basestring):
                self.text_box.insert(END, '\n')
            if isinstance(item, ListType):
                self.text_box.insert(END, '\n')
            self.text_box.config(state=DISABLED)
            self.text_box.see('end')
            if not self.runPrintQueue:
                break
            time.sleep(.1)
            self.printQueue.task_done()

    def print_user_input(self, item):
        self.text_box.config(state=NORMAL)
        self.text_box.tag_config("b", foreground="blue")
        self.text_box.insert(END, item, "b")
        self.text_box.insert(END, '\n')
        self.text_box.config(state=DISABLED)
        self.text_box.see('end')

    def print2(self, txt):
        print txt
        self.printQueue.put(txt)

    def process_user_input(self, ui):
        # build this one function at a time
        if ui[:4].upper() == 'ECHO':
            self.print2(ui[4:])
            self.prompt_var.set(ui[4:])
        elif ui.upper() == 'QUIT' or ui.upper() == 'Q':
            self.print2('Breaking out of interactive.')
            sys.stdout.flush()
            self.root.quit()
            return -1
        elif ui.upper() == 'LOAD SHEET':
            self.print2('Called Load Sheet')
            try:
                self.google_sheet = gs.GoogleSheetDailyTradingProcedure()

                self.print2('wait a moment . . . ')
                sys.stdout.flush()
                self.google_sheet.load_sheet()
                self.print2('sheet loaded')

            except E:
                self.print2('problem loading sheet' + E)

        elif ui.upper() == 'PRINT SHEET':
            if self.google_sheet:
                for row in self.google_sheet.sheet:
                    self.print2(row)

            else:
                self.print2('Load sheet first. (cmd = load sheet)')

        elif ui.upper()[:10] == 'SUBMIT ROW':
            row = int(ui.split(' ')[2]) - 1

            self.submit_row(row)
            # submit_row_thread = Thread(target=self.submit_row,args=[row])
            # submit_row_thread.start()
        elif ui.upper() == 'SUBMIT ALL':
            if self.google_sheet.sheet:
                i = -1
                for _ in self.google_sheet.sheet:
                    i += 1
                    if i < 2:
                        continue
                    a = self.submit_row(i)
                    if a == 'b':
                        break
            else:
                pass
        elif ui.upper() == 'LOAD ADRS':
            self.google_sheet = gs.GoogleSheetDailyTradingProcedure()
            sheet_id = '1Z3POIK8N5Vi_CsF_MDLszrJeNviBwrU9BuVFC8h-xgQ'
            worksheet_range = 'ADRs Test!A1:F'
            self.print2('wait a moment')
            sys.stdout.flush()
            self.google_sheet.load_sheet(sheet_id, worksheet_range)
            self.print2('adrs loaded')
        elif ui.upper()[:14] == 'SUBMIT ADR ROW':
            r = int(ui.split(' ')[3])
            self.submit_our_adr_row(r)
            self.print2('submit adr row')
        elif ui.upper() == 'SUBMIT ALL ADRS':
            if self.google_sheet.sheet:
                i = -1
                for _ in self.google_sheet.sheet:
                    i += 1
                    if i < 2:
                        continue
                    a = self.submit_our_adr_row(i)

                    if a == 'b':
                        break
            else:
                pass
            self.print2('submit adrs')
        elif ui.upper() == 'SUBMIT ALL MOCS':
            if self.google_sheet.sheet:
                i = -1
                for _ in self.google_sheet.sheet:
                    i += 1
                    if i < 2:
                        continue
                    a = self.submit_our_moc_row(i)
                    if a == 'b':
                        break
            else:
                pass
        elif ui.upper()[:14] == 'SUBMIT MOC ROW':
            r = int(ui.split(' ')[3])
            self.submit_our_moc_row(r)
            self.print2('submit adr row')
        elif ui.upper()[:8] == 'STOP ROW':
            stop_tokens = ui.split(' ')
            row_num = int(stop_tokens[2]) - 1
            row = self.google_sheet.sheet[row_num]
            if len(stop_tokens) == 4:
                quantity = int(stop_tokens[3])
            else:
                quantity = int(row[4])
            side = 'sell' if (row[3].upper() == 'LONG' or row[3].upper()
                              == 'BUY' or row[3].upper() == 'B') else 'buy'
            if side == 'sell':
                quantity *= -1
            symbol = row[2].split()[0].upper()
            stop_price = 0
            if len(row) >= 13:
                stop_price = round(float(row[12]), 2)
            account = row[1].upper()
            if side == 'sell':
                stop_limit = round(stop_price * .99, 2)
            else:
                stop_limit = round(stop_price * 1.01, 2)
            self.of.generate_stop_limit_order(quantity, symbol, stop_price,
                                              stop_limit, account)
        elif ui.upper()[:9] == 'PRINT ROW':
            if self.google_sheet:
                tokens = ui.split(' ')
                self.print2(self.google_sheet.sheet[int(tokens[2]) - 1])
            else:
                self.print2('Load sheet first. (cmd = load sheet)')
        else:
            if ui != 'y' and ui != 'n' and ui != 'b':
                self.print2('Command not understood.')

    def submit_row(self, r, confirm=True):
        try:
            if self.google_sheet:
                row = self.google_sheet.sheet[r]
                self.print2(row)
                sys.stdout.flush()

                account = row[1].upper()
                symbol = row[2].split()[0].upper()
                if symbol == '':
                    return
                if row[4] == '':
                    self.print2(
                        "Row doesn't have quantity. Enter quantity and reload sheet."
                    )
                    sys.stdout.flush()
                    return
                quantity = int(row[4])
                side = 'buy' if (row[3].upper() == 'LONG' or row[3].upper()
                                 == 'BUY' or row[3].upper() == 'B') else 'sell'
                if side == 'sell':
                    quantity *= -1
                o_type = None
                if len(row) >= 7:
                    o_type = row[6].upper()
                price = 0
                if len(row) >= 8:
                    if row[7] == '':
                        price = 0
                    else:
                        price = float(
                            row[7][1:]) if row[7][0] == '$' else float(row[7])
                trade_date = None
                if len(row) >= 9:
                    trade_date = row[8]

                if str(datetime.datetime.now())[:10] != trade_date:
                    self.print2('Date is not today')
                    sys.stdout.flush()
                    return

                order_string = '{} {} {} {} {} in {}'.format(
                    side, abs(quantity), symbol, price, o_type, account)
                if confirm:
                    confirm_msg = '{}? (y/n/b)'.format(order_string)

                    self.user_input = ''
                    self.prompt_var.set(confirm_msg)
                    while self.user_input == '':
                        time.sleep(.1)
                    inp = self.user_input
                    self.prompt_var.set('')
                else:
                    inp = 'y'

                if inp == 'y':
                    o = False
                    if o_type == 'MOO':
                        o = self.of.generate_opg_market_order(
                            quantity, symbol, account)
                    elif o_type == 'LOO':
                        o = self.of.generate_opg_limit_order(
                            quantity, symbol, price, account)
                    elif o_type == 'LOC':
                        o = self.of.generate_loc_order(quantity, symbol, price,
                                                       account)
                    elif o_type == 'MOC':
                        o = self.of.generate_moc_order(quantity, symbol,
                                                       account)
                    elif o_type == 'LIMIT' or o_type == 'LMT':
                        o = self.of.generate_limit_order(
                            quantity, symbol, price, account)
                    time.sleep(.05)
                    if o:
                        return '1'
                    else:
                        return '0'
                elif inp == 'b':
                    return 'b'  # user requested break
                else:
                    return inp
            else:
                self.print2('Load sheet first. (cmd = load sheet)')
                sys.stdout.flush()
                return 'b'
        except Exception as e:
            self.print2('row {} failed to submit: {}'.format(r + 1, e))
            sys.stdout.flush()

    def submit_our_adr_row(self, r, confirm=False):

        try:
            if self.google_sheet:
                row = self.google_sheet.sheet[r - 1]
                self.print2(row)
                sys.stdout.flush()

                symbol = row[1].split()[0].upper()
                if symbol == '':
                    return
                if row[3] == '':
                    self.print2(
                        "Row doesn't have quantity. Enter quantity and reload sheet."
                    )
                    sys.stdout.flush()
                    return
                quantity = int(row[3])
                if row[2] == '':
                    return
                side = 'buy' if (row[2].upper() == 'LONG' or row[2].upper()
                                 == 'BUY' or row[2].upper() == 'B') else 'sell'
                if side == 'sell':
                    quantity *= -1
                order_type = None
                if len(row) >= 6:
                    order_type = row[5].upper()
                price = 0
                if len(row) >= 5:
                    if row[4] == '':
                        price = 0
                    else:
                        price = float(
                            row[4][1:]) if row[4][0] == '$' else float(row[4])
                trade_date = None
                if len(row) >= 1:
                    trade_date = row[0]

                if str(datetime.datetime.now())[:10] != trade_date:
                    self.print2('Date is not today')
                    sys.stdout.flush()
                    return

                order_string = '{} {} {} {} {}'.format(side, abs(quantity),
                                                       symbol, price,
                                                       order_type)
                if confirm:
                    sys.stdout.write('{} {} {} {} {}? (y/n/b)'.format(
                        side, abs(quantity), symbol, price, order_type))
                    sys.stdout.flush()
                    inp = raw_input()
                else:
                    inp = 'y'
                if inp == 'y':
                    o = 0
                    if order_type == 'MOO':
                        o = self.of.generate_opg_market_order(quantity, symbol)
                    elif order_type == 'LOO':
                        o = self.of.generate_opg_limit_order(
                            quantity, symbol, price)
                    elif order_type == 'LOC':
                        o = self.of.generate_loc_order(quantity, symbol, price)
                    elif order_type == 'MOC':
                        o = self.of.generate_moc_order(quantity, symbol)
                    elif order_type == 'LIMIT' or order_type == 'LMT':
                        o = self.of.generate_limit_order(
                            quantity, symbol, price)
                    if o:
                        return '1'
                    else:
                        return '0'
                if inp == 'b':
                    return 'b'
                else:
                    self.print2('order not submitted: {}'.format(order_string))
                    sys.stdout.flush()
                return ''
            else:
                self.print2('Load sheet first. (cmd = load sheet)')
                sys.stdout.flush()
                return 'b'
        except Exception as e:
            self.print2('row {} failed to submit: {}'.format(r + 1, e))
            sys.stdout.flush()

    def submit_our_moc_row(self, r, confirm=False):

        try:
            if self.google_sheet:
                row = self.google_sheet.sheet[r - 1]
                self.print2(row)
                sys.stdout.flush()

                symbol = row[1].split()[0].upper()
                if symbol == '':
                    return
                if row[3] == '':
                    self.print2(
                        "Row doesn't have quantity. Enter quantity and reload sheet."
                    )
                    sys.stdout.flush()
                    return
                quantity = int(row[3])
                if row[2] == '':
                    return
                side = 'sell' if (row[2].upper() == 'LONG' or row[2].upper()
                                  == 'BUY' or row[2].upper() == 'B') else 'buy'
                if side == 'sell':
                    quantity *= -1
                order_type = 'MOC'
                price = 0
                order_string = '{} {} {} {} {}'.format(side, abs(quantity),
                                                       symbol, price,
                                                       order_type)
                if confirm:
                    sys.stdout.write('{} {} {} {} {}? (y/n/b)'.format(
                        side, abs(quantity), symbol, price, order_type))
                    sys.stdout.flush()
                    inp = raw_input()
                else:
                    inp = 'y'

                if inp == 'y':
                    o = 0
                    if order_type == 'MOC':
                        o = self.of.generate_moc_order(quantity, symbol)
                    time.sleep(.05)
                    if o:
                        return '1'
                    else:
                        return '0'
                if inp == 'b':
                    return 'b'
                else:
                    self.print2('order not submitted: {}'.format(order_string))
                    sys.stdout.flush()
                return ''
            else:
                self.print2('Load sheet first. (cmd = load sheet)')
                sys.stdout.flush()
                return 'b'
        except Exception as e:
            self.print2('row {} failed to submit: {}'.format(r + 1, e))
            sys.stdout.flush()
Пример #24
0
    ##创建需要的几个元素
    # text_msglist作为对话信息展示区域,在sendmessage函数中处理
    text_msglist = ScrolledText(frame_top,wrap=WORD)  #加滑动条的文本区,wrap自动换行
    msg_lable = Label(frame_left_bottom,text='请输入')
    # text_msg作为信息输入框按钮,其中信息被read_msg()函数读取
    text_msg = Entry(frame_left_bottom,width=24)
    select_lable =Label(frame_center_bottom,text='请选择')
    text_select = Listbox(frame_center_bottom,width=20,height = 2)
    button_lable = Label(frame_right_bottom,text='按我')
    # button_sendmsg作为发送按钮,触发sendmessage函数
    button_sendmsg = Button(frame_right_bottom, text=unicode('发送', 'utf-8'), command=sendmessage)
    # 不显示的标签
    text_respond = Label(frame_top)

    # 创建一个绿色的tag
    text_msglist.tag_config('green', foreground='#008B00')
    # 3. 显示欢迎信息
    insert_msg('Robot',u'您好,请问有什么可以帮您:)')

    # 使用grid设置各个容器位置
    frame_top.grid(row=0, column=0, padx=2, pady=5, columnspan=3,sticky=N)
    # frame_left_center.grid(row=1, column=0, padx=2, pady=5)
    frame_left_bottom.grid(row=1, column=0,sticky=W)
    frame_center_bottom.grid(row=1,column=1,sticky=E)
    frame_right_bottom.grid(row=1, column=2, padx=1, pady=2,sticky=E)
    frame_top.grid_propagate(0)
    frame_left_bottom.grid_propagate(0)
    frame_right_bottom.grid_propagate(0)

    # 把元素填充进frame
    text_msglist.pack(expand=True, fill='both') #文本区加滑动条
Пример #25
0
class GUI:
    """Graphical user interface to clfit.

    Data attributes that may sensibly be used externally:

    exe (string) -- path to clfit executable

    device (string) -- PGPLOT device, passed to clfit

    fileName (Tkinter.StringVar) -- path to OI-FITS/Mapping Data file
    (use set() & get() methods)

    ChangeFileButton (Tkinter.Button) -- brings up data file dialog
    box (may wish to disable)
    
    initialdir (string) -- initial directory for file dialog boxes

    preFitCallback -- function to call just before running clfit. If this
    returns false, clfit won't be run

    postFitCallback -- function to call after running clfit (if successful)
    
    """

    def __init__(self, parent, dismissCommand=None):
        """Constructor.

        Arguments are:

        parent -- parent window

        dismissCommand -- function to call when Dismiss button clicked

        """
        # Initialise data attributes
        self.parent = parent
        self.exe = 'clfit'
        self.device = '/xserv'
        self.fileName = StringVar()
        self.fileName.set('(unset)')
        self.initialdir = os.getcwd()
        self.preFitCallback = None
        self.postFitCallback = None
        self.calErr = StringVar()
        self.calErr.set('0.0')
        self.cwl = StringVar()
        self.bw = StringVar()
        self.wlmin = StringVar()
        self.wlmax = StringVar()
        self.target_id = StringVar()
        self.nofit = IntVar()
        self.nofit.set(0)
        self.plots = ['No plot', 'uv', 'vis2', 't3amp', 't3phi',
                      'vis2-wl', 't3amp-wl', 't3phi-wl',
                      'vis2-mjd', 't3amp-mjd', 't3phi-mjd',
                      'vis2-st', 't3amp-st', 't3phi-st', 'vis2-pa',
                      'post', 'mpost', 'post2d', 'mpost2d']
        self.selPlot = StringVar()
        self.selPlot.set(self.plots[1])
        self.plotXIndex = StringVar()
        self.plotXIndex.set('1')
        self.plotYIndex = StringVar()
        self.plotYIndex.set('2')
        self.plotXFrom = StringVar()
        self.plotXTo = StringVar()
        self.plotYFrom = StringVar()
        self.plotYTo = StringVar()
        self.margErr = IntVar()
        self.margErr.set(0)
        self.margErrVar = StringVar()
        self.margErrVar.set('1')

        # Initialise GUI elements
        fileFrame = Frame(parent)
        fileFrame.pack(side=TOP)
        Label(fileFrame, text='Data file:').pack(side=LEFT)
        Label(fileFrame, textvariable=self.fileName).pack(side=LEFT)
        self.ChangeFileButton = Button(fileFrame, text='Change',
                                       command=self._ChangeFileName)
        self.ChangeFileButton.pack(side=LEFT)
        calErrFrame = Frame(parent)
        calErrFrame.pack(side=TOP, fill=X, pady=4)
        Label(calErrFrame, text='Calibration Error (extra frac. error in system vis.)').pack(side=LEFT, anchor=W)
        Entry(calErrFrame, textvariable=self.calErr, width=5).pack(
            side=LEFT, anchor=W, padx=4)
        wbFrame = Frame(parent)
        wbFrame.pack(side=TOP, fill=X, pady=4)
        Label(wbFrame, text='Waveband:').pack(side=LEFT, anchor=W)
        Entry(wbFrame, textvariable=self.cwl, width=5).pack(side=LEFT,
                                                            anchor=W, padx=4)
        Entry(wbFrame, textvariable=self.bw, width=5).pack(side=LEFT,
                                                           anchor=W, padx=4)
        Label(wbFrame, text='or Wavelength range:').pack(side=LEFT, anchor=W)
        Entry(wbFrame, textvariable=self.wlmin,
              width=5).pack(side=LEFT, anchor=W, padx=4)
        Entry(wbFrame, textvariable=self.wlmax,
              width=5).pack(side=LEFT, anchor=W, padx=4)
        targetFrame = Frame(parent)
        targetFrame.pack(side=TOP, fill=X, pady=4)
        Label(targetFrame, text='TARGET_ID (blank to use 1st in OI_TARGET table):').pack(side=LEFT, anchor=W)
        Entry(targetFrame, textvariable=self.target_id,
              width=5).pack(side=LEFT, anchor=W, padx=4)
        Label(parent, text='Model:').pack(side=TOP, anchor=W)
        self.ModelText = ScrolledText(parent, height=19, width=40,
                                      font=('Helvetica', 10))
        self.ModelText.pack(side=TOP, expand=1, fill=BOTH)
        midFrame1 = Frame(parent)
        midFrame1.pack(side=TOP, fill=X, pady=4)
        Label(midFrame1, text='Plot:').pack(side=LEFT, anchor=NW)
        plotFrame = Frame(midFrame1)
        plotFrame.pack(side=LEFT)
        ncol = 3
        for i in range(len(self.plots)):
            p = self.plots[i]
            Radiobutton(plotFrame, text=p, variable=self.selPlot,
                        value=p).grid(row=(i+1)/ncol, column=(i+1)%ncol,
                                      sticky=W)
        Entry(plotFrame, textvariable=self.plotXIndex,
              width=3).grid(row=len(self.plots)/ncol-1, column=ncol)
        Entry(plotFrame, textvariable=self.plotYIndex,
              width=3).grid(row=len(self.plots)/ncol, column=ncol)
        rangeFrame = Frame(midFrame1)
        rangeFrame.pack(side=LEFT)
        Label(rangeFrame, text='X From:').grid(row=0, column=0, sticky=E)
        Entry(rangeFrame, textvariable=self.plotXFrom, width=5).grid(row=0, column=1)
        Label(rangeFrame, text='To:').grid(row=0, column=2)
        Entry(rangeFrame, textvariable=self.plotXTo, width=5).grid(row=0, column=3)
        Label(rangeFrame, text='Y From:').grid(row=1, column=0, sticky=E)
        Entry(rangeFrame, textvariable=self.plotYFrom, width=5).grid(row=1, column=1)
        Label(rangeFrame, text='To:').grid(row=1, column=2)
        Entry(rangeFrame, textvariable=self.plotYTo, width=5).grid(row=1, column=3)
        Label(rangeFrame, text='[Y for (m)post2d only]').grid(row=2, columnspan=4)
        Button(midFrame1, text='Go', command=self.Go).pack(side=RIGHT,
                                                           anchor=NE, padx=4)
        Button(midFrame1, text='Save model',
               command=self.SaveModel).pack(side=RIGHT, anchor=NE, padx=4)
        Button(midFrame1, text='Load model',
               command=self.LoadModel).pack(side=RIGHT, anchor=NE, padx=4)
        midFrame2 = Frame(parent)
        midFrame2.pack(side=TOP, fill=X, pady=4)
        Checkbutton(midFrame2, text="Don't fit (report goodness-of-fit only)",
                    variable=self.nofit).pack(side=LEFT, anchor=W, padx=8)
        Entry(midFrame2, textvariable=self.margErrVar,
              width=5).pack(side=LEFT, anchor=W)
        Checkbutton(midFrame2, text="Error bar by marginalising",
                    variable=self.margErr).pack(side=LEFT, anchor=W)
        midFrame3 = Frame(parent)
        midFrame3.pack(side=TOP, fill=X)
        Label(midFrame3, text='Results:').pack(side=LEFT, anchor=SW)
        if dismissCommand is None: dismissCommand = parent.quit
        Button(midFrame3, text='Dismiss',
               command=dismissCommand).pack(side=RIGHT, padx=4, pady=4)
        Button(midFrame3, text='Clear results',
               command=self.ClearResults).pack(side=RIGHT, padx=4, pady=4)
        self.Results = ScrolledText(parent, height=31, width=90,
                                    font=('Courier', 10), state=DISABLED)
        self.Results.tag_config('result', foreground='#1e90ff') # dodger blue
        self.Results.tag_config('commentary', foreground='#ff8c00') # dark orange
        self.Results.tag_config('error', foreground='#8b0000') # dark red
        self.Results.pack(side=TOP, expand=1, fill=BOTH)

    def LoadModel(self):
        """Get filename and read model from file."""
        fileName = tkFileDialog.askopenfilename(parent=self.parent,
            initialdir=self.initialdir,
            filetypes=[('mfit model files','*.model'),
                       ('All files','*')])
        if fileName != '': self.ReadModel(fileName)

    def ReadModel(self, fileName):
        """Read model from file."""
        try:
            fil = file(fileName, 'r')
            text = fil.read()
            fil.close()
        except IOError, (errNo, errStr):
            self.ShowResult('Error reading %s: %s\n' % (fileName, errStr),
                            'error')
        else:
Пример #26
0
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()
Пример #27
0
class Room(Toplevel):
    __client_sock = None
    __user_name = None
    __room_name = None
    __main_frame = None
    __top_frame = None

    __exit_room = False

    def __init__(self, client, room_name, main_frame, top_frame):
        Toplevel.__init__(self)

        self['background'] = 'grey'

        self.protocol('WM_DELETE_WINDOW', self.close_room)
        self.__user_name = main_frame.get_user_name()

        self.title("Room Name:" + room_name)
        self.__room_name = room_name

        self.configure_GUI()
        self.__client_sock = client

        self.__top_frame = top_frame
        self.__main_frame = main_frame
        self.__main_frame.add_new_room(self.__room_name, self)

        self.withdraw()
        self.mainloop()

    def show_room(self):
        self.__top_frame.withdraw()
        self.deiconify()

    def close_room(self):
        self.withdraw()

    def configure_GUI(self):
        # main window
        bg_color = '#208090'
        self['bg'] = bg_color
        self.geometry("400x500+520+500")
        self.resizable(width=True, height=True)

        self.frm_top = Frame(self, width=380, height=250)
        self.frm_mid = Frame(self, width=380, height=150)
        self.frm_btm = Frame(self, width=380, height=30)
        self.frm_btm['bg'] = bg_color

        self.label_msg_list = Label(self, justify=LEFT, text=u"""消息列表""")
        self.label_user_name = Label(self, justify=LEFT, text=self.__user_name)

        self.text_msg_List = ScrolledText(self.frm_top,
                                          borderwidth=1,
                                          highlightthickness=0,
                                          relief='flat',
                                          bg='#fffff0')
        self.text_msg_List.tag_config('userColor', foreground='red')
        self.text_msg_List.place(x=0, y=0, width=380, height=250)

        self.text_client_msg = ScrolledText(self.frm_mid)
        self.text_client_msg.grid(row=0, column=0)

        self.button_send_msg = Button(self.frm_btm,
                                      text='发送消息',
                                      command=self.__send_msg_btn_cmd)
        self.button_send_msg.place(x=0, y=0, width=100, height=30)

        self.button_exit_room = Button(self.frm_btm,
                                       text='退出房间',
                                       command=self.__exit_room_btn_cmd)
        self.button_exit_room.place(x=280, y=0, width=100, height=30)

        self.label_msg_list.grid(row=0, column=0, padx=2, pady=2, sticky=W)
        self.frm_top.grid(row=1, column=0, padx=2, pady=2)
        self.label_user_name.grid(row=2, column=0, padx=2, pady=2, sticky=W)
        self.frm_mid.grid(
            row=3,
            column=0,
            padx=2,
            pady=2,
        )
        self.frm_btm.grid(
            row=4,
            column=0,
            padx=2,
            pady=2,
        )

        self.frm_top.grid_propagate(0)
        self.frm_mid.grid_propagate(0)
        self.frm_btm.grid_propagate(0)

    def destroy_room(self):
        self.destroy()

    def query_room_user_name(self):
        msg = {'roomName': self.__room_name}
        data = package_sys_msg("SysRoomUserNameRequest", msg)
        self.__client_sock.append_to_msg_sending_queue(data)

    def __exit_room_btn_cmd(self):
        self.__exit_room = True
        msg = {'roomName': self.__room_name}
        data = package_sys_msg("SysExitRoomRequest", msg)
        self.__client_sock.append_to_msg_sending_queue(data)

    def __send_msg_btn_cmd(self):
        if self.__exit_room:
            return

        usr_msg = self.text_client_msg.get('0.0', END)
        self.display_new_msg(self.__user_name, usr_msg, 'userColor')
        self.text_client_msg.delete('0.0', END)
        data = package_room_chat_msg(self.__user_name, self.__room_name,
                                     usr_msg)
        self.__client_sock.append_to_msg_sending_queue(data)

    def display_new_msg(self, user_name, msg, config=''):
        self.text_msg_List['state'] = 'normal'
        msg_time = time.strftime(" %Y-%m-%d %H:%M:%S", time.localtime()) + '\n'
        self.text_msg_List.insert(END,
                                  user_name + ': ' + msg_time + msg + '\n',
                                  config)
        self.text_msg_List['state'] = 'disabled'
Пример #28
0
class MyThing (Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.textBox = ScrolledText(self, height=30, width=85)
        self.textBox.pack()
        self.addText()

    def leftMouseClick(self,event):
        print "got a click"
        mouseIndex =  "@%d,%d" % (event.x, event.y)
        current = self.textBox.index(mouseIndex)
        row = current.split(".")[0] + ".0"
        rowFl = float(row)+1.0
        row = str(rowFl)
        target = self.rowIndex[row]
        target = float(target)+12.0
        target = str(target)
        print "moving to target",target
        self.textBox.see(target)

    def rightMouseClick(self,event):
        self.textBox.see("0.0")



    def addText(self):
        f=open("help.txt",'r')
        lines = f.readlines()
        f.close()
        flag = 1
        i=0
        sectionOrder = {}
        sectionHeads = {}
        outlines = {} 
        targetId = 0
        defaultTarget = ""
        tocEntries = []
        lineId=0
        for line in lines:
            if line[0:1] =="#":
                tocEntries.append(line)
                if flag:
                    top = lineId
                    flag = 0
            lineId+=1



        self.tocEntries = tocEntries
        # header text
        header = lines[0:top]

        for line in header:
            hid=self.textBox.insert(END,line,"header")
            self.textBox.tag_config("header",foreground=FGCOLOR)
            self.textBox.tag_config("header",background=BGCOLOR)

        

        self.textBox.insert(END,"Table of Contents\n","toc")
        self.textBox.tag_config("toc",foreground="red")
        self.textBox.tag_config("toc",background=BGCOLOR)
        self.textBox.insert(END,
            "(Left-click entry to navigate, right-click to return)\n\n","directions")
        self.textBox.tag_config("directions",background=BGCOLOR)
        self.textBox.tag_config("directions",foreground="purple")



        sectionDict = {}
        rowIndex = {}
        for tocEntry in tocEntries:
            if tocEntry[0:2] == "##":
                line = "\t"+tocEntry[2:]
            else:
                line = tocEntry[1:]
            rowPosition = self.textBox.index(END).split(".")[0] + ".0"
            rowIndex[rowPosition] = "0.0"
            sectionDict[tocEntry] = rowPosition
            self.textBox.insert(END,line,"tocEntry")

        self.textBox.tag_bind("tocEntry",'<ButtonRelease-1>',
                               self.leftMouseClick)
        self.textBox.tag_config("tocEntry",background=BGCOLOR)
        self.textBox.tag_config("tocEntry",foreground=hfg)
        for i in range(50):
            self.textBox.insert(END,"\n","regular")

        lines = lines[top:]
        for line in lines:
            if sectionDict.has_key(line):
                print "section id",line
                position = self.textBox.index(END)
                tocPosition = sectionDict[line]
                rowIndex[tocPosition] = position
                line = line.replace("#","")

            self.textBox.insert(END,line,"regular")

        self.rowIndex = rowIndex

        self.sectionDict = sectionDict

        self.textBox.see("0.0")

        self.textBox.bind_all('<ButtonRelease-3>',
                              self.rightMouseClick)
        self.textBox.tag_config("regular",background=BGCOLOR)
        self.textBox.tag_config("regular",foreground="black")
Пример #29
0
class Cilent(Tkinter.Frame):
  
  def SetAccount(self,Account):   
    self.Account=Account
    self.master.title("Talking With: "+self.Account)
  def SetNewAccount(self):
    data=self.text_accountname.get('0.0', END)
    data=data[0:len(data)-1]
    self.Account=data
    self.text_msglist.insert(END, "Current Account:"+self.Account+'\n')
    #self.master.title("Talking With"+self.Account)
  def sendmessage(self):
    msgcontent = "MySelf: " + time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
    self.text_msglist.insert(END, msgcontent, 'green')         
    data=self.text_msg.get('0.0', END)
    data=data[0:len(data)-1]
    data="03#"+self.Account+"#"+data+"#"
    self.udpCliSock.sendto(data, self.ADDR)
    data, addr = self.udpCliSock.recvfrom(1024)
    if(data=="03:01"):
      self.Line="  (OnLine)"
      self.text_msglist.insert(END,"  (He is OnLine now)" +'\n', 'yellow')
    elif(data=="03:02"):
      self.Line="  (OffLine)"
      self.text_msglist.insert(END, "   (He is Off-Line now)"+'\n', 'yellow')
    else:
      self.text_msglist.insert(END, " "+data+'\n', 'yellow')
    self.text_msglist.insert(END, self.text_msg.get('0.0', END))   
    self.text_msg.delete('0.0', END)

  def OnlineRecvMessage(self):
    data="04#"+self.Account+"#"
    self.udpCliSock.sendto(data, self.ADDR)
    data, addr = self.udpCliSock.recvfrom(1024)
    if(data!="04:0"):
      data="05#"+self.Account+"#"
      self.udpCliSock.sendto(data, self.ADDR)
      data1, addr = self.udpCliSock.recvfrom(1024)
      if data1!="05:01":
        data1=data1[3:]
        msgcontent = data1 + '\n'
        self.text_msglist.insert(END, msgcontent, 'red')
      
    global timer
    timer=threading.Timer(0.5,self.OnlineRecvMessage)
    timer.start()
    
  def recvessage(self):
    data="04#"+self.Account+"#"
    self.udpCliSock.sendto(data, self.ADDR)
    data, addr = self.udpCliSock.recvfrom(1024)

    if(data!="04:0"):   
      data="05#"+self.Account+"#"
      self.udpCliSock.sendto(data, self.ADDR)
      data1, addr = self.udpCliSock.recvfrom(1024)
    
      if data1!="05:01":
        data1=data1[3:]
        msgcontent = data1 + '\n'
        self.text_msglist.insert(END, msgcontent, 'red')    
      else:
        self.text_msglist.insert(END, "No Message!"+'\n', 'red')
    else:
      self.text_msglist.insert(END, "No Message!"+'\n', 'red')
    

      
  def __init__(self,master,clisock= socket(AF_INET, SOCK_DGRAM),account="20161001234"):
    self.Account=account
    self.Line="."
    
    Tkinter.Frame.__init__(self, master, padx=10, pady=10)   
    master.title("Talking With"+self.Account)
    #创建几个frame作为容器
    self.frame_left_top   = Frame(master,width=380, height=270, bg='white')
    self.frame_left_center  = Frame(master,width=380, height=100, bg='white')
    self.frame_left_bottom  = Frame(master,width=380, height=20)
    self.frame_left_bottom1 = Frame(master,width=380, height=20)
    self.frame_right     = Frame(master,width=170, height=400, bg='white')

    self.frame_Account = Frame(master,width=380, height=20)
    self.frame_AccountName=Frame(master,width=100, height=20, bg='white')
    ##创建需要的几个元素
    self.text_msglist    = ScrolledText(self.frame_left_top,width=60, height=22)
    self.text_msg      = ScrolledText(self.frame_left_center,width=60, height=8);
    self.button_sendmsg   = Button(self.frame_left_bottom, text=unicode('发送','eucgb2312_cn'), command=self.sendmessage)   
    self.button_recvmsg   = Button(self.frame_left_bottom1, text=unicode('接收','eucgb2312_cn'), command=self.recvessage)
    
    self.button_Account   = Button(self.frame_Account, text=unicode('设置用户:','eucgb2312_cn'), command=self.SetNewAccount)
    self.text_accountname    = Text(self.frame_AccountName,)
    #UDP
    self.ADDR = ('202.114.196.97', 21568)
    self.udpCliSock = clisock
    #创建一个绿色的tag
    self.text_msglist.tag_config('green', foreground='#008B00')
    #使用grid设置各个容器位置
    self.frame_left_top.grid(row=0, column=0, padx=2, pady=5)
    self.frame_left_center.grid(row=1, column=0, padx=2, pady=5)
    self.frame_left_bottom.grid(row=2, column=0)
    self.frame_left_bottom1.grid(row=2, column=0)
    self.frame_right.grid(row=0, column=1, rowspan=3, padx=4, pady=5)

    self.frame_Account.grid(row=5, column=0, padx=0, pady=20)
    self.frame_AccountName.grid(row=5, column=0,padx=0, pady=20)   
    self.frame_left_top.grid_propagate(0)
    self.frame_left_center.grid_propagate(0)
    self.frame_left_bottom.grid_propagate(0)
    self.frame_Account.grid_propagate(0)
    self.frame_AccountName.grid_propagate(0)    
    #把元素填充进frame
    self.text_msglist.pack()
    self.text_msg.pack()
    self.button_sendmsg.grid(sticky=E)
    self.button_recvmsg.grid(sticky=E)

    self.button_Account.grid(sticky=E)
    self.text_accountname.grid()
    

    t=threading.Thread(target=self.OnlineRecvMessage)
    t.start()
Пример #30
0
class SigBridgeUI(Tk):
    server = None
    server_thread = None

    def __init__(self):
        Tk.__init__(self)

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        # 2 rows: firts with settings, second with registrar data
        self.main_frame = Frame(self)
        # Commands row doesn't expands
        self.main_frame.rowconfigure(0, weight=0)
        # Logs row will grow
        self.main_frame.rowconfigure(1, weight=1)
        # Main frame can enlarge
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.columnconfigure(1, weight=1)
        self.main_frame.grid(row=0, column=0)

        # Run/Stop button
        self.server_button = Button(self.main_frame, text="Connect", command=self.start_server)
        self.server_button.grid(row=0, column=0)

        # Clear button
        self.clear_button = Button(self.main_frame, text="Clear Log", command=self.clear_log)
        self.clear_button.grid(row=0, column=1)

        # Logs Widget
        self.log_widget = ScrolledText(self.main_frame)
        self.log_widget.grid(row=1, column=0, columnspan=2)
        # made not editable
        self.log_widget.config(state='disabled')

        # Queue where the logging handler will write
        self.log_queue = Queue.Queue()

        # Setup the logger
        self.uilogger = logging.getLogger('SigBridgeUI')
        self.uilogger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

        # Use the QueueLogger as Handler
        hl = QueueLogger(queue=self.log_queue)
        hl.setFormatter(formatter)
        self.uilogger.addHandler(hl)

        # self.log_widget.update_idletasks()
        self.set_geometry()

        # Setup the update_widget callback reading logs from the queue
        self.start_log()

    def clear_log(self):
        self.log_widget.config(state='normal')
        self.log_widget.delete(0.0, END)
        self.log_widget.config(state='disabled')

    def start_log(self):
        self.uilogger.info("SigBridge Started.")
        self.update_widget()
        # self.control_log_button.configure(text="Pause Log", command=self.stop_log)

    def update_widget(self):
        self.log_widget.config(state='normal')
        # Read from the Queue and add to the log widger
        while not self.log_queue.empty():
            line = self.log_queue.get()
            tag = "error" if " ERROR " in line else 'info'
            self.log_widget.insert(END, line, tag)
            self.log_widget.see(END)  # Scroll to the bottom
            self.log_widget.update_idletasks()
        self.log_widget.tag_config('error', foreground="red")
        self.log_widget.config(state='disabled')
        self.log_widget.after(10, self.update_widget)

    def set_geometry(self):
        # set position in window
        w = 600  # width for the Tk
        h = 300  # height for the Tk

        # get screen width and height
        ws = self.winfo_screenwidth()   # width of the screen
        hs = self.winfo_screenheight()  # height of the screen

        # calculate x and y coordinates for the Tk window
        x = (ws/2) - (w/2)
        y = (hs/2) - (h/2)

        # set the dimensions of the screen 
        # and where it is placed
        self.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def start_server(self):
        try:
            self.server = SigServer(('0.0.0.0', 25), None, self.uilogger)
            self.server_thread = threading.Thread(name='server', target=self.server.run)
            self.server_thread.daemon = True
            self.server_thread.start()
            self.server_button.configure(text="Disconnect", command=self.stop_server)
        except Exception as err:
            self.uilogger("Cannot start the server: %s" % err.message)

        # self.label_variable.set(self.entry_variable.get()+"(Started Signal Server)")
        # self.entry.focus_set()
        # self.entry.selection_range(0, END)

    def stop_server(self):
        self.server.shutdown()
        self.server_button.configure(text="Connect", command=self.start_server)
        self.server = None
Пример #31
0
class Mu_XBoardDebugger_Widget(Frame):
  def __init__(self, root, mu_board_debugger):
    self.root = root
    self.mu_board_debugger = mu_board_debugger
    self.mu_debugger = self.mu_board_debugger.mu_debugger
    self.mu = self.mu_debugger.mu
    self.mu_board = self.mu_board_debugger.mu_board

    Frame.__init__(self, self.root)
    self.button_frame = Frame(self)
    self.button_set_max = Button(self.button_frame,
			width=3,
			repeatinterval=10,
			repeatdelay=10,
			text="M",
			command=self.set_height_max
    )
    self.button_set_max.pack(side=TOP)
    self.button_increase_2 = Button(self.button_frame,
			width=3,
			repeatinterval=10,
			repeatdelay=10,
			text="++",
			command=self.increase_height_2
    )
    self.button_increase_2.pack(side=TOP)
    self.button_increase_1 = Button(self.button_frame,
			width=3,
			repeatinterval=10,
			repeatdelay=10,
			text="+",
			command=self.increase_height_1
    )
    self.button_increase_1.pack(side=TOP)
    self.button_decrease_1 = Button(self.button_frame,
			width=3,
			repeatinterval=10,
			repeatdelay=10,
			text="-",
			command=self.decrease_height_1
    )
    self.button_decrease_1.pack(side=TOP)
    self.button_decrease_2 = Button(self.button_frame,
			width=3,
			repeatinterval=10,
			repeatdelay=10,
			text="--",
			command=self.decrease_height_2
    )
    self.button_decrease_2.pack(side=TOP)
    self.button_set_min = Button(self.button_frame,
			width=3,
			repeatinterval=10,
			repeatdelay=10,
			text="m",
			command=self.set_height_min
    )
    self.button_set_min.pack(side=TOP)
    self.button_frame.pack(side=RIGHT)
    self.field_frame = Frame(self)
    self.field = ScrolledText(self.field_frame, width=self.mu_board.max_j, height=1+self.mu_board.max_i, highlightthickness=2)
    self.field.tag_config("unseen", background="white", foreground="dark gray")
    self.field.tag_config("seen", background="yellow", foreground="blue", borderwidth=1)
    self.field.tag_config("current_active", background="orange", foreground="black", borderwidth=1)
    self.field.tag_config("current_held", background="black", foreground="white", borderwidth=1)
    self.field.tag_config("current_waiting", background="blue", foreground="white", borderwidth=1)
    self.field.tag_config("error", background="red", foreground="yellow", borderwidth=1)
    self.field.tag_config("breakpoint_in", background="red", foreground="green", borderwidth=1)
    self.field.tag_config("breakpoint_out", background="green", foreground="red", borderwidth=1)
    for row_num, row in enumerate(self.mu_board.matrix):
      line = "%s\n" % ''.join(self.mu.i2a(i) for i in row)
      self.field.insert("%d.0" % (row_num+1), line, "unseen")
    #self.field.set_debug_mode()
    self.field.pack(padx = 5, pady = 5, fill = 'both', expand = 1)
    self.field_frame.pack(side=LEFT)
    self.bind("<Return>", self.event_press_enter)
    self.bind("<Key>", self.event_press_key)
    self.focus_set()

  def increase_height_1(self):
    self.field["height"] += 1

  def decrease_height_1(self):
    self.field["height"] -= 1

  def increase_height_2(self):
    self.field["height"] += 2

  def decrease_height_2(self):
    self.field["height"] -= 2

  def set_height_max(self):
    self.field["height"] = self.mu_board.max_i

  def set_height_min(self):
    self.field["height"] = 5

  def event_press_enter(self, event):
    return self.mu_debugger.xdebugger.event_press_enter(event)

  def event_press_key(self, event):
    return self.mu_debugger.xdebugger.event_press_key(event)
Пример #32
0
   def __init__(self, master):
      Client.__init__(self)
      self.started = False          # use it to not try stopping if didn't start
      self.parent = master          # used to distroy it on exit
      master.title("TomIRC")        # app's title
      master.resizable(0, 0)        # user cannot resize it
      # master.config(width = 720, height = 526)
      # master.grid_propagate(False)  # doesn't change size because of inner elements

      result = InitialDialog(master, "Connection settings").result
      if not result:
         self.onExit()
         return

      self.started = True
      self.start(result[0], result[1])
      self.name = result[2]

      master.protocol("WM_DELETE_WINDOW", self.onExit)

      # add a menu
      menu = Menu(master)
      master.config(menu = menu)

      filemenu = Menu(menu)
      menu.add_cascade(label = "File", menu = filemenu)
      filemenu.add_command(label = "Change your username", command = self.changeName)
      filemenu.add_separator()
      filemenu.add_command(label = "Quit", command = self.onExit)
      menu.add_command(label = "About", command = self.aboutBox)

      # use a menu entry as an information bar
      menu.add_command(label = "               ", state = DISABLED)
      menu.add_command(label = "Connected to %s:%s as %s" % (result[0], result[1],\
                       self.name), state = DISABLED, background = "gray", \
                       font = tkFont.Font(family = "Times", weight = tkFont.BOLD,\
                              size = 10))
      menu.add_command(label = "                                         ",\
                       state = DISABLED)
      menu.add_command(label = "          Connected users           ",\
                       state = DISABLED, background = "gray", \
                       font = tkFont.Font(family = "Times", weight = tkFont.BOLD, \
                                          size = 10))
      menu.config(disabledforeground = "#777")
      self.menu = menu

      # list of connected users
      self.connectedUsers = StringVar()         # used to update the userList
      self.userList = Listbox(master, height = 15, width = 21, selectmode = MULTIPLE, \
                              listvariable = self.connectedUsers)
      self.userList.bind('<<ListboxSelect>>', self.onListSelect)
      # self.connectedUsers.set("default_user\n" + self.name)

      # add widget for displaying incoming text
      text = ScrolledText(master, height = 20, width = 75, state = DISABLED)
      text.tag_config("a", background = "lightgray")        # set a tag for the author
      text.tag_config('s', background = "darkgray")         # set a tag for the server
      self.display = text

      # add the text input
      text = ScrolledText(master, height = 5, width = 75)
      text.bind('<KeyRelease-Return>', self.sendMessage)
      text.focus_set()
      self.input = text

      # add a label to state errors and warnings
      self.infoLabel = StringVar(value = "Registered successfully...")
      label = Label(master, textvariable = self.infoLabel, anchor = W, fg = "#555")

      label.grid(row = 2, column = 0, columnspan = 2, sticky = W)
      self.display.grid(row = 0, column = 0, sticky = N)
      self.input.grid(row = 1, column = 0)
      self.userList.grid(row = 0, column = 1, rowspan = 2, sticky = N + S)
      self.send("REG " + self.name)          # register the user
      self.populateList()
Пример #33
0
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")
Пример #34
0
class Mu_XDebugger_Widget(Frame):
  def __init__(self, root, mu_debugger):
    self.root = root
    Frame.__init__(self, root)
    self.mu_debugger = mu_debugger
    self.mu = mu_debugger.mu
    self.interaction_frame = Frame(self.root)
    self.interaction_frame.pack(side=TOP)
    self.button_frame = Frame(self.interaction_frame)
    self.button_frame.pack(side=LEFT)
    self.control_frame = Frame(self.interaction_frame)
    self.control_frame.pack(side=LEFT)
    self.step_num_control_frame = Frame(self.control_frame)
    self.step_num_control_frame.pack(side=TOP)
    self.repeatinterval_control_frame = Frame(self.control_frame)
    self.repeatinterval_control_frame.pack(side=TOP)
    self.console_frame = Frame(self.root)
    self.console_frame.pack(side=TOP)
    self.boards_frame = Frame(self.root)

    self.boards_frame.grid_rowconfigure(0, weight=1)
    self.boards_frame.grid_columnconfigure(0, weight=1)

    self.boards_xscrollbar = Scrollbar(self.boards_frame, orient=HORIZONTAL)
    self.boards_xscrollbar.grid(row=1, column=0, sticky=E+W)

    self.boards_yscrollbar = Scrollbar(self.boards_frame)
    self.boards_yscrollbar.grid(row=0, column=1, sticky=N+S)

    self.boards_canvas = Canvas(	self.boards_frame,
					scrollregion=(0, 0, 1200, 10240),
					bd=0,
					xscrollcommand=self.boards_xscrollbar.set,
					yscrollcommand=self.boards_yscrollbar.set,
					confine=True,
    )

    self.boards_canvas.grid(row=0, column=0, sticky=N+S+E+W)
    self.boards_xscrollbar.config(command=self.boards_canvas.xview)
    self.boards_yscrollbar.config(command=self.boards_canvas.yview)

    self.xboard_debuggers = []
    for mu_board_debugger in reversed(mu_debugger.mu_board_debuggers):
      xboard_debugger = Mu_XBoardDebugger_Widget(self.boards_canvas, mu_board_debugger)
      mu_board_debugger.xboard_debugger = xboard_debugger
      xboard_debugger.pack(side=TOP)
    self.xboard_debuggers.append(xboard_debugger)

    #self.boards_canvas.config(scrollregion=(0, 0, 1200, 10240))
    self.boards_frame.pack(side=TOP)

    #for mu_board_debugger in reversed(mu_debugger.mu_board_debuggers):
    #  print "...", mu_board_debugger.xboard_debugger.bbox(), mu_board_debugger.xboard_debugger.size()
    #

    self.repeatinterval = 10
    self.repeatdelay = 500
    self.step_num = 1
    self.bind("<Return>", self.event_press_enter)
    self.bind("<Key>", self.event_press_key)
    self.focus_set()
    self.pack()
    self._key_int = []
    self.breakpoints = []

    #for mu_board_debugger in reversed(mu_debugger.mu_board_debuggers):
    #  print mu_board_debugger.xboard_debugger.field["width"], mu_board_debugger.xboard_debugger.field["height"]

  def run(self):
    self.running = False
    self.step_button = Button(self.button_frame,
			repeatinterval=self.repeatinterval,
			repeatdelay=self.repeatdelay,
			text="Step",
			command=self.run_steps
    )
    self.step_button.pack(side=LEFT)
    self.quit_button = Button(self.button_frame,
			text="Quit",
			command=self.mu_debugger.quit
    )
    self.quit_button.pack(side=LEFT)
    self.itn = Label( self.button_frame,
			width=16,
			height=1,
			text=self.mu_debugger.iteration()
    )
    self.itn.pack(side=LEFT)

    self.step_num_label = Label( self.step_num_control_frame,
			width=16,
			height=1,
			text="Step #",
    )
    self.step_num_label.pack(side=LEFT)
    self.step_num_decrease_10_button = Button(self.step_num_control_frame,
			text="<<",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.step_num_decrease_10,
    )
    self.step_num_decrease_10_button.pack(side=LEFT)
    self.step_num_decrease_button = Button(self.step_num_control_frame,
			text="<",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.step_num_decrease,
    )
    self.step_num_decrease_button.pack(side=LEFT)
    self.step_num_value = Label( self.step_num_control_frame,
			width=10,
			height=1,
			text=str(self.step_num),
    )
    self.step_num_value.pack(side=LEFT)
    self.step_num_increase_button = Button(self.step_num_control_frame,
			text=">",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.step_num_increase,
    )
    self.step_num_increase_button.pack(side=LEFT)
    self.step_num_increase_10_button = Button(self.step_num_control_frame,
			text=">>",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.step_num_increase_10,
    )
    self.step_num_increase_10_button.pack(side=LEFT)
			
			
    self.repeatinterval_label = Label( self.repeatinterval_control_frame,
			width=16,
			height=1,
			text="Repeat interval",
    )
    self.repeatinterval_label.pack(side=LEFT)
    self.repeatinterval_decrease_10_button = Button(self.repeatinterval_control_frame,
			text="<<",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.repeatinterval_decrease_10,
    )
    self.repeatinterval_decrease_10_button.pack(side=LEFT)
    self.repeatinterval_decrease_button = Button(self.repeatinterval_control_frame,
			text="<",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.repeatinterval_decrease,
    )
    self.repeatinterval_decrease_button.pack(side=LEFT)
    self.repeatinterval_value = Label( self.repeatinterval_control_frame,
			width=10,
			height=1,
			text=str(self.repeatinterval),
    )
    self.repeatinterval_value.pack(side=LEFT)
    self.repeatinterval_increase_button = Button(self.repeatinterval_control_frame,
			text=">",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.repeatinterval_increase,
    )
    self.repeatinterval_increase_button.pack(side=LEFT)
			
    self.repeatinterval_increase_10_button = Button(self.repeatinterval_control_frame,
			text=">>",
			repeatdelay=self.repeatdelay,
			repeatinterval=self.repeatinterval,
			command=self.repeatinterval_increase_10,
    )
    self.repeatinterval_increase_10_button.pack(side=LEFT)

    self.breakpoint_frame = Frame(self.button_frame)
    self.breakpoint_frame.pack(side=LEFT)
    self.add_breakpoint_button =  Button(self.repeatinterval_control_frame,
			text="ADD BREAK POINT",
			command=self.add_break_point,
    )

			
    self.console_text = ScrolledText(
			self.console_frame,
			width=80,
			height=3,
    )
    self.console_text.pack(side=LEFT)
    self.console_text.tag_config("line_number", background="black", foreground="light gray", borderwidth=1)
    self.console_text.tag_config("output", background="black", foreground="yellow", borderwidth=1)


  def add_break_point(self, event):
    pass

  def event_press_enter(self, event):
    self.run_steps()

  def event_press_key(self, event):
    if event.keysym_num >= ord('0') and event.keysym_num <= ord('9'):
      self._key_int.append(event.keysym)
      self._key_int.append(event.keysym)
    else:
      if self._key_int:
        ki = int(''.join(self._key_int))
        print ki
        self.step_num = ki
        self.step_num_value['text'] = str(ki)
      self._key_int = []
      if event.keysym_num == ord('+'):
        self.step_num_increase()
      elif event.keysym_num == ord('-'):
        self.step_num_decrease()
      elif event.keysym_num == ord('>'):
        self.step_num_increase_10()
      elif event.keysym_num == ord('<'):
        self.step_num_decrease_10()
      elif event.keysym_num in (ord('q'), ord('Q')):
        self.mu_debugger.quit()
      else:
        self.run_steps()

  def run_steps(self):
    if self.mu_debugger.disabled:
      return
    try:
      n = self.step_num
      while n > 0:
        self.mu_debugger.run_step()
        n -= 1
    except Mu_Error, e:
      self.exception(e)
Пример #35
0
    class TkTCPWatch (Tkinter.Frame):
        '''The tcpwatch top-level window.
        '''
        def __init__(self, master):
            Tkinter.Frame.__init__(self, master)
            self.createWidgets()
            # connections maps ids to TkConnectionObservers.
            self.connections = {}
            self.showingid = ''
            self.queue = Queue()
            self.processQueue()

        def createWidgets(self):
            listframe = Tkinter.Frame(self)
            listframe.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=1)
            scrollbar = Tkinter.Scrollbar(listframe, orient=Tkinter.VERTICAL)
            self.connectlist = Tkinter.Listbox(
                listframe, yscrollcommand=scrollbar.set, exportselection=0)
            scrollbar.config(command=self.connectlist.yview)
            scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y)
            self.connectlist.pack(
                side=Tkinter.LEFT, fill=Tkinter.BOTH, expand=1)
            self.connectlist.bind('<Button-1>', self.mouseListSelect)
            self.textbox = ScrolledText(self, background="#ffffff")
            self.textbox.tag_config("message", foreground="#000000")
            self.textbox.tag_config("client", foreground="#007700")
            self.textbox.tag_config(
                "clientesc", foreground="#007700", background="#dddddd")
            self.textbox.tag_config("server", foreground="#770000")
            self.textbox.tag_config(
                "serveresc", foreground="#770000", background="#dddddd")
            self.textbox.insert(Tkinter.END, startup_text, "message")
            self.textbox.pack(side='right', fill=Tkinter.BOTH, expand=1)
            self.pack(fill=Tkinter.BOTH, expand=1)

        def addConnection(self, id, conn):
            self.connections[id] = conn
            connectlist = self.connectlist
            connectlist.insert(Tkinter.END, id)

        def updateConnection(self, id, output):
            if id == self.showingid:
                textbox = self.textbox
                for data, style in output:
                    textbox.insert(Tkinter.END, data, style)

        def mouseListSelect(self, event=None):
            connectlist = self.connectlist
            idx = connectlist.nearest(event.y)
            sel = connectlist.get(idx)
            connections = self.connections
            if connections.has_key(sel):
                self.showingid = ''
                output = connections[sel].getOutput()
                self.textbox.delete(1.0, Tkinter.END)
                for data, style in output:
                    self.textbox.insert(Tkinter.END, data, style)
                self.showingid = sel

        def processQueue(self):
            try:
                if not self.queue.empty():
                    # Process messages for up to 1/4 second
                    from time import time
                    limit = time() + 0.25
                    while time() < limit:
                        try:
                            f, args = self.queue.get_nowait()
                        except Empty:
                            break
                        f(*args)
            finally:
                self.master.after(50, self.processQueue)
Пример #36
0
class xbbtools_help(Toplevel):
    def __init__(self, *args):
        Toplevel.__init__(self)
        self.tid = ScrolledText(self)
        self.tid.pack(fill = BOTH, expand = 1)
        self.Styles()
        self.Show()

    def Styles(self):
        for c in ['red', 'blue', 'magenta', 'yellow', 'green', 'red4', 'green4', 'blue4']:
            self.tid.tag_configure(c, foreground = c)

        self.tid.tag_config('underline', underline =1)
        self.tid.tag_config('italic', font = ('Courier', 6, 'italic'))
        self.tid.tag_config('bold', font = ('Courier', 8, 'bold'))
        self.tid.tag_config('title', font = ('Courier', 12, 'bold'))
        self.tid.tag_config('small', font = ('Courier', 6, ''))
        self.tid.tag_config('highlight', background = 'gray')

    def Show(self):
        t = self.tid
        t.insert(END, "XBBtools Help\n", 'title')
        t.insert(END, """
Copyright 2001 by Thomas Sicheritz-Ponten.  All rights reserved.
This code is part of the Biopython distribution and governed by its
license.  Please see the LICENSE file that should have been included
as part of this package.\n
""", 'italic')
        t.insert(END, '[email protected]\n\n', 'blue')
        t.insert(END, '* Goto Field\n', 'bold')
        t.insert(END, '\tinserting one position moves cursor to position\n')
        t.insert(END, "\tinserting two positions, sperated by ':' ")
        t.insert(END, 'highlights', 'highlight')
        t.insert(END, ' selected range\n')
        t.insert(END, '\n')
        t.insert(END, '* Search\n', 'bold')
        t.insert(END, '\tambiguous dna values are\n')
        t.insert(END, """
                A: A
                C: C
                G: G
                T: T
                M: AC
                R: AG
                W: AT
                S: CG
                Y: CT
                K: GT
                V: ACG
                H: ACT
                D: AGT
                B: CGT
                X: GATC
                N: GATC

                """, 'small')
Пример #37
0
class MyThing(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.textBox = ScrolledText(self, height=30, width=85)
        self.textBox.pack()
        self.addText()

    def leftMouseClick(self, event):
        print "got a click"
        mouseIndex = "@%d,%d" % (event.x, event.y)
        current = self.textBox.index(mouseIndex)
        row = current.split(".")[0] + ".0"
        rowFl = float(row) + 1.0
        row = str(rowFl)
        target = self.rowIndex[row]
        target = float(target) + 12.0
        target = str(target)
        print "moving to target", target
        self.textBox.see(target)

    def rightMouseClick(self, event):
        self.textBox.see("0.0")

    def addText(self):
        f = open("help.txt", 'r')
        lines = f.readlines()
        f.close()
        flag = 1
        i = 0
        sectionOrder = {}
        sectionHeads = {}
        outlines = {}
        targetId = 0
        defaultTarget = ""
        tocEntries = []
        lineId = 0
        for line in lines:
            if line[0:1] == "#":
                tocEntries.append(line)
                if flag:
                    top = lineId
                    flag = 0
            lineId += 1

        self.tocEntries = tocEntries
        # header text
        header = lines[0:top]

        for line in header:
            hid = self.textBox.insert(END, line, "header")
            self.textBox.tag_config("header", foreground=FGCOLOR)
            self.textBox.tag_config("header", background=BGCOLOR)

        self.textBox.insert(END, "Table of Contents\n", "toc")
        self.textBox.tag_config("toc", foreground="red")
        self.textBox.tag_config("toc", background=BGCOLOR)
        self.textBox.insert(
            END, "(Left-click entry to navigate, right-click to return)\n\n",
            "directions")
        self.textBox.tag_config("directions", background=BGCOLOR)
        self.textBox.tag_config("directions", foreground="purple")

        sectionDict = {}
        rowIndex = {}
        for tocEntry in tocEntries:
            if tocEntry[0:2] == "##":
                line = "\t" + tocEntry[2:]
            else:
                line = tocEntry[1:]
            rowPosition = self.textBox.index(END).split(".")[0] + ".0"
            rowIndex[rowPosition] = "0.0"
            sectionDict[tocEntry] = rowPosition
            self.textBox.insert(END, line, "tocEntry")

        self.textBox.tag_bind("tocEntry", '<ButtonRelease-1>',
                              self.leftMouseClick)
        self.textBox.tag_config("tocEntry", background=BGCOLOR)
        self.textBox.tag_config("tocEntry", foreground=hfg)
        for i in range(50):
            self.textBox.insert(END, "\n", "regular")

        lines = lines[top:]
        for line in lines:
            if sectionDict.has_key(line):
                print "section id", line
                position = self.textBox.index(END)
                tocPosition = sectionDict[line]
                rowIndex[tocPosition] = position
                line = line.replace("#", "")

            self.textBox.insert(END, line, "regular")

        self.rowIndex = rowIndex

        self.sectionDict = sectionDict

        self.textBox.see("0.0")

        self.textBox.bind_all('<ButtonRelease-3>', self.rightMouseClick)
        self.textBox.tag_config("regular", background=BGCOLOR)
        self.textBox.tag_config("regular", foreground="black")
Пример #38
0
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()
Пример #39
0
class DesDesk():
    def __init__(self):
        window = Tk()
        window.title("des加密与解密")
        window.geometry('700x500+300+150')
        # window['background'] = 'MintCream'
        # window['background'] = 'Moccasin'
        # window['background'] = 'Honeydew'
        # img_gif = PhotoImage(file='timg.gif')
        # image = Image.open(r'timg.gif')
        # background_image = ImageTk.PhotoImage(image)
        # background_image = ImageTk.PhotoImage(image)
        # window['background'] = background_image
        # window['background'] = img_gif
        window['background'] = "LightCyan"

        # window.iconbitmap("des.jpeg")

        # frame1 = Frame(window)
        # frame1.pack()

        window_x = 120
        font = "Times"
        font_color = "LightCoral"
        # font_color = "Wheat"
        input_label = Label(window, text="明文")
        input_label.config(bg=font_color)
        input_label.config(font=font)
        input_label_y = 10
        input_label.place(x=window_x, y=input_label_y)

        self.input_text = ScrolledText(window, height=8, width=60)
        self.input_text.tag_config('a', foreground='red')
        self.input_text.place(x=window_x, y=input_label_y + 30)

        key_label = Label(window, text="密码")
        key_label.config(font=font)
        key_label.config(bg=font_color)
        self.key = StringVar()
        key_entry = Entry(window, textvariable=self.key)
        key_entry['show'] = "*"
        key_label_y = 190

        key_label.place(x=window_x, y=key_label_y)
        key_entry.place(x=window_x + 40, y=key_label_y)

        button_color = "CornflowerBlue"
        btn_font_color = "Ivory"
        encode = Button(window, text="加密", command=self.encode_text)
        encode.config(font=font)
        encode.config(bg=button_color)
        encode.config(fg=btn_font_color)

        #decode_img = PhotoImage(file="decode.png")
        decode = Button(window, text="解密", command=self.decode_text)
        decode.config(font=font)
        decode.config(bg=button_color)
        decode.config(fg=btn_font_color)

        encode.place(x=window_x + 300, y=key_label_y)
        decode.place(x=window_x + 380, y=key_label_y)

        out_label = Label(window, text="密文")
        out_label.config(font=font)
        out_label.config(bg=font_color)
        out_label_y = 240
        out_label.place(x=window_x, y=out_label_y)
        self.out_text = ScrolledText(window, height=8, width=60)
        self.out_text.place(x=window_x, y=out_label_y + 30)

        #label = Label(window, text="解密").place(x=20,y=30)

        # text_area.grid(row=1, column=1)
        # text_entry.grid(row=1, column=2)

        # key_label.grid(row=2, column=1)
        # key_entry.grid(row=2, column=2)

        # encode.grid(row=2, column=1)

        # import and export button
        import_btn = Button(window, text="导入", command=self.ask_open_file)
        export_btn = Button(window, text="导出", command=self.ask_save_file)
        import_btn.place(x=window_x + 300, y=out_label_y + 160)
        export_btn.place(x=window_x + 380, y=out_label_y + 160)
        import_btn.config(font=font)
        import_btn.config(bg=button_color)
        import_btn.config(fg=btn_font_color)
        export_btn.config(font=font)
        export_btn.config(bg=button_color)
        export_btn.config(fg=btn_font_color)

        window.mainloop()

    def ask_open_file(self):
        try:
            file_path = tkFileDialog.askopenfilename()
            with open(file_path, "r") as file:
                contents = file.read()
                # print(contents)
                contents = eval(contents)

                text_not_null = False

                if contents.has_key('text'):
                    self.input_text.insert(END, contents['text'])
                    text_not_null = True

                if contents.has_key("key"):
                    self.key.set(contents['key'])
                    text_not_null = True

                if contents.has_key("encode"):
                    self.out_text.insert(END, contents['encode'])
                    text_not_null = True

            if text_not_null:
                showinfo("提示", "导入成功!")
            else:
                showinfo("提示", "文件为空!")
        except Exception as e:
            return

    # 将明文、密码和密文以字典方式保存
    def ask_save_file(self):
        try:
            file_path = tkFileDialog.asksaveasfilename()
            contents = dict(
                text=self.input_text.get("1.0", END).strip(),
                key=self.key.get().strip(),
                encode=self.out_text.get("1.0", END).strip(),
            )
            contents = str(contents)
            print(contents)
            with open(file_path, "w") as file:
                file.write(contents)

            showinfo("提示", "导出成功!")
        except Exception as e:
            return

    def encode_text(self):
        text = self.input_text.get("1.0", END).strip()
        key = self.key.get().strip()

        if text == "" or text == None:
            print("请输入明文!")
            showinfo("提示", "请输入明文!")
            return

        if key == "" or key == None:
            print("请输入密码!")
            showinfo("提示", "请输入密码!")
            return

        if not check_key(key):
            showinfo("提示", "密码中必须含有数字、字母和特殊字符!")
            self.key.set("")
            return

        print("text:%s;key:%s" % (text, key))
        encoded_text = des.code(text, key)
        print("encode_text is %s" % encoded_text)

        # clean out_put area
        self.out_text.delete("1.0", END)
        # insert into out_put text
        self.out_text.insert(END, encoded_text)

    def decode_text(self):
        text = self.out_text.get("0.0", END).strip()
        key = self.key.get().strip()

        if text == "" or text == None:
            print("请输入密文!")
            showinfo("提示", "请输入密文!")
            return

        if key == "" or text == None:
            print("请输入密码!")
            showinfo("提示", "请输入密码!")
            return

        print("text:%s;key:%s" % (text, key))
        try:
            decoded_text = des_1.decode(text, key)
            print("decoded_text is %s" % decoded_text)
        except Exception as e:
            showerror("", "解密过程出错请重试!")
            self.out_text.delete("1.0", END)
            self.key.set("")
            return

        self.input_text.delete("1.0", END)
        self.input_text.insert(END, decoded_text)