Esempio n. 1
0
 def test_text(self):
     with self.draw_and_check():
         font = Font(family=MODERN)
         font.size = 24
         self.gc.set_font(font)
         self.gc.set_text_position(23, 67)
         self.gc.show_text("hello kiva")
Esempio n. 2
0
    def test_locale_independence(self):
        # Ensure that >ASCII Unicode text is decoded correctly regardless of
        # the locale.
        text = u'\N{GREEK SMALL LETTER MU}'

        with locale_context(locale.LC_CTYPE, ('en', 'UTF-8')):
            gc = agg.GraphicsContextArray((200, 200))
            f = Font('modern')
            with gc:
                gc.set_font(f)
                gc.translate_ctm(50, 50)
                tx0, _, _, _ = gc.get_text_extent(text)
                gc.show_text(text)
                x0, _ = gc.get_text_position()

        with locale_context(locale.LC_CTYPE, ('en', 'ASCII')):
            gc = agg.GraphicsContextArray((200, 200))
            f = Font('modern')
            with gc:
                gc.set_font(f)
                gc.translate_ctm(50, 50)
                tx1, _, _, _ = gc.get_text_extent(text)
                gc.show_text(text)
                x1, _ = gc.get_text_position()

        self.assertEqual(tx1, tx0)
        self.assertEqual(x1, x0)
Esempio n. 3
0
 def test_text(self):
     with self.draw_and_check():
         font = Font(family=MODERN)
         font.size = 24
         self.gc.set_font(font)
         self.gc.set_text_position(23, 67)
         self.gc.show_text("hello kiva")
Esempio n. 4
0
 def test_text_clip(self):
     with self.draw_and_check():
         self.gc.clip_to_rect(23, 77, 100, 23)
         font = Font(family=MODERN)
         font.size = 24
         self.gc.set_font(font)
         self.gc.set_text_position(23, 67)
         self.gc.show_text("hello kiva")
Esempio n. 5
0
 def test_text_clip(self):
     with self.draw_and_check():
         self.gc.clip_to_rect(23, 77, 100, 23)
         font = Font(family=MODERN)
         font.size = 24
         self.gc.set_font(font)
         self.gc.set_text_position(23, 67)
         self.gc.show_text("hello kiva")
Esempio n. 6
0
    def _draw_info(self, gc, lines):
        if not self.tool.current_screen:
            return

        x, y = self.tool.current_screen

        gc.set_font(Font('Arial'))
        gc.set_fill_color((0.8, 0.8, 0.8))
        lws, lhs = zip(*[gc.get_full_text_extent(mi)[:2] for mi in lines])

        lw = max(lws)
        lh = sum(lhs) * 1.25 + 2 * len(lhs)

        xoffset = 12
        yoffset = 10

        x += xoffset
        y -= yoffset

        # if the box doesnt fit in window
        # move left
        x2 = self.component.x2
        if x + lw > x2:
            x = x2 - lw - 3

        gc.rect(x, y - lh + 2, lw + 4, lh)
        gc.draw_path()
        gc.set_fill_color((0, 0, 0))
        h = lhs[0] * 1.25

        for i, mi in enumerate(lines):
            gc.set_text_position(x + 2,
                                 y - h * (i + 1)
            )
            gc.show_text(mi)
Esempio n. 7
0
    def from_wx_font(self, font):
        """ Gets the application equivalent of a wxPython value.
        """
        from pyface.ui.wx.font import wx_weight_to_weight
        import kiva.constants as kc
        from kiva.fonttools import Font

        return Font(
            size=font.GetPointSize(),
            family={
                wx.FONTFAMILY_DEFAULT: kc.DEFAULT,
                wx.FONTFAMILY_DECORATIVE: kc.DECORATIVE,
                wx.FONTFAMILY_ROMAN: kc.ROMAN,
                wx.FONTFAMILY_SCRIPT: kc.SCRIPT,
                wx.FONTFAMILY_SWISS: kc.SWISS,
                wx.FONTFAMILY_MODERN: kc.MODERN,
            }.get(font.GetFamily(), kc.SWISS),
            weight=wx_weight_to_weight[font.GetWeight()],
            style=(
                # XXX: treat wx.FONTSTYLE_OBLIQUE as italic for now
                kc.NORMAL
                if font.GetStyle() == wx.FONTSTYLE_NORMAL else kc.ITALIC),
            underline=font.GetUnderlined() - 0,  # convert Bool to an int type
            face_name=font.GetFaceName(),
        )
