예제 #1
0
def run(event):
    """Run the script and shows the resulting HTML code in a
    new window
    If started with the "Make HTML" button, saves HTML output in
    a file"""
    pythonCode=pythonText.get(1.0,END)
    lines=pythonCode.split('\n')
    lines=map(lambda x:x[5:],lines)
    pythonCode='\n'.join(lines)
    execWindow=Toplevel()
    execText=ScrolledText(execWindow,width=40,height=40,bg="white",
        font=FONT)
    execText.pack()
    s=sys.stdout
    sys.stdout=Output(execText)
    try:
        exec(pythonCode) in globals()
        if event.widget is bRunHTML:
            htmlFilename=os.path.splitext(pihText.filename)[0]+".htm"
            if os.path.exists(htmlFilename):
                override=tkMessageBox.askyesno("Override ?",
                    "File %s already exists - Override ?" \
                    %os.path.basename(htmlFilename))
                if not override:
                    return
            f=open(htmlFilename,"w")
            f.write(execText.get(1.0,END))
            f.close()
            path=os.path.join(os.getcwd(),htmlFilename)
            webbrowser.open_new("file://"+path)
    except:
        traceback.print_exc(file=sys.stdout)
    sys.stdout=s
예제 #2
0
파일: tkui.py 프로젝트: v-legoff/accertin
class Autotyper:
    """
  Autotyper class, it generates the autotyper window, waits for entering text
  and then calls a function to work with the text.
  """
    def __init__(self, master, sendfunc):
        """
    Initializes the autotyper.
    
    @param master: the main tk window
    @type  master: Tk

    @param sendfunc: the callback function
    @type  sendfunc: function
    """
        self._sendfunc = sendfunc

        self._frame = Toplevel(master)

        # self._frame.geometry("400x300")
        self._frame.title("Lyntin -- Autotyper")

        self._frame.protocol("WM_DELETE_WINDOW", self.cancel)

        if os.name == "posix":
            fontname = "Courier"
        else:
            fontname = "Fixedsys"
        fnt = tkFont.Font(family=fontname, size=12)

        self._txt = ScrolledText(self._frame,
                                 fg="white",
                                 bg="black",
                                 font=fnt,
                                 height=20)
        self._txt.pack(side=TOP, fill=BOTH, expand=1)

        self._send_btn = Button(self._frame, text="Send", command=self.send)
        self._send_btn.pack(side=LEFT, fill=X, expand=0)

        self._cancel_btn = Button(self._frame,
                                  text="Cancel",
                                  command=self.cancel)
        self._cancel_btn.pack(side=RIGHT, fill=X, expand=0)

    def send(self):
        """
    Will be called when the user clicks on the 'Send' button.
    """
        text = fix_unicode(self._txt.get(1.0, END))
        self._sendfunc(text)
        self._frame.destroy()

    def cancel(self):
        """
    Will be called when the user clicks on the 'Cancel' button.
    """
        self._sendfunc(None)
        self._frame.destroy()
예제 #3
0
class PopupScrolledText(PopupWindow):
    """
    Scrolled text output window with 'Save As...'
    """

    def __init__(self, title="", kind="", iconfile=None, var=None):
        PopupWindow.__init__(self, title=title, kind=kind, iconfile=iconfile)
        if var:
            self._var = var
        else:
            self._var = BooleanVar()
        self._var.trace_variable("w", self._visibility_control)
        self._text = ScrolledText(self)
        self._text.pack()
        self._text.config(font=FONT)
        self._make_menu()
        self._visibility_control()

    def on_close(self, *args):
        self._var.set(False)

    def _visibility_control(self, *args):
        if self._var.get():
            self.deiconify()
        else:
            self.withdraw()

    def _make_menu(self):
        topmenu = Menu(self)
        self.config(menu=topmenu)
        file = Menu(topmenu, tearoff=0)
        file.add_command(label="Save as...", command=self.on_save_as)
        file.add_command(label="Hide", command=self.on_close)
        topmenu.add_cascade(label="File", menu=file)
        edit = Menu(topmenu, tearoff=0)
        edit.add_command(label="Clear text", command=self.on_clear)
        topmenu.add_cascade(label="Edit", menu=edit)

    def on_save_as(self):
        filename = asksaveasfilename()
        if filename:
            alltext = self.gettext()
            f = open(filename, "w")
            f.write(alltext)
            f.close()

    def on_clear(self):
        self._text.delete("0.0", END)
        self._text.update()

    def gettext(self):
        return self._text.get("1.0", END + "-1c")

    def hide(self):
        self._var.set(False)

    def show(self):
        self._var.set(True)
예제 #4
0
파일: tkui.py 프로젝트: v-legoff/accertin
class Autotyper:
    """
  Autotyper class, it generates the autotyper window, waits for entering text
  and then calls a function to work with the text.
  """

    def __init__(self, master, sendfunc):
        """
    Initializes the autotyper.
    
    @param master: the main tk window
    @type  master: Tk

    @param sendfunc: the callback function
    @type  sendfunc: function
    """
        self._sendfunc = sendfunc

        self._frame = Toplevel(master)

        # self._frame.geometry("400x300")
        self._frame.title("Lyntin -- Autotyper")

        self._frame.protocol("WM_DELETE_WINDOW", self.cancel)

        if os.name == "posix":
            fontname = "Courier"
        else:
            fontname = "Fixedsys"
        fnt = tkFont.Font(family=fontname, size=12)

        self._txt = ScrolledText(self._frame, fg="white", bg="black", font=fnt, height=20)
        self._txt.pack(side=TOP, fill=BOTH, expand=1)

        self._send_btn = Button(self._frame, text="Send", command=self.send)
        self._send_btn.pack(side=LEFT, fill=X, expand=0)

        self._cancel_btn = Button(self._frame, text="Cancel", command=self.cancel)
        self._cancel_btn.pack(side=RIGHT, fill=X, expand=0)

    def send(self):
        """
    Will be called when the user clicks on the 'Send' button.
    """
        text = fix_unicode(self._txt.get(1.0, END))
        self._sendfunc(text)
        self._frame.destroy()

    def cancel(self):
        """
    Will be called when the user clicks on the 'Cancel' button.
    """
        self._sendfunc(None)
        self._frame.destroy()
예제 #5
0
class EmailPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        case_name = entry.get()
        label = tk.Label(self,text=case_name)
        label.pack(side="top", fill="x", pady=10)
    
        sidebar = Frame(self , width=200 , bg='white' , height=500, relief='sunken' , borderwidth=2)
        sidebar.pack(expand=True , fill='y' , side='left' , anchor='nw')
    
        screen = Frame(self, width=200, bg='white', height=500, relief='sunken', borderwidth=2)
        screen.pack(expand=True, fill='y', side='left', anchor='nw')
    
        self.text = ScrolledText(screen, undo=True)
        self.text['font'] = ('consolas', '12')
        self.text.grid(row=0,column=4)
        self.text.pack(expand=True, fill='both',side=RIGHT)
        
        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        button = tk.Button(sidebar, text="Start",command=lambda:self.run_script(),width=20)
        button.pack()

        label = tk.Label(sidebar,text='',width=20,bg="white")
        label.pack()
        button = tk.Button(sidebar, text="Go Back <<",command=lambda:controller.show_frame("PageTwo"),width=20)
        button.pack()


    def run_script(self):
        
        sys.stdout = self
        tkMessageBox.showinfo('FYI', 'Analyzing...Please Wait')
        import final_spam
        final_spam
        self.que()
    def write(self, txt):
        self.text.insert(INSERT, txt)

    def que(self):
        conn=pymysql.connect(host="localhost",user="******",passwd="1234567890",db="poject")
        cursor = conn.cursor()
        rep=self.text.get('1.0', 'end')
        cursor.execute("SELECT @id := (SELECT caseid FROM poject.case ORDER BY caseid DESC LIMIT 1)")
        cursor.execute("UPDATE  poject.case set email_report=%s where caseid=@id", (rep))
        conn.commit()
        conn.close()
        return
예제 #6
0
class CopyableMessageWindow(basicWindow):
    """ Creates a modeless (non-modal) message window that allows the user to copy the presented text. """
    def __init__(self, topLevel, message, title, align, buttons, makeModal):
        self.guiRoot = topLevel

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

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

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

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

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

    # Button functions
    def copyText(self):
        self.guiRoot.clipboard_clear()
        self.guiRoot.clipboard_append(
            self.messageText.get('1.0', 'end').strip())
예제 #7
0
class CopyableMsg(basicWindow):
    """ Creates a modeless (non-modal) message window that allows the user to easily copy the given text. 
		If buttons are provided, they should be an iterable of tuples of the form (buttonText, buttonCallback). """
    def __init__(self,
                 root,
                 message='',
                 title='',
                 alignment='center',
                 buttons=None):
        super(CopyableMsg, self).__init__(root,
                                          title,
                                          resizable=True,
                                          topMost=False)
        self.root = root

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

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

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

    def copyToClipboard(self):
        self.root.clipboard_clear()
        self.root.clipboard_append(self.messageText.get('1.0', 'end'))
예제 #8
0
class Licensing( Frame ):
    BUTTON_TEXT = "Copy to clipboard"

    def __init__( self, master ):
        Frame.__init__( self, master )
        COMPOSITOR.register_view( self )
        self._setup_view()
        self.on_model_updated( COMPOSITOR.OTHER_UPDATED )

    def _setup_view( self ):
        self.rowconfigure( 0, weight = 1 )
        self.columnconfigure( 0, weight = 1 )

        self.license_box = ScrolledText( self, state = DISABLED )
        self.license_box.grid( row = 0, column = 0, sticky = W + E + N + S, padx = 5, pady = 5 )

        self.clipboard_button = Button( self, text = self.BUTTON_TEXT, command = self._on_copy_pressed )
        self.clipboard_button.grid( row = 1, column = 0, sticky = N + E )

    def _on_copy_pressed( self ):
        self.license_box.clipboard_clear()
        self.license_box.clipboard_append( self.license_box.get( '0.0', END ) )
        self.clipboard_button.configure( text = "Copied!", state = DISABLED )
        self.after( 2500, lambda: self.clipboard_button.configure( text = self.BUTTON_TEXT, state = NORMAL ) )

    def on_model_updated( self, reason ):
        if reason not in [COMPOSITOR.OTHER_UPDATED, COMPOSITOR.SELECTED_TYPE_CHANGED, COMPOSITOR.LAYER_ADDED, COMPOSITOR.LAYER_REMOVED, COMPOSITOR.SHEET_SELECTED, COMPOSITOR.LAYER_ORDER_CHANGED]:
            return

        # The compositor changed state, so make sure we're up to date, too.
        self.license_box.configure( state = NORMAL )

        # clear the existing text
        self.license_box.delete( 1.0, END )

        sheets = COMPOSITOR.get_selected_sheets().values()
        license_text = LICENSING.get_formatted_licensing( sheets )

        self.license_box.insert( END, license_text )
        self.license_box.configure( state = DISABLED )

    def destroy( self ):
        COMPOSITOR.deregister_view( self )
        Frame.destroy( self )
예제 #9
0
class PopupScrolledTextWindow(basicWindow):
    """ Creates a modal dialog window with only a multi-line text input box (with scrollbar), and a few buttons.
		Useful for displaying text that the user should be able to select/copy, or for input. """
    def __init__(self,
                 master,
                 message='',
                 defaultText='',
                 title='',
                 width=100,
                 height=8,
                 button1Text='Ok'):
        basicWindow.__init__(self, master, windowTitle=title)
        self.entryText = ''

        # Add the explanation text and text input field
        self.label = ttk.Label(self.window, text=message)
        self.label.pack(pady=5)
        self.entry = ScrolledText(self.window, width=width, height=height)
        self.entry.insert('end', defaultText)
        self.entry.pack(padx=5)

        # Add the confirm/cancel buttons
        buttonsFrame = ttk.Frame(self.window)
        self.okButton = ttk.Button(buttonsFrame,
                                   text=button1Text,
                                   command=self.cleanup)
        self.okButton.pack(side='left', padx=10)
        ttk.Button(buttonsFrame, text='Cancel',
                   command=self.cancel).pack(side='left', padx=10)
        buttonsFrame.pack(pady=5)

        # Move focus to this window (for keyboard control), and pause execution of the calling function until this window is closed.
        self.entry.focus_set()
        master.wait_window(
            self.window
        )  # Pauses execution of the calling function until this window is closed.

    def cleanup(self, event=''):
        self.entryText = self.entry.get('1.0', 'end').strip()
        self.window.destroy()

    def cancel(self, event=''):
        self.entryText = ''
        self.window.destroy()
예제 #10
0
class App(object):

    def __init__(self):
        self.root = tki.Tk()
        self.root.title("Loadshedding Schedule Parser")
        tki.Label(text='Copy Schedules from a table and paste it here:').pack()
        self.txt = ScrolledText(self.root, width="50" ,undo=True)
        self.txt['font'] = ('consolas', '12')
        self.txt.pack(expand=True, fill='both')


	def onok():

          dirname = tdog.askdirectory(parent=self.root,initialdir="/",title='Please select a directory')
          print dirname
          schFunc.parse(self.txt.get("1.0","end"),dirname)
          tbox.showinfo("Done","Schedules have been parsed and converted to INI files")


	tki.Button(self.root, text='Parse Schedules', command=onok).pack()
예제 #11
0
class App(object):
    def __init__(self):
        self.root = tki.Tk()
        self.root.title("Loadshedding Schedule Parser")
        tki.Label(text='Copy Schedules from a table and paste it here:').pack()
        self.txt = ScrolledText(self.root, width="50", undo=True)
        self.txt['font'] = ('consolas', '12')
        self.txt.pack(expand=True, fill='both')

        def onok():

            dirname = tdog.askdirectory(parent=self.root,
                                        initialdir="/",
                                        title='Please select a directory')
            print dirname
            schFunc.parse(self.txt.get("1.0", "end"), dirname)
            tbox.showinfo(
                "Done",
                "Schedules have been parsed and converted to INI files")

        tki.Button(self.root, text='Parse Schedules', command=onok).pack()
예제 #12
0
def run(event):
    """Run the script and shows the resulting HTML code in a
    new window
    If started with the "Make HTML" button, saves HTML output in
    a file"""
    pythonCode = pythonText.get(1.0, END)
    lines = pythonCode.split('\n')
    lines = map(lambda x: x[5:], lines)
    pythonCode = '\n'.join(lines)
    execWindow = Toplevel()
    execText = ScrolledText(execWindow,
                            width=40,
                            height=40,
                            bg="white",
                            font=FONT)
    execText.pack()
    s = sys.stdout
    sys.stdout = Output(execText)
    try:
        exec(pythonCode) in globals()
        if event.widget is bRunHTML:
            htmlFilename = os.path.splitext(pihText.filename)[0] + ".htm"
            if os.path.exists(htmlFilename):
                override=tkMessageBox.askyesno("Override ?",
                    "File %s already exists - Override ?" \
                    %os.path.basename(htmlFilename))
                if not override:
                    return
            f = open(htmlFilename, "w")
            f.write(execText.get(1.0, END))
            f.close()
            path = os.path.join(os.getcwd(), htmlFilename)
            webbrowser.open_new("file://" + path)
    except:
        traceback.print_exc(file=sys.stdout)
    sys.stdout = s
예제 #13
0
class ClustererGui(ttk.Frame):
    """GUI to open/save xml/text-files and visualize clustering."""
    def __init__(self, master=None):
        """Init GUI - get auto-split-sentences-option and standard test-file-folder from config-file."""
        ttk.Frame.__init__(self, master)
        self.grid(sticky=tk.N + tk.S + tk.E + tk.W)

        self.createWidgets()
        self.filepath = None
        self.xml_filepath = None
        self.filename = None
        self.article_id = None
        self.extraction = None
        self.author_no = None
        self.correct = None
        self.result = None
        self.colors = []

        config = ConfigParser.ConfigParser()
        config.read("config.cfg")
        params = dict(config.items("params"))
        article_dir = params['test_file_dir']
        self.auto_split_sentences = bool(int(params['auto_split_sentences']))
        self.show_knee_point = bool(int(params['show_knee_point']))
        self.show_knee_point = False  # currently not supported in GUI-mode
        self.last_dir = article_dir

    def createWidgets(self):
        """Organize GUI."""
        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

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

        left_frame = ttk.Frame(self, relief="raised", borderwidth=1)
        left_frame.grid(row=0, column=0, sticky=tk.N + tk.S + tk.E + tk.W)
        left_frame.rowconfigure(0, weight=0)
        left_frame.rowconfigure(1, weight=1)
        left_frame.columnconfigure(0, weight=1)

        buttons_topleft = ttk.Frame(left_frame)
        buttons_topleft.grid(row=0, column=0)

        self.choose_file_btn = ttk.Button(buttons_topleft,
                                          text='choose file...',
                                          command=self.choose_file)
        self.choose_file_btn.grid(row=0, column=0)

        self.save_file_btn = ttk.Button(buttons_topleft,
                                        text='save file...',
                                        command=self.save_file)
        self.save_file_btn.grid(row=0, column=1)

        self.extract_feat_btn = ttk.Button(
            buttons_topleft,
            text='process',
            command=self.start_featureextr_thread)
        self.extract_feat_btn.grid(row=0, column=2)

        right_frame = ttk.Frame(self)
        right_frame.grid(row=0, column=1, sticky=tk.N + tk.S + tk.E + tk.W)
        right_frame.rowconfigure(0, weight=1)
        right_frame.rowconfigure(1, weight=1)

        self.distr_entry = ScrolledText(right_frame, width=30, height=30)
        self.distr_entry.grid(row=0, column=0, columnspan=2, sticky=tk.N)

        self.test_entry = ScrolledText(right_frame, width=30)
        self.test_entry.grid(row=1, column=0, columnspan=2, sticky=tk.N)

        self.scrolledText = ScrolledText(left_frame, undo=True, wrap=tk.WORD)
        self.scrolledText['font'] = ('Helvetica', '12')
        self.scrolledText.tag_configure('lines',
                                        background="#dddddd",
                                        foreground="black",
                                        font=('Helvetica', 9))
        self.scrolledText.tag_configure('blanks',
                                        background="#ffffff",
                                        foreground="black",
                                        font=('Helvetica', 9))
        self.scrolledText.grid(row=1,
                               column=0,
                               sticky=tk.N + tk.S + tk.E + tk.W)

        status_bar = ttk.Frame(self)
        status_bar.grid(row=1, column=0, columnspan=2, sticky=tk.W)
        status_bar.columnconfigure(0, weight=1, minsize=100)
        status_bar.columnconfigure(1, weight=1)

        self.status = tk.StringVar()
        self.status.set("ready")
        self.status_label = ttk.Label(status_bar, textvariable=self.status)
        self.status_label.grid(row=0, column=1, padx=10)

        self.progressbar = ttk.Progressbar(status_bar,
                                           mode='indeterminate',
                                           length=200)
        self.progressbar.grid(row=0, column=0, padx=3)

    def choose_file(self):
        """Choose text or xml file dialog."""
        self.filepath = askopenfilename(initialdir=self.last_dir,
                                        filetypes=(("text and xml files",
                                                    ("*.txt", "*.xml")), ))
        if self.filepath:
            ext = os.path.splitext(self.filepath)[1]

            if ext == ".xml":
                '''save raw-text of xml-file to a new file and print it'''
                self.xml_filepath = self.filepath
                self.filepath = self.create_text_fromXML()

            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            self.scrolledText.delete(1.0, tk.END)
            self.print_raw_text()
            self.scrolledText.edit_reset()

    def create_text_fromXML(self):
        """Create text-file out of given xml-file."""
        new_filepath = os.path.splitext(self.filepath)[0] + ".txt"
        with codecs.open(self.filepath, 'r', 'UTF-8') as xml_file:
            xml_tree = etree.parse(xml_file)

        with codecs.open(new_filepath, 'w', 'UTF-8') as newFile:
            first_entry = True
            for entry in xml_tree.getroot():
                if entry.text is not None:
                    if not first_entry:
                        newFile.write("\n\n")
                    else:
                        first_entry = False
                    newFile.write(entry.text)
        return new_filepath

    def save_file(self):
        """Save text-file-dialog."""
        text = self.scrolledText.get("0.0", tk.END)
        if self.filepath is None:
            name = asksaveasfilename(initialdir=self.last_dir,
                                     defaultextension=".txt")
            if name:
                self.filepath = name
            else:
                return
        try:
            with codecs.open(self.filepath, 'w', 'UTF-8') as newFile:
                newFile.write(text.strip())
            self.scrolledText.edit_reset()
            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            return True
        except Exception:  # as e:
            raise

    def start_featureextr_thread(self):
        """Start thread for feature extraction."""
        self.distr_entry.delete(1.0, tk.END)
        self.status.set("processing...")
        if self.filepath is None or self.article_id is None:
            tkMessageBox.showwarning("Save File",
                                     "Save file for feature extraction.")
            return
        try:
            self.scrolledText.edit_undo()
            self.scrolledText.edit_redo()

            tkMessageBox.showwarning("File changed",
                                     "File was changed, please save.")
            return
        except tk.TclError:
            self.extraction = clusterer.Clusterer(self.article_id,
                                                  self.filepath,
                                                  self.xml_filepath,
                                                  self.auto_split_sentences,
                                                  self.show_knee_point)

            self.ftr_extr_thread = threading.Thread(
                target=self.extract_features)
            self.ftr_extr_thread.daemon = True
            self.progressbar.start()
            self.ftr_extr_thread.start()
            self.after(1000, self.check_feat_thread)

    def check_feat_thread(self):
        """Check if feature extraction thread is still working - if not: visualize cluster-results."""
        if self.ftr_extr_thread.is_alive():
            self.after(1000, self.check_feat_thread)
        else:
            self.status.set("ready")

            # generate author-colormap
            self.colors = [None] * len(set(self.clusters))
            for k in set(self.clusters):
                temp_color = plt.cm.spectral(
                    np.float(k) / (np.max(self.clusters) + 1))
                if k == 0:
                    temp_color = plt.cm.spectral(0.05)
                self.colors[k] = self.convert_to_hex(temp_color)
            self.configure_colors()

            self.progressbar.stop()
            self.print_author_distr()
            self.print_text()
            if self.correct is not None and self.author_no is not None:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                s += "\n\n true number of authors: {}".format(self.author_no)
                s += "\n precision: {:.4f}".format(self.scores[0])
                s += "\n recall: {:.4f}".format(self.scores[1])
                s += "\n f1-score: {:.4f}".format(self.scores[2])
                s += "\n adjusted-rand-index: {:.4f}".format(self.scores[3])
                self.test_entry.insert(tk.INSERT, s)
            else:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                self.test_entry.insert(tk.INSERT, s)

    def extract_features(self):
        """Start feature extraction."""
        self.clusters, self.result, self.author_no, self.believe_score, self.scores = self.extraction.calc_cluster(
        )

        if self.result is not None:
            c = Counter(self.result)
            self.correct = c[True] / sum(c.values()) * 100

    def print_text(self):
        """Print raw text with specified author-colors."""
        self.scrolledText.delete(1.0, tk.END)
        f = open(self.filepath)

        line_number = 0
        actual_line_number = 0
        for line in f:
            actual_line_number += 1
            if line.strip():
                s = str(line_number) + ' ' + str(
                    self.clusters[line_number]) + ' ' + line
                s = line
                line_cluster = str(line_number) + ' ' + str(
                    self.clusters[line_number]) + ' '
                line_cluster = ('{:^' + str(14 - len(line_cluster)) +
                                '}').format(line_cluster)
                self.scrolledText.insert(tk.INSERT, line_cluster, 'lines')
                try:
                    self.scrolledText.insert(tk.INSERT, s,
                                             str(self.clusters[line_number]))
                    # if self.result[line_number]:
                    #     # correct assignment - print text foreground in white
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                    # else:
                    #     # false assignment - print text foreground in black
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]*10**2))
                except IndexError:
                    self.scrolledText.insert(tk.INSERT, s)
                except TypeError:
                    self.scrolledText.insert(tk.INSERT, s,
                                             str(self.clusters[line_number]))
                line_number += 1
            else:
                s = line
                self.scrolledText.insert(tk.INSERT, s, 'blanks')
        f.close()

    def print_raw_text(self):
        """Print raw text."""
        f = open(self.filepath)
        for line in f:
            self.scrolledText.insert(tk.INSERT, line)
        f.close()

    def get_distribution(self, l=None):
        """Return Counter with author distribution in percent."""
        if l is None:
            l = self.clusters
        counter = Counter(l)
        sum_counter = sum(counter.values())

        for key in counter.iterkeys():
            counter[key] = counter[key] / sum_counter * 100
        return counter

    def print_author_distr(self):
        """Print author distribution with specified author-colors."""
        self.distr_entry.delete(1.0, tk.END)
        distr = self.get_distribution(self.clusters)

        for index, count in distr.most_common():
            author_i = "author " + str(index) + "{:>20}%\n".format(
                locale.format(u'%.2f', count))
            self.distr_entry.insert(tk.INSERT, author_i, str(index))

    def convert_to_hex(self, col):
        """Convert inter-tuple to hex-coded string."""
        red = int(col[0] * 255)
        green = int(col[1] * 255)
        blue = int(col[2] * 255)
        return '#{r:02x}{g:02x}{b:02x}'.format(r=red, g=green, b=blue)

    def configure_colors(self):
        """Configure author-specific colors for author-distribution and cluster-results."""
        for i, c in enumerate(self.colors):
            self.scrolledText.tag_configure(str(i),
                                            background=c,
                                            foreground="white")
            self.distr_entry.tag_configure(str(i),
                                           background=c,
                                           foreground="white")
