Example #1
0
 def compute_trafo(self, state=0):
     sel = self.selection
     if sel in self.selTurn:
         # rotation
         vec = self.drag_cur - self.center
         angle = math.atan2(vec.y, vec.x)
         angle = angle - self.start_angle + 2 * math.pi
         if state & const.ConstraintMask:
             pi12 = math.pi / 12
             angle = pi12 * int(angle / pi12 + 0.5)
         self.trafo = Rotation(angle, self.center)
         self.trafo_desc = (1, angle)
     elif sel in self.selShear:
         if sel in (2, 6):
             # horiz. shear
             height = self.drag_start.y - self.reference
             if height:
                 ratio = self.off.x / height
                 self.trafo = Trafo(1, 0, ratio, 1, -ratio * self.reference,
                                    0)
                 self.trafo_desc = (2, ratio)
         else:
             # vert. shear
             width = self.drag_start.x - self.reference
             if width:
                 ratio = self.off.y / width
                 self.trafo = Trafo(1, ratio, 0, 1, 0,
                                    -ratio * self.reference)
                 self.trafo_desc = (3, ratio)
Example #2
0
 def rect(self, attrs):
     #print 'rect', attrs.map
     if self.in_defs:
         id = attrs.get('id', '')
         if id:
             self.named_objects[id] = ('object', 'rect', attrs)
         return
     if attrs.has_key('x'):
         x = attrs['x']
     else:
         x = '0'
     if attrs.has_key('y'):
         y = attrs['y']
     else:
         y = '0'
     x, y = self.point(x, y)
     wx, wy = self.point(attrs['width'], "0", relative=1)
     hx, hy = self.point("0", attrs['height'], relative=1)
     t = Trafo(wx, wy, hx, hy, x, y)
     self._print('rect', t)
     style = attrs.get('style', '')
     if style:
         self.parse_style(style)
     self.set_loader_style()
     apply(self.loader.rectangle, t.coeff())
Example #3
0
    def compute_trafo(self):
	height = self.tkwin.height
	doc_to_win = Trafo(1, 0, 0, -1, 0, height)
	win_to_doc = doc_to_win.inverse()
	self.gc.SetViewportTransform(1.0, doc_to_win, win_to_doc)
	self.fill_rect = Rect(0, 0, self.tkwin.width, self.tkwin.height)
	self.gc.SetProperties(self.properties, self.fill_rect)
Example #4
0
 def rect(self, attrs):
     #print 'rect', attrs.map
     if self.in_defs:
         id = attrs.get('id', '')
         if id:
             self.named_objects[id] = ('object', 'rect', attrs)
         return
     if attrs.has_key('x'):
         x = attrs['x']
     else:
         x = '0'
     if attrs.has_key('y'):
         y = attrs['y']
     else:
         y = '0'
     x, y = self.point(x, y)
     wx, wy = self.point(attrs['width'], "0", relative = 1)
     hx, hy = self.point("0", attrs['height'], relative = 1)
     t = Trafo(wx, wy, hx, hy, x, y)
     self._print('rect', t)
     style = attrs.get('style', '')
     if style:
         self.parse_style(style)
     self.set_loader_style()
     apply(self.loader.rectangle, t.coeff())
Example #5
0
 def parse_transform(self, trafo_string):
     trafo = self.trafo
     #print trafo
     trafo_string = as_latin1(trafo_string)
     while trafo_string:
         #print trafo_string
         match = rx_trafo.match(trafo_string)
         if match:
             function = match.group(1)
             args = string.translate(match.group(2), commatospace)
             args = map(float, split(args))
             trafo_string = trafo_string[match.end(0):]
             if function == 'matrix':
                 trafo = trafo(apply(Trafo, tuple(args)))
             elif function == 'scale':
                 trafo = trafo(Scale(args[0]))
             elif function == 'translate':
                 dx, dy = args
                 trafo = trafo(Translation(dx, dy))
             elif function == 'rotate':
                 trafo = trafo(Rotation(args[0] * degrees))
             elif function == 'skewX':
                 trafo = trafo(Trafo(1, 0, tan(args[0] * degrees), 1, 0, 0))
             elif function == 'skewY':
                 trafo = trafo(Trafo(1, tan(args[0] * degrees), 0, 1, 0, 0))
         else:
             trafo_string = ''
     #print trafo
     self.trafo = trafo
