Ejemplo n.º 1
0
class LogWindow(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title("Network Simulator Log")
        self.text = ScrolledText(self)
        self.text.pack(fill=BOTH, expand=1)
        self.pack(fill=BOTH, expand=1)
        self.text.config(
            background="black",
            foreground="white",
            font=Font(
                family="Courier", weight="bold"),
            # state=DISABLED,
            wrap=NONE, )

        self.text.tag_config("DEBUG", foreground="green")
        self.text.tag_config("ERROR", foreground="red")
        self.text.tag_config("CRITICAL", foreground="red")
        self.text.tag_config("EXCEPTION", foreground="red")
        self.text.tag_config("WARNING", foreground="yellow")
        self.text.tag_config("INFO", foreground="white")

        self.text.bind("<Key>", lambda e: 'break')
        self.text.bind("<Return>", self._clear)
        self.queue = Queue()
        self._update()

    def _clear(self, event):
        self.text.delete(1.0, END)
        return 'break'

    def _update(self):
        try:
            while True:
                text, level = self.queue.get(block=False)

                at_bottom = self.text.yview()[1] == 1.0
                # self.text.config(state=NORMAL)
                if len(self.text.get(1.0, END).strip()) != 0:
                    text = "\n" + text
                self.text.insert(END, text, str(level))
                # self.text.config(state=DISABLED)
                if at_bottom:
                    self.text.yview_moveto(1.0)
        except Empty:
            pass
        self.after(50, self._update)

    def append(self, entry, level="INFO"):
        self.queue.put((entry, level))
Ejemplo n.º 2
0
class LogWindow(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title("Network Simulator Log")
        self.text = ScrolledText(self)
        self.text.pack(fill=BOTH, expand=1)
        self.pack(fill=BOTH, expand=1)
        self.text.config(
            background="black",
            foreground="white",
            font=Font(family="Courier", weight="bold"),
            # state=DISABLED,
            wrap=NONE,
        )

        self.text.tag_config("DEBUG", foreground="green")
        self.text.tag_config("ERROR", foreground="red")
        self.text.tag_config("CRITICAL", foreground="red")
        self.text.tag_config("EXCEPTION", foreground="red")
        self.text.tag_config("WARNING", foreground="yellow")
        self.text.tag_config("INFO", foreground="white")

        self.text.bind("<Key>", lambda e: 'break')
        self.text.bind("<Return>", self._clear)
        self.queue = Queue()
        self._update()

    def _clear(self, event):
        self.text.delete(1.0, END)
        return 'break'

    def _update(self):
        try:
            while True:
                text, level = self.queue.get(block=False)

                at_bottom = self.text.yview()[1] == 1.0
                # self.text.config(state=NORMAL)
                if len(self.text.get(1.0, END).strip()) != 0:
                    text = "\n" + text
                self.text.insert(END, text, str(level))
                # self.text.config(state=DISABLED)
                if at_bottom:
                    self.text.yview_moveto(1.0)
        except Empty:
            pass
        self.after(50, self._update)

    def append(self, entry, level="INFO"):
        self.queue.put((entry, level))
Ejemplo n.º 3
0
def Show_Configs():

    root = Tk()
    root.title("Configuration")
    root.geometry("700x500+100+100")

    s = Style()
    s.configure('Yellow.TFrame', background='yellow', borderwidth = 5, padding=15, relief='sunken')

    FrameA = Frame(width=450, height=200, style='Yellow.TFrame')
    FrameB = Frame(width=450, height=200)
    
    root.grid_rowconfigure(1, weight=1, pad=5)
    root.grid_columnconfigure(0, weight=1, pad=5)  

    FrameA.grid(row=0, sticky="ew")
    FrameB.grid(row=1, sticky="ew")  

    cfg_space = ScrolledText(FrameA,
                             wrap = 'word',
                             width =30,
                             height = 6,
                             bg = 'beige')
    cfg_space.grid(row=0, column=0, padx=5, pady=5)
    cfg_space.insert('insert', "pile of text \n more text")

    fix_space = ScrolledText(FrameA,
                             wrap = 'word',
                             width =30,
                             height = 6,
                             bg = 'beige')
    fix_space.grid(row=0, column=1)
    fix_space.insert('insert', "hello text \n more text")    

    clr_space = ScrolledText(FrameB,
                             wrap = 'word',
                             width =30,
                             height = 10,
                             bg = 'beige')
    clr_space.grid(row=0, column=0)
    clr_space.insert('insert', "bottom text \n more text")   
    clr_space.config(state='disabled')      

    seq_space = c_ScrolledTextBox(FrameA,6,30,1,0)
    seq_space.Add_Text("\nHello World")

    root.mainloop()
Ejemplo n.º 4
0
    def showskeleton(self):
        self.skel_location = zdracheck.findskeleton(self.fl)
        if os.path.isfile(self.skel_location):
            skelwindow = Toplevel()
            skelwindow.title("Generalised Skeleton")
            skelspec = ScrolledText(skelwindow, wrap=WORD)
            skelspec.pack()
            skelspecif = self.readFile(self.skel_location)
            skelspec.insert(END, skelspecif)
            skelspec.config(state=DISABLED)

        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)
Ejemplo n.º 5
0
 def showgpsa(self):
     self.gpsalocation = totalise.findgpsa(self.fl)
     if os.path.isfile(self.gpsalocation):
         gpsawindow = Toplevel()
         gpsawindow.title("ProofPower Skeleton")
         gpsaspec = ScrolledText(gpsawindow, wrap=WORD)
         gpsaspec.pack()
         gpsaspecif = self.readFile(self.gpsalocation)
         gpsaspec.config(state=NORMAL)
         gpsaspec.insert(END, gpsaspecif)
         gpsaspec.config(state=DISABLED)
     else:
         self.top.config(state=NORMAL)
         self.top.delete(1.0, END)
         self.top.insert(END,
                         "Please convert specification into GPSa first")
         self.top.config(state=DISABLED)
Ejemplo n.º 6
0
 def showIsaSkel(self):
     self.Isalocation = totalise.findisagpsa(self.fl)
     if os.path.isfile(self.Isalocation):
         isawindow = Toplevel()
         isawindow.title("Isabelle Skeleton")
         isaspec = ScrolledText(isawindow, wrap=WORD)
         isaspec.pack()
         isaspecif = self.readFile(self.Isalocation)
         isaspec.config(state=NORMAL)
         isaspec.insert(END, isaspecif)
         isaspec.config(state=DISABLED)
     else:
         self.top.config(state=NORMAL)
         self.top.delete(1.0, END)
         self.top.insert(
             END,
             "Please convert specification into Isabelle Skeleton first")
         self.top.config(state=DISABLED)
Ejemplo n.º 7
0
class SigMsgBox:
    def __init__(self, parent, fnames):
        self.fnames = fnames
        self.parent = parent
        self.top = Toplevel(parent)
        self.result = None

        Label(self.top,
              text="Verify that the size of the signatures is as expected: "
              ).grid(row=0, columnspan=2)

        self.text = ScrolledText(self.top, bg='#D9D9D9', width=32, height=10)
        self.text.config(state=DISABLED)
        self.text.grid(row=1, columnspan=2)

        self.ok_b = Button(self.top, text="OK", command=self.ok)
        self.no_b = Button(self.top, text="No", command=self.cancel)

        self.ok_b.grid(row=2, column=0)
        self.no_b.grid(row=2, column=1)

        self.add_sigs()

    def ok(self):
        self.result = 1
        if self.parent is not None:
            self.parent.focus_set()
        self.destroy()

    def cancel(self):
        self.result = 0
        if self.parent is not None:
            self.parent.focus_set()
        self.destroy()

    def destroy(self):
        self.top.destroy()

    def add_sigs(self):
        self.text.config(state=NORMAL)
        for fname in self.fnames:
            name = os.path.splitext(os.path.split(fname)[1])[0]
            ct = str(map(lambda x: len(x), read_sig_file(fname)))
            self.text.insert(END, name + ' ' + ct + '\n')
        self.text.config(state=DISABLED)
Ejemplo n.º 8
0
class HTMLViewer(Toplevel):
    """ Basic class which provides a scrollable area for viewing HTML
        text and a Dismiss button """
    def __init__(self, htmlcode, title, master=None):

        Toplevel.__init__(self, master)
        #self.protocol('WM_DELETE_WINDOW',self.withdraw)
        self.titleprefix = title
        color = self.config("bg")[4]
        borderFrame = Frame(self, relief=SUNKEN, bd=2)  # Extra Frame
        self.text = ScrolledText(
            borderFrame,
            relief=FLAT,
            padx=3,
            pady=3,
            background='white',
            #background=color,
            #foreground="black",
            wrap='word',
            width=60,
            height=20,
            spacing1=3,
            spacing2=2,
            spacing3=3)
        self.text.pack(expand=1, fill=BOTH)
        #self.text.insert('0.0', text)
        self.text['state'] = DISABLED
        borderFrame.pack(side=TOP, expand=1, fill=BOTH)
        box = Frame(self)
        w = Button(box,
                   text="Dismiss",
                   width=10,
                   command=self.doWithdraw,
                   default=ACTIVE)
        w.pack(side=RIGHT, padx=5, pady=5)
        self.bind("<Return>", self.doWithdraw)
        box.pack(side=BOTTOM, fill=BOTH)
        self.setStyle()
        self.insert(htmlcode)

    def setStyle(self):
        baseSize = 14
        self.text.config(font="Times %d" % baseSize)

        self.text.tag_config('h1', font="Times %d bold" % (baseSize + 8))
        self.text.tag_config('h2', font="Times %d bold" % (baseSize + 6))
        self.text.tag_config('h3', font="Times %d bold" % (baseSize + 4))
        self.text.tag_config('h4', font="Times %d bold" % (baseSize + 2))
        self.text.tag_config('h5', font="Times %d bold" % (baseSize + 1))
        self.text.tag_config('b', font="Times %d bold" % baseSize)
        self.text.tag_config('em', font="Times %d italic" % baseSize)
        self.text.tag_config('pre', font="Courier %d" % baseSize)
        self.text.tag_config('tt', font="Courier %d" % baseSize)

    def doWithdraw(self, event=None):
        # Need to eat optional event so that we can use is in both button and bind callback
        self.withdraw()

    def Update(self, htmlcode, title):
        self.titleprefix = title
        self.insert(htmlcode)

    def insert(self, htmlcode):
        self.text['state'] = NORMAL
        self.text.delete('0.0', END)
        writer = HTMLWriter(self.text, self)
        format = formatter.AbstractFormatter(writer)
        #parser = htmllib.HTMLParser(format)
        parser = MyHTMLParser(format, self.text)
        parser.nofill = False
        parser.feed(htmlcode)
        parser.close()

        self.text['state'] = DISABLED
        if parser.title != None:
            self.title(self.titleprefix + " - " + parser.title)
        else:
            self.title(self.titleprefix)
Ejemplo n.º 9
0
class GUI(object):
    selected_file = None
    file_changes = ""

    def __init__(self, parent, client):
        '''
        :param parent: Tkinter object
        :param client: Client object
        '''

        self.root = parent
        self.client = client

        # load initial setting
        self.text = ScrolledText(self.root, width=50, height=15)
        self.text.grid(row=0, column=2, columnspan=3)

        # Loading the list of files in menu
        self.files_list = Listbox(self.root, height=5)
        self.files_list.grid(column=0, row=0, sticky=(N, W, E, S))

        # Attach scroll to list of files
        self.scrollbar = ttk.Scrollbar(self.root,
                                       orient=VERTICAL,
                                       command=self.files_list.yview)
        self.scrollbar.grid(column=1, row=0, sticky=(N, S))
        self.files_list['yscrollcommand'] = self.scrollbar.set

        ttk.Sizegrip().grid(column=1, row=1, sticky=(S, E))
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_rowconfigure(0, weight=1)

        # Status
        self.status = StringVar()
        self.label = Label(self.root, textvariable=self.status)
        self.set_notification_status("-")

        # Radio button to choose "Access"
        self.label.grid(column=0, columnspan=2, sticky=(W))
        self.access_button_val = StringVar()
        self.public_access = Radiobutton(self.root,
                                         text="Make file public",
                                         variable=self.access_button_val,
                                         value="0",
                                         state=DISABLED,
                                         command=self.onAccessChange)
        self.private_access = Radiobutton(self.root,
                                          text="Make file private",
                                          variable=self.access_button_val,
                                          value="1",
                                          state=DISABLED,
                                          command=self.onAccessChange)
        self.public_access.grid(column=2, row=2, sticky=(E))
        self.private_access.grid(column=3, row=2, sticky=(E))

        # Button check changes
        self.button_check_changes = Button(self.root,
                                           text="Check Changes",
                                           command=self.onCheckChanges)
        self.button_check_changes.grid(column=4, row=2, sticky=(E))

        # Main menu in GUI ----------------------------------------------------------------------------
        self.menu = Menu(self.root)
        self.root.config(menu=self.menu)

        self.menu.add_command(label="New file", command=self.onFileCreation)
        # self.menu.add_command(label="Open", command=self.onOpenFile)
        self.menu.add_command(label="Delete file",
                              state=DISABLED,
                              command=self.onFileDeletion)
        self.menu.add_command(label="Exit", command=self.onExit)

        # Update list of accessible files (request to server)
        self.upload_list_of_accessible_files_into_menu()

        # Start triggers for the first launch
        self.block_text_window()
        self.block_button_check_changes()

        # Add triggers
        # Recognize any press on the keyboard and"Enter" press
        self.text.bind("<Key>", self.onKeyPress)
        self.text.bind("<Return>", self.onEnterPress)

        self.root.protocol('WM_DELETE_WINDOW', self.onExit)
        self.files_list.bind('<<ListboxSelect>>', self.onFileSelection)

    # Triggers in the GUI window ========================================================================
    # ========= Triggers in text area ===================================================================
    def get_index(self, index):
        return tuple(map(int, str(self.text.index(index)).split(".")))

    def onKeyPress(self, event):
        current_file = self.selected_file
        # inserted character and position of change
        char, pos_change = event.char, str(self.text.index("insert"))

        # char = char.encode('utf-8')

        # print repr(char)
        # char = char.encode('utf-8')
        # print repr(char)

        # If any file was chosen
        if current_file:
            # self.count += 1
            # if self.count == 5:
            #     self.text.insert(1.1, "click here!")
            # c, pos = event.char, self.get_index("insert")

            if event.keysym == "BackSpace":
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.BACKSPACE,
                                                  pos_change)
                print "backspace", pos_change

            elif event.keysym == "Delete":
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.DELETE,
                                                  pos_change)
                print "Delete pressed", pos_change
                # self.text.delete(float(pos_change[0]) + .1)

            elif char != "" and event.keysym != "Escape":
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.INSERT,
                                                  pos_change,
                                                  key=char)
                print "pressed", char, pos_change, event.keysym

    def onEnterPress(self, event):
        current_file = self.selected_file

        # If any file was chosen
        if current_file:
            char, pos_change = event.char, str(self.text.index("insert"))

            # "Enter" was pressed
            if char in ["\r", "\n"]:
                self.client.update_file_on_server(current_file,
                                                  CHANGE_TYPE.ENTER,
                                                  pos_change)
                print repr("\n"), self.get_index("insert")
            else:
                print(char)

    # ========= Other triggers ==========================================================================
    def onFileSelection(self, event):
        # Get currently selected file
        widget = self.files_list
        try:
            index = int(widget.curselection()[0])
            selected_file = widget.get(index)
        except:
            selected_file = None

        if selected_file and (not self.selected_file
                              or self.selected_file != selected_file):
            # Update notification bar
            self.set_notification_status("selected file " + selected_file)

            # Save previously opened text file in local storage
            self.save_opened_text()

            # Download selected file
            resp_code, response_data = self.client.get_file_on_server(
                selected_file)

            # Split additional arguments
            am_i_owner, file_access, content = response_data

            # Freeze delete and access buttons
            self.block_delete_button()
            self.block_access_buttons()

            # Case: File was successfully downloaded
            if resp_code == RESP.OK:
                # If I'm owner, then I can delete file and change its access
                if am_i_owner == "1":
                    self.release_delete_button()
                    self.choose_access_button(file_access)
                    self.chosen_access = file_access

                # Unblock and update text window
                self.unblock_text_window()
                self.replace_text(content)

                # Check and write changes in the file (prepare them)
                # When user clicks on the button, then these changes will be shown in the window)
                self.compare_local_copy_with_origin(selected_file,
                                                    original_text=content)
                self.unblock_button_check_changes()

            # Case: Error response from server on file downloading
            else:
                self.clear_text()
                self.block_text_window()

            # Update notification bar
            self.set_notification_status("download file", resp_code)
            # print "Error occurred while tried to download file"

            self.selected_file = selected_file

    def onFileCreation(self):
        ask_file_dialog = DialogAskFileName(self.root)

        # Fetch values from Dialog form
        file_name = ask_file_dialog.file_name

        # Check if the user didn't press cancel
        if file_name:
            access = str(ask_file_dialog.access)  # Private(1) or Public(0)

            # Send request to server to create file
            resp_code = self.client.create_new_file(file_name, access)

            if resp_code == RESP.OK:
                self.save_opened_text()

                # add new file to the list
                self.files_list.insert(END, file_name)

                # Choose access button and activate delete button
                self.release_delete_button()
                self.choose_access_button(access)

            # Update notification bar
            self.set_notification_status("File creation", resp_code)

    # Trigger on switching between access buttons
    def onAccessChange(self):
        curent_access = self.access_button_val.get()
        file_name = self.selected_file

        # Request to the server to change access to the file
        if self.chosen_access != curent_access:
            resp_code = self.client.change_access_to_file(
                file_name, self.chosen_access)

            self.set_notification_status(
                "change access to file " + str(file_name), resp_code)
        self.chosen_access = curent_access

    # Trigger on file deletion button
    def onFileDeletion(self):
        # Send request to server to delete file
        file_name = self.selected_file

        resp_code = self.client.delete_file(file_name)

        # Block window, until user will select the file
        if resp_code == RESP.OK:
            self.remove_file_from_menu_and_delete_local_copy(file_name)

        # Update notification bar
        self.set_notification_status("file deletion", resp_code)

    # def onOpenFile(self):
    #     tk_file = tkFileDialog.askopenfile(parent=root, mode='rb', title='Select a file')
    #
    #     with open('test.txt','w') as f:
    #         f.write(self.text.get(1.0, END))
    #
    #     if tk_file:
    #         contents = tk_file.read()
    #         self.upload_content_into_textfield(contents)
    #         tk_file.close()

    def onCheckChanges(self):
        window = Toplevel(self.root)
        changes_window = ScrolledText(window,
                                      width=50,
                                      height=15,
                                      state="normal")
        changes_window.grid(row=0, column=0)

        # Clear, rewrite and show changes between opened and downloaded file
        changes_window.delete(1.0, "end")
        changes_window.insert(END, self.file_changes)

    def onExit(self):
        if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
            # save opened text in window
            self.save_opened_text()
            self.root.destroy()

    # Functions to work with interface ==================================================================
    def compare_local_copy_with_origin(self, local_file_name, original_text):
        '''
        :param local_file_name: File that may locate on the client side
        :param original_text: original content on the server
        :return: (Boolean) True - if the texts are the same
        '''
        local_file_path = os.path.join(client_files_dir, local_file_name)

        # If local copy of the file exists, then compare copies
        if os.path.isfile(local_file_path):
            with open(local_file_path, "r") as lf:
                local_content = lf.read()

            if local_content == original_text:
                self.file_changes = "Information is the same as in local copy"

            else:
                self.file_changes = "Information doesn't match!\n"

                local_content, original_text = local_content.strip(
                ).splitlines(), original_text.strip().splitlines()

                # Write mismatches and mismatches
                for line in difflib.unified_diff(local_content,
                                                 original_text,
                                                 lineterm=''):
                    self.file_changes += line + "\n"

        else:
            self.file_changes = "Local copy was not found"

    def upload_list_of_accessible_files_into_menu(self):
        resp_code, accessible_files = self.client.get_accessible_files()
        # accessible_files = []
        # resp_code = 0

        for filename in accessible_files:
            self.files_list.insert(END, filename)

        # Update notification bar
        self.set_notification_status("List of files", resp_code)

    # Save previously opened text file in local storage
    def save_opened_text(self):
        if self.selected_file is not None:
            ps_file_path = os.path.join(client_files_dir, self.selected_file)

            with open(ps_file_path, "w") as f:
                content = self.get_text()
                content = content.encode('utf-8')
                print repr(content)
                f.write(content)

    def get_text(self):
        contents = self.text.get(1.0, Tkinter.END)

        # Tkinter adds \n in the text field. That's why we should deduct it.
        contents = contents[:len(contents) - len("\n")]

        return contents

    def set_text(self, info):
        self.text.insert(END, info)

    def replace_text(self, content):
        self.clear_text()
        self.set_text(content)

    def clear_text(self):
        self.text.delete(1.0, "end")

    def block_text_window(self):
        # block text area
        self.text.config(state=DISABLED, background="gray")

    def unblock_text_window(self):
        self.text.config(state=NORMAL, background="white")

    # Delete button block
    def block_delete_button(self):
        self.menu.entryconfigure("Delete file", state="disabled")

    # Delete button release
    def release_delete_button(self):
        self.menu.entryconfigure("Delete file", state="normal")

    # Block and reset Access radio buttons
    def block_access_buttons(self):
        self.public_access.configure(state="disabled")
        self.private_access.configure(state="disabled")

    # Update Access radio buttons
    def choose_access_button(self, file_access):
        # Unfreeze buttons if they're not active
        self.public_access.configure(state="normal")
        self.private_access.configure(state="normal")

        # Select current access to file in radio button
        if file_access == ACCESS.PRIVATE:
            self.private_access.select()

        elif file_access == ACCESS.PUBLIC:
            self.public_access.select()

    # (un)Block the button "check changes"
    def block_button_check_changes(self):
        self.button_check_changes.config(state=DISABLED)

    def unblock_button_check_changes(self):
        self.button_check_changes.config(state=NORMAL)

    def set_notification_status(self, message, err_code=None):
        if err_code:
            message += ".\n" + error_code_to_string(err_code)

        self.status.set("Last action: " + message)

    # NOTIFICATION UPDATES (From server) ===============================================================
    # ======== Some change was made in file by another client ==========================================
    def notification_update_file(self, change):
        '''
        Another client made the change => update text window
        :param change: (string) in format
        '''

        # Parse change that arrived from server
        # position is in format "row.column"
        file_to_change, change_type, pos, key = parse_change(
            change, case_update_file=True)

        # And check whether the selected file matches with file in change
        if self.selected_file and self.selected_file == file_to_change:
            # Depending on change, do the change

            if change_type == CHANGE_TYPE.DELETE:
                self.text.delete(pos)

            elif change_type == CHANGE_TYPE.BACKSPACE:
                splitted_pos = pos.split(".")
                row, column = int(splitted_pos[0]), int(splitted_pos[1])

                if row - 1 > 0 and column == 0:
                    # Get last index in previous line, and delete it
                    pr_pos = str(row - 1) + ".0"
                    pr_line_last_len = len(self.text.get(pr_pos, pos))
                    last_index = str(row - 1) + "." + str(pr_line_last_len)

                    self.text.delete(last_index)
                elif column > 0:
                    pos_to_del = str(row) + "." + str(column - 1)
                    self.text.delete(pos_to_del)

            elif change_type == CHANGE_TYPE.ENTER:
                self.text.insert(pos, "\n")

            elif change_type == CHANGE_TYPE.INSERT:
                self.text.insert(pos, key)

            # print file_to_change, change_type, pos, key
            self.set_notification_status("another user changed the file")

    # ======== Another client created a document with public access ====================================
    def notification_file_creation(self, change):
        file_name = parse_change(change)
        file_name = file_name[0]

        # Update file list
        self.files_list.insert(END, file_name)

        # Update notification bar
        self.set_notification_status(
            "another client created file with public access")

    # ======== Another client deleted a document =======================================================
    def notification_file_deletion(self, change):
        '''
        :param change: (string) contain file
        '''
        deleted_file = parse_change(change)
        deleted_file = deleted_file[0]

        # Delete file from menu and its local copy and block the window if current=changed_file
        notification = "owner deleted file " + str(deleted_file)
        self.remove_file_from_menu_and_delete_local_copy(
            deleted_file, notification)

    # ======== Another client changed the access to the file (made it private/public) ==================
    def notification_changed_access_to_file(self, change):
        file_name, access = parse_change(change)

        # Owner changed access to file to Private status
        if access == ACCESS.PRIVATE:
            notification = "another client changed access file " + str(
                file_name) + " to private"
            notification += ". Local copy deleted"

            # Delete file from menu and its local copy and block the window if current=changed_file
            self.remove_file_from_menu_and_delete_local_copy(
                file_name, notification)

            # Freeze some buttons (access/delete/text)
            self.set_state_after_deletion()

        # Owner changed access to file to Public status
        elif access == ACCESS.PUBLIC:
            # Add file to the end of list of files
            self.files_list.insert(END, file_name)

            notification = "another client opened access to file " + str(
                file_name)
            self.set_notification_status(notification)

    # OTHER FUNCTIONS ==================================================================================
    # Reset states after deletion
    def set_state_after_deletion(self):
        self.clear_text()
        self.block_delete_button()
        self.block_access_buttons()
        self.block_text_window()
        self.selected_file = None
        self.block_button_check_changes()

    # Delete file from menu and its local copy (if exists)
    def remove_file_from_menu_and_delete_local_copy(self,
                                                    file_name,
                                                    notification=None):
        '''
        :param file_name: (string) file that should ne deleted
        :param notification: (string)
            optional param. Will update status bar, if the deletion was performed
        :return: (Boolean) True if file deletion was performed
        '''
        wasFileRemoved = False

        files_in_menu = self.files_list.get(0, END)

        if file_name in files_in_menu:
            for index, file_in_menu in enumerate(files_in_menu):
                if file_name == file_in_menu:
                    # Delete file from menu
                    self.files_list.delete(index)

                    # Update status bar
                    if notification:
                        self.set_notification_status(notification)

                    wasFileRemoved = True
                    break

        # Delete local copy of the file
        self.client.delete_local_file_copy(file_name)

        # Check if deleted file is currently opened in the text window
        if self.selected_file and self.selected_file == file_name:
            # Change states for some buttons (as after deletion)
            self.set_state_after_deletion()

            # Set prev. selected file to None to avoid conflicts (when user presses on keys)
            self.selected_file = None

        return wasFileRemoved