예제 #14
0
파일: gui.py 프로젝트: privatehosting/SPLiT
class MainFrame:
    def __init__(self, root, options, main_logger):
        self.root = root
        self.options = options
        self.frame = tk.Frame(root)
        self.main_logger = main_logger
        self.sip_proxy = None
        self.tftp_server = None
        self.http_server = None

        # can enlarge
        self.frame.columnconfigure(0, weight=1)
        # first row: setting, cannot vertical enlarge:
        self.frame.rowconfigure(0, weight=0)
        # second row: registrar, can vertical enlarge:
        self.frame.rowconfigure(1, weight=1)

        # Settings control frame
        self.settings_frame = tk.LabelFrame(self.frame,
                                            text="Settings",
                                            padx=5,
                                            pady=5)
        self.settings_frame.grid(row=0, column=0, sticky=tk.N, padx=5, pady=5)

        # Registrar frame
        #self.registrar_frame = tk.Frame(self.frame)
        #self.registrar_frame.rowconfigure(0, weight=1)

        row = 0
        tk.Label(self.settings_frame,
                 text="General settings:",
                 font="-weight bold").grid(row=row, column=0, sticky=tk.W)
        row = row + 1

        self.gui_debug = tk.BooleanVar()
        self.gui_debug.set(self.options.debug)
        tk.Label(self.settings_frame, text="Debug:").grid(row=row,
                                                          column=0,
                                                          sticky=tk.W)
        tk.Checkbutton(self.settings_frame,
                       variable=self.gui_debug,
                       command=self.gui_debug_action).grid(row=row,
                                                           column=1,
                                                           sticky=tk.W)
        #row = row + 1

        self.gui_sip_ip_address = tk.StringVar()
        self.gui_sip_ip_address.set(self.options.ip_address)
        tk.Label(self.settings_frame, text="IP Address:").grid(row=row,
                                                               column=2,
                                                               sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_sip_ip_address,
                 width=15).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        tk.Label(self.settings_frame, text="TFTP Server:",
                 font="-weight bold").grid(row=row, column=0, sticky=tk.W)
        row = row + 1

        self.gui_tftp_port = tk.IntVar()
        self.gui_tftp_port.set(self.options.tftp_port)
        tk.Label(self.settings_frame, text="TFTP Port:").grid(row=row,
                                                              column=0,
                                                              sticky=tk.W)
        tk.Entry(self.settings_frame, textvariable=self.gui_tftp_port,
                 width=5).grid(row=row, column=1, sticky=tk.W)
        #row = row + 1

        self.gui_tftp_root = tk.StringVar()
        self.gui_tftp_root.set(self.options.tftp_root)
        tk.Label(self.settings_frame, text="TFTP Directory:").grid(row=row,
                                                                   column=2,
                                                                   sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_tftp_root,
                 width=15).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        tk.Label(self.settings_frame, text="HTTP Server:",
                 font="-weight bold").grid(row=row, column=0, sticky=tk.W)
        row = row + 1

        self.gui_http_port = tk.IntVar()
        self.gui_http_port.set(self.options.http_port)
        tk.Label(self.settings_frame, text="HTTP Port:").grid(row=row,
                                                              column=0,
                                                              sticky=tk.W)
        tk.Entry(self.settings_frame, textvariable=self.gui_http_port,
                 width=5).grid(row=row, column=1, sticky=tk.W)
        #row = row + 1

        self.gui_http_root = tk.StringVar()
        self.gui_http_root.set(self.options.http_root)
        tk.Label(self.settings_frame, text="HTTP Directory:").grid(row=row,
                                                                   column=2,
                                                                   sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_http_root,
                 width=15).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        tk.Label(self.settings_frame, text="DHCP Server:",
                 font="-weight bold").grid(row=row, column=0, sticky=tk.W)
        row = row + 1

        self.gui_dhcp_begin = tk.StringVar()
        self.gui_dhcp_begin.set(self.options.dhcp_begin)
        tk.Label(self.settings_frame,
                 text="DHCP Pool start:").grid(row=row, column=0, sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_dhcp_begin,
                 width=15).grid(row=row, column=1, sticky=tk.W)
        #row = row + 1

        self.gui_dhcp_end = tk.StringVar()
        self.gui_dhcp_end.set(self.options.dhcp_end)
        tk.Label(self.settings_frame, text="DHCP Pool end:").grid(row=row,
                                                                  column=2,
                                                                  sticky=tk.W)
        tk.Entry(self.settings_frame, textvariable=self.gui_dhcp_end,
                 width=15).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        self.gui_dhcp_subnetmask = tk.StringVar()
        self.gui_dhcp_subnetmask.set(self.options.dhcp_subnetmask)
        tk.Label(self.settings_frame,
                 text="DHCP Subnet mask:").grid(row=row, column=0, sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_dhcp_subnetmask,
                 width=15).grid(row=row, column=1, sticky=tk.W)
        #row = row + 1

        self.gui_dhcp_gateway = tk.StringVar()
        self.gui_dhcp_gateway.set(self.options.dhcp_gateway)
        tk.Label(self.settings_frame, text="DHCP Gateway:").grid(row=row,
                                                                 column=2,
                                                                 sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_dhcp_gateway,
                 width=15).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        self.gui_dhcp_bcast = tk.StringVar()
        self.gui_dhcp_bcast.set(self.options.dhcp_bcast)
        tk.Label(self.settings_frame, text="DHCP Broadcast:").grid(row=row,
                                                                   column=0,
                                                                   sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_dhcp_bcast,
                 width=15).grid(row=row, column=1, sticky=tk.W)
        #row = row + 1

        self.gui_dhcp_dns = tk.StringVar()
        self.gui_dhcp_dns.set(self.options.dhcp_dns)
        tk.Label(self.settings_frame, text="DHCP DNS:").grid(row=row,
                                                             column=2,
                                                             sticky=tk.W)
        tk.Entry(self.settings_frame, textvariable=self.gui_dhcp_dns,
                 width=15).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        self.gui_dhcp_fileserver = tk.StringVar()
        self.gui_dhcp_fileserver.set(self.options.dhcp_fileserver)
        tk.Label(self.settings_frame,
                 text="DHCP Fileserver (opt. 66):").grid(row=row,
                                                         column=0,
                                                         sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_dhcp_fileserver,
                 width=25).grid(row=row, column=1, sticky=tk.W)
        #row = row + 1

        self.gui_dhcp_filename = tk.StringVar()
        self.gui_dhcp_filename.set(self.options.dhcp_filename)
        tk.Label(self.settings_frame,
                 text="DHCP Filename (opt. 67):").grid(row=row,
                                                       column=2,
                                                       sticky=tk.W)
        tk.Entry(self.settings_frame,
                 textvariable=self.gui_dhcp_filename,
                 width=25).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        tk.Label(self.settings_frame,
                 text="SIP Plug&Play:",
                 font="-weight bold").grid(row=row, column=0, sticky=tk.W)
        row = row + 1

        self.gui_pnp_uri = tk.StringVar()
        self.gui_pnp_uri.set(self.options.pnp_uri)
        tk.Label(self.settings_frame, text="PnP URI:").grid(row=row,
                                                            column=0,
                                                            sticky=tk.W)
        tk.Entry(self.settings_frame, textvariable=self.gui_pnp_uri,
                 width=60).grid(row=row, column=1, columnspan=3, sticky=tk.W)
        row = row + 1

        tk.Label(self.settings_frame, text="SIP Proxy:",
                 font="-weight bold").grid(row=row, column=0, sticky=tk.W)
        row = row + 1

        self.gui_sip_redirect = tk.BooleanVar()
        self.gui_sip_redirect.set(self.options.sip_redirect)
        tk.Label(self.settings_frame,
                 text="SIP Redirect server:").grid(row=row,
                                                   column=0,
                                                   sticky=tk.W)
        tk.Checkbutton(self.settings_frame,
                       variable=self.gui_sip_redirect,
                       command=self.gui_sip_redirect_action).grid(row=row,
                                                                  column=1,
                                                                  sticky=tk.W)
        #row = row + 1

        self.gui_sip_port = tk.IntVar()
        self.gui_sip_port.set(self.options.sip_port)
        tk.Label(self.settings_frame, text="SIP Port:").grid(row=row,
                                                             column=2,
                                                             sticky=tk.W)
        tk.Entry(self.settings_frame, textvariable=self.gui_sip_port,
                 width=5).grid(row=row, column=3, sticky=tk.W)
        row = row + 1

        self.gui_sip_password = tk.StringVar()
        self.gui_sip_password.set(self.options.sip_password)
        tk.Label(self.settings_frame, text="Password:"******"Custom Headers:").grid(row=row,
                                                                   column=0,
                                                                   sticky=tk.W)
        self.gui_sip_custom_headers = ScrolledText(self.settings_frame,
                                                   height=10,
                                                   bg='beige')
        self.gui_sip_custom_headers.insert(
            0.0, '\n'.join(self.options.sip_custom_headers).rstrip())
        self.gui_sip_custom_headers.grid(row=row,
                                         column=1,
                                         columnspan=3,
                                         sticky=tk.W)
        row = row + 1

        self.sip_control_button = tk.Button(self.settings_frame,
                                            text="Start SIP Proxy",
                                            command=self.start_sip_proxy)
        self.sip_control_button.grid(row=row, column=0, sticky=tk.N)

        self.tftp_control_button = tk.Button(self.settings_frame,
                                             text="Start TFTP Server",
                                             command=self.start_tftp_server)
        self.tftp_control_button.grid(row=row, column=1, sticky=tk.N)

        self.http_control_button = tk.Button(self.settings_frame,
                                             text="Start HTTP Server",
                                             command=self.start_http_server)
        self.http_control_button.grid(row=row, column=2, sticky=tk.N)

        self.dhcp_control_button = tk.Button(self.settings_frame,
                                             text="Start DHCP Server",
                                             command=self.start_dhcp_server)
        self.dhcp_control_button.grid(row=row, column=3, sticky=tk.N)

        self.pnp_control_button = tk.Button(self.settings_frame,
                                            text="Start PnP Server",
                                            command=self.start_pnp_server)
        self.pnp_control_button.grid(row=row, column=4, sticky=tk.N)

        #self.registrar_button = tk.Button(self.settings_frame, text="Reload registered", command=self.load_registrar)
        #self.registrar_button.grid(row=row, column=4, sticky=tk.N)
        #row = row + 1

        #self.registrar_frame.grid(row=1, column=0, sticky=tk.NS)

        #self.registrar_text = ScrolledText(self.registrar_frame)
        #self.registrar_text.grid(row=0, column=0, sticky=tk.NS)
        #self.registrar_text.config(state='disabled')

        self.sip_queue = Queue.Queue()
        self.sip_trace_logger = utils.setup_logger(
            'sip_widget_logger',
            log_file=None,
            debug=True,
            str_format='%(asctime)s %(message)s',
            handler=SipTraceQueueLogger(queue=self.sip_queue))

        self.log_queue = Queue.Queue()
        utils.setup_logger('main_logger',
                           options.logfile,
                           self.options.debug,
                           handler=MessagesQueueLogger(queue=self.log_queue))

    def get_frame(self):
        return self.frame

    def get_sip_queue(self):
        return self.sip_queue

    def get_log_queue(self):
        return self.log_queue

    def load_registrar(self):
        self.registrar_text.config(state='normal')
        self.registrar_text.delete(0.0, tk.END)

        if self.sip_proxy == None:
            self.registrar_text.insert(tk.END, "Server not running\n")
            self.registrar_text.see(tk.END)
            self.registrar_text.config(state='disabled')
            return

        if len(self.sip_proxy.registrar) > 0:
            for regname in self.sip_proxy.registrar:
                self.registrar_text.insert(tk.END, "\n%s:\n" % regname)
                self.registrar_text.insert(
                    tk.END,
                    "\t Contact: %s\n" % self.sip_proxy.registrar[regname][0])
                self.registrar_text.insert(
                    tk.END, "\t IP: %s:%s\n" %
                    (self.sip_proxy.registrar[regname][2][0],
                     self.sip_proxy.registrar[regname][2][1]))
                self.registrar_text.insert(
                    tk.END, "\t Expires: %s\n" %
                    time.ctime(self.sip_proxy.registrar[regname][3]))
        else:
            self.registrar_text.insert(tk.END,
                                       "No User Agent registered yet\n")

        self.registrar_text.see(tk.END)
        self.registrar_text.config(state='disabled')

    def start_sip_proxy(self):
        self.main_logger.debug("SIP Proxy: Starting thread")
        self.options.ip_address = self.gui_sip_ip_address.get()
        self.options.sip_port = self.gui_sip_port.get()
        self.options.sip_password = self.gui_sip_password.get()
        self.options.sip_redirect = self.gui_sip_redirect.get()
        self.options.sip_custom_headers = self.gui_sip_custom_headers.get(
            0.0, tk.END).splitlines()

        self.main_logger.debug("Writing SIP messages in %s log file" %
                               self.options.sip_logfile)
        self.main_logger.debug("Authentication password: %s" %
                               self.options.sip_password)
        self.main_logger.debug("Logfile: %s" % self.options.logfile)

        try:
            self.sip_proxy = proxy.SipTracedUDPServer(
                (self.options.ip_address, self.options.sip_port),
                proxy.UDPHandler, self.sip_trace_logger, self.main_logger,
                self.options)
            self.sip_server_thread = threading.Thread(
                name='sip', target=self.sip_proxy.serve_forever)
            self.sip_server_thread.daemon = True
            self.sip_server_thread.start()
            self.sip_control_button.configure(text="Stop SIP Proxy",
                                              command=self.stop_sip_proxy)
        except Exception, e:
            self.main_logger.error("Cannot start the server: %s" % e)
            raise e

        self.main_logger.debug("Using the top Via header: %s" %
                               self.sip_proxy.topvia)

        if self.options.sip_redirect:
            self.main_logger.debug("Working in redirect server mode")
        else:
            self.main_logger.debug("Using the Record-Route header: %s" %
                                   self.sip_proxy.recordroute)
예제 #15
0
class GrammarGUI:
    def __init__(self, grammar, text, title='Input Grammar'):
        self.root = None
        try:
            self._root = Tkinter.Tk()
            self._root.title(title)

            level1 = Tkinter.Frame(self._root)
            level1.pack(side='top', fill='none')
            Tkinter.Frame(self._root).pack(side='top', fill='none')
            level2 = Tkinter.Frame(self._root)
            level2.pack(side='top', fill='x')            
            buttons = Tkinter.Frame(self._root)
            buttons.pack(side='top', fill='none')

            self.sentence = Tkinter.StringVar()            
            Tkinter.Label(level2, text="Sentence:").pack(side='left')
            Tkinter.Entry(level2, background='white', foreground='black',
                          width=60, textvariable=self.sentence).pack(
                side='left')

            lexiconFrame = Tkinter.Frame(level1)
            Tkinter.Label(lexiconFrame, text="Lexicon:").pack(side='top',
                                                              fill='x')
            Tkinter.Label(lexiconFrame, text="  ex. 'dog N':").pack(
                side='top', fill='x')
            self.lexicon = ScrolledText(lexiconFrame, background='white',
                                              foreground='black', width=30)
            self.lexicon.pack(side='top')


            grammarFrame = Tkinter.Frame(level1)
            Tkinter.Label(grammarFrame, text="Grammar:").pack(side='top',
                                                              fill='x')
            Tkinter.Label(grammarFrame,
                          text="  ex. 'S -> NP VP':").pack(side='top',fill='x')
            self.grammarRules = ScrolledText(grammarFrame, background='white',
                                              foreground='black', width=30)
            self.grammarRules.pack(side='top')
            
            lexiconFrame.pack(side='left')
            grammarFrame.pack(side='left')


            Tkinter.Button(buttons, text='Clear',
                           background='#a0c0c0', foreground='black',
                           command=self.clear).pack(side='left')
            Tkinter.Button(buttons, text='Parse',
                           background='#a0c0c0', foreground='black',
                           command=self.parse).pack(side='left')

            self.init_menubar()
            
            # Enter mainloop.
            Tkinter.mainloop()
        except:
            print 'Error creating Tree View'
            self.destroy()
            raise

    def init_menubar(self):
        menubar = Tkinter.Menu(self._root)
        
        filemenu = Tkinter.Menu(menubar, tearoff=0)
        filemenu.add_command(label='Save Rules', underline=0,
                             command=self.save, accelerator='Ctrl-s')
        self._root.bind('<Control-s>', self.save)
        filemenu.add_command(label='Load Rules', underline=0,
                             command=self.load, accelerator='Ctrl-o')
        self._root.bind('<Control-o>', self.load)
        filemenu.add_command(label='Clear Rules', underline=0,
                             command=self.clear, accelerator='Ctrl-r')
        self._root.bind('<Control-r>', self.clear)
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='Ctrl-q')
        self._root.bind('<Control-q>', self.destroy)
        menubar.add_cascade(label='File', underline=0,
                            menu=filemenu)
        self._root.config(menu=menubar)

    def getRules(self, makegrammar=True):
        """
        Takes the currently typed in rules and turns them from text into
        a list of either string rules or Earley CFGs
        """
        text = self.grammarRules.get(1.0, Tkinter.END)
        rules = []
        for item in text.split("\n"):
            moreitems = item.split(",")
            for furtheritem in moreitems:
                furtheritem = furtheritem.strip()
                if not furtheritem:
                    continue
                tokens = furtheritem.split()
                if not (len(tokens)>=3 and tokens[1] == "->"):
                    print "Invalid rule: %s"%furtheritem
                else:
                    if makegrammar:
                        rules.append(Rule(cfg.Nonterminal(tokens[0]),
                                          *map(lambda x: cfg.Nonterminal(x),
                                               tokens[2:])))
                    else:
                        rules.append(furtheritem.strip())
        return rules

    def getLexicon(self, makegrammar=True):
        """
        Takes the currently typed in lexicon and turns them from text into
        a list of either string lexical definitions or Earley CFGs
        """
        text = self.lexicon.get(1.0, Tkinter.END)
        lex = []
        for item in text.split("\n"):
            moreitems = item.split(",")
            for furtheritem in moreitems:
                furtheritem = furtheritem.strip()
                if not furtheritem:
                    continue
                tokens = furtheritem.split()
                if not len(tokens)>=2:
                    print "Invalid lexical mapping: %s"%furtheritem
                else:
                    if makegrammar:
                        word = tokens[0]
                        for pos in tokens[1:]:
                            lex.append(Rule(cfg.Nonterminal(pos), word))
                    else:
                        lex.append(furtheritem.strip())
        return lex

    def parse(self, *args):
        """
        Calls the FullChartViewer with the given grammar and lexicon to parse
        the given sentence
        """
        grammar = EarleyCFG(cfg.Nonterminal('S'),
                            self.getRules(), self.getLexicon())

        sent = self.sentence.get().strip()
        tok_sent = WSTokenizer().tokenize(sent)
        print "Starting chart parsing viewer"
        FullChartViewer(grammar, tok_sent, 'Parsing "%s"'%sent)

    def save(self, *args):
        "Save a rule/lexicon set to a text file"
        from tkFileDialog import asksaveasfilename
        ftypes = [('Text file', '.txt'),
                  ('All files', '*')]
        filename = asksaveasfilename(filetypes=ftypes,
                                     defaultextension='.txt')
        if not filename: return
        f = open(filename, 'w')
        f.write('---- Rules -----\n%s\n' % '\n'.join(self.getRules(False)))
        f.write('---- Lexicon -----\n%s\n' % '\n'.join(self.getLexicon(False)))
        f.close()
        
    def load(self, *args):
        "Load rule/lexicon set from a text file"
        from tkFileDialog import askopenfilename
        ftypes = [('Text file', '.txt'),
                  ('All files', '*')]
        filename = askopenfilename(filetypes=ftypes,
                                   defaultextension='.txt')
        if not filename: return
        f = open(filename, 'r')
        lines = f.readlines()
        f.close()

        rules = []
        lexicon = []
        state = 'rules'
        for line in lines:
            line = line.strip()
            if not line:
                continue
            elif line.startswith("-"):
                if line.find("Rules")>0: state = 'rules'
                else: state = 'lexicon'
            else:
                toks = line.split()
                if state == 'rules' and len(toks)>=3 and toks[1]=='->':
                    rules.append(line)
                elif state == 'lexicon' and len(toks)>=2:
                    lexicon.append(line)
                    
        self.clear()
        self.grammarRules.insert(1.0, '\n'.join(rules))
        self.lexicon.insert(1.0, '\n'.join(lexicon))

    def clear(self, *args):
        "Clears the grammar and lexical and sentence inputs"
        self.grammarRules.delete(1.0, Tkinter.END)
        self.lexicon.delete(1.0, Tkinter.END)
        self.sentence.set('')

    def destroy(self, *args):
        if self._root is None: return
        self._root.destroy()
        self._root = None
        print self.sentence.get()
예제 #16
0
    SECOND_MENU = Menu(MENU_BAR, tearoff=0)
    SECOND_MENU.add_command(label='Info', command=lambda: info_gui())
    MENU_BAR.add_cascade(label='Help', menu=SECOND_MENU)
    #Text Display
    MESSAGE_DISPLAY = ScrolledText(ROOT, width=37, height=15, font=('Arial', 13),
                                   fg='black', bg='white')
    MESSAGE_DISPLAY.pack(expand=1, padx=5, pady=5, side=TOP)

    FRAME_ONE = Frame(ROOT)
    #Text Input
    MESSAGE_INPUT = ScrolledText(FRAME_ONE, width=25, height=5, font=('Arial', 13),
                                 fg='black', bg='white')
    MESSAGE_INPUT.pack(expand=1, padx=5, pady=5, side=RIGHT)
    #Send Button
    FRAME_ONE_LEFT = Frame(FRAME_ONE)
    SEND_BUTTON = Button(FRAME_ONE_LEFT, text='SEND', width=10,
                         height=2, font=('Arial', 13, "bold"),
                         fg='white', bg='DarkOrange',
                         command=lambda: send(MESSAGE_INPUT.get("0.0", "end")))
    SEND_BUTTON.pack(side=TOP)
    #Refresh Button
    REFRESH_BUTTON = Button(FRAME_ONE_LEFT, text='REFRESH',
                            width=10, height=2, font=('Arial', 13, "bold"),
                            fg='white', bg='DarkOrange', command=lambda: recieve())
    REFRESH_BUTTON.pack(side=BOTTOM)
    FRAME_ONE_LEFT.pack(side=LEFT)
    FRAME_ONE.pack(side=BOTTOM)

    ROOT.config(menu=MENU_BAR)
    ROOT.mainloop()