Example #6
0
 def compute_trafo(self):
     height = self.tkwin.height
     doc_to_win = Trafo(1, 0, 0, -1, 0, height)
     win_to_doc = doc_to_win.inverse()
     self.gc.SetViewportTransform(1.0, doc_to_win, win_to_doc)
     self.fill_rect = Rect(0, 0, self.tkwin.width, self.tkwin.height)
     self.gc.SetProperties(self.properties, self.fill_rect)
Example #7
0
 def __init__(self, file, filename, match):
     SimplifiedLoader.__init__(self, file, filename, match)
     self.layout = None
     self.format_version = atof(match.group('version'))
     self.trafo = Trafo(1.0, 0.0, 0.0, -1.0, 0.0, 800)
     self.colors = std_colors + [StandardColors.black] * 512
     self.depths = {}  # map object ids to depth
     self.guess_cont()
Example #8
0
    def make_gradient_pattern(self):
        name, trafo, start, end = self.gradient_geo
        self.gradient_geo = None
        type, array = self.gradients[name]
        array = array[:]
        if type == 0:
            # linear (axial) gradient
            origdir = end - start
            start = trafo(start)
            end = trafo(end)
            dir = end - start
            try:
                # adjust endpoint to accomodate trafo
                v = trafo.DTransform(origdir.y, -origdir.x).normalized()
                v = Point(v.y, -v.x)  # rotate 90 degrees
                end = start + (v * dir) * v
                dir = end - start
            except ZeroDivisionError:
                pass

            trafo2 = Trafo(dir.x, dir.y, dir.y, -dir.x, start.x, start.y)
            trafo2 = trafo2.inverse()
            left, bottom, right, top = trafo2(self.current_bounding_rect())
            if right > left:
                factor = 1 / (right - left)
                offset = -left * factor
            else:
                factor = 1
                offset = 0
            array = fix_gradient(array, factor, offset)
            pattern = LinearGradient(MultiGradient(array),
                                     (start - end).normalized())
        elif type == 1:
            # radial gradient
            start = trafo(start)
            end = trafo(end)
            left, bottom, right, top = self.current_bounding_rect()
            if left == right or top == bottom:
                # an empty coord_rect????
                center = Point(0, 0)
            else:
                center = Point((start.x - left) / (right - left),
                               (start.y - bottom) / (top - bottom))
            radius = max(hypot(left - start.x, top - start.y),
                         hypot(right - start.x, top - start.y),
                         hypot(right - start.x, bottom - start.y),
                         hypot(left - start.x, bottom - start.y))
            if radius:
                factor = -abs(start - end) / radius
                array = fix_gradient(array, factor, 1)
            pattern = RadialGradient(MultiGradient(array), center)
        else:
            self.add_message(_("Unknown gradient type %d"), type)
            pattern = EmptyPattern
        return pattern
Example #9
0
    def make_gradient_pattern(self):
        name, trafo, start, end = self.gradient_geo
        self.gradient_geo = None
        type, array = self.gradients[name]
        array = array[:]
        if type == 0:
            # linear (axial) gradient
            origdir = end - start
            start = trafo(start)
            end = trafo(end)
            dir = end - start
            try:
                # adjust endpoint to accomodate trafo
                v = trafo.DTransform(origdir.y, -origdir.x).normalized()
                v = Point(v.y, -v.x)  # rotate 90 degrees
                end = start + (v * dir) * v
                dir = end - start
            except ZeroDivisionError:
                pass

            trafo2 = Trafo(dir.x, dir.y, dir.y, -dir.x, start.x, start.y)
            trafo2 = trafo2.inverse()
            left, bottom, right, top = trafo2(self.current_bounding_rect())
            if right > left:
                factor = 1 / (right - left)
                offset = -left * factor
            else:
                factor = 1
                offset = 0
            array = fix_gradient(array, factor, offset)
            pattern = LinearGradient(MultiGradient(array), (start - end).normalized())
        elif type == 1:
            # radial gradient
            start = trafo(start)
            end = trafo(end)
            left, bottom, right, top = self.current_bounding_rect()
            if left == right or top == bottom:
                # an empty coord_rect????
                center = Point(0, 0)
            else:
                center = Point((start.x - left) / (right - left), (start.y - bottom) / (top - bottom))
            radius = max(
                hypot(left - start.x, top - start.y),
                hypot(right - start.x, top - start.y),
                hypot(right - start.x, bottom - start.y),
                hypot(left - start.x, bottom - start.y),
            )
            if radius:
                factor = -abs(start - end) / radius
                array = fix_gradient(array, factor, 1)
            pattern = RadialGradient(MultiGradient(array), center)
        else:
            self.add_message(_("Unknown gradient type %d"), type)
            pattern = EmptyPattern
        return pattern