Esempio n. 8
0
def str_to_font(object, name, value):
    "Converts a (somewhat) free-form string into a valid Font object."
    # FIXME: Make this less free-form and more well-defined.
    try:
        point_size = 10
        family = SWISS
        style = NORMAL
        weight = NORMAL
        underline = 0
        face_name = []
        for word in value.split():
            lword = word.lower()
            if lword in font_families:
                family = font_families[lword]
            elif lword in font_styles:
                style = font_styles[lword]
            elif lword in font_weights:
                weight = font_weights[lword]
            elif lword == 'underline':
                underline = 1
            elif lword not in font_noise:
                try:
                    point_size = int(lword)
                except:
                    face_name.append(word)
        return Font(face_name=" ".join(face_name),
                    size=point_size,
                    family=family,
                    weight=weight,
                    style=style,
                    underline=underline)
    except:
        pass
    raise TraitError(object, name, 'a font descriptor string', repr(value))
Esempio n. 9
0
 def test_no_antialias(self):
     gc = agg.GraphicsContextArray((200, 50), pix_format="bgra32")
     f = Font('modern')
     gc.set_font(f)
     gc.set_antialias(0)
     gc.show_text("hello")
     save(gc, test_name() + '.bmp')
Esempio n. 10
0
    def _draw_label(self, gc):
        with gc:
            font = Font(family=MODERN)
            gc.set_font(font)

            x, y, width, height = gc.get_text_extent(self.label)
            text_x = self.x + (self.width - width) / 2.0
            text_y = self.y - height

            gc.show_text(self.label, (text_x, text_y))
 def test_get_set_font(self):
     gc = agg.GraphicsContextArray((5, 5))
     font1 = Font('modern')
     gc.set_font(font1)
     font3 = gc.get_font()
     self.assertEqual(font1.face_name, font3.name)
     self.assertEqual(font1.size, font3.size)
     self.assertEqual(font1.family, font3.family)
     self.assertEqual(font1.style, font3.style)
     self.assertEqual(font1.encoding, font3.encoding)
 def getFont(cls, font_name='Arial'):
     kiva_style = constants.NORMAL
     if '-' in font_name:
         font_name, style = font_name.split('-', 2)
         style = style.lower()
         if 'bold' in style:
             kiva_style += constants.BOLD
         if 'italic' in style:
             kiva_style += constants.ITALIC
     return Font(font_name, style=kiva_style)
Esempio n. 13
0
def font_metrics_provider():
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.lib.pagesizes import letter
    from kiva.fonttools import Font

    # a file will not be created unless save() is called on the context
    pdf_canvas = Canvas(filename='enable_tmp.pdf', pagesize=letter)
    gc = GraphicsContext(pdf_canvas)
    gc.set_font(Font())
    return gc
Esempio n. 14
0
    def validate(self, object, name, value):
        """ Validates that the value is a valid font.
        """
        from kiva.fonttools import Font

        if isinstance(value, Font):
            return value

        # Make sure all Kiva related data is loaded:
        init_constants()

        try:
            point_size = 10
            family = DEFAULT
            style = NORMAL
            weight = WEIGHT_NORMAL
            underline = 0
            facename = []
            for word in value.split():
                lword = word.lower()
                if lword in font_families:
                    family = font_families[lword]
                elif lword in font_styles:
                    style = font_styles[lword]
                elif lword in font_weights:
                    weight = font_weights[lword]
                elif lword == "underline":
                    underline = 1
                elif lword not in font_noise:
                    try:
                        point_size = int(lword)
                    except Exception:
                        facename.append(word)

            if facename == "":
                facename = default_face.get(family, "")
            # FIXME: The above if clause never happens, the below should
            # be correct though it results in loading weird fonts.
            #             if facename == []:
            #                 facename = [default_face.get(family, "")]
            return Font(
                face_name=" ".join(facename),
                size=point_size,
                family=family,
                weight=weight,
                style=style,
                underline=underline,
            )
        except Exception:
            pass

        raise TraitError(object, name, "a font descriptor string", repr(value))
