예제 #1
0
 def dstyle(self, name=''):
     if not name:
         raise SketchLoadError(_("unnamed style"))
     style = self.style.AsDynamicStyle()
     style.SetName(name)
     self.style_dict[name] = style
     self.style = Style()
예제 #2
0
 def __init__(self, file, filename, match):
     GenericLoader.__init__(self, file, filename, match)
     self.file = file
     self.curstyle = Style()
     self.verbosity = 0
     self.gdiobjects = []
     self.dcstack = []
     self.curpoint = Point(0, 0)
예제 #3
0
 def use_style(self, name=''):
     if not name:
         raise SketchLoadError(_("unnamed style"))
     if not self.style.IsEmpty():
         self.prop_stack.load_AddStyle(self.style)
         self.style = Style()
     style = self.style_dict[name]
     self.prop_stack.load_AddStyle(style)
예제 #4
0
 def get_prop_stack(self):
     stack = self.prop_stack
     if not self.style.IsEmpty():
         stack.load_AddStyle(self.style)
     stack.condense()
     if self.base_style is not None:
         self.prop_stack = PropertyStack(base =self.base_style.Duplicate())
     else:
         self.prop_stack = PropertyStack()
     self.style = Style()
     return stack
예제 #5
0
 def __init__(self, file, filename, match):
     LoaderWithComposites.__init__(self)
     self.file = file
     self.filename = filename
     self.match = match
     self.style = Style()
     if self.base_style is not None:
         self.prop_stack = PropertyStack(base=self.base_style.Duplicate())
     else:
         self.prop_stack = PropertyStack()
     self.messages = {}
예제 #6
0
elp_radius = 2.5
elp_startx = 0
elp_starty = 0
elp.trafo = Trafo(elp_radius, 0, 0, elp_radius, elp_startx, elp_starty)
elpbz = elp.AsBezier()
elpbz_nl = elpbz.Paths()[0].NodeList() # as list of Point(x,y)
elpbz_tnl = [] # as list of tuples (x,y)
for tpnt in elpbz_nl:
	elpbz_tnl.append( (tpnt.x, tpnt.y) )
tarrw1 = Arrow(elpbz_tnl, closed=1) #_nl or _tnl - all the same here; ellipse sends four points, which in Arrow are AppendBezier (AppendLine only for two points -- but still it looks like a diamond.. )..
# the difference is in tarrw1.Paths()[0].arc_lengths() vs elpbz.Paths()[0].arc_lengths()
tarrw1.path = elpbz.Paths()[0] # and this FINALLY makes the arrow a circle!
tarrw2 = Arrow(arpath2, closed=1)

global tbase_style
tbase_style = Style()
tbase_style.fill_pattern = EmptyPattern
tbase_style.fill_transform = 1
tbase_style.line_pattern = SolidPattern(StandardColors.red)
tbase_style.line_width = 2.0
tbase_style.line_join = const.JoinMiter
tbase_style.line_cap = const.CapButt
tbase_style.line_dashes = ()
tbase_style.line_arrow1 = tarrw1
tbase_style.line_arrow2 = tarrw2
tbase_style.font = None
tbase_style.font_size = 12.0

# from create_spiral.py
from Sketch import CreatePath
예제 #7
0
from Sketch.warn import warn, INTERNAL, pdebug, warn_tb

from Sketch import load, const, plugins, SketchLoadError, SketchError
from Sketch import CreateRGBColor, SolidPattern, HatchingPattern,EmptyPattern,\
     LinearGradient, ConicalGradient, RadialGradient, ImageTilePattern, \
     Style, MultiGradient, Trafo, Translation, Point, \
     GridLayer, GuideLayer, GuideLine, Arrow, CreatePath, StandardColors, \
     GetFont

from Sketch.load import GenericLoader

from Sketch.Graphics import pagelayout, plugobj, blendgroup, text, image, eps,\
     properties

base_style = Style()
base_style.fill_pattern = EmptyPattern
base_style.fill_transform = 1
base_style.line_pattern = SolidPattern(StandardColors.black)
base_style.line_width = 0.0
base_style.line_join = const.JoinMiter
base_style.line_cap = const.CapButt
base_style.line_dashes = ()
base_style.line_arrow1 = None
base_style.line_arrow2 = None
base_style.font = None
base_style.font_size = 12.0