class ClustererGui(ttk.Frame):
    """GUI to open/save xml/text-files and visualize clustering."""

    def __init__(self, master=None):
        """Init GUI - get auto-split-sentences-option and standard test-file-folder from config-file."""
        ttk.Frame.__init__(self, master)
        self.grid(sticky=tk.N+tk.S+tk.E+tk.W)

        self.createWidgets()
        self.filepath = None
        self.xml_filepath = None
        self.filename = None
        self.article_id = None
        self.extraction = None
        self.author_no = None
        self.correct = None
        self.result = None
        self.colors = []

        config = ConfigParser.ConfigParser()
        config.read("config.cfg")
        params = dict(config.items("params"))
        article_dir = params['test_file_dir']
        self.auto_split_sentences = bool(int(params['auto_split_sentences']))
        self.show_knee_point = bool(int(params['show_knee_point']))
        self.show_knee_point = False # currently not supported in GUI-mode
        self.last_dir = article_dir


    def createWidgets(self):
        """Organize GUI."""
        top=self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

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

        left_frame = ttk.Frame(self, relief="raised", borderwidth=1)
        left_frame.grid(row=0, column=0, sticky=tk.N+tk.S+tk.E+tk.W)
        left_frame.rowconfigure(0, weight=0)
        left_frame.rowconfigure(1, weight=1)
        left_frame.columnconfigure(0, weight=1)
        
        buttons_topleft = ttk.Frame(left_frame)
        buttons_topleft.grid(row=0, column=0)

        self.choose_file_btn = ttk.Button(buttons_topleft, text='choose file...',
            command=self.choose_file)
        self.choose_file_btn.grid(row=0, column=0)

        self.save_file_btn = ttk.Button(buttons_topleft, text='save file...',
            command=self.save_file)
        self.save_file_btn.grid(row=0, column=1)
        
        self.extract_feat_btn = ttk.Button(buttons_topleft, text='process',
            command=self.start_featureextr_thread)
        self.extract_feat_btn.grid(row=0, column=2)

        right_frame = ttk.Frame(self)
        right_frame.grid(row=0, column=1, sticky=tk.N+tk.S+tk.E+tk.W)
        right_frame.rowconfigure(0, weight=1)
        right_frame.rowconfigure(1, weight=1)
        
        self.distr_entry = ScrolledText(right_frame, width=30, height=30)
        self.distr_entry.grid(row=0, column=0, columnspan=2, sticky=tk.N)

        self.test_entry = ScrolledText(right_frame, width=30)
        self.test_entry.grid(row=1, column=0, columnspan=2, sticky=tk.N)

        self.scrolledText = ScrolledText(left_frame, undo=True, wrap=tk.WORD)
        self.scrolledText['font'] = ('Helvetica', '12')
        self.scrolledText.tag_configure('lines', background="#dddddd", foreground="black", font=('Helvetica', 9))
        self.scrolledText.tag_configure('blanks', background="#ffffff", foreground="black", font=('Helvetica', 9))        
        self.scrolledText.grid(row=1, column=0, sticky=tk.N+tk.S+tk.E+tk.W)

        status_bar = ttk.Frame(self)
        status_bar.grid(row=1, column=0, columnspan=2, sticky=tk.W)
        status_bar.columnconfigure(0, weight=1, minsize=100)
        status_bar.columnconfigure(1, weight=1)

        self.status = tk.StringVar()
        self.status.set("ready")
        self.status_label = ttk.Label(status_bar, textvariable=self.status)
        self.status_label.grid(row=0, column=1, padx=10)

        self.progressbar = ttk.Progressbar(status_bar, mode='indeterminate', length=200)
        self.progressbar.grid(row=0, column=0, padx=3)
    
    def choose_file(self):
        """Choose text or xml file dialog."""
        self.filepath = askopenfilename(initialdir=self.last_dir, filetypes=(("text and xml files", ("*.txt","*.xml")),))
        if self.filepath:
            ext = os.path.splitext(self.filepath)[1]

            if ext == ".xml":
                '''save raw-text of xml-file to a new file and print it'''
                self.xml_filepath = self.filepath
                self.filepath = self.create_text_fromXML()

            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            self.scrolledText.delete(1.0, tk.END)
            self.print_raw_text()
            self.scrolledText.edit_reset()

    def create_text_fromXML(self):
        """Create text-file out of given xml-file."""
        new_filepath = os.path.splitext(self.filepath)[0] + ".txt"
        with codecs.open(self.filepath, 'r', 'UTF-8') as xml_file:
            xml_tree = etree.parse(xml_file)
        
        with codecs.open(new_filepath, 'w', 'UTF-8') as newFile:
            first_entry = True
            for entry in xml_tree.getroot():
                if entry.text is not None:
                    if not first_entry:
                        newFile.write("\n\n")
                    else:
                        first_entry = False
                    newFile.write(entry.text)
        return new_filepath



    def save_file(self):
        """Save text-file-dialog."""
        text = self.scrolledText.get("0.0", tk.END)
        if self.filepath is None:
            name = asksaveasfilename(initialdir=self.last_dir, defaultextension=".txt")
            if name:
                self.filepath = name
            else:
                return
        try:
            with codecs.open(self.filepath, 'w', 'UTF-8') as newFile:
                newFile.write(text.strip())
            self.scrolledText.edit_reset()
            base = os.path.split(self.filepath)[0]
            self.article_id = os.path.split(base)[1]
            self.filename = os.path.split(self.filepath)[1]
            return True
        except Exception:# as e:
            raise


    def start_featureextr_thread(self):
        """Start thread for feature extraction."""
        self.distr_entry.delete(1.0, tk.END)
        self.status.set("processing...")
        if self.filepath is None or self.article_id is None:
            tkMessageBox.showwarning(
                "Save File",
                "Save file for feature extraction.")
            return
        try:
            self.scrolledText.edit_undo()
            self.scrolledText.edit_redo()

            tkMessageBox.showwarning(
                "File changed",
                "File was changed, please save.")
            return
        except tk.TclError:
            self.extraction = clusterer.Clusterer(self.article_id, self.filepath, self.xml_filepath, self.auto_split_sentences, self.show_knee_point)

            self.ftr_extr_thread = threading.Thread(target=self.extract_features)
            self.ftr_extr_thread.daemon = True
            self.progressbar.start()
            self.ftr_extr_thread.start()
            self.after(1000, self.check_feat_thread)

    def check_feat_thread(self):
        """Check if feature extraction thread is still working - if not: visualize cluster-results."""
        if self.ftr_extr_thread.is_alive():
            self.after(1000, self.check_feat_thread)
        else:
            self.status.set("ready")

            # generate author-colormap
            self.colors = [None]*len(set(self.clusters))
            for k in set(self.clusters):  
                temp_color = plt.cm.spectral(np.float(k) / (np.max(self.clusters) + 1))
                if k == 0:
                    temp_color = plt.cm.spectral(0.05)
                self.colors[k] = self.convert_to_hex(temp_color)
            self.configure_colors()

            self.progressbar.stop()
            self.print_author_distr()
            self.print_text()
            if self.correct is not None and self.author_no is not None:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                s += "\n\n true number of authors: {}".format(self.author_no)
                s += "\n precision: {:.4f}".format(self.scores[0])
                s += "\n recall: {:.4f}".format(self.scores[1])
                s += "\n f1-score: {:.4f}".format(self.scores[2])
                s += "\n adjusted-rand-index: {:.4f}".format(self.scores[3])
                self.test_entry.insert(tk.INSERT, s)
            else:
                self.test_entry.delete(1.0, tk.END)
                s = "authors found: {}".format(len(set(self.clusters)))
                s += "\n believe-score: {:.4f}".format(self.believe_score)
                self.test_entry.insert(tk.INSERT, s)

    def extract_features(self):
        """Start feature extraction."""
        self.clusters, self.result, self.author_no, self.believe_score, self.scores = self.extraction.calc_cluster()

        if self.result is not None:
            c = Counter(self.result)
            self.correct = c[True] / sum(c.values()) * 100

    def print_text(self):
        """Print raw text with specified author-colors."""
        self.scrolledText.delete(1.0, tk.END)
        f = open(self.filepath)

        line_number = 0
        actual_line_number = 0
        for line in f:
            actual_line_number += 1
            if line.strip():
                s = str(line_number) + ' '+str(self.clusters[line_number]) + ' '+line
                s = line
                line_cluster = str(line_number) + ' '+str(self.clusters[line_number])+ ' '
                line_cluster = ('{:^'+str(14-len(line_cluster))+'}').format(line_cluster)
                self.scrolledText.insert(tk.INSERT, line_cluster, 'lines')
                try:
                    self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                    # if self.result[line_number]:
                    #     # correct assignment - print text foreground in white
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                    # else:
                    #     # false assignment - print text foreground in black
                    #     self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]*10**2))
                except IndexError:
                    self.scrolledText.insert(tk.INSERT, s)
                except TypeError:
                        self.scrolledText.insert(tk.INSERT, s, str(self.clusters[line_number]))
                line_number += 1
            else:
                s = line
                self.scrolledText.insert(tk.INSERT, s, 'blanks')
        f.close()

    def print_raw_text(self):
        """Print raw text."""
        f = open(self.filepath)
        for line in f:
            self.scrolledText.insert(tk.INSERT, line)
        f.close()

    def get_distribution(self, l=None):
        """Return Counter with author distribution in percent."""
        if l is None:
            l = self.clusters
        counter = Counter(l)
        sum_counter = sum(counter.values())

        for key in counter.iterkeys():
            counter[key] = counter[key] / sum_counter * 100
        return counter

    def print_author_distr(self):
        """Print author distribution with specified author-colors."""
        self.distr_entry.delete(1.0, tk.END)
        distr = self.get_distribution(self.clusters)

        for index, count in distr.most_common():
            author_i = "author "+str(index)+"{:>20}%\n".format(locale.format(u'%.2f',count))
            self.distr_entry.insert(tk.INSERT, author_i, str(index))

    def convert_to_hex(self, col):
        """Convert inter-tuple to hex-coded string."""
        red = int(col[0]*255)
        green = int(col[1]*255)
        blue = int(col[2]*255)
        return '#{r:02x}{g:02x}{b:02x}'.format(r=red,g=green,b=blue)

    def configure_colors(self):
        """Configure author-specific colors for author-distribution and cluster-results."""
        for i,c in enumerate(self.colors):
            self.scrolledText.tag_configure(str(i), background=c, foreground="white")            
            self.distr_entry.tag_configure(str(i), background=c, foreground="white")
예제 #18
0
class DesDesk():
    def __init__(self):
        window = Tk()
        window.title("des加密与解密")
        window.geometry('700x500+300+150')
        # window['background'] = 'MintCream'
        # window['background'] = 'Moccasin'
        # window['background'] = 'Honeydew'
        # img_gif = PhotoImage(file='timg.gif')
        # image = Image.open(r'timg.gif')
        # background_image = ImageTk.PhotoImage(image)
        # background_image = ImageTk.PhotoImage(image)
        # window['background'] = background_image
        # window['background'] = img_gif
        window['background'] = "LightCyan"

        # window.iconbitmap("des.jpeg")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        window.mainloop()

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

                text_not_null = False

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.input_text.delete("1.0", END)
        self.input_text.insert(END, decoded_text)
예제 #19
0
class ViewportCard(object):
    '''
    Manages the graphical representation of a card in a
    Tkinter canvas. Creates and destroys items as necessary, facilitates
    editing, and so on and so forth.

    Members:
    * card: model.Card
    * viewport: GPViewport
    * gpfile: gpfile.GraphPaperFile, contains model.graph()
    * canvas: TKinter canvas we get drawn on
    * editing: bool, text is being edited
    * moving: bool, being dragged
    * moving_edgescroll_id: callback id to scroll periodically when hovering
      near edge of screen
    * resize_state: {}
    * resize_edgescroll_id: as moving_edgescroll_id
    * slot: calls callbacks whenever geometry changes
    * new_edge: if an edge is being dragged out from a handle, this is it.
    * card_after_new_edge: bool, if we should make a new card when edge is dropped.
    '''
    def __init__(self, viewport, gpfile, card):
        self.card = card
        self.viewport = viewport
        self.gpfile = gpfile
        self.canvas = viewport.canvas
        self.draw()
        self.editing = False
        self.moving = False
        self.moving_edgescroll_id = None
        self.resize_state = None
        self.resize_edgescroll_id = None
        # slot triggered when geometry (pos/size) changes
        # fn args: (self, x, y, w, h)
        self.geom_slot = Slot()
        self.deletion_slot = Slot()
        self.new_edge = None

    def draw(self):
        self.frame_thickness = 5
        self.window = ResizableCanvasFrame(self.canvas,
                                           self.card.x,
                                           self.card.y,
                                           self.card.w,
                                           self.card.h,
                                           min_width=MIN_CARD_SIZE,
                                           min_height=MIN_CARD_SIZE)
        self.text = ScrolledText(self.window, wrap=WORD)
        self.text.pack(expand=1, fill='both')
        # set up text for editing, dragging, deleting
        self.text.bind("<Button-1>", self.mousedown)
        self.text.bind("<Shift-Button-1>", self.shiftmousedown)
        self.text.bind("<Double-Button-1>", self.doubleclick)
        self.text.bind("<B1-Motion>", self.mousemove)
        self.text.bind("<ButtonRelease-1>", self.mouseup)
        self.text.bind("<FocusIn>", self.focusin)
        self.text.bind("<FocusOut>", self.focusout)
        self.text.bind("<Control-Delete>", self.ctrldelete)
        self.text.insert(END, self.card.text)
        # set up frame for resizing
        self.window.bind('<Configure>', self.configure)
        self.window.save_callback = self.save_card
        # draw edge handles
        self.edge_handles = None
        #self.redraw_edge_handles()

    def redraw_edge_handles(self):
        '''
        Either creates or modifies the edge handles, little circles poking
        out the side of the card, based on the current position and width.

        self.edge_handles is a list of itemids of the circles in (top,
        right, bottom, left) order.
        '''
        def create_circle(bbox):
            # create circle suitable for edge-handle use
            new = self.canvas.create_oval(bbox[0],
                                          bbox[1],
                                          bbox[2],
                                          bbox[3],
                                          fill='green',
                                          outline='')
            self.canvas.addtag_withtag('card_handle_tag',
                                       new)  # for z-ordering
            self.canvas.tag_bind(new, '<Button-1>', self.handle_click)
            self.canvas.tag_bind(new, '<Shift-Button-1>',
                                 self.handle_shift_click)
            self.canvas.tag_bind(new, '<B1-Motion>', self.handle_mousemove)
            self.canvas.tag_bind(new, '<ButtonRelease-1>', self.handle_mouseup)
            return new

        x, y = self.window.canvas_coords()
        w, h = self.window.winfo_width(), self.window.winfo_height()
        # 2*radius should be < MIN_CARD_SIZE, and offset < radius
        radius = 30
        offset = 19  # offset of center of circle from card edge
        left_coords = (x + offset, y + h / 2)
        right_coords = (x + w - offset, y + h / 2)
        top_coords = (x + w / 2, y + offset)
        bottom_coords = (x + w / 2, y + h - offset)
        all_coords = (top_coords, right_coords, bottom_coords, left_coords)
        bboxes = [(x - radius, y - radius, x + radius, y + radius)
                  for x, y in all_coords]
        if self.edge_handles:
            # move the edge handles
            for i, box in enumerate(bboxes):
                #self.canvas.coords(handle, box[0], box[1], box[2], box[3])
                self.canvas.delete(self.edge_handles[i])
                self.edge_handles[i] = create_circle(box)
                #self.canvas.itemconfig(handle, bbox = box)
        else:
            # create new ones
            self.edge_handles = [create_circle(b) for b in bboxes]
        # have to do this every time, every time we recreate the edge handles
        self.viewport.fix_z_order()

    def get_text(self):
        "gets the text from the actual editor, which may not be saved yet"
        return self.text.get('0.0', END)

    def save_text(self):
        # get text from window
        text = self.get_text()
        if text != self.card.text:
            self.card.text = text
            self.gpfile.commit()

    def canvas_coords(self):
        return self.window.canvas_coords()

    def start_moving(self, event):
        # set up state for a drag
        self.moving = True
        self.foocoords = (event.x, event.y)
        self.set_moving_edgescroll_callback()

    def edge_scroll(self):
        # if any edges are too close to the edge, move and scroll the canvas
        canvas_coords = self.canvas_coords()
        relative_mouse_pos = self.foocoords
        canvas_mouse_coords = (canvas_coords[0] + relative_mouse_pos[0] +
                               self.frame_thickness, canvas_coords[1] +
                               relative_mouse_pos[1] + self.frame_thickness)
        scroll_x, scroll_y = self.viewport.edge_scroll(canvas_mouse_coords)
        # move the opposite direction the viewport scrolled
        scroll_x, scroll_y = -scroll_x, -scroll_y
        #print 'card.edgescroll x y', scroll_x, scroll_y, 'relative_mouse_pos', relative_mouse_pos
        self.window.move(scroll_x, scroll_y)
        self.viewport.reset_scroll_region()
        self.set_moving_edgescroll_callback()

    def set_moving_edgescroll_callback(self):
        self.moving_edgescroll_id = self.text.after(10, self.edge_scroll)

    def cancel_moving_edgescroll_callback(self):
        self.text.after_cancel(self.moving_edgescroll_id)
        self.moving_edgescroll_id = None

    def mousedown(self, event):
        self.window.lift()

    def doubleclick(self, event):
        self.start_moving(event)
        return 'break'

    def shiftmousedown(self, event):
        self.mousedown(event)
        self.start_moving(event)
        return "break"

    def mousemove(self, event):
        if self.moving:
            # coords are relative to card, not canvas
            if self.foocoords:
                delta = (event.x - self.foocoords[0],
                         event.y - self.foocoords[1])
            else:
                delta = (event.x, event.y)
            self.window.move(delta[0], delta[1])
            self.geometry_callback()
            self.viewport.reset_scroll_region()
            return "break"

    def mouseup(self, event):
        if self.moving:
            self.moving = False
            new_coords = self.canvas_coords()
            self.card.x, self.card.y = new_coords[0], new_coords[1]
            self.gpfile.commit()
            self.cancel_moving_edgescroll_callback()
            self.geometry_callback()

    # next several functions are bound to the circular edge handles
    def handle_click(self, event):
        # create new edge
        self.new_edge = ViewportEdge(self.viewport, self.gpfile, None, self,
                                     None)
        self.new_edge.mousemove(event)  # give it a real start pos

    def handle_shift_click(self, event):
        self.handle_click(event)
        self.new_edge.make_new_card = True

    def handle_mousemove(self, event):
        if self.new_edge:
            self.new_edge.mousemove(event)

    def handle_mouseup(self, event):
        if self.new_edge:
            self.new_edge.mouseup(event)
            self.new_edge = None

    def configure(self, event):
        self.redraw_edge_handles()

    def focusin(self, event):
        self.editing = True

    def focusout(self, event):
        self.editing = False
        self.save_text()

    def ctrldelete(self, event):
        title_sample = self.get_text().split('\n', 1)[0]
        if len(title_sample) > 20:
            title_sample = title_sample[:20] + '...'
        # delete the card
        if tkMessageBox.askokcancel(
                "Delete?",
                "Delete card \"%s\" and all its edges?" % title_sample):
            for handle in self.edge_handles:
                self.canvas.delete(handle)
            self.deletion_slot.signal()
            self.viewport.remove_card(self)
            self.card.delete()
            self.window.destroy()
            self.gpfile.commit()
        return "break"

    def save_card(self):
        # grab values from self.window,
        # and put them in the model.card
        self.card.x, self.card.y = self.window.canvas_coords()
        self.card.w, self.card.h = self.window.winfo_width(
        ), self.window.winfo_height()
        self.geometry_callback()  # here so it gets called after resizing
        self.gpfile.commit()

    def add_geom_signal(self, fn):
        return self.geom_slot.add(fn)

    def remove_geom_signal(self, handle):
        self.geom_slot.remove(handle)

    def add_deletion_signal(self, fn):
        return self.deletion_slot.add(fn)

    def remove_deletion_signal(self, handle):
        self.deletion_slot.remove(handle)

    def geometry_callback(self):
        x, y = self.canvas_coords()
        w, h = self.window.winfo_width(), self.window.winfo_height()
        self.geom_slot.signal(self, x, y, w, h)

    def highlight(self):
        self.text.config(background='#ffffa2')

    def unhighlight(self):
        self.text.config(background='white')
예제 #20
0
class MainWindows(tkinter.Frame):
    def __init__(self, master):
        frame = tkinter.Frame(master,width=500,height=220)
        frame.grid(row=0, column=0)
        frame.pack()
        #self.repWin = repWin

        self.labelFile = tkinter.Label(frame,
                                       text='文件',
                                       font=('黑体'),
                                       justify='left',
                                       )
        self.labelFile.place(x=35, y=30)

        self.fileVar = tkinter.Variable()
        self.fileEntry = tkinter.Entry(frame,textvariable=self.fileVar, width=45)
        #self.fileEntry.delete(0, 'end')
        self.fileEntry.place(x=90,y=30)
        
        self.buttonOpenFile = tkinter.Button(frame, text='打开', width=5, height=1, command=self.openFile)
        self.buttonOpenFile.place(x=430, y=30) 
        
        self.labelPic = tkinter.Label(frame,
                                       text='图片',
                                       font=('黑体'),
                                       justify='left',
                                       )
        self.labelPic.place(x=35, y=90)
        
        self.picVar = tkinter.Variable()
        self.picEntry = tkinter.Entry(frame,textvariable=self.picVar, width=45)
        self.picEntry.place(x=90,y=90)
        
        self.buttonOpenPic = tkinter.Button(frame, text='打开', width=5, height=1, command=self.openPic)
        self.buttonOpenPic.place(x=430, y=90)
        
        self.labelPic = tkinter.Label(frame,
                                       text='过滤词',
                                       font=('黑体'),
                                       justify='left',
                                       )
        self.labelPic.place(x=20, y=150)
        
        self.st = ScrolledText(frame, width=43, height=3)
        self.st.place(x=90,y=150)
        
        self.buttonAddWords = tkinter.Button(frame, text='添加', width=5, height=1, command=self.addWords)
        self.buttonAddWords.place(x=430, y=150)        

      
    def openFile(self):

        path = os.path.split(os.path.realpath(__file__))[0]
        fileName = askopenfilename(initialdir = path,filetypes=[('Word文档', '*.doc;*.docx'), ('文本文件', '*.txt')])
        self.fileVar.set(fileName)
        return fileName
        
    def openPic(self):
        path = os.path.split(os.path.realpath(__file__))[0]
        picName = askopenfilename(initialdir = path,filetypes=[('JPEG', '*.jpg;*.jpeg;*.jpe;*.jfif'), ('PNG', '*.png')])
        self.picVar.set(picName)
        return picName
    
    def addWords(self):
        
        f = open('./stopwords.txt','a+')
        text = f.read()
        dupWords = list()

        tempStrings = self.st.get('1.0', 'end-1c')

        tempStrings = tempStrings.encode('UTF-8')
        if tempStrings == '':
            self.replyNoneWin()
        else:
            wordList = re.split(',|,',tempStrings) 
            for i in range(len(wordList)):
                if wordList[i].strip() not in text:
                    f.seek(0,2)
                    f.write(wordList[i].strip()+'\n')
                else:
                    dupWords.append(wordList[i].strip())
                    
            self.replyOkWin()
            
            if dupWords != '':
                self.replyDupWin(dupWords)
        f.close()
        
    def replyOkWin(self):
        showinfo(title='提示', message='添加成功!')

    def replyDupWin(self,dupWords):
        showinfo(title='提示', message='以下词语:"' + ','.join(dupWords) + '" 已经收录,无需再次添加。')

    def replyNoneWin(self):
        showinfo(title='提示', message='没有添加内容')
예제 #21
0
class InputFile:
    def __init__(self, drawing):
        self.drawing = drawing
        self.toplevel = Toplevel()
        self.dirty = False
        self.filename = drawing.name + ".inp"
        self.toplevel.title(self.filename)
        self.inputText = ScrolledText(self.toplevel)
        self.inputText.pack()

        self.popup = Menu(self.toplevel, tearoff=0)
        self.popup.add_command(label="Dismiss", command=self.nothing)
        self.popup.add_command(label="Abort", command=self.abort)
        self.popup.add_command(label="Accept", command=self.accept)
        self.popup.add_command(label="Feedback", command=self.feedback)
        self.popup.add_command(label="Other File", command=self.changeFile)
        self.popup.add_command(label="Run", command=self.run)
        self.popup.add_command(label="Debug", command=self.debug)

        def popupMenu(event):
            self.popup.post(event.x_root, event.y_root)

        self.toplevel.bind('<Button-3>', popupMenu)
        Widget.bind(self.inputText, '<Any-KeyPress>', self.setDirty)
        self.refreshSource()

    def nothing(self):
        pass

    def abort(self):
        self.refreshSource()
        self.setClean()
        print "aborted"

    def accept(self):
        inptext = self.getSource()
        handle = open(self.filename, "w")
        handle.write(inptext)
        self.setClean()

    def run(self):
        self.accept()
        self.drawing.doRun()

    def debug(self):
        self.drawing.doDebug()

    def changeFile(self):
        self.filename = tkFileDialog.asksaveasfilename(
            initialdir=os.getcwd(),
            parent=self.toplevel,
            title="Select Input file",
            filetypes=[("Input files", ".inp")],
            defaultextension='.inp')
        self.filename = os.path.basename(self.filename)
        self.refreshSource()
        self.drawing.setInpFile(os.path.splitext(self.filename)[0])

    def refreshSource(self):
        inptext = ""
        if os.path.exists(self.filename):
            inptext = open(self.filename).read()
        self.setSource(inptext)
        self.toplevel.title(self.filename)

    def setSource(self, txt):
        self.inputText.delete('1.0', END)
        self.inputText.insert(END, txt)

    def getSource(self):
        return self.inputText.get("1.0", END)

    def feedback(self):
        resFile = "res" + os.sep + os.path.splitext(
            os.path.basename(self.filename))[0] + ".res"
        if os.path.exists(resFile):
            resText = open(resFile).read()
            self.setSource(resText)
            self.setDirty()

    def setClean(self):
        if self.dirty:
            self.dirty = False
            self.toplevel.title(self.filename)

    def setDirty(self, event=None):
        if event and (event.keysym in [
                'Shift_L', 'Shift_R', 'Alt_L', 'Alt_R', 'Win_L', 'Win_R'
        ]):
            return
        if not self.dirty:
            self.dirty = True
            self.toplevel.title(self.filename + "*")