Esempio n. 15
0
 def GetFont(font):
     """ Returns a Pylget Font object for the given Agg or Kiva font """
     if isinstance(font, PygletFont):
         pyglet_font = font
     else:
         # KivaGLFontType
         key = (font.name, font.size, font.family, font.style)
         if key not in GlobalFontCache:
             if isinstance(font, KivaGLFontType):
                 kiva_gl_font = font
                 font = Font(
                     face_name=kiva_gl_font.name,
                     size=kiva_gl_font.size,
                     family=kiva_gl_font.family,
                     style=kiva_gl_font.style,
                 )
             bold = font.is_bold()
             italic = font.style in italic_styles
             pyglet_font = load_font(font.findfontname(), font.size, bold,
                                     italic)
             GlobalFontCache[key] = pyglet_font
         else:
             pyglet_font = GlobalFontCache[key]
     return pyglet_font
Esempio n. 16
0
    def draw(self, gc, view_bounds=None, mode="default"):
        """ Draws the graph node
        """

        font = Font(family=MODERN)
        gc.set_font(font)

        # update the size to match the text extent.
        x, y, width, height = gc.get_text_extent(self.label)

        self.width = width + self.padding_left + self.padding_right
        self.height = height + self.padding_bottom + self.padding_top

        self._draw_border(gc, view_bounds, mode)
        self._draw_text(gc, view_bounds, mode)
    def _draw_text(self, gc):
        """ Draw the shape's text. """

        if len(self.text) > 0:
            gc.set_fill_color(self._get_text_color(self.event_state))

            gc.set_font(Font(family=MODERN, size=16))
            tx, ty, tw, th = gc.get_text_extent(self.text)

            dx, dy = self.bounds
            x, y = self.position
            gc.set_text_position(x + (dx - tw) / 2, y + (dy - th) / 2)

            gc.show_text(self.text)

        return
Esempio n. 18
0
 def test_rotate(self):
     text = "hello"
     gc = agg.GraphicsContextArray((150, 150), pix_format="bgra32")
     f = Font('modern')
     gc.set_font(f)
     tx, ty, sx, sy = bbox = gc.get_text_extent(text)
     gc.translate_ctm(25, 25)
     gc.rotate_ctm(pi / 2.)
     gc.translate_ctm(0, -sy)
     #gc.show_text(text)
     gc.set_stroke_color([1, 0, 0])
     gc.set_fill_color([.5, .5, .5])
     gc.rect(tx, ty, sx, sy)
     gc.stroke_path()
     gc.show_text(text)
     save(gc, test_name() + '.bmp')
Esempio n. 19
0
def test():

    allmetrics = []
    for count in counts:
        start = time.time()
        for i in range(count):
            metrics = FMP()
            for face, size in fonts:
                metrics.set_font(Font(face, size))
                for s in strings:
                    dims = metrics.get_text_extent(s)
            allmetrics.append(metrics)
        end = time.time()
        print("finished count=%d" % count)
        print("   total time:", end - start)
        print("   time/set_font:", (end - start) / float(count * len(fonts)))
def test_handling_text(gc):
    font = Font(face_name="Arial", size=32)
    gc.set_font(font)
    gc.translate_ctm(100.0, 100.0)
    gc.move_to(-5, 0)
    gc.line_to(5, 0)
    gc.move_to(0, 5)
    gc.line_to(0, -5)
    gc.move_to(0, 0)
    gc.stroke_path()
    txtRot = affine.affine_from_rotation(PI / 6)
    gc.set_text_matrix(txtRot)
    gc.show_text("Hello")
    txtRot = affine.invert(txtRot)
    gc.set_text_matrix(txtRot)
    gc.show_text("inverted")