Ejemplo n.º 10
0
class PatchClampGUI(Frame):
    """
    Simple GUI for the patch clamp robot.
    Controls:
        conect/disconnect robot (controller, arm, camera, amplifier and pump to be specified)
        Launch auto calibration
        Load previous calibration
        Set position to Zero
        Positionning pipette when left clicking on camera window
        Patch (and clamp if enable) at given position by right clicking on camera window
        Enable/disable clamp when right clicking
        Clamping
        Enable/disable pipette following the camera
        Enable/disable resistance metering
        Check pipette resistance for patch
    """
    def __init__(self, master=None):
        Frame.__init__(self, master)

        # State variables
        self.pause = 0
        self.calibrated = 0

        # Variables for manipulator, microscope
        self.robot = None
        self.controller = None
        self.arm = None
        self.camera = None
        self.amplifier = None
        self.pump = None
        self.continuous = IntVar()
        self.follow = IntVar()

        # GUI

        # Connection to robot
        self.robot_box = LabelFrame(self, text='Connection')
        self.robot_box.grid(row=0, column=0, padx=5, pady=5)

        # Controller
        self.ask_controller = Label(self.robot_box, text='Controller: ')
        self.ask_controller.grid(row=0, column=0, padx=2, pady=2)

        self.controllist = ttk.Combobox(self.robot_box,
                                        state='readonly',
                                        values='SM5 SM10')
        self.controllist.grid(row=0, column=1, columnspan=2, padx=2, pady=2)

        # Arm
        self.ask_arm = Label(self.robot_box, text='Arm: ')
        self.ask_arm.grid(row=1, column=0, padx=2, pady=2)

        self.armlist = ttk.Combobox(self.robot_box,
                                    state='readonly',
                                    values='dev1 dev2 Arduino')
        self.armlist.grid(row=1, column=1, columnspan=2, padx=2, pady=2)

        # Camera
        self.ask_camera = Label(self.robot_box, text='Camera: ')
        self.ask_camera.grid(row=2, column=0, padx=2, pady=2)

        self.camlist = ttk.Combobox(self.robot_box,
                                    state='readonly',
                                    values='Hamamatsu Lumenera')
        self.camlist.grid(row=2, column=1, columnspan=2, padx=2, pady=2)

        # Amplifier
        self.ask_amp = Label(self.robot_box, text='Amplifier: ')
        self.ask_amp.grid(row=3, column=0, padx=2, pady=2)

        self.amplist = ttk.Combobox(self.robot_box,
                                    state='readonly',
                                    values='FakeAmplifier Multiclamp')
        self.amplist.grid(row=3, column=1, columnspan=2, padx=2, pady=2)

        # Pump for pressure control
        self.ask_pump = Label(self.robot_box, text='Pump: ')
        self.ask_pump.grid(row=4, column=0, padx=2, pady=2)

        self.pumplist = ttk.Combobox(self.robot_box,
                                     state='readonly',
                                     values='FakePump OB1')
        self.pumplist.grid(row=4, column=1, columnspan=2, padx=2, pady=2)

        # Connection button
        self.connection = Button(self.robot_box,
                                 text='Connect',
                                 command=self.connect,
                                 bg='green',
                                 fg='white')
        self.connection.grid(row=5, column=0, padx=2, pady=2)

        # disconnection button
        self.disconnection = Button(self.robot_box,
                                    text='Disconnect',
                                    command=self.disconnect,
                                    state='disable')
        self.disconnection.grid(row=5, column=1, padx=2, pady=2)

        # Top right frame
        self.tr = LabelFrame(self, bd=0)
        self.tr.grid(row=0, column=1, padx=2, pady=2)

        # Auto calibration
        self.calibrate_box = LabelFrame(self.tr, text='Calibration')
        self.calibrate_box.grid(row=0, column=0, padx=2, pady=2)

        # Begin calibration button
        self.calibrate = Button(self.calibrate_box,
                                text='Calibrate',
                                command=self.calibration,
                                state='disable')
        self.calibrate.grid(row=0, column=0, padx=2, pady=2)

        # Load the previous calibration button
        self.load_calibrate = Button(self.calibrate_box,
                                     text='Load calibration',
                                     command=self.load_cali,
                                     state='disable')
        self.load_calibrate.grid(row=0, column=1, padx=2, pady=2)

        # Message to indicate if robot is calibrated or not
        self.calibrate_msg = Label(self.calibrate_box,
                                   text='Robot is NOT calibrated !',
                                   fg='red')
        self.calibrate_msg.grid(row=1, column=0, padx=2, pady=2, columnspan=3)

        # PUMP
        self.pump_box = LabelFrame(self.tr, text='Pressure controller')
        self.pump_box.grid(row=1, column=0, padx=2, pady=2)

        # Patch button
        self.patch = Button(self.pump_box, text='Seal', state='disable')
        self.patch.grid(row=0, column=0, padx=2, pady=2)

        # Clamp button
        self.clamp = Button(self.pump_box, text='Break-in', state='disable')
        self.clamp.grid(row=0, column=1, padx=2, pady=2)

        # Nearing button
        self.nearing = Button(self.pump_box, text='Nearing', state='disable')
        self.nearing.grid(row=0, column=2, padx=2, pady=2)

        # High pressure
        self.push = Button(self.pump_box, text='Push', state='disable')
        self.push.grid(row=0, column=3, padx=2, pady=2)

        # Clamp when right click on/off
        self.clamp_switch = Checkbutton(self.pump_box,
                                        text='Break-in when clicking',
                                        command=self.enable_clamp,
                                        state='disable')
        self.clamp_switch.grid(row=1, column=0, padx=2, pady=2, columnspan=2)

        # release button
        self.release = Button(self.pump_box, text='Release', state='disable')
        self.release.grid(row=1, column=2, padx=2, pady=2)

        # Control of amplifier
        self.meter_box = LabelFrame(self, text='Metering')
        self.meter_box.grid(row=1, column=1, padx=2, pady=2)

        # Selection of meter: potential or resistance
        self.chosen_meter = IntVar()
        self.choose_resistance = Radiobutton(self.meter_box,
                                             text='Resistance metering',
                                             variable=self.chosen_meter,
                                             value=1,
                                             command=self.switch_meter)
        self.choose_resistance.select()
        self.choose_resistance.grid(row=0, column=0, padx=2, pady=2)

        self.choose_potential = Radiobutton(self.meter_box,
                                            text='Potential metering',
                                            variable=self.chosen_meter,
                                            value=2,
                                            command=self.switch_meter)
        self.choose_potential.grid(row=0, column=1, padx=2, pady=2)

        # display resistance
        self.res_window = Label(self.meter_box, text='Resistance: ')
        self.res_window.grid(row=1, column=0, padx=2, pady=2)

        self.res_value = Label(self.meter_box, text='0 Ohm')
        self.res_value.grid(row=1, column=1, padx=2, pady=2)

        self.potential_window = Label(self.meter_box, text='Potential')
        self.potential_window.grid(row=2, column=0, padx=2, pady=2)

        self.potential_value = Label(self.meter_box, text='0 V')
        self.potential_value.grid(row=2, column=1, padx=2, pady=2)

        # Check the resistance of the pipette for patching button

        # continuous resistance metering on/off
        self.continuous_meter = Checkbutton(
            self.meter_box,
            text='Continuous metering',
            variable=self.continuous,
            command=self.switch_continuous_meter,
            state='disable')
        self.continuous_meter.grid(row=3, column=0, padx=2, pady=2)

        self.check_pipette_resistance = Button(self.meter_box,
                                               text='Check pipette',
                                               command=self.init_patch_clamp,
                                               state='disable')
        self.check_pipette_resistance.grid(row=3, column=1, padx=2, pady=2)

        # Other controls
        self.misc = LabelFrame(self, text='misc')
        self.misc.grid(row=1, column=0, padx=2, pady=2)

        # reset postion
        self.zero = Button(self.misc,
                           text='Go to zero',
                           command=self.reset_pos,
                           state='disable')
        self.zero.grid(row=0, column=0, padx=2, pady=2)

        # Save position
        self.save_pos = Button(self.misc,
                               text='Save position',
                               state='disable')
        self.save_pos.grid(row=0, column=1, padx=2, pady=2)

        # Pipette follow camera on/off
        self.switch_follow = Checkbutton(self.misc,
                                         text='Following',
                                         command=self.following,
                                         variable=self.follow,
                                         state='disable')
        self.switch_follow.grid(row=1, column=0, padx=2, pady=2)

        self.offset_slide = Scale(self.misc, from_=0, to=20, orient=HORIZONTAL)
        self.offset_slide.set(2)
        self.offset_slide.grid(row=1, column=1, padx=2, pady=2)

        self.follow_paramecia = IntVar()
        self.paramecia = Checkbutton(self.misc,
                                     text='paramecia',
                                     variable=self.follow_paramecia,
                                     command=self.switch_follow_paramecia,
                                     state='disable')
        self.paramecia.grid(row=2, column=0, padx=2, pady=2)

        self.screenshots = Button(self.misc,
                                  text='Screenshot',
                                  state='disable')
        self.screenshots.grid(row=2, column=1, padx=2, pady=2)

        # Messages zone
        self.text_zone = ScrolledText(master=self,
                                      width=60,
                                      height=10,
                                      state='disabled')
        self.text_zone.grid(row=2, column=0, columnspan=3)

        # Quit button
        self.QUIT = Button(self,
                           text='QUIT',
                           bg='orange',
                           fg='white',
                           command=self.exit)
        self.QUIT.grid(row=3, column=0, padx=2, pady=2)

        # Stop button
        self.emergency_stop = Button(self,
                                     text='STOP',
                                     bg='red',
                                     fg='white',
                                     command=self.stop_moves)
        self.emergency_stop.grid(row=3, column=1, padx=2, pady=2)

        self.message = ''

        self.pack()

    def connect(self):
        """
        Connect to the robot
        """
        # Devices to connect to
        self.controller = self.controllist.get()
        self.arm = self.armlist.get()
        self.amplifier = self.amplist.get()
        self.pump = self.pumplist.get()
        self.camera = self.camlist.get()

        # Checking primordial devices have been specified: controller, arm and camera
        if not self.controller:
            showerror('Connection error', 'Please specify a controller.')
        elif not self.arm:
            showerror('Connection error',
                      'Please specify a device for the arm.')
        elif not self.camera:
            showerror('Connection error', 'Please specify a camera.')
        else:
            # Connection to the robot
            self.robot = PatchClampRobot(self.controller, self.arm,
                                         self.camera, self.amplifier,
                                         self.pump, False)

            # Setting messages
            self.message = self.robot.message

            # Disable connection buttons and lists
            self.controllist['state'] = 'disabled'
            self.armlist['state'] = 'disabled'
            self.amplist['state'] = 'disabled'
            self.camlist['state'] = 'disabled'
            self.pumplist['state'] = 'disabled'
            self.connection.config(state='disable')

            # Activate all the others buttons
            self.load_calibrate.config(state='normal')
            self.calibrate.config(state='normal')
            self.zero.config(state='normal')
            self.disconnection.config(state='normal')
            self.continuous_meter.config(state='normal')
            self.check_pipette_resistance.config(state='normal')
            self.patch.config(state='normal', command=self.robot.pressure.seal)
            self.release.config(state='normal',
                                command=self.robot.pressure.release)
            self.nearing.config(state='normal',
                                command=self.robot.pressure.nearing)
            self.push.config(state='normal',
                             command=self.robot.pressure.high_pressure)
            self.clamp.config(state='normal', command=self.robot.clamp)
            self.clamp_switch.config(state='normal')
            self.switch_follow.config(state='normal')
            self.save_pos.config(state='normal',
                                 command=self.robot.save_position)
            self.paramecia.config(state='normal')
            self.screenshots.config(state='normal',
                                    command=self.robot.save_img)

            # Checking changes of robot messages and display them
            self.check_message()
        pass

    def disconnect(self):
        """
        Disconnect the robot. For now reconnection doesn't work (controller not really disconnected)
        :return: 
        """
        # stoping threads linked to the robot
        self.robot.stop()
        del self.robot
        self.robot = None

        # Disable all buttons and enable connection buttons
        self.calibrate.config(state='disable')
        self.load_calibrate.config(state='disable')
        self.zero.config(state='disable')
        self.controllist['state'] = 'readonly'
        self.armlist['state'] = 'readonly'
        self.amplist['state'] = 'readonly'
        self.camlist['state'] = 'readonly'
        self.pumplist['state'] = 'readonly'
        self.connection.config(state='normal')
        self.disconnection.config(state='disable')
        self.check_pipette_resistance.config(state='disable')
        self.clamp.config(state='disable', command=None)
        self.patch.config(state='disable', command=None)
        self.release.config(state='disable', command=None)
        self.nearing.config(state='disable', command=None)
        self.push.config(state='disable', command=None)
        self.save_pos.config(state='disable', command=None)
        self.clamp_switch.config(state='disable')
        self.switch_follow.config(state='disable')
        pass

    def calibration(self):
        """
        Launch auto calibration
        :return: 
        """
        if self.robot:
            # Connection to the robot has been established
            if askokcancel(
                    'Calibrating',
                    'Please put the tip of the pipette in focus and at the center of the image.',
                    icon=INFO):
                # Pipette in focus and centered: calibrating
                self.robot.event['event'] = 'Calibration'
                self.wait_calibration()
            pass

    def wait_calibration(self):
        if self.robot.event['event'] == 'Calibration':
            self.after(10, self.wait_calibration)
        elif self.robot.calibrated:
            self.calibrate_msg.config(text='Robot calibrated', fg='black')

    def load_cali(self):
        """
        Loads previous calibration
        :return: 
        """
        if self.robot:
            # Connection to the robot has been established
            if askokcancel(
                    'Loading calibration',
                    'Please put the tip of the pipette in focus and at the center of the image.',
                    icon=INFO):
                # Pipette in focus and centered: loading calibration
                self.robot.load_calibration()
                if self.robot.calibrated:
                    self.calibrate_msg.config(text='Robot calibrated',
                                              fg='black')
            pass

    def reset_pos(self):
        """
        Reset position to null position
        :return: 
        """
        if self.robot:
            self.robot.go_to_zero()
        pass

    def get_res(self):
        """
        Retrieve the resistance metered by robot.
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.res_value['text'] = self.robot.get_resistance(res_type='text')
            with open('Resistance.txt', 'at') as f:
                f.write(str(self.robot.get_resistance()) + '\n')
            if self.continuous.get():
                # Retrieving continuoulsy enabled
                if (self.chosen_meter.get() == 1) | (
                        self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_resistance.select()
                    self.after(10, self.get_res)
                elif (self.chosen_meter.get() == 2) | (
                        not self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_potential.select()
                    self.after(10, self.get_pot)
        pass

    def get_pot(self):
        """
        Retrieve the resistance metered by robot.
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.potential_value['text'] = self.robot.get_potential(
                res_type='text')
            if self.continuous.get():
                # Retrieving continuoulsy enabled
                if (self.chosen_meter.get() == 1) | (
                        self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_resistance.select()
                    self.after(10, self.get_res)
                elif (self.chosen_meter.get() == 2) | (
                        not self.robot.amplifier.get_meter_resist_enable()):
                    self.choose_potential.select()
                    self.after(10, self.get_pot)
        pass

    def init_patch_clamp(self):
        """
        Checks if conditions for patching are met (pipette resistance)
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.choose_resistance.select()
            if self.robot.init_patch_clamp():
                # Conditions are met, enable continous resistance metering
                self.continuous_meter.select()
                self.choose_resistance.select()
                self.switch_continuous_meter()
                file_res = open('Resistance.txt', 'wt')
                file_res.close()
        pass

    def enable_clamp(self):
        """
        Enable/disable calmp when right clicking on the camera window
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.robot.enable_clamp ^= 1
        pass

    def switch_continuous_meter(self):
        """
        Enable/Disable continuous resistance metering
        :return: 
        """
        if self.robot:
            if self.continuous.get():
                # Continuous metering button is checked, activate continuous metering
                self.robot.set_continuous_meter(True)

                if self.chosen_meter.get() == 1:
                    self.get_res()
                elif self.chosen_meter.get() == 2:
                    self.get_pot()
            else:
                # Continuous metering button unchecked, deactivate continuous metering
                self.robot.set_continuous_meter(False)
        pass

    def switch_meter(self):
        if self.robot:
            if self.chosen_meter.get() == 1:
                self.robot.amplifier.meter_resist_enable(True)
            elif self.chosen_meter.get() == 2:
                self.robot.amplifier.meter_resist_enable(False)

    def following(self):
        """
        Enable/disable pipette following the camera 
        :return: 
        """
        if self.robot:
            # Connection of robot established, enable folowing if follow button is checked
            self.robot.following = self.follow.get()
        pass

    def switch_follow_paramecia(self):
        if self.robot:
            self.robot.follow_paramecia = self.follow_paramecia.get()

    def check_message(self):
        """
        Retrieve messages from robot and display them when they change
        :return: 
        """
        if self.robot:
            # Connection of robot established
            self.robot.offset = self.offset_slide.get()
            if self.message != self.robot.message:
                # Message memory is different from actual robot message
                self.message = self.robot.message
                if self.message[:5] == 'ERROR':
                    # The new message is an error, display the message in a new window
                    showerror('ERROR', self.message)

                # Activate the message zone, write the message and deactivate message zone (thus make a read only)
                self.text_zone.config(state='normal')
                self.text_zone.insert(INSERT, self.message + '\n')
                self.text_zone.config(state='disabled')
                self.text_zone.see(END)

                # Update memory and actual message: if same messages follow each other, both are retrieve
                self.message = ''
                self.robot.message = ''

            # Check again in 10ms
            self.after(10, self.check_message)
        pass

    def stop_moves(self):
        if self.robot:
            self.robot.arm.stop()
            self.robot.microscope.stop()

    def exit(self):
        """
        Close GUI and all threads
        :return: 
        """
        if self.robot:
            # Connection of robot established, disconnecting
            self.robot.stop()
            del self.robot
        # quit GUI
        self.quit()
Ejemplo n.º 11
0
class skulltagBotWindow(Frame):
	def __init__(self, args='', parent=None):
		Frame.__init__(self, parent)
		
		self.args = args
		self.flags = [0,0,0,0,0]
		self.history = []
		self.players = {'amount': 0}
		self.historyMarker = 0
		self.playerinfoRE = re.compile("([0-9]+)\. ([^%]+?) - IP \(([0-9\.]+:[0-9]+)\)")
		
		for flag, index in (('+dmflags', 0), ('+dmflags2', 1), ('+dmflags3', 2), ('+compatflags', 3), ('+compatflags2', 4)):
			if flag in self.args:
				try:
					self.flags[index] = int(self.args[self.args.index(flag)+1])
				except:
					pass
		
		self.outputText = ScrolledText()
		self.outputText.config(state=DISABLED)
		self.outputText.pack(expand=1, fill='both', anchor='n')
		self.inputTextText = StringVar()
		self.inputText = Entry(textvariable=self.inputTextText)
		self.inputText.bind('<Return>', self.writeLine)
		self.inputText.bind('<Up>', self.upOneHist)
		self.inputText.bind('<Down>', self.downOneHist)
		self.inputText.pack(fill='x', anchor='s')
		self.outputText.tk.call('tk', 'scaling', 1)
		
		self.outputQueue = Queue.Queue()		# just to be orderly
		self.inputQueue = Queue.Queue()			# same
		self.inQLock = thread.allocate_lock()	# well durrrrrr
		self.outQLock = thread.allocate_lock()
		
		thread.start_new(self.startSkulltag, (None,))
		
		self.pack()
	
	def startSkulltag(self, deadArg):
		self.skulltag = subprocess.Popen(['/usr/games/skulltag/skulltag-server', '+sv_markchatlines 1']+self.args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=0)
		self.stdinPoll = select.poll()
		self.stdinPoll.register(self.skulltag.stdout, select.POLLIN)
		self.stdoutPoll = select.poll()
		self.stdoutPoll.register(self.skulltag.stdout, select.POLLOUT)
		thread.start_new(self.rwLoop, (None,))
	
	def rwLoop(self, deadArg):
		self.readLine()
		try:										#check for input
			output = self.inputQueue.get(block=0)
		except Queue.Empty:
			pass
		else:
			self.inQLock.acquire()
			self.outputText.config(state=NORMAL)
			self.outputText.insert(END, output)		#put it in the main window
			self.outputText.scan_mark(100000, 1)
			self.outputText.scan_dragto(10, 1)
			try:
				lscbot = stbehaviour.LSCParserBot(output, copy.deepcopy(self.players), *self.flags[:])
				chatText = lscbot.get()
						
				if chatText[0]:
					self.skulltag.stdin.flush()
					self.skulltag.stdin.write("say " + chatText[0] + '\n')
				
				self.flags = chatText[2:]
			except:
				import traceback
				print "%s\n%s" % (sys.exc_info()[0], sys.exc_info()[1])
				print traceback.print_tb(sys.exc_info()[2])
				self.cquit()
			self.outputText.config(state=DISABLED)
			self.inQLock.release()
		
		try:										#now for output
			output = self.outputQueue.get(block=0)
		except Queue.Empty:
			pass
		else:
			self.outQLock.acquire()
			self.skulltag.stdin.write(output)
			self.skulltag.stdin.flush()
			self.outQLock.release()
		self.after(5, self.rwLoop, (None,))
	
	def readLine(self):
		output = ''
		scrollAmount = 0
		if self.skulltag.poll():
			output = '\n\n - Terminated - '
			sys.exit()
		else:
			pollin = self.stdinPoll.poll(1)
			while pollin:
				pollin = pollin[0]
				if pollin[1] == 1:
					self.skulltag.stdout.flush()
					output += self.skulltag.stdout.readline()
					scrollAmount += 1
				pollin = self.stdinPoll.poll(1)
		
		if output == 'NETWORK_LaunchPacket: Permission denied\n' or output == 'NETWORK_LaunchPacket: Address 192.168.1.255:15101\n':
			output = ''
		
		if output:
			self.outputText.yview_scroll(16*((len(output)/80)+1)+(scrollAmount*16), 'pixels')
			
		self.inputQueue.put(output)
	
	def upOneHist(self, deadArg):
		if self.historyMarker <= -len(self.history):
			return
		
		self.historyMarker -= 1
		self.inputText.delete(0, END)
		self.inputText.insert(END, self.history[self.historyMarker])
		
	def downOneHist(self, deadArg):
		if self.historyMarker >= -1:
			self.inputText.delete(0, END)
			self.historyMarker = 0
			return
		
		self.historyMarker += 1
		self.inputText.delete(0, END)
		self.inputText.insert(END, self.history[self.historyMarker])
		
	def writeLine(self, deadArg):
		self.inputText.insert(END, ' ')
		output = self.inputTextText.get()
		self.history += [output[:-1]]
		self.historyMarker = 0
		if output[0] == ':':
			output = 'say ' + output[1:]
		if output.strip() == 'reset_lscbot':
			self.inputText.delete(0, END)
			self.skulltag.stdin.write("say Resetting the LSC Bot - should be a second\n")
			self.skulltag.stdin.flush()
			reload(stbehaviour)
			self.skulltag.stdin.write("say or less\n")
			self.skulltag.stdin.flush()
		else:
			self.inputText.delete(0, END)
			self.outputQueue.put(output)
				
		
	def cquit(self):
		for i in range(32):
			self.skulltag.stdin.write("kick_idx %s \" -- Server quit by host -- \"\n" % (i + 1))
			self.skulltag.stdin.flush()
		self.skulltag.stdin.write("error_fatal \"-- Server quit by host --\"")
		time.sleep(1)
		self.skulltag.terminate()
		self.quit()
import pyautogui


lineColPosList=[]




def callback(event):
    lineColPosList = textPad.index(CURRENT).split('.')
    print textPad.index(CURRENT)
    status["text"]="Line" + lineColPosList[0] + " Column " + lineColPosList[1]
    
root = tk.Tk(className="Intelligent Code Editor")
textPad = ScrolledText(root, width=500, height=100,fg="white",bg="black")
textPad.config(font=("Arial",15),insertbackground="white")
lineColPosList = textPad.index(CURRENT).split('.')

textPad.bind("<Button-1>", callback)
textPad.bind("<Key>", callback)
textPad.focus()
status = Label(root, text="Line" + lineColPosList[0] + " Column " + lineColPosList[1], bd=1, relief=SUNKEN, anchor=W) 
status.pack(side=BOTTOM, fill=X)

def replaceText(inputText):
    inputText = inputText.replace('of','[]')
    inputText = inputText.replace('function','')
    inputText = inputText.replace('increment','')
    inputText = inputText.replace('initialize','')
    inputText = inputText.replace('condition','')
    inputText = inputText.replace('math','')
Ejemplo n.º 13
0
    def initialisation(self):
        global input_pipe
        global output_pipe
        if len(sys.argv) > 2:
            print 'output_pipe : ', output_pipe
        global ChaineALire
        global st
        global fp
        global sortieTube
        global entreeTube

        def click_python(event):
            st.insert(END, '\nVous avez cliquez sur Python')

        def affiche_message():
            global output_pipe
            message = entre.get()

            #openning the OUTPUT pipe
            if len(sys.argv
                   ) > 2:  #if an output pipe was given as the second argument
                try:
                    assert output_pipe != ''
                    #opening the pipe
                    try:
                        entreeTube = os.open(output_pipe, os.O_WRONLY)
                        if entreeTube == -1:
                            raise ValueError
                        os.write(entreeTube, message)
                        #st.insert(END,'\n'+message,'rouge')
                    except ValueError:
                        showerror('Error', "Could not open Output pipe")
                except AssertionError:
                    showerror("Error", "You must choose an output pipe first")
                    output_pipe = tkFileDialog.askopenfilename(
                        title='Choose the output pipe to open',
                        defaultextension='.fifo')

        texte = """ Welcome in GUI for ARINC 653 Partition """

        #on cree un fenetre principale 'fp' a� partir du 'modele' Tk
        #fp = Tk()
        #self.title('ARINC 653 function')
        self.title('ARINC 653 function : ' + sys.argv[3])

        #Creation d'un panneau 'menu_top' insere dans 'fp'
        menu_top = Frame(self, borderwidth=2)
        menu_top.pack(side='bottom', fill='x')

        #Creation d'une etiquette inseree dans 'menu_top'
        etiquette = Label(menu_top, text='Commande : ')
        etiquette.pack(side='left')

        #Creation d'un boutton dans 'menu_top'
        b = Button(menu_top, text='execute', command=affiche_message)
        b.pack(side='right')

        #Creation d'un boite d'edition dans 'nenu_top'
        entre = Entry(menu_top, width=20, relief='sunken')
        entre.insert(END, 'Texte a afficher')
        entre.pack(side='left', fill='x', expand='true')

        #Declaration du texte deroulant dans 'fp'
        st = ScrolledText(self)
        st.pack(expand=1, fill='both', side='top')

        #on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
        st.insert(END, texte)
        #on applique a� tout le texte la police par defaut
        st.config(font='Arial 12 bold')
        st.config(foreground='Black')
        #on configure le fond du 'texte derouant'

        if ((sys.argv[3] == "Master") or (sys.argv[3] == "Partition1")
                or (sys.argv[3] == "Primary")):
            st.config(background='LightYellow')
        elif ((sys.argv[3] == "Slave") or (sys.argv[3] == "Partition2")
              or (sys.argv[3] == "Backup")):
            st.config(background='LightGreen')
        #e = Entry(st,width=25)
        elif ((sys.argv[3] == "Leica") or (sys.argv[3] == "Partition3")
              or (sys.argv[3] == "Capteur")):
            st.config(background='misty rose')
        else:
            st.config(background='PeachPuff')
        try:
            assert input_pipe != ''

        except AssertionError:
            showerror('Info', "choisissez un chemin de tube")
            input_pipe = tkFileDialog.askopenfilename(
                title='Choose the input pipe to open',
                defaultextension='.fifo')

        #openning the INPUT pipe
        try:
            assert input_pipe != ''

            try:

                #			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
                sortieTube = os.open(input_pipe, os.O_RDONLY)
                if sortieTube == -1:
                    raise ValueError
            except ValueError:
                showerror('Error', "fail to open the Input pipe's output")
        except AssertionError:
            showerror("Error", "You must choose a pipe first")

        #openning the OUTPUT pipe
        if len(sys.argv
               ) > 2:  #if an output pipe was given as the second argument
            try:
                assert output_pipe != ''

                #opening the pipe
                try:
                    entreeTube = os.open(output_pipe, os.O_WRONLY)

                    if entreeTube == -1:
                        raise ValueError
                except ValueError:
                    showerror('Error', "Could not open Output pipe")
            except AssertionError:
                showerror("Error", "You must choose an output pipe first")
                output_pipe = tkFileDialog.askopenfilename(
                    title='Choose the output pipe to open',
                    defaultextension='.fifo')

        #Positionnement de la fenetre dans l'ecran
        ScreenSizeX = self.winfo_screenwidth()  # Get screen width [pixels]
        ScreenSizeY = self.winfo_screenheight()  # Get screen height [pixels]
        CorrectionX = 30
        CorrectionY = 30
        FrameSizeX = int(ScreenSizeX * 0.5) - CorrectionX
        FrameSizeY = int(ScreenSizeY * 0.5) - CorrectionY

        if ((sys.argv[3] == "Master")
                or (sys.argv[3]
                    == "Partition1")):  # Find left and up border of window
            FramePosX = 0
            FramePosY = 0
        elif ((sys.argv[3] == "Slave") or (sys.argv[3] == "Partition2")):
            FramePosX = 0
            FramePosY = ScreenSizeY / 2 + CorrectionY
        elif sys.argv[3] == "Scao":
            FramePosX = ScreenSizeX / 2 + CorrectionX
            FramePosY = 0
        else:
            FramePosX = ScreenSizeX / 2 + CorrectionX
            FramePosY = ScreenSizeY / 2 + CorrectionY

        self.geometry("%sx%s+%s+%s" %
                      (FrameSizeX, FrameSizeY, FramePosX, FramePosY))
Ejemplo n.º 14
0
class ChatClient(Frame):
  
  def __init__(self, root):
    Frame.__init__(self, root)
    self.root = root
    self.initUI()
    self.serverSoc = None
    self.serverStatus = 0
    self.buffsize = 1024
    self.allClients = {}
    self.counter = 0
  
  def initUI(self):
    self.root.title("Simple P2P Chat Client")
    ScreenSizeX = self.root.winfo_screenwidth()
    ScreenSizeY = self.root.winfo_screenheight()
    self.FrameSizeX  = 690
    self.FrameSizeY  = 690
    FramePosX   = (ScreenSizeX - self.FrameSizeX)/2
    FramePosY   = (ScreenSizeY - self.FrameSizeY)/2
    self.root.geometry("%sx%s+%s+%s" % (self.FrameSizeX,self.FrameSizeY,FramePosX,FramePosY))
    self.root.resizable(width=False, height=False)
    
    padX = 10
    padY = 10
    parentFrame = Frame(self.root)
    parentFrame.grid(padx=padX, pady=padY, stick=E+W+N+S)
    
    ipGroup = Frame(parentFrame)
    serverLabel = Label(ipGroup, text="Set: ")
    self.nameVar = StringVar()
    self.nameVar.set("Username")
    nameField = Entry(ipGroup, width=20, textvariable=self.nameVar)
    self.serverIPVar = StringVar()
    self.serverIPVar.set("127.0.0.1")
    serverIPField = Entry(ipGroup, width=15, textvariable=self.serverIPVar)
    self.serverPortVar = StringVar()
    self.serverPortVar.set("8090")
    serverPortField = Entry(ipGroup, width=5, textvariable=self.serverPortVar)
    serverSetButton = Button(ipGroup, text="Set", width=10, command=self.handleSetServer)
    addClientLabel = Label(ipGroup, text="Add friend: ")
    self.clientIPVar = StringVar()
    self.clientIPVar.set("127.0.0.1")
    clientIPField = Entry(ipGroup, width=15, textvariable=self.clientIPVar)
    self.clientPortVar = StringVar()
    self.clientPortVar.set("8090")
    clientPortField = Entry(ipGroup, width=5, textvariable=self.clientPortVar)
    clientSetButton = Button(ipGroup, text="Add", width=10, command=self.handleAddClient)
    serverLabel.grid(row=0, column=0)
    nameField.grid(row=0, column=1)
    serverIPField.grid(row=0, column=2)
    serverPortField.grid(row=0, column=3)
    serverSetButton.grid(row=0, column=4, padx=5)
    addClientLabel.grid(row=0, column=5)
    clientIPField.grid(row=0, column=6)
    clientPortField.grid(row=0, column=7)
    clientSetButton.grid(row=0, column=8, padx=5)
    
    readChatGroup = Frame(parentFrame)
    self.profil = ScrolledText(readChatGroup, bg="white", width=50, height=10, state=DISABLED)
    self.receivedChats = ScrolledText(readChatGroup, bg="white", width=55, height=20, state=DISABLED)
    self.friends = Listbox(readChatGroup, bg="white", width=30, height=20)
    self.profil.pack(fill=X, pady=5)
    self.receivedChats.pack(padx=0, pady=10, side=LEFT)
    self.friends.pack(padx=5, pady=10, side=LEFT)

    writeChatGroup = Frame(parentFrame)
    self.chatVar = StringVar()
    self.chatField = Entry(writeChatGroup, width=90, textvariable=self.chatVar)
    sendChatButton = Button(writeChatGroup, text="Kirim", width=15, command=self.handleSendChat)
    self.chatField.grid(row=0, column=0, sticky=W)
    sendChatButton.grid(row=0, column=1, padx=5)
    self.statusLabel = Label(parentFrame)
    bottomLabel = Label(parentFrame, text="Modified By CREVION - PTIIK")
    ipGroup.grid(row=0, column=0)
    readChatGroup.grid(row=1, column=0)
    writeChatGroup.grid(row=2, column=0, pady=10)
    self.statusLabel.grid(row=3, column=0)
    bottomLabel.grid(row=4, column=0, pady=10)
    self.profil.config(state=NORMAL)
    
    self.profil.insert("end","Profil :\n\n")
    self.profil.config(state=DISABLED)
  def handleSetServer(self):
    if self.serverSoc != None:
        self.serverSoc.close()
        self.serverSoc = None
        self.serverStatus = 0
    serveraddr = (self.serverIPVar.get().replace(' ',''), int(self.serverPortVar.get().replace(' ','')))
    try:
        self.serverSoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.serverSoc.bind(serveraddr)
        self.serverSoc.listen(5)
        self.setStatus("Server listening on %s:%s" % serveraddr)
        thread.start_new_thread(self.listenClients,())
        self.serverStatus = 1
        self.name = self.nameVar.get().replace(' ','')
        if self.name == '':
            self.name = "%s:%s" % serveraddr
    except:
        self.setStatus("Error setting up server")
    
  def listenClients(self):
    while 1:
      clientsoc, clientaddr = self.serverSoc.accept()
      self.setStatus("Client connected from %s:%s" % clientaddr)
      self.addClient(clientsoc, clientaddr)
      self.profil.config(state=NORMAL)
      try:
        data = clientsoc.recv(self.buffsize)
        if not data:
            break
        self.profil.insert("end","%s\n\n" % data)
      except:
          break
      self.profil.config(state=DISABLED)
      x = open("profil.txt", "r")
      semua = x.read()
      clientsoc.send(self.serverIPVar.get()+"("+self.nameVar.get()+") Terhubung"+"\n"+semua)
      thread.start_new_thread(self.handleClientMessages, (clientsoc, clientaddr))
    self.serverSoc.close()
  
  def handleAddClient(self):
    if self.serverStatus == 0:
      self.setStatus("Set server address first")
      return
    clientaddr = (self.clientIPVar.get().replace(' ',''), int(self.clientPortVar.get().replace(' ','')))
    try:
        clientsoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        clientsoc.connect(clientaddr)
        self.setStatus("Connected to client on %s:%s" % clientaddr)
        self.addClient(clientsoc, clientaddr)
        x = open("profil.txt", "r")
        semua = x.read()
        clientsoc.send(self.serverIPVar.get()+"("+self.nameVar.get()+") Terhubung"+"\n"+semua)
        self.profil.config(state=NORMAL)
        data = clientsoc.recv(self.buffsize)
        self.profil.insert("end","%s\n\n" % data)
        self.profil.config(state=DISABLED)
        thread.start_new_thread(self.handleClientMessages, (clientsoc, clientaddr))
    except:
        self.setStatus("Error connecting to client")

  def handleClientMessages(self, clientsoc, clientaddr):
    while 1:
      try:
        data = clientsoc.recv(self.buffsize)
        if not data:
            break
        self.addChat("%s:%s" % clientaddr, data)
      except:
          break
    self.removeClient(clientsoc, clientaddr)
    clientsoc.close()
    self.setStatus("Client disconnected from %s:%s" % clientaddr)
  
  def handleSendChat(self):
    if self.serverStatus == 0:
      self.setStatus("Set server address first")
      return
    msg = self.nameVar.get()+" : "+self.chatVar.get().replace(' ',' ')
    if msg == '':
        return
    for client in self.allClients.keys():
      client.send(msg)
    msg = "(saya)"+self.nameVar.get()+" : "+self.chatVar.get().replace(' ',' ')
    self.addChat("halo",msg)
  def addChat(self, client, msg):
    self.receivedChats.config(state=NORMAL)
    self.receivedChats.insert("end",msg+"\n")
    self.receivedChats.config(state=DISABLED)
  
  def addClient(self, clientsoc, clientaddr):
    self.allClients[clientsoc]=self.counter
    self.counter += 1
    self.friends.insert(self.counter,"%s:%s" % clientaddr)
  
  def removeClient(self, clientsoc, clientaddr):
      print self.allClients
      self.friends.delete(self.allClients[clientsoc])
      del self.allClients[clientsoc]
      print self.allClients
  
  def setStatus(self, msg):
    self.statusLabel.config(text=msg)
    print msg
Ejemplo n.º 15
0
    def initialisation(self):
        global input_pipe
        global output_pipe

        if len(sys.argv) > 2:
            print 'output_pipe : ', output_pipe
        global ChaineALire
        global st
        global fp
        global colorbox
        global sortieTube
        global entreeTube

        texte = """ Welcome in GUI for ARINC 653 emulator 
"""

        #on cree un fenetre principale 'fp' a� partir du 'modele' Tk
        #fp = Tk()
        self.title('ARINC 653 Partition')

        #Declaration du texte deroulant dans 'fp'
        st = ScrolledText(self, wrap="word")
        st.grid(column=1, columnspan=2, rowspan=2, sticky='nw')

        #Creation d'un panneau 'menu_bottom' insere dans 'fp'
        #		menu_bottom = Frame(self,borderwidth=2)
        #		menu_bottom.grid(column=1,columnspan=3,sticky='sw')

        ##Creation d'une etiquette inseree dans 'menu_bottom'
        #etiquette = Label(menu_bottom,text = 'Commande : ')
        #etiquette.grid(row=1,column=1,sticky='w')

        ##Creation d'un boutton dans 'menu_bottom'
        #b = Button(menu_bottom,text='execute',command=self.affiche_commande)
        #b.grid(row=1,column=3,sticky='e')

        ##Creation d'un boite d'edition dans 'nenu_top'
        #entre = Entry(menu_bottom,width=20,relief='sunken')
        #entre.insert(END,'Texte a afficher')
        #entre.grid(row=1,column=2,sticky='ew')

        #Creation d'une etiquette inseree
        etiquette = Label(self, text='Command : ')
        etiquette.grid(row=2, column=0, sticky='w')

        #Creation d'un boutton
        b = Button(self, text='execute', command=self.affiche_commande)
        b.grid(row=2, column=2, sticky='e')

        #Creation d'un boite d'edition dans 'nenu_top'
        entre = Entry(self, width=20, relief='sunken')
        entre.insert(END, 'Text to send')
        entre.grid(row=2, column=1, sticky='ew')

        partitionbox = Label(self, text='Active partition : ')
        partitionbox.grid(column=0, row=0, sticky='n')

        self.labelVariable = StringVar()
        self.backcolorlabel = StringVar()
        self.frontcolorlabel = StringVar()
        self.backcolorlabel = "LightBlue"
        self.frontcolorlabel = "Black"
        label = Label(self,
                      textvariable=self.labelVariable,
                      anchor="w",
                      fg=self.frontcolorlabel,
                      bg=self.backcolorlabel,
                      height=28)
        label.grid(column=0, row=1, sticky='EW')

        #on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
        st.insert(END, texte)
        #on applique a� tout le texte la police par defaut
        st.config(font='Arial 12')
        st.config(foreground='Black')
        #on configure le fond du 'texte derouant'
        st.config(background='LightBlue')
        #e = Entry(st,width=25)

        self.grid_columnconfigure(1, weight=1)
        self.rowconfigure(1, weight=1)

        self.resizable(False, True)
        self.update()
        self.geometry(self.geometry())

        try:
            assert input_pipe != ''

        except AssertionError:
            showerror('error', "no pipe choosed")
            input_pipe = tkFileDialog.askopenfilename(
                title='Choose the input pipe to open',
                defaultextension='.fifo')

        #openning the INPUT pipe
        try:
            assert input_pipe != ''

            try:

                #			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
                sortieTube = os.open(input_pipe, os.O_RDONLY)
                if sortieTube == -1:
                    raise ValueError
            except ValueError:
                showerror('Error', "fail to open the Input pipe's output")
        except AssertionError:
            showerror("Error", "You must choose a pipe first")

        #openning the OUTPUT pipe
        if len(sys.argv
               ) > 2:  #if an output pipe was given as the second argument
            try:
                assert output_pipe != ''

                #opening the pipe
                try:
                    entreeTube = os.open(output_pipe, os.O_WRONLY)

                    if entreeTube == -1:
                        raise ValueError
                except ValueError:
                    showerror('Error', "Could not open Output pipe")
            except AssertionError:
                showerror("Error", "You must choose an output pipe first")
                output_pipe = tkFileDialog.askopenfilename(
                    title='Choose the output pipe to open',
                    defaultextension='.fifo')
Ejemplo n.º 16
0
Archivo: gui.py Proyecto: ARISSIM/ARISS
	def initialisation(self):
		global input_pipe
		global output_pipe
		if len(sys.argv) > 2 :
			print 'output_pipe : ', output_pipe
		global ChaineALire
		global st
		global fp
		global sortieTube
		global entreeTube
					
		def click_python(event):
			st.insert(END,'\nVous avez cliquez sur Python')

		def affiche_message():
			global output_pipe
			message = entre.get()
			
			#openning the OUTPUT pipe
			if len(sys.argv) > 2 : #if an output pipe was given as the second argument
				try:
					assert output_pipe != ''
					#opening the pipe
					try :
						entreeTube = os.open(output_pipe,os.O_WRONLY)
						if entreeTube == -1 :
							raise ValueError
						os.write(entreeTube,message)
						#st.insert(END,'\n'+message,'rouge')						
					except ValueError :
						showerror('Error', "Could not open Output pipe")
				except AssertionError:
					showerror("Error", "You must choose an output pipe first")
					output_pipe = tkFileDialog.askopenfilename(title='Choose the output pipe to open', defaultextension ='.fifo')

		texte = """ Welcome in GUI for ARINC 653 Partition """

		#on cree un fenetre principale 'fp' a� partir du 'modele' Tk   
		#fp = Tk()
		#self.title('ARINC 653 function')
		self.title('ARINC 653 function : ' + sys.argv[3])
	
		#Creation d'un panneau 'menu_top' insere dans 'fp'
		menu_top = Frame(self,borderwidth=2)
		menu_top.pack(side='bottom',fill='x')

		#Creation d'une etiquette inseree dans 'menu_top'
		etiquette = Label(menu_top,text = 'Commande : ')
		etiquette.pack(side = 'left')

		#Creation d'un boutton dans 'menu_top'
		b = Button(menu_top,text='execute',command=affiche_message)
		b.pack(side='right')

		#Creation d'un boite d'edition dans 'nenu_top'
		entre = Entry(menu_top,width=20,relief='sunken')
		entre.insert(END,'Texte a afficher')
		entre.pack(side='left',fill='x',expand='true')
	

	
		#Declaration du texte deroulant dans 'fp'
		st = ScrolledText(self)
		st.pack(expand=1,fill='both',side='top')

		#on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
		st.insert(END,texte)
		#on applique a� tout le texte la police par defaut
		st.config(font = 'Arial 12 bold')
		st.config(foreground='Black')
		#on configure le fond du 'texte derouant'
		
		if ((sys.argv[3] == "Master") or (sys.argv[3] == "Partition1")or (sys.argv[3] == "Primary")):
			st.config(background='LightYellow')
		elif ((sys.argv[3] =="Slave") or (sys.argv[3] == "Partition2")or (sys.argv[3] == "Backup")):
			st.config(background='LightGreen')
		#e = Entry(st,width=25)
		elif ((sys.argv[3] =="Leica") or (sys.argv[3] == "Partition3")or (sys.argv[3] == "Capteur")):
		        st.config(background='misty rose')
		else: 
		        st.config(background='PeachPuff')
		try:
			assert input_pipe != ''
		
		except AssertionError:
			showerror('Info', "choisissez un chemin de tube")
			input_pipe = tkFileDialog.askopenfilename(title='Choose the input pipe to open', defaultextension ='.fifo')

		#openning the INPUT pipe
		try:
			assert input_pipe != ''	

			try :

	#			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
				sortieTube = os.open(input_pipe,os.O_RDONLY)
				if sortieTube == -1 :
					raise ValueError
			except ValueError :		
				showerror('Error', "fail to open the Input pipe's output")
		except AssertionError:
			showerror("Error", "You must choose a pipe first")


		#openning the OUTPUT pipe
		if len(sys.argv) > 2 : #if an output pipe was given as the second argument
			try:
				assert output_pipe != ''

				#opening the pipe
				try :
					entreeTube = os.open(output_pipe,os.O_WRONLY)
			
					if entreeTube == -1 :
						raise ValueError
				except ValueError :
					showerror('Error', "Could not open Output pipe")
			except AssertionError:
				showerror("Error", "You must choose an output pipe first")
				output_pipe = tkFileDialog.askopenfilename(title='Choose the output pipe to open', defaultextension ='.fifo')


		#Positionnement de la fenetre dans l'ecran
		ScreenSizeX = self.winfo_screenwidth()  # Get screen width [pixels]
		ScreenSizeY = self.winfo_screenheight() # Get screen height [pixels]
		CorrectionX = 30
		CorrectionY = 30
		FrameSizeX  = int(ScreenSizeX * 0.5) - CorrectionX
		FrameSizeY  = int(ScreenSizeY * 0.5) - CorrectionY

		if ((sys.argv[3] == "Master") or (sys.argv[3] == "Partition1")) : # Find left and up border of window
			FramePosX   = 0
			FramePosY   = 0
		elif ((sys.argv[3] == "Slave") or (sys.argv[3] == "Partition2")) :
			FramePosX   = 0
			FramePosY   = ScreenSizeY/2 + CorrectionY
		elif sys.argv[3] =="Scao":
			FramePosX   = ScreenSizeX/2 + CorrectionX 
			FramePosY   = 0
		else: 
			FramePosX   = ScreenSizeX/2 + CorrectionX 
			FramePosY   = ScreenSizeY/2 + CorrectionY

		self.geometry("%sx%s+%s+%s"%(FrameSizeX,FrameSizeY,FramePosX,FramePosY))
Ejemplo n.º 17
0
class Textee:
    def __init__(self, master):
        self.master = master
        self.theme = 'dark' # the startup will always be opposite
        self.options = TexteeOptions()
        self.status_bar = TexteeStatusBar(master)
        self.create_menu(master)
        self.create_ui(master)
        self.set_bindings(master)
        self.file = None
        self.find_text = ''
        self.font_dialog = None
        self.find_and_replace_dialog = None
        self.windows = []
        
    def create_menu(self, master):
        self.menu = Menu(master)
        master.config(menu=self.menu)
        
        filemenu = Menu(self.menu)
        self.menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="New", command=self.new_file)
        filemenu.add_command(label="Open...", command=self.open_file)
        filemenu.add_command(label="Save", command=self.save_file)
        filemenu.add_command(label="Save As", command=lambda: self.save_file(save_as=True))
        filemenu.add_separator()
        filemenu.add_command(label="New window", command=self.new_window)
        filemenu.add_separator()
        filemenu.add_command(label="Print", command=self.printer)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.exit)

        editmenu = Menu(self.menu)
        self.menu.add_cascade(label='Edit', menu=editmenu)
        editmenu.add_command(label='Copy', command=lambda: event_generate(self.editor, 'Copy'))
        editmenu.add_command(label='Paste', command=lambda: event_generate(self.editor, 'Paste'))
        editmenu.add_command(label='Undo', command=lambda: event_generate(self.editor, 'Undo'))
        editmenu.add_separator()
        editmenu.add_command(label='Goto', command=self.goto_line) # need to develop custom find with regex
        editmenu.add_command(label='Find', command=self.find) # need to develop custom find with regex
        editmenu.add_command(label='Find & Replace', command=self.find_and_replace) # need to test the replace logic in separate playground
        editmenu.add_separator()
        editmenu.add_command(label='Check spelling', command=self.spell_check) # need to see how to use system's grammer check.. if not possible remove it.

        formatmenu = Menu(self.menu)
        self.menu.add_cascade(label='Format', menu=formatmenu)
        formatmenu.add_command(label='Font', command=self.select_font) # pop-up to select system fonts
        formatmenu.add_checkbutton(label='Wrap', onvalue=True, offvalue=False, variable=self.options.wrap, command=self.toggle_wrap)
        
        viewmenu = Menu(self.menu)
        self.menu.add_cascade(label='View', menu=viewmenu)
        viewmenu.add_checkbutton(label='Status bar', onvalue=True, offvalue=False, variable=self.options.status_bar, command=lambda: self.status_bar.display(self.options.status_bar.get()))
        viewmenu.add_command(label='Toggle theme', command=self.toggle_theme)
        
        helpmenu = Menu(self.menu)
        self.menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About", command=lambda : self.about())

    def create_ui(self, master):
        self.editor = ScrolledText(master, width=100, height=50, highlightthickness=0)
        self.editor.config(undo=True)
        self.editor.pack(expand=YES, fill='both', padx=0, pady=0)
        self.toggle_theme()
        #print_configs(self.editor)
        
        # Create pop-menu for the entire editor.. do some cool stuff with it
        self.editor.popmenu = Menu(self.master, tearoff=0)
        # TODO : later need to do smart copy/paste i.e. selected text copy of entire line copy
        self.editor.popmenu.add_command(label='Copy', command=lambda: event_generate(self.editor, 'Copy'))
        self.editor.popmenu.add_command(label='Paste', command=lambda: event_generate(self.editor, 'Paste'))
        # TODO : disable undo when not available, not sure if its possible. Need to check research later
        self.editor.popmenu.add_command(label='Undo', command=lambda: event_generate(self.editor, 'Undo'))
        self.editor.popmenu.add_separator()
        # TODO : 'share' this will be the best feature in the editor, share the file with the future textee sharing api
        self.editor.popmenu.add_command(label='Share', command=do_nothing)

        # add status bar by default, it can be hidden from menu
        self.status_bar.update_status('Hi there')
        
    def set_bindings(self, master):
        master.bind_class('Text', '<Control-a>', select_all)
        master.bind_class('Text', '<Control-s>', lambda event: self.save_file())
        master.bind_class('Text', '<Control-o>', lambda event: self.open_file())
        master.bind_class('Text', '<Control-n>', lambda event: self.new_file())
        master.bind_class('Text', '<Control-g>', lambda event: self.goto_line())
        master.bind_class('Text', '<Control-f>', lambda event: self.find())
        master.bind_class('Text', '<Control-p>', lambda event: self.printer())
        master.bind_class('Text', '<Control-;>', lambda event: self.find_and_replace()) # this function is only for temporoy use - for dev purpose only

        # editor section bindings only
        self.editor.bind('<Button-2>', self.show_right_click_menu) # for right-click
        self.editor.bind('<Button-3>', self.show_right_click_menu) # for middle-click (scroll press)

        #display the current cursor position
        self.display_current_position()


    def new_file(self):
        self.file = None
        self.editor.delete('1.0', END+'-1c') # clear all the contents

    def open_file(self):
        self.file = tkFileDialog.askopenfilename(parent=self.master,title='Select a file')
        if self.file != None and self.file != '':
            self.editor.delete('1.0', END+'-1c') # clear all the contents
            infile = open(self.file, 'r')
            contents = infile.read()
            self.editor.insert('1.0',contents)
            infile.close()

    def save_file(self, save_as=False):
        data = self.editor.get('1.0', END+'-1c')
        save_as_file = None

        # if saving the file by creation
        if self.file == None or save_as == True:
            save_as_file = tkFileDialog.asksaveasfilename() # attempt to select the filename, the user can select cancel so check agian below

        # the above could result in None if the user cancels the dialog
        if save_as_file:
            self.file = save_as_file

        # final check, as both the above could result in None
        if self.file != None:
            outfile = open(self.file, 'w')
            outfile.write(data)
            outfile.close()

    def goto_line(self):
        lineno = tkSimpleDialog.askinteger('Textee', 'Goto line:')
        if lineno > 0:
            self.editor.mark_set(INSERT, lineno + 0.0) #convert to float
            self.editor.see(INSERT)
        self.editor.focus_set()

    def toggle_theme(self):
        if self.theme == 'light':
            self.editor.config(bg='black', fg='white', insertbackground='white',highlightcolor='black')
            self.editor.frame.config(bg='black')
            # theme for misspelled words
            self.editor.tag_configure("misspelled", foreground="red", underline=True)
            self.theme = 'dark'
        else:
            self.editor.config(bg='white', fg='black', insertbackground='black',highlightcolor='white')
            self.editor.frame.config(bg='white')
            # theme for misspelled words
            self.editor.tag_configure("misspelled", foreground="red", underline=True)
            self.theme = 'light'

    def toggle_wrap(self):
        # self.editor.cget('wrap') # gets the config value
        if not self.options.wrap.get():
            self.editor.config(wrap='none')
        else:
            self.editor.config(wrap='word')

    def find(self):
        find_text = tkSimpleDialog.askstring("Textee", "Enter text to search", initialvalue=self.find_text)
        if find_text:
            if find_text == self.find_text:
                start_pos = self.editor.search(find_text, self.editor.index('insert'), stopindex=END, nocase=True)
            else:
                start_pos = self.editor.search(find_text, '1.0', stopindex=END, nocase=True)
                
            self.find_text = find_text
            if(start_pos):
                end_pos = '%s+%sc' % (start_pos, len(self.find_text))
                self.editor.tag_add(SEL, start_pos, end_pos)
                self.editor.mark_set(INSERT, end_pos) # mark the cursor to end of find text to start editing
                self.editor.see(INSERT) # bing the cursor position in the viewport incase of long text causinng scrollbar
                self.editor.focus_set() # strangely tkinter doesnt return focus after prompt
            else:
                tkMessageBox.showinfo("Textee", "No morw matches found")
        else:
            self.editor.focus_set() # strangely tkinter doesnt return focus after prompt

    def find_and_replace(self):
        #show the custom dialog
        self.find_and_replace_dialog = TexteeFindAndReplaceDialog(self.master)
        if self.find_and_replace_dialog.find_text:
            start_pos = self.editor.search(self.find_and_replace_dialog.find_text, '1.0', stopindex=END, nocase=True)
            # lazy recursive replace for all the matched elements, no need to parse whole dataset again and again
            while start_pos:
                self.editor.delete(start_pos, '%s+%sc' % (start_pos, len(self.find_and_replace_dialog.find_text)))
                self.editor.insert(start_pos, self.find_and_replace_dialog.replace_with)
                # break after first replace if replace all flag is off
                if not self.find_and_replace_dialog.replace_all:
                    break
                start_pos = self.editor.search(self.find_and_replace_dialog.find_text, '%s+%sc' % (start_pos, len(self.find_and_replace_dialog.replace_with)), stopindex=END, nocase=True)


    def select_font(self):
        self.font_dialog = TexteeFontDialog(self.master)
        fs = 12 # default size for any font selected

        if self.font_dialog.selected_font_family:
            ff = self.font_dialog.selected_font_family
        
        if self.font_dialog.selected_font_size:
            fs = self.font_dialog.selected_font_size

        print ff, fs, " - font properties"

        if ff and fs > 0:
            self.default_font = tkFont.Font(self.master, family=ff, size=fs)
            self.editor.config(font=self.default_font)

    def show_right_click_menu(self, event):
        print 'going to display popmenu at', event.x_root, event.y_root
        try:
            self.editor.popmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            # TODO: not sure why we need this, pasting it from the documentation. Later check to remove it
            self.editor.popmenu.grab_release()

    def spell_check(self):
        # check if the dictonary exists in the system (only mac and linux have it at this location)
        # TODO: to check on windows how to do?
        print "inside the spell check"
        if not os.path.exists('/usr/share/dict/words'):
            return

        with open('/usr/share/dict/words', 'r') as words_file:
            system_words = words_file.read().split('\n') 
            current_file_lines = self.editor.get('1.0', END+'-1c').split('\n') 

            for lineno, current_line in enumerate(current_file_lines):
                current_line_words = re.split('\W', current_line)
                columnposition = 0 # this is to ignore the white space with which we split above, the marking of the invalid word should be be without the space
                for word in current_line_words:
                    start_index = '%s.%s' % (lineno+1, columnposition)
                    end_index = '%s+%dc' % (start_index, len(word))
                    if word in system_words:
                        self.editor.tag_remove('misspelled', start_index, end_index)
                    else:
                        self.editor.tag_add('misspelled', start_index, end_index)
                    columnposition += len(word)+1 # take into account the space
     
    def display_current_position(self):
        cursor_position =  self.editor.index("insert").replace('.', ',')
        self.status_bar.update_status(cursor_position)
        self.master.after(self.status_bar.update_interval, self.display_current_position)

    def printer(self):
        if not os.path.exists('/usr/bin/lpr'):
            tkMessageBox.showerror('Printing is not supported with your operating system')
            return
        lpr = subprocess.Popen('/usr/bin/lpr', stdin=subprocess.PIPE)
        text = self.editor.get('1.0', END+'-1c')
        lpr.stdin.write(text)
        lpr.stdin.close()

    def new_window(self):
        #allow multiple windows to be opened
        root = Tkinter.Tk(className=" Textee")
        root.title("Textee - A Stupid Text Editor")
        app = Textee(root)
        self.windows.append(app)
        root.mainloop()
        

    def about(self):
        tkMessageBox.showinfo("About", "Textee - A stupid text editor")

    def exit(self, master):
        if tkMessageBox.askokcancel("Quit", "Are you sure?"):
            master.destroy()