예제 #22
0
class GUI_hcheck:

    # do everything!
	def __init__(self):
		self.top = Tk()
		self.top.title('Health Check Tool')
		self.top.geometry('1400x800')

		#------- Label,Entry defination ----------#
		self.l1 = Label(self.top, text="IP:").grid(row=1, column=1, sticky="w")
		self.e1 = Entry(self.top)
		self.e1.grid(row=1, column=2,sticky="ew")
		self.l2 = Label(self.top, text="User:"******"w")
		self.e2 = Entry(self.top)
		self.e2.grid(row=2, column=2,sticky="ew")
		self.l3 = Label(self.top, text="Passwd:").grid(row=3, column=1, sticky="w")
		self.e3 = Entry(self.top)
		self.e3['show'] = '*'
		self.e3.grid(row=3, column=2,sticky="ew")
		self.l4 = Label(self.top, text="Command pool:").grid(row=4, column=1, sticky="e")
		self.l5 = Label(self.top, text="To be run command:").grid(row=4, column=5, sticky="e")
		self.e4 = Entry(self.top, width=30)
		self.e4.grid(row=16, column=0, columnspan=3, sticky="ew")

		#------- Checkbutton defination ----------#
		self.cb1State = IntVar()
		self.cb1 = Checkbutton(self.top, variable=self.cb1State, text = "Always Yes", command=self.callCheckbutton)
		self.cb1.grid(row=21, column=16)

		#------- Listbox defination ----------#
		self.cmdfm = Frame(self.top)
		self.cmdsb = Scrollbar(self.cmdfm)
		self.cmdsb_x = Scrollbar(self.cmdfm,orient = HORIZONTAL)
		self.cmdsb.pack(side=RIGHT, fill=Y)
		self.cmdsb_x.pack(side=BOTTOM, fill=X)
		self.cmdls = Listbox(self.cmdfm, selectmode=EXTENDED, height=25, width=40, xscrollcommand=self.cmdsb_x.set, yscrollcommand=self.cmdsb.set)
		self.cmdsb.config(command=self.cmdls.yview)
		self.cmdsb_x.config(command=self.cmdls.xview)
		self.cmdls.pack(side=LEFT, fill=BOTH)
		self.cmdfm.grid(row=5, rowspan=10, column=0,columnspan=4,sticky="ew")
		self.db_file = os.path.join(os.getcwd(),'%s' % constants.DB_NAME)
		flist = utility.load_file(self.db_file)
		if flist != None:
			log.debug ("db file found, start load command")
			for element in flist:
				element = element.strip('\n')
				if element == '' or element.startswith('#'):
					continue
				self.cmdls.insert(END, element)
		else:
			log.debug ("db file doesn't existed, initail cmd")
			for element in constants.CMD_LIST_COMM:
				self.cmdls.insert(END, element)

		self.dirfm = Frame(self.top)
		self.dirsb = Scrollbar(self.dirfm)
		self.dirsb_x = Scrollbar(self.dirfm,orient = HORIZONTAL)
		self.dirsb.pack(side=RIGHT, fill=Y)
		self.dirsb_x.pack(side=BOTTOM, fill=X)
		self.dirs = Listbox(self.dirfm, selectmode=EXTENDED, height=25, width=40, xscrollcommand=self.dirsb_x.set,yscrollcommand=self.dirsb.set)
		self.dirsb.config(command=self.dirs.yview)
		self.dirsb_x.config(command=self.dirs.xview)
		self.dirs.pack(side=LEFT, fill=BOTH)
		self.dirfm.grid(row=5, rowspan=10, column=5,columnspan=4,sticky="ew")

		#------- Buttion defination ----------#
		# add command button
		self.b1 = Button(self.top,text=">>",width=6,borderwidth=3,relief=RAISED, command=self.move_cmd)
		self.b1.grid(row=7, column=4)
		# del command button
		self.b2 = Button(self.top,text="<<",width=6,borderwidth=3,relief=RAISED, command=self.del_cmd)
		self.b2.grid(row=8, column=4)
		# move up command button
		self.b3 = Button(self.top,text="up",width=6,borderwidth=3,relief=RAISED, command=self.up_cmd)
		self.b3.grid(row=7, column=10)
		# move down command button
		self.b4 = Button(self.top,text="down",width=6,borderwidth=3,relief=RAISED, command=self.down_cmd)
		self.b4.grid(row=8, column=10)
		# start command button
		self.b5 = Button(self.top,text="Start",bg='red',width=10,borderwidth=3,relief=RAISED, command=self.start_process)
		self.b5.grid(row=2, column=11)
		# yes button
		self.b6 = Button(self.top,text="Yes",width=6,borderwidth=3,relief=RAISED, command=self.set_confirm_yes)
		self.b6.grid(row=21, column=13)
		# No button
		self.b7 = Button(self.top,text="No",width=6,borderwidth=3,relief=RAISED, command=self.set_confirm_no)
		self.b7.grid(row=21, column=14)
		# Skip button
		self.b8 = Button(self.top,text="Skip",width=6,borderwidth=3,relief=RAISED, command=self.set_confirm_skip)
		self.b8.grid(row=21, column=15)
		# Add button
		self.b9 = Button(self.top,text="add cmd",width=10,borderwidth=3,relief=RAISED, command=self.add_command)
		self.b9.grid(row=15, column=1)
		# Del button
		self.b10 = Button(self.top,text="del cmd",width=10,borderwidth=3,relief=RAISED, command=self.del_command)
		self.b10.grid(row=15, column=2)
		# Manual button
		self.manual = False
		self.b11 = Button(self.top,text="Manual model",width=10,borderwidth=3,relief=RAISED, command=self.manual_mode)
		self.b11.grid(row=2, column=12)

		#------- ScrolledText defination ----------#
		self.sfm = Frame(self.top)
		self.console = ScrolledText(self.sfm,height=45, width=86,bg='black',fg='green',insertbackground='green')
		self.console['font'] = ('lucida console','10')
		self.console.bind("<Return>", self.process_input)
		self.console.pack()
		self.sfm.grid(row=4, rowspan=15, column=11,columnspan=10,sticky="ew")

		self.redir = redirect(self.console)
		sys.stdout = self.redir
		sys.stderr = self.redir
		self.fconsole = logging.StreamHandler(sys.stdout)
		self.fconsole.setLevel(logging.INFO)
		logging.getLogger('').addHandler(self.fconsole)

		#------- Menu defination ----------#
		self.menubar = Menu()
		# file menu
		self.fmenu = Menu()
		#self.fmenu.add_command(label = 'New',command=self.new_win)
		self.fmenu.add_command(label = 'Import cmd',command=self.load_cmd)
		self.fmenu.add_command(label = 'Export cmd',command=self.export_cmd)
		self.menubar.add_cascade(label = 'File', menu = self.fmenu)
		# edit menu
		self.emenu = Menu()
		self.cmenu = Menu()
		self.cvar = StringVar()
		for item in ['white/black', 'black/white', 'green/black']:
			self.cmenu.add_radiobutton(label = item, variable=self.cvar, value=item, command=self.sel_color_style)
		self.emenu.add_cascade(label = 'console style', menu = self.cmenu)
		self.emenu.add_command(label = 'reset cmd pool',command=self.reset_cmd_pool)
		self.menubar.add_cascade(label = 'Edit', menu = self.emenu)

		self.top['menu'] = self.menubar

	def new_win(self):
		#GUI_hcheck()
		pass

	def sel_color_style(self):
		log.debug ("select console color style: %s " % self.cvar.get())
		color = self.cvar.get()
		if color == 'white/black':
			self.console.config(bg='black',fg='white',insertbackground='white')
		elif color == 'black/white':
			self.console.config(bg='white',fg='black',insertbackground='black')
		elif color == 'green/black':
			self.console.config(bg='black',fg='green',insertbackground='green')

	def move_cmd(self):
		if self.cmdls.curselection() != ():
			for i in self.cmdls.curselection():
				if utility.elemet_exists(self.dirs.get(0,END), self.cmdls.get(i)) == None:
					self.dirs.insert(END,self.cmdls.get(i))
					log.debug ("move command %s" % self.cmdls.get(i))
		else:
			tkMessageBox.showwarning('Message', 'Please select at lease one item')

	def load_cmd(self):
		file = tkFileDialog.askopenfilename()
		flist = utility.load_file(file)
		if flist != None:
			self.dirs.delete(0,END)
			for element in flist:
				element = element.strip('\n')
				if element == '' or element.startswith('#'):
					continue
				if utility.elemet_exists(self.dirs.get(0,END), element) == None:
					self.dirs.insert(END, element)
		else:
			tkMessageBox.showerror('Message', 'import failed')

	def export_cmd(self):
		file = tkFileDialog.askopenfilename()
		if utility.export_file(self.dirs.get(0,END), file) == True:
			tkMessageBox.showinfo('Message', 'export finish')
		else:
			tkMessageBox.showerror('Message', 'export failed')

	def del_cmd(self):
		if self.dirs.curselection() != ():
			for i in self.dirs.curselection():
				self.dirs.delete(i)
		else:
			tkMessageBox.showwarning('Message', 'Please select at lease one item')

	def up_cmd(self):
		select = self.dirs.curselection()
		if (len(select)) >= 2:
			tkMessageBox.showwarning('Message', 'Only one select is supported')
			return
		log.debug ("move up select pos: %s" % str(select))
		if select != () and select != (0,):
			element = self.dirs.get(select)
			self.dirs.delete(select)
			self.dirs.insert((select[0] - 1), element)
			self.dirs.select_set(select[0] - 1)

	def down_cmd(self):
		select = self.dirs.curselection()
		if (len(select)) >= 2:
			tkMessageBox.showwarning('Message', 'Only one select is supported')
			return
		log.debug ("move down select pos: %s" % str(select))
		if select != () and select != (END,):
			element = self.dirs.get(select)
			self.dirs.delete(select)
			self.dirs.insert((select[0] + 1), element)
			self.dirs.select_set(select[0] + 1)

	def start_process(self):
		log.debug ("current thread total numbers: %d" % threading.activeCount())
		response = tkMessageBox.askokcancel('Message', 'Will start healthcheck, please click OK to continue, or cancel')
		if response == False:
			return
		th = threading.Thread(target=self.start_cmd)
		th.setDaemon(True)
		th.start()

	def start_cmd(self):
		self.manual = False
		cmd = list(self.dirs.get(0,END))
		if len(cmd) == 0:
			log.info ("To be run cmd numbers none, quit...")
			return
		log.debug ("fetch cmd list from GUI: %s" % cmd)
		(ip, port) = utility.getipinfo(self.e1.get())
		log.debug ("get ip infor-> ip: %s, port:%s" % (ip,port))
		if ip == False:
			log.error ("Given ip infor is wrong! The right ip address: xxx.xxx.xxx.xxx or IP:port ")
			return
		self.b5.config(state=DISABLED)
		self.b11.config(state=DISABLED)
		self.console.delete('1.0',END)
		try:
			self.wf = Workflow(cmd, ip, self.e2.get(), self.e3.get(), port)
			self.wf.start()
		except:
			pass
		self.b5.config(state=NORMAL)
		self.b11.config(state=NORMAL)

	def manual_mode(self):
		cmd = []
		(ip, port) = utility.getipinfo(self.e1.get())
		log.debug ("get ip infor-> ip: %s, port:%s" % (ip,port))
		if ip == False:
			log.error ("Given ip infor is wrong! The right ip address: xxx.xxx.xxx.xxx or IP:port ")
			return
		self.wf_manual = Workflow(cmd, ip, self.e2.get(), self.e3.get(), port)
		if self.wf_manual.setup_ssh(self.wf_manual.hostip) == False:
			log.error ("\nssh setup error! please check ip/user/passwd and network is okay")
			del self.wf_manual
			return
		self.console.delete('1.0',END)
		self.console.insert(END, "Switch to manual mode...\n\
Please input command directly after \">>> \"\n\n")
		self.prompt = ">>> "
		self.insert_prompt()
		self.manual = True
		self.b5.config(state=DISABLED)
		self.b11.config(state=DISABLED)

	def set_confirm_yes(self):
		try:
			self.wf.set_confirm('Yes')
		except AttributeError:
			log.debug("wf doesn't existed")
	def set_confirm_no(self):
		try:
			self.wf.set_confirm('No')
		except AttributeError:
			log.debug("wf doesn't existed")
	def set_confirm_skip(self):
		try:
			self.wf.set_confirm('Skip')
		except AttributeError:
			log.debug("wf doesn't existed")

	def callCheckbutton(self):
		try:
			if self.cb1State.get() == 1:
				self.wf.set_automatic(5)
			else:
				self.wf.set_automatic(None)
		except AttributeError:
			log.debug("wf doesn't existed")
			self.cb1.deselect()
			tkMessageBox.showwarning('Message', 'please press start button first')

	def saveinfo(self):
		pass

	def add_command(self):
		item = self.e4.get()
		if item != '':
			if utility.elemet_exists(self.cmdls.get(0,END), item) == None:
				self.cmdls.insert(END,item)
				self.cmdls.see(END)
				log.debug ("add new command %s" % item)
				self.save_command()
		else:
			tkMessageBox.showwarning('Message', 'entry can not empty')

	def del_command(self):
		if self.cmdls.curselection() != ():
			for i in self.cmdls.curselection():
				self.cmdls.delete(i)
				self.save_command()
		else:
			tkMessageBox.showwarning('Message', 'Please select at lease one item')

	def save_command(self):
		if utility.export_file(self.cmdls.get(0,END), self.db_file) != True:
			log.error ("save command pool failed")

	def reset_cmd_pool(self):
		log.debug ("start to reset command pool list")
		self.cmdls.delete(0,END)
		for element in constants.CMD_LIST_COMM:
			self.cmdls.insert(END, element)
		self.save_command()

	def insert_prompt(self):
		c = self.console.get("end-2c")
		if c != "\n":
			self.console.insert("end", "\n")
		self.console.insert("end", self.prompt, ("prompt",))
		#self.text.insert("end", self.prompt)
		# this mark lets us find the end of the prompt, and thus
		# the beggining of the user input
		self.console.mark_set("end-of-prompt", "end-1c")
		self.console.mark_gravity("end-of-prompt", "left")

	def process_input(self,event):
		index = self.console.index("end-1c linestart")
		line = self.console.get(index,'end-1c')
		log.debug ("last line: %s" % line)
		if self.manual == True:
			self.console.insert("end", "\n")
			command = self.console.get("end-of-prompt", "end-1c")
			command = command.strip()
			if command != '':
				if command == 'bye' or command == 'exit':
					log.info ("quit from manual mode...")
					self.wf_manual.ssh.close()
					self.manual = False
					self.b5.config(state=NORMAL)
					self.b11.config(state=NORMAL)
					return
				elif command == 'help':
					log.info ("This is used for run command on target server by ssh, for example: >>> df -h, >>> svcs -xv")
				elif self.wf_manual.remote_cmd(command) == 1:
					log.error ("command %s execute failed" % command)
			self.insert_prompt()
			self.console.see("end")
			# this prevents the class binding from firing, since we 
			# inserted the newline in this method
			return "break"
		else:
			if line == 'Yes' or line == 'y' or line == 'yes': 
				self.set_confirm_yes()
			elif line == 'No' or line == 'n' or line == 'no':
				self.set_confirm_no()
			elif line == 'Skip' or line == 's' or line == 'skip':
				self.set_confirm_skip()
			else:
				pass
예제 #23
0
class Room(Toplevel):
    __client_sock = None
    __user_name = None
    __room_name = None
    __main_frame = None
    __top_frame = None

    __exit_room = False

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

        self['background'] = 'grey'

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

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

        self.configure_GUI()
        self.__client_sock = client

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

        self.withdraw()
        self.mainloop()

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

    def close_room(self):
        self.withdraw()

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

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

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

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

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

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

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

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

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

    def destroy_room(self):
        self.destroy()

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

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

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

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

    def display_new_msg(self, user_name, msg, config=''):
        self.text_msg_List['state'] = 'normal'
        msg_time = time.strftime(" %Y-%m-%d %H:%M:%S", time.localtime()) + '\n'
        self.text_msg_List.insert(END,
                                  user_name + ': ' + msg_time + msg + '\n',
                                  config)
        self.text_msg_List['state'] = 'disabled'
예제 #24
0
파일: fbdot.py 프로젝트: acspike/Arpeggio
class App(tk.Frame):
    def __init__(self, master=None, frets=17, strings=6):
        tk.Frame.__init__(self, master)
        self.pack(fill=tk.BOTH,expand=True)
        self.master.title('FB Dots')
        
        self.frets = frets + 1
        self.strings = strings
        
        tframe = tk.Frame(self)
        tframe.pack(expand=False, anchor=tk.W)
        for i in range(self.frets):
            tk.Label(tframe, text=str(i)).grid(row=0, column=i)
        self.dots = []
        for i in range(self.strings):
            dots = []
            for j in range(self.frets):
                x = DotEntry(tframe, width=3)
                x.grid(row=(i + 1), column=j, sticky=(tk.E+tk.W))
                dots.append(x)
            self.dots.append(dots)
            
        bframe = tk.Frame(self)
        bframe.pack(expand=False, anchor=tk.W)
        tk.Button(bframe, text='Load', command=self.load).grid(row=0, column=0, sticky=(tk.E+tk.W))
        tk.Button(bframe, text='Save', command=self.save).grid(row=0, column=1, sticky=(tk.E+tk.W))
        tk.Button(bframe, text='Clear', command=self.clear).grid(row=0, column=2, sticky=(tk.E+tk.W))
        tk.Label(bframe, text=' Ring Character: ').grid(row=0, column=3, sticky=(tk.E+tk.W))
        self.ring_character = tk.StringVar()
        self.ring_character.set('.')
        tk.Entry(bframe, textvariable=self.ring_character, width=2).grid(row=0, column=4, sticky=(tk.E+tk.W))
        tk.Button(bframe, text='Down', command=self.move_down).grid(row=0, column=5, sticky=(tk.E+tk.W))
        tk.Button(bframe, text='Up', command=self.move_up).grid(row=0, column=6, sticky=(tk.E+tk.W))
        
        self.io = ScrolledText(self)
        self.io.pack(fill=tk.BOTH, expand=True, anchor=tk.N)
    def load(self):
        rc = self.ring_character.get()
        v = self.io.get(1.0, tk.END)
        val = unrepr(v)
        for d in val:
            s,f,t,r = d
            s = s - 1
            out = t
            if r:
                out += rc
            if not out:
                out += ' '
            self.dots[s][f].set(out)
    def save(self):
        rc = self.ring_character.get()
        val = []
        for i in range(self.strings):
            for j in range(self.frets):
                v = self.dots[i][j].get()

                if len(v) == 0:
                    continue
                    
                if rc in v:
                    r = 1
                else:
                    r = 0
                
                v = ''.join([x for x in v if x not in [rc, ' ']])
                
                val.append(((i + 1), j, v, r))
                
        self.io.delete(1.0, tk.END)
        self.io.insert(tk.END, str(val))
    def clear(self):
        for s in self.dots:
            for f in s:
                f.set('')
    def move(self, offset):
        self.save()
        self.clear()
        v = self.io.get(1.0, tk.END)
        val = unrepr(v)
        new_val = []
        for d in val:
            s,f,t,r = d
            f += offset
            if 0 <= f < self.frets:
                new_val.append((s,f,t,r))
            else:
                print f
        self.io.delete(1.0, tk.END)
        self.io.insert(tk.END, str(new_val))
        self.load()
    def move_up(self):
        self.move(1)
    def move_down(self):
        self.move(-1)
class dial_gui(Frame):   

    doireg = re.compile('^[0-9]{2}\.[0-9]{4}/.+$')
           
    def __init__(self, master=None):
        Frame.__init__(self, master)   
        self.pack(expand=YES, fill=BOTH)
        log = login_win()
        self.login  = log.login
        self.passwd = log.passwd
        self.createWidgets()
        self.importer = DialImporter(log.login,log.passwd)

    def createWidgets(self):
        self.inframe = Frame(self)
        self.intext   = Label(self.inframe,text="Fetch DOIs for:")
        self.ininput  = Entry(self.inframe)
        self.ininput.bind('<Return>', (lambda event: self.fetch_dois()))
        self.inbutton = Button(self.inframe,text="get DOIs",command=self.fetch_dois)
        self.qb = Button(self, text='Quit', command=self.quit)   
        self.en = ScrolledText(self)
        self.en.insert(INSERT,'Enter DOI here, one line per DOI')
        self.rb = Button(self,text="Process",command=self.readentries)
        self.qb.pack(side=BOTTOM, fill=X, padx=10, pady=10)
        self.rb.pack(side=BOTTOM, fill=X, padx=10, pady=10)
        self.inframe.pack(side=TOP,fill=X,padx=10, pady=10)
        self.intext.pack(side=LEFT)
        self.ininput.pack(side=LEFT, padx=10)
        self.inbutton.pack(side=RIGHT)
        self.en.pack(side=TOP, fill=BOTH, padx=10, pady=10)
        self.ininput.focus()

    def fetch_dois(self):
        author = self.ininput.get().strip() 
        dois = "\n".join(self.importer.get_author_dois(author))
        self.en.delete('1.0', END)
        self.en.insert("1.0",dois)
        self.rb.focus()

    def readentries(self):
        self.content = self.en.get("1.0",END).strip().split("\n")
        badmatches = [doi for doi in self.content if not self.doireg.match(doi)]
        okmatches = [doi for doi in self.content if self.doireg.match(doi)]
        if len(badmatches):
            showwarning('','The following DOIs are malformed and will not be processed: \n'+'\n'.join(badmatches))
        fails = {}
        for doi in okmatches:
            print "Getting info about", doi
            error = self.importer.get_info(doi)
            if error: 
                fails[doi] = error
            else:
                print "Inserting into DIAL", doi
                try:
                    error = self.importer.push_to_dial()
                except Exception as push_err:
                    error = repr(push_err)
                if error : fails[doi] = error
        if len(fails):
            failmsg = '\n'.join([ key+", error: "+value for key, value in fails.items()])
            showwarning('','The following DOIs import failed :\n\n'+failmsg)
        else:
            showinfo('','Importation of all {} DOIs ended successfully'.format(len(okmatches)))
        self.importer.cleanup_files()