Example #10
0
    def Snap(self, p):
        try:
            x, y = self.trafo.inverse()(p)
            minx = self.radius1
            maxx = 1 - self.radius1
            miny = self.radius2
            maxy = 1 - self.radius2
            if minx < x < maxx:
                if miny < y < maxy:
                    ratio = hypot(self.trafo.m11, self.trafo.m21) \
                          / hypot(self.trafo.m12, self.trafo.m22)
                    if x < 0.5:
                        dx = x
                    else:
                        dx = 1 - x
                    if y < 0.5:
                        dy = y
                    else:
                        dy = 1 - y
                    if dy / dx > ratio:
                        x = round(x)
                    else:
                        y = round(y)
                elif y > maxy:
                    y = 1
                else:
                    y = 0
            elif miny < y < maxy:
                if x > maxx:
                    x = 1
                else:
                    x = 0
            elif minx > 0 and miny > 0:
                # the round corners
                if x < 0.5:
                    cx = minx
                else:
                    cx = maxx
                if y < 0.5:
                    cy = miny
                else:
                    cy = maxy
                trafo = Trafo(minx, 0, 0, miny, cx, cy)
                r, phi = trafo.inverse()(x, y).polar()
                x, y = trafo(Polar(1, phi))
            else:
                # normal corners
                x = round(min(max(x, 0), 1))
                y = round(min(max(y, 0), 1))

            p2 = self.trafo(x, y)
            return (abs(p - p2), p2)
        except SingularMatrix:
            return (1e200, p)
Example #11
0
 def initsvg(self, attrs):
     width = self.user_length(attrs.get('width', '100%'))
     height = self.user_length(attrs.get('height', '100%'))
     self._print('initsvg', width, height)
     self.trafo = Trafo(1, 0, 0, -1, 0, height)
     self.basetrafo = self.trafo
     # evaluate viewBox
     # FIXME: Handle preserveAspectRatio as well
     viewbox = attrs.get("viewBox", "")
     if viewbox:
         vx, vy, vwidth, vheight = map(float, split(viewbox))
         t = Scale(width / vwidth, height / vheight)
         t = t(Translation(-vx, -vy))
         self.trafo = self.trafo(t)
     self._print("basetrafo", self.basetrafo)
Example #12
0
 def __init__(self,
              master,
              width,
              height,
              xcomp=0,
              ycomp=1,
              color=(0, 0, 0),
              **kw):
     self.xcomp = xcomp
     self.ycomp = ycomp
     self.win_to_color = Trafo(1 / float(width - 1), 0, 0,
                               -1 / float(height - 1), 0, 1)
     self.color_to_win = self.win_to_color.inverse()
     apply(ChooseComponent.__init__, (self, master, width, height, color),
           kw)
Example #13
0
def BlendTrafo(t1, t2, frac1, frac2):
    return Trafo(frac1 * t1.m11 + frac2 * t2.m11,
                 frac1 * t1.m21 + frac2 * t2.m21,
                 frac1 * t1.m12 + frac2 * t2.m12,
                 frac1 * t1.m22 + frac2 * t2.m22,
                 frac1 * t1.v1  + frac2 * t2.v1,
                 frac1 * t1.v2  + frac2 * t2.v2)
Example #14
0
    def image(self, attrs):
        if self.in_defs:
            id = attrs.get('id', '')
            if id:
                self.named_objects[id] = ('object', 'image', attrs)
            return
        href = as_latin1(attrs['xlink:href'])
        image = load_image(os.path.join(self.loader.directory, href)).image
        if attrs.has_key('x'):
            x = attrs['x']
        else:
            x = '0'
        if attrs.has_key('y'):
            y = attrs['y']
        else:
            y = '0'
        x, y = self.user_point(x, y)

        width = self.user_length(attrs['width'])
        scalex = width / image.size[0]

        height = self.user_length(attrs['height'])
        scaley = -height / image.size[1]

        style = attrs.get('style', '')
        if style:
            self.parse_style(style)
        self.set_loader_style()
        t = self.trafo(Trafo(scalex, 0, 0, scaley, x, y + height))
        self._print('image', t)
        self.loader.image(image, t)
