testtext.py

来自「pygtk的教程」· Python 代码 · 共 325 行

PY
325
字号
#!/usr/bin/env python# -*- coding: iso-8859-1 -*-import pygtkpygtk.require('2.0')import sys, os, errnoimport gtkimport pangoRESPONSE_FORWARD = 0RESPONSE_BACKWARD = 1book_closed_xpm = ["16 16 6 1","       c None s None",".      c black","X      c red","o      c yellow","O      c #808080","#      c white","                ","       ..       ","     ..XX.      ","   ..XXXXX.     "," ..XXXXXXXX.    ",".ooXXXXXXXXX.   ","..ooXXXXXXXXX.  ",".X.ooXXXXXXXXX. ",".XX.ooXXXXXX..  "," .XX.ooXXX..#O  ","  .XX.oo..##OO. ","   .XX..##OO..  ","    .X.#OO..    ","     ..O..      ","      ..        ","                "]def hsv_to_rgb(h, s, v):    if s == 0.0:        return (v, v, v)    else:        hue = h * 6.0        saturation = s        value = v        if hue >= 6.0:            hue = 0.0        f = hue - int(hue)        p = value * (1.0 - saturation)        q = value * (1.0 - saturation * f)        t = value * (1.0 - saturation * (1.0 - f))        ihue = int(hue)        if ihue == 0:            return(value, t, p)	elif ihue == 1:            return(q, value, p)	elif ihue == 2:            return(p, value, t)        elif ihue == 3:            return(p, q, value)        elif ihue == 4:            return(t, p, value)        elif ihue == 5:            return(value, p, q)def hue_to_color(hue):    if hue > 1.0:        raise ValueError    h, s, v = hsv_to_rgb (hue, 1.0, 1.0)    return (h*65535, s*65535, v*65535)class FileSel(gtk.FileSelection):    def __init__(self):        gtk.FileSelection.__init__(self)        self.result = False    def ok_cb(self, button):        self.hide()        if self.ok_func(self.get_filename()):            self.destroy()            self.result = True        else:            self.show()    def run(self, parent, title, start_file, func):        if start_file:            self.set_filename(start_file)        self.ok_func = func        self.ok_button.connect("clicked", self.ok_cb)        self.cancel_button.connect("clicked", lambda x: self.destroy())        self.connect("destroy", lambda x: gtk.main_quit())        self.set_modal(True)        self.show()        gtk.main()        return self.resultclass Buffer(gtk.TextBuffer):    N_COLORS = 16    PANGO_SCALE = 1024    def __init__(self):        gtk.TextBuffer.__init__(self)        tt = self.get_tag_table()        self.refcount = 0        self.filename = None        self.untitled_serial = -1        self.color_tags = []        self.color_cycle_timeout_id = 0        self.start_hue = 0.0        for i in range(Buffer.N_COLORS):            tag = self.create_tag()            self.color_tags.append(tag)          #self.invisible_tag = self.create_tag(None, invisible=True)        self.not_editable_tag = self.create_tag(editable=False,                                                foreground="purple")        self.found_text_tag = self.create_tag(foreground="red")        tabs = pango.TabArray(4, True)        tabs.set_tab(0, pango.TAB_LEFT, 10)        tabs.set_tab(1, pango.TAB_LEFT, 30)        tabs.set_tab(2, pango.TAB_LEFT, 60)        tabs.set_tab(3, pango.TAB_LEFT, 120)        self.custom_tabs_tag = self.create_tag(tabs=tabs, foreground="green")        TestText.buffers.push(self)    def pretty_name(self):        if self.filename:            return os.path.basename(self.filename)        else:            if self.untitled_serial == -1:                self.untitled_serial = TestText.untitled_serial                TestText.untitled_serial += 1            if self.untitled_serial == 1:                return "Untitled"            else:                return "Untitled #%d" % self.untitled_serial    def filename_set(self):        for view in TestText.views:            if view.text_view.get_buffer() == self:                view.set_view_title()    def search(self, str, view, forward):        # remove tag from whole buffer        start, end = self.get_bounds()        self.remove_tag(self.found_text_tag, start, end)          iter = self.get_iter_at_mark(self.get_insert())        i = 0        if str:            if forward:                while 1:                    res = iter.forward_search(str, gtk.TEXT_SEARCH_TEXT_ONLY)                    if not res:                        break                    match_start, match_end = res                    i += 1                    self.apply_tag(self.found_text_tag, match_start, match_end)                    iter = match_end            else:                while 1:                    res = iter.backward_search(str, gtk.TEXT_SEARCH_TEXT_ONLY)                    if not res:                        break                    match_start, match_end = res                    i += 1                    self.apply_tag(self.found_text_tag, match_start, match_end)                    iter = match_start        dialog = gtk.MessageDialog(view,                                   gtk.DIALOG_DESTROY_WITH_PARENT,                                   gtk.MESSAGE_INFO,                                   gtk.BUTTONS_OK,                                   "%d strings found and marked in red" % i)        dialog.connect("response", lambda x,y: dialog.destroy())          dialog.show()    def search_forward(self, str, view):        self.search(str, view, True)    def search_backward(self, str, view):        self.search(str, view, False)    def ref(self):        self.refcount += 1    def unref(self):        self.refcount -= 1        if self.refcount == 0:            self.set_colors(False)            TestText.buffers.remove(self)            del self    def color_cycle_timeout(self):        self.cycle_colors()        return True    def set_colors(self, enabled):        hue = 0.0        if (enabled and self.color_cycle_timeout_id == 0):            self.color_cycle_timeout_id = gtk.timeout_add(                200, self.color_cycle_timeout)        elif (not enabled and self.color_cycle_timeout_id != 0):            gtk.timeout_remove(self.color_cycle_timeout_id)            self.color_cycle_timeout_id = 0            for tag in self.color_tags:            if enabled:                color = apply(TestText.colormap.alloc_color,                              hue_to_color(hue))                tag.set_property("foreground_gdk", color)            else:                tag.set_property("foreground_set", False)            hue += 1.0 / Buffer.N_COLORS          def cycle_colors(self):        hue = self.start_hue          for tag in self.color_tags:            color = apply(TestText.colormap.alloc_color,                          hue_to_color (hue))            tag.set_property("foreground_gdk", color)            hue += 1.0 / Buffer.N_COLORS            if hue > 1.0:                hue = 0.0        self.start_hue += 1.0 / Buffer.N_COLORS        if self.start_hue > 1.0:            self.start_hue = 0.0    def tag_event_handler(self, tag, widget, event, iter):        char_index = iter.get_offset()        tag_name = tag.get_property("name")        if event.type == gtk.gdk.MOTION_NOTIFY:            print "Motion event at char %d tag `%s'\n" % (char_index, tag_name)        elif event.type == gtk.gdk.BUTTON_PRESS:            print "Button press at char %d tag `%s'\n" % (char_index, tag_name)        elif event.type == gtk.gdk._2BUTTON_PRESS:            print "Double click at char %d tag `%s'\n" % (char_index, tag_name)        elif event.type == gtk.gdk._3BUTTON_PRESS:            print "Triple click at char %d tag `%s'\n" % (char_index, tag_name)        elif event.type == gtk.gdk.BUTTON_RELEASE:            print "Button release at char %d tag `%s'\n" % (char_index, tag_name)        elif (event.type == gtk.gdk.KEY_PRESS or              event.type == gtk.gdk.KEY_RELEASE):            print "Key event at char %d tag `%s'\n" % (char_index, tag_name)        return False    def init_tags(self):        colormap = TestText.colormap        color = colormap.alloc_color(0, 0, 0xffff)        tag = self.create_tag("fg_blue",                                foreground_gdk=color,                                background='yellow',                                size_points=24.0)        tag.connect("event", self.tag_event_handler)        color = colormap.alloc_color(0xffff, 0, 0)        tag = self.create_tag("fg_red",                                rise= -4*Buffer.PANGO_SCALE,                                foreground_gdk=color)        tag.connect("event", self.tag_event_handler)        color = colormap.alloc_color(0, 0xffff, 0)        tag = self.create_tag("bg_green",                                background_gdk=color,                                size_points=10.0)        tag.connect("event", self.tag_event_handler)        tag = self.create_tag("strikethrough",                                strikethrough=True)        tag.connect("event", self.tag_event_handler)        tag = self.create_tag("underline",                                underline=pango.UNDERLINE_SINGLE)        tag.connect("event", self.tag_event_handler)        tag = self.create_tag("centered",                                justification=gtk.JUSTIFY_CENTER)        tag = self.create_tag("rtl_quote",                                wrap_mode=gtk.WRAP_WORD,                                direction=gtk.TEXT_DIR_RTL,                                indent=30,                                left_margin=20,                                right_margin=20)        tag = self.create_tag("negative_indent",                                indent=-25)    def fill_example_buffer(self):        tagtable = self.get_tag_table()        if not tagtable.lookup("fg_blue"):            self.init_tags()        iter = self.get_iter_at_offset(0)        anchor = self.create_child_anchor(iter)        self.set_data("anchor", anchor)        pixbuf = gtk.gdk.pixbuf_new_from_xpm_data(book_closed_xpm)        #pixbuf = gtk.gdk.pixbuf_new_from_file('book_closed.xpm')        for i in range(100):            iter = self.get_iter_at_offset(0)            self.insert_pixbuf(iter, pixbuf)                      str = "%d Hello World! blah blah blah blah blah blah blah blah blah blah blah blah\nwoo woo woo woo woo woo woo woo woo woo woo woo woo woo woo\n" % i            self.insert(iter, str)            iter = self.get_iter_at_line_offset(0, 5)            self.insert(iter,                          "(Hello World!)\nfoo foo Hello this is some text we are using to text word wrap. It has punctuation! gee; blah - hmm, great.\nnew line with a significant quantity of text on it. This line really does contain some text. More text! More text! More text!\n"                          "German (Deutsch S眉d) Gr眉脽 Gott Greek (螘位位畏谓喂魏维) 螕蔚喂维 蟽伪蟼 Hebrew(砖诇讜诐) Hebrew punctuation(\xd6\xbf砖\xd6\xbb\xd6\xbc\xd6\xbb\xd6\xbf诇\xd6\xbc讜\xd6\xbc\xd6\xbb\xd6\xbb\xd6\xbf诐\xd6\xbc\xd6\xbb\xd6\xbf) Japanese (鏃ユ湰瑾

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?