Ejemplo n.º 18
0
	def initialisation(self):
		global input_pipe
		global output_pipe

		if len(sys.argv) > 2 :
			print 'output_pipe : ', output_pipe
		global ChaineALire
		global st
		global fp
		global colorbox
		global sortieTube
		global entreeTube



		texte = """ Welcome in GUI for ARINC 653 emulator 
"""

		#on cree un fenetre principale 'fp' a� partir du 'modele' Tk   
		#fp = Tk()
		self.title('ARINC 653 Partition')	

		#Declaration du texte deroulant dans 'fp'
		st = ScrolledText(self,wrap="word")
		st.grid(column=1,columnspan=2,rowspan=2,sticky='nw')

		#Creation d'un panneau 'menu_bottom' insere dans 'fp'
#		menu_bottom = Frame(self,borderwidth=2)
#		menu_bottom.grid(column=1,columnspan=3,sticky='sw')

		##Creation d'une etiquette inseree dans 'menu_bottom'
		#etiquette = Label(menu_bottom,text = 'Commande : ')
		#etiquette.grid(row=1,column=1,sticky='w')

		##Creation d'un boutton dans 'menu_bottom'
		#b = Button(menu_bottom,text='execute',command=self.affiche_commande)
		#b.grid(row=1,column=3,sticky='e')

		##Creation d'un boite d'edition dans 'nenu_top'
		#entre = Entry(menu_bottom,width=20,relief='sunken')
		#entre.insert(END,'Texte a afficher')
		#entre.grid(row=1,column=2,sticky='ew')
			
		#Creation d'une etiquette inseree
		etiquette = Label(self,text = 'Command : ')
		etiquette.grid(row=2,column=0,sticky='w')			
		
		#Creation d'un boutton
		b = Button(self,text='execute',command=self.affiche_commande)
		b.grid(row=2,column=2,sticky='e')

		#Creation d'un boite d'edition dans 'nenu_top'
		entre = Entry(self,width=20,relief='sunken')
		entre.insert(END,'Text to send')
		entre.grid(row=2,column=1,sticky='ew')
		
		partitionbox = Label(self ,text = 'Active partition : ')
		partitionbox.grid(column=0,row=0,sticky='n')
		
		self.labelVariable = StringVar()
		self.backcolorlabel = StringVar()
		self.frontcolorlabel = StringVar()
		self.backcolorlabel = "LightBlue"
		self.frontcolorlabel = "Black"
		label = Label(self,textvariable=self.labelVariable,
			anchor="w",fg=self.frontcolorlabel,bg=self.backcolorlabel,height=28)
		label.grid(column=0,row=1,sticky='EW')
		


		#on insete le texte 'texte' dans le widget 'texte deroulant' nomme 'st'
		st.insert(END,texte)
		#on applique a� tout le texte la police par defaut
		st.config(font = 'Arial 12')
		st.config(foreground='Black')
		#on configure le fond du 'texte derouant'
		st.config(background='LightBlue')
		#e = Entry(st,width=25)


		self.grid_columnconfigure(1,weight=1)
		self.rowconfigure(1,weight=1)
		
		self.resizable(False,True)
		self.update()
		self.geometry(self.geometry())
		
		try:
			assert input_pipe != ''
		
		except AssertionError:
			showerror('error', "no pipe choosed")
			input_pipe = tkFileDialog.askopenfilename(title='Choose the input pipe to open', defaultextension ='.fifo')

		#openning the INPUT pipe
		try:
			assert input_pipe != ''	

			try :

	#			sortieTube = os.open(input_pipe+nomTube,os.O_RDONLY|os.O_NONBLOCK)
				sortieTube = os.open(input_pipe,os.O_RDONLY)
				if sortieTube == -1 :
					raise ValueError
			except ValueError :		
				showerror('Error', "fail to open the Input pipe's output")
		except AssertionError:
			showerror("Error", "You must choose a pipe first")


		#openning the OUTPUT pipe
		if len(sys.argv) > 2 : #if an output pipe was given as the second argument
			try:
				assert output_pipe != ''

				#opening the pipe
				try :
					entreeTube = os.open(output_pipe,os.O_WRONLY)
			
					if entreeTube == -1 :
						raise ValueError
				except ValueError :
					showerror('Error', "Could not open Output pipe")
			except AssertionError:
				showerror("Error", "You must choose an output pipe first")
				output_pipe = tkFileDialog.askopenfilename(title='Choose the output pipe to open', defaultextension ='.fifo')	