# sanity check: does base_style have all properties?
for key in dir(properties.factory_defaults):
    if not hasattr(base_style, key):
예제 #8
0
class WMFLoader(GenericLoader):
    def __init__(self, file, filename, match):
        GenericLoader.__init__(self, file, filename, match)
        self.file = file
        self.curstyle = Style()
        self.verbosity = 0
        self.gdiobjects = []
        self.dcstack = []
        self.curpoint = Point(0, 0)

    def _print(self, format, *args, **kw):
        if self.verbosity:
            try:
                if kw:
                    text = format % kw
                elif args:
                    text = format % args
                else:
                    text = format
            except:
                text = string.join([format] + map(str, args))
            if text[-1] != '\n':
                text = text + '\n'
            sys.stdout.write(text)

    def get_struct(self, format):
        size = calcsize(format)
        return unpack(format, self.file.read(size))

    def get_int16(self):
        return self.get_struct('<h')[0]

    def get_int32(self):
        return self.get_struct('<i')[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')

    def update_trafo(self):
        wt = Translation(-self.wx, -self.wy)
        vt = Translation(self.vx, self.vy)
        scale = Scale(
            float(self.vwidth) / self.wwidth,
            float(self.vheight) / self.wheight)
        self.trafo = self.base_trafo(vt(scale(wt)))

    def add_gdiobject(self, object):
        try:
            idx = self.gdiobjects.index(None)
        except ValueError:
            self.gdiobjects.append(object)
        else:
            self.gdiobjects[idx] = object

    def delete_gdiobject(self, idx):
        self.gdiobjects[idx] = None

    def SelectObject(self):
        idx = self.get_int16()
        try:
            object = self.gdiobjects[idx]
        except IndexError:
            print 'Index Error:', idx, self.gdiobjects
            raise
        for property, value in object:
            setattr(self.curstyle, property, value)
        self._print('->', idx, object)

    def DeleteObject(self):
        idx = self.get_int16()
        self.delete_gdiobject(idx)
        self._print('->', idx)

    def get_dc(self):
        return self.curstyle.Duplicate(), self.trafo, self.curpoint

    def set_dc(self, dc):
        self.curstyle, self.trafo, self.curpoint = dc

    def SaveDC(self):
        self.dcstack.append(self.get_dc())

    def RestoreDC(self):
        self.set_dc(self.dcstack[-1])
        del self.dcstack[-1]

    def SetMapMode(self):
        mode = self.get_int16()
        self._print('->', mode)

    def SetWindowOrg(self):
        self.wy, self.wx = self.get_struct('<hh')
        self.update_trafo()
        self._print('->', self.wx, self.wy)

    def SetWindowExt(self):
        self.wheight, self.wwidth = self.get_struct('<hh')
        self.update_trafo()
        self._print('->', self.wwidth, self.wheight)

    def SetPolyFillMode(self):
        mode = self.get_int16()
        self._print('->', mode)

    SetBkMode = noop
    SetBkColor = noop
    SetROP2 = noop

    def CreateBrushIndirect(self):
        style, r, g, b, hatch = self.get_struct('<hBBBxh')
        if style == 1:
            pattern = EmptyPattern
        else:
            pattern = SolidPattern(
                CreateRGBColor(r / 255.0, g / 255.0, b / 255.0))
        self.add_gdiobject((('fill_pattern', pattern), ))

        self._print('->', style, r, g, b, hatch)

    def DibCreatePatternBrush(self):
        self.add_message(_("Bitmap brushes not yet implemented. Using black"))
        pattern = SolidPattern(StandardColors.black)
        self.add_gdiobject((('fill_pattern', pattern), ))

    def CreatePenIndirect(self):
        style, widthx, widthy, r, g, b = self.get_struct('<hhhBBBx')
        cap = (style & 0x0F00) >> 8
        join = (style & 0x00F0) >> 4
        style = style & 0x000F
        if style == 5:
            pattern = EmptyPattern
        else:
            pattern = SolidPattern(
                CreateRGBColor(r / 255.0, g / 255.0, b / 255.0))
        width = abs(widthx * self.trafo.m11)
        self.add_gdiobject(((
            'line_pattern',
            pattern,
        ), ('line_width', width)))
        self._print('->', style, widthx, widthy, r, g, b, cap, join)

    def CreatePalette(self):
        self.add_gdiobject((('ignore', None), ))

    def CreateRegion(self):
        self.add_gdiobject((('ignore', None), ))

    CreateFontIndirect = CreatePalette
    SelectPalette = noop
    RealizePalette = noop

    SetTextColor = noop
    SetTextAlign = noop
    SetTextJustification = noop

    SetStretchBltMode = noop

    def read_points(self, num):
        coords = self.get_struct('<' + num * 'hh')
        points = []
        append = points.append
        trafo = self.trafo
        for i in range(0, 2 * num, 2):
            append(trafo(coords[i], coords[i + 1]))
        return points

    def Polyline(self):
        points = self.read_points(self.get_int16())
        if points:
            path = CreatePath()
            map(path.AppendLine, points)
            self.prop_stack.AddStyle(self.curstyle.Duplicate())
            self.prop_stack.SetProperty(fill_pattern=EmptyPattern)
            self.bezier((path, ))

        #for i in range(len(points)):
        #    self._print('->', points[i])

    def Polygon(self):
        points = self.read_points(self.get_int16())
        if points:
            path = CreatePath()
            map(path.AppendLine, points)
            if path.Node(-1) != path.Node(0):
                #print 'correct polygon'
                path.AppendLine(path.Node(0))
            path.load_close()
            self.prop_stack.AddStyle(self.curstyle.Duplicate())
            self.bezier((path, ))

        #for i in range(len(points)):
        #    self._print('->', points[i])

    def PolyPolygon(self):
        nr_of_polygons = self.get_int16()
        nr_of_points = []
        for i in range(nr_of_polygons):
            nr_of_points.append(self.get_int16())
        path = ()
        for i in nr_of_points:
            points = self.read_points(i)
            if points:
                subpath = CreatePath()
                map(subpath.AppendLine, points)
                if subpath.Node(-1) != subpath.Node(0):
                    subpath.AppendLine(subpath.Node(0))
                subpath.load_close()
                path = path + (subpath, )
        if path:
            self.prop_stack.AddStyle(self.curstyle.Duplicate())
            self.bezier(path)

    def MoveTo(self):
        y, x = self.get_struct('<hh')
        self.curpoint = self.trafo(x, y)
        self._print('->', self.curpoint)

    def LineTo(self):
        y, x = self.get_struct('<hh')
        p = self.trafo(x, y)
        self.prop_stack.AddStyle(self.curstyle.Duplicate())
        self.prop_stack.SetProperty(fill_pattern=EmptyPattern)
        path = CreatePath()
        path.AppendLine(self.curpoint)
        path.AppendLine(p)
        self.bezier((path, ))
        self.curpoint = p
        self._print('->', self.curpoint)

    def Ellipse(self):
        bottom, right, top, left = self.get_struct('<hhhh')
        left, top = self.trafo(left, top)
        right, bottom = self.trafo(right, bottom)
        self.prop_stack.AddStyle(self.curstyle.Duplicate())
        self.ellipse((right - left) / 2, 0, 0, (bottom - top) / 2,
                     (right + left) / 2, (top + bottom) / 2)

    def Arc(self, arc_type=const.ArcArc):
        ye, xe, ys, xs, bottom, right, top, left = self.get_struct('<hhhhhhhh')
        left, top = self.trafo(left, top)
        right, bottom = self.trafo(right, bottom)
        xs, ys = self.trafo(xs, ys)
        xe, ye = self.trafo(xe, ye)
        self.prop_stack.AddStyle(self.curstyle.Duplicate())
        if arc_type == const.ArcArc:
            self.prop_stack.SetProperty(fill_pattern=EmptyPattern)
        if left != right and top != bottom:
            t = Trafo((right - left) / 2, 0, 0, (bottom - top) / 2,
                      (right + left) / 2, (top + bottom) / 2).inverse()
            # swap start and end-angle
            end_angle = t(xs, ys).polar()[1]
            start_angle = t(xe, ye).polar()[1]
        else:
            start_angle = end_angle = 0.0
        self.ellipse((right - left) / 2,
                     0,
                     0, (bottom - top) / 2, (right + left) / 2,
                     (top + bottom) / 2,
                     start_angle=start_angle,
                     end_angle=end_angle,
                     arc_type=arc_type)

    def Pie(self):
        self.Arc(const.ArcPieSlice)

    def Rectangle(self):
        bottom, right, top, left = self.get_struct('<hhhh')
        left, top = self.trafo(left, top)
        right, bottom = self.trafo(right, bottom)
        self.prop_stack.AddStyle(self.curstyle.Duplicate())
        self.rectangle(right - left, 0, 0, bottom - top, left, top)

    def RoundRect(self):
        ellh, ellw, bottom, right, top, left = self.get_struct('<hhhhhh')
        left, top = self.trafo(left, top)
        right, bottom = self.trafo(right, bottom)
        ellw, ellh = self.trafo.DTransform(ellw, ellh)
        self._print('->', left, top, right, bottom, ellw, ellh)
        self.prop_stack.AddStyle(self.curstyle.Duplicate())
        self.rectangle(right - left,
                       0,
                       0,
                       bottom - top,
                       left,
                       top,
                       radius1=abs(ellw / (right - left)),
                       radius2=abs(ellh / (bottom - top)))

    def Escape(self):
        pass

    def interpret(self):
        tell = self.file.tell
        function = -1
        while function:
            pos = tell()
            size, function = self.get_struct('<ih')
            self._print('%5d: %4x: %s' %
                        (size, function, wmf_functions.get(function, '')))
            if hasattr(self, wmf_functions.get(function, '')):
                getattr(self, wmf_functions[function])()
            else:
                if function:
                    self.file.read(2 * (size - 3))
                    self._print('*** unimplemented:',
                                wmf_functions.get(function, ''))
            pos = pos + 2 * size
            if tell() < pos:
                self.file.read(pos - tell())
            elif tell() > pos:
                self._print('read too many bytes')
                self.file.seek(pos - tell(), 1)

    def Load(self):
        self.document()
        self.layer(name=_("WMF objects"))
        self.read_headers()
        self.interpret()
        self.end_all()
        self.object.load_Completed()
        return self.object
예제 #9
0
class SKLoader(GenericLoader):

    format_name = format_name

    base_style = base_style

    functions = [
        'document', 'layer', ('bezier', 'b'), ('rectangle', 'r'),
        ('ellipse', 'e'), 'group', ('group', 'G'), 'endgroup',
        ('endgroup', 'G_'), 'guess_cont'
    ]

    def __init__(self, file, filename, match):
        GenericLoader.__init__(self, file, filename, match)
        if atoi(match.group('minor')) > 2:
            self.add_message(
                _("The file was created by a newer version of "
                  "Skencil or Sketch, there might be inaccuracies."))
        if self.filename:
            self.directory = os.path.split(filename)[0]
        else:
            self.directory = ''
        self.style_dict = {}
        self.id_dict = {}
        self.page_layout = None
        self.pattern = None
        self.gradient = None
        self.arrow1 = None
        self.arrow2 = None
        self.font = None
        self.font_size = 1.0
        self.color_cache = {}

    def __del__(self):
        pass

    def warn(self, level, *args, **kw):
        message = apply(warn, (level, ) + args, kw)
        self.add_message(message)

    def get_func_dict(self):
        func_dict = {}
        for name in self.functions:
            if type(name) == StringType:
                func_dict[name] = getattr(self, name)
            else:
                func_dict[name[1]] = getattr(self, name[0])
        return func_dict

    functions.append('layout')

    def layout(self, format, orientation):
        if type(format) == StringType:
            if format not in papersizes:
                # The format is given by name but it's not one of the
                # standard papersizes. The file may be corrupted.
                self.add_message(
                    _("Unknown paper format '%s', "
                      "using A4 instead") % format)
                format = "A4"
            layout = pagelayout.PageLayout(format, orientation=orientation)
        else:
            w, h = format
            layout = pagelayout.PageLayout(width=w,
                                           height=h,
                                           orientation=orientation)
        self.page_layout = layout

    functions.append('grid')

    def grid(self, geometry, visible=0, color=None, name=None):
        if name is None:
            name = _("Grid")
        self.begin_layer_class(
            GridLayer, (geometry, visible, self.convert_color(color), name))
        self.end_composite()

    def convert_color(self, color_spec):
        try:
            c = self.color_cache.get(color_spec)
            if c:
                return c
            c = apply(CreateRGBColor, color_spec)
            self.color_cache[color_spec] = c
        except:
            # This should only happen if the color_spec is invalid
            type, value = sys.exc_info()[:2]
            warn(INTERNAL, 'Color allocation failed: %s: %s', type, value)
            c = StandardColors.black
        return c

    functions.append('gl')

    def gl(self, colors):
        c = []
        for pos, color in colors:
            c.append((pos, self.convert_color(color)))
        self.gradient = MultiGradient(c)

    functions.append('pe')

    def pe(self):
        self.pattern = EmptyPattern

    functions.append('ps')

    def ps(self, color):
        self.pattern = SolidPattern(self.convert_color(color))

    functions.append('pgl')

    def pgl(self, dx, dy, border=0):
        if not self.gradient:
            raise SketchLoadError(_("No gradient for gradient pattern"))
        self.pattern = LinearGradient(self.gradient, Point(dx, dy), border)

    functions.append('pgr')

    def pgr(self, dx, dy, border=0):
        if not self.gradient:
            raise SketchLoadError(_("No gradient for gradient pattern"))
        self.pattern = RadialGradient(self.gradient, Point(dx, dy), border)

    functions.append('pgc')

    def pgc(self, cx, cy, dx, dy):
        if not self.gradient:
            raise SketchLoadError(_("No gradient for gradient pattern"))
        self.pattern = ConicalGradient(self.gradient, Point(cx, cy),
                                       Point(dx, dy))

    functions.append('phs')

    def phs(self, color, background, dx, dy, dist, width):
        self.pattern = HatchingPattern(self.convert_color(color),
                                       self.convert_color(background),
                                       Point(dx, dy), dist, width)

    functions.append('pit')

    def pit(self, id, trafo):
        trafo = apply(Trafo, trafo)
        self.pattern = ImageTilePattern(self.id_dict[id], trafo)

    functions.append('fp')

    def fp(self, color=None):
        if color is None:
            self.style.fill_pattern = self.pattern
        else:
            self.style.fill_pattern = SolidPattern(self.convert_color(color))

    functions.append('fe')

    def fe(self):
        self.style.fill_pattern = EmptyPattern

    functions.append('ft')

    def ft(self, bool):
        self.style.fill_transform = bool

    functions.append('lp')

    def lp(self, color=None):
        if color is None:
            self.style.line_pattern = self.pattern
        else:
            self.style.line_pattern = SolidPattern(self.convert_color(color))

    functions.append('le')

    def le(self):
        self.style.line_pattern = EmptyPattern

    functions.append('lw')

    def lw(self, width):
        self.style.line_width = width

    functions.append('lj')

    def lj(self, join):
        self.style.line_join = join

    functions.append('lc')

    def lc(self, cap):
        if not 1 <= cap <= 3:
            self.add_message('line cap corrected from %d to 1' % cap)
            cap = 1
        self.style.line_cap = cap

    functions.append('ld')

    def ld(self, dashes):
        self.style.line_dashes = dashes

    functions.append('la1')

    def la1(self, args=None, head=None):
        #print head
        if args is not None:
            self.style.line_arrow1 = apply(Arrow, args)
        else:
            self.style.line_arrow1 = None

    functions.append('la2')

    def la2(self, args=None):
        if args is not None:
            self.style.line_arrow2 = apply(Arrow, args)
        else:
            self.style.line_arrow2 = None

    functions.append('dstyle')

    def dstyle(self, name=''):
        if not name:
            raise SketchLoadError(_("unnamed style"))
        style = self.style.AsDynamicStyle()
        style.SetName(name)
        self.style_dict[name] = style
        self.style = Style()

    functions.append(('use_style', 'style'))

    def use_style(self, name=''):
        if not name:
            raise SketchLoadError(_("unnamed style"))
        if not self.style.IsEmpty():
            self.prop_stack.load_AddStyle(self.style)
            self.style = Style()
        style = self.style_dict[name]
        self.prop_stack.load_AddStyle(style)

    functions.append('Fn')

    def Fn(self, name):
        self.style.font = GetFont(name)

    functions.append('Fs')

    def Fs(self, size):
        self.style.font_size = size

    functions.append('guide')

    def guide(self, pos, horizontal):
        if horizontal:
            p = Point(0, pos)
        else:
            p = Point(pos, 0)
        self.append_object(GuideLine(p, horizontal))

    functions.append('guidelayer')

    def guidelayer(self, *args, **kw):
        self.begin_layer_class(GuideLayer, args, kw)

    def bezier_load(self, line):
        bezier = self.object
        while 1:
            try:
                bezier.paths[-1].append_from_string(line)
                line = bezier.paths[-1].append_from_file(self.file)
            except:
                warn(INTERNAL, _("Error reading line %s"), ` line `)
                line = self.file.readline()
            if line[:2] == 'bC':
                bezier.paths[-1].load_close()
                line = self.file.readline()
            if line[:2] == 'bn':
                bezier.paths = bezier.paths + (CreatePath(), )
                line = self.file.readline()
            else:
                break
            if line[:2] not in ('bs', 'bc'):
                break
        return line

    functions.append('txt')

    def txt(self,
            thetext,
            trafo,
            halign=text.ALIGN_LEFT,
            valign=text.ALIGN_BASE):
        if len(trafo) == 2:
            trafo = Translation(trafo)
        else:
            trafo = apply(Trafo, trafo)
        object = text.SimpleText(text=thetext,
                                 trafo=trafo,
                                 halign=halign,
                                 valign=valign,
                                 properties=self.get_prop_stack())
        self.append_object(object)

    functions.append('im')

    def im(self, trafo, id):
        if len(trafo) == 2:
            trafo = Translation(trafo)
        else:
            trafo = apply(Trafo, trafo)
        self.append_object(image.Image(self.id_dict[id], trafo=trafo))

    functions.append('bm')

    def bm(self, id, filename=None):
        if filename is None:
            from streamfilter import Base64Decode, SubFileDecode
            decoder = Base64Decode(SubFileDecode(self.file, '-'))
            data = image.load_image(decoder)
        else:
            data = image.load_image(os.path.join(self.directory, filename))
        self.id_dict[id] = data

    functions.append('eps')

    def eps(self, trafo, filename):
        if len(trafo) == 2:
            trafo = Translation(trafo)
        else:
            trafo = apply(Trafo, trafo)
        if not os.path.isabs(filename):
            if self.directory:
                filename = os.path.join(self.directory, filename)
            else:
                filename = os.path.join(os.getcwd(), filename)
        self.append_object(eps.EpsImage(filename=filename, trafo=trafo))

    functions.append('B')

    def B(self, *args, **kw):
        self.begin_composite(blendgroup.BlendGroup, args, kw)

    functions.append('B_')

    def B_(self):
        self.end_composite()

    functions.append('Bi')

    def Bi(self, *args, **kw):
        self.begin_composite(blendgroup.BlendInterpolation, args, kw)
        self.end_composite()

    group = GenericLoader.begin_group
    endgroup = GenericLoader.end_group

    functions.append('M')

    def M(self, *args, **kw):
        from Sketch.Graphics import maskgroup
        self.begin_composite(maskgroup.MaskGroup, args, kw)

    functions.append('M_')

    def M_(self):
        self.end_composite()

    functions.append('PT')

    def PT(self, *args, **kw):
        self.begin_composite(text.PathText, args, kw)

    functions.append('pt')

    def pt(self, thetext, *args):
        matrix = ()
        model = text.PATHTEXT_ROTATE
        start_pos = 0.0
        if args:
            if type(args[0]) == TupleType:
                matrix = args[0]
                args = args[1:]
            if args:
                model = args[0]
                if len(args) > 1:
                    start_pos = args[1]

        if matrix:
            trafo = apply(Trafo, matrix)
        else:
            trafo = None

        self.append_object(
            text.InternalPathText(thetext,
                                  trafo=trafo,
                                  model=model,
                                  start_pos=start_pos,
                                  properties=self.get_prop_stack()))

    functions.append('PT_')

    def PT_(self):
        self.end_composite()

    functions.append('PC')

    def PC(self, class_name, *args, **kw):
        kw['loading'] = 1
        info = plugins.find_object_plugin(class_name)
        if info is not None:
            try:
                theclass = info.Constructor()
                self.begin_composite(theclass, args, kw)
                return
            except SketchError:
                pass
        # constructing the plugin object failed. Use an UnknownPlugin
        # object.
        self.add_message(_("Unknown Plugin: %s") % class_name)
        self.begin_composite(plugobj.UnknownPlugin, (class_name, ) + args, kw)

    functions.append('PC_')

    def PC_(self):
        self.end_composite()

    #
    #	The loader driver
    #

    def Load(self):
        file = self.file
        if type(file) == StringType:
            file = open(file, 'r')
        dict = self.get_func_dict()
        from Sketch import skread
        parse = skread.parse_sk_line2
        readline = file.readline
        bezier_load = self.bezier_load
        num = 1
        line = '#'
        if __debug__:
            import time
            start_time = time.clock()
        try:
            line = readline()
            while line:
                num = num + 1
                if line[0] == 'b' and line[1] in 'sc':
                    line = bezier_load(line)
                    continue
                #parse(line, dict)
                funcname, args, kwargs = parse(line)
                if funcname is not None:
                    function = dict.get(funcname)
                    if function is not None:
                        try:
                            apply(function, args, kwargs)
                        except TypeError:
                            tb = sys.exc_info()[2]
                            try:
                                if tb.tb_next is None:
                                    # the exception was raised by apply
                                    # and not within the function. Try to
                                    # invoke the function with fewer
                                    # arguments
                                    if call_function(function, args, kwargs):
                                        message = _("Omitted some arguments "
                                                    "for function %s")
                                    else:
                                        message = _("Cannot call function %s")
                                    self.add_message(message %
                                                     function.__name__)

                                else:
                                    raise
                            finally:
                                del tb
                    else:
                        self.add_message(_("Unknown function %s") % funcname)

                line = readline()

        except (SketchLoadError, SyntaxError), value:
            # a loader specific error occurred
            warn_tb(INTERNAL, 'error in line %d', num)
            if load._dont_handle_exceptions:
                raise
            else:
                raise SketchLoadError('%d:%s' % (num, value))
        except:
예제 #10
0
from Sketch.warn import warn, INTERNAL, pdebug, warn_tb

from Sketch import load, const, plugins, SketchLoadError, SketchError
from Sketch import CreateRGBColor, SolidPattern, HatchingPattern,EmptyPattern,\
     LinearGradient, ConicalGradient, RadialGradient, ImageTilePattern, \
     Style, MultiGradient, Trafo, Translation, Point, \
     GridLayer, GuideLayer, GuideLine, Arrow, CreatePath, StandardColors, \
     GetFont

from Sketch.load import GenericLoader

from Sketch.Graphics import pagelayout, plugobj, blendgroup, text, image, eps,\
     properties

base_style = Style()
base_style.fill_pattern = EmptyPattern
base_style.fill_transform = 1
base_style.line_pattern = SolidPattern(StandardColors.black)
base_style.line_width = 0.0
base_style.line_join = const.JoinMiter
base_style.line_cap = const.CapButt
base_style.line_dashes = ()
base_style.line_arrow1 = None
base_style.line_arrow2 = None
base_style.font = None
base_style.font_size = 12.0

# sanity check: does base_style have all properties?
for key in dir(properties.factory_defaults):
    if not hasattr(base_style, key):
예제 #11
0
import struct
import operator
import copy
import types

from Sketch import _, Trafo, Scale, Translation, Point, Polar, CreatePath, \
     CreateRGBColor, SolidPattern, EmptyPattern, LinearGradient, \
     MultiGradient, Style, const, StandardColors, GridLayer, GetFont, \
     HatchingPattern

from Sketch.warn import INTERNAL, warn_tb
from Sketch.load import GenericLoader, SketchLoadError
import Sketch.Graphics.font
from Sketch.Graphics import text

basestyle = Style()
basestyle.fill_pattern = EmptyPattern
basestyle.fill_transform = 1
basestyle.line_pattern = EmptyPattern
basestyle.line_width = 1.0
basestyle.line_join = const.JoinMiter
basestyle.line_cap = const.CapButt
basestyle.line_dashes = ()
basestyle.line_arrow1 = None
basestyle.line_arrow2 = None
basestyle.font = None
basestyle.font_size = 12.0

CGM_ID = {
    0x0020: 'BEGMF',
    0x0040: 'ENDMF',
예제 #12
0
class GenericLoader(LoaderWithComposites):

    format_name = ''

    base_style = None

    def __init__(self, file, filename, match):
        LoaderWithComposites.__init__(self)
        self.file = file
        self.filename = filename
        self.match = match
        self.style = Style()
        if self.base_style is not None:
            self.prop_stack = PropertyStack(base=self.base_style.Duplicate())
        else:
            self.prop_stack = PropertyStack()
        self.messages = {}

    def get_prop_stack(self):
        stack = self.prop_stack
        if not self.style.IsEmpty():
            stack.load_AddStyle(self.style)
        stack.condense()
        if self.base_style is not None:
            self.prop_stack = PropertyStack(base =self.base_style.Duplicate())
        else:
            self.prop_stack = PropertyStack()
        self.style = Style()
        return stack

    def set_prop_stack(self, stack):
        self.prop_stack = stack

    def document(self, *args, **kw):
        self.begin_composite(doc_class, args, kw)

    def layer(self, *args, **kw):
        self.begin_layer_class(layer.Layer, args, kw)

    def end_layer(self):
        self.end_composite()

    def begin_layer_class(self, layer_class, args, kw = None):
        if issubclass(self.composite_class, layer.Layer):
            self.end_composite()
        if issubclass(self.composite_class, doc_class):
            self.begin_composite(layer_class, args, kw)
        else:
            raise SketchLoadError('self.composite_class is %s, not a document',
                                  self.composite_class)

    def bezier(self, paths = None):
        self.append_object(PolyBezier(paths = paths,
                                      properties = self.get_prop_stack()))

    def rectangle(self, m11, m21, m12, m22, v1, v2, radius1 = 0, radius2 = 0):
        trafo = Trafo(m11, m21, m12, m22, v1, v2)
        self.append_object(Rectangle(trafo, radius1 = radius1,
                                     radius2 = radius2,
                                     properties = self.get_prop_stack()))

    def ellipse(self, m11, m21, m12, m22, v1, v2, start_angle = 0.0,
                end_angle = 0.0, arc_type = ArcPieSlice):
        self.append_object(Ellipse(Trafo(m11, m21, m12, m22, v1, v2),
                                   start_angle, end_angle, arc_type,
                                   properties = self.get_prop_stack()))
    def simple_text(self, str, trafo = None, valign = text.ALIGN_BASE,
                    halign = text.ALIGN_LEFT):
        if type(trafo) == TupleType:
            if len(trafo) == 2:
                trafo = apply(Translation, trafo)
            else:
                raise TypeError, "trafo must be a Trafo-object or a 2-tuple"
        self.append_object(text.SimpleText(text = str, trafo = trafo,
                                           valign = valign, halign = halign,
                                           properties = self.get_prop_stack()))

    def image(self, image, trafo):
        if type(trafo) == TupleType:
            if len(trafo) == 2:
                trafo = apply(Translation, trafo)
            else:
                raise TypeError, "trafo must be a Trafo-object or a 2-tuple"
        image = ImageData(image)
        self.append_object(Image(image, trafo = trafo))

    def begin_group(self, *args, **kw):
        self.begin_composite(group.Group, args, kw)

    def end_group(self):
        self.end_composite()

    def guess_cont(self):
        self.guess_continuity = 1

    def end_composite(self):
        isdoc = self.composite_class is doc_class
        LoaderWithComposites.end_composite(self)
        if isdoc:
            self.add_meta(self.object)

    def add_meta(self, doc):
        doc.meta.fullpathname = self.filename
        dir, name = os.path.split(self.filename)
        doc.meta.directory = dir
        doc.meta.filename = name
        doc.meta.native_format = 0
        doc.meta.format_name = self.format_name

    def add_message(self, message):
        pdebug(('load', 'echo_messages'), message)
        self.messages[message] = self.messages.get(message, 0) + 1

    def Messages(self):
        messages = self.messages.items()
        list = []
        for message, count in messages:
            if count > 1:
                list.append(_("%(message)s (%(count)d times)") % locals())
            else:
                list.append(message)
        list.sort()
        return string.join(list, '\n')
예제 #13
0
import struct
import operator
import copy
import types

from Sketch import _, Trafo, Scale, Translation, Point, Polar, CreatePath, \
     CreateRGBColor, SolidPattern, EmptyPattern, LinearGradient, \
     MultiGradient, Style, const, StandardColors, GridLayer, GetFont, \
     HatchingPattern

from Sketch.warn import INTERNAL, warn_tb
from Sketch.load import GenericLoader, SketchLoadError
import Sketch.Graphics.font
from Sketch.Graphics import text

basestyle = Style()
basestyle.fill_pattern = EmptyPattern
basestyle.fill_transform = 1
basestyle.line_pattern = EmptyPattern
basestyle.line_width = 1.0
basestyle.line_join = const.JoinMiter
basestyle.line_cap = const.CapButt
basestyle.line_dashes = ()
basestyle.line_arrow1 = None
basestyle.line_arrow2 = None
basestyle.font = None
basestyle.font_size = 12.0


CGM_ID = {
    0x0020: 'BEGMF',