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
class MyTkAppFrame(ttk.Notebook):

    # the req is a list
    def cb_task(self, tid, req):
        L.debug("do task: tid=" + str(tid) + ", req=" + str(req))
        reqstr = req[0]
        resp = self.serv.get_request_block(reqstr)
        if resp != None:
            if resp.strip() != "":
                self.mymailbox.mailbox_serv.put(req[1], resp)

    def do_stop(self):
        isrun = False;
        if self.runth_svr != None:
            if self.runth_svr.isAlive():
                #L.info('signal server to stop ...')
                self.server.shutdown()
                #L.info('server close ...')
                self.server.server_close()
                #L.info('server closed.')
                isrun = True
        if isrun == False:
            L.info('server is not running. skip')
        if self.serv != None:
            self.serv.close()
            self.serv = None

        self.btn_svr_start.config(state=tk.NORMAL)
        self.btn_svr_stop.config(state=tk.DISABLED)

        #return

    def do_start(self):
        import socketserver as ss
        import neatocmdsim as nsim

        class ThreadedTCPRequestHandler(ss.BaseRequestHandler):
            # override base class handle method
            def handle(self):
                BUFFER_SIZE = 4096
                MAXIUM_SIZE = BUFFER_SIZE * 5
                data = ""
                L.info("server connectd by client: " + str(self.client_address))
                mbox_id = self.server.mydata.mailbox_serv.declair()

                cli_log_head = "CLI" + str(self.client_address)
                while 1:
                    try:
                        # receive the requests
                        recvdat = self.request.recv(BUFFER_SIZE)
                        if not recvdat:
                            # EOF, client closed, just return
                            L.info(cli_log_head + " disconnected: " + str(self.client_address))
                            break
                        data += str(recvdat, 'ascii')
                        L.debug(cli_log_head + " all of data: " + data)
                        cntdata = data.count('\n')
                        L.debug(cli_log_head + " the # of newline: %d"%cntdata)
                        if (cntdata < 1):
                            L.debug(cli_log_head + " not receive newline, skip: " + data)
                            continue
                        # process the requests after a '\n'
                        requests = data.split('\n')
                        for i in range(0, cntdata):
                            # for each line:
                            request = requests[i].strip()
                            L.info(cli_log_head + " request [" + str(i+1) + "/" + str(cntdata) + "] '" + request + "'")
                            self.server.serv.request ([request, mbox_id])
                            response = self.server.mydata.mailbox_serv.get(mbox_id)
                            if response != "":
                                L.debug(cli_log_head + 'send data back: sz=' + str(len(response)))
                                self.request.sendall(bytes(response, 'ascii'))

                        data = requests[-1]

                    except BrokenPipeError:
                        L.error (cli_log_head + 'remote closed: ' + str(self.client_address))
                        break
                    except ConnectionResetError:
                        L.error (cli_log_head + 'remote reset: ' + str(self.client_address))
                        break
                    except Exception as e1:
                        L.error (cli_log_head + 'Error in read serial: ' + str(e1))
                        break

                L.error (cli_log_head + 'close: ' + str(self.client_address))
                self.server.mydata.mailbox_serv.close(mbox_id)


        # pass the data strcture from main frame to all of subclasses
        # mailbox_serv, mailbox_servcli

        class ThreadedTCPServer(ss.ThreadingMixIn, ss.TCPServer):
            daemon_threads = True
            allow_reuse_address = True
            # pass the serv to handler
            def __init__(self, host_port_tuple, streamhandler, serv, mydata):
                super().__init__(host_port_tuple, streamhandler)
                self.serv = serv
                self.mydata = mydata

        if self.runth_svr != None:
            if self.runth_svr.isAlive():
                L.info('server is already running. skip')
                return True

        L.info('connect to ' + self.conn_port.get())
        self.serv = neatocmdapi.NCIService(target=self.conn_port.get().strip(), timeout=0.5)
        if self.serv.open(self.cb_task) == False:
            L.error ('Error in open serial')
            return False

        L.info('start server ' + self.bind_port.get())
        b = self.bind_port.get().split(":")
        L.info('b=' + str(b))
        HOST=b[0]
        PORT=3333
        if len(b) > 1:
            PORT=int(b[1])
        L.info('server is running ...')
        try:
            self.server = ThreadedTCPServer((HOST, PORT), ThreadedTCPRequestHandler, self.serv, self.mymailbox)
        except Exception as e:
            L.error("Error in starting service: " + str(e))
            return False
        ip, port = self.server.server_address
        L.info("server listened to: " + str(ip) + ":" + str(port))
        self.runth_svr = Thread(target=self.server.serve_forever)
        self.runth_svr.setDaemon(True) # When closing the main thread, which is our GUI, all daemons will automatically be stopped as well.
        self.runth_svr.start()

        self.btn_svr_start.config(state=tk.DISABLED)
        self.btn_svr_stop.config(state=tk.NORMAL)
        L.info('server started.')
        return True

    def get_log_text(self):
        return self.text_log

    def __init__(self, tk_frame_parent):
        global config_use_textarea_log
        ttk.Notebook.__init__(self, tk_frame_parent)
        nb = self
        self.runth_svr = None
        self.serv = None
        self.serv_cli = None

        class MyMailbox(object):
            "mymailbox"
            def __init__(self):
                self.mailbox_serv = neatocmdapi.MailPipe()
                self.mailbox_servcli = neatocmdapi.MailPipe()

        self.mymailbox = MyMailbox()

        guilog.rClickbinder(tk_frame_parent)

        # page for About
        page_about = ttk.Frame(nb)
        lbl_about_head = tk.Label(page_about, text=_("About"), font=LARGE_FONT)
        lbl_about_head.pack(side="top", fill="x", pady=10)
        lbl_about_main = tk.Label(page_about
                , font=NORM_FONT
                , text="\n" + str_progname + "\n" + str_version + "\n"
                    + _("Forward Neato XV control over network") + "\n"
                    + "\n"
                    + _("Copyright © 2015–2016 The nxvForward Authors") + "\n"
                    + "\n"
                    + _("This program comes with absolutely no warranty.") + "\n"
                    + _("See the GNU General Public License, version 3 or later for details.")
                )
        lbl_about_main.pack(side="top", fill="x", pady=10)

        # page for server
        page_server = ttk.Frame(nb)
        lbl_svr_head = tk.Label(page_server, text=_("Server"), font=LARGE_FONT)
        lbl_svr_head.pack(side="top", fill="x", pady=10)

        frame_svr = ttk.LabelFrame(page_server, text=_("Setup"))

        line=0
        bind_port_history = ('localhost:3333', '127.0.0.1:4444', '0.0.0.0:3333')
        self.bind_port = tk.StringVar()
        lbl_svr_port = tk.Label(frame_svr, text=_("Bind Address:"))
        lbl_svr_port.grid(row=line, column=0, padx=5, sticky=tk.N+tk.S+tk.W)
        combobox_bind_port = ttk.Combobox(frame_svr, textvariable=self.bind_port)
        combobox_bind_port['values'] = bind_port_history
        combobox_bind_port.grid(row=line, column=1, padx=5, pady=5, sticky=tk.N+tk.S+tk.W)
        combobox_bind_port.current(0)

        line += 1
        conn_port_history = ('dev://ttyACM0:115200', 'dev://ttyUSB0:115200', 'dev://COM11:115200', 'dev://COM12:115200', 'sim:', 'tcp://localhost:3333', 'tcp://192.168.3.163:3333')
        self.conn_port = tk.StringVar()
        lbl_svr_port = tk.Label(frame_svr, text=_("Connect to:"))
        lbl_svr_port.grid(row=line, column=0, padx=5, sticky=tk.N+tk.S+tk.W)
        combobox_conn_port = ttk.Combobox(frame_svr, textvariable=self.conn_port)
        combobox_conn_port['values'] = conn_port_history
        combobox_conn_port.grid(row=line, column=1, padx=5, pady=5, sticky=tk.N+tk.S+tk.W)
        combobox_conn_port.current(0)

        line -= 1
        self.btn_svr_start = tk.Button(frame_svr, text=_("Start"), command=self.do_start)
        self.btn_svr_start.grid(row=line, column=2, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
        #self.btn_svr_start.pack(side="right", fill="both", padx=5, pady=5, expand=True)

        line += 1
        self.btn_svr_stop = tk.Button(frame_svr, text=_("Stop"), command=self.do_stop)
        self.btn_svr_stop.grid(row=line, column=2, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
        #self.btn_svr_stop.pack(side="right", fill="both", padx=5, pady=5, expand=True)

        frame_svr.pack(side="top", fill="x", pady=10)

        self.text_log = None
        if config_use_textarea_log:
            self.text_log = tk.scrolledtext.ScrolledText(page_server, wrap=tk.WORD, height=1)
            self.text_log.configure(state='disabled')
            self.text_log.pack(expand=True, fill="both", side="top")
            #self.text_log.grid(row=line, column=1, columnspan=2, padx=5)
            self.text_log.bind("<1>", lambda event: self.text_log.focus_set()) # enable highlighting and copying
            #set_readonly_text(self.text_log, "Version Info\nver 1\nver 2\n")

            btn_log_clear = tk.Button(page_server, text=_("Clear"), command=lambda: (set_readonly_text(self.text_log, ""), self.text_log.update_idletasks()))
            #btn_log_clear.grid(row=line, column=0, columnspan=2, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
            btn_log_clear.pack(side="right", fill="both", padx=5, pady=5, expand=True)

        # page for client
        page_client = ttk.Frame(nb)
        lbl_cli_head = tk.Label(page_client, text=_("Test Client"), font=LARGE_FONT)
        lbl_cli_head.pack(side="top", fill="x", pady=10)

        frame_cli = ttk.LabelFrame(page_client, text=_("Connection"))

        line=0
        client_port_history = ('tcp://192.168.3.163:3333', 'dev://ttyACM0:115200', 'dev://ttyUSB0:115200', 'dev://COM11:115200', 'dev://COM12:115200', 'sim:', 'tcp://localhost:3333')
        self.client_port = tk.StringVar()
        lbl_cli_port = tk.Label(frame_cli, text=_("Connect to:"))
        lbl_cli_port.grid(row=line, column=0, padx=5, sticky=tk.N+tk.S+tk.W)
        combobox_client_port = ttk.Combobox(frame_cli, textvariable=self.client_port)
        combobox_client_port['values'] = client_port_history
        combobox_client_port.grid(row=line, column=1, padx=5, pady=5, sticky=tk.N+tk.S+tk.W)
        combobox_client_port.current(0)

        self.btn_cli_connect = tk.Button(frame_cli, text=_("Connect"), command=self.do_cli_connect)
        self.btn_cli_connect.grid(row=line, column=2, columnspan=1, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
        #self.btn_cli_connect.pack(side="left", fill="both", padx=5, pady=5, expand=True)

        self.btn_cli_disconnect = tk.Button(frame_cli, text=_("Disconnect"), command=self.do_cli_disconnect)
        self.btn_cli_disconnect.grid(row=line, column=3, columnspan=1, padx=5, sticky=tk.N+tk.S+tk.W+tk.E)
        #self.btn_cli_disconnect.pack(side="left", fill="both", padx=5, pady=5, expand=True)

        frame_cli.pack(side="top", fill="x", pady=10)

        page_command = page_client
        frame_top = tk.Frame(page_command)#, background="green")
        frame_bottom = tk.Frame(page_command)#, background="yellow")
        frame_top.pack(side="top", fill="both", expand=True)
        frame_bottom.pack(side="bottom", fill="x", expand=False)

        self.text_cli_command = ScrolledText(frame_top, wrap=tk.WORD)
        #self.text_cli_command.insert(tk.END, "Some Text\ntest 1\ntest 2\n")
        self.text_cli_command.configure(state='disabled')
        self.text_cli_command.pack(expand=True, fill="both", side="top")
        # make sure the widget gets focus when clicked
        # on, to enable highlighting and copying to the
        # clipboard.
        self.text_cli_command.bind("<1>", lambda event: self.text_cli_command.focus_set())

        btn_clear_cli_command = tk.Button(frame_bottom, text=_("Clear"), command=lambda: (set_readonly_text(self.text_cli_command, ""), self.text_cli_command.update_idletasks()) )
        btn_clear_cli_command.pack(side="left", fill="x", padx=5, pady=5, expand=False)
        self.cli_command = tk.StringVar()
        self.combobox_cli_command = ttk.Combobox(frame_bottom, textvariable=self.cli_command)
        self.combobox_cli_command['values'] = ('Help', 'GetAccel', 'GetButtons', 'GetCalInfo', 'GetCharger', 'GetDigitalSensors', 'GetErr', 'GetLDSScan', 'GetLifeStatLog', 'GetMotors', 'GetSchedule', 'GetTime', 'GetVersion', 'GetWarranty', 'PlaySound 0', 'Clean House', 'DiagTest MoveAndBump', 'DiagTest DropTest', 'RestoreDefaults', 'SetDistanceCal DropMinimum', 'SetFuelGauge Percent 100', 'SetIEC FloorSelection carpet', 'SetLCD BGWhite', 'SetLDSRotation On', 'SetLED BacklightOn', 'SetMotor VacuumOn', 'SetSchedule Day Sunday Hour 17 Min 0 House ON', 'SetSystemMode Shutdown', 'SetTime Day Sunday Hour 12 Min 5 Sec 25', 'SetWallFollower Enable', 'TestMode On', 'Upload' )
        self.combobox_cli_command.pack(side="left", fill="both", padx=5, pady=5, expand=True)
        self.combobox_cli_command.bind("<Return>", self.do_cli_run_ev)
        self.combobox_cli_command.bind("<<ComboboxSelected>>", self.do_select_clicmd)
        self.combobox_cli_command.current(0)
        btn_run_cli_command = tk.Button(frame_bottom, text=_("Run"), command=self.do_cli_run)
        btn_run_cli_command.pack(side="right", fill="x", padx=5, pady=5, expand=False)

        self.check_mid_cli_command()


        # last
        nb.add(page_server, text=_("Server"))
        nb.add(page_client, text=_("Test Client"))
        nb.add(page_about, text=_("About"))
        combobox_bind_port.focus()

        self.do_stop()
        self.do_cli_disconnect()
        return

    #
    # connection and command: support functions
    #
    def do_select_clicmd(self, event):
        self.combobox_cli_command.select_range(0, tk.END)
        return

    # the req is a list
    def cb_task_cli(self, tid, req):
        L.debug("do task: tid=" + str(tid) + ", req=" + str(req))
        reqstr = req[0]
        resp = self.serv_cli.get_request_block(reqstr)
        if resp != None:
            if resp.strip() != "":
                self.mymailbox.mailbox_servcli.put(req[1], resp.strip())
        return

    def do_cli_connect(self):
        self.do_cli_disconnect()
        L.info('client connect ...')
        L.info('connect to ' + self.client_port.get())
        self.serv_cli = neatocmdapi.NCIService(target=self.client_port.get().strip(), timeout=0.5)
        if self.serv_cli.open(self.cb_task_cli) == False:
            L.error ('Error in open serial')
            return
        self.mid_cli_command = self.mymailbox.mailbox_servcli.declair();
        L.info ('serial opened')
        self.btn_cli_connect.config(state=tk.DISABLED)
        self.btn_cli_disconnect.config(state=tk.NORMAL)
        return

    def do_cli_disconnect(self):
        if self.serv_cli != None:
            L.info('client disconnect ...')
            self.serv_cli.close()
        else:
            L.info('client is not connected, skip.')
        self.serv_cli = None
        self.mid_cli_command = -1;
        self.btn_cli_connect.config(state=tk.NORMAL)
        self.btn_cli_disconnect.config(state=tk.DISABLED)
        return

    def do_cli_run(self):
        if self.serv_cli == None:
            L.error('client is not connected, please connect it first!')
            return
        L.info('client run ...')
        reqstr = self.cli_command.get().strip()
        if reqstr != "":
            self.serv_cli.request([reqstr, self.mid_cli_command])
        return

    def do_cli_run_ev(self, event):
        self.do_cli_run()
        return

    def check_mid_cli_command(self):
        if self.serv_cli != None and self.mid_cli_command >= 0:
            try:
                resp = self.mymailbox.mailbox_servcli.get(self.mid_cli_command, False)
                respstr = resp.strip() + "\n\n"
                # put the content to the end of the textarea
                guilog.textarea_append (self.text_cli_command, respstr)
                self.text_cli_command.update_idletasks()
            except queue.Empty:
                # ignore
                pass
        # setup next
        self.after(300, self.check_mid_cli_command)
        return
Ejemplo n.º 4
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.serial_list = None
        self.updator = None
        self.news_list = None
        self.firmware_list = None

        # initialize widgets/UI
        self.createWindow(master, 1280, 800)
        self.createWidget(master)

        try:
            self.network_manager = NetworkManager(self)
            profile_path = os.path.join(
                os.path.join(os.path.split(os.path.realpath(__file__))[0]),
                "net.conf")
            profile_u_path = path_2_unicode(profile_path)
            self.network_manager.detect_network_queue()
            self.network_manager.load_config(profile_u_path)
            self.network_manager.run_tasks()
            self.network_manager.detect_serial_port()
            self.network_manager.detect_news()
            self.output_to_panel('success',
                                 'Connecting remote end successfully!\n')
        except Exception as e:
            self.output_to_panel(
                'error',
                'Network manager setup failed! Details: ' + str(e) + '\n')

        self.init_ad_board()
        self.init_output_board()

    def show_firmware_details(self, event):
        lbx = event.widget
        index = lbx.curselection()
        size = len(index)
        if size > 0:
            for i in index[::-1]:
                self.firmware_text.delete(1.0, END)
                self.firmware_text.insert(
                    END,
                    'Firmware:\n' + self.firmware_list[i]["name"] + '\n\n')
                self.firmware_text.see(END)
                details = self.firmware_list[i]["details"]
                for item in details:
                    if item["type"] == "feature":
                        self.firmware_text.insert(END, 'Features:\n')
                        self.firmware_text.see(END)
                        for index, descs in enumerate(item["description"]):
                            self.firmware_text.insert(END, descs + '\n\n')
                            self.firmware_text.see(END)
                    elif item["type"] == "bug":
                        self.firmware_text.insert(END, 'Bugs:\n')
                        self.firmware_text.see(END)
                        for index, descs in enumerate(item["description"]):
                            self.firmware_text.insert(END, descs + '\n\n')
                            self.firmware_text.see(END)
                self.firmware_text.see(END)

    def init_output_board(self):
        prompt_conf = {
            "info": "blue",
            "progress": "yellow",
            "success": "green",
            "error": "red"
        }
        for tag, color in prompt_conf.items():
            self.info_text.tag_config(tag, foreground=color)

    def init_ad_board(self):
        prompt_conf = {"info": "blue", "warning": "yellow", "solved": "green"}
        for tag, color in prompt_conf.items():
            self.news_text.tag_config(tag, foreground=color)

    def show_notice(self, level, msg):
        prompt = {}
        (prompt['info'], prompt['warning'], prompt['solved']) = ["☼", "☢", "☑"]
        if level in ['info', 'warning', 'solved']:
            self.news_text.insert(END, prompt[level], level)
            self.news_text.insert(END, ' ' + msg)
            self.news_text.see(END)

    def output_to_panel(self, level, msg):
        prompt = {}
        (prompt['info'], prompt['progress'], prompt['success'],
         prompt['error']) = ["☼", "➢", "✔", "✘"]
        if level in ['info', 'progress', 'success', 'error']:
            self.info_text.insert(END, prompt[level], level)
            self.info_text.insert(END, ' ' + msg)
            self.info_text.see(END)

    def createWindow(self, root, width, height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2,
                                (screenheight - height) / 2)
        root.geometry(size)
        root.maxsize(width, height)
        root.minsize(width, height)

    def createWidget(self, master):

        ft = tkFont.Font(family='Lucida Console', size=15)

        self.news_panel = Frame(master, width=450)
        self.news_panel.pack(side=LEFT, fill=Y)

        self.news_upper_menu = Frame(self.news_panel, height=10)
        self.news_upper_menu.pack(side=TOP, fill=X, pady=5)

        self.btn_connect_to_remote = Button(self.news_upper_menu,
                                            width=64,
                                            text="Reconnect to remote",
                                            height=1,
                                            command=self.reconnect_to_remote)
        self.btn_connect_to_remote.pack(side=LEFT, anchor="n", padx=10)

        self.news_board = Frame(self.news_panel)
        self.news_board.pack(side=TOP, fill=X, pady=5)

        self.news_text = ScrolledText(self.news_board,
                                      state="normal",
                                      width=66,
                                      height=10,
                                      font=ft,
                                      highlightbackground='black',
                                      highlightthickness=1)
        self.news_text.pack(side=LEFT, anchor="n", padx=5)

        self.firmware_board = Frame(self.news_panel)
        self.firmware_board.pack(side=TOP, fill=X, pady=5)

        firmware_list_ft = tkFont.Font(family='Lucida Console', size=12)
        self.lbx_firmware = Listbox(self.firmware_board,
                                    width=29,
                                    height=32,
                                    font=firmware_list_ft)
        self.lbx_firmware.pack(side=LEFT, anchor="n", padx=5)
        self.lbx_firmware.bind('<<ListboxSelect>>', self.show_firmware_details)

        self.firmware_text = ScrolledText(self.firmware_board,
                                          state="normal",
                                          width=44,
                                          height=34,
                                          font=firmware_list_ft,
                                          highlightbackground='black',
                                          highlightthickness=1)
        self.firmware_text.pack(side=LEFT, anchor="n", padx=5)

        self.news_lower_menu = Frame(self.news_panel, height=10)
        self.news_lower_menu.pack(side=TOP, fill=X, pady=5)

        self.btn_upgrade_from_remote = Button(
            self.news_lower_menu,
            width=64,
            text="Upgrade from remote",
            height=1,
            command=self.create_remote_upgrade_thread)
        self.btn_upgrade_from_remote.pack(side=LEFT, anchor="n", padx=10)

        self.user_panel = Frame(master)
        self.user_panel.pack(side=LEFT, fill=Y)

        self.user_upper_menu = Frame(self.user_panel, height=10)
        self.user_upper_menu.pack(side=TOP, fill=X, pady=5)

        self.lb_port_list = Label(self.user_upper_menu,
                                  text="Port:",
                                  width=6,
                                  height=1)
        self.lb_port_list.pack(side=LEFT, anchor="n", padx=5)
        self.port_item = StringVar()
        self.cb_port_list = ttk.Combobox(self.user_upper_menu,
                                         width=25,
                                         textvariable=self.port_item,
                                         state="readonly")
        self.cb_port_list["values"] = self.serial_list or ("Empty")
        self.cb_port_list.current(0)
        self.cb_port_list.pack(side=LEFT, anchor="w", padx=5)

        self.btn_select = Button(self.user_upper_menu,
                                 text="Select",
                                 height=1,
                                 width=18,
                                 command=self.select_firmware)
        self.btn_select.pack(side=LEFT, anchor="w", padx=10)

        self.btn_clear = Button(self.user_upper_menu,
                                text="Clear",
                                height=1,
                                width=8,
                                command=self.clear_info_text)
        self.btn_clear.pack(side=LEFT, anchor="w", padx=10)

        self.display_board = Frame(self.user_panel)
        self.display_board.pack(side=TOP, fill=X, pady=5)

        self.info_text = ScrolledText(self.display_board,
                                      state="normal",
                                      width=70,
                                      height=39,
                                      font=ft,
                                      highlightbackground='black',
                                      highlightthickness=1)
        self.info_text.bind("<KeyPress>", lambda e: "break")
        self.info_text.pack(side=LEFT, anchor="n", padx=5)
        self.info_text.drop_target_register('DND_Files')
        self.info_text.dnd_bind('<<Drop>>', self.drop_file)

        self.user_lower_menu = Frame(self.user_panel, height=10)
        self.user_lower_menu.pack(side=TOP, fill=X, pady=5)

        self.btn_upgrade_from_local = Button(
            self.user_lower_menu,
            width=64,
            text="Upgrade from local",
            height=1,
            command=self.create_upgrade_thread)
        self.btn_upgrade_from_local.pack(side=LEFT, anchor="n", padx=10)

        self.output_to_panel('info',
                             "Drag and drop local firmware into here.\n")

    def drop_file(self, event):
        self.file_path = event.data
        if self.file_path is not None and self.file_path != "":
            self.output_to_panel('success',
                                 "Selected path: " + self.file_path + '\n')

    def select_firmware(self):
        self.file_path = filedialog.askopenfilename(
            filetypes=[('BIN', 'bin'), ('HEX', 'hex')])
        if self.file_path is not None and self.file_path != "":
            self.output_to_panel('success',
                                 "Selected path: " + self.file_path + '\n')

    def clear_info_text(self):
        self.info_text.delete(1.0, END)

    def create_remote_upgrade_thread(self):
        index = self.lbx_firmware.curselection()
        size = len(index)
        if size > 0:
            remote_upgrade_thread = threading.Thread(
                target=self.start_to_remote_upgrade, args=(index))
            remote_upgrade_thread.setDaemon(True)
            remote_upgrade_thread.start()
        else:
            self.output_to_panel(
                'error', "You haven't selected any remote firmware!\n")

    def start_to_remote_upgrade(self, firmware_index):
        '''
        self.btn_upgrade_from_local["state"] = "disabled"
        self.btn_upgrade_from_remote["state"] = "disabled"
        self.btn_connect_to_remote["state"] = "disabled"
        self.btn_select["state"] = "disabled"
        self.btn_clear["state"] = "disabled"
        '''

        try:
            url = self.firmware_list[firmware_index]["url"]
            self.output_to_panel('info',
                                 'Start to get firmware from remote...\n')
            r = requests.get(url)
            if r.status_code == 200:
                firmware_path = os.path.join(
                    os.path.join(os.path.split(os.path.realpath(__file__))[0]),
                    "Firmware", "origin", "firmware.zip")
                firmware_u_path = path_2_unicode(firmware_path)
                with open(firmware_u_path, "wb") as code:
                    code.write(r.content)
                self.output_to_panel(
                    'success', 'Firmware downloaded to Firmware/origin/\n')
            elif r.status_code == 404:
                self.output_to_panel('error', 'Firmware doesn\'t exist\n')
                return
            else:
                self.output_to_panel(
                    'error', 'Firmware downloaded error! Details: code--%d\n' %
                    r.status_code)
                return
        except Exception as e:
            self.output_to_panel(
                'error',
                'Firmware downloaded error! Details: ' + str(e) + '\n')
            return

        self.output_to_panel('info', 'Start to extract files from zip...\n')
        firmware_extract_path = os.path.join(
            os.path.join(os.path.split(os.path.realpath(__file__))[0]),
            "Firmware", "extract")
        firmware_extract_u_path = path_2_unicode(firmware_extract_path)

        self.target_file_list = []

        try:
            f = zipfile.ZipFile(firmware_u_path, 'r')
            for file in f.namelist():
                if '_S_' in file or 'hex' in file or 'HEX' in file:
                    self.target_file_list.append(file)
                f.extract(file, firmware_extract_u_path)
            self.output_to_panel('success',
                                 'Firmware extracted to Firmware/extract\n')
        except Exception as e:
            self.output_to_panel(
                'error', 'Firmware extracted error! Details: ' + str(e) + '\n')
            return

        self.updator = FirmwareUpdator(self.info_text)

        profile_path = os.path.join(
            os.path.join(os.path.split(os.path.realpath(__file__))[0]),
            "default.conf")
        profile_u_path = path_2_unicode(profile_path)

        self.file_path = path_2_unicode(
            os.path.join(firmware_extract_path, self.target_file_list[0]))
        self.updator.update_firmware(profile_u_path, self.port_item.get(),
                                     self.file_path)
        '''
        self.btn_upgrade_from_local["state"] = "normal"
        self.btn_upgrade_from_remote["state"] = "normal"
        self.btn_connect_to_remote["state"] = "normal"
        self.btn_select["state"] = "normal"
        self.btn_clear["state"] = "normal"
        '''

    def create_upgrade_thread(self):
        if hasattr(self, 'file_path'):
            upgrade_thread = threading.Thread(target=self.start_to_upgrade,
                                              args=())
            upgrade_thread.setDaemon(True)
            upgrade_thread.start()
        else:
            self.output_to_panel('error',
                                 "You haven't selected any firmware files!\n")

    def start_to_upgrade(self):
        self.btn_upgrade_from_local["state"] = "disabled"
        self.btn_upgrade_from_remote["state"] = "disabled"
        self.btn_connect_to_remote["state"] = "disabled"
        self.btn_select["state"] = "disabled"
        self.btn_clear["state"] = "disabled"
        self.updator = FirmwareUpdator(self.info_text)

        profile = os.path.join(
            os.path.split(os.path.realpath(__file__))[0], "default.conf")
        profile_path = os.path.join(
            os.path.join(os.path.split(os.path.realpath(__file__))[0]),
            "default.conf")
        profile_u_path = path_2_unicode(profile_path)

        self.updator.update_firmware(profile_u_path, self.port_item.get(),
                                     self.file_path)
        self.btn_upgrade_from_local["state"] = "normal"
        self.btn_upgrade_from_remote["state"] = "normal"
        self.btn_connect_to_remote["state"] = "normal"
        self.btn_select["state"] = "normal"
        self.btn_clear["state"] = "normal"

    def reconnect_to_remote(self):
        self.network_manager.run_tasks()
        self.output_to_panel('success',
                             'Reconnecting remote end successfully!\n')

    def close_connection(self):
        if self.updator is not None:
            self.updator.close_serial()
Ejemplo n.º 5
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.º 6
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.º 7
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.º 8
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.º 9
0
class MemoPadFrame( Frame ):

    def __init__(self, master=None):
        Frame.__init__(self, master)

        # Modelの初期化
        self.version = (0, 2, 5)
        self.memos = MemoPad()
        self.memos.addObserver(self)

        # change-logger のバインド
        self.changeLogger = ChangeLogger()
        self.memos.addObserver( self.changeLogger )

        # View-Controller の初期化
        self.master.title( 'MemoPad %d.%d.%d' % self.version )
        self.make_listPanel(self)
        self.make_editAria(self)
        self.pack(fill=BOTH)

        # データの復帰
        self.memos.loadImage()


        def bye():
            self.saveMemo()    # 現在編集中のメモをセーブ
            self.memos.saveImage()

            print 'bye'
            self.master.destroy()

        self.master.protocol('WM_DELETE_WINDOW', bye )


    def make_listPanel(self, parent):
        frm = Frame(parent)

        # リストの生成・配置
        def changeTarget(evt):
            try: index = int(self.memoList.curselection()[0])
            except: index = None

            self.saveMemo()
            if index != None: self.selectMemo( index )


        self.memoList = ScrolledListbox(frm,
                                        selectmode=BROWSE,
                                        width=72,
                                        height=7 )
        self.memoList.bind("<ButtonRelease>", changeTarget )
        self.memoList.bind('<B1-Motion>', changeTarget )
        self.memoList.pack(side=LEFT, fill=BOTH)


        # ボタンの作成
        btnfrm = Frame(frm)

        def appendMemo():
            self.saveMemo()
            self.memos.appendMemo()

        Button( btnfrm,
                text='new',
                command=appendMemo ).pack(side=TOP, fill=X)


        def deleteMemo():
            self.saveMemo()
            self.memos.removeMemo()

        Button( btnfrm,
                text='delete',
                command=deleteMemo ).pack(side=TOP, fill=X)


        btnfrm.pack(side=LEFT)

        frm.pack(side=TOP, fill=X)



    def make_editAria(self, parent):
        self.text = ScrolledText( parent )
        self.text.pack(side=TOP, fill=BOTH)

        def updateTitle(evt):
            '''実験コード。まだ
            改行や行末改行の削除に弱いです
            '''
#            print self.text.index('1.end')
#            print self.text.index(INSERT)

            if self.text.index(INSERT).split('.')[0] == '1': # 1行目
                itemnum = self.memos.getSelectedIndex()

                self.memoList.delete(itemnum)
                self.memoList.insert(itemnum,
                             "%s | %s" % (self.memos[itemnum].getDatetime().strftime("%Y-%m-%d %H:%M"),
                                          u'%s%s%s' % ( self.text.get('1.0', INSERT), 
                                                        evt.char.decode('utf_8'),
                                                        self.text.get(INSERT, '1.end'))))
                self.memoList.selection_clear(0,END)
                self.memoList.selection_set(itemnum)
                self.memoList.see(itemnum)


        self.text.bind('<Key>', updateTitle )

        def ime_ctrl_m(evt):
            if evt.keycode == 0:
                self.text.insert( INSERT, evt.char )
        self.text.bind('<Control-Key>',ime_ctrl_m)

    #==================================
    # observer
    #==================================

    def update(self, aspect, obj):
        if aspect == 'saveImage' : return

        # リストの表示 (全更新 or 選択行の変更)
        if aspect == "selectMemo":
            self.selectList()
        elif aspect == "setText":
            self.renderOneLine(self.memos.getSelectedIndex())
        else:
            self.renderList()

        # テキストエリアの表示
        if aspect != "setText":
            self.renderTextArea()

        print "disyplay update (%s)" % aspect



    #==================================
    # rendering
    #==================================

    def renderList(self):
        self.memoList.delete(0, END)
        for memo in self.memos:
            self.memoList.insert(END, 
                                 "%s | %s" % (memo.getDatetime().strftime("%Y-%m-%d %H:%M"),
                                              memo.getTitle()))

        if self.memos.getSelectedItem() != None:
            self.memoList.selection_set( self.memos.getSelectedIndex() )
            self.memoList.see( self.memos.getSelectedIndex() )


    def selectList(self):
        try:
            if int(self.memoList.curselection()[0]) == self.memos.getSelectedIndex():
                return
        except: # そもそも選択が成されていない
            pass

        self.memoList.selection_clear(0,END)
        self.memoList.selection_set( self.memos.getSelectedIndex() )
        self.memoList.see( self.memos.getSelectedIndex() )



    def renderOneLine(self, index ):
        if self.memoList.get(index) == self.memos[index].getTitle(): return

        try: indexbackup = int(self.memoList.curselection()[0])
        except: indexbackup = self.memos.getSelectedIndex()

        self.memoList.delete(index)
        self.memoList.insert(index,
                             "%s | %s" % (self.memos[index].getDatetime().strftime("%Y-%m-%d %H:%M"),
                                          self.memos[index].getTitle()))

        if indexbackup != None:
            self.memoList.selection_clear(0,END)
            self.memoList.selection_set(indexbackup)
            self.memoList.see(indexbackup)



    def renderTextArea(self):
        self.text.delete('1.0', END )
        if self.memos.getSelectedItem() != None:
            self.text.insert(END, self.memos.getSelectedItem().getText())



    #==================================
    # controller-function (VC->M)
    #==================================

    def saveMemo( self, memo=None ):
        if memo == None:
            memo = self.memos.getSelectedItem()
            if memo == None: return

        if memo.getText() == self.text.get('1.0', END)[:-1]: return # 内容が同じ場合はなにもしない

        self.memos.getSelectedItem().setText( self.text.get('1.0', END)[:-1] )
        print '--- save "%s"---' % memo.getTitle()

    def selectMemo( self, index ):
        self.memos.selectMemo( index )
Ejemplo n.º 10
0
colorschemes = {
'White': '000000.FFFFFF',
'Grey':'83406A.D1D4D1', 
'Aqua': '5B8340.D1E7E0',
}
themechoice = StringVar()
themechoice.set('White')
for k in sorted(colorschemes):
    themesmenu.add_radiobutton(label = k, variable = themechoice, command = theme)

bottombar = Label(textarea, text = 'Row : 1 | Column : 0')
bottombar.pack(expand = NO, fill = None, side = RIGHT, anchor = 'se')    

textarea.tag_configure("active_line", background = "yellow")
textarea.bind("<Any-KeyPress>", lnupdater)
textarea.bind("<Button-1>", lnupdatermouse)

window.bind('<Control-n>', new_command)
window.bind('<Control-o>', open_command)
window.bind('<Control-s>', save_command)
window.bind('<Control-Shift-KeyPress-S>', saveas_command)
window.bind('<Control-q>', exit_command)
window.bind('<Control-z>', undo_command)
window.bind('<Control-y>', redo_command)
window.bind('<Control-x>', cut_command)
window.bind('<Control-c>', copy_command)
window.bind('<Control-v>', paste_command)
window.bind('<Control-f>', find_command)
window.bind('<Control-Shift-KeyPress-F>', findnext_command)
window.bind('<Control-Alt-KeyPress-F>', fab_command)
Ejemplo n.º 11
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.º 12
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.serial_list = None
        self.createWindow(master, 1000, 680)
        self.createWidget(master)

    def createWindow(self, root, width, height):
        screenwidth = root.winfo_screenwidth()  
        screenheight = root.winfo_screenheight()  
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
        root.geometry(size)
        root.maxsize(width, height)
        root.minsize(width, height)

    def createWidget(self, master):

        self.device_helper = DeviceHelper()
        self.device_helper.find_all_devices(self)

        self.menu = Frame(master, background="#f2f2f2")
        self.menu.pack(side=TOP, fill=X)

        self.lb_port_list = Label(self.menu, text="Serial Port:", width=10, bg="#f2f2f2")
        self.lb_port_list.pack(side=LEFT, anchor="n", padx=5, pady=5)

        self.port_item = StringVar()
        self.cb_port_list = ttk.Combobox(self.menu, width=25, textvariable=self.port_item, state="readonly")
        self.cb_port_list["values"] = self.serial_list or ("Empty")
        self.cb_port_list.current(0)
        self.cb_port_list.pack(side=LEFT, anchor="n", pady=5)

        self.btn_get = Button(self.menu, text=" Get Status",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.get_motor_status)
        self.btn_get.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.btn_reconnect = Button(self.menu, text=" Reconnect",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.reconnect)
        self.btn_reconnect.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.btn_disconnect = Button(self.menu, text=" Disconnect", bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.disconnect)
        self.btn_disconnect.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.btn_connect = Button(self.menu, text=" Connect",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.connect)
        self.btn_connect.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.upper_panel = Frame(master, background="#f2f2f2")
        self.upper_panel.pack(side=TOP, fill=X)

        self.middle_panel = Frame(master, background="#f2f2f2")
        self.middle_panel.pack(side=TOP, fill=X)

        self.lower_panel = Frame(master, background="#f2f2f2")
        self.lower_panel.pack(side=TOP, fill=X)

        self.travel_board = Frame(self.upper_panel, background="#f2f2f2")
        self.travel_board.pack(side=TOP, fill=X)
        
        self.lb_travel = Label(self.travel_board, text="Motor Travel", anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_travel.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_travel_x = Label(self.travel_board, text="X", width=2, bg="#f2f2f2")
        self.lb_travel_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.travel_x = StringVar()
        self.et_travel_x = Entry(self.travel_board, textvariable=self.travel_x, width=8, state="normal")
        self.et_travel_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_travel_y = Label(self.travel_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_travel_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.travel_y = StringVar()
        self.et_travel_y = Entry(self.travel_board, textvariable=self.travel_y, width=8, state="normal")
        self.et_travel_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_travel_z = Label(self.travel_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_travel_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.travel_z = StringVar()
        self.et_travel_z = Entry(self.travel_board, textvariable=self.travel_z, width=8, state="normal")
        self.et_travel_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_travel = Button(self.travel_board, text=" Set Travel ",   bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.set_travel)
        self.btn_travel.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.step_board = Frame(self.upper_panel, background="#f2f2f2")
        self.step_board.pack(side=TOP, fill=X)

        self.lb_step = Label(self.step_board, text="Motor Step",  anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_step.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_step_x = Label(self.step_board, text="X", width=2, bg="#f2f2f2")
        self.lb_step_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.step_x = StringVar()
        self.et_step_x = Entry(self.step_board, textvariable=self.step_x, width=8, state="normal")
        self.et_step_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_step_y = Label(self.step_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_step_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.step_y = StringVar()
        self.et_step_y = Entry(self.step_board, textvariable=self.step_y, width=8, state="normal")
        self.et_step_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_step_z = Label(self.step_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_step_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.step_z = StringVar()
        self.et_step_z = Entry(self.step_board, textvariable=self.step_z, width=8, state="normal")
        self.et_step_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_step_e = Label(self.step_board, text="E", width=2, bg="#f2f2f2")
        self.lb_step_e.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.step_e = StringVar()
        self.et_step_e = Entry(self.step_board, textvariable=self.step_e, width=8, state="normal")
        self.et_step_e.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_step = Button(self.step_board, text=" Set Step ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.set_step)
        self.btn_step.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.direction_board = Frame(self.upper_panel, background="#f2f2f2")
        self.direction_board.pack(side=TOP, fill=X)

        self.lb_direction = Label(self.direction_board, text="Motor Direction", anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_direction.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_direction_x = Label(self.direction_board, text="X", width=2, bg="#f2f2f2")
        self.lb_direction_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.direction_x = StringVar()
        self.et_direction_x = Entry(self.direction_board, textvariable=self.direction_x, width=8, state="normal")
        self.et_direction_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_direction_y = Label(self.direction_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_direction_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.direction_y = StringVar()
        self.et_direction_y = Entry(self.direction_board, textvariable=self.direction_y, width=8, state="normal")
        self.et_direction_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_direction_z = Label(self.direction_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_direction_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.direction_z = StringVar()
        self.et_direction_z = Entry(self.direction_board, textvariable=self.direction_z, width=8, state="normal")
        self.et_direction_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_direction_e0 = Label(self.direction_board, text="E0", width=2, bg="#f2f2f2")
        self.lb_direction_e0.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.direction_e0 = StringVar()
        self.et_direction_e0 = Entry(self.direction_board, textvariable=self.direction_e0, width=8, state="normal")
        self.et_direction_e0.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_direction_e1 = Label(self.direction_board, text="E1", width=2, bg="#f2f2f2")
        self.lb_direction_e1.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.direction_e1 = StringVar()
        self.et_direction_e1 = Entry(self.direction_board, textvariable=self.direction_e1, width=8, state="normal")
        self.et_direction_e1.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_direction_e2 = Label(self.direction_board, text="E2", width=2, bg="#f2f2f2")
        self.lb_direction_e2.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.direction_e2 = StringVar()
        self.et_direction_e2 = Entry(self.direction_board, textvariable=self.direction_e2, width=8, state="normal")
        self.et_direction_e2.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_direction = Button(self.direction_board, text=" Set Direction ",   bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.set_direction)
        self.btn_direction.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.velocity_board = Frame(self.upper_panel, background="#f2f2f2")
        self.velocity_board.pack(side=TOP, fill=X)

        self.lb_velocity = Label(self.velocity_board, text="Motor Velocity", anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_velocity.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_velocity_x = Label(self.velocity_board, text="X", width=2, bg="#f2f2f2")
        self.lb_velocity_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.velocity_x = StringVar()
        self.et_velocity_x = Entry(self.velocity_board, textvariable=self.velocity_x, width=8, state="normal")
        self.et_velocity_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_velocity_y = Label(self.velocity_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_velocity_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.velocity_y = StringVar()
        self.et_velocity_y = Entry(self.velocity_board, textvariable=self.velocity_y, width=8, state="normal")
        self.et_velocity_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_velocity_z = Label(self.velocity_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_velocity_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.velocity_z = StringVar()
        self.et_velocity_z = Entry(self.velocity_board, textvariable=self.velocity_z, width=8, state="normal")
        self.et_velocity_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_velocity_e = Label(self.velocity_board, text="E", width=2, bg="#f2f2f2")
        self.lb_velocity_e.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.velocity_e = StringVar()
        self.et_velocity_e = Entry(self.velocity_board, textvariable=self.velocity_e, width=8, state="normal")
        self.et_velocity_e.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_velocity = Button(self.velocity_board, text=" Set Velocity ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.set_velocity)
        self.btn_velocity.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        ##########Max Printing Acceleration##########

        self.max_printing_acceleration_board = Frame(self.upper_panel, background="#f2f2f2")
        self.max_printing_acceleration_board.pack(side=TOP, fill=X)

        self.lb_max_printing_acceleration = Label(self.max_printing_acceleration_board, text="Max printing move acceleration", anchor = 'w', width=28, bg="#f2f2f2")
        self.lb_max_printing_acceleration.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_max_printing_acceleration_x = Label(self.max_printing_acceleration_board, text="X", width=2, bg="#f2f2f2")
        self.lb_max_printing_acceleration_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_printing_acceleration_x = StringVar()
        self.et_max_printing_acceleration_x = Entry(self.max_printing_acceleration_board, textvariable=self.max_printing_acceleration_x, width=8, state="normal")
        self.et_max_printing_acceleration_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_max_printing_acceleration_y = Label(self.max_printing_acceleration_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_max_printing_acceleration_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_printing_acceleration_y = StringVar()
        self.et_max_printing_acceleration_y = Entry(self.max_printing_acceleration_board, textvariable=self.max_printing_acceleration_y, width=8, state="normal")
        self.et_max_printing_acceleration_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_max_printing_acceleration_z = Label(self.max_printing_acceleration_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_max_printing_acceleration_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_printing_acceleration_z = StringVar()
        self.et_max_printing_acceleration_z = Entry(self.max_printing_acceleration_board, textvariable=self.max_printing_acceleration_z, width=8, state="normal")
        self.et_max_printing_acceleration_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_max_printing_acceleration_e = Label(self.max_printing_acceleration_board, text="E", width=2, bg="#f2f2f2")
        self.lb_max_printing_acceleration_e.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_printing_acceleration_e = StringVar()
        self.et_max_printing_acceleration_e = Entry(self.max_printing_acceleration_board, textvariable=self.max_printing_acceleration_e, width=8, state="normal")
        self.et_max_printing_acceleration_e.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_max_printing_acceleration = Button(self.max_printing_acceleration_board, text=" Set Acceleration(P) ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=130, command=self.set_max_printing_acceleration)
        self.btn_max_printing_acceleration.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        ##########Max Traveling Acceleration##########

        self.max_traveling_acceleration_board = Frame(self.upper_panel, background="#f2f2f2")
        self.max_traveling_acceleration_board.pack(side=TOP, fill=X)

        self.lb_max_traveling_acceleration = Label(self.max_traveling_acceleration_board, text="Max traveling move acceleration", anchor = 'w', width=28, bg="#f2f2f2")
        self.lb_max_traveling_acceleration.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_max_traveling_acceleration_x = Label(self.max_traveling_acceleration_board, text="X", width=2, bg="#f2f2f2")
        self.lb_max_traveling_acceleration_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_traveling_acceleration_x = StringVar()
        self.et_max_traveling_acceleration_x = Entry(self.max_traveling_acceleration_board, textvariable=self.max_traveling_acceleration_x, width=8, state="normal")
        self.et_max_traveling_acceleration_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_max_traveling_acceleration_y = Label(self.max_traveling_acceleration_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_max_traveling_acceleration_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_traveling_acceleration_y = StringVar()
        self.et_max_traveling_acceleration_y = Entry(self.max_traveling_acceleration_board, textvariable=self.max_traveling_acceleration_y, width=8, state="normal")
        self.et_max_traveling_acceleration_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_max_traveling_acceleration_z = Label(self.max_traveling_acceleration_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_max_traveling_acceleration_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_traveling_acceleration_z = StringVar()
        self.et_max_traveling_acceleration_z = Entry(self.max_traveling_acceleration_board, textvariable=self.max_traveling_acceleration_z, width=8, state="normal")
        self.et_max_traveling_acceleration_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_max_traveling_acceleration_e = Label(self.max_traveling_acceleration_board, text="E", width=2, bg="#f2f2f2")
        self.lb_max_traveling_acceleration_e.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_traveling_acceleration_e = StringVar()
        self.et_max_traveling_acceleration_e = Entry(self.max_traveling_acceleration_board, textvariable=self.max_traveling_acceleration_e, width=8, state="normal")
        self.et_max_traveling_acceleration_e.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_max_traveling_acceleration = Button(self.max_traveling_acceleration_board, text=" Set Acceleration(T) ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=130, command=self.set_max_traveling_acceleration)
        self.btn_max_traveling_acceleration.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        ##########Extruder PID##########

        self.extruder_pid_board = Frame(self.upper_panel, background="#f2f2f2")
        self.extruder_pid_board.pack(side=TOP, fill=X)

        self.lb_extruder_pid = Label(self.extruder_pid_board, text="Extruder PID", anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_extruder_pid.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_extruder_pid_h = Label(self.extruder_pid_board, text="H", width=2, bg="#f2f2f2")
        self.lb_extruder_pid_h.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.extruder_pid_h = StringVar()
        self.et_extruder_pid_h = Entry(self.extruder_pid_board, textvariable=self.extruder_pid_h, width=8, state="normal")
        self.et_extruder_pid_h.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_extruder_pid_p = Label(self.extruder_pid_board, text="P", width=2, bg="#f2f2f2")
        self.lb_extruder_pid_p.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.extruder_pid_p = StringVar()
        self.et_extruder_pid_p = Entry(self.extruder_pid_board, textvariable=self.extruder_pid_p, width=8, state="normal")
        self.et_extruder_pid_p.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_extruder_pid_i = Label(self.extruder_pid_board, text="I", width=2, bg="#f2f2f2")
        self.lb_extruder_pid_i.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.extruder_pid_i = StringVar()
        self.et_extruder_pid_i = Entry(self.extruder_pid_board, textvariable=self.extruder_pid_i, width=8, state="normal")
        self.et_extruder_pid_i.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_extruder_pid_d = Label(self.extruder_pid_board, text="D", width=2, bg="#f2f2f2")
        self.lb_extruder_pid_d.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.extruder_pid_d = StringVar()
        self.et_extruder_pid_d = Entry(self.extruder_pid_board, textvariable=self.extruder_pid_d, width=8, state="normal")
        self.et_extruder_pid_d.pack(side=LEFT, anchor="n", padx=2, pady=5)


        self.btn_extruder_pid = Button(self.extruder_pid_board, text=" Set Extruder PID ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=130, command=self.set_extruder_pid)
        self.btn_extruder_pid.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        ##########Bed PID##########
        self.bed_pid_board = Frame(self.upper_panel, background="#f2f2f2")
        self.bed_pid_board.pack(side=TOP, fill=X)

        self.lb_bed_pid = Label(self.bed_pid_board, text="Bed PID", anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_bed_pid.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_bed_pid_p = Label(self.bed_pid_board, text="P", width=2, bg="#f2f2f2")
        self.lb_bed_pid_p.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.bed_pid_p = StringVar()
        self.et_bed_pid_p = Entry(self.bed_pid_board, textvariable=self.bed_pid_p, width=8, state="normal")
        self.et_bed_pid_p.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_bed_pid_i = Label(self.bed_pid_board, text="I", width=2, bg="#f2f2f2")
        self.lb_bed_pid_i.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.bed_pid_i = StringVar()
        self.et_bed_pid_i = Entry(self.bed_pid_board, textvariable=self.bed_pid_i, width=8, state="normal")
        self.et_bed_pid_i.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_bed_pid_d = Label(self.bed_pid_board, text="D", width=2, bg="#f2f2f2")
        self.lb_bed_pid_d.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.bed_pid_d = StringVar()
        self.et_bed_pid_d = Entry(self.bed_pid_board, textvariable=self.bed_pid_d, width=8, state="normal")
        self.et_bed_pid_d.pack(side=LEFT, anchor="n", padx=2, pady=5)


        self.btn_bed_pid = Button(self.bed_pid_board, text=" Set Bed PID ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.set_bed_pid)
        self.btn_bed_pid.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        ##########Max Jerk##########
        self.max_jerk_board = Frame(self.upper_panel, background="#f2f2f2")
        self.max_jerk_board.pack(side=TOP, fill=X)

        self.lb_max_jerk = Label(self.max_jerk_board, text="Max Jerk", anchor = 'w', width=12, bg="#f2f2f2")
        self.lb_max_jerk.pack(side=LEFT, anchor="n", padx=10, pady=5)

        self.lb_max_jerk_x = Label(self.max_jerk_board, text="X", width=2, bg="#f2f2f2")
        self.lb_max_jerk_x.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_jerk_x = StringVar()
        self.et_max_jerk_x = Entry(self.max_jerk_board, textvariable=self.max_jerk_x, width=8, state="normal")
        self.et_max_jerk_x.pack(side=LEFT, anchor="n", padx=2, pady=5)
        
        self.lb_max_jerk_y = Label(self.max_jerk_board, text="Y", width=2, bg="#f2f2f2")
        self.lb_max_jerk_y.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_jerk_y = StringVar()
        self.et_max_jerk_y = Entry(self.max_jerk_board, textvariable=self.max_jerk_y, width=8, state="normal")
        self.et_max_jerk_y.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_max_jerk_z = Label(self.max_jerk_board, text="Z", width=2, bg="#f2f2f2")
        self.lb_max_jerk_z.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_jerk_z = StringVar()
        self.et_max_jerk_z = Entry(self.max_jerk_board, textvariable=self.max_jerk_z, width=8, state="normal")
        self.et_max_jerk_z.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.lb_max_jerk_e = Label(self.max_jerk_board, text="E", width=2, bg="#f2f2f2")
        self.lb_max_jerk_e.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.max_jerk_e = StringVar()
        self.et_max_jerk_e = Entry(self.max_jerk_board, textvariable=self.max_jerk_e, width=8, state="normal")
        self.et_max_jerk_e.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_max_jerk = Button(self.max_jerk_board, text=" Set Max Jerk ",  bitmap="gray12", compound=LEFT, anchor="w",   height=15, width=95, command=self.set_max_jerk)
        self.btn_max_jerk.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        ##########Custom Command Line##########

        self.lb_command_line = Label(self.middle_panel, text="Command", width=10, bg="#f2f2f2")
        self.lb_command_line.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.command_line = StringVar()
        self.et_command_line = Entry(self.middle_panel, textvariable=self.command_line, width=80, state="normal")
        self.et_command_line.pack(side=LEFT, anchor="n", padx=2, pady=5)

        self.btn_command = Button(self.middle_panel, text=" Send Command ", bitmap="gray12", width=115, height=15, compound=LEFT, anchor="w", command=self.send_command)
        self.btn_command.pack(side=RIGHT, anchor="n", padx=5, pady=5)

        self.motor_text = ScrolledText(self.lower_panel, state="normal", width=180)
        self.motor_text.bind("<KeyPress>", lambda e: "break")
        self.motor_text.pack(side=LEFT, anchor="n", padx=5)

        self.controller = MotorController(self.motor_text)
        self.profile = os.path.join(os.path.split(os.path.realpath(__file__))[0], "default.conf")

        self.controller.output_to_panel("Note: some of new features are still unfinished.\nAbout acceleration settings, they all in unit/sec^2. \nIf you have problems in using, please contact us\n")

    def send_command(self):
        self.controller.send_cmd(self.command_line.get(), self)

    def set_travel(self):
        self.controller.set_motor(1, self)
    
    def set_step(self):
        self.controller.set_motor(2, self)
    
    def set_direction(self):
        self.controller.set_motor(3, self)
    
    def set_velocity(self):
        self.controller.set_motor(4, self)

    def set_max_printing_acceleration(self):
        pass

    def set_max_traveling_acceleration(self):
        pass

    def set_max_jerk(self):
        pass

    def set_extruder_pid(self):
        pass

    def set_bed_pid(self):
        pass
    
    def connect(self):
        try:
            self.controller.output_to_panel("Start to initialize configuration...\n")
            self.controller.init_config(self.profile, self.port_item.get(), False)
            self.controller.output_to_panel("Start to set boot mode...\n")
            self.controller.set_normal()
        except Exception as e:
            self.controller.output_to_panel("Error, Connecting failed! Details: " + str(e) + "\n")
            return
    
    def disconnect(self):
        self.controller.close_serial()
        self.controller.output_to_panel("Serial port has been closed!\n")

    def reconnect(self):
        self.controller.reconnect_serial()
        self.controller.output_to_panel("Serial port has been reconnected!\n")
    
    def get_motor_status(self):
        self.controller.get_motor_status(self)
Ejemplo n.º 13
0
def OnDoubleClick(event, param):

    global fileview_l

    if len(fileview_l) > 0:
        fileview_l[0].destroy()
    item = treeview_l[param].selection()[0]
    filename = treeview_l[param].item(item, "text")
    linenumber = treeview_l[param].item(item, "values")
    fileview = Toplevel()
    fileview.title(target_path)
    fileview.geometry("700x560+450+450")
    fileview_l.append(fileview)

    filename_text = Text(fileview,
                         state='normal',
                         height=2,
                         width=100,
                         bg='#f5f5f0')
    filename_text.pack()
    filename_text.tag_configure('color3',
                                background='#0077b3',
                                foreground='#ffffff',
                                font=('Verdana', 12, 'bold'),
                                justify=CENTER)
    filename_text.tag_configure('color2',
                                background='#808000',
                                foreground='#ffffff',
                                font=('Verdana', 9, 'bold'))
    filename_text.insert(END, filename + "\n", 'color3')

    if len(linenumber[1]) > 90:
        firstpart = linenumber[1][0:90]
        secondpart = '        - ' + linenumber[1][90:len(linenumber[1]) - 1]
    else:
        firstpart = linenumber[1]
        secondpart = ''

    filename_text.insert(END, "        Reason: " + firstpart + "\n", 'color2')
    filename_text.insert(END, secondpart, 'color2')

    filename_text.configure(state='disabled')
    style_text = Text(fileview,
                      state='normal',
                      height=35,
                      width=2,
                      bg='#808080')
    style_text.pack(side=LEFT)
    #fileview_text.tag_configure('color1', background='#808080',foreground='#808080', font=('Verdana', 9, 'bold'))

    fileview_text = ScrolledText(fileview,
                                 state='normal',
                                 height=35,
                                 width=100,
                                 bg='#FFFCFC')
    fileview_text.pack(side=LEFT)

    fileview_text.tag_configure('big1',
                                font=('Verdana', 11, 'bold'),
                                justify=CENTER)
    fileview_text.tag_configure('big0', font=('Verdana', 10, 'bold'))
    fileview_text.tag_configure('big2', font=('Verdana', 9, 'bold'))
    fileview_text.tag_configure('big', font=('Verdana', 7))
    fileview_text.tag_configure('color',
                                background='#b30000',
                                foreground='#ffffff',
                                font=('Verdana', 8, 'bold'))

    #fileview_text.add_separator()

    fileview_text.insert(END, "\n", 'color2')
    #fileview_text.insert(END, "\n", 'big0')
    i = 1
    with open(target_path, 'r') as f:
        for line in f:
            if str(i) == linenumber[0]:
                #fileview_text.insert(END, ".>     ", 'color1')
                fileview_text.insert(END, str(i) + "" + ".>     ", 'color')
                fileview_text.insert(END, line, 'color')
            else:
                #fileview_text.insert(END, ".>     ", 'color1')
                fileview_text.insert(END, str(i) + "" + ".>     ", 'big')
                fileview_text.insert(END, line, 'big')
            #style_text.insert(END, "  "+ str(i)+".>     ", 'big')

            i += 1
    f.close()
    #fileview_text.insert(END, ".>     ", 'color1')
    # create a popup menu
    popmenu = Menu(fileview)
    popmenu.add_command(label="Undo", command=save)
    popmenu.add_command(label="Redo", command=save)

    # attach popup to frame
    fileview_text.bind("<Button-3>", functools.partial(popup, param=popmenu))
    fileview_text.configure(state='disabled')
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','')
    inputText = inputText.replace('equals','=')
    inputText = inputText.replace('plus','+')
    inputText = inputText.replace('multiplies','*')
Ejemplo n.º 15
0
class SocketGUI:
    def __init__(self):
        """ 
          Sets up the tkinter window and some attributes.
        """
        # Initialize Attributes
        self.port = 80
        self.address = "127.0.0.1"
        self.connected = False
        self.acting_as_server = False
        self.acting_as_client = True

        # Create Tkinter root window and set title
        self.root = Tk()
        self.root.title(PROGRAM_NAME + " " + VERSION)
        self.root.protocol("WM_DELETE_WINDOW", self.close)

        # Create frame
        self.fpopup = Frame(self.root, width=500)
        self.fpopup.pack(expand=1, fill=BOTH)

        # Create the menus
        self.menuobj = Menu(self.root)
        self.root.config(menu=self.menuobj)
        self.filemenu = Menu(self.menuobj, tearoff=0)
        self.menuobj.add_cascade(label="File", menu=self.filemenu)
        self.filemenu.add_command(label="Start Server", command=self.setup_server)
        self.filemenu.add_command(label="Stop Server", command=self.setup_server)
        self.filemenu.add_command(label="Connect", command=self.connect)
        self.filemenu.add_command(label="Disconnect", command=self.disconnect)
        self.filemenu.add_command(label="Exit", command=self.close)
        self.editmenu = Menu(self.menuobj, tearoff=0)
        self.menuobj.add_cascade(label="Edit", menu=self.editmenu)
        self.editmenu.add_command(label="Configuration", command=self.configuration)
        self.helpmenu = Menu(self.menuobj, tearoff=0)
        self.menuobj.add_cascade(label="Help", menu=self.helpmenu)
        self.helpmenu.add_command(label="About", command=self.about)

        # Create the message window
        self.message_window = ScrolledText(self.fpopup, width=90, height=24, background="white")
        self.message_window.pack(fill=BOTH, expand=YES)

        # Create the entry field
        self.entry_field = Entry(self.fpopup, width=60, background="white")
        self.entry_field.pack(side=LEFT, fill=BOTH, expand=YES)

        # Bindings
        self.entry_field.bind("<Return>", self.sendmessage_event)
        self.entry_field.bind("<Control-n>", self.connect_event)
        self.message_window.bind("<Control-n>", self.connect_event)

        # Create Buttons
        self.send_button = Button(self.fpopup, text="Send", command=self.sendmessage)
        self.send_button.pack(side=LEFT, expand=NO)

        # Start the Tk main routine
        self.root.mainloop()

    def configuration(self):
        """
          Sets up the configuration menu
        """
        self.configuration_menu = Toplevel()
        self.configuration_menu.title(PROGRAM_NAME + " - Configuration")

        self.port_label = Label(self.configuration_menu, text="Port:", width=40, anchor=W)
        self.port_entry_field = Entry(self.configuration_menu, width=40, background="white")
        self.address_label = Label(self.configuration_menu, text="Address:", width=40, anchor=W)
        self.address_entry_field = Entry(self.configuration_menu, width=40, background="white")
        self.save_configuration_button = Button(self.configuration_menu, text="Save", command=self.save_configuration)
        self.cancel_configuration_button = Button(
            self.configuration_menu, text="Cancel", command=self.cancel_configuration
        )

        self.port_entry_field.insert(END, str(self.port))
        self.address_entry_field.insert(END, self.address)

        self.port_label.grid(row=0, columnspan=2, sticky=W)
        self.port_entry_field.grid(row=1, columnspan=2, sticky=W, pady=5)
        self.address_label.grid(row=2, columnspan=2, sticky=W)
        self.address_entry_field.grid(row=3, columnspan=2, sticky=W, pady=5)
        self.save_configuration_button.grid(row=5, columnspan=2)
        self.cancel_configuration_button.grid(row=5, column=1, columnspan=2)

    def cancel_configuration(self):
        """
          Destroys the configuration menu
        """
        self.configuration_menu.destroy()

    def cancel_server(self):
        """
          Destroys the server setup menu
        """
        self.server_menu.destroy()

    def save_configuration(self):
        """
          Saves the configuration values and closes the window
        """
        self.port = int(self.port_entry_field.get())
        self.address = self.address_entry_field.get()
        self.configuration_menu.destroy()

    def about(self):
        """
          Calls the about window
        """
        tkMessageBox.showinfo("About", PROGRAM_NAME + " " + VERSION + "\n" + AUTHOR + "\n" + WEBSITE)

    def close(self):
        """
          Closes the whole application window
        """
        # Close the application
        if self.connected == True:
            self.clientSocket.sendmessage("/quit")
        if self.acting_as_server:
            self.serverSocket.close()
        self.root.destroy()

    def receiver(self, clientSocket, ADDR):
        """
          Receives the messages (called as a thread)
        """
        while 1:
            if self.connected == True:
                data = clientSocket.recv(1024)
                self.message_window.insert(END, "\n" + data)
                self.message_window.see(END)
                if data == "/quit":
                    self.connected = False
                    return 0

    def setup_server(self):
        """
          Calls the server setup menu
        """
        self.server_menu = Toplevel()
        self.server_menu.title(PROGRAM_NAME + " - Setup Server")

        self.server_port_label = Label(self.server_menu, text="Port:", width=40, anchor=W)
        self.server_port_entry_field = Entry(self.server_menu, width=40, background="white")
        self.server_address_label = Label(self.server_menu, text="Address:", width=40, anchor=W)
        self.server_address_entry_field = Entry(self.server_menu, width=40, background="white")
        self.start_server_button = Button(self.server_menu, text="Start", command=self.start_server)
        self.server_cancel_configuration_button = Button(self.server_menu, text="Cancel", command=self.cancel_server)

        self.server_port_label.grid(row=0, columnspan=2, sticky=W)
        self.server_port_entry_field.grid(row=1, columnspan=2, sticky=W, pady=5)
        self.server_address_label.grid(row=2, columnspan=2, sticky=W)
        self.server_address_entry_field.grid(row=3, columnspan=2, sticky=W, pady=5)
        self.start_server_button.grid(row=5, columnspan=2)
        self.server_cancel_configuration_button.grid(row=5, column=1, columnspan=2)

    def start_server(self):
        """
          Creates a server
        """
        try:
            self.serverSocket = Server(self.server_address_entry_field.get(), self.server_port_entry_field.get())
            self.serverSocket.listen()
            self.serverSocket.main()
            self.message_window.insert(
                END,
                "\n"
                + "*** ACTING AS A SERVER: LISTENING ON PORT "
                + self.server_port_entry_field.get()
                + " ON ADDRESS "
                + self.server_address_entry_field.get()
                + " ***",
            )
        except:
            pass

        self.cancel_server()
        self.acting_as_server = True

    def connect(self):
        """
          Connects the client to the given address and port
        """
        self.clientSocket = Client(self.address, self.port)
        try:
            if not self.connected:
                self.clientSocket.connect()
                self.connected = True
                thread.start_new_thread(self.receiver, (self.clientSocket.clientSocket, (self.address, self.port)))
            else:
                self.message_window.insert(END, "\n" + "Already connected!")
                self.message_window.see(END)
        except socket.error, (errno, errmessage):
            self.message_window.insert(END, "\n" + "**** ERROR No." + str(errno) + " --> " + str(errmessage) + " **** ")
            if errno == 111:
                self.message_window.insert(
                    END, "\n" + "Maybe you typed a false PORT or ADDRESS or the server has not been set up yet"
                )
            self.message_window.see(END)
Ejemplo n.º 16
0
class EditorMain(object):
    def __init__(self):
        self.root = tk.Tk(className="PyNestML IDE")
        self.after_id = None

        self.text_frame = tk.Frame(self.root,
                                   width=self.root.winfo_screenwidth(),
                                   height=self.root.winfo_screenheight() *
                                   0.70)
        self.text_frame.pack_propagate(False)
        self.textPad = ScrolledText(self.text_frame,
                                    height=1,
                                    width=1,
                                    undo=True)
        self.textPad.pack(side="top", fill="both", expand=True)
        self.text_frame.pack(side="top", fill="both", expand=True)

        self.line_nr_frame = tk.Frame(self.root,
                                      width=self.root.winfo_screenwidth())
        self.line_nr_frame.pack_propagate(False)
        self.line_nr = tk.Text(self.root,
                               width=self.root.winfo_screenwidth(),
                               height=1)
        self.line_nr.pack(side="top", fill="both", expand=True)
        self.line_nr_frame.pack(side="top", fill="both", expand=True)

        self.console_frame = tk.Frame(self.root,
                                      width=self.root.winfo_screenwidth(),
                                      height=self.root.winfo_screenheight() *
                                      0.20)
        self.console_frame.pack_propagate(False)
        self.console = ScrolledText(self.console_frame, width=1, height=1)
        self.console.pack(side="top", fill="both", expand=True)
        self.console_frame.pack(side="top", fill="both", expand=True)

        self.menu = Menu(root=self.root, text_pad=self.textPad, editor=self)
        self.highlighter = Highlighter(self.textPad, self)

        # insert empty model
        self.textPad.insert('1.0', 'PyNestML             \n')
        self.textPad.insert('2.0', '         Model       \n')
        self.textPad.insert('3.0', '               Editor\n')
        self.textPad.tag_add("l1", "%s.%s" % (1, 0),
                             "%s.%s" % (1, len('PyNestML')))
        self.textPad.tag_add("l2", "%s.%s" % (2, 0),
                             "%s.%s" % (2, len('         Model')))
        self.textPad.tag_add("l3", "%s.%s" % (3, 0),
                             "%s.%s" % (3, len('               Editor')))
        self.textPad.tag_config("l1", background="white", foreground="blue")
        self.textPad.tag_config("l2", background="white", foreground="red")
        self.textPad.tag_config("l3", background="white", foreground="green")
        self.last = self.textPad.get('0.0', tk.END)
        # insert start position of cursor
        self.console.pack(side=tk.BOTTOM)
        self.console.configure(state='disabled')
        self.line_nr.insert('1.0', 'Position: 0:0')
        self.line_nr.configure(state='disabled')
        # bind keys
        self.bind_keys()
        self.root.mainloop()

    def change_button_state(self, active=True):
        if not active:
            self.menu.modelmenu.entryconfig('Check CoCos', state=tk.DISABLED)
            self.menu.modelmenu.entryconfig('Compile Model', state=tk.DISABLED)
        else:
            self.menu.modelmenu.entryconfig('Check CoCos', state=tk.NORMAL)
            self.menu.modelmenu.entryconfig('Compile Model', state=tk.NORMAL)

    def exit_editor(self, _):
        self.menu.exit_command()

    def store_command(self, _):
        self.menu.save_command()

    def check_model(self):
        self.change_button_state(False)
        thread = threading.Thread(target=self.check_model_in_separate_thread)
        thread.start()
        return thread  # returns immediately after the thread starts

    def check_model_in_separate_thread(self):
        self.textPad.configure(state='disabled')
        ModelChecker.check_model_with_cocos(self.textPad.get('0.0', tk.END))
        self.report_findings()
        self.textPad.configure(state='normal')

    def check_syntax_in_separate_thread(self):
        ModelChecker.check_model_syntax(self.textPad.get('0.0', tk.END))
        self.report_findings()

    def check_model_syntax(self, _):
        self.update_line_number()
        # cancel the old job
        if self.after_id is not None:
            self.textPad.after_cancel(self.after_id)

        # create a new job
        self.after_id = self.textPad.after(800, self.do_check_model_syntax)

    def do_check_model_syntax(self):
        if self.textPad.get('0.0', tk.END) != self.last:
            if self.last is None or "".join(
                    self.textPad.get('0.0', tk.END).split()) != "".join(
                        self.last.split()):
                thread = threading.Thread(
                    target=self.check_syntax_in_separate_thread)
                thread.start()
                self.last = self.textPad.get('0.0', tk.END)
                return thread  # returns immediately after the thread starts

    def update_line_number(self):
        self.line_nr.configure(state='normal')
        self.line_nr.delete('1.0', tk.END)
        pos = self.textPad.index(tk.INSERT).split('.')
        self.line_nr.insert('1.0', 'Position: %s:%s' % (pos[0], pos[1]))
        self.line_nr.configure(state='disabled')

    def report_findings(self):
        # print('process complete!')
        self.highlighter.process_report()
        self.change_button_state(True)

    def bind_keys(self):
        # bind the events
        self.textPad.bind('<Control-q>', self.exit_editor)
        self.textPad.bind('<KeyRelease>', self.check_model_syntax)
        self.textPad.bind('<Control-s>', self.store_command)

    def clear_console(self):
        self.console.delete('1.0', tk.END)

    def report(self, text):
        if self.menu.show_syntax_errors_var.get() == 1:
            self.console.configure(state='normal')
            self.console.insert(tk.END, text + '\n')
            self.console.configure(state='disabled')

    def inc_font_size(self):
        f = tkFont.Font(self.textPad, self.textPad.cget('font'))
        self.textPad.configure(font=("Courier", f.configure()['size'] + 1))

    def dec_font_size(self):
        f = tkFont.Font(self.textPad, self.textPad.cget('font'))
        if not f.configure()['size'] - 1 < 4:
            self.textPad.configure(font=("Courier", f.configure()['size'] - 1))
Ejemplo n.º 17
0
class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.serial_list = None
        self.createWindow(master, 680, 350)
        self.createWidget(master)

    def createWindow(self, root, width, height):
        screenwidth = root.winfo_screenwidth()
        screenheight = root.winfo_screenheight()
        size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2,
                                (screenheight - height) / 2)
        root.geometry(size)
        root.maxsize(width, height)
        root.minsize(width, height)

    def createWidget(self, master):

        self.device_helper = DeviceHelper()
        self.device_helper.find_all_devices(self)
        self.menu = Frame(master, height=10, background="#f2f2f2")
        self.menu.pack(side=TOP, fill=X, pady=5)

        self.display_board = Frame(master, background="#f2f2f2")
        self.display_board.pack(side=TOP, fill=X)

        self.lb_port_list = Label(self.menu,
                                  text="Port:",
                                  width=4,
                                  background="#f2f2f2")
        self.lb_port_list.pack(side=LEFT, anchor="n", padx=5, pady=5)
        self.port_item = StringVar()
        self.cb_port_list = ttk.Combobox(self.menu,
                                         width=20,
                                         textvariable=self.port_item,
                                         state="readonly",
                                         background="#f2f2f2")
        self.cb_port_list["values"] = self.serial_list or ("Empty")
        self.cb_port_list.current(0)
        self.cb_port_list.pack(side=LEFT, anchor="w", pady=5)

        self.btn_select = Button(self.menu,
                                 text="Select",
                                 height=1,
                                 width=13,
                                 command=self.select_firmware,
                                 bg="#f2f2f2")
        self.btn_select.pack(side=LEFT, anchor="w", padx=10)

        self.btn_upgrade = Button(self.menu,
                                  text="Upgrade",
                                  height=1,
                                  width=13,
                                  command=self.create_upgrade_thread,
                                  bg="#f2f2f2")
        self.btn_upgrade.pack(side=LEFT, anchor="w", padx=10)

        self.btn_clear = Button(self.menu,
                                text="Clear",
                                height=1,
                                width=8,
                                command=self.clear_info_text,
                                bg="#f2f2f2")
        self.btn_clear.pack(side=LEFT, anchor="w", padx=10)

        self.info_text = ScrolledText(self.display_board,
                                      state="normal",
                                      width=93)
        self.info_text.bind("<KeyPress>", lambda e: "break")
        self.info_text.pack(side=LEFT, anchor="n", padx=5, fill=Y)

    def select_firmware(self):
        self.file_path = filedialog.askopenfilename(filetypes=[('BIN', 'bin')])
        if self.file_path is not None and self.file_path != "":
            self.info_text.insert(
                END, "New firmware file has been selected! Path:" +
                self.file_path + '\n')
            self.info_text.see(END)

    def clear_info_text(self):
        self.info_text.delete(1.0, END)

    def create_upgrade_thread(self):
        if hasattr(self, 'file_path'):
            tConnected = threading.Thread(target=self.start_to_upgrade,
                                          args=())
            tConnected.setDaemon(True)
            tConnected.start()
        else:
            self.info_text.insert(
                END, "Error, you haven't selected any firmware files!\n")
            self.info_text.see(END)

    def start_to_upgrade(self):
        self.btn_upgrade["state"] = "disabled"
        updator = FirmwareUpdator(self.info_text)
        profile = os.path.join(
            os.path.split(os.path.realpath(__file__))[0], "default.conf")
        updator.update_firmware(profile, self.port_item.get(), self.file_path)
        self.btn_upgrade["state"] = "normal"
Ejemplo n.º 18
0
    data = tkFileDialog.asksaveasfile(mode='w',
                                      title="Save file",
                                      defaultextension='.txt',
                                      filetypes=(("Text Documents", "*.txt"),
                                                 ("All Files", "*.*")))
    if data:
        data.write(contents)
        data.close()
    pass


def help():
    tkMessageBox.showinfo(
        "About", "Version: 0.1 \nPython Homework 3\nAuthor: "
        "Yildirim Can Sehirlioglu\nStudent ID: 156336IVCM")
    pass


textFrame.bind("<Control-Key-a>", selectAll)
textFrame.bind("<Control-Key-A>", selectAll)
mainMenu = tiki.Menu(motherContainer)
motherContainer.config(menu=mainMenu)
flMenu = tiki.Menu(mainMenu, tearoff=False)
mainMenu.add_cascade(label="File", menu=flMenu)
flMenu.add_command(label="Open", command=openFile)
flMenu.add_command(label="Save", command=saveFile)
flMenu.add_separator()
flMenu.add_command(label="Close", command=motherContainer.quit)
mainMenu.add_command(label="Help", command=help)
motherContainer.mainloop()
Ejemplo n.º 19
0
class mainwindow:
    def __init__(self, master):
        self.master = master
        if os.path.exists("C:\Python27") or os.path.exists("C:\Python36-32"):

            self.frame2 = tk.LabelFrame(
                self.master,
                text="Editor",
                width=800,
                height=self.master.winfo_screenheight(),
                bd=5)
            self.frame3 = tk.LabelFrame(
                self.master,
                text="Output",
                width=self.master.winfo_screenwidth() - 830,
                height=(self.master.winfo_screenheight()) / 2,
                bd=5)
            self.frame2.grid(row=1, column=0, padx=8)
            self.frame2.pack_propagate(0)
            self.frame3.grid(row=1, column=1, sticky='nw')
            self.frame3.pack_propagate(0)
            self.textPad = ScrolledText(self.frame2, width=800, height=1000)
            self.textPad.focus_set()
            self.textPad.bind('<KeyPress>', self.onKeyPress)
            self.textPad.bind('<Control-Key-a>', self.select_all)
            self.textPad.bind('<Control-Key-A>', self.select_all)
            self.outputpad = Text(self.frame3, width=450, height=400)
            self.textPad.pack()
            self.outputpad.pack()
            self.outputpad.configure(state='disabled')
            self.filename = ""
            self.final_data = ""
            self.entry = 0
            self.s = wincl.Dispatch("SAPI.SpVoice")
            self.s.Rate = 1
            global voice
            self.special_char = {
                '(': 'Parenthesis L',
                ')': 'Parenthestis R',
                '[': 'Bracket L',
                ']': 'Bracket R',
                '{': 'Curly Braces L',
                '}': 'Curly Braces R',
                '<': 'Angle Bracket L',
                '>': 'Angle Bracket R',
                ':': 'Colon',
                '!': 'Exclamation Mark',
                '~': 'Tilde',
                '^': 'Caret',
                '-': 'Hyphen',
                ' ': 'Space',
                '|': 'Pipe',
                ';': 'Semicolon',
                '\'': 'Single Quote',
                '"': 'Double Quote',
                '?': 'Question Mark',
                ',': 'Comma',
                '.': 'Period'
            }
            if os.path.exists("C:\Python27\PowerPad"): pass
            else: os.makedirs("C:\Python27\PowerPad")
            os.chdir("C:\\Python27\\PowerPad")
            os.environ["PATH"] += os.pathsep + "C:\Python27\PowerPad"
        else:
            tkMessageBox.showerror("Python Not Found",
                                   "Sorry, no Python available")
            s = wincl.Dispatch("SAPI.SpVoice")
            s.Rate = 1
            s.Speak(
                "python is not installed, Please intall python on your Computer"
            )
            self.master.destroy()

    def speak(self, string):
        self.s.Speak(string)

    def select_all(self, event):
        self.textPad.tag_add(SEL, "1.0", END)
        self.textPad.mark_set(INSERT, "1.0")
        self.textPad.see(INSERT)
        return 'break'

    def outputconf(self):
        self.outputpad.configure(state='normal')
        self.outputpad.insert('end', '>>> Running Your Code\n')
        self.outputpad.configure(state='disabled')

    def alreadysave(self, data, filename):
        self.speak("SAVING " + filename)
        self.saved_file = open(filename, "w+")
        self.saved_file.write(data)
        self.saved_file.close()

    def popup(self):
        self.w = popupWindow(self.master)
        self.w.e.focus_set()
        self.master.wait_window(self.w.top)
        self.filename = self.w.val

    def open_file(self):
        try:
            self.speak("ENTER THE FILE NAME WITHOUT EXTENSION AND PRESS ENTER")
            self.master.bell()
            self.popup()
            file = open(self.filename, "r")
            contents = file.read()
            self.textPad.delete('0.0', 'end')
            self.outputpad.configure(state='normal')
            self.outputpad.delete('0.0', 'end')
            self.outputpad.configure(state='disabled')
            self.textPad.insert('1.0', contents)
            file.close()
            self.final_data = self.textPad.get('1.0', END + '-1c')
            self.textPad.focus_set()
            self.frame2.configure(text=self.filename)
        except IOError:
            pass

    def SaVe(self, data):
        self.final_data = self.data
        if not self.filename:
            self.speak("ENTER THE FILE NAME WITHOUT EXTENSION AND PRESS ENTER")
            self.master.bell()
            self.popup2()
            if str(self.filename) in os.listdir("C:\\Python27\\PowerPad"):
                if self.onreplace() == "yes":
                    self.alreadysave(self.data, self.filename)
                    self.textPad.focus_set()
                else:
                    self.speak("ENTER THE NAME AGAIN")
                    self.popup2()
                    self.SaVe(self.data)
            else:
                self.SaVe(self.filename)
        else:
            self.alreadysave(self.data, self.filename)
        self.textPad.focus_set()
        self.frame2.configure(text=self.filename)

    def popup2(self):
        self.w1 = popupWindow1(self.master)
        self.w1.e1.focus_set()
        self.master.wait_window(self.w1.top1)
        self.filename = self.w1.val1

    def outputgen(self, filename):
        process = subprocess.Popen(["python", filename],
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
        self.output = process.stdout.readlines()
        self.error = process.stderr.readlines()
        process.wait()
        '''if not 'prompt' in os.environ:
			self.speak("input")
			print("in")'''

        if self.error:
            self.speak("Error")
            self.errorsay(self.error)
        else:
            self.speak("Output")
            self.outputsay(self.output)

    def errorline(self, error):
        s = ""
        for i in error:
            if not "line" in i:
                pass
            else:
                s += i
        x = s.split(",")
        s = ""
        for i in x:
            if not "line" in i:
                pass
            else:
                s += i
        return s

    def errorsay(self, error):
        s = self.errorline(error)
        x = ((error[-1].split(":"))[0]) + " ON THE "
        self.outputpad.configure(state='normal')
        self.outputpad.insert('end', x + s)
        self.outputpad.configure(state='disabled')
        l = s.split(' ')
        errorline = (self.textPad.get('1.0', END +
                                      '-1c').split("\n"))[int(l[-1][0]) - 1]
        self.textPad.mark_set("insert",
                              "%d.%d" % (int(l[-1][0]), len(errorline)))
        self.speak(x)
        self.speak(s)
        for i in errorline:
            if i in self.special_char.keys(): self.speak(self.special_char[i])
            else: self.speak(i)

    def outputsay(self, output):
        self.outputpad.configure(state='normal')
        for i in output:
            self.speak(i)
            self.outputpad.insert('end', i)
        self.outputpad.configure(state='disabled')

    def onexit(self):
        self.speak("PRESS Y TO EXIT AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Exit", "Are You Sure?")

    def onopen(self):
        self.speak(
            "THERE ARE SOME UNSAVED CHANGES DO YOU WANT TO SAVE THE FILE BEFORE OPEN A FILE?"
        )
        self.speak("PRESS Y TO SAVE AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Save and Open", "Are You Sure?")

    def onsave(self):
        self.speak(
            "THERE ARE SOME UNSAVED CHANGES DO YOU WANT TO SAVE THE FILE BEFORE EXIT?"
        )
        self.speak("PRESS Y TO SAVE AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Save and Exit", "Are You Sure?")

    def onreplace(self):
        self.speak(
            "THERE ALREADY EXIXT FILE WITH THE SAME NAME, DO YOU WANT TO REPLACE IT ?"
        )
        self.speak("PRESS Y TO REPLACE AND N TO CANCEL")
        self.master.bell()
        return tkMessageBox.askquestion("Replace", "Are You Sure?")

    def pressf1(self):
        if self.final_data != self.data:
            if self.onsave() == "yes":
                self.SaVe(self.data)
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
            else:
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
        else:
            self.final_data = ""
            self.filename = ""
            self.textPad.delete('0.0', 'end')

        self.outputpad.configure(state='normal')
        self.outputpad.delete('0.0', 'end')
        self.outputpad.configure(state='disabled')
        self.frame2.configure(text="Editor")
        self.speak("Opening a new Tab")

    def pressf2(self):
        if self.final_data != self.data:
            if self.onopen() == "yes":
                self.SaVe(self.data)
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
                self.open_file()
            else:
                self.alreadysave(self.data, self.filename)
                self.final_data = ""
                self.filename = ""
                self.textPad.delete('0.0', 'end')
                self.open_file()
        else:
            self.open_file()

    def pressf4(self):
        if not self.final_data == self.data:
            if self.onsave() == "yes":
                self.SaVe(self.data)
                self.master.destroy()
            else:
                self.master.destroy()
        else:
            if self.onexit() == "yes": self.master.destroy()
            else: pass

    def pressf5(self):
        if self.filename:
            self.outputconf()
            self.alreadysave(self.data, self.filename)
            self.outputgen(self.filename)
        else:
            self.SaVe(self.data)
            self.outputconf()
            self.outputgen(self.filename)

    def pressf8(self):
        global voice
        if voice == 0:
            voice = 1
            self.s.Voice = self.s.GetVoices().Item(voice)
        else:
            voice = 0
            self.s.Voice = self.s.GetVoices().Item(voice)

    def pressf11(self):
        self.speak("INSTRUCTIONS ARE ")
        self.speak(
            "PRESS F1 FOR NEW FILE, F2 TO OPEN FILE, F3 TO SAVE FILE, F4 TO EXIT, F5 TO COMPILE, F6 TO LISTEN ALL CODE, F7 TO CLEAR ALL, F8 TO CHANGE VOICE, F9 TO KNOW ABOUT US, F11 FOR INSTRUCTIONS"
        )

    def onKeyPress(self, event):
        #global self.filename
        #self.speak(event.keysym)
        #print(event.keysym)
        global row, col
        row, col = self.textPad.index('insert').split('.')
        self.data = self.textPad.get('1.0', END + '-1c')

        if event.keysym == "F1": self.pressf1()

        elif event.keysym == "F2":
            self.speak("OPENING")
            if self.data == "": self.open_file()
            else: self.pressf2()

        elif event.keysym == "F3":
            self.speak("SAVING")
            if self.data == "": pass
            else: self.SaVe(self.data)

        elif event.keysym == "F4":
            self.speak("EXITING")
            if self.data == "":
                if self.onexit() == "yes": self.master.destroy()
                else: pass
            else: self.pressf4()

        elif event.keysym == "F5":
            self.speak("COMPILE")
            if self.data == "": pass
            else: self.pressf5()

        elif event.keysym == "F6":
            self.speak("CODE IS")
            self.speak(self.data)

        elif event.keysym == "F7":
            self.speak("CLEARING ALL CODE")
            self.textPad.delete("0.0", 'end')

        elif event.keysym == "F8":
            self.speak("CHANGING VOICE")
            self.pressf8()

        elif event.keysym == "F9":
            #self.speak("ABOUT Us");
            self.speak("CREATED BY NANDISH PATEL")

        elif event.keysym == "F11":
            self.speak("INSTRUCTIONS")
            self.pressf11()

        else:
            pass