Ejemplo n.º 19
0
class SphxUI():
    def __init__(self, root):

        self.data = SphxData()
        self.xdopy = XdoPy()
        self.gooey = GuiPiece(self.data.MAIN_PATH, self.data.GUI_PIECE_DIR)
        self.script_dir = self.data.SCRIPT_DIR
        self.txt_dir = self.data.TXT_FILE_DIR

        # sphx data to reset upon new or fill upon load
        self.script_lines = []
        self.gui_pieces = []
        self.window_names = []
        self.passed_script_data = None
        self.text_file_pass = None
        self.return_data = None
        self.gui_piece_list_active = False
        self.script_fn = None

        # generate UI
        self.root = root
        self.master = Frame(self.root)
        self.master.grid()
        self.add_file_menu()
        self.create_script_pad()
        self.create_action_buttons()
        self.create_gui_pieces_list()
        return

    def start(self):
        self.root.mainloop()
        return

    def _dummy(self):
        pass

    def _dummy_event(self, event, arg=None):
        pass

    # TOP MENU
    #
    #
    def add_file_menu(self):
        self.menubar = Menu(self.root)
        self.filemenu = Menu(self.menubar, tearoff=0)
        self.filemenu.add_command(label="New", command=self._new)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Open...", command=self._open)
        self.filemenu.add_command(label="Save",
                                  command=lambda: self._save(saveas=False))
        self.filemenu.add_command(label="Save As...",
                                  command=lambda: self._save(saveas=True))
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=self._regular_exit)
        self.menubar.add_cascade(label="File", menu=self.filemenu)
        self.helpmenu = Menu(self.menubar, tearoff=0)
        self.helpmenu.add_command(label="About", command=self._dummy)
        self.menubar.add_cascade(label="Help", menu=self.helpmenu)
        self.root.config(menu=self.menubar)

    def _clear_everything(self):
        self.script_pad.delete('1.0', END)
        for button in self.gui_piece_buttons:
            button.config(text='')
        for line in self.script_lines:
            if line[2]:
                self.script_pad.tag_delete(line[2])
        self.script_lines = []
        self.gui_pieces = []
        self.window_names = []
        self.passed_script_data = None
        self.return_data = None
        self.gui_piece_list_active = False

    def _new(self):
        self.new_save = Toplevel()
        self.new_save.title('Save Script?')
        new_frame1 = Frame(self.new_save)
        new_frame1.grid(row=0, column=0)
        label = Label(
            new_frame1,
            text='Do you want to save your script before starting over?')
        label.grid()
        new_frame2 = Frame(self.new_save)
        new_frame2.grid(row=1, column=0)
        button = Button(new_frame2,
                        text='Yes',
                        command=lambda: self._new_save(0))
        button.grid(row=0, column=0)
        button = Button(new_frame2,
                        text='No',
                        command=lambda: self._new_save(1))
        button.grid(row=0, column=1)
        button = Button(new_frame2,
                        text='Cancel',
                        command=lambda: self._new_save(2))
        button.grid(row=0, column=2)

    def _new_save(self, answer):
        if answer == 0:
            if self.script_fn:
                self._save()
            else:
                self._save(False)
            self._clear_everything()
            self.new_save.destroy()
        if answer == 1:
            self._clear_everything()
            self.new_save.destroy()
        if answer == 2:
            self.new_save.destroy()

    def _open(self):
        if self.script_lines == [] and self.gui_pieces == []:
            self._load_everything()
            return
        self.open_save = Toplevel()
        self.open_save.title('Save Script?')
        new_frame1 = Frame(self.open_save)
        new_frame1.grid(row=0, column=0)
        label = Label(
            new_frame1,
            text='Do you want to save your script before opening a saved one?')
        label.grid()
        new_frame2 = Frame(self.open_save)
        new_frame2.grid(row=1, column=0)
        button = Button(new_frame2,
                        text='Yes',
                        command=lambda: self._open_save(0))
        button.grid(row=0, column=0)
        button = Button(new_frame2,
                        text='No',
                        command=lambda: self._open_save(1))
        button.grid(row=0, column=1)
        button = Button(new_frame2,
                        text='Cancel',
                        command=lambda: self._open_save(2))
        button.grid(row=0, column=2)

    def _open_save(self, answer):
        if answer == 0:
            if self.script_fn:
                self._save()
            else:
                self._save(False)
            self.open_save.destroy()
            self._load_everything()
        if answer == 1:
            self.open_save.destroy()
            self._load_everything()
        if answer == 2:
            self.open_save.destroy()

    def _load_everything(self):
        f = tkFileDialog.askopenfilename(initialdir=self.data.SCRIPT_DIR,
                                         title="Open Script",
                                         filetypes=(("sphx files", "*.sphx"),
                                                    ("all files", "*.*")))
        with open(f, 'r') as openfile:
            sphx_dict = json.load(openfile)
        self.script_fn = f.rpartition('/')[2]
        openfile.close()
        self._clear_everything()
        self.script_lines = sphx_dict['script_lines']
        self.gui_pieces = sphx_dict['gui_pieces']
        button_index = 0
        for gui_piece in self.gui_pieces:
            gui_piece_text = '{0}. {1}'.format(button_index + 1, gui_piece)
            self.gui_piece_buttons[button_index].config(text=gui_piece_text)
            button_index += 1
        for line in self.script_lines:
            line_number, script_text, tagname, tag_start, tag_end, script_data = line
            self.script_pad.insert(END, script_text + '\n')
            self._scanfix_script_lines(None)

    def _save(self, saveas=False):
        self._scanfix_script_lines(None)
        script_dict = {
            'script_lines': self.script_lines,
            'gui_pieces': self.gui_pieces
        }
        if not saveas and self.script_fn:
            with open(os.path.join(self.data.SCRIPT_DIR, self.script_fn),
                      'w') as outfile:
                json.dump(script_dict, outfile)
                self.script_fn = outfile.name.rpartition('/')[2]
        if (saveas or not self.script_fn) or (saveas and not self.script_fn):
            outfile = tkFileDialog.asksaveasfile(
                mode='w',
                defaultextension='.sphx',
                initialdir=self.data.SCRIPT_DIR)
            if outfile is None:
                return
            json.dump(script_dict, outfile)
            outfile.close()
            self.script_fn = outfile.name.rpartition('/')[2]

    def _regular_exit(self):
        self.exit_save = Toplevel()
        self.exit_save.title('Save Script')
        exit_frame1 = Frame(self.exit_save)
        exit_frame1.grid(row=0, column=0)
        label = Label(exit_frame1,
                      text='Do you want to save your script before exiting?')
        label.grid()
        exit_frame2 = Frame(self.exit_save)
        exit_frame2.grid(row=1, column=0)
        button = Button(exit_frame2,
                        text='Yes',
                        command=lambda: self._exit_save(0))
        button.grid(row=0, column=0)
        button = Button(exit_frame2,
                        text='No',
                        command=lambda: self._exit_save(1))
        button.grid(row=0, column=1)
        button = Button(exit_frame2,
                        text='Cancel',
                        command=lambda: self._exit_save(2))
        button.grid(row=0, column=2)

    def _exit_save(self, answer):
        if answer == 0:
            if self.script_fn:
                self._save()
            else:
                self._save(False)
            self.root.quit()
        if answer == 1:
            self.root.quit()
        if answer == 2:
            self.exit_save.destroy()

    # SCRIPT PAD COLUMN
    #
    #
    def create_script_pad(self):
        script_pad_label = Label(self.master,
                                 text='SCRIPT BUILD (right-click for options)')
        script_pad_label.grid(row=0, column=1)
        self.script_pad = ScrolledText(self.master, width=75, height=32)
        self.script_pad.grid(row=1, column=1, sticky='nw')
        self.script_pad.bind('<KeyRelease>', self._scanfix_script_lines)
        self.print_button = Button(self.master,
                                   text='Print Script Line Data To Terminal',
                                   command=self._print_script_line_data)
        self.print_button.grid(row=2, column=1, sticky='nwes')
        return

    def _print_script_line_data(self):
        for line in self.script_lines:
            print(line[1])

    def _get_tag_data(self, line_count, line_text, script_data):
        tag_start = '{0}.{1}'.format(line_count, line_text.index(script_data))
        tag_end = '{0}.{1}'.format(
            line_count,
            line_text.index(script_data) + len(script_data))
        return tag_start, tag_end

    def _scanfix_script_lines(self, event):
        new_script_lines = []
        new_text = self.script_pad.get('1.0', END)
        new_text_lines = new_text.split('\n')
        line_count = 0
        gui_tags = []
        win_tags = []
        key_tags = []
        self.script_lines = []
        new_window_names = []
        for line in new_text_lines:
            line_count += 1
            if ';' and ' ' in line:
                line_text = line.rpartition(';')[0]
                line_pieces = line_text.split(' ')
                action = line_pieces[0]
                script_line_data = []
                if action in [a[0] for a in self.data.GUI_ACTIONS]:
                    script_data = line_pieces[1]
                    tag_index = len(gui_tags)
                    tag_name = 'gui{0}'.format(tag_index)
                    self.script_pad.tag_delete(tag_name)
                    gui_tags.append(tag_name)
                    tag_start, tag_end = self._get_tag_data(
                        line_count, line_text, script_data)
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                    self.script_pad.tag_add(tag_name, tag_start, tag_end)
                    self.script_pad.tag_config(tag_name,
                                               background='blue',
                                               foreground='white')
                    self.script_pad.tag_bind(
                        tag_name,
                        '<Button-3>',
                        lambda event, arg=script_line_data: self.
                        _gui_piece_menu_popup(event, arg))
                if action in [a[0] for a in self.data.WINDOW_ACTIONS]:
                    script_data = line_pieces[1]
                    tag_index = len(win_tags)
                    tag_name = 'win{0}'.format(tag_index)
                    self.script_pad.tag_delete(tag_name)
                    win_tags.append(tag_name)
                    tag_start, tag_end = self._get_tag_data(
                        line_count, line_text, script_data)
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                    if action == 'name_active_window':
                        new_window_names.append(script_data)
                        self.script_pad.tag_add(tag_name, tag_start, tag_end)
                        self.script_pad.tag_config(tag_name,
                                                   background='gray',
                                                   foreground='white')
                    else:
                        self.script_pad.tag_add(tag_name, tag_start, tag_end)
                        self.script_pad.tag_config(tag_name,
                                                   background='pink',
                                                   foreground='white')
                        self.script_pad.tag_bind(
                            tag_name,
                            '<Button-3>',
                            lambda event, arg=script_line_data: self.
                            _window_menu_popup(event, arg))
                if action in [a[0] for a in self.data.KEYBOARD_ACTIONS]:
                    script_data = line_text.partition(' ')[2]
                    tag_index = len(key_tags)
                    tag_name = 'key{0}'.format(tag_index)
                    key_tags.append(tag_name)
                    tag_start, tag_end = self._get_tag_data(
                        line_count, line_text, script_data)
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                    self.script_pad.tag_add(tag_name, tag_start, tag_end)
                    if 'type' in action:
                        tag_bg, tag_fg = 'green', 'white'
                    else:
                        tag_bg, tag_fg = 'green', 'yellow'
                    self.script_pad.tag_config(tag_name,
                                               background=tag_bg,
                                               foreground=tag_fg)
                    self.script_pad.tag_bind(
                        tag_name,
                        '<Button-3>',
                        lambda event, arg=script_line_data: self.
                        _text_piece_popup(event, arg))
                if action in [a[0] for a in self.data.OTHER_ACTIONS]:
                    script_data = None
                    tag_name = None
                    tag_start, tag_end = None, None
                    script_line_data = [
                        line_count, line, tag_name, tag_start, tag_end,
                        script_data
                    ]
                if len(script_line_data) > 0:
                    self.script_lines.append(script_line_data)
        self.window_names = sorted(new_window_names)
        if len(self.window_names) == 0:
            self.action_buttons_list[15].config(state=DISABLED)
            self.action_buttons_list[16].config(state=DISABLED)
        else:
            if not self.gui_piece_list_active:
                self.action_buttons_list[15].config(state='normal')
                self.action_buttons_list[16].config(state='normal')
        return

    # ACTION BUTTONS COLUMN
    #
    #
    def create_action_buttons(self):
        action_buttons_label = Label(self.master, text='SCRIPT ACTIONS')
        action_buttons_label.grid(row=0, column=2)
        self.action_buttons = Frame(self.master)
        self.action_buttons.grid(row=1, column=2, sticky='nw')
        self.auto_snap = IntVar()
        self.auto_snap.set(1)
        self.auto_snap_check = Checkbutton(self.action_buttons,
                                           text='Auto-snap',
                                           variable=self.auto_snap)
        self.auto_snap_check.grid(row=0, column=2)
        self.action_buttons_list = []
        action_index = 0
        for i in range(3):
            for j in range(3):
                button = Button(self.action_buttons,
                                text=self.data.GUI_ACTIONS[action_index][0],
                                pady=5,
                                command=functools.partial(
                                    self._append_gui_piece_action,
                                    self.data.GUI_ACTIONS[action_index][1]))
                button.grid(row=i + 1, column=j, sticky='nwes')
                action_index += 1
                self.action_buttons_list.append(button)
        action_index = 0
        for i in range(2):
            for j in range(3):
                if i == 0 and j == 0:
                    continue
                button = Button(
                    self.action_buttons,
                    text=self.data.KEYBOARD_ACTIONS[action_index][0],
                    pady=5,
                    command=functools.partial(
                        self._append_text_piece_action,
                        self.data.KEYBOARD_ACTIONS[action_index][1]))
                button.grid(row=i + 4, column=j, sticky='nwes')
                self.action_buttons_list.append(button)
                action_index += 1
        action_index = 0
        for j in range(3):
            button = Button(self.action_buttons,
                            text=self.data.WINDOW_ACTIONS[action_index][0],
                            pady=5,
                            command=functools.partial(
                                self._append_window_action,
                                self.data.WINDOW_ACTIONS[action_index][1]))
            button.grid(row=6, column=j, sticky='nwes')
            if j > 0:
                button.config(state=DISABLED)
            self.action_buttons_list.append(button)
            action_index += 1
        action_index = 0
        for j in range(2):
            button = Button(self.action_buttons,
                            text=self.data.OTHER_ACTIONS[action_index][0],
                            pady=5,
                            command=functools.partial(
                                self._append_other_action,
                                self.data.OTHER_ACTIONS[action_index][1]))
            button.grid(row=7, column=j + 1, sticky='nwes')
            self.action_buttons_list.append(button)
            action_index += 1
        # insert another layer for hover-over data about script action

        return

    # GUI PIECES COLUMN
    #
    #
    def create_gui_pieces_list(self):
        gui_pieces_label = Label(self.master,
                                 text='GUI PIECES (click to view)')
        gui_pieces_label.grid(row=0, column=0)
        self.gui_piece_buttons = []
        self.gui_pieces_pad = Frame(self.master)
        self.gui_pieces_pad.grid(row=1, column=0, sticky='nw')
        button_index = 0
        for j in range(2):
            for i in range(25):
                new_button = Button(self.gui_pieces_pad,
                                    text='',
                                    bg='blue',
                                    fg='white',
                                    borderwidth=0,
                                    width=15,
                                    padx=0,
                                    pady=0,
                                    command=functools.partial(
                                        self._gui_piece_button_click,
                                        button_index))
                button_index += 1
                new_button.grid(row=i, column=j, sticky='w')
                self.gui_piece_buttons.append(new_button)
        self.gui_piece_extras = Frame(self.master)
        self.gui_piece_extras.grid(row=2, column=0, sticky='nwes')
        self.take_new_gui_piece_button = Button(self.gui_piece_extras,
                                                text='Take New',
                                                command=self._get_gui_piece)
        self.take_new_gui_piece_button.grid(row=0, column=0, sticky='nwes')
        # TO FINISH -- LOAD BUTTON
        self.load_png_gui_piece_button = Button(self.gui_piece_extras,
                                                text='Load Png',
                                                command=self._dummy)
        self.load_png_gui_piece_button.config(state=DISABLED)
        self.load_png_gui_piece_button.grid(row=0, column=1, sticky='nwes')
        # TO FINISH -- REMOVE BUTTON
        self.remove_gui_piece_button = Button(
            self.gui_piece_extras,
            text='Remove',
            command=lambda: self._activate_gui_pieces_list(None))
        self.remove_gui_piece_button.grid(row=0, column=2, sticky='nwes')
        return

    def _append_gui_pieces_list(self, gui_piece):
        gui_piece_text = '{0}. {1}'.format(len(self.gui_pieces) + 1, gui_piece)
        self.gui_piece_buttons[len(
            self.gui_pieces)].config(text=gui_piece_text)
        self.gui_pieces.append(gui_piece)
        return

    def _remove_gui_piece(self, button_index):
        removed_gui_piece = self.gui_pieces.pop(button_index)
        if button_index < len(self.gui_pieces):
            for replace_index in range(button_index, len(self.gui_pieces)):
                self.gui_piece_buttons[replace_index].config(
                    text='{0}. {1}'.format(replace_index +
                                           1, self.gui_pieces[replace_index]))
        self.gui_piece_buttons[len(self.gui_pieces)].config(text='')
        for index in range(len(self.script_lines)):
            line_data = self.script_lines[index][-1]
            if line_data == removed_gui_piece:
                data = '<right-click>', self.script_lines[index]
                self._replace_gui_piece(data)
        return

    def _activate_gui_pieces_list(self, script_line_data):
        if len(self.gui_pieces):
            for button in self.gui_piece_buttons:
                button.config(fg='white', bg='red')
            self.script_pad.config(state=DISABLED)
            self.print_button.config(state=DISABLED)
            for button in self.action_buttons_list:
                button.config(state=DISABLED)
            self.take_new_gui_piece_button.config(state=DISABLED)
            # self.load_png_gui_piece_button.config(state=DISABLED)
            self.remove_gui_piece_button.config(state=DISABLED)
            self.gui_piece_list_active = True
            self.passed_script_data = script_line_data

    def _gui_piece_button_click(self, button_index):
        if button_index < len(self.gui_pieces):
            gui_piece = self.gui_pieces[button_index]
            if not self.gui_piece_list_active:
                self._display_gui_piece(gui_piece)
            else:
                if self.passed_script_data:
                    script_line_data = self.passed_script_data
                    data = gui_piece, script_line_data
                    self._replace_gui_piece(data)
                else:
                    self._remove_gui_piece(button_index)
                for button in self.gui_piece_buttons:
                    button.config(bg='blue', fg='white')
                self.print_button.config(state='normal')
                for button in self.action_buttons_list:
                    button.config(state='normal')
                if len(self.window_names) == 0:
                    self.action_buttons_list[15].config(state=DISABLED)
                    self.action_buttons_list[16].config(state=DISABLED)
                self.take_new_gui_piece_button.config(state='normal')
                # self.load_png_gui_piece_button.config(state='normal')
                self.remove_gui_piece_button.config(state='normal')
                self.gui_piece_list_active = False

    #     -- gui piece action functions --
    #
    #
    def _append_gui_piece_action(self, script_text):
        if self.auto_snap.get():
            gui_piece = self._get_gui_piece()
        else:
            gui_piece = '<right-click>'
        script_line = script_text.format(gui_piece)
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)

    def _gui_piece_menu_popup(self, event, script_line_data):
        self.popup_menu1 = Menu(self.root, tearoff=0)
        self.popup_menu1.add_command(label='View',
                                     command=functools.partial(
                                         self._display_gui_piece,
                                         script_line_data[-1]))
        self.popup_menu1.add_command(label='Take New',
                                     command=functools.partial(
                                         self._sub_new_gui_piece,
                                         script_line_data))
        self.popup_menu1.add_command(label='Choose From Others',
                                     command=functools.partial(
                                         self._activate_gui_pieces_list,
                                         script_line_data))
        self.popup_menu1.post(event.x_root, event.y_root)
        self.master.bind('<Button-1>', self._destroy_gui_piece_menu)
        self.master.bind('<Button-3>', self._destroy_gui_piece_menu)
        self.script_pad.bind('<Enter>', self._destroy_gui_piece_menu)

    def _get_gui_piece(self):
        self.root.iconify()
        self.gooey.take_new_gui_piece()
        self.root.deiconify()
        gui_piece = self.gooey.gui_piece_filename
        self._append_gui_pieces_list(gui_piece)
        return gui_piece

    def _display_gui_piece(self, gui_piece):
        if gui_piece != '<right-click>':
            self.img_viewer = Toplevel()
            self.img_viewer.title(gui_piece)
            img_open = Image.open(
                os.path.join(self.data.GUI_PIECE_DIR, gui_piece))
            img = ImageTk.PhotoImage(img_open)
            img_label = Label(self.img_viewer, image=img)
            img_label.image = img
            img_label.grid(row=0, column=0, padx=20, pady=20)

    def _replace_gui_piece(self, data):
        new_gui_piece, script_line_data = data
        line_number, script_text, gui_tagname, gui_tag_start, gui_tag_end, gui_piece = script_line_data
        self.script_pad.config(state='normal')
        self.script_pad.delete(gui_tag_start, gui_tag_end)
        self.script_pad.insert(gui_tag_start, new_gui_piece)
        self._scanfix_script_lines(None)

    def _sub_new_gui_piece(self, gui_tag_data):
        data = self._get_gui_piece(), gui_tag_data
        self._replace_gui_piece(data)

    def _destroy_gui_piece_menu(self, event):
        self.popup_menu1.destroy()

    #     -- window action functions --
    #
    #
    def _append_window_action(self, script_text):
        if script_text.split(' ')[0] == 'name_active_window':
            if len(self.window_names) == 0:
                self.action_buttons_list[13].config(state='normal')
                self.action_buttons_list[14].config(state='normal')
            window_name = 'window{0}'.format(
                str(len(self.window_names)).zfill(2))
            self.window_names.append(window_name)
        else:
            window_name = self.window_names[-1]
        script_line = script_text.format(window_name)
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)

    def _window_menu_popup(self, event, script_line_data):
        self.popup_menu2 = Menu(self.root, tearoff=0)
        for other_window_name in self.window_names:
            data = other_window_name, script_line_data
            self.popup_menu2.add_command(label=other_window_name,
                                         command=functools.partial(
                                             self._replace_window_name, data))
        self.popup_menu2.post(event.x_root, event.y_root)
        self.master.bind('<Button-1>', self._destroy_window_name_menu)
        self.master.bind('<Button-3>', self._destroy_window_name_menu)
        self.script_pad.bind('<Enter>', self._destroy_window_name_menu)

    def _replace_window_name(self, data):
        self.popup_menu2.destroy()
        new_window_name, script_line_data = data
        line_number, script_text, win_tagname, win_tag_start, win_tag_end, window_name = script_line_data
        self.script_pad.delete(win_tag_start, win_tag_end)
        self.script_pad.insert(win_tag_start, new_window_name)
        self._scanfix_script_lines(None)

    def _destroy_window_name_menu(self, event):
        self.popup_menu2.destroy()

    #     -- type_text action functions --
    #
    #
    def _append_text_piece_action(self, script_text):
        text_piece = '<right-click>'
        script_line = script_text.format(text_piece)
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)

    def _text_piece_popup(self, event, data):
        open_text_file = False
        text_piece = data[-1]
        if text_piece == '<right-click>':
            text_piece = ''

        if 'type' in data[1]:
            if 'type_text_file' in data[1]:
                open_text_file = True
            else:
                text_type_title = 'Text to Type:'
        else:
            text_type_title = 'Key(s) to Press:'
        if not open_text_file:
            self.get_text = Toplevel()
            self.get_text.title(text_type_title)
            self.text_entry = Entry(self.get_text,
                                    text=text_piece,
                                    width=75,
                                    font=("Helvetica", 12))
            self.text_entry.grid()
            self.text_entry.bind(
                '<Return>',
                lambda event, arg=data: self._replace_text_piece(event, arg))
        else:
            self._open_text_file(data)

    def _open_text_file(self, script_line_data):
        f = tkFileDialog.askopenfilename(initialdir=self.data.TXT_FILE_DIR,
                                         title="Open Text File",
                                         filetypes=(("txt files", "*.txt"),
                                                    ("all files", "*.*")))
        if f is None:
            return
        with open(f, 'r') as openfile:
            text_from_file = openfile.read()
        self.text_file_pass = f.rpartition('/')[2]
        self._replace_text_piece(None, script_line_data)
        return

    def _replace_text_piece(self, event, data):
        line_number, script_text, text_tagname, text_tag_start, text_tag_end, text_piece = data
        if 'type_text_file' in script_text:
            new_text_piece = self.text_file_pass
        else:
            new_text_piece = self.text_entry.get()
            self.get_text.destroy()
        self.script_pad.config(state='normal')
        self.script_pad.delete(text_tag_start, text_tag_end)
        self.script_pad.insert(text_tag_start, new_text_piece)
        self._scanfix_script_lines(None)

    #     -- sleep & other action functions --
    #
    #
    def _append_other_action(self, script_text):
        script_line = script_text
        self.script_pad.insert(END, script_line)
        self._scanfix_script_lines(None)