Example #15
0
    def __init__(self, master, width, height, comp = 1, color = (0, 0, 0),
		 **kw):
	self.comp = comp
	self.win_to_color = Trafo(1, 0, 0, -1 / float(height - 1), 0, 1)
	self.color_to_win = self.win_to_color.inverse()
	apply(ChooseComponent.__init__, (self, master, width, height, color),
	      kw)
Example #16
0
    def begin_text(self, attrs):
        if self.in_defs:
            id = attrs.get('id', '')
            if id:
                self.named_objects[id] = ('object', 'text', attrs)
            return

        # parse the presentation attributes if any.
        # FIXME: this has to be implemented for the other elements that
        # can have presentation attributes as well.
        for key, value in attrs.items():
            self.try_add_style(key, value)

        if attrs.has_key('x'):
            x = attrs['x']
        else:
            x = '0'
        if attrs.has_key('y'):
            y = attrs['y']
        else:
            y = '0'
        x, y = self.user_point(x, y)
        self.text_trafo = self.trafo(Trafo(1, 0, 0, -1, x, y))
        self._print('text', self.text_trafo)
        style = attrs.get('style', '')
        if style:
            self.parse_style(style)
        self.set_loader_style(allow_font=1)
        self.current_text = ''
Example #17
0
 def gradient_geometry(self, flag, name, xorig, yorig, angle, length, a, b,
                       c, d, tx, ty):
     trafo = Trafo(a, b, c, d, tx, ty)
     trafo = artboard_trafo_inv(trafo(artboard_trafo))
     start = Point(xorig, yorig)
     end = start + Polar(length, (pi * angle) / 180.0)
     self.gradient_geo = (name, trafo, start, end)
Example #18
0
class ChooseRGBXY(ChooseComponent):
    def __init__(self,
                 master,
                 width,
                 height,
                 xcomp=0,
                 ycomp=1,
                 color=(0, 0, 0),
                 **kw):
        self.xcomp = xcomp
        self.ycomp = ycomp
        self.win_to_color = Trafo(1 / float(width - 1), 0, 0,
                                  -1 / float(height - 1), 0, 1)
        self.color_to_win = self.win_to_color.inverse()
        apply(ChooseComponent.__init__, (self, master, width, height, color),
              kw)

    def SetColor(self, color):
        color = apply(rgb_to_hsv, tuple(color))
        otheridx = 3 - self.xcomp - self.ycomp
        if color[otheridx] != self.color[otheridx]:
            self.UpdateWhenIdle()
        self.hide_mark()
        self.color = color
        self.show_mark()

    def update_ramp(self):
        _sketch.fill_hsv_xy(self.image.im, self.xcomp, self.ycomp, self.color)
        self.set_image(self.image)

    def move_to(self, p, state):
        x, y = p
        if state & ConstraintMask:
            sx = self.drag_start[self.xcomp]
            sy = self.drag_start[self.ycomp]
            if abs(sx - x) < abs(sy - y):
                x = sx
            else:
                y = sy
        if x < 0: x = 0
        elif x >= 1.0: x = 1.0
        if y < 0: y = 0
        elif y >= 1.0: y = 1.0

        color = list(self.color)
        color[self.xcomp] = x
        color[self.ycomp] = y
        self.hide_mark()
        self.color = tuple(color)
        self.show_mark()
        self.issue(CHANGED, self.RGBColor())

    def draw_mark(self):
        color = self.color
        w, h = self.image.size
        x, y = self.color_to_win(color[self.xcomp], color[self.ycomp])
        x = int(x)
        y = int(y)
        self.invgc.DrawLine(x, 0, x, h)
        self.invgc.DrawLine(0, y, w, y)
Example #19
0
def getQuickRect(sx, sy, ox, oy):
    start_x = sx
    start_y = sy
    off_x = ox
    off_y = oy
    trec = Rectangle(trafo=Trafo(off_x, 0, 0, off_y, start_x, start_y))
    trec.update_rects()
    return trec