Esempio n. 21
0
    def _draw_info(self, plot, gc, lines):
        if not self.tool.current_screen:
            return

        x, y = sx, sy = self.tool.current_screen

        gc.set_font(Font('Arial'))
        gc.set_fill_color((0.8, 0.8, 0.8))

        lws, lhs = zip(*[gc.get_full_text_extent(mi)[:2] for mi in lines])

        rect_width = max(lws) + 4
        rect_height = (max(lhs) + 2) * len(lhs)

        xoffset = 15
        yoffset = -15
        gc.translate_ctm(xoffset, yoffset)

        # if the box doesnt fit in window
        # move left
        x2 = self.component.x2
        y2 = self.component.y2

        if x + xoffset + rect_width > x2:
            x = x2 - rect_width - xoffset - 1

        # move down if to tall
        # if y + yoffset + rect_height > y2:
        #     y = y2 - rect_height - yoffset -1

        # if current point within bounds of box, move box to left
        if x < sx:
            x = sx - rect_width - xoffset - 6

        gc.translate_ctm(x, y - rect_height)
        gc.rect(0, -2, rect_width, rect_height + 4)
        gc.draw_path()
        gc.set_fill_color((0, 0, 0))

        h = max(lhs) + 2

        # this is cause the pointer to change to an IBeam if the cursor is close the the box
        # increase offsets? as a hack
        for i, mi in enumerate(lines[::-1]):
            gc.set_text_position(0, h * i)
            gc.show_text(mi)
Esempio n. 22
0
    def overlay(self, component, gc, *args, **kw):

        gc.save_state()
        gc.set_font(Font('Monaco'))
        x = component.x
        y2 = component.y2

        gc.set_fill_color((1, 1, 1))
        w = 100
        h = 110

        gc.rect(x + 5, y2 - 5 - h, w, h)
        gc.draw_path()

        machines = ['jan', 'obama', 'map']
        colors = [(1, 0.5, 0), (0, 0, 1), (1, 0, 0)]
        xo = x + 5
        yo = y2 - 10
        texth = 12
        for i, (mi, color) in enumerate(zip(machines, colors)):
            gc.set_fill_color(color)
            yi = yo - (texth) * (i + 1)
            gc.set_text_position(xo + 20, yi)
            gc.show_text(mi)


#        markers = ['circle', 'square', 'diamond', 'triangle']
        ats = ['blank', 'air', 'cocktail', 'unknown', 'background']
        gc.set_fill_color((0, 0, 0))
        for i, si in enumerate(ats):
            yy = yi - (texth) * (i + 1)
            try:
                plot = component.plots['jan {}'.format(si)][0]
            except KeyError:
                continue
            pcolor, plot.color = plot.color, 'black'
            mpcolor, plot.outline_color = plot.outline_color, 'black'
            plot._render_icon(gc, xo + 5, yy, 5, 5)
            plot.color = pcolor
            plot.outline_color = mpcolor
            gc.set_text_position(xo + 20, yy)
            gc.show_text(si)

        gc.restore_state()
Esempio n. 23
0
    def from_wx_font(self, font):
        """ Gets the application equivalent of a wxPython value.
        """
        import kiva.constants as kc
        from kiva.fonttools import Font

        return Font(
            size=font.GetPointSize(),
            family={
                wx.DEFAULT: kc.DEFAULT,
                wx.DECORATIVE: kc.DECORATIVE,
                wx.ROMAN: kc.ROMAN,
                wx.SCRIPT: kc.SCRIPT,
                wx.SWISS: kc.SWISS,
                wx.MODERN: kc.MODERN
            }.get(font.GetFamily(), kc.SWISS),
            weight=(kc.NORMAL, kc.BOLD)[font.GetWeight() == wx.BOLD],
            style=(kc.NORMAL, kc.ITALIC)[font.GetStyle() == wx.ITALIC],
            underline=font.GetUnderlined() - 0,  #convert Bool to an int type
            face_name=font.GetFaceName())
Esempio n. 24
0
    def _draw_mainlayer(self, gc, view_bounds=None, mode='default'):
        if self.should_profile and self.profile_this is not None:
            # Only profile the first draw.
            self.should_profile = False
            self.profile_this.start('Drawing')
        start = now()
        gc.clear()

        width, height = self.bounds
        gc.save_state()
        if self.document is None:
            # fixme: The Mac backend doesn't accept style/width as non-integers
            #        in set_font, but does for select_font...
            if sys.platform == 'darwin':
                gc.select_font("Helvetica", 36)
            else:
                gc.set_font(Font("Helvetica", 36))
            gc.show_text_at_point("Could not parse document.", 20, height - 56)
            gc.restore_state()
            if self.profile_this is not None:
                self.profile_this.stop()
            return

        try:
            # SVG origin is upper right with y positive is down.
            # Set up the transforms to fix this up.
            # FIXME: if the rendering stage fails, all subsequent renders are vertically flipped
            gc.translate_ctm(0, height)
            # TODO: bother with zoom?
            # TODO: inspect the view bounds and scale to the shape of the
            # component?
            scale = 1.0
            gc.scale_ctm(scale, -scale)
            self.document.render(gc)
            self.last_render = now() - start

        finally:
            gc.restore_state()
            if self.profile_this is not None:
                self.profile_this.stop()