Ejemplo n.º 20
0
class TextEditor(EventBasedAnimationClass):

    @staticmethod
    def make2dList(rows, cols):
        # From 15-112 class notes
        a=[]
        for row in xrange(rows): a += [[0]*cols]
        return a

    @staticmethod
    def readFile(filename, mode="rt"):
        # From 15-112 class notes
        # rt = "read text"
        with open(filename, mode) as fin:
            return fin.read()

    @staticmethod
    def writeFile(filename, contents, mode="wt"):
        # From 15-112 class notes
        # wt = "write text"
        with open(filename, mode) as fout:
            fout.write(contents)


    def highlightError(self, lineNumber):
        # highlights error in the code based on line number
        self.textWidget.tag_remove("error",1.0,END)
        self.textWidget.tag_add("error", "%d.0"%lineNumber,
            "%d.end"%lineNumber)
        self.textWidget.tag_config("error", underline = 1)

    def colorIsBlack(self, color):
        # ranks whether a color is nearing black or white
        color = color[1:]
        count = int(color,16)
        if(count<(16**len(color) -1 )/2):
            return True
        return False

    def styleTokens(self,tokenisedText,colorScheme,
                    startIndex,seenlen,seenLines,flag):
        # apply style to tokens in the text
        for token in tokenisedText:
            styleForThisToken = colorScheme.style_for_token(token[0])
            if(styleForThisToken['color']):
                self.currentColor = "#" + styleForThisToken['color'] 
            else:
                if(self.colorIsBlack(colorScheme.background_color)):
                    self.currentColor = "White"
                else: self.currentColor = "Black"
            if(token[1] == "\n"): seenLines += 1
            if(seenLines > 23 and flag): break
            # the '#' is to denote hex value
            textWidget = self.textWidget
            newSeenLen = seenlen + len(token[1])
            textWidget.tag_add(startIndex+"+%dc"%seenlen,
                startIndex+"+%dc"%(seenlen),
                startIndex+"+%dc"%(newSeenLen))
            self.textWidget.tag_config(startIndex+"+%dc"%seenlen,
                foreground = self.currentColor)
            seenlen = newSeenLen

    def checkErrors(self):
        # checks whether there is an error in the code by parsing it
        # and analysing the traceback
        errors = MyParse().pythonCodeContainsErrorOnParse(self.currentText)
        if(errors[0]):
            try:
                lineNumber=int(errors[1][-5][errors[1][-5].find("line ")+5:])
            except:
                lineNumber=int(errors[1][-7][errors[1][-7].find("line ")+5:])
            self.highlightError(lineNumber)
        else:
            self.textWidget.tag_remove("error",1.0,END)

    def highlightText(self,lineCounter = "1",columnCounter = "0",flag = False):
        # highlight text since syntax mode is on
        text = self.currentText.split("\n")
        text = "\n".join(text[int(lineCounter)-1:])
        startIndex = lineCounter + "." + columnCounter
        seenlen, seenLines = 0,0
        tokenisedText = pygments.lex(text, self.lexer)
        if(self.colorScheme):
            colorScheme = pygments.styles.get_style_by_name(self.colorScheme)
        else:
            colorScheme = pygments.styles.get_style_by_name(
                self.defaultColorScheme)
        if(self.colorIsBlack(colorScheme.background_color)):
            self.insertColor = "White"
        else: self.insertColor = "Black"
        self.textWidget.config(background = colorScheme.background_color,
            highlightbackground = colorScheme.highlight_color,
            highlightcolor = colorScheme.highlight_color,
            insertbackground = self.insertColor)
        self.styleTokens(tokenisedText,colorScheme,startIndex,seenlen,
            seenLines, flag)
        if(self.fileExtension == ".py" and self.errorDetectionMode):
            self.checkErrors()

    def editDistance(self,currentWord, word):
        # wagner-fischer algorithm for calculating levenshtein distance
        dp = TextEditor.make2dList(len(currentWord)+1, len(word)+1)
        costOfInsertion = 1
        costOfDeletion = 1
        costOfSubstitution = 1
        for i in xrange(len(currentWord)+1):
            dp[i][0] = i*costOfInsertion
        for i in xrange(len(word)+1):
            dp[0][i] = i*costOfDeletion
        for i in xrange(1,len(currentWord)+1):
            for j in xrange(1,len(word)+1):
                if(currentWord[i-1] == word[j-1]):
                    dp[i][j] = dp[i-1][j-1]
                else:
                    dp[i][j] = min(dp[i][j-1]+costOfInsertion,
                            dp[i-1][j]+costOfDeletion,dp[i-1][j-1] + 
                            costOfSubstitution)
        return dp[len(currentWord)][len(word)]

    def wordsAreSimilar(self, currentWord, word):
        if(word.startswith(currentWord)):
            return True, abs(len(currentWord)-len(word))/2
        similarity = self.editDistance(currentWord, word)
        return float(similarity)/len(currentWord)<=.5,similarity 

    def cleanWord(self, word):
        # cleans a word by removing all not (char or numbers)
        processedWord = ""
        for c in word:
            if(c in string.ascii_uppercase or
                c in string.ascii_lowercase or 
                c in "1234567890"):
                processedWord += c
        return processedWord

    def sortSuggestionDict(self):
        # sorts suggestion dictionary
        self.suggestionDict = sorted(self.suggestionDict.items(),
             key=operator.itemgetter(1))

    def findMatchesToWord(self, currentWord):
        # checks words in current text and adds them to suggestionDict
        # based on whether they are similar or not
        if(currentWord == ""): return []
        listOfWords = self.currentText.split()
        for word in listOfWords:
            word = self.cleanWord(word)
            if word!= currentWord[:-1]:
                similar = self.wordsAreSimilar(currentWord, word)
                if(similar[0] and word not in self.suggestionDict):
                    self.suggestionDict[word] = similar[1]
        self.sortSuggestionDict
        return self.suggestionDict

    def getCurrentWord(self):
        # gets current word user is typing
        word = self.textWidget.get(self.textWidget.index("insert wordstart"), 
            self.textWidget.index("insert wordend"))
        if(word == "\n" or word == " "):
            word = self.textWidget.get(
                self.textWidget.index("insert -1c wordstart"), 
                self.textWidget.index("insert wordend"))
        word = word.replace("\n","")
        return word

    def openFile(self):
        # opens a file, also detects whether it is 
        # a program or not
        self.initProgrammingModeAttributes()
        path = tkFileDialog.askopenfilename()
        if(path):
            self.currentFilePath = path
            self.currentFile = os.path.basename(path)
            self.currentText = TextEditor.readFile(path)
            self.textWidget.delete(1.0,END)
            self.textWidget.insert(1.0,self.currentText)
            self.fileExtension = os.path.splitext(path)[1]
            self.root.wm_title(self.currentFile)
            if(self.fileExtension != ".txt" and
                pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])):
                self.programmingMode = True
                self.lexer = pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])
                self.highlightText()

    def saveFile(self):
        if(self.currentFilePath):
            TextEditor.writeFile(self.currentFilePath, self.currentText)

    def saveAs(self):
        # saves a file, automatically adds extension
        path = tkFileDialog.asksaveasfilename()
        if(path):
            if(self.fileExtension): path += self.fileExtension
            else: path += ".txt"
            TextEditor.writeFile(path, self.currentText)
            self.currentFilePath = path
            self.currentFile = os.path.basename(path)
            self.root.wm_title(self.currentFile)
            if(self.fileExtension !=".txt" and
                pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])):
                self.programmingMode = True
                self.lexer = pygments.lexers.guess_lexer_for_filename(
                    "example%s"%self.fileExtension,[])
                self.highlightText()

    def newTab(self):
        TextEditor(1500,50).run()

    def undo(self):
        self.textWidget.edit_undo()

    def redo(self):
        self.textWidget.edit_redo()

    def cut(self):
        if self.textWidget.tag_ranges("sel"):
            self.clipboard = self.textWidget.get("sel.first","sel.last")
            self.textWidget.delete("sel.first","sel.last")
        else:
            self.clipboard = ""

    def copy(self):
        if self.textWidget.tag_ranges("sel"):
            self.clipboard = self.textWidget.get("sel.first","sel.last")

    def paste(self):
        if self.textWidget.tag_ranges("sel"):
            self.textWidget.insert("insert",self.clipboard)

    def resetFontAttribute(self):
        self.font = tkFont.Font(family = self.currentFont,
            size = self.fontSize)
        self.textWidget.config(font = self.font)

    def increaseFontSize(self):
        self.fontSize += 2
        self.resetFontAttribute()

    def decreaseFontSize(self):
        self.fontSize -= 2
        self.resetFontAttribute()

    def highlightString(self,searchString):
        lenSearchString = len(searchString) 
        self.textWidget.tag_delete("search")
        self.textWidget.tag_config("search", background = "#FFE792")
        start = 1.0
        while True:
            pos = self.textWidget.search(searchString, start, stopindex = END)
            if(not pos):
                break
            self.textWidget.tag_add("search", pos, pos+"+%dc"%(lenSearchString))
            start = pos + "+1c"

    # search highlight color #FFE792
    def searchInText(self):
        title = "Search"
        message = "Enter word to search for"
        searchString = tkSimpleDialog.askstring(title,message)
        if(searchString == None): return
        self.highlightString(searchString)

    def commentCode(self):
        # puts an annotation in the currently selected text
        title = "Comment"
        message = "Enter comment for selection"
        comment = tkSimpleDialog.askstring(title,message)
        if(comment == None): return
        if self.textWidget.tag_ranges("sel"):
            self.textWidget.tag_add("comment",
                self.textWidget.index(SEL_FIRST),
                self.textWidget.index(SEL_LAST))
            self.textWidget.tag_config("comment", underline = 1)
            self.comments += [self.textWidget.index(SEL_FIRST) + "|" +
                self.textWidget.index(SEL_LAST) + "|" + comment]
            if(self.collaborativeCodingMode):
                # can only send strings through socket 
                self.client.sendData(";".join(self.comments))

    def findAndReplaceInText(self):
        # finds and replaces a word
        title = "Find and replace"
        message = "Enter string to remove"
        stringToRemove = tkSimpleDialog.askstring(title,message)
        if(stringToRemove == None): return
        message = "Enter string to add"
        stringToReplace = tkSimpleDialog.askstring(title, message)
        if(stringToReplace == None): return
        self.currentText = self.currentText.replace(
            stringToRemove, stringToReplace)
        self.textWidget.delete(1.0, END)
        self.textWidget.insert(1.0, self.currentText)
        self.highlightString(stringToReplace)

    def initTextWidget(self):
        # initialises text widget
        # used the below link to make it stop resizing on font change
        # http://stackoverflow.com/questions/9833698/
        # python-tkinter-how-to-stop-text-box-re-size-on-font-change
        self.textWidgetContainer = Frame(self.root, borderwidth = 1,
            relief = "sunken", width = 600, height = 400)
        self.textWidgetContainer.grid_propagate(False)
        self.textWidgetContainer.pack(side = TOP, fill = "both", expand = True)
        self.textWidgetContainer.grid_rowconfigure(0, weight=1)
        self.textWidgetContainer.grid_columnconfigure(0, weight=1)
        self.textWidget = ScrolledText(self.textWidgetContainer, 
            width = 10,
            font = self.font,
            background =self.textWidgetBackGround)
        self.textWidget.grid(row = 0, column = 0, sticky = "nsew")
        self.textWidget.config(insertbackground = self.cursorColor,
            foreground = self.textWidgetDefaultFontColor,
            tabs = ("%dc"%self.tabWidth,"%dc"%(2*self.tabWidth)),
            undo = True)

    def initFont(self):
        self.currentFont = "Arial"
        self.fontSize = 15
        self.font = tkFont.Font(family = self.currentFont, 
            size = self.fontSize)

    def initProgrammingModeAttributes(self):
        self.programmingMode = False
        self.errorDetectionMode = False
        self.colorScheme = None
        self.defaultColorScheme = "monokai"
        self.lexer = None

    def initMoreGeneralAttributes(self):
        self.hostingServer = False
        self.hostIP = None
        self.joinedServerIP = None
        self.server = None
        self.client = None
        self.spellCorrector = SpellCorrector()
        self.root.wm_title("Untitled")
        self.commentButX = self.width - 300
        self.commentButY = 10
        self.commentButWidth = 200
        self.commentButHeight = self.height - 10

    def initGeneralAttributes(self):
        # general editor attributes
        self.currentText,self.tabWidth = "",1
        self.rulerWidth,self.currentFilePath = None,None
        self.currentFile = None
        self.fileExtension = None
        self.suggestionDict = dict()
        self.indentationLevel = 0
        self.prevChar = None
        self.spellCorrection = False
        self.clipboard = ""
        self.comments = ["comments"]
        self.collaborativeCodingMode = False
        self.insertColor = "Black"
        self.initMoreGeneralAttributes()

    def initTextWidgetAttributes(self):
        self.textWidgetBackGround = "White"
        self.textWidgetDefaultFontColor = "Black"
        self.textWidgetTabSize = ""
        self.cursorColor = "Black"

    def initAttributes(self):
        self.initGeneralAttributes()
        self.initFont()
        self.initProgrammingModeAttributes()
        self.initTextWidgetAttributes()

    def addEditMenu(self):
        self.editMenu = Menu(self.menuBar, tearoff = 0)
        self.editMenu.add_command(label = "Undo", command = self.undo)
        self.editMenu.add_command(label = "Redo", command = self.redo)
        self.editMenu.add_command(label = "Cut", command = self.cut)
        self.editMenu.add_command(label = "Copy", command = self.copy)
        self.editMenu.add_command(label = "Paste", command = self.paste)
        self.editMenu.add_command(label = "Increase Font", 
            command = self.increaseFontSize)
        self.editMenu.add_command(label = "Decrease Font", 
            command = self.decreaseFontSize)
        self.menuBar.add_cascade(label = "Edit", menu = self.editMenu)

    def addFileMenu(self):
        self.fileMenu = Menu(self.menuBar, tearoff = 0)
        self.fileMenu.add_command(label = "Open", command = self.openFile)
        self.fileMenu.add_command(label = "New File", command = self.newTab)
        self.fileMenu.add_command(label = "Save", command = self.saveFile)
        self.fileMenu.add_command(label = "Save As", command = self.saveAs)
        self.menuBar.add_cascade(label = "File", menu = self.fileMenu)

    def setFileExtension(self, ext):
        # sets file extension
        self.fileExtension = ext
        self.programmingMode = True
        try:
            self.lexer = pygments.lexers.guess_lexer_for_filename("example%s"%self.fileExtension,[])
        except:
            self.lexer = pygments.lexers.guess_lexer_for_filename("example.py",[])
        self.highlightText()

    def setColorScheme(self, colorScheme):
        self.colorScheme = colorScheme
        self.programmingMode = True
        # assumes start from python
        if(not self.lexer):
            self.lexer = pygments.lexers.guess_lexer_for_filename("example.py",[])
            self.fileExtension = ".py"
        self.highlightText()

    # should have radio buttons for this
    def turnOnErrorDetection(self):
        self.errorDetectionMode = True
        self.setFileExtension(".py")

    def turnOffErrorDetection(self):
        self.errorDetectionMode = False

    def turnOnSpellCorrection(self):
        self.spellCorrection = True

    def turnOffSpellCorrection(self):
        self.spellCorrection = False

    def addErrorDetectionMenu(self):
        self.errorDetectionMenu = Menu(self.menuBar, tearoff = 0)
        self.errorDetectionMenu.add_command(label = "Python error detection ON",
            command = self.turnOnErrorDetection)
        self.errorDetectionMenu.add_command(label = "Python error detection OFF",
            command = self.turnOffErrorDetection)
        self.viewMenu.add_cascade(label = "Error Detection",
            menu = self.errorDetectionMenu)

    def addSpellCorrectionMenu(self):
        self.spellCorrectionMenu = Menu(self.menuBar, tearoff = 0)
        self.spellCorrectionMenu.add_command(label = "Spelling Correction ON",
            command = self.turnOnSpellCorrection)
        self.spellCorrectionMenu.add_command(label = "Spelling Correction OFF",
            command = self.turnOffSpellCorrection)
        self.viewMenu.add_cascade(label = "Spelling Correction",
            menu = self.spellCorrectionMenu)

    def addColorSchemeCommand(self, name):
        self.colorSchemeMenu.add_command(label = name,
                command = lambda : self.setColorScheme(name))

    def addColorSchemeMenu(self):
        # colorScheme Menu
        self.colorSchemeMenu = Menu(self.menuBar, tearoff = 0)
        self.addColorSchemeCommand("manni")
        self.addColorSchemeCommand("igor")
        self.addColorSchemeCommand("xcode")
        self.addColorSchemeCommand("vim")
        self.addColorSchemeCommand("autumn")
        self.addColorSchemeCommand("vs")
        self.addColorSchemeCommand("rrt")
        self.addColorSchemeCommand("native")
        self.addColorSchemeCommand("perldoc")
        self.addColorSchemeCommand("borland")
        self.addColorSchemeCommand("tango")
        self.addColorSchemeCommand("emacs")
        self.addColorSchemeCommand("friendly")
        self.addColorSchemeCommand("monokai")
        self.addColorSchemeCommand("paraiso-dark")
        self.addColorSchemeCommand("colorful")
        self.addColorSchemeCommand("murphy")
        self.addColorSchemeCommand("bw")
        self.addColorSchemeCommand("pastie")
        self.addColorSchemeCommand("paraiso-light")
        self.addColorSchemeCommand("trac")
        self.addColorSchemeCommand("default")
        self.addColorSchemeCommand("fruity")
        self.menuBar.add_cascade(label = "Color Scheme",
            menu = self.colorSchemeMenu)

    def addLanguageCommand(self, language, extension):
        self.syntaxMenu.add_command(label = language, 
            command = lambda : self.setFileExtension(extension))

    def addSyntaxMenu(self):
        self.syntaxMenu = Menu(self.menuBar, tearoff = 0)
        self.addLanguageCommand("Python",".py")
        self.addLanguageCommand("C++",".cpp")
        self.addLanguageCommand("Javascript",".js")
        self.addLanguageCommand("Java",".java")
        self.addLanguageCommand("HTML",".html")
        self.addLanguageCommand("CSS",".css")
        self.addLanguageCommand("PHP",".php")
        self.addLanguageCommand("Haskell",".hs")
        self.addLanguageCommand("Clojure",".clj")
        self.addLanguageCommand("CoffeeScript",".coffee")
        self.addLanguageCommand("AppleScript",".scpt")
        self.addLanguageCommand("Objective C",".h")
        self.addLanguageCommand("Scheme",".scm")
        self.addLanguageCommand("Ruby",".rb")
        self.addLanguageCommand("OCaml",".ml")
        self.addLanguageCommand("Scala",".scala")
        self.viewMenu.add_cascade(label = "Syntax", menu = self.syntaxMenu)
        self.menuBar.add_cascade(label = "View", menu = self.viewMenu)

    def addViewMenu(self):
        self.viewMenu = Menu(self.menuBar, tearoff = 0)
        # syntax Menu
        self.addSyntaxMenu()
        self.addColorSchemeMenu()
        self.addErrorDetectionMenu()
        self.addSpellCorrectionMenu()

    def displayMessageBox(self, title = "", text = ""):
        tkMessageBox.showinfo(title, text)

    def startServer(self):
        # starts a new thread running the server
        self.collaborativeCodingMode = True
        start_new_thread(self.server.acceptConnection(),())

    def startRecieving(self):    
        # starts a new thread to recieve data
        start_new_thread(self.client.recieveData,())

    def collaborateWrapper(self):
        # starts collaborative mode
        if(not self.collaborativeCodingMode):
            self.server = Server()
            host = self.server.getHost()
            self.hostingServer = True
            self.hostIP = host
            self.client = Client(host)
            start_new_thread(self.startServer,())
            start_new_thread(self.startRecieving,())
            self.client.sendData(";".join(self.comments))
            time.sleep(.01)
            self.client.sendData(self.currentText)

    def joinServer(self):
        # starts a new thread to recieve data
        start_new_thread(self.client.recieveData,())

    def joinServerWrapper(self):
        # join a server for collaboration
        if(not self.collaborativeCodingMode):
            try:
                self.collaborativeCodingMode = True
                title = "Host IP address"
                message = "Enter IP address of server to link to."
                host = tkSimpleDialog.askstring(title,message)
                if(host == None): 
                    self.collaborativeCodingMode = False
                    return       
                self.joinedServerIP = host
                self.client = Client(host)
                start_new_thread(self.joinServer,())
            except:
                self.collaborativeCodingMode = False
                self.joinedServerIP = None
                print "Server isn't running"
                self.displayMessageBox("Error","Server isn't running")

    def addNetworkMenu(self):
        self.networkMenu = Menu(self.menuBar, tearoff = 0)
        self.networkMenu.add_command(label = "Collaborate| Create new server", 
                                    command = self.collaborateWrapper)
        self.networkMenu.add_command(label = "Collaborate| Join server", 
                                    command = self.joinServerWrapper)
        self.menuBar.add_cascade(label = "Collaborative", 
                                menu = self.networkMenu)
        
    def addFindMenu(self):
        self.findMenu = Menu(self.menuBar, tearoff = 0)
        self.findMenu.add_command(label = "Search", command =self.searchInText)
        self.findMenu.add_command(label = "Find and Replace", 
            command = self.findAndReplaceInText)
        self.menuBar.add_cascade(label = "Find", menu = self.findMenu)

    def showHelp(self):
        self.helpCanvasRoot = Tk()
        self.helpCanvas = Canvas(self.helpCanvasRoot, width = 600, height = 600)
        self.helpCanvasRoot.wm_title("Collaborative Coder | Help")
        self.helpCanvas.pack()
        canvas = self.helpCanvas
        canvas.create_rectangle(0,0,600,600,fill="Grey")
        canvas.create_text(300,30,text = "Collaborative Coder!", 
            font = "Arial 30 bold italic underline")
        canvas.create_rectangle(8,48,592,596,fill = "White",
            width = 2)
        message = """
        1. Find all options on the top of the screen in the menu bar.
        2. There are two boxes on the screen which hold 
            comments and suggestions(Autocomplete and
            Spelling Correction) respectively.
            To choose a suggestion double click on it.
        3. To enable syntax highlighting choose the programming 
            language in View --> Syntax menu.
        4. Choose the color scheme you want in the color
            scheme menu.
        5. Press Command+B to compile python code.
        6. Turn on or off dynamic python error detection and 
           spelling correction from view menu.
        7. To collaborate with others you can either start a server
            or join a server
                1. To start a server click 
                    Collaboration --> Start New Server
                    This will display your IP address in the 
                    bottom which your friend will join.
                2. To join click Collaboration --> Join Server
                    Enter server IP you want to join
                    and click OK.
        8. To annotate select a piece of text and press 
            the comment button in the bottom right. When your cursor
            shows up in those indices the annotation will show
            up in the comments box.

        """
        canvas.create_text(10,50,text = message, anchor = "nw",
            fill = "Dark Blue", font = "Arial 18 bold")
        canvas.mainloop()

    def showAbout(self):
        self.aboutCanvasRoot = Tk()
        self.aboutCanvas = Canvas(self.aboutCanvasRoot, width = 600,height =670)
        self.aboutCanvasRoot.wm_title("Collaborative Coder | About")
        self.aboutCanvas.pack()
        self.aboutCanvas.create_rectangle(0,0,600,670,fill="Grey")
        self.aboutCanvas.create_text(300,30,text = "Collaborative Coder!", 
            font = "Arial 30 bold italic underline")
        self.aboutCanvas.create_rectangle(8,48,592,652,fill = "White",
            width = 2)
        message = """
        This is a text editor application made by Manik Panwar
        for the course 15-112 Fundamentals of programming and 
        computer science at Carnegie Mellon University,
        which you can use to edit text documents and write code.
        Not only can you do this on your own
        machine but you can also collaborate 
        with friends live on different computers 
        through the internet and edit the same 
        text documents; all the while commenting 
        and annotating the text which automatically 
        shows up on your friends computer.
        Apart from all the general text editor features 
        this also supports syntax highlighting for 
        all major languages, autocompletion(which show up 
        in the suggestion box), autoindenation,
        auto parentheses completion, spelling correction,
        dynamic python error detection, multiple text editor 
        color schemes and live collaboration with 
        others on other machines. For collaborating with 
        a friend you can either create a server and ask 
        your friends to join your server or
        join an already running server. All you have to 
        do now is choose a language from the syntax menu, 
        choose your color scheme and preferences, set up 
        collaboration with a friend, and get started on 
        that 15-112 inspired project you are now about to do!
        """
        self.aboutCanvas.create_text(10,50,text = message, anchor = "nw",
            fill = "Dark Blue", font = "Arial 18 bold")
        self.aboutCanvasRoot.mainloop()

    def addHelpMenu(self):
        self.helpMenu = Menu(self.menuBar, tearoff = 0)
        self.helpMenu.add_command(label = "Help", command = self.showHelp)
        self.helpMenu.add_command(label = "About", command = self.showAbout)
        self.menuBar.add_cascade(label = "Help", menu = self.helpMenu)

    def initListBox(self):
        self.suggestionBox = Listbox(self.root, width = 50,
                    height = 5,selectmode = SINGLE)
        self.scrollbar = Scrollbar(self.root, orient = VERTICAL)
        self.scrollbar.config(command = self.suggestionBox.yview)
        self.scrollbar.pack(side = RIGHT,fill = Y)
        self.suggestionBox.config(yscrollcommand = self.scrollbar.set,
            background = "Grey")
        self.suggestionBox.pack(side = RIGHT)
        self.suggestionBox.insert(END, "Suggestions(Autocomplete and Spelling correction):")

    def initCommentBox(self):
        self.commentBoxFontSize = 20
        self.commentBox = Listbox(self.root, width = 180,height = 5, 
                                    selectmode = SINGLE)
        self.commentScrollbar = Scrollbar(self.root, orient = VERTICAL)
        self.commentScrollbar.config(command = self.commentBox.yview)
        self.commentScrollbar.pack(side = RIGHT,fill = Y)
        self.commentBoxFont = tkFont.Font(family = self.currentFont,
            size = self.commentBoxFontSize)
        self.commentBox.config(yscrollcommand = self.commentScrollbar.set,
            background = "Grey", foreground = "Black",
            font = self.commentBoxFont)
        self.commentBox.pack(side = RIGHT, fill = X)
        self.commentBox.insert(END,"Comments (if any) in current cursor index:")

    def initMenuBar(self):
        # init menuBar
        self.menuBar = Menu(self.root)
        # file menu option
        self.addFileMenu()
        # Edit menu option
        self.addEditMenu()
        # Find menu option
        self.addFindMenu()
        # View menu option
        self.addViewMenu()
        # Network menu
        self.addNetworkMenu()
        # Help menu
        self.addHelpMenu()
        self.root.config(menu = self.menuBar)

    def onTabPressed(self, event):
        if(self.fileExtension == ".py"):
            self.indentationLevel += 1

    def bindEvents(self):
        self.textWidget.bind("<Tab>",lambda event: self.onTabPressed(event))
        self.suggestionBox.bind("<Double-Button-1>", 
                                lambda event: self.replaceWord(event))

    def indent(self):
        if(self.fileExtension == ".py"):
            self.textWidget.insert("insert","\t"*self.indentationLevel)

    def modifyIndent(self, event):
        # modifies indentation based on python rules
        if(self.fileExtension == ".py"):
            if(event.char == ":"): 
                self.indentationLevel += 1
            elif(event.keysym == "BackSpace"):
                line = self.textWidget.get("insert linestart","insert lineend")
                flag = True
                for c in line:
                    if not((c == " ") or (c == "\t")):
                        flag = False
                        break
                if(flag):
                    self.indentationLevel = (self.indentationLevel - 1 if 
                        self.indentationLevel>=1 else 0)

    def completeParens(self, event):
        # autocomplete parens
        if(event.char == "{" and self.programmingMode):
            self.textWidget.insert("insert","\n"+"\t"*self.indentationLevel+"}")
            self.currentText = self.textWidget.get(1.0,END)
        elif(event.char == "(" and self.programmingMode):
            self.textWidget.insert("insert",")")
            self.currentText = self.textWidget.get(1.0,END)

    def replaceWord(self,event):
        # replaces a word on double click in suggestion box
        word = self.getCurrentWord()
        self.textWidget.delete("insert - %dc"%(len(word)),"insert")
        wordToReplace = ""
        if(self.suggestionBox.curselection()):
            wordToReplace = self.suggestionBox.get(
                            self.suggestionBox.curselection())
            if(wordToReplace != "Suggestions(Autocomplete and Spelling correction):"):
                self.textWidget.insert("insert", wordToReplace)
            self.resetSuggestions()

    def calculateSuggestions(self):
        # populates suggestion box
        self.suggestionBox.delete(0,END)
        self.suggestionDict = dict()
        currentWord = self.getCurrentWord()
        self.findMatchesToWord(currentWord)
        self.suggestionBox.insert(END,
            "Suggestions(Autocomplete and Spelling correction):")
        for key in self.suggestionDict:
            self.suggestionBox.insert(END,key)
        if(self.spellCorrection):
            correctSpelling = self.spellCorrector.correct(currentWord)
            if(not currentWord.startswith(correctSpelling)):
                self.suggestionBox.insert(END, correctSpelling)

    def resetSuggestions(self):
        self.suggestionBox.delete(0,END)
        self.suggestionBox.insert(END, 
            "Suggestions(Autocomplete and Spelling correction):")
        self.suggestionDict = dict()

    def compilePythonCode(self):
        if(self.currentFile):
            self.saveFile()
            original_stdout = sys.stdout
            try:
                a = compiler.compile(self.currentText, self.currentFile, 
                                    mode = "exec")
                # (http://stackoverflow.com/questions/4904079/
                # execute-a-block-of-python-code-with-exec-capturing-all-its-output)
                # captures stdout in temp stringIO buffer to get output
                # and then reverts changes
                buffer = StringIO()
                sys.stdout = buffer
                eval(a)
                sys.stdout = original_stdout
                val = buffer.getvalue()
                rt = Tk()
                outputText = ScrolledText(rt, width = 50)
                outputText.insert(END, val)
                outputText.pack()
                rt.mainloop()
            except:
                print "Error!"
                self.displayMessageBox("Error","There is an error in the code.")
                sys.stdout = original_stdout
        else:
            self.saveAs()

    def getLineAndColFromIndex(self, index):
        return int(index.split('.')[0]),int(index.split('.')[1])

    def checkIfInCommonRange(self, comment):
        # check if insert is in range of any comment
        index = self.textWidget.index("insert")
        indexCStart = comment[0]
        indexCEnd = comment[1]
        line,col = self.getLineAndColFromIndex(index)
        line1,col1 = self.getLineAndColFromIndex(indexCStart)
        line2,col2 = self.getLineAndColFromIndex(indexCEnd)
        if((line>line1 and line<line2) or
            (line == line1 and col>=col1 and (line1!=line2 or col<=col2)) or 
            (line == line2 and col<=col2 and (line1!=line2 or col>=col1))):
            return True
        else:
            return False

    def checkComments(self):
        self.commentBox.delete(0,END)
        self.commentBox.insert(END,"Comments (if any) in current cursor index:")
        for comment in self.comments:
            if("|" in comment):
                comment = comment.split("|")
                if(self.checkIfInCommonRange(comment)):
                    self.commentBox.insert(END, comment[2])

    def onKeyPressed(self, event):
        ctrl  = ((event.state & 0x0004) != 0)
        shift = ((event.state & 0x0001) != 0)
        command = ((event.state & 0x0008) != 0)
        flag = False
        self.checkComments()
        if(self.textWidget.get(1.0,END)!=self.currentText):
            flag = True
        if(event.char.isalpha()):
            self.calculateSuggestions()
        if(event.keysym == "Return" and self.fileExtension == ".py"):
            self.indent()
        if(event.keysym in ["Return"," ","\n","\t","BackSpace","space"]):
            self.resetSuggestions()
        self.currentText = self.textWidget.get(1.0,END)
        self.modifyIndent(event)
        self.completeParens(event)
        if((flag) and self.collaborativeCodingMode):
            self.client.sendData(self.currentText)
        if(self.programmingMode):
            if((command and event.keysym in "vV")):
                self.highlightText()
            else:
                insertLineNumber = int(self.textWidget.index(
                                                    "insert").split(".")[0])
                self.highlightText(
                        str(insertLineNumber),"0", 
                        (event.keysym!="Return" and 
                        not self.collaborativeCodingMode)
                        ) 
        if(self.fileExtension == ".py" and command and event.keysym in "bB"):
            self.compilePythonCode()

    def onMousePressed(self, event):
        # remove search tag if it exists
        self.textWidget.tag_delete("search")
        self.checkComments()
        if((event.x>=self.commentButX) and 
            (event.x<=(self.commentButX + self.commentButWidth)) and
            (event.y>=self.commentButY) and 
            (event.y<=(self.commentButY + self.commentButHeight))):
            self.commentCode()

    def onTimerFired(self):
        pass

    def redrawAll(self):
        # draws info onto canvas
        self.canvas.delete(ALL)
        self.canvas.create_rectangle(0,0,self.width,self.height,fill = "Black")
        self.canvas.create_rectangle(self.commentButX,self.commentButY,
            self.commentButX+self.commentButWidth,
            self.commentButY+self.commentButHeight,fill = "Grey")
        self.canvas.create_text(self.commentButX + self.commentButWidth/2,
            self.commentButY + self.commentButHeight/2,text = "Comment")
        self.canvas.create_text(400,10,
            text = "Press help in the menu bar to get started", fill = "White")
        if(self.programmingMode):
            self.canvas.create_text(600,10,
                            text = "Programming mode on",fill="Green")
        if(self.errorDetectionMode):
            self.canvas.create_text(600,25,
                            text = "Error detection mode on",fill = "Green")
        if(self.spellCorrection):
            self.canvas.create_text(600,40,
                            text = "Spelling Correction on",fill = "Green")
        a = self.textWidget.index("insert")
        ln = int(a.split(".")[0])
        l = self.textWidget.get("insert linestart","insert")
        cn = 1
        for c in l:
            if(c == "\t"):
                cn += 4*self.tabWidth
            else:
                cn += 1
        self.canvas.create_text(100,10,text="Row:%d Column:%d"%(ln,cn),
                                fill = "White")
        self.canvas.create_text(850,30,text = "Collaborative Coder!",
            fill = "Grey", font = "Arial 30 bold")
        if(self.hostingServer):
            self.canvas.create_text(400,30,
                text = "Hosting server at IP: %s"%(self.hostIP),fill="White")
        elif(self.joinedServerIP):
            self.canvas.create_text(400,30,
                text = "Joined server at IP: %s"%(self.joinedServerIP),
                fill = "White")


    def initAnimation(self):
        self.timerCounter = 10000
        self.initAttributes()
        self.initTextWidget()
        self.initMenuBar()
        self.initListBox()
        self.initCommentBox()
        self.bindEvents()