Example #20
0
 def RemoveTransformation(self):
     if self.trafo.matrix() != IdentityMatrix:
         center = self.coord_rect.center()
         width, height = self.data.Size()
         trafo = Trafo(1, 0, 0, 1, center.x - width / 2,
                       center.y - height / 2)
         return self.set_transformation(trafo)
     return NullUndo
Example #21
0
    def SaveDocument(self, doc):

        left, bottom, right, top = doc.BoundingRect()
        width = right - left
        height = top - bottom

        inch = 1440
        x = max(width, height)
        if x * (inch / 72.) > 32767:
            inch = 32767 / x
        sc = inch / 72.
        self.trafo = Trafo(sc, 0, 0, -sc, -sc * left, sc * top)
        self.Scale = sc
        self.inch = inch
        self.extend = map(
            rndtoint,
            tuple(self.trafo(left, bottom)) + tuple(self.trafo(right, top)))

        self.numobj = self.idx = MIN_OBJECT
        self.objects = []
        self.maxrecord = 0
        self.cur_pen = -1
        self.cur_brush = -1

        # Header
        self.write_headers()

        # SetWindowOrg
        self.packrec('<LHhh', 5, 0x020B, self.extend[3], self.extend[0])

        # SetWindowExt
        self.packrec('<LHhh', 5, 0x020C, self.extend[1], self.extend[2])

        # SetBkMode to 1 (transparent)
        self.packrec('<LHh', 4, 0x0102, 1)

        # SetROP2 to 13 (R2_COPYPEN)
        # me self.packrec('<LHl', 5, 0x0104, 13)
        self.packrec('<LHh', 4, 0x0104, 13)  # oo

        # CreatePenIndirect: 5 -- PS_NULL
        self.add_select_object(
            struct.pack('<LHhhhBBBx', 8, 0x02FA, 5, 0, 0, 0, 0, 0))

        # CreateBrushIndirect: 1 -- BS_NULL
        self.add_select_object(
            struct.pack('<LHhBBBxh', 7, 0x02FC, 1, 0, 0, 0, 0))

        self.SaveLayers(doc.Layers())

        self.DeleteObject(0)
        self.DeleteObject(1)

        self.packrec('<LH', 3, 0)  # terminator

        # update some fields
        self.write_headers()
Example #22
0
 def ButtonUp(self, p, button, state):
     if self.state & AlternateMask:
         p = self.apply_constraint(p, state)
         self.DragStop(p)
         off = 2 * self.off
         end = self.trafo.offset() - self.off
         self.trafo = Trafo(off.x, 0, 0, off.y, end.x, end.y)
     else:
         RectangularCreator.ButtonUp(self, p, button, state)
Example #23
0
class ChooseRGBXY(ChooseComponent):

    def __init__(self, master, width, height, xcomp = 0, ycomp = 1,
		 color = (0, 0, 0), **kw):
	self.xcomp = xcomp
	self.ycomp = ycomp
	self.win_to_color = Trafo(1 / float(width - 1), 0,
				  0, -1 / float(height - 1),
				  0, 1)
	self.color_to_win = self.win_to_color.inverse()
	apply(ChooseComponent.__init__, (self, master, width, height, color),
	      kw)

    def SetColor(self, color):
	color = apply(rgb_to_hsv, tuple(color))
	otheridx = 3 - self.xcomp - self.ycomp
	if color[otheridx] != self.color[otheridx]:
	    self.UpdateWhenIdle()
	self.hide_mark()
	self.color = color
	self.show_mark()

    def update_ramp(self):
	_sketch.fill_hsv_xy(self.image.im, self.xcomp, self.ycomp, self.color)
	self.set_image(self.image)

    def move_to(self, p, state):
	x, y = p
	if state & ConstraintMask:
	    sx = self.drag_start[self.xcomp]
	    sy = self.drag_start[self.ycomp]
	    if abs(sx - x) < abs(sy - y):
		x = sx
	    else:
		y = sy
	if x < 0:	x = 0
	elif x >= 1.0:	x = 1.0
	if y < 0:	y = 0
	elif y >= 1.0:	y = 1.0

	color = list(self.color)
	color[self.xcomp] = x
	color[self.ycomp] = y
	self.hide_mark()
	self.color = tuple(color)
	self.show_mark()
	self.issue(CHANGED, self.RGBColor())

    def draw_mark(self):
        color = self.color
        w, h = self.image.size
        x, y = self.color_to_win(color[self.xcomp], color[self.ycomp])
        x = int(x)
        y = int(y)
        self.invgc.DrawLine(x, 0, x, h)
        self.invgc.DrawLine(0, y, w, y)