예제 #26
0
class LoggingUI(TimedFrame):
    u'''ロギング用UI'''
    def __init__(self, *args, **kwargs):
        TimedFrame.__init__(self, *args, **kwargs)
        self.pack()
        self.init()
        self.startTimer()
    
    def init(self):
        if not config.normalize.points:
            self._label = tk.Label(self, text = u'まだ正規化が済んでいません。\n正規化を行ってください。')
            self._label.pack()
            return

        if not config.template.images or len(config.template.images) < 10 or not all(config.template.images):
            self._label = tk.Label(self, text = u'まだ学習が済んでいません。\n学習を行ってください。')
            self._label.pack()
            return
        
        # テンプレートの読み込み
        self.loadTemplates()
        
        # カメラの準備
        self._camera = cv.CaptureFromCAM(config.camera.id)
        
        # 左側UI
        frame1 = tk.Frame(self)
        frame1.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
        
        # カメラ画像表示用Canvasなどの準備
        self._cvmat = None
        self._image = tk.PhotoImage(width = config.canvas.width, height = config.canvas.height)
        self._canvas = tk.Canvas(frame1, width = config.canvas.width, height = config.canvas.height)
        self._canvas.create_image(config.canvas.width / 2, config.canvas.height / 2, image = self._image, tags = 'image')
        self._canvas.pack(expand = True, fill = tk.BOTH)
        
        # ボタン
        self._main_button = tk.Button(frame1)
        self._main_button.pack(side = tk.LEFT)
        self.logStop()
        self._reset_button = tk.Button(frame1, text = u'リセット', command = self.reset)
        self._reset_button.pack(side = tk.RIGHT)
        
        # 生データ表示領域
        self._textarea = ScrolledText(self, width = 6, height = 18)
        self._textarea.pack(side = tk.LEFT, expand = True)
        
        # 右側UI
        frame2 = tk.Frame(self)
        frame2.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
        
        # ログデータ表示領域
        self._graph = tk.Canvas(frame2, width = config.canvas.width, height = config.canvas.height, bg = 'white')
        self._graph.pack(expand = True, fill = tk.BOTH)
        self._bar_graph = BarGraph(A(width = config.canvas.width, height = config.canvas.height), config.logging.graph_max_count)
        
        # ボタン
        self._out_button = tk.Button(frame2, text = u'生データをコピー', command = self.datacopy)
        self._out_button.pack(side = tk.LEFT)
        self._gchart_button = tk.Button(frame2, text = u'Google Chart URLをコピー', command = self.gchart)
        self._gchart_button.pack(side = tk.RIGHT)
        
        # 画像をフィルタするための変数
        self._clip_rect, self._perspective_points = Points2Rect(config.normalize.points)
        
        # ロギング開始、停止のフラグ
        self._take_log = False
        
        # ログ
        self._log = []
        
        # カメラ画像の更新を1秒間隔にする
        self.addTiming(self.showImage, 1)
    
    def setValue(self, value):
        if value is None: value = 0
        self._bar_graph.setValue(value)
        
        self._graph.delete('bar')
        for bar in self._bar_graph.getAllBars():
            self._graph.create_rectangle(
                bar.p1.x, bar.p1.y,
                bar.p2.x, bar.p2.y,
                fill = 'green', stipple = 'gray25',
                tags = 'bar'
            )
    
    def loadTemplates(self):
        u'''テンプレート画像の読み込み'''
        self._templates = []
        for i, cvimageinfo in enumerate(config.template.images):
            cvmat = cv.CreateMatHeader(cvimageinfo.rows, cvimageinfo.cols, cvimageinfo.type)
            cv.SetData(cvmat, cvimageinfo.data)
            self._templates.append(A(
                image = cv.GetImage(cvmat),
                number = i,
                result = None,
            ))
    
    def showImage(self):
        u'''カメラ画像の表示'''
        captured = cv.QueryFrame(self._camera)
        self._cvmat = self.filter(captured)
        self._image = CvMat2TkImage(self._cvmat)
        self._canvas.itemconfigure('image', image = self._image)
        if self._take_log:
            self.logging()
    
    def logging(self):
        u'''ログを取る'''
        target = self._cvmat
        digits_sieve = DigitsSieve()
        for template in self._templates:
            if not template.result:
                # マッチング結果保存用領域の準備
                template.result = cv.CreateImage(
                    (target.width - template.image.width + 1, target.height - template.image.height + 1),
                    cv.IPL_DEPTH_32F, 1,
                )
            
            cv.MatchTemplate(target, template.image, template.result, config.logging.match_method)

            # 数値の読み取り
            minVal, maxVal, minLoc, maxLoc = cv.MinMaxLoc(template.result)
            while maxVal > config.logging.match_threshold:
                # 検出された数値情報の保持
                digits_sieve.push(A(
                    number = template.number,
                    x = maxLoc[0],
                    y = maxLoc[1],
                    width = template.image.width,
                    height = template.image.height,
                    score = maxVal,
                ))
                
                # 現在の位置周辺のスコアをクリアし、次にスコアの高い位置を取得する
                SetReal2DAround(template.result, maxLoc, config.logging.match_exclusion_size, 0.0)
                minVal, maxVal, minLoc, maxLoc = cv.MinMaxLoc(template.result)
        
        value = digits_sieve.getValue()
        if value is not None:
            self._log.append(value)
            self.setValue(value)
            self._textarea.insert(tk.END, '%d\n' % value)
            self._textarea.see(tk.END)

    def logStart(self):
        u'''ロギングを開始する'''
        self._main_button.configure(text = u'ストップ', command = self.logStop)
        self._take_log = True
        
    def logStop(self):
        u'''ロギングを停止する'''
        self._main_button.configure(text = u'スタート', command = self.logStart)
        self._take_log = False
    
    def reset(self):
        u'''リセット'''
        self._bar_graph.init()
        self.setValue(0)
        self._log = []
        self._textarea.delete('1.0', tk.END)
    
    def datacopy(self):
        u'''生データをクリップボードにコピーする'''
        text = self._textarea.get('1.0', tk.END)
        self.clipboard_clear()
        self.clipboard_append(text)
    
    def gchart(self):
        u'''Google Chart API用のURLをクリップボードにコピーする'''
        if  self._log \
            and len(self._log) > 0 \
            and max(self._log) > 0:
                
                unit = float(4095) / max(self._log)
                url = gExtendedUrl(
                    map(lambda x: unit * x, self._log),
                    cht = 'bvs', # 棒グラフ
                    chxt = 'y', # y軸の目盛り表示
                    chxr = '0,0,%d' % max(self._log), # y軸の最小最大値
                    chg = '0,10,3,2', # 補助線
                    chbh = '%d,1' % (480 / len(self._log) - 1), # 棒グラフの棒の幅
                )
                self.clipboard_clear()
                self.clipboard_append(url)
        
    def filter(self, cvmat):
        u'''画像をフィルタする'''
        # サイズ調整
        thumbnail = cv.CreateMat(config.canvas.height, config.canvas.width, cv.CV_8UC3)
        cv.Resize(cvmat, thumbnail)
        return NormalizeImage(thumbnail, self._clip_rect, self._perspective_points)
예제 #27
0
class MainApp(Tk):
    """
    Main page
    """

    def __init__(self):
        Tk.__init__(self)
        self.find_b = PhotoImage(file="Image/Find_button.gif")
        self.logo = PhotoImage(file='Image/logo_app.gif')
        self.find_b2 = PhotoImage(file='Image/find_b2.gif')
        self.date = date()
        self.var = IntVar()

    def window(self):
        """Display Main window"""
        self.header = Frame(self, width=450, height=65, bg='#1E90FF')
        self.logo_name = Label(self.header, image=self.logo, bg='#1E90FF')
        self.datetime = Label(self, text=self.date)
        self.title_name = Label(self, text="Title", font=('Arial', 12,))
        self.title_box = Entry(self, width = 58, bg='white', relief=FLAT,  
                                font=('AngsanaUPC', 15))
        self.note_text = Label(self, text="Your Note", font=('Arial', 12,))
        self.note_box = ScrolledText(self, font=('AngsanaUPC', 14), width=65,
                                     relief=FLAT, bg='white', height=9)
        self.check = Checkbutton(self, text='Favorite', bg='#FEFF92',
                      variable=self.var, activebackground='#FEFF92',
                      width=55, justify='left')
        self.add_note = Button(self, width=45, text="Add Note", 
                               bg='green', relief=FLAT, font=('Arial', 11, 'bold')
                               , command=self.create_note, fg='white',
                               activebackground='#13AA02', activeforeground='white')
        self.find_note = Button(self.header, image=self.find_b, relief=FLAT, 
                              bg='gray', font=('Arial', 13, 'bold')
                                , command=self.find_notes, width=68, height=59,
                                activebackground='#1E90FF')
        self.all = Button(self, width=31, height=2, fg='white', 
                                text="Note Storage", bg='#009cff',
                                relief=FLAT, activeforeground='white', 
                                font=('Arial', 16, 'bold'),
                          command=self.note_storage, activebackground='#0069C6')
        self.last = Frame(self, bg='#1E90FF', width=450, height=25)
        self.fac = Label(self.last, fg='white', bg='#1E90FF', 
                         text="Faculty of Information Technology, KMITL")

        self.header.place(x=0, y=0)
        self.logo_name.place(x=15, y=5)
        self.datetime.place(x=325, y=75)
        self.title_name.place(x=20, y=80)
        self.title_box.place(x=20, y=110)
        self.note_text.place(x=20, y=150)
        self.note_box.place(x=20, y=185)
        self.check.place(x=20, y=423)
        self.add_note.place(x=20, y=457)
        self.find_note.place(x=376, y=0)
        self.all.place(x=20, y=500)
        self.last.place(x=0, y=575)
        self.fac.place(x=110, y=3)
        self.bind("<Button-1>", self.flat)
        self.find_note.bind("<Button-1>", self.find_press)
        self.find_note.bind("<ButtonRelease-1>", self.find_release)
        
    def note_storage(self):
        """Create Note Storage page"""
        note_store = NoteStorage()
        note_store.geometry('450x600+450+90')
        note_store.title('Note Storage')
        note_store.resizable(width=False, height=False)
        note_store.all_note()

    def create_note(self):
        """Create new note page"""
        title_name = self.title_box.get()
        note_text = self.note_box.get('1.0', END)
        favorite = self.var.get()

        count = 0
        for i in get_data():
            if title_name == i:
                break
            else:
                count += 1
        
        if title_name != '' and note_text != '' and len(title_name) <= 30:
            if count != len(get_data()):
                ask = tkMessageBox.askquestion\
                      ("Replace note", "Are you want to replace?",
                       icon="warning")
                if ask == 'yes':
                    self.title_box.delete(0, END)
                    self.note_box.delete('1.0', END)
                    note_page = NoteCreate()
                    note_page.geometry('350x500+500+150')
                    note_page.title('New note' + ' ' + ':' + ' ' + title_name)
                    note_page.resizable(width=False, height=False)
                    note_page.note_page(title_name, note_text, favorite)
            else:
                self.title_box.delete(0, END)
                self.note_box.delete('1.0', END)
                note_page = NoteCreate()
                note_page.geometry('350x500+500+150')
                note_page.title('New note' + ' ' + ':' + ' ' + title_name)
                note_page.resizable(width=False, height=False)
                note_page.note_page(title_name, note_text, favorite)

        elif len(title_name) > 30:
                error = tkMessageBox.showerror('Error', 'Your title is too long!')
        
        else:
            error = tkMessageBox.showerror('Error', 'Please input your note!')

    def find_notes(self):
        """Create find note page"""
        find = Findpage()
        find.geometry('400x500+475+145')
        find.resizable(width=False, height=False)
        find.title('Find your note')

    def flat(self, event):
        """Event widget flat"""
        event.widget.config(relief=FLAT)

    def find_press(self, event):
        """Event button press"""
        self.find_note.config(image=self.find_b2)

    def find_release(self, event):
        """Event button release"""
        self.find_note.config(image=self.find_b)
예제 #28
0
class Globby_Text_Editor(tk.Frame):
    def __init__(self, parent_widget, settings):
        # some initial values
        # TODO this Values are obsolete since Project_Settings covers them
        # --> self.settings.projects_path
        self.hash_opened_filename = None
        self.opened_filename = None
        self.settings = settings

        self.edit_button_list=[
            {'text':'new page', 'cmd':self.on_new_page,
                'keytxt':'CTRL+n','hotkey':'<Control-n>'},
            {'text':'del page', 'cmd':self.on_del_page,
                'keytxt':'CTRL+n','hotkey':'<DELETE>'} ,
            {'text':'save', 'cmd':self.on_save,
                'keytxt':'CTRL+s','hotkey':'<Control-s>'},
            {'text':'undo', 'cmd':self.on_undo,
                'keytxt':'CTRL+z','hotkey':'<Control-z>'},
            {'text':'redo', 'cmd':self.on_redo,
                'keytxt':'CTRL+y','hotkey':'<Control-y>'}]

        self.syntax_button_list=[
            {'text':'**bold**', 'cmd':self.on_tag_insert, 'open_tag':'**',
                'close_tag':'**','keytxt':'CTRL+b','hotkey':'<Control-b>'},
            {'text':'//italic//', 'cmd':self.on_tag_insert, 'open_tag':'//',
                'close_tag':'//', 'keytxt':'CTRL+i','hotkey':'<Control-i>'},
            {'text':'__underline__', 'cmd':self.on_tag_insert, 'open_tag':'__',
                'close_tag':'__', 'keytxt':'CTRL+u','hotkey':'<Control-u>'},
            {'text':'[Link]', 'cmd':self.on_tag_insert, 'open_tag':'[',
                'close_tag':']', 'keytxt':'CTRL+l','hotkey':'<Control-l>'},
            {'text':'¸¸sub¸¸', 'cmd':self.on_tag_insert, 'open_tag':'¸¸',
                'close_tag':'¸¸', 'keytxt':'CTRL+d','hotkey':'<Control-d>'},
            {'text':'^^upper^^', 'cmd':self.on_tag_insert, 'open_tag':'^^',
                'close_tag':'^^', 'keytxt':'CTRL+q','hotkey':'<Control-q>'},
            {'text':'-~smaller~-', 'cmd':self.on_tag_insert, 'open_tag':'-~',
                'close_tag':'~-', 'keytxt':'CTRL+w','hotkey':'<Control-w>'},
            {'text':'+~bigger~+', 'cmd':self.on_tag_insert, 'open_tag':'+~',
                'close_tag':'~+', 'keytxt':'CTRL+e','hotkey':'<Control-e>'},
            {'text':'~~strike_thru~~', 'cmd':self.on_tag_insert, 'open_tag':'~~',
                'close_tag':'~~', 'keytxt':'CTRL+t','hotkey':'<Control-t>'} ]

        # build Widgets
        tk.Frame.__init__(self, parent_widget)
        self.pack(fill=tk.BOTH, expand=tk.YES)

        #self.baseframe = tk.Frame(parent_widget)
        #self.baseframe.pack(fill=tk.BOTH, expand=tk.YES)
        self.editor()
        self.button_frame()

        # start tracking text changes inside the editfield
        thread.start_new_thread(self.on_txt_changes, ('',))



    def editor(self):
        """ combine some Widgets to an enhanced editor (incl. Scrollbar)

        --> self.text
                the text widget itself

        --> self.opened_file_label
                Label on top of the editfield to show the name of the current
                opened File
                It can be used to show textchanges
        """
        # build widgets
        self.txtfrm = tk.Frame(self)
        self.txtfrm.pack(fill=tk.BOTH, side=tk.LEFT, expand=tk.YES)
        self.opened_file_label = tk.Label(self.txtfrm, text="No File chosen")
        self.opened_file_label.pack(fill=tk.X)
        self.text = ScrolledText(self.txtfrm, bg="white",
                                undo=1, maxundo=30,
                                wrap=tk.WORD)
        self.text.pack(fill=tk.BOTH, expand=tk.YES, side=tk.LEFT)
        self.text.insert(1.0, u"Please open a File to edit")

        # build first(reference -- new name??) hash for comparison on changes
        self.hash_opened_filename = hash(self.text.get(1.0,tk.END))

        # Set focus on textwidget and move cursor to the upper left
        self.text.focus_set()
        self.text.mark_set(tk.INSERT, '0.0')      # goto line
        self.text.see(tk.INSERT)                  # scroll to line


    def label_button_row(self, parent_widget=None,
                            btnlst=None, start_count=0):
        """Build a 2 column table with a label beside each button in a row.
        Bind a keyboard sequence to the button command.
        Display this keyboard sequence on the label.

        todo:
            - think about a parameter for the widget to bind the Hotkeys
            - rename to: labled_button_row, draw_labled_button_row

        Parameter:
        --> parent_widget:
                Parent widget to place the table

        --> btnlst:
                Type: List of dicts representing a button
                Example:
                    {'text':'**bold**',     # displayed on the Button (string)
                    'cmd':self.on_tag_insert,   # command
                    'open_tag':'**',        # chars representing the beginning
                                            # of a tag for inserting (string)
                    'close_tag':'**',       # chars representing the end
                                            # of a tag for inserting (string)
                    'keytxt':'CTRL+b',      # displayed on the Label (string)
                    'hotkey':'<Control-b>'} # keyboard sequence (string)
                Note:
                    The existence of 'open_tag' and 'close_tag' in btnlst
                    decides which command is bound to the Button.
                    If they aren't there 'cmd' must be a function without
                    parameters!!!
                    otherwise 'cmd' needs following parameters:
                        otag = btn['open_tag']
                        ctag = btn['close_tag']
                        event = None  # Placeholder for a keysequence

        --> start_count:
                Type: int

                Description:
                    The table is relized with tkinter grid layout manager.
                    start_count is used if there is already a grid
                    (with a Label beside a button).
                    start_count can add the automatic genrated
                    buttons under the existing.
                    In Globby_Editor it is used to put a label_button_row
                    under a Tkinter menubutton(file choose, headlines).
        """
        i = start_count
        for btn in btnlst:
            try:
                otag = btn['open_tag']
                ctag = btn['close_tag']
                event = None
                doit = lambda e=event, o=otag, c=ctag:self.on_tag_insert(e,o,c)
                tk.Button(parent_widget, text=btn['text'], command=doit,
                        relief=tk.RIDGE
                        ).grid(column=0, row=i, sticky=tk.W+tk.E)
                self.text.bind(btn['hotkey'],doit)
            except KeyError:
                tk.Button(parent_widget, text=btn['text'], command=btn['cmd'],
                        relief=tk.RIDGE
                        ).grid(column=0, row=i, sticky=tk.W+tk.E)
            tk.Label(parent_widget, text=btn['keytxt'], relief=tk.FLAT
                ).grid(column=1, row=i, sticky=tk.W)
            i +=1


    def button_frame(self):
        """draws a frame to hold a edit- and syntax-buttons under each other
        """
        self.btnfrm = tk.Frame(self)
        self.btnfrm.pack(fill=tk.BOTH, side=tk.LEFT)
        self.edit_buttons()
        self.syntax_buttons()


    def edit_buttons(self):
        """draws a frame with buttons for editing (save, undo, redo, open)
        """

        # genrate a labelframe
        self.efrm = tk.LabelFrame(self.btnfrm, text="Edit Buttons")
        self.efrm.pack(fill=tk.BOTH, padx=5, pady=5)

        # generate a button with a pulldown menue to open a file to edit
        self.file_open_mbtn = tk.Menubutton(self.efrm, text='Open File')
        # generate the pulldown menue
        self.file_open_menu = tk.Menu(self.file_open_mbtn,
                                        postcommand=self.gen_file2edit_menu)
        # bind the pulldown menue to the menubutton
        self.file_open_mbtn.config(menu=self.file_open_menu, relief=tk.RIDGE)


        self.file_open_mbtn.grid(column=0,row=0, sticky=tk.W+tk.E)

        # label beside the Button to display the associated keyboard shortcut
        self.file_open_lbl = tk.Label(self.efrm, text='CTRL+o', relief=tk.FLAT)
        self.file_open_lbl.grid(column=1, row=0, sticky=tk.W+tk.E)


        # generate buttons as described in self.edit_button_list
        self.label_button_row(self.efrm, self.edit_button_list, 2)


        # bind keyboard shortcut to the menue
        self.text.bind('<Control-o>',
                lambda e: self.file_open_menu.tk_popup(e.x_root, e.y_root))


    def gen_file2edit_menu(self):
        """generates a (new) menu bound to the file chooser button
        so every time when a project is created or deleted
        gen_choose_project_menu should be called
        """
        # delete all existing menue entrys
        self.file_open_menu.delete(0,tk.END)
        proj_path = os.path.join(self.settings.projects_path,
                                self.settings.current_project )
        print "proj_path", proj_path
        for this_file in os.listdir(proj_path):
            splitted = os.path.splitext(this_file)
            if splitted[1] == ".txt" and splitted[0] != "menue":
                #print "this_file",this_file
                open_file = os.path.join(proj_path, this_file)
                do_it = lambda bla = open_file:self.on_open(bla)
                self.file_open_menu.add_command(label=splitted, command=do_it)




    def syntax_buttons(self):
        """draws a frame with buttons for insert (wiki)markup

        idea: new parameter for on_tag_insert()
            jump_in_between=True/False so a pulldown list for different levels
            of headlines arn't necessary
        """

        # genrate a labelframe
        self.sfrm = tk.LabelFrame(self.btnfrm, text="Syntax Buttons")
        self.sfrm.pack(fill=tk.BOTH, padx=5, pady=5)

        # generate a button with a pulldown menue für headline Syntax
        self.headln_menubtn = tk.Menubutton(self.sfrm, text='= Headlines =')
        # generate the pulldown menue
        self.headln_menu = tk.Menu(self.headln_menubtn)
        # bind the pulldown menue to the menubutton
        self.headln_menubtn.config(menu=self.headln_menu, relief=tk.RIDGE)
        # generate menue entrys
        i=1
        for entry in ('h1','h2','h3','h4','h5','h6'):
            otag = '\n\n'+'='*i+' '
            ctag = ' '+'='*i+'\n\n'
            doit = lambda event=None, o=otag, c=ctag:self.on_tag_insert(event,o,c)
            self.headln_menu.add_command(label=entry, command=doit)
            i+=1
        self.headln_menubtn.grid(column=0,row=0, sticky=tk.W+tk.E)

        # label beside the Button to display the associated keyboard shortcut
        self.headln_lbl = tk.Label(self.sfrm, text='CTRL+h', relief=tk.FLAT)
        self.headln_lbl.grid(column=1, row=0, sticky=tk.W+tk.E)

        # generate buttons as described in self.edit_button_list
        self.label_button_row(self.sfrm, self.syntax_button_list, 1)

        # bind keyboard shortcut to the menue
        self.text.bind('<Control-h>',
                lambda e: self.headln_menu.tk_popup(e.x_root, e.y_root))


    def on_txt_changes(self, dummy_value=tk.NONE):
        """ tracks text changes inside the editfield by comparing hash values
        new name: visualize_txt_changes???
        """
        while True:
            new_hash = hash(self.text.get(1.0, tk.END))
            if new_hash != self.hash_opened_filename:
                #print "changes"
                self.opened_file_label.configure(fg="red")
            else:
                #print "no changes"
                self.opened_file_label.configure(fg="black")
            sleep(0.2)


    def on_open(self, file_to_open=None):
        """- opens a *.txt file from project folder
        - generates a reference hash.
        - Brings the cursor to the upper left and show this position
          in the textfield

        Parameter:
        --> file_to_open:
                complete path for file to open
        idea:
            - rename file_to_open to openfile or file_to_open
        """
        self.opened_file_to_open = file_to_open
        self.opened_file_label.configure(text=file_to_open)
        self.text.delete(1.0, tk.END)

        self.opened_filename = os.path.basename(file_to_open)


        # write file content into the editfield
        editfile = codecs.open(file_to_open,'r', 'utf-8')
        self.text.insert(1.0, editfile.read())
        editfile.close()

        # generate reference hash for a comparison to track text changes
        self.hash_opened_filename = hash(self.text.get(1.0,tk.END))

        self.text.edit_reset()                  # clear tk's undo/redo stacks
        self.text.focus_set()                   # focus to textfield
        self.text.mark_set(tk.INSERT, '0.0')    # place cursor to upper left
        self.text.see(tk.INSERT)                # and display this line


    def on_save(self):
        """ Safes the current edited file"""
        if self.opened_filename:
            print "on_safe_"
            print "  self.opened_filename",self.opened_filename

            self.hash_opened_filename = hash(self.text.get(1.0,tk.END))


            path_to_safe_file = os.path.join(self.settings.projects_path,
                                    self.settings.current_project,
                                    self.opened_filename)

            safefile = codecs.open(path_to_safe_file,'w', 'utf-8')
            safefile.write(self.text.get(1.0,tk.END))
            safefile.close()
            self.text.edit_reset()        #clear tk's undo/redo stacks
        else:
            showinfo('Globby Text Editor','No File to save \n\n'
                    'You need to choose a File before editing')


    def on_undo(self):
        try:                                    # tk8.4 keeps undo/redo stacks
            self.text.edit_undo( )              # exception if stacks empty
        except tk.TclError:
            showinfo('Globby Text Editor', 'Nothing to undo')


    def on_redo(self):
        print "redo"
        try:                                  # tk8.4 keeps undo/redo stacks
            self.text.edit_redo()             # exception if stacks empty
        except tk.TclError:
            showinfo('Globby Text Editor', 'Nothing to redo')


    def on_new_page(self):
        """ Ask the user to name the new File, create a blank File and load it
        into the Editorwidget

        TODO:   check if file with the new filename allready exists
                check if Filename contains Specialchars
        """
        print "on_new_page"
        nfile_name = tkSimpleDialog.askstring("New File Name",
                                    "Fill in a new File Name")
        proj_path = os.path.join(self.settings.projects_path,
                                self.settings.current_project)
        nfile_name = os.path.join(proj_path, nfile_name.strip()+'.txt')
        nfile = codecs.open(nfile_name, 'w', 'utf-8')

        current_project = self.settings.current_project
        infostring1 = u'# Diese Datei wurde automatisch mit '
        infostring2 = u'dem Projekt "%s" erstellt' % current_project
        nfile.write(infostring1+infostring2 )
        nfile.close()

        self.on_open(nfile_name)

    def on_del_page(self):
        """"""
        print "del page"
        # self.settings.current_project
        del_file = os.path.join(self.settings.projects_path,
                                    self.settings.current_project,
                                    self.opened_filename)

        del_page = askyesno("Do you really want to delete ", del_file)

        if del_page:
            #self.set_project(self.new_project_name)
            print "%s geloescht" % del_file
            os.remove(del_file)


    def on_tag_insert(self, event=None, open_tag=None, close_tag=None):
        """ inserts a (wiki)tag to the current cursor position.

        If there is no text marked in the editfield, open_tag and close_tag
        are inserted to the current cursor position behind each other and the
        cursor jumps in between.
        Otherwise the marked string is enclosed by open_tag and close_tag and
        inserted to the current cursor position. Here the new cursor position
        is right behind the complete inserted string with tags.

        At this moment this behavior is quite buggy :-(

        idea:
            - new parameter for on_tag_insert()
              jump_in_between=True/False so a pulldown list for different levels
              of headlines arn't necessary
            - rename to: on_insert_tag?? on_tag_insert

        Parameter:
        --> event                       # keyboard shortcut
        --> open_tag                    # string
        --> close_tag                   # string

        """
        #print 'event',event
        #print 'open_tag',open_tag
        #print 'close_tag',close_tag

        ## when no String is selected:
        if not self.text.tag_ranges(tk.SEL):
            print "no String is selected"
            insert_point = self.text.index('insert')
            insertline = insert_point.split('.')[0]
            addit = 1
            if event != None:
                print "event not None"
                addit = 2
            insertrow = str(int(insert_point.split('.')[1])+len(open_tag)+addit)
            new_insert_point = insertline+'.'+ insertrow
            self.text.insert(insert_point, open_tag+''+close_tag)
            # place cursor to insert_point
            self.text.mark_set(tk.INSERT, new_insert_point)
            # display this position on the editfield
            self.text.see(tk.INSERT)

        ## when a String is selected:
        else:
            #print "im else"
            marked_text = self.text.get(self.text.index(tk.SEL_FIRST),
                                        self.text.index(tk.SEL_LAST))
            replace_index = self.text.index(tk.SEL_FIRST)
            print "replace_index in selected", replace_index
            self.text.delete(self.text.index(tk.SEL_FIRST),
                            self.text.index(tk.SEL_LAST))
            self.text.insert(replace_index, open_tag+marked_text+close_tag)