Ejemplo n.º 21
0
class Example(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)

        self.master = master
        self.initUI()

    def initUI(self):
        #self.topMessage = StringVar()

        self.master.title("ZDRa Interface")
        self.pack(fill=BOTH, expand=1, side=LEFT)

        m1 = PanedWindow(self.master, width=750)
        m1.pack(fill=BOTH, expand=1)

        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)

        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar)
        zcgaMenu = Menu(menubar)
        zdraMenu = Menu(menubar)
        gpsaMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.onOpen)
        zcgaMenu.add_command(label="ZCGa Check", command=self.zcgacheck)
        zdraMenu.add_command(label="ZDRa Check", command=self.zdracheck)
        #zdraMenu.add_command(label = "Totalise Spec", command=self.totalisespec)
        #zdraMenu.add_command(label = "Add Refinements")
        gpsaMenu.add_command(label="Proof Skeleton",
                             command=self.createskeleton)
        gpsaMenu.add_command(label="ProofPower-Z Skeleton",
                             command=self.createppgpsa)
        gpsaMenu.add_command(label="Isabelle Skeleton",
                             command=self.createIsaPS)
        gpsaMenu.add_command(label="FillInIsaSkeleton", command=self.fillInIsa)
        menubar.add_cascade(label="File", menu=fileMenu)
        menubar.add_cascade(label="ZCGa", menu=zcgaMenu)
        menubar.add_cascade(label="ZDRa", menu=zdraMenu)
        menubar.add_cascade(label="GPSa", menu=gpsaMenu)

        self.txt = Text(self, yscrollcommand=scrollbar.set)
        self.txt.pack(fill=BOTH, expand=1)

        self.m2 = PanedWindow(m1, orient=VERTICAL)
        m1.add(self.m2)

        toplabel = Label(self.m2, text="Messages")
        toplabel.pack()

        self.top = ScrolledText(self.m2, wrap=WORD, state=DISABLED)
        self.m2.add(self.top)
        self.top.pack()

        bottomlabel = Label(self.m2, text="User input")
        bottomlabel.pack()

        self.bottom = ScrolledText(self.m2, wrap=WORD)
        self.m2.add(self.bottom)
        self.bottom.pack()

        scrollbar.config(command=self.txt.yview)

        self.txt.insert(
            END, "Please choose a specification by clicking on file then open")

        b = Button(self.m2, text="Submit Message", command=self.submitbutton)
        b.pack()

        self.file_opt = options = {}
        options['defaultextension'] = '.thy'
        options['filetypes'] = [('thy files', '.thy'), ('all files', '.*')]

        #self.topMessage.set("Please pick a specification from the top left")

    def totalisespec(self):
        self.gpsalocation = totalise.findgpsa(self.fl)
        if os.path.isfile(self.gpsalocation):
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END, "Found Specifications")
            self.top.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)

    def zdracheck(self):
        zdracheck.totalcheck(self.fl)
        #self.thedepgraph = zdracheck.creatdepgraphplot(self.fl)
        #self.thegoto = zdracheck.createplot(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, zdracheck.printoutput())
        self.top.config(state=DISABLED)
        self.depbutton = Button(self.m2,
                                text="Show Dependency",
                                command=self.showDependency)
        self.depbutton.pack()
        self.gotobutton = Button(self.m2,
                                 text="Show GoTo",
                                 command=self.showGoTo)
        self.gotobutton.pack()

    def zcgacheck(self):
        zcga.specCorrect(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, zcga.printoutput())
        self.top.config(state=DISABLED)

    def showGoTo(self):
        self.goto_location = totalise.find_goto_name(self.fl)
        gotoWindow = Toplevel()
        gotoWindow.title("GoTo Graph")
        canvas = Canvas(gotoWindow, width=600, height=600)
        canvas.pack()
        #photoimage = ImageTk.PhotoImage(file=self.goto_location)
        # canvas.create_image(300, 300, image=photoimage)
        gotoWindow.pack()
        #zdracheck.showplot(self.thegoto)

    def showDependency(self):
        self_dep_location = totalise.find_dp_name(self.fl)
        gotoWindow = Toplevel()
        gotoWindow.title("Dep Graph")
        canvas = Canvas(gotoWindow, width=600, height=600)
        canvas.pack()
        #   photoimage = ImageTk.PhotoImage(file=self_dep_location)
        # canvas.create_image(300, 300, image=photoimage)
        gotoWindow.pack()
        #zdracheck.showplot(self.thedepgraph)

    def showgpsa(self):
        self.gpsalocation = totalise.findgpsa(self.fl)
        if os.path.isfile(self.gpsalocation):
            gpsawindow = Toplevel()
            gpsawindow.title("ProofPower Skeleton")
            gpsaspec = ScrolledText(gpsawindow, wrap=WORD)
            gpsaspec.pack()
            gpsaspecif = self.readFile(self.gpsalocation)
            gpsaspec.config(state=NORMAL)
            gpsaspec.insert(END, gpsaspecif)
            gpsaspec.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)

    def showIsaSkel(self):
        self.Isalocation = totalise.findisagpsa(self.fl)
        if os.path.isfile(self.Isalocation):
            isawindow = Toplevel()
            isawindow.title("Isabelle Skeleton")
            isaspec = ScrolledText(isawindow, wrap=WORD)
            isaspec.pack()
            isaspecif = self.readFile(self.Isalocation)
            isaspec.config(state=NORMAL)
            isaspec.insert(END, isaspecif)
            isaspec.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(
                END,
                "Please convert specification into Isabelle Skeleton first")
            self.top.config(state=DISABLED)

    def fillInIsa(self):
        self.Isalocation = totalise.findisagpsa(self.fl)
        if os.path.isfile(self.Isalocation):
            if ('\\usepackage{zmathlang}' in open(
                    self.fl).read()) or ('\\usepackage{zmathlang}' in open(
                        self.fl).read()):
                self.Isalocation = totalise.findisagpsa(self.fl)
                zdra.x.fillinIsa(self.fl, self.Isalocation)
                zdra.x.fillinIsa(self.fl, self.Isalocation)
                zdra.x.fillNames(self.Isalocation)
                self.top.config(state=NORMAL)
                self.top.delete(1.0, END)
                self.top.insert(END,
                                "Isabelle Skeleton successfully filled in ")
                self.top.config(state=DISABLED)
            else:
                self.top.config(state=NORMAL)
                self.top.delete(1.0, END)
                self.top.insert(END, "Please select your isabelle skeleton:")
                self.top.config(state=DISABLED)
                filename = tkFileDialog.askopenfilename(**self.file_opt)
                zdra.x.fillinIsa(self.fl, filename)
                zdra.x.fillinIsa(self.fl, filename)
                zdra.x.fillNames(filename)
                self.top.config(state=NORMAL)
                self.top.delete(1.0, END)
                self.top.insert(END,
                                "Isabelle Skeleton successfully filled in ")
                self.top.config(state=DISABLED)
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(
                END,
                "Please convert specification into Isabelle Skeleton first")
            self.top.config(state=DISABLED)

    def askopenfilename(self):
        filename = tkFileDialog.askopenfilename(**self.file_opt)
        if filename:
            print filename

    def createppgpsa(self):
        zdra.createPPZskel(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, "ProofPower-Z Skeleton Created")
        self.top.config(state=DISABLED)
        self.gpsabutton = Button(self.m2,
                                 text="Show PP Skeleton",
                                 command=self.showgpsa)
        self.gpsabutton.pack()

    def createIsaPS(self):
        zdra.createIsaskel(self.fl)
        self.top.config(state=NORMAL)
        self.top.delete(1.0, END)
        self.top.insert(END, "Isabelle Skeleton Created")
        self.top.config(state=DISABLED)
        self.gpsabutton = Button(self.m2,
                                 text="Show Isabelle Skeleton",
                                 command=self.showIsaSkel)
        self.gpsabutton.pack()

    def showskeleton(self):
        self.skel_location = zdracheck.findskeleton(self.fl)
        if os.path.isfile(self.skel_location):
            skelwindow = Toplevel()
            skelwindow.title("Generalised Skeleton")
            skelspec = ScrolledText(skelwindow, wrap=WORD)
            skelspec.pack()
            skelspecif = self.readFile(self.skel_location)
            skelspec.insert(END, skelspecif)
            skelspec.config(state=DISABLED)

        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Please convert specification into GPSa first")
            self.top.config(state=DISABLED)

    def createskeleton(self):
        if zdracheck.isthereanyloops() == False:
            zdracheck.createskeleton(self.fl)
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END, "Skeleton Created")
            self.top.config(state=DISABLED)
            self.skelbutton = Button(self.m2,
                                     text="Show Skeleton",
                                     command=self.showskeleton)
            self.skelbutton.pack()
        else:
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)
            self.top.insert(END,
                            "Loops in reasoning \nCan not create Skeleton")
            self.top.config(state=DISABLED)

    def submitbutton(self):
        print self.bottom.get("1.0", "end-1c")

    def onOpen(self):
        ftypes = [('Tex files', '*.tex'), ('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes=ftypes)
        self.fl = dlg.show()

        if self.fl != '':
            self.txt.delete(1.0, END)
            self.text = self.readFile(self.fl)
            self.txt.insert(END, self.text)
            self.top.config(state=NORMAL)
            self.top.delete(1.0, END)

    def readFile(self, filename):
        f = open(filename, "r")
        text = f.read()
        return text
Ejemplo n.º 22
0
class GUI:
    queue = []
    client_socket = None
    text = None

    #root = Tkinter.Tk(className=" Collaborative Text Editor")
    #textPad = ScrolledText(root, width=100, height=80)

    def __init__(self, file, socket):
        self.queue = []
        self.client_socket = socket
        self.text = text_file.File()
        self.text.download_from_txt(file)
        root = Tkinter.Tk(className=" Collaborative Text Editor")
        self.textPad = ScrolledText(root, width=100, height=80)
        menu = Menu(root)
        root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Save", command=self.save_command)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.exit_command)
        helpmenu = Menu(menu)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=self.about_command)
        # Insert given text
        if file:
            f = open(file, 'r')
            self.textPad.insert(END, f.read())
        # Keybord bindings to virtual events
        self.textPad.bind("<Button-1>", self.mouse_button)
        self.textPad.bind("<Control-v>", self.key_disable)
        self.textPad.bind("<Control-c>", self.key_disable)
        self.textPad.bind("<Shift_L>", self.key_shift)
        self.textPad.bind("<Delete>", self.key_disable)
        self.textPad.bind("<Tab>", self.key_disable)
        self.textPad.bind("<Insert>", self.key_disable)
        self.textPad.bind("<Return>", self.key_enter)
        self.textPad.bind("<BackSpace>", self.key_backspace)
        self.textPad.bind("<Key>", self.key_press)
        self.textPad.bind("<KeyRelease>", self.key)
        self.textPad.pack()
        root.bind('<<send_recv>>', self.send_receive)

        def heartbeat():
            while True:
                time.sleep(0.5)
                root.event_generate('<<send_recv>>', when='tail')

        th = Thread(None, heartbeat)
        th.setDaemon(True)
        th.start()

        root.mainloop()

    def send_receive(self, event):
        #print "Good"
        if self.queue:
            self.client_socket.send(self.queue.pop(0))
            print self.queue
        else:
            self.client_socket.send('Nothing')
        triple = self.client_socket.recv(1024)
        triple_list = self.get_triples(triple)
        for triple in triple_list:
            insert = self.text.parse_triple(triple)
            self.text.change(insert[0], insert[1], insert[2])
            if insert[2] == "bs":
                if insert[1] == -1:
                    self.textPad.insert("%d.0" % (insert[0] - 1),
                                        "%d.end" % insert[0],
                                        self.text.rows[insert[0] - 1])
                else:
                    self.textPad.delete(
                        "%d.%d" % (insert[0] + 1, insert[1]),
                        "%d.%d" % (insert[0] + 1, insert[1] + 1))
            elif insert[2] == "ent":
                self.textPad.insert("%d.%d" % (insert[0] + 1, insert[1]), "\n")
            else:
                self.textPad.insert("%d.%d" % (insert[0] + 1, insert[1]),
                                    insert[2])

    def get_triples(self, input_triple):
        output = []
        while "(" in input_triple:
            left_index = input_triple.index("(")
            right_index = input_triple.index(")")
            output.append(input_triple[left_index:right_index + 1])
            input_triple = input_triple[right_index + 1:]
        return output

    #Function raises by Tk events.
    def save_command(self):
        file = tkFileDialog.asksaveasfile(mode='w')
        if file != None:
            # slice off the last character from get, as an extra return is added
            data = self.textPad.get('1.0', END + '-1c')
            file.write(data)
            file.close()

    def exit_command(self, root):
        if tkMessageBox.askokcancel("Quit", "Do you really want to quit?"):
            root.destroy()

    def about_command(self):
        label = tkMessageBox.showinfo(
            "About",
            "Collaborative text editor \n Developed by Bachinskiy A., Shapaval R., \
                                        Shuchorukov M., Tkachuk D. using Tk.tkinter.\n No rights left to reserve :)"
        )

    #Here come all button handlers
    def key_enter(self, event):
        s = self.textPad.index(INSERT)
        self.add_to_queue(s, "ent")

    def key_backspace(self, event):
        s = self.textPad.index(INSERT)
        self.add_to_queue(s, "bs")

    def key_disable(self, event):
        self.textPad.config(state=DISABLED)
        global disableFlag
        disableFlag = True

    def mouse_button(self, event):
        self.textPad.config(state=NORMAL)

    def key_shift(self, event):
        global shiftFlag
        shiftFlag = True

    def key(self, event):
        #print event.keycode
        global disableFlag
        global shiftFlag
        if disableFlag == True:
            #print "disabled"
            if event.keysym != "v":
                disableFlag = False
        else:
            #print event.keycode
            #Shift handling
            if shiftFlag == True:
                s = self.textPad.index(INSERT)
                self.add_to_queue(s)
                shiftFlag = False
            else:
                #Block output for Arrows keys
                if event.keysym == "Down" or event.keysym == "Up" or \
                        event.keysym == "Right" or event.keysym == "Left":
                    print event.keysym
                    return
                #Block output for Ctrl, Shift, BackSpace, Tab, Delete, etc
                if event.keysym == "Alt_L" or event.keysym == "Alt_R" or \
                                event.keysym == "BackSpace" or event.keysym == "Delete" or \
                                event.keysym == "Control_L" or event.keysym == "Control_R" or \
                                event.keysym == "Shift_L" or event.keysym == "Shift_R" or \
                                event.keysym == "Tab" or event.keysym == "Return":
                    print event.keysym
                    return
                self.textPad.config(state=NORMAL)
                s = self.textPad.index(INSERT)
                self.add_to_queue(s)

    def key_press(self, event):
        self.textPad.config(state=DISABLED)
        time.sleep(0.2)
        self.textPad.config(state=NORMAL)

    def add_to_queue(self, s, key=""):
        point_index = s.index(".")
        index1 = int(s[:point_index])
        index2 = int(s[point_index + 1:])
        out = self.textPad.get("%d.%d" % (index1, index2 - 1),
                               "%d.%d" % (index1, index2))
        if key:
            if key == "ent":
                self.queue.append("(%d,%d,%s)" % (index1 - 1, index2, key))
            if key == "bs":
                self.queue.append("(%d,%d,%s)" % (index1 - 1, index2 - 1, key))
        else:
            self.queue.append("(%d,%d,%s)" % (index1 - 1, index2 - 1, out))
        print self.queue
Ejemplo n.º 23
0
class HTMLViewer(Toplevel):
    """ Basic class which provides a scrollable area for viewing HTML
        text and a Dismiss button """
    
    def __init__(self, htmlcode, title, master=None):
    
        Toplevel.__init__(self, master)
        #self.protocol('WM_DELETE_WINDOW',self.withdraw)
        self.titleprefix = title
        color = self.config("bg")[4]
        borderFrame = Frame(self, relief=SUNKEN, bd=2) # Extra Frame
        self.text = ScrolledText(borderFrame, relief=FLAT, 
                                 padx=3, pady=3,
                                 background='white', 
                                 #background=color, 
                                 #foreground="black",
                                 wrap='word',
                                 width=60, height=20,
                                 spacing1=3,
                                 spacing2=2,
                                 spacing3=3)
        self.text.pack(expand=1, fill=BOTH)
        #self.text.insert('0.0', text)
        self.text['state'] = DISABLED 
        borderFrame.pack(side=TOP,expand=1,fill=BOTH)
        box = Frame(self)
        w = Button(box, text="Dismiss", width=10, command=self.doWithdraw, default=ACTIVE)
        w.pack(side=RIGHT, padx=5, pady=5)
        self.bind("<Return>", self.doWithdraw)
        box.pack(side=BOTTOM,fill=BOTH)
        self.setStyle()
        self.insert(htmlcode)

    def setStyle(self):
        baseSize = 14
        self.text.config(font="Times %d" % baseSize)
        
        self.text.tag_config('h1', font="Times %d bold" % (baseSize + 8))
        self.text.tag_config('h2', font="Times %d bold" % (baseSize + 6))
        self.text.tag_config('h3', font="Times %d bold" % (baseSize + 4))
        self.text.tag_config('h4', font="Times %d bold" % (baseSize + 2))
        self.text.tag_config('h5', font="Times %d bold" % (baseSize + 1))
        self.text.tag_config('b', font="Times %d bold" % baseSize)
        self.text.tag_config('em', font="Times %d italic" % baseSize)
        self.text.tag_config('pre', font="Courier %d" % baseSize)
        self.text.tag_config('tt', font="Courier %d" % baseSize)
       


    def doWithdraw(self, event=None):
        # Need to eat optional event so that we can use is in both button and bind callback
        self.withdraw()
        
    def Update(self,htmlcode, title):
        self.titleprefix = title
        self.insert(htmlcode)
        
    def insert(self, htmlcode):
        self.text['state'] = NORMAL
        self.text.delete('0.0', END)
        writer = HTMLWriter(self.text, self)
        format = formatter.AbstractFormatter(writer)
        #parser = htmllib.HTMLParser(format)
        parser = MyHTMLParser(format, self.text)
        parser.nofill=False
        parser.feed(htmlcode)
        parser.close()
        
        self.text['state'] = DISABLED 
        if parser.title != None:
            self.title(self.titleprefix + " - " + parser.title)
        else:
            self.title(self.titleprefix)