Example #24
0
 def __init__(self, data=None, trafo=None, duplicate=None):
     if duplicate is not None:
         data = duplicate.data
         self.trafo = duplicate.trafo
     else:
         if trafo is None:
             #width, height = data.size
             trafo = Trafo(1, 0, 0, -1, 0, 0)
         self.trafo = trafo
     self.data = data
Example #25
0
    def read_ellipse(self, line):
        readline = self.readline
        tokenize = skread.tokenize_line
        args = tokenize(line)
        if len(args) != 19:
            raise SketchLoadError("Invalid Ellipse specification")
        sub_type, line_style, thickness, pen_color, fill_color, depth, pen_style, area_fill, style, direction, angle, cx, cy, rx, ry, sx, sy, ex, ey = (
            args
        )
        self.fill(fill_color, area_fill)
        self.line(pen_color, thickness, const.JoinMiter, const.CapButt, line_style, style)

        center = self.trafo(cx, cy)
        radius = self.trafo.DTransform(rx, ry)
        trafo = Trafo(radius.x, 0, 0, radius.y)
        trafo = Rotation(angle)(trafo)
        trafo = Translation(center)(trafo)
        apply(self.ellipse, trafo.coeff())
        self.set_depth(depth)
Example #26
0
def coord_sys_at(lengths, pos, type):
    if len(lengths) < 2:
        return None
    for idx in range(len(lengths)):
        if lengths[idx][0] > pos:
            d2, p2 = lengths[idx]
            d1, p1 = lengths[idx - 1]
            if d2 != d1 and p1 != p2:
                break
    else:
        return None
    t = (pos - d1) / (d2 - d1)
    p = (1 - t) * p1 + t * p2
    diff = (p2 - p1).normalized()
    del lengths[:idx - 1]
    if type == PATHTEXT_SKEW:
        return Trafo(diff.x, diff.y, 0, 1, p.x, p.y)
    else:
        return Trafo(diff.x, diff.y, -diff.y, diff.x, p.x, p.y)
Example #27
0
def read_gimp_path(context, filename=''):
    if not filename:
        filename = context.application.GetOpenFilename()
        if not filename:
            return
    paths = read_path(filename)
    object = PolyBezier(paths)
    object.Transform(Trafo(1, 0, 0, -1, 0, 800))
    #context.main_window.PlaceObject(object)
    context.document.Insert(object)
Example #28
0
 def RedrawMethod(self, region = None):
     win = self.tkwin
     self.gc.StartDblBuffer()
     self.gc.SetFillColor(StandardColors.white)
     self.gc.FillRectangle(0, 0, win.width, win.height)
     if self.properties.HasFill():
         self.gc.Rectangle(Trafo(win.width, 0, 0, win.height, 0, 0))
     else:
         self.gc.SetLineColor(StandardColors.black)
         self.gc.DrawLineXY(0, win.height, win.width, 0)
     self.gc.EndDblBuffer()
Example #29
0
 def compute_trafo(self, state):
     start = self.drag_start
     end = self.drag_cur
     if state & AlternateMask:
         # start is the center of the ellipse
         if state & ConstraintMask:
             # end is a point of the periphery of a *circle* centered
             # at start
             radius = abs(start - end)
             self.trafo = Trafo(radius, 0, 0, radius, start.x, start.y)
         else:
             # end is a corner of the bounding box
             d = end - start
             self.trafo = Trafo(d.x, 0, 0, d.y, start.x, start.y)
     else:
         # the ellipse is inscribed into the rectangle with start and
         # end as opposite corners. 
         end = self.apply_constraint(self.drag_cur, state)
         d = (end - start) / 2
         self.trafo = Trafo(d.x, 0, 0, d.y, start.x + d.x, start.y + d.y)
Example #30
0
 def Hit(self, p, rect, device, clip=0):
     a = self.properties
     llx, lly, urx, ury = a.font.TextBoundingBox(self.text, a.font_size)
     trafo = self.trafo(self.atrafo)
     trafo = trafo(Trafo(urx - llx, 0, 0, ury - lly, llx, lly))
     return device.ParallelogramHit(p,
                                    trafo,
                                    1,
                                    1,
                                    1,
                                    ignore_outline_mode=1)