Esempio n. 25
0
def font_metrics_provider():
    from kiva.fonttools import Font
    gc = GraphicsContext((1, 1))
    gc.set_font(Font())
    return gc
Esempio n. 26
0
    def _draw_info(self, plot, gc, lines):
        if not self.tool.current_screen:
            return

        x, y = sx, sy = self.tool.current_screen

        size = 14
        gc.set_font(Font('Arial', size=size))
        gc.set_fill_color((0.8, 0.8, 0.8))

        lws, lhs = list(zip(*[gc.get_full_text_extent(mi)[:2]
                              for mi in lines]))

        rect_width = max(lws) + 4
        rect_height = (max(lhs) + 2) * len(lhs)

        xoffset = 15
        yoffset = -15
        gc.translate_ctm(xoffset, yoffset)

        # if the box doesnt fit in window
        # move left
        x2 = self.component.x2
        y2 = self.component.y2

        if x + xoffset + rect_width > x2:
            x = x2 - rect_width - xoffset - 1

        multi_column = 0
        h = max(lhs) + 2
        cheight = self.component.height
        if rect_height > cheight + 5 * h:
            multi_column = 2
        else:
            # move up if too tall
            if y + yoffset - rect_height < self.component.y:
                y = y2 - yoffset

        # if current point within bounds of box, move box to left
        if x < sx:
            x = sx - rect_width - xoffset - 6

        if multi_column:
            gc.translate_ctm(x, self.component.y)
            gc.rect(0, -2, multi_column * rect_width, cheight - yoffset)
        else:
            gc.translate_ctm(x, y - rect_height)
            gc.rect(0, -2, rect_width, rect_height + 4)

        gc.draw_path()
        gc.set_fill_color((0, 0, 0))

        if multi_column:
            gen = (li for li in lines)
            for col in range(multi_column):
                i = 0
                for mi in gen:
                    if i == 0 and mi == '--------':
                        continue

                    yi = h * i
                    if yi > cheight:
                        break
                    gc.set_text_position(col * rect_width, y2 - yi)
                    gc.show_text(mi)
                    i += 1
        else:
            for i, mi in enumerate(lines[::-1]):
                gc.set_text_position(0, h * i)
                gc.show_text(mi)
Esempio n. 27
0
from __future__ import print_function

import time
from kiva.fonttools import Font
from kiva.constants import MODERN
from kiva.agg import AffineMatrix, GraphicsContextArray

gc = GraphicsContextArray((200,200))

font = Font(family=MODERN)
#print font.size
font.size=8
gc.set_font(font)


t1 = time.clock()

# consecutive printing of text.
with gc:
    gc.set_antialias(False)
    gc.set_fill_color((0,1,0))
    gc.translate_ctm(50,50)
    gc.rotate_ctm(3.1416/4)
    gc.show_text("hello")
    gc.translate_ctm(-50,-50)
    gc.set_text_matrix(AffineMatrix())
    gc.set_fill_color((0,1,1))
    gc.show_text("hello")

t2 = time.clock()
print('aliased:', t2 - t1)
Esempio n. 28
0
"""
Test to see what level of click latency is noticeable.
"""
import time

from traits.api import Float
from enable.api import (Component, Container, ColorTrait, black_color_trait,
                        Window)
from enable.example_support import DemoFrame, demo_main
from kiva.constants import SWISS
from kiva.fonttools import Font

font = Font(family=SWISS)