예제 #29
0
class Note(Toplevel):
    """
    Display select Note
    """

    def __init__(self, window=None):
        Toplevel.__init__(self, window=None)
        self.background = PhotoImage(file='Image/note_bg1.gif')
        self.image = PhotoImage(file='Image/favorite2.gif')
        self.window = window

    def my_note(self, title):
        """Main UI for note"""
        data = get_data()[title]
        data = get_data()[title]
        self.bg = Label(self, image=self.background)
        self.title = Label(self, text=title, fg='#f46b2f', bg='#efe9dc',
                           font=('AngsanaUPC', 18, 'bold'))
        self.txt = ScrolledText(self, width=44, height=13, bg='#efe9dc',\
                                font=('AngsanaUPC', 14), relief=FLAT)
        self.txt.insert('1.0', data[0])
        self.txt.config(state='disable')
        self.ok = Button(self, text='Ok', bg='white', relief=FLAT,
                         width=13, font=('Arial', 10, 'bold'),
                         command=lambda title=title: self.check_edit(title),
                         activebackground='#3FBB06')
        self.delete = Button(self, text='Delete', bg='white', relief=FLAT,
                             width=13, font=('Arial', 10, 'bold'),
                             activebackground='#C62F2F', command=lambda
                             title=title: self.delete_select(title))
        self.edit = Button(self, text='Edit', bg='white', font=('Arial', 10, 'bold'),
                           activebackground='#747474', command=self.make_edit,
                           relief=FLAT, width=14)

        self.ok.bind("<Enter>", self.button_ok1)
        self.ok.bind("<Leave>", self.button_ok2)
        self.delete.bind("<Enter>", self.button_delete1)
        self.delete.bind("<Leave>", self.button_delete2)
        self.edit.bind("<Enter>", self.button_edit1)
        self.edit.bind("<Leave>", self.button_edit2)
        
        self.bg.place(x=-2, y=0)
        self.title.place(x=30, y=50)
        self.ok.place(x=236, y=472)
        self.delete.place(x=0, y=472)
        self.txt.place(x=25, y=100)
        self.edit.place(x=114, y=472)
        
        if data[2] == '1':
            self.favor = Label(self, image=self.image, bg='#efe9dc')
            self.favor.place(x=266, y=40)

    def delete_select(self, title):
        """Delete data and destroy current window"""
        ask = tkMessageBox.askquestion("Delete", "Are you sure?", icon="warning")
        if ask == 'yes':
            delete_data(title)
            self.destroy()
            if self.window != None:
                self.window.destroy()
                note_store = NoteStorage()
                note_store.geometry('450x600+450+90')
                note_store.title('Note Storage')
                note_store.resizable(width=False, height=False)
                note_store.all_note()

    def check_edit(self, title):
        """replace text if text have change else destroy current page"""
        old = get_data()[title][0].splitlines()
        new = self.txt.get('1.0', END).splitlines()
        star = get_data()[title][2]
        for i in new:
            if i == '':
                new.remove(i)
        if new != old:
            tkMessageBox.showinfo('Status', 'Complete')
            add_data(title, self.txt.get('1.0', END), date(), star)
            self.destroy()
            if self.window != None:
                self.window.destroy()
                note_store = NoteStorage()
                note_store.geometry('450x600+450+90')
                note_store.title('Note Storage')
                note_store.resizable(width=False, height=False)
                note_store.all_note()
        else:
            self.destroy()
  
    def button_ok1(self, event):
        """Event button when press"""
        self.ok.config(relief=GROOVE, bg='#44D002')
        self.edit.config(bg='#44D002')
        self.delete.config(bg='#44D002')

    def button_ok2(self, event):
        """Event button when release"""
        self.ok.config(relief=FLAT, bg='white')
        self.edit.config(bg='white')
        self.delete.config(bg='white')

    def button_delete1(self, event):
        """Event ok button when press"""
        self.delete.config(relief=GROOVE, bg='#FF2828')
        self.ok.config(bg='#FF2828')
        self.edit.config(bg='#FF2828')

    def button_delete2(self, event):
        """Event button when release"""
        self.delete.config(relief=FLAT, bg='white')
        self.ok.config(bg='white')
        self.edit.config(bg='white')

    def button_edit1(self, event):
        """Event ok button when press"""
        self.delete.config(bg='#AFAFAF')
        self.ok.config(bg='#AFAFAF')
        self.edit.config(bg='#AFAFAF', relief=GROOVE)

    def button_edit2(self, event):
        """Event button when release"""
        self.delete.config(bg='white')
        self.ok.config(bg='white')
        self.edit.config(relief=FLAT, bg='white')

    def make_edit(self):
        """config text widget"""
        self.txt.config(state='normal')
예제 #30
0
class ViewportCard(object):
    """
    Manages the graphical representation of a card in a
    Tkinter canvas. Creates and destroys items as necessary, facilitates
    editing, and so on and so forth.

    Members:
    * card: model.Card
    * viewport: GPViewport
    * gpfile: gpfile.GraphPaperFile, contains model.graph()
    * canvas: TKinter canvas we get drawn on
    * editing: bool, text is being edited
    * moving: bool, being dragged
    * moving_edgescroll_id: callback id to scroll periodically when hovering
      near edge of screen
    * resize_state: {}
    * resize_edgescroll_id: as moving_edgescroll_id
    * slot: calls callbacks whenever geometry changes
    * new_edge: if an edge is being dragged out from a handle, this is it.
    * card_after_new_edge: bool, if we should make a new card when edge is dropped.
    """

    def __init__(self, viewport, gpfile, card):
        self.card = card
        self.viewport = viewport
        self.gpfile = gpfile
        self.canvas = viewport.canvas
        self.draw()
        self.editing = False
        self.moving = False
        self.moving_edgescroll_id = None
        self.resize_state = None
        self.resize_edgescroll_id = None
        # slot triggered when geometry (pos/size) changes
        # fn args: (self, x, y, w, h)
        self.geom_slot = Slot()
        self.deletion_slot = Slot()
        self.new_edge = None

    def draw(self):
        self.frame_thickness = 5
        self.window = ResizableCanvasFrame(
            self.canvas,
            self.card.x,
            self.card.y,
            self.card.w,
            self.card.h,
            min_width=MIN_CARD_SIZE,
            min_height=MIN_CARD_SIZE,
        )
        self.text = ScrolledText(self.window, wrap=WORD)
        self.text.pack(expand=1, fill="both")
        # set up text for editing, dragging, deleting
        self.text.bind("<Button-1>", self.mousedown)
        self.text.bind("<Shift-Button-1>", self.shiftmousedown)
        self.text.bind("<Double-Button-1>", self.doubleclick)
        self.text.bind("<B1-Motion>", self.mousemove)
        self.text.bind("<ButtonRelease-1>", self.mouseup)
        self.text.bind("<FocusIn>", self.focusin)
        self.text.bind("<FocusOut>", self.focusout)
        self.text.bind("<Control-Delete>", self.ctrldelete)
        self.text.insert(END, self.card.text)
        # set up frame for resizing
        self.window.bind("<Configure>", self.configure)
        self.window.save_callback = self.save_card
        # draw edge handles
        self.edge_handles = None
        # self.redraw_edge_handles()

    def redraw_edge_handles(self):
        """
        Either creates or modifies the edge handles, little circles poking
        out the side of the card, based on the current position and width.

        self.edge_handles is a list of itemids of the circles in (top,
        right, bottom, left) order.
        """

        def create_circle(bbox):
            # create circle suitable for edge-handle use
            new = self.canvas.create_oval(bbox[0], bbox[1], bbox[2], bbox[3], fill="green", outline="")
            self.canvas.addtag_withtag("card_handle_tag", new)  # for z-ordering
            self.canvas.tag_bind(new, "<Button-1>", self.handle_click)
            self.canvas.tag_bind(new, "<Shift-Button-1>", self.handle_shift_click)
            self.canvas.tag_bind(new, "<B1-Motion>", self.handle_mousemove)
            self.canvas.tag_bind(new, "<ButtonRelease-1>", self.handle_mouseup)
            return new

        x, y = self.window.canvas_coords()
        w, h = self.window.winfo_width(), self.window.winfo_height()
        # 2*radius should be < MIN_CARD_SIZE, and offset < radius
        radius = 30
        offset = 19  # offset of center of circle from card edge
        left_coords = (x + offset, y + h / 2)
        right_coords = (x + w - offset, y + h / 2)
        top_coords = (x + w / 2, y + offset)
        bottom_coords = (x + w / 2, y + h - offset)
        all_coords = (top_coords, right_coords, bottom_coords, left_coords)
        bboxes = [(x - radius, y - radius, x + radius, y + radius) for x, y in all_coords]
        if self.edge_handles:
            # move the edge handles
            for i, box in enumerate(bboxes):
                # self.canvas.coords(handle, box[0], box[1], box[2], box[3])
                self.canvas.delete(self.edge_handles[i])
                self.edge_handles[i] = create_circle(box)
                # self.canvas.itemconfig(handle, bbox = box)
        else:
            # create new ones
            self.edge_handles = [create_circle(b) for b in bboxes]
        # have to do this every time, every time we recreate the edge handles
        self.viewport.fix_z_order()

    def get_text(self):
        "gets the text from the actual editor, which may not be saved yet"
        return self.text.get("0.0", END)

    def save_text(self):
        # get text from window
        text = self.get_text()
        if text != self.card.text:
            self.card.text = text
            self.gpfile.commit()

    def canvas_coords(self):
        return self.window.canvas_coords()

    def start_moving(self, event):
        # set up state for a drag
        self.moving = True
        self.foocoords = (event.x, event.y)
        self.set_moving_edgescroll_callback()

    def edge_scroll(self):
        # if any edges are too close to the edge, move and scroll the canvas
        canvas_coords = self.canvas_coords()
        relative_mouse_pos = self.foocoords
        canvas_mouse_coords = (
            canvas_coords[0] + relative_mouse_pos[0] + self.frame_thickness,
            canvas_coords[1] + relative_mouse_pos[1] + self.frame_thickness,
        )
        scroll_x, scroll_y = self.viewport.edge_scroll(canvas_mouse_coords)
        # move the opposite direction the viewport scrolled
        scroll_x, scroll_y = -scroll_x, -scroll_y
        # print 'card.edgescroll x y', scroll_x, scroll_y, 'relative_mouse_pos', relative_mouse_pos
        self.window.move(scroll_x, scroll_y)
        self.viewport.reset_scroll_region()
        self.set_moving_edgescroll_callback()

    def set_moving_edgescroll_callback(self):
        self.moving_edgescroll_id = self.text.after(10, self.edge_scroll)

    def cancel_moving_edgescroll_callback(self):
        self.text.after_cancel(self.moving_edgescroll_id)
        self.moving_edgescroll_id = None

    def mousedown(self, event):
        self.window.lift()

    def doubleclick(self, event):
        self.start_moving(event)
        return "break"

    def shiftmousedown(self, event):
        self.mousedown(event)
        self.start_moving(event)
        return "break"

    def mousemove(self, event):
        if self.moving:
            # coords are relative to card, not canvas
            if self.foocoords:
                delta = (event.x - self.foocoords[0], event.y - self.foocoords[1])
            else:
                delta = (event.x, event.y)
            self.window.move(delta[0], delta[1])
            self.geometry_callback()
            self.viewport.reset_scroll_region()
            return "break"

    def mouseup(self, event):
        if self.moving:
            self.moving = False
            new_coords = self.canvas_coords()
            self.card.x, self.card.y = new_coords[0], new_coords[1]
            self.gpfile.commit()
            self.cancel_moving_edgescroll_callback()
            self.geometry_callback()

    # next several functions are bound to the circular edge handles
    def handle_click(self, event):
        # create new edge
        self.new_edge = ViewportEdge(self.viewport, self.gpfile, None, self, None)
        self.new_edge.mousemove(event)  # give it a real start pos

    def handle_shift_click(self, event):
        self.handle_click(event)
        self.new_edge.make_new_card = True

    def handle_mousemove(self, event):
        if self.new_edge:
            self.new_edge.mousemove(event)

    def handle_mouseup(self, event):
        if self.new_edge:
            self.new_edge.mouseup(event)
            self.new_edge = None

    def configure(self, event):
        self.redraw_edge_handles()

    def focusin(self, event):
        self.editing = True

    def focusout(self, event):
        self.editing = False
        self.save_text()

    def ctrldelete(self, event):
        title_sample = self.get_text().split("\n", 1)[0]
        if len(title_sample) > 20:
            title_sample = title_sample[:20] + "..."
        # delete the card
        if tkMessageBox.askokcancel("Delete?", 'Delete card "%s" and all its edges?' % title_sample):
            for handle in self.edge_handles:
                self.canvas.delete(handle)
            self.deletion_slot.signal()
            self.viewport.remove_card(self)
            self.card.delete()
            self.window.destroy()
            self.gpfile.commit()
        return "break"

    def save_card(self):
        # grab values from self.window,
        # and put them in the model.card
        self.card.x, self.card.y = self.window.canvas_coords()
        self.card.w, self.card.h = self.window.winfo_width(), self.window.winfo_height()
        self.geometry_callback()  # here so it gets called after resizing
        self.gpfile.commit()

    def add_geom_signal(self, fn):
        return self.geom_slot.add(fn)

    def remove_geom_signal(self, handle):
        self.geom_slot.remove(handle)

    def add_deletion_signal(self, fn):
        return self.deletion_slot.add(fn)

    def remove_deletion_signal(self, handle):
        self.deletion_slot.remove(handle)

    def geometry_callback(self):
        x, y = self.canvas_coords()
        w, h = self.window.winfo_width(), self.window.winfo_height()
        self.geom_slot.signal(self, x, y, w, h)

    def highlight(self):
        self.text.config(background="#ffffa2")

    def unhighlight(self):
        self.text.config(background="white")
예제 #31
0
class BlockdiagEditor(object):
    """
    Interactive editor UI for blockdiag
    """
    def __init__(self, diag_method, source, diag_image):
        self.diag_method = diag_method
        self.source = intern(source.encode("utf-8"))
        self.image_format = "PNG"
        self.tmp = NamedTemporaryFile(mode="wb")
        self.root = Tk.Tk()
        self.root.geometry("1024x768")
        self.root.protocol("WM_DELETE_WINDOW", self.quit)

        # Frames
        self.frame = Tk.Frame(self.root)
        self.frame.master.title("blockdiag editor")
        self.frame.pack(fill=Tk.BOTH, expand=1, padx=3, pady=3)
        self.btn_frame = Tk.Frame(self.frame)
        self.btn_frame.pack(fill=Tk.BOTH, padx=3, pady=3)
        self.text_frame = Tk.Frame(self.frame)
        self.text_frame.pack(fill=Tk.BOTH, expand=1, padx=3, pady=3)
        self.image_frame = Tk.Frame(self.frame)
        self.image_frame.pack(fill=Tk.BOTH, expand=1, padx=3, pady=3)
        self.image_frame.grid_rowconfigure(0, weight=1, minsize=0)
        self.image_frame.grid_columnconfigure(0, weight=1, minsize=0)

        # Button
        self.upd_btn = Tk.Button(self.btn_frame,
                                 bd=2,
                                 text="Update Canvas",
                                 command=self.redraw_diag_image)
        self.upd_btn.pack(side=Tk.LEFT)
        self.link_btn = Tk.Button(self.btn_frame,
                                  bd=2,
                                  text="Permanent link",
                                  command=self.open_permanent_link)
        self.link_btn.pack(side=Tk.LEFT)
        self.quit_btn = Tk.Button(self.btn_frame,
                                  bd=2,
                                  text="Quit",
                                  command=self.quit)
        self.quit_btn.pack(side=Tk.LEFT)

        # Text Editor
        self.text = ScrolledText(self.text_frame, wrap=Tk.WORD)
        self.text.pack(fill=Tk.BOTH, expand=1)
        self.text.insert(Tk.END, source)
        self.text.focus_set()
        self.text.bind("<KeyRelease-Control_L>", self.redraw_diag_image)
        self.text.bind("<KeyRelease-Control_R>", self.redraw_diag_image)

        # Image Viewer
        self.image = ImageTk.PhotoImage(file=diag_image)
        self.canvas = Tk.Canvas(self.image_frame,
                                scrollregion=(0, 0, self.image.width(),
                                              self.image.height()))
        self.canvas.grid(row=0, column=0, sticky=Tk.N + Tk.E + Tk.W + Tk.S)
        # Add Scrollbar
        xscr = Tk.Scrollbar(self.image_frame,
                            orient=Tk.HORIZONTAL,
                            command=self.canvas.xview)
        xscr.grid(row=1, column=0, sticky=Tk.E + Tk.W)
        yscr = Tk.Scrollbar(self.image_frame,
                            orient=Tk.VERTICAL,
                            command=self.canvas.yview)
        yscr.grid(row=0, column=1, sticky=(Tk.N, Tk.S))
        self.canvas.config(xscrollcommand=xscr.set, yscrollcommand=yscr.set)
        self.canvas.create_image(0, 0, image=self.image, anchor=Tk.NW)

    def redraw_canvas(self, file_name):
        self.image = ImageTk.PhotoImage(file=file_name)
        self.canvas.config(scrollregion=(0, 0, self.image.width(),
                                         self.image.height()))
        self.canvas.create_image(0, 0, image=self.image, anchor=Tk.NW)

    def redraw_diag_image(self, event=None):
        source = intern(self.text.get("1.0", Tk.END).encode("utf-8"))
        if source is not self.source:
            self.diag_method(source, self.tmp.name, self.image_format)
            if getsize(self.tmp.name) > 0:
                self.redraw_canvas(self.tmp.name)
            self.source = source

    def open_permanent_link(self):
        url = self.make_permanent_link()
        webbrowser.open_new_tab(url)

    def make_permanent_link(self):
        import base64
        source = intern(self.text.get("1.0", Tk.END).encode("utf-8"))
        url = _DIAG_LINK_PREFIX + base64.urlsafe_b64encode(source)
        print url
        return url

    def quit(self):
        self.tmp.close()
        self.root.destroy()