Example #31
0
    def read_ellipse(self, line):
        readline = self.readline
        tokenize = skread.tokenize_line
        args = tokenize(line)
        if len(args) != 19:
            raise SketchLoadError('Invalid Ellipse specification')
        sub_type, line_style, thickness, pen_color, fill_color, depth, \
                pen_style, area_fill, style, direction, angle, \
                cx, cy, rx, ry, sx, sy, ex, ey = args
        self.fill(fill_color, area_fill)
        self.line(pen_color, thickness, const.JoinMiter, const.CapButt,
                  line_style, style)

        center = self.trafo(cx, cy)
        radius = self.trafo.DTransform(rx, ry)
        trafo = Trafo(radius.x, 0, 0, radius.y)
        trafo = Rotation(angle)(trafo)
        trafo = Translation(center)(trafo)
        apply(self.ellipse, trafo.coeff())
        self.set_depth(depth)
Example #32
0
 def BoundingRect(self, pos, dir, width):
     try:
         angle = atan2(dir.y, dir.x)
     except ValueError:
         angle = 0
     if width < 1.0:
         width = 1.0
     s = width * sin(angle)
     c = width * cos(angle)
     trafo = Trafo(c, s, -s, c, pos.x, pos.y)
     return self.path.accurate_rect(trafo)
Example #33
0
 def ellipse(self, attrs):
     if self.in_defs:
         id = attrs.get('id', '')
         if id:
             self.named_objects[id] = ('object', 'ellipse', attrs)
         return
     if attrs.has_key('cx'):
         x = attrs['cx']
     else:
         x = '0'
     if attrs.has_key('cy'):
         y = attrs['cy']
     else:
         y = '0'
     x, y = self.point(x, y)
     rx, ry = self.point(attrs['rx'], attrs['ry'], relative = 1)
     t = Trafo(rx, 0, 0, ry, x, y)
     self._print('ellipse', t)
     style = attrs.get('style', '')
     if style:
         self.parse_style(style)
     self.set_loader_style()
     apply(self.loader.ellipse, t.coeff())
Example #34
0
 def ellipse(self, attrs):
     if self.in_defs:
         id = attrs.get('id', '')
         if id:
             self.named_objects[id] = ('object', 'ellipse', attrs)
         return
     if attrs.has_key('cx'):
         x = attrs['cx']
     else:
         x = '0'
     if attrs.has_key('cy'):
         y = attrs['cy']
     else:
         y = '0'
     x, y = self.point(x, y)
     rx, ry = self.point(attrs['rx'], attrs['ry'], relative=1)
     t = Trafo(rx, 0, 0, ry, x, y)
     self._print('ellipse', t)
     style = attrs.get('style', '')
     if style:
         self.parse_style(style)
     self.set_loader_style()
     apply(self.loader.ellipse, t.coeff())
Example #35
0
 def __init__(self, loader):
     self.loader = loader
     self.trafo = self.basetrafo = Trafo()
     self.state_stack = ()
     self.style = loader.style.Copy()
     self.style.line_pattern = EmptyPattern
     self.style.fill_pattern = SolidPattern(StandardColors.black)
     self.current_text = ""
     self.style.font = GetFont("Times-Roman")
     self.style.font_size = 12
     self.halign = text.ALIGN_LEFT
     self.named_objects = {}
     self.in_defs = 0
     self.paths = None
     self.path = None
     self.depth = 0
     self.indent = '    '
Example #36
0
    def Hit(self, p, rect, device, clip=0):
        bbox = self.properties.font.TextBoundingBox
        font_size = self.properties.font_size
        text = self.text
        trafos = self.trafos

        for idx in range(len(trafos)):
            llx, lly, urx, ury = bbox(text[idx], font_size)
            trafo = trafos[idx](Trafo(urx - llx, 0, 0, ury - lly, llx, lly))
            if device.ParallelogramHit(p,
                                       trafo,
                                       1,
                                       1,
                                       1,
                                       ignore_outline_mode=1):
                return 1
        return 0