class Box(Component):
    color = ColorTrait("red")

    delay = Float(0.50)

    def _draw_mainlayer(self, gc, view=None, mode="default"):
        if self.event_state == "clicked":
            print("waiting %0.4f seconds... " % self.delay, end=' ')
            time.sleep(self.delay)
            print("done.")

            with gc:
                gc.set_fill_color(self.color_)
                gc.rect(*(self.position + self.bounds))
                gc.fill_path()
Esempio n. 29
0
def font_metrics_provider():
    gc = GraphicsContext((1, 1))
    gc.set_font(Font())
    return gc
Esempio n. 30
0
 def select_font(self, face_name, size=12, style="regular", encoding=None):
     """ Set the font for the current graphics context.
     """
     weight, style = font_styles[style.lower()]
     self.set_font(Font(face_name, size=size, weight=weight, style=style))
 def test_show_text_at_point(self):
     gc = GraphicsContextArray((100, 100))
     gc.set_font(Font())
     gc.show_text_at_point(str('asdf'), 5, 5)
Esempio n. 32
0
    def build_graph(self):

        skw = dict(type='scatter', marker_size=3)
#            skw = dict(type='bar')
        g = self.graph
        xs = []
        ys = []
        ats = ['blank', 'air', 'cocktail', 'unknown', 'background']
#        ats += ['blank_air', 'blank_cocktail', 'blank_unknown']
        machines = ['jan', 'obama', 'map']
        rids = []
        def test(ri, at, mach):
            if at == 'blank':
                attest = ri.analysis_type.startswith('blank')
            else:
                attest = ri.analysis_type == at

            if attest:
                return ri.mass_spectrometer == mach

        for mach in machines:
            for i, at in enumerate(ats):
                dd = [(ri.shortname, ri.timestamp)
                               for ri in self.table.records
                                    if test(ri, at, mach)

                        ]
                if dd:
                    ni, xi = zip(*dd)
                else:
                    xi = []
                    ni = []
                xi = np.array(xi)
                n = len(xi)
                xs.append(xi)
                ys.append(np.array(range(n)) + 1 + 3 * i)
                rids.append(ni)

        mm = [min(xj) for xj in xs if len(xj)]
        if not mm:
            return
        xmi = min(mm)
        mm = [max(yj) for yj in ys if len(yj)]
        yma = max(mm)

        xs = np.array([xk - xmi for xk in xs])
        ys = np.array(ys)
        mm = [max(xj) for xj in xs if len(xj)]
        xma = max(mm)

        colors = ['orange', 'blue', 'green']
        markers = ['circle', 'square', 'diamond', 'triangle', 'cross']

        def ffunc(s):
            def func(new):
                if new:
                    self._update_graph(s, xmi)
            return func

        def fffunc(s):
            def func(new):
                if new:
                    self._update(s, xmi)
            return func

        for i, (name, color) in enumerate(zip(machines, colors)):
            xxj = xs[i * 5:i * 5 + 5]
            yyj = ys[i * 5:i * 5 + 5]
            nnj = rids[i * 5:i * 5 + 5]
            for at, xx, yy, nn, marker in zip(ats, xxj, yyj, nnj, markers):
                s, _ = g.new_series(xx, yy, marker=marker, color=color, **skw)
                g.set_series_label('{} {}'.format(name, at))
#                self.add_trait('scatter_{}_{}'.format(at, name), s)

                tool = ScatterInspector(s, selection_mode='single')
                s.tools.append(tool)

                s.index.on_trait_change(ffunc(s), 'metadata_changed')

                for xi, yi, ni in zip(xx, yy, nn):
                    dl = DataLabel(component=s,
                                   font=Font('Monaco'),
                                   data_point=(xi, yi),
                                   label_position='top left',
                                   bgcolor='white',
#                                   label_format='%s',
                                   label_text=ni,
                                   show_label_coords=False,
                                   arrow_visible=False,
                                   marker_visible=False
                                   )
                    s.overlays.append(dl)
                    self.data_labels.append(dl)
                # add range selection tool
#                s.active_tool = RangeSelection(s, left_button_selects=True)
#                s.overlays.append(RangeSelectionOverlay(component=s))
#                s.index.on_trait_change(getattr(self, '_update_{}'.format(at)), 'metadata_changed')

        g.set_x_limits(min_=0, max_=xma, pad='0.1')
        g.set_y_limits(min_=0, max_=yma * 1.1)