예제 #32
0
파일: tkui.py 프로젝트: v-legoff/accertin
class Tkui(base.BaseUI):
    """
  This is a ui class which handles the complete Tk user interface.
  """
    def __init__(self):
        """ Initializes."""
        base.BaseUI.__init__(self)

        # internal ui queue
        self._event_queue = Queue.Queue()

        # map of session -> (bold, foreground, background)
        self._currcolors = {}

        # ses -> string
        self._unfinishedcolor = {}

        self._viewhistory = 0
        self._do_i_echo = 1

        # holds a map of window names -> window references
        self._windows = {}

        # instantiate all the widgets
        self._tk = Tk()
        self._tk.geometry("800x600")

        self.settitle()

        if os.name == 'posix':
            fnt = tkFont.Font(family="Courier", size=12)
        else:
            fnt = tkFont.Font(family="Fixedsys", size=12)

        self._entry = CommandEntry(self._tk,
                                   self,
                                   fg='white',
                                   bg='black',
                                   insertbackground='yellow',
                                   font=fnt,
                                   insertwidth='2')
        self._entry.pack(side='bottom', fill='both')

        self._topframe = Frame(self._tk)
        self._topframe.pack(side='top', fill='both', expand=1)

        self._txt = ScrolledText(self._topframe,
                                 fg='white',
                                 bg='black',
                                 font=fnt,
                                 height=20)
        self._txt.pack(side='bottom', fill='both', expand=1)

        self._txt.bind("<KeyPress>", self._ignoreThis)
        self._txtbuffer = ScrolledText(self._topframe,
                                       fg='white',
                                       bg='black',
                                       font=fnt,
                                       height=20)
        self._txtbuffer.bind("<KeyPress-Escape>", self.escape)
        self._txtbuffer.bind("<KeyPress>", self._ignoreThis)

        self._entry.focus_set()
        self._initColorTags()
        self.dequeue()

        exported.hook_register("config_change_hook", self.configChangeHandler)
        exported.hook_register("to_user_hook", self.write)

        # FIXME - fix this explanation.  this is just terrible.
        tc = config.BoolConfig(
            "saveinputhighlight", 0, 1,
            "Allows you to change the behavior of the command entry.  When "
            "saveinputhighlight is off, we discard whatever is on the entry "
            "line.  When it is on, we will retain the contents allowing you "
            "to press the enter key to do whatever you typed again.")
        exported.add_config("saveinputhighlight", tc)

        self._quit = 0

    def runui(self):
        global HELP_TEXT
        exported.add_help("tkui", HELP_TEXT)
        exported.write_message("For tk help type \"#help tkui\".")
        exported.add_command("colorcheck", colorcheck_cmd)

        # run the tk mainloop here
        self._tk.mainloop()

    def wantMainThread(self):
        # The tkui needs the main thread of execution so we return
        # a 1 here.
        return 1

    def quit(self):
        if not self._quit:
            self._quit = 1
            self._topframe.quit()

    def dequeue(self):
        qsize = self._event_queue.qsize()
        if qsize > 10:
            qsize = 10

        for i in range(qsize):
            ev = self._event_queue.get_nowait()
            ev.execute(self)

        self._tk.after(25, self.dequeue)

    def settitle(self, title=""):
        """
    Sets the title bar to the Lyntin title plus the given string.

    @param title: the title to set
    @type  title: string
    """
        if title:
            title = constants.LYNTINTITLE + title
        else:
            title = constants.LYNTINTITLE
        self._event_queue.put(_TitleEvent(self._tk, title))

    def removeWindow(self, windowname):
        """
    This removes a NamedWindow from our list of NamedWindows.

    @param windowname: the name of the window to write to
    @type  windowname: string
    """
        if self._windows.has_key(windowname):
            del self._windows[windowname]

    def writeWindow(self, windowname, message):
        """
    This writes to the window named "windowname".  If the window
    does not exist, we spin one off.  It handles ansi text and
    messages just like writing to the main window.

    @param windowname: the name of the window to write to
    @type  windowname: string

    @param message: the message to write to the window
    @type  message: string or Message instance
    """
        self._event_queue.put(_WriteWindowEvent(windowname, message))

    def writeWindow_internal(self, windowname, message):
        if not self._windows.has_key(windowname):
            self._windows[windowname] = NamedWindow(windowname, self, self._tk)
        self._windows[windowname].write(message)

    def _ignoreThis(self, tkevent):
        """ This catches keypresses from the history buffer."""
        # kludge so that ctrl-c doesn't get caught allowing windows
        # users to copy the buffer....
        if tkevent.keycode == 17 or tkevent.keycode == 67:
            return

        self._entry.focus()
        if tkevent.char:
            # we do this little song and dance so as to pass events
            # we don't want to deal with to the entry widget essentially
            # by creating a new event and tossing it in the event list.
            # it only sort of works--but it's the best code we've got
            # so far.
            args = ('event', 'generate', self._entry, "<KeyPress>")
            args = args + ('-rootx', tkevent.x_root)
            args = args + ('-rooty', tkevent.y_root)
            args = args + ('-keycode', tkevent.keycode)
            args = args + ('-keysym', tkevent.keysym)

            self._tk.tk.call(args)

        return "break"

    def pageUp(self):
        """ Handles prior (Page-Up) events."""
        if self._viewhistory == 0:
            self._txtbuffer.pack(side='top', fill='both', expand=1)

            self._viewhistory = 1
            self._txtbuffer.delete("1.0", "end")
            lotofstuff = self._txt.get('1.0', 'end')
            self._txtbuffer.insert('end', lotofstuff)
            for t in self._txt.tag_names():
                taux = None
                tst = 0
                for e in self._txt.tag_ranges(t):
                    if tst == 0:
                        taux = e
                        tst = 1
                    else:
                        tst = 0
                        self._txtbuffer.tag_add(t, str(taux), str(e))

            self._txtbuffer.yview('moveto', '1')
            if os.name != 'posix':
                self._txtbuffer.yview('scroll', '20', 'units')
            self._tk.update_idletasks()
            self._txt.yview('moveto', '1.0')
            if os.name != 'posix':
                self._txt.yview('scroll', '220', 'units')

        else:
            # yscroll up stuff
            self._txtbuffer.yview('scroll', '-15', 'units')

    def pageDown(self):
        """ Handles next (Page-Down) events."""
        if self._viewhistory == 1:
            # yscroll down stuff
            self._txtbuffer.yview('scroll', '15', 'units')

    def escape(self, tkevent):
        """ Handles escape (Escape) events."""
        if self._viewhistory == 1:
            self._txtbuffer.forget()
            self._viewhistory = 0
        else:
            self._entry.clearInput()

    def configChangeHandler(self, args):
        """ This handles config changes including mudecho. """
        name = args["name"]
        newvalue = args["newvalue"]

        if name == "mudecho":
            if newvalue == 1:
                # echo on
                self._do_i_echo = 1
                self._entry.configure(show='')
            else:
                # echo off
                self._do_i_echo = 0
                self._entry.configure(show='*')

    def _yadjust(self):
        """Handles y scrolling after text insertion."""
        self._txt.yview('moveto', '1')
        # if os.name != 'posix':
        self._txt.yview('scroll', '20', 'units')

    def _clipText(self):
        """
    Scrolls the text buffer up so that the new text written at
    the bottom of the text buffer can be seen.
    """
        temp = self._txt.index("end")
        ind = temp.find(".")
        temp = temp[:ind]
        if (temp.isdigit() and int(temp) > 800):
            self._txt.delete("1.0", "100.end")

    def write(self, args):
        """
    This writes text to the text buffer for viewing by the user.

    This is overridden from the 'base.BaseUI'.
    """
        self._event_queue.put(_OutputEvent(args))

    def write_internal(self, args):
        mess = args["message"]
        if type(mess) == types.StringType:
            mess = message.Message(mess, message.LTDATA)

        line = mess.data
        ses = mess.session

        if line == '' or self.showTextForSession(ses) == 0:
            return

        color, leftover = buffer_write(mess, self._txt, self._currcolors,
                                       self._unfinishedcolor)

        if mess.type == message.MUDDATA:
            self._unfinishedcolor[ses] = leftover
            self._currcolors[ses] = color

        self._clipText()
        self._yadjust()

    def convertColor(self, name):
        """
    Tk has this really weird color palatte.  So I switched to using
    color names in most cases and rgb values in cases where I couldn't
    find a good color name.

    This method allows me to specify either an rgb or a color name
    and it converts the color names to rgb.

    @param name: either an rgb value or a name
    @type  name: string

    @returns: the rgb color value
    @rtype: string
    """
        if name.startswith("#"):
            return name

        rgb = self._tk._getints(
            self._tk.tk.call('winfo', 'rgb', self._txt, name))
        rgb = "#%02x%02x%02x" % (rgb[0] / 256, rgb[1] / 256, rgb[2] / 256)
        print name, "converted to: ", rgb

        return rgb

    def _initColorTags(self):
        """ Sets up Tk tags for the text widget (fg/bg/u)."""
        for ck in fg_color_codes.keys():
            color = self.convertColor(fg_color_codes[ck])
            self._txt.tag_config(ck, foreground=color)
            self._txtbuffer.tag_config(ck, foreground=color)

        for ck in bg_color_codes.keys():
            self._txt.tag_config(ck, background=bg_color_codes[ck])
            self._txtbuffer.tag_config(ck, background=bg_color_codes[ck])

        self._txt.tag_config("u", underline=1)
        self._txtbuffer.tag_config("u", underline=1)

    def colorCheck(self):
        """
    Goes through and displays all the combinations of fg and bg
    with the text string involved.  Purely for debugging
    purposes.
    """
        fgkeys = ['30', '31', '32', '33', '34', '35', '36', '37']
        bgkeys = ['40', '41', '42', '43', '44', '45', '46', '47']

        self._txt.insert('end', 'color check:\n')
        for bg in bgkeys:
            for fg in fgkeys:
                self._txt.insert('end', str(fg), (fg, bg))
                self._txt.insert('end', str("b" + fg), ("b" + fg, bg))
            self._txt.insert('end', '\n')

            for fg in fgkeys:
                self._txt.insert('end', str(fg), (fg, "b" + bg))
                self._txt.insert('end', str("b" + fg), ("b" + fg, "b" + bg))
            self._txt.insert('end', '\n')

        self._txt.insert('end', '\n')
        self._txt.insert('end', '\n')
예제 #33
0
                  width=25,
                  height=5,
                  font=('Arial', 13),
                  fg='black',
                  bg='white')
TI.pack(expand=1, padx=5, pady=5, side=RIGHT)

FRL = Frame(FR)
SB = Button(FRL,
            text='SEND',
            width=10,
            height=2,
            font=('Arial', 13, "bold"),
            fg='white',
            bg='DarkOrange',
            command=lambda: send(TI.get("0.0", "end")))
SB.pack(side=TOP)
SB2 = Button(FRL,
             text='REFRESH',
             width=10,
             height=2,
             font=('Arial', 13, "bold"),
             fg='white',
             bg='DarkOrange',
             command=lambda: recieve())
SB2.pack(side=BOTTOM)
FRL.pack(side=LEFT)
FR.pack(side=BOTTOM)

TOPP.config(menu=MB)
TOPP.mainloop()
예제 #34
0
class TextBox:
    def __init__(self):

        self.WIDTH = 600
        self.HEIGHT = 800
        self.FONT = "helvetica"
        self.FONT_SIZE = 12

        # colours specified as RGB fractions
        self.bg_input = [1, 1, 1]
        self.fg_input = [0, 0, 0]

        self.bg_article = [0, 0, 0]
        self.fg_min_article = [0.5, 0.5, 0.5]
        self.fg_max_article = [0.9, 0.9, 0.9]
        self.fg_solution_article = [1, 1, 1]  #[0.3, 0.5, 1.0] #[1, 0.7, 0.4]

        invert = False
        if invert:
            self.bg_input = [1. - v for v in self.bg_input]
            self.fg_input = [1. - v for v in self.fg_input]

            self.bg_article = [1. - v for v in self.bg_article]
            self.fg_min_article = [1. - v for v in self.fg_min_article]
            self.fg_max_article = [1. - v for v in self.fg_max_article]

        self.text = ""  # what is shown in the box
        self.allText = ""  # the text for the entire article
        self.sentences = []  # list of sentences in article
        # dictionary mapping from size to k-hot encoding indicating
        # which sentences are in the summary
        self.solutions = []
        # (not used) how much weight is put on each sentence
        self.weights = []

        self.only_summary = True
        self.summary_size = 1
        self.summary_coherence = 0.0
        self.summary_independence = 0.8

        self.summarizer = Summarizer(parent=self)

        self.root = Tk()

        self.draw(init=True)

        #self.root.mainloop()

    def draw(self, init=False):

        if init:
            # show main article body
            self.tk_article = ScrolledText(self.root)

            # let user paste and enter text
            self.tk_user_input = ScrolledText(self.root)

            self.tk_summary_size_scale = Scale(self.root)
            self.tk_summary_size_scale_label = Label(self.root, text="Length")

            self.tk_summary_coherence_scale = Scale(self.root)
            self.tk_summary_coherence_scale_label = Label(self.root,
                                                          text="Coherence")

            self.tk_summary_independence_scale = Scale(self.root)
            self.tk_summary_independence_scale_label = Label(
                self.root, text="Independence")

            self.tk_toggle_view = Button(self.root,
                                         text="more",
                                         command=self.handleToggleView)
            self.tk_recalculate = Button(self.root,
                                         text="Update",
                                         command=self.handleRecalculate)

            self.root.geometry("%dx%d" % (self.WIDTH, self.HEIGHT))
            self.root.title("QuickReader V4")

            self.tk_article.configure(width=25,
                                      height=6,
                                      bd=0,
                                      highlightthickness=0,
                                      wrap="word",
                                      font=self.FONT)

            self.tk_user_input.configure(width=25,
                                         height=3,
                                         bd=0,
                                         highlightthickness=0,
                                         wrap="word",
                                         font=self.FONT)

            self.tk_summary_size_scale.configure(
                bd=0,
                from_=0,
                to=20,
                orient=HORIZONTAL,
                sliderrelief=FLAT,
                command=lambda event: self.handleSlider(
                    self.tk_summary_size_scale.get()))

            ######
            self.tk_summary_coherence_scale.configure(
                bd=0,
                from_=0,
                to=1,
                orient=HORIZONTAL,
                sliderrelief=FLAT,
                resolution=0.05,
                command=lambda event: self.handleCoherenceSlider(
                    self.tk_summary_coherence_scale.get()))

            self.tk_summary_coherence_scale.set(self.summary_coherence)

            ######
            self.tk_summary_independence_scale.configure(
                bd=0,
                from_=0,
                to=1.5,
                orient=HORIZONTAL,
                sliderrelief=FLAT,
                resolution=0.05,
                command=lambda event: self.handleIndependenceSlider(
                    self.tk_summary_independence_scale.get()))

            self.tk_summary_independence_scale.set(self.summary_independence)

            # set colours
            self.root.configure(background="black")

            self.tk_summary_size_scale.configure(troughcolor="#444444",
                                                 fg="black",
                                                 background="white",
                                                 activebackground="#bbbbbb")

            self.tk_summary_coherence_scale.configure(
                troughcolor="#444444",
                fg="black",
                background="white",
                activebackground="#bbbbbb")

            self.tk_summary_independence_scale.configure(
                troughcolor="#444444",
                fg="black",
                background="white",
                activebackground="#bbbbbb")

            self.tk_article.configure(bg=toHex(self.bg_article),
                                      fg="white",
                                      insertbackground="blue")
            self.tk_article.vbar.configure(bg="white",
                                           width=10,
                                           troughcolor="black")

            self.tk_user_input.configure(bg=toHex(self.bg_input),
                                         fg=toHex(self.fg_input),
                                         insertbackground="blue")
            self.tk_user_input.vbar.configure(bg="white",
                                              width=10,
                                              troughcolor="black")

            self.tk_user_input.focus()
            self.tk_user_input.bind("<KeyRelease-Return>",
                                    (lambda event: self.handleUserInput(
                                        self.tk_user_input.get("0.0", END))))
            self.root.bind("<Configure>", self.resize)

    def setText(self, text, redraw=False):
        self.text = text
        if redraw: self.updateArticleInfo()

    def setSentences(self, sentences, redraw=False):
        self.sentences = sentences
        if redraw: self.updateArticleInfo()

    def setSolutions(self, solutions, redraw=False):
        self.solutions = solutions
        if redraw: self.updateArticleInfo()

    def setWeights(self, weights, redraw=False):
        self.weights = weights
        if redraw: self.updateArticleInfo()

    def handleToggleView(self):

        print("View toggle!")

        self.only_summary = not self.only_summary

        if self.only_summary:
            self.tk_toggle_view.configure(text="more")
        else:
            self.tk_toggle_view.configure(text="less")

        self.updateSummary()

    def handleRecalculate(self):
        print("Update!")

        self.handleUserInput(self.allText)

    def handleSlider(self, value):

        print("Slider:", value)

        self.summary_size = value

        self.updateSummary()

    def handleCoherenceSlider(self, value):

        print("Coherence Slider:", value)

        self.summary_coherence = value

        #self.updateSummary()

    def handleIndependenceSlider(self, value):

        print("Independence Slider:", value)

        self.summary_independence = value

        #self.updateSummary()

    def updateSummary(self):

        l = self.summary_size

        if self.only_summary and l != 0:
            self.setText('\n\n'.join([
                self.sentences[i] for i in range(len(self.sentences))
                if self.solutions[l][i] == 1
            ]))
        else:
            self.setText(self.allText, redraw=False)

        self.updateArticleInfo()

        self.setWeights([0. for _ in self.sentences], redraw=True)

        self.tk_article.yview_moveto(0)  #vbar.set(0, 0) #configure(jump=0)

    def handleUserInput(self, inStr):
        self.tk_user_input.delete("0.0", END)

        if inStr.strip() == "": return

        text = inStr

        text = ''.join([ch for ch in text if ord(ch) < 128])

        self.setText(text, redraw=False)
        self.setSolutions([], redraw=False)
        self.setWeights([], redraw=True)

        text, sentences, solutions = self.summarizer.summarize(
            text,
            coherence_weight=self.summary_coherence,
            independence_weight=self.summary_independence,
            size_weight=1.,
            beam_width=3,
            hard_size_limit=None)

        self.allText = text
        self.sentences = sentences
        self.solutions = solutions

        self.solutions[0] = [1. for _ in sentences]

        # get max length for summary
        max_len = max(solutions.keys())
        set_len = min(max_len, 3)
        self.tk_summary_size_scale.configure(from_=0, to=max_len)
        self.tk_summary_size_scale.set(set_len)
        self.summary_size = set_len

        # text: all the text in one long string
        # sentences: the text split up into a list of sentences
        # solution: dictionary mapping summary size to a one-hot vector over the sentences, indicating
        #   which sentences are included in the summarization

        # the text should be the same, but update it anyways since it needs to contain the
        #  exact same stuff as the sentences

        self.updateSummary()

        #self.updateArticleInfo()

    def resize(self, event=[]):
        LINEH = 20.0

        pixelX = self.root.winfo_width()
        pixelY = self.root.winfo_height()

        bf = 5  # buffer size in pixels

        # update find_icon, wiki_icon, and graph_icon

        # set toggle and recalculate button
        toggleW = 50
        toggleH = 35 * 1
        self.tk_toggle_view.place(x=pixelX - toggleW,
                                  y=0,
                                  width=toggleW,
                                  height=toggleH)

        updateW = 50
        updateH = 35 * 2
        self.tk_recalculate.place(x=pixelX - updateW,
                                  y=toggleH,
                                  width=updateW,
                                  height=updateH)

        buttonH = toggleH + updateH

        labelW = 90

        # set position of size scale
        scaleW = pixelX - updateW - labelW
        scaleH = 35
        self.tk_summary_size_scale.place(x=labelW,
                                         y=0,
                                         width=scaleW,
                                         height=scaleH)

        self.tk_summary_size_scale_label.place(x=0,
                                               y=0,
                                               width=labelW,
                                               height=scaleH)

        # set position of coherence scale
        coherenceW = pixelX - updateW - labelW
        coherenceH = 35
        self.tk_summary_coherence_scale.place(x=labelW,
                                              y=scaleH,
                                              width=scaleW,
                                              height=scaleH)

        self.tk_summary_coherence_scale_label.place(x=0,
                                                    y=scaleH,
                                                    width=labelW,
                                                    height=coherenceH)

        # set position of independence scale
        independenceW = pixelX - updateW - labelW
        independenceH = 35
        self.tk_summary_independence_scale.place(x=labelW,
                                                 y=scaleH + coherenceH,
                                                 width=scaleW,
                                                 height=scaleH)

        self.tk_summary_independence_scale_label.place(x=0,
                                                       y=scaleH + coherenceH,
                                                       width=labelW,
                                                       height=independenceH)

        # update user input
        inputW = pixelX
        inputH = int(3.0 * LINEH)
        self.tk_user_input.place(x=0,
                                 y=pixelY - inputH,
                                 width=inputW,
                                 height=inputH)

        # update article
        articleW = pixelX
        articleH = pixelY - inputH - scaleH - coherenceH - independenceH
        self.tk_article.place(x=0,
                              y=scaleH + coherenceH + independenceH,
                              width=articleW,
                              height=articleH)

    def updateArticleInfo(self):

        self.articleClear()

        self.articleCat(self.text)

        if self.weights != []:
            self.articleColour()

        self.root.update()

    def articleClear(self):
        self.tk_article.delete("1.0", END)
        self.tk_article.update()

        self.root.update()

        return

    def articleCat(self, inStr):

        self.tk_article.insert(END, inStr)

        self.tk_article.yview(END)

    def articleColour(self):
        '''
		solution = self.solutions[self.summary_size]

		allText = self.text #self.tk_article.get('1.0', 'end-1c')

		# make sure weights are normalised
		maxW = max(self.weights)
		minW = min(self.weights)

		weights = self.weights
		if maxW != minW:
			weights = [(v-minW)/(maxW-minW) for v in self.weights]

		for i in range(len(self.sentences)):
			if self.only_summary and solution[i] != 1.: continue

			s = self.sentences[i]
			if len(s.strip()) == 0:

				continue

			tagNameA = ''.join([random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10)])
			L_Size = 12 # if solution[i] == 1 else 10
			
			L_Colour = blend(self.fg_min_article, self.fg_max_article, weights[i])
			L_Colour = self.fg_solution_article if solution[i] == 1 else L_Colour

			countVar = StringVar(self.root)
			pos = self.tk_article.search(s, "1.0", stopindex="end", count=countVar)

			self.tk_article.tag_add(tagNameA, pos, "{} + {}c".format(pos, countVar.get()))

			bolding = "normal" #"bold" if self.solution[i] == 1 else "normal" #
			font = (self.FONT, L_Size, bolding)
			self.tk_article.tag_config(tagNameA, foreground=toHex(L_Colour), font=font)#self.FONT+' %s'%(L_Size))

		
		self.root.update()
		'''

        solution = self.solutions[self.summary_size]

        allText = self.text  #self.tk_article.get('1.0', 'end-1c')

        #print("=========")
        for i in range(len(self.sentences)):
            if self.only_summary and solution[i] != 1.: continue

            s = self.sentences[i]
            #if len(s.strip()) == 0:
            #	continue

            #print("- ", s)

            tagNameA = ''.join([
                random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(10)
            ])
            L_Size = self.FONT_SIZE  # if solution[i] == 1 else 10

            L_Colour = self.fg_solution_article if solution[
                i] == 1 else self.fg_min_article
            #print("\t", L_Colour)

            countVar = StringVar(self.root)
            pos = self.tk_article.search(s,
                                         "1.0",
                                         stopindex="end",
                                         count=countVar)

            self.tk_article.tag_add(tagNameA, pos,
                                    "{} + {}c".format(pos, countVar.get()))

            bolding = "normal"  #"bold" if self.solution[i] == 1 else "normal" #
            font = (self.FONT, L_Size, bolding)
            self.tk_article.tag_config(tagNameA,
                                       foreground=toHex(L_Colour),
                                       font=font)  #self.FONT+' %s'%(L_Size))

        self.root.update()