Example #37
0
    def read_headers(self):
        self.file.seek(0)
        placeable = self.file.read(calcsize(struct_placeable_header))
        key, handle, left, top, right, bottom, inch, reserved, checksum\
           = unpack(struct_placeable_header, placeable)
        if key != rx_magic:
            raise SketchLoadError(
                _("The file is not a placeable "
                  "windows metafile"))
            self._print("The file is not a placeable windows metafile")
        sum = 0
        for word in unpack('<10h', placeable[:20]):
            sum = sum ^ word
        if sum != checksum:
            #raise SketchLoadError(_("The file has an incorrect checksum"))
            self._print("The file has an incorrect checksum")

        self.inch = inch
        self.bbox = (left, top, right, bottom)
        factor = 72.0 / self.inch
        self.wx = self.wy = 0
        self.wwidth = right - left
        self.wheight = bottom - top
        self.vx = self.vy = 0
        self.vwidth = self.wwidth
        self.vheight = self.wheight
        self.base_trafo = Trafo(factor, 0, 0, -factor, 0,
                                factor * self.vheight)
        self.update_trafo()

        header = self.file.read(calcsize(struct_wmf_header))
        filetype, headersize, version, filesize, numobj, maxrecord, numparams\
                = unpack(struct_wmf_header, header)

        self._print('\nHeader\n------\n')
        fmt = '% 10s: %s\n'
        self._print(fmt, 'inch', self.inch)
        self._print(fmt, 'bbox', self.bbox)
        self._print(fmt, 'headersize', headersize)
        self._print(fmt, 'version', version)
        self._print(fmt, 'numobj', numobj)
        self._print(fmt, 'numparams', numparams)
        self._print(fmt, 'maxrecord', maxrecord)
        self._print('\n')
Example #38
0
class ChooseRGBZ(ChooseComponent):

    def __init__(self, master, width, height, comp = 1, color = (0, 0, 0),
		 **kw):
	self.comp = comp
	self.win_to_color = Trafo(1, 0, 0, -1 / float(height - 1), 0, 1)
	self.color_to_win = self.win_to_color.inverse()
	apply(ChooseComponent.__init__, (self, master, width, height, color),
	      kw)

    def SetColor(self, color):
	c = self.color;
	color = apply(rgb_to_hsv, tuple(color))
	if ((self.comp == 0 and (color[1] != c[1] or color[2] != c[2]))
	    or (self.comp == 1 and (color[0] != c[0] or color[2] != c[2]))
	    or (self.comp == 2 and (color[0] != c[0] or color[1] != c[1]))):
	    self.hide_mark()
	    self.color = color
	    self.show_mark()
	    self.UpdateWhenIdle()

    def update_ramp(self):
	_sketch.fill_hsv_z(self.image.im, self.comp, self.color)
	self.set_image(self.image)

    def move_to(self, p, state):
	y = p.y
	if y < 0:	y = 0
	elif y >= 1.0:	y = 1.0

	color = list(self.color)
	color[self.comp] = y
	self.hide_mark()
	self.color = tuple(color)
	self.show_mark()
	self.issue(CHANGED, self.RGBColor())

    def draw_mark(self):
        w, h = self.image.size
        x, y = self.color_to_win(0, self.color[self.comp])
        x = int(x)
        y = int(y)
        self.invgc.DrawLine(0, y, w, y)
Example #39
0
    return array


# arrays to convert AI join and cap to Sketch's join and cap. In AI
# files they're given as small ints so we just use a tuple where we can
# use the AI cap/join value as index to get the corresponding value in
# Sketch.
_ai_join = (const.JoinMiter, const.JoinRound, const.JoinBevel)
_ai_cap = (const.CapButt, const.CapRound, const.CapProjecting)

# The same for text alignment. The last two values are two variants of
# justified text, which Sketch doesn't have, so we're just using
# centered for now.
_ai_text_align = (text.ALIGN_LEFT, text.ALIGN_CENTER, text.ALIGN_RIGHT, text.ALIGN_CENTER, text.ALIGN_CENTER)

artboard_trafo = Trafo(1, 0, 0, -1, 4014, 4716)
artboard_trafo_inv = artboard_trafo.inverse()


class FontInfo:
    def __init__(self, psname, newname, encoding):
        self.psname = psname
        self.newname = newname
        self.encoding = encoding
        self.reencoder = None

    def Reencode(self, text):
        if self.reencoder is None:
            self.reencoder = encoding.Reencoder(self.encoding, encoding.iso_latin_1)
        return self.reencoder(text)