예제 #35
0
파일: tkui.py 프로젝트: v-legoff/accertin
class Tkui(base.BaseUI):
    """
  This is a ui class which handles the complete Tk user interface.
  """

    def __init__(self):
        """ Initializes."""
        base.BaseUI.__init__(self)

        # internal ui queue
        self._event_queue = Queue.Queue()

        # map of session -> (bold, foreground, background)
        self._currcolors = {}

        # ses -> string
        self._unfinishedcolor = {}

        self._viewhistory = 0
        self._do_i_echo = 1

        # holds a map of window names -> window references
        self._windows = {}

        # instantiate all the widgets
        self._tk = Tk()
        self._tk.geometry("800x600")

        self.settitle()

        if os.name == "posix":
            fnt = tkFont.Font(family="Courier", size=12)
        else:
            fnt = tkFont.Font(family="Fixedsys", size=12)

        self._entry = CommandEntry(
            self._tk, self, fg="white", bg="black", insertbackground="yellow", font=fnt, insertwidth="2"
        )
        self._entry.pack(side="bottom", fill="both")

        self._topframe = Frame(self._tk)
        self._topframe.pack(side="top", fill="both", expand=1)

        self._txt = ScrolledText(self._topframe, fg="white", bg="black", font=fnt, height=20)
        self._txt.pack(side="bottom", fill="both", expand=1)

        self._txt.bind("<KeyPress>", self._ignoreThis)
        self._txtbuffer = ScrolledText(self._topframe, fg="white", bg="black", font=fnt, height=20)
        self._txtbuffer.bind("<KeyPress-Escape>", self.escape)
        self._txtbuffer.bind("<KeyPress>", self._ignoreThis)

        self._entry.focus_set()
        self._initColorTags()
        self.dequeue()

        exported.hook_register("config_change_hook", self.configChangeHandler)
        exported.hook_register("to_user_hook", self.write)

        # FIXME - fix this explanation.  this is just terrible.
        tc = config.BoolConfig(
            "saveinputhighlight",
            0,
            1,
            "Allows you to change the behavior of the command entry.  When "
            "saveinputhighlight is off, we discard whatever is on the entry "
            "line.  When it is on, we will retain the contents allowing you "
            "to press the enter key to do whatever you typed again.",
        )
        exported.add_config("saveinputhighlight", tc)

        self._quit = 0

    def runui(self):
        global HELP_TEXT
        exported.add_help("tkui", HELP_TEXT)
        exported.write_message('For tk help type "#help tkui".')
        exported.add_command("colorcheck", colorcheck_cmd)

        # run the tk mainloop here
        self._tk.mainloop()

    def wantMainThread(self):
        # The tkui needs the main thread of execution so we return
        # a 1 here.
        return 1

    def quit(self):
        if not self._quit:
            self._quit = 1
            self._topframe.quit()

    def dequeue(self):
        qsize = self._event_queue.qsize()
        if qsize > 10:
            qsize = 10

        for i in range(qsize):
            ev = self._event_queue.get_nowait()
            ev.execute(self)

        self._tk.after(25, self.dequeue)

    def settitle(self, title=""):
        """
    Sets the title bar to the Lyntin title plus the given string.

    @param title: the title to set
    @type  title: string
    """
        if title:
            title = constants.LYNTINTITLE + title
        else:
            title = constants.LYNTINTITLE
        self._event_queue.put(_TitleEvent(self._tk, title))

    def removeWindow(self, windowname):
        """
    This removes a NamedWindow from our list of NamedWindows.

    @param windowname: the name of the window to write to
    @type  windowname: string
    """
        if self._windows.has_key(windowname):
            del self._windows[windowname]

    def writeWindow(self, windowname, message):
        """
    This writes to the window named "windowname".  If the window
    does not exist, we spin one off.  It handles ansi text and
    messages just like writing to the main window.

    @param windowname: the name of the window to write to
    @type  windowname: string

    @param message: the message to write to the window
    @type  message: string or Message instance
    """
        self._event_queue.put(_WriteWindowEvent(windowname, message))

    def writeWindow_internal(self, windowname, message):
        if not self._windows.has_key(windowname):
            self._windows[windowname] = NamedWindow(windowname, self, self._tk)
        self._windows[windowname].write(message)

    def _ignoreThis(self, tkevent):
        """ This catches keypresses from the history buffer."""
        # kludge so that ctrl-c doesn't get caught allowing windows
        # users to copy the buffer....
        if tkevent.keycode == 17 or tkevent.keycode == 67:
            return

        self._entry.focus()
        if tkevent.char:
            # we do this little song and dance so as to pass events
            # we don't want to deal with to the entry widget essentially
            # by creating a new event and tossing it in the event list.
            # it only sort of works--but it's the best code we've got
            # so far.
            args = ("event", "generate", self._entry, "<KeyPress>")
            args = args + ("-rootx", tkevent.x_root)
            args = args + ("-rooty", tkevent.y_root)
            args = args + ("-keycode", tkevent.keycode)
            args = args + ("-keysym", tkevent.keysym)

            self._tk.tk.call(args)

        return "break"

    def pageUp(self):
        """ Handles prior (Page-Up) events."""
        if self._viewhistory == 0:
            self._txtbuffer.pack(side="top", fill="both", expand=1)

            self._viewhistory = 1
            self._txtbuffer.delete("1.0", "end")
            lotofstuff = self._txt.get("1.0", "end")
            self._txtbuffer.insert("end", lotofstuff)
            for t in self._txt.tag_names():
                taux = None
                tst = 0
                for e in self._txt.tag_ranges(t):
                    if tst == 0:
                        taux = e
                        tst = 1
                    else:
                        tst = 0
                        self._txtbuffer.tag_add(t, str(taux), str(e))

            self._txtbuffer.yview("moveto", "1")
            if os.name != "posix":
                self._txtbuffer.yview("scroll", "20", "units")
            self._tk.update_idletasks()
            self._txt.yview("moveto", "1.0")
            if os.name != "posix":
                self._txt.yview("scroll", "220", "units")

        else:
            # yscroll up stuff
            self._txtbuffer.yview("scroll", "-15", "units")

    def pageDown(self):
        """ Handles next (Page-Down) events."""
        if self._viewhistory == 1:
            # yscroll down stuff
            self._txtbuffer.yview("scroll", "15", "units")

    def escape(self, tkevent):
        """ Handles escape (Escape) events."""
        if self._viewhistory == 1:
            self._txtbuffer.forget()
            self._viewhistory = 0
        else:
            self._entry.clearInput()

    def configChangeHandler(self, args):
        """ This handles config changes including mudecho. """
        name = args["name"]
        newvalue = args["newvalue"]

        if name == "mudecho":
            if newvalue == 1:
                # echo on
                self._do_i_echo = 1
                self._entry.configure(show="")
            else:
                # echo off
                self._do_i_echo = 0
                self._entry.configure(show="*")

    def _yadjust(self):
        """Handles y scrolling after text insertion."""
        self._txt.yview("moveto", "1")
        # if os.name != 'posix':
        self._txt.yview("scroll", "20", "units")

    def _clipText(self):
        """
    Scrolls the text buffer up so that the new text written at
    the bottom of the text buffer can be seen.
    """
        temp = self._txt.index("end")
        ind = temp.find(".")
        temp = temp[:ind]
        if temp.isdigit() and int(temp) > 800:
            self._txt.delete("1.0", "100.end")

    def write(self, args):
        """
    This writes text to the text buffer for viewing by the user.

    This is overridden from the 'base.BaseUI'.
    """
        self._event_queue.put(_OutputEvent(args))

    def write_internal(self, args):
        mess = args["message"]
        if type(mess) == types.StringType:
            mess = message.Message(mess, message.LTDATA)

        line = mess.data
        ses = mess.session

        if line == "" or self.showTextForSession(ses) == 0:
            return

        color, leftover = buffer_write(mess, self._txt, self._currcolors, self._unfinishedcolor)

        if mess.type == message.MUDDATA:
            self._unfinishedcolor[ses] = leftover
            self._currcolors[ses] = color

        self._clipText()
        self._yadjust()

    def convertColor(self, name):
        """
    Tk has this really weird color palatte.  So I switched to using
    color names in most cases and rgb values in cases where I couldn't
    find a good color name.

    This method allows me to specify either an rgb or a color name
    and it converts the color names to rgb.

    @param name: either an rgb value or a name
    @type  name: string

    @returns: the rgb color value
    @rtype: string
    """
        if name.startswith("#"):
            return name

        rgb = self._tk._getints(self._tk.tk.call("winfo", "rgb", self._txt, name))
        rgb = "#%02x%02x%02x" % (rgb[0] / 256, rgb[1] / 256, rgb[2] / 256)
        print name, "converted to: ", rgb

        return rgb

    def _initColorTags(self):
        """ Sets up Tk tags for the text widget (fg/bg/u)."""
        for ck in fg_color_codes.keys():
            color = self.convertColor(fg_color_codes[ck])
            self._txt.tag_config(ck, foreground=color)
            self._txtbuffer.tag_config(ck, foreground=color)

        for ck in bg_color_codes.keys():
            self._txt.tag_config(ck, background=bg_color_codes[ck])
            self._txtbuffer.tag_config(ck, background=bg_color_codes[ck])

        self._txt.tag_config("u", underline=1)
        self._txtbuffer.tag_config("u", underline=1)

    def colorCheck(self):
        """
    Goes through and displays all the combinations of fg and bg
    with the text string involved.  Purely for debugging
    purposes.
    """
        fgkeys = ["30", "31", "32", "33", "34", "35", "36", "37"]
        bgkeys = ["40", "41", "42", "43", "44", "45", "46", "47"]

        self._txt.insert("end", "color check:\n")
        for bg in bgkeys:
            for fg in fgkeys:
                self._txt.insert("end", str(fg), (fg, bg))
                self._txt.insert("end", str("b" + fg), ("b" + fg, bg))
            self._txt.insert("end", "\n")

            for fg in fgkeys:
                self._txt.insert("end", str(fg), (fg, "b" + bg))
                self._txt.insert("end", str("b" + fg), ("b" + fg, "b" + bg))
            self._txt.insert("end", "\n")

        self._txt.insert("end", "\n")
        self._txt.insert("end", "\n")
예제 #36
0
파일: cv7seg.py 프로젝트: 12019/cv7seg.py
class LoggingUI(TimedFrame):
    u'''ロギング用UI'''
    def __init__(self, *args, **kwargs):
        TimedFrame.__init__(self, *args, **kwargs)
        self.pack()
        self.init()
        self.startTimer()
    
    def init(self):
        if not config.normalize.points:
            self._label = tk.Label(self, text = u'まだ正規化が済んでいません。\n正規化を行ってください。')
            self._label.pack()
            return

        if not config.template.images or len(config.template.images) < 10 or not all(config.template.images):
            self._label = tk.Label(self, text = u'まだ学習が済んでいません。\n学習を行ってください。')
            self._label.pack()
            return
        
        # テンプレートの読み込み
        self.loadTemplates()
        
        # カメラの準備
        self._camera = cv.CaptureFromCAM(config.camera.id)
        
        # 左側UI
        frame1 = tk.Frame(self)
        frame1.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
        
        # カメラ画像表示用Canvasなどの準備
        self._cvmat = None
        self._image = tk.PhotoImage(width = config.canvas.width, height = config.canvas.height)
        self._canvas = tk.Canvas(frame1, width = config.canvas.width, height = config.canvas.height)
        self._canvas.create_image(config.canvas.width / 2, config.canvas.height / 2, image = self._image, tags = 'image')
        self._canvas.pack(expand = True, fill = tk.BOTH)
        
        # ボタン
        self._main_button = tk.Button(frame1)
        self._main_button.pack(side = tk.LEFT)
        self.logStop()
        self._reset_button = tk.Button(frame1, text = u'リセット', command = self.reset)
        self._reset_button.pack(side = tk.RIGHT)
        
        # 生データ表示領域
        self._textarea = ScrolledText(self, width = 6, height = 18)
        self._textarea.pack(side = tk.LEFT, expand = True)
        
        # 右側UI
        frame2 = tk.Frame(self)
        frame2.pack(side = tk.LEFT, expand = True, fill = tk.BOTH)
        
        # ログデータ表示領域
        self._graph = tk.Canvas(frame2, width = config.canvas.width, height = config.canvas.height, bg = 'white')
        self._graph.pack(expand = True, fill = tk.BOTH)
        self._bar_graph = BarGraph(A(width = config.canvas.width, height = config.canvas.height), config.logging.graph_max_count)
        
        # ボタン
        self._out_button = tk.Button(frame2, text = u'生データをコピー', command = self.datacopy)
        self._out_button.pack(side = tk.LEFT)
        self._gchart_button = tk.Button(frame2, text = u'Google Chart URLをコピー', command = self.gchart)
        self._gchart_button.pack(side = tk.RIGHT)
        
        # 画像をフィルタするための変数
        self._clip_rect, self._perspective_points = Points2Rect(config.normalize.points)
        
        # ロギング開始、停止のフラグ
        self._take_log = False
        
        # ログ
        self._log = []
        
        # カメラ画像の更新を1秒間隔にする
        self.addTiming(self.showImage, 1)
    
    def setValue(self, value):
        if value is None: value = 0
        self._bar_graph.setValue(value)
        
        self._graph.delete('bar')
        for bar in self._bar_graph.getAllBars():
            self._graph.create_rectangle(
                bar.p1.x, bar.p1.y,
                bar.p2.x, bar.p2.y,
                fill = 'green', stipple = 'gray25',
                tags = 'bar'
            )
    
    def loadTemplates(self):
        u'''テンプレート画像の読み込み'''
        self._templates = []
        for i, cvimageinfo in enumerate(config.template.images):
            cvmat = cv.CreateMatHeader(cvimageinfo.rows, cvimageinfo.cols, cvimageinfo.type)
            cv.SetData(cvmat, cvimageinfo.data)
            self._templates.append(A(
                image = cv.GetImage(cvmat),
                number = i,
                result = None,
            ))
    
    def showImage(self):
        u'''カメラ画像の表示'''
        captured = cv.QueryFrame(self._camera)
        self._cvmat = self.filter(captured)
        self._image = CvMat2TkImage(self._cvmat)
        self._canvas.itemconfigure('image', image = self._image)
        if self._take_log:
            self.logging()
    
    def logging(self):
        u'''ログを取る'''
        target = self._cvmat
        digits_sieve = DigitsSieve()
        for template in self._templates:
            if not template.result:
                # マッチング結果保存用領域の準備
                template.result = cv.CreateImage(
                    (target.width - template.image.width + 1, target.height - template.image.height + 1),
                    cv.IPL_DEPTH_32F, 1,
                )
            
            cv.MatchTemplate(target, template.image, template.result, config.logging.match_method)

            # 数値の読み取り
            minVal, maxVal, minLoc, maxLoc = cv.MinMaxLoc(template.result)
            while maxVal > config.logging.match_threshold:
                # 検出された数値情報の保持
                digits_sieve.push(A(
                    number = template.number,
                    x = maxLoc[0],
                    y = maxLoc[1],
                    width = template.image.width,
                    height = template.image.height,
                    score = maxVal,
                ))
                
                # 現在の位置周辺のスコアをクリアし、次にスコアの高い位置を取得する
                SetReal2DAround(template.result, maxLoc, config.logging.match_exclusion_size, 0.0)
                minVal, maxVal, minLoc, maxLoc = cv.MinMaxLoc(template.result)
        
        value = digits_sieve.getValue()
        if value is not None:
            self._log.append(value)
            self.setValue(value)
            self._textarea.insert(tk.END, '%d\n' % value)
            self._textarea.see(tk.END)

    def logStart(self):
        u'''ロギングを開始する'''
        self._main_button.configure(text = u'ストップ', command = self.logStop)
        self._take_log = True
        
    def logStop(self):
        u'''ロギングを停止する'''
        self._main_button.configure(text = u'スタート', command = self.logStart)
        self._take_log = False
    
    def reset(self):
        u'''リセット'''
        self._bar_graph.init()
        self.setValue(0)
        self._log = []
        self._textarea.delete('1.0', tk.END)
    
    def datacopy(self):
        u'''生データをクリップボードにコピーする'''
        text = self._textarea.get('1.0', tk.END)
        self.clipboard_clear()
        self.clipboard_append(text)
    
    def gchart(self):
        u'''Google Chart API用のURLをクリップボードにコピーする'''
        if  self._log \
            and len(self._log) > 0 \
            and max(self._log) > 0:
                
                unit = float(4095) / max(self._log)
                url = gExtendedUrl(
                    map(lambda x: unit * x, self._log),
                    cht = 'bvs', # 棒グラフ
                    chxt = 'y', # y軸の目盛り表示
                    chxr = '0,0,%d' % max(self._log), # y軸の最小最大値
                    chg = '0,10,3,2', # 補助線
                    chbh = '%d,1' % (480 / len(self._log) - 1), # 棒グラフの棒の幅
                )
                self.clipboard_clear()
                self.clipboard_append(url)
        
    def filter(self, cvmat):
        u'''画像をフィルタする'''
        # サイズ調整
        thumbnail = cv.CreateMat(config.canvas.height, config.canvas.width, cv.CV_8UC3)
        cv.Resize(cvmat, thumbnail)
        return NormalizeImage(thumbnail, self._clip_rect, self._perspective_points)
예제 #37
0
class myPanel(tkinter.Tk):
    def __init__(self):
        tkinter.Tk.__init__(self, 'lsx')

        try:
            self.ss = self.clipboard_get()
        except:
            self.ss = ''
        self.cnt = 0
        self.slices = paragraph(self.ss, qrlen)
        self.string = None

        if not os.path.exists('config.ini'):
            x = - 100 + 0.2 * self.winfo_screenwidth() # 100: 补偿初始Tk界面为200x200
            y = - 100 + 0.7 * self.winfo_screenheight()
            xy = '+%d+%d'%(x,y)
            with open('config.ini','w') as f:
                f.write(xy)
        with open('config.ini','r') as f:
            xy = f.read()
        self.geometry(xy)
        self.minsize(450,206)

        self.qrc = tkinter.Label(self)
        self.ent = ScrolledText(self, width=1, height=15)
        self.ent.insert(1.0, self.ss)
        self.ent.mark_set('insert','0.0') # 程序首次运行时不使用see函数,否则会有未知原因半行内容沉没在Text窗体上面一点点
        self.ent.focus()

        text = self.slices[self.cnt]
        basic = (len(self.slices),len(self.ss))
        info = 'Page: %s, Length: %s'%basic
        if zh_cn:
            info = '共%s页, %s字'%basic

        self.withdraw() # withdraw/deiconify 阻止页面闪烁
        self.update_idletasks()
        self.ent.pack(padx=2, pady=2, fill='both', expand=True, side='right') # RIGHT为了在Label隐藏再显示后所在位置一致
        self.qrc.pack()
        self.setQrcode(text, info)
        self.deiconify()

        self.qrc.bind('<Button-2>',self.onExit)
        self.qrc.bind('<Button-1>',self.fliping)
        self.qrc.bind('<Button-3>',self.fliping)
        self.qrc.bind('<Double-Button-1>',self.setting)
        self.qrc.bind('<Double-ButtonRelease-3>',self.openFile) # 没有Release会在窗口打开之后的鼠标抬起时唤起右键菜单

        self.ent.bind('<Escape>',self.onExit)
        self.ent.bind('<F1>',self.openFile)
        self.ent.bind('<F2>',self.fliping)
        self.ent.bind('<F3>',self.fliping)
        self.ent.bind('<F4>',self.setting)

        self.ent.bind('<KeyRelease>',self.refresh)
        self.ent.bind('<ButtonRelease-1>',self.selected)
        self.bind('<Destroy>',lambda evt:self.onExit(evt,close=True))

    def setQrcode(self, string, info):
        if self.string != string:
            self.string = string
            if string == '':
                self.qrc.forget()
            else:
                global img
                img = qrmake(string)
                self.qrc.config(image=img)
                self.qrc.pack()
        log(string, info)
        self.title('Text Helper v1.06 (%s)'%info)
        if zh_cn:
            self.title('文本助手v1.06 (%s)'%info)

    def refresh(self, evt):
        if evt.keysym in ['Control_L', 'Return', 'BackSpace']:
            ss2 = self.ent.get('0.0', 'end')[:-1]
            if self.ss != ss2:
                self.ss = ss2
                self.cnt = 0
                self.slices = paragraph(self.ss, qrlen)

            text = self.slices[self.cnt]
            basic = (len(self.slices),len(self.ss))
            info = 'Page: %s, Length: %s'%basic
            if zh_cn:
                info = '共%s页, %s字'%basic
            self.setQrcode(text, info)

    def fliping(self, evt):
        if evt.num == 1 or evt.keysym == 'F3':
            self.cnt = min(self.cnt+1,len(self.slices)-1)
        else:
            self.cnt = max(self.cnt-1,0)
        cur1 = getIndex(''.join(self.slices[:self.cnt]))
        cur2 = getIndex(''.join(self.slices[:self.cnt+1]))
        self.setCursor(cur1, cur2)

        text = self.slices[self.cnt]
        basic = (self.cnt+1,len(self.slices),len(text),len(self.ss))
        info = 'Page: %s/%s, Sel: %s/%s'%basic
        if zh_cn:
            info = '第%s/%s页, 共%s/%s字'%basic
        self.setQrcode(text, info)

    def selected(self, evt):
        if self.ent.tag_ranges('sel'):
            text = self.ent.selection_get()
            info = 'Sel: %s/%s'%(len(text),len(self.ss))
            if zh_cn:
                info = '选中%s/%s字'%(len(text),len(self.ss))
            self.setQrcode(text, info)

    def setCursor(self, cur1, cur2):
        self.ent.mark_set('insert', cur1)
        self.ent.tag_remove('sel','0.0','end')
        self.ent.tag_add('sel',cur1,cur2)
        self.ent.see(cur1)

    def setting(self, evt):
        max_page = len(self.slices)
        num = tkinter.simpledialog.askinteger('Goto','Go to page (1-%s):'%max_page, initialvalue=self.cnt+1)
        self.ent.focus()
        if num:
            self.cnt = max(1,min(max_page,num)) - 1

            text = self.slices[self.cnt]
            basic = (self.cnt+1,len(self.slices),len(text),len(self.ss))
            info = 'Page: %s/%s, Sel: %s/%s'%basic
            if zh_cn:
                info = '第%s/%s页, 共%s/%s字'%basic
            self.setQrcode(text, info)

    def openFile(self, evt):
        path = tkinter.filedialog.askopenfilename()
        if path != '':
            filename = os.path.basename(path)
            with open(path,'rb') as f:
                s = f.read()
            try:
                try:
                    res = s.decode()
                except:
                    try:
                        res = s.decode('gbk')
                    except:
                        raise
            except:
                s = base64.urlsafe_b64encode(filename.encode()+b'\n'+s).decode()
                total = int((len(s)-1)/(qrlen-10)+1)
                res = ''
                for i in range(total):
                    res += '%04d%04d.%s,'%(total, i+1, s[(qrlen-10)*i:(qrlen-10)*(i+1)])

            self.ss = res
            self.cnt = 0
            self.slices = paragraph(self.ss, qrlen)
            self.ent.delete(1.0, 'end')
            self.ent.insert(1.0, res)

            text = self.slices[self.cnt]
            basic = (len(self.slices),len(self.ss))
            info = 'Page: %s, Length: %s'%basic
            if zh_cn:
                info = '共%s页, %s字'%basic
            self.setQrcode(text, info)

    def onExit(self, evt, close=False):
        xy = '+%d+%d'%(self.winfo_x(),self.winfo_y())
        with open('config.ini','w') as f:
            f.write(xy)
        if not close:
            self.destroy()
예제 #38
0
파일: SourceEditor.py 프로젝트: sofayam/m3
class SourceEditor:
    def __init__(self,central,name,bodyTopNode,specTopNode):
        self.dirty = False
        self.central = central
        self.name = name
        self.toplevel = Toplevel()
        self.toplevel.title(name)
        self.pw = Pmw.PanedWidget(self.toplevel, orient='vertical')

        specpane = self.pw.add("spec")
        bodypane = self.pw.add("body")
        self.specText = ScrolledText(specpane,font=("monaco",10),height=5,background=Colors.background)
        self.specText.pack(expand=YES,fill=BOTH)
        self.bodyText = ScrolledText(bodypane,font=("monaco",10),height=15,background=Colors.background)
        self.bodyText.pack(expand=YES,fill=BOTH)        
        self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText}
        self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode}
        Widget.bind(self.bodyText,'<Any-KeyPress>',self.setDirty)
        Widget.bind(self.specText,'<Any-KeyPress>',self.setDirty)
        self.popup = Menu(self.toplevel,tearoff=0)
        self.popup.add_command(label="Dismiss", command=self.nothing)
        self.popup.add_command(label="Diagram", command=self.goDiagram)
        self.popup.add_command(label="Abort", command=self.abort)
        self.popup.add_command(label="Accept", command=self.accept)
        self.popup.add_command(label="Recolor", command=self.recolor)        
        def popupMenu(event):
            self.popup.post(event.x_root,event.y_root)
        self.toplevel.bind('<Button-3>', popupMenu)
        self.pw.pack(expand=YES,fill=BOTH)
        self.toplevel.protocol("WM_DELETE_WINDOW",self.central.doQuit)
        self.refresh()
    def nothing(self): pass
    def setClean(self):
        if self.dirty:
            self.dirty = False
            self.toplevel.title(self.name)
            self.central.unlockGraphics(self.name)
    def setDirty(self,event):
        if event.keysym in ['Shift_L', 'Shift_R', 'Alt_L', 'Alt_R', 'Win_L', 'Win_R']:
            return 
        if not self.dirty:
            self.dirty = True
            self.toplevel.title(self.name+"*")
            self.central.lockGraphics(self.name)
    def abort(self):
        if self.dirty:
            self.setClean()
            self.setSource()
    def getSource(self):
        return (self.specText.get("1.0",END),
                self.bodyText.get("1.0",END))
    def accept(self):
        if self.dirty:
            self.bodyText.config(cursor="watch")
            self.specText.config(cursor="watch")
            self.bodyText.update() # so that the cursor will show
            self.specText.update()
            self.central.update(self.name, self.specText.get("1.0",END),
                                self.bodyText.get("1.0",END),saveOutput=False)
            self.central.setChanged(self.name)
            self.setClean()
            self.bodyText.config(cursor="xterm")
            self.specText.config(cursor="xterm")
    def recolor(self):
        stext,btext = self.getSource()
        self.colorize(self.specText,stext)
        self.colorize(self.bodyText,btext)
    def show(self, specTopNode, bodyTopNode):
        self.nodeMap = {bodyTopNode: self.bodyText, specTopNode: self.specText}
        self.textMap = {self.bodyText: bodyTopNode, self.specText: specTopNode}        
        self.setSource()
    def setSource(self):
        oldScroll,dummy = self.specText.yview()
        self.specText.delete('1.0',END)
        stext = self.textMap[self.specText].regen(forDisplay=True)
        self.specText.insert(END,stext)
        self.colorize(self.specText,stext)
        self.specText.yview("moveto", oldScroll)

        oldScroll,dummy = self.bodyText.yview()
        self.bodyText.delete('1.0',END)
        btext = self.textMap[self.bodyText].regen(forDisplay=True)
        self.bodyText.insert(END,btext)
        self.colorize(self.bodyText,btext)
        self.bodyText.yview("moveto", oldScroll)
    def colorize(self,textWidget,progText):
        def colorizeSub(color,wordList):
            textWidget.tag_remove(color,'1.0',END)
            textWidget.tag_configure(color,foreground=color)
            keywords = re.compile(r'\b(' + string.join(wordList,"|") + r')\b')
            iter = keywords.finditer(progText)
            for match in iter:
                start, stop = match.span()
                textWidget.tag_add(color,"1.0+%dc" % start, "1.0+%dc" % stop)
        textWidget.tag_remove('hilite','1.0',END)
        colorizeSub(Colors.keyword, Lexis.keywords)
        colorizeSub(Colors.reserved, Lexis.reservedWords)
    def refresh(self):
        self.setSource()
    def goDiagram(self):
        self.central.showDiagram(self.name)
    def showSource(self,node):
        self.makeTop()
        topNode = node.getTopNode()
        self.text = self.nodeMap[topNode]
        self.text.tag_remove('hilite','1.0',END)
        start, end =  node.lineRange()
        startIdx = '%d.0' % int(start)
        endIdx = '%d.0' % (int(end)+1)
        self.text.tag_configure('hilite',background=Colors.locatecolor,foreground='black')
        self.text.see(startIdx)
        self.text.tag_add('hilite',startIdx,endIdx)

    def coolSource(self):
        self.text.tag_configure('hilite',background='white',foreground=Colors.locatecooledcolor)
    def makeTop(self):
        TkWorkaround.raiseWindow(self.toplevel)
    def rescueResource(self):
        return repr(self.toplevel.geometry())
    def setGeom(self,geom):
        self.toplevel.geometry(geom)

    def showError(self, unitType, lineNo):
        text = {'m': self.bodyText, 'i': self.specText}[unitType]
        startIdx = '%s.0' % int(lineNo)
        endIdx = '%s.0' % (int(lineNo)+1)
        text.tag_remove('hilite','1.0',END)
        text.tag_configure('hilite',background=Colors.locatecolor,foreground='black')
        text.see(startIdx)
        text.tag_add('hilite',startIdx,endIdx)
        self.makeTop()