Ejemplo n.º 1
0
def _search_dir(dir, recurse, package = _plugin_package_name):
	try:
		files = os.listdir(dir)
	except os.error, value:
		warn(USER, _("Cannot list directory %(filename)s\n%(message)s"),
				filename = dir, message = value[1])
		return
Ejemplo n.º 2
0
	def Info(self):
		selected = 0
		idx = None
		paths = self.paths
		for i in range(len(paths)):
			path = paths[i]
			count = path.selection_count()
			if count > 0:
				selected = selected + count
				idx = i
		if selected > 1:
			return _("%d nodes in PolyBezier") % selected
		else:
			if idx is not None:
				path = paths[idx]
				for i in range(path.len):
					if path.SegmentSelected(i):
						break
				else:
					warn(INTERNAL, 'Strange selection count')
					return _("PolyBezier")
				if i == 0:
					return _("First node of PolyBezier")
				elif i == path.len - 1:
					return _("Last node of PolyBezier")
				else:
					return _("1 node of PolyBezier")
			else:
				if self.selection_type == SelCurvePoint:
					return _("Point on curve at position %.2f") \
							% self.selected_idx
				else:
					return _("No Node of PolyBezier")
Ejemplo n.º 3
0
def load_drawing_from_file(file, filename = '', doc_class = None):
	# Note: the doc_class argument is only here for plugin interface
	# compatibility with 0.7 (especiall e.g. gziploader)
	line = file.readline()
	# XXX ugly hack for riff-based files, e.g. Corel's CMX. The length
	# might contain newline characters.
	if line[:4] == 'RIFF' and len(line) < 12:
		line = line + file.read(12 - len(line))
	#print line
	for info in plugins.import_plugins:
		match = info.rx_magic.match(line)
		if match:
			loader = info(file, filename, match)
			try:
				if do_profile:
					import profile
					warn(INTERNAL, 'profiling...')
					prof = profile.Profile()
					prof.runctx('loader.Load()', globals(), locals())
					prof.dump_stats(os.path.join(info.dir, info.module_name + '.prof'))
					warn(INTERNAL, 'profiling... (done)')
					doc = loader.object
				else:
					#t = time.clock()
					doc = loader.Load()
					#print 'load in', time.clock() - t, 'sec.'
				messages = loader.Messages()
				if messages:
					doc.meta.load_messages = messages
				return doc
			finally:
				info.UnloadPlugin()
	else:
		raise SketchLoadError(_("unrecognised file type"))
Ejemplo n.º 4
0
def read_metric(ps_name):
	for afm in ps_to_filename[ps_name]:
		afm = afm + '.afm'
		filename = find_in_path(config.font_path, afm)
		if filename:
			if __debug__:
				import time
				start = time.clock()
			metric = read_afm_file(filename)
			if __debug__:
				pdebug('timing', 'time to read afm %s: %g', afm,
						time.clock() - start)
			return metric
	else:
		if not _warned_about_afm.get(afm):
			warn(USER,
					_("I cannot find the metrics for the font %(ps_name)s.\n"
					"The file %(afm)s is not in the font_path.\n"
					"I'll use the metrics for %(fallback)s instead."),
					ps_name = ps_name, afm = afm,
					fallback = config.preferences.fallback_font)
			_warned_about_afm[afm] = 1
		if ps_name != config.preferences.fallback_font:
			return read_metric(config.preferences.fallback_font)
		else:
			raise SketchError("Can't load metrics for fallback font %s",
								config.preferences.fallback_font)
Ejemplo n.º 5
0
	def convert_color(self, color_spec):
		try:
			c = self.color_cache.get(color_spec)
			if c:
				return c
			if color_spec[0] == 'RGB' and len(color_spec) == 4:
				c = CreateRGBColor(color_spec[1], color_spec[2], color_spec[3])
			elif color_spec[0] == 'RGB' and len(color_spec) == 5:
				c = CreateRGBAColor(color_spec[1], color_spec[2], color_spec[3], color_spec[4])
			elif color_spec[0] == 'CMYK' and len(color_spec) == 5:
				c = CreateCMYKColor(color_spec[1], color_spec[2], color_spec[3], color_spec[4])
			elif color_spec[0] == 'CMYK' and len(color_spec) == 6:
				c = CreateCMYKAColor(color_spec[1], color_spec[2], color_spec[3], color_spec[4], color_spec[5])
			elif color_spec[0] == 'SPOT' and len(color_spec) == 10:
				c = CreateSPOTColor(color_spec[3], color_spec[4], color_spec[5],
								color_spec[6], color_spec[7], color_spec[8], color_spec[9],
								color_spec[2], color_spec[1])
			elif color_spec[0] == 'SPOT' and len(color_spec) == 11:
				c = CreateSPOTAColor(color_spec[3], color_spec[4], color_spec[5],
								color_spec[6], color_spec[7], color_spec[8], color_spec[9],
								color_spec[10], color_spec[2], color_spec[1])
			else:
				c = apply(ParseSketchColor, 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
Ejemplo n.º 6
0
	def InitFromWidget(self, widget, files, basedir):
		for name in files:
			file_base = os.path.join(basedir, name)
			try:
				pixmap = widget.ReadBitmapFile(file_base + '.xbm')[2]
				setattr(self, name, pixmap)
			except IOError, info:
				warn(USER, "Warning: Can't load Pixmap from %s: %s",
						file_base + '.xbm', info)
Ejemplo n.º 7
0
 def InitFromWidget(self, widget, files, basedir):
     for name in files:
         file_base = os.path.join(basedir, name)
         try:
             pixmap = widget.ReadBitmapFile(file_base + '.xbm')[2]
             setattr(self, name, pixmap)
         except IOError, info:
             warn(USER, "Warning: Can't load Pixmap from %s: %s",
                  file_base + '.xbm', info)
Ejemplo n.º 8
0
	def get_sensitive(self):
		if self.sensitive_cb:
			method = self.get_method(self.sensitive_cb)
			if method:
				return method()
			else:
				warn(INTERNAL, 'no method for sensitive_cb (%s)',
						self.sensitive_cb)
				return 0
		return 1
Ejemplo n.º 9
0
 def get_sensitive(self):
     if self.sensitive_cb:
         method = self.get_method(self.sensitive_cb)
         if method:
             return method()
         else:
             warn(INTERNAL, 'no method for sensitive_cb (%s)',
                  self.sensitive_cb)
             return 0
     return 1
Ejemplo n.º 10
0
	def __getattr__(self, attr):
		# if a lazy attribute is accessed, compute it.
		method = self._lazy_attrs.get(attr)
		if method:
			getattr(self, method)()
			# now it should work... use self.__dict__ directly to avoid
			# recursion if the method is buggy
			try:
				return self.__dict__[attr]
			except KeyError, msg:
				warn(INTERNAL, '%s did not compute %s for %s.', method, attr, self)
Ejemplo n.º 11
0
	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
Ejemplo n.º 12
0
	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
Ejemplo n.º 13
0
 def Add(self, script, menu=()):
     if type(menu) == StringType:
         menu = (menu,)
     self.registry[script.name] = script
     submenu = self.menu
     for item in menu:
         if submenu.has_key(item):
             if type(submenu[item]) != DictType:
                 warn(USER, 'Replacing menu entry "%s" with a submenu', item)
                 submenu[item] = {}
         else:
             submenu[item] = {}
         submenu = submenu[item]
     submenu[script.Title()] = script
Ejemplo n.º 14
0
def fill_colormap(cmap):
    max = 65535
    colors = []
    color_idx = []
    failed = 0

    shades_r, shades_g, shades_b, shades_gray = config.preferences.color_cube
    max_r = shades_r - 1
    max_g = shades_g - 1
    max_b = shades_b - 1

    for red in range(shades_r):
        red = float_to_x(red / float(max_r))
        for green in range(shades_g):
            green = float_to_x(green / float(max_g))
            for blue in range(shades_b):
                blue = float_to_x(blue / float(max_b))
                colors.append((red, green, blue))
    for i in range(shades_gray):
        value = int((i / float(shades_gray - 1)) * max)
        colors.append((value, value, value))

    for red, green, blue in colors:
        try:
            ret = cmap.AllocColor(red, green, blue)
            color_idx.append(ret[0])
        except:
            color_idx.append(None)
            failed = 1

    if failed:
        warn(USER,
             _("I can't alloc all needed colors. I'll use a private colormap"))
        warn(INTERNAL, "allocated colors without private colormap: %d",
             len(filter(lambda i: i is None, color_idx)))
        if config.preferences.reduce_color_flashing:
            #print 'reduce color flashing'
            cmap = cmap.CopyColormapAndFree()
            for idx in range(len(color_idx)):
                if color_idx[idx] is None:
                    color_idx[idx] = apply(cmap.AllocColor, colors[idx])[0]
        else:
            #print "don't reduce color flashing"
            cmap = cmap.CopyColormapAndFree()
            cmap.FreeColors(filter(lambda i: i is not None, color_idx), 0)
            color_idx = []
            for red, green, blue in colors:
                color_idx.append(cmap.AllocColor(red, green, blue)[0])

    return cmap, color_idx
Ejemplo n.º 15
0
def GetFont(fontname):
	if font_cache.has_key(fontname):
		return font_cache[fontname]
	if not fontmap.has_key(fontname):
		if not _warned_about_font.get(fontname):
			warn(USER, _("I can't find font %(fontname)s. "
							"I'll use %(fallback)s instead"),
					fontname = fontname,
					fallback = config.preferences.fallback_font)
			_warned_about_font[fontname] = 1
		if fontname != config.preferences.fallback_font:
			return GetFont(config.preferences.fallback_font)
		raise ValueError, 'Cannot find font %s.' % fontname
	return Font(fontname)
Ejemplo n.º 16
0
def fill_colormap(cmap):
	max = 65535
	colors = []
	color_idx = []
	failed = 0
	
	shades_r, shades_g, shades_b, shades_gray = config.preferences.color_cube
	max_r = shades_r - 1
	max_g = shades_g - 1
	max_b = shades_b - 1

	for red in range(shades_r):
		red = float_to_x(red / float(max_r))
		for green in range(shades_g):
			green = float_to_x(green / float(max_g))
			for blue in range(shades_b):
				blue = float_to_x(blue / float(max_b))
				colors.append((red, green, blue))
	for i in range(shades_gray):
		value = int((i / float(shades_gray - 1)) * max)
		colors.append((value, value, value))

	for red, green, blue in colors:
		try:
			ret = cmap.AllocColor(red, green, blue)
			color_idx.append(ret[0])
		except:
			color_idx.append(None)
			failed = 1

	if failed:
		warn(USER,
				_("I can't alloc all needed colors. I'll use a private colormap"))
		warn(INTERNAL, "allocated colors without private colormap: %d",
				len(filter(lambda i: i is None, color_idx)))
		if config.preferences.reduce_color_flashing:
			#print 'reduce color flashing'
			cmap = cmap.CopyColormapAndFree()
			for idx in range(len(color_idx)):
				if color_idx[idx] is None:
					color_idx[idx] = apply(cmap.AllocColor, colors[idx])[0]
		else:
			#print "don't reduce color flashing"
			cmap = cmap.CopyColormapAndFree()
			cmap.FreeColors(filter(lambda i: i is not None, color_idx), 0)
			color_idx = []
			for red, green, blue in colors:
				color_idx.append(cmap.AllocColor(red, green, blue)[0])
				
	return cmap, color_idx
Ejemplo n.º 17
0
 def Add(self, script, menu=()):
     if type(menu) == StringType:
         menu = (menu, )
     self.registry[script.name] = script
     submenu = self.menu
     for item in menu:
         if submenu.has_key(item):
             if type(submenu[item]) != DictType:
                 warn(USER, 'Replacing menu entry "%s" with a submenu',
                      item)
                 submenu[item] = {}
         else:
             submenu[item] = {}
         submenu = submenu[item]
     submenu[script.Title()] = script
Ejemplo n.º 18
0
	def Load(self):
		try:			
			self.file.seek(0)
			cdr = RiffChunk()
			cdr.load(self.file.read())
			app.updateInfo(inf2=_("Parsing is finished"),inf3=10)
			
			self.document()
			
			
			if self.verbosity:
				text=''
				if cdr.infocollector.cdr_version>0:
					text+='CorelDRAW ver.%u'%cdr.infocollector.cdr_version+'          \n'
					text+='   Pages: %u'%(cdr.infocollector.pages-1)+'\n'
					text+='   Layers: %u'%(cdr.infocollector.layers/cdr.infocollector.pages)+'\n'
					text+='   Groups: %u'%cdr.infocollector.groups+'\n'
					text+='   Objects: %u'%cdr.infocollector.objects+'\n'
					text+='   Bitmaps: %u'%cdr.infocollector.bitmaps+'\n'
					if cdr.infocollector.compression:
						text+='   COMPRESSED'
				sys.stderr.write(text)
			
			if cdr.infocollector.cdr_version>6:
				self.info=cdr.infocollector
				self.info.loader=self
				self.info.process_properties()
				
				self.import_curves()
				
			else:
				warn(USER, 'File <'+self.filename+
										'> contains usupported CorelDRAW ver.%u'%cdr.infocollector.cdr_version+'.0 drawing')
			self.end_all()
			self.object.load_Completed()
			self.object.pages.remove(self.object.pages[-1])
			self.object.pages.reverse()
			self.object.active_page=len(self.object.pages)-1
			self.object.setActivePage(0)
			
			return self.object
		
		except RiffEOF:
			raise SketchLoadError(_("Unexpected problems in file parsing"))
		except:
			import traceback
			traceback.print_exc()
			raise
Ejemplo n.º 19
0
	def SetTrafoAndRadii(self, trafo, radius1, radius2):
		undo = self.SetTrafoAndRadii, self.trafo, self.radius1, self.radius2
		self.trafo = trafo
		if radius1 <= 0 or radius2 <= 0:
			self.radius1 = 0
			self.radius2 = 0
			if __debug__:
				if radius1 > 0 or radius2 > 0:
					warn(INTERNAL,
							'Rectangle radius corrected: r1 = %g, r2 = %g',
							radius1, radius2)
		else:
			self.radius1 = radius1
			self.radius2 = radius2
		self._changed()
		return undo
Ejemplo n.º 20
0
def make_file_names(filenames, subdir = ''):
	default = 'error'	# a standard Tk bitmap
	for name in filenames:
		fullname = os.path.join(config.pixmap_dir, subdir, name)
		if os.path.exists(fullname + '.png'):
			setattr(PixmapTk, name, '*' + fullname + '.png')
		elif os.path.exists(fullname + '.gif'):
			setattr(PixmapTk, name, '*' + fullname + '.gif')
		elif os.path.exists(fullname + '.ppm'):
			setattr(PixmapTk, name, '@' + fullname + '.ppm')
		elif os.path.exists(fullname + '.xbm'):
			setattr(PixmapTk, name, '@' + fullname + '.xbm')
		else:
			warn(USER, "Warning: no file %s substituting '%s'",
					fullname, default)
			setattr(PixmapTk, name, default)
Ejemplo n.º 21
0
def make_file_names(filenames, subdir=''):
    default = 'error'  # a standard Tk bitmap
    for name in filenames:
        fullname = os.path.join(config.pixmap_dir, subdir, name)
        if os.path.exists(fullname + '.png'):
            setattr(PixmapTk, name, '*' + fullname + '.png')
        elif os.path.exists(fullname + '.gif'):
            setattr(PixmapTk, name, '*' + fullname + '.gif')
        elif os.path.exists(fullname + '.ppm'):
            setattr(PixmapTk, name, '@' + fullname + '.ppm')
        elif os.path.exists(fullname + '.xbm'):
            setattr(PixmapTk, name, '@' + fullname + '.xbm')
        else:
            warn(USER, "Warning: no file %s substituting '%s'", fullname,
                 default)
            setattr(PixmapTk, name, default)
Ejemplo n.º 22
0
def GetFont(fontname):
	if font_cache.has_key(fontname):
		return font_cache[fontname]
	if not fontmap.has_key(fontname):
		if not _warned_about_font.get(fontname):
			warn(USER, _("I can't find font %(fontname)s. "
							"I'll use %(fallback)s instead"),
					fontname = fontname,
					fallback = config.preferences.fallback_font)
			warn(USER, _("Fontsystem not yet implemented in UniConvertor. "
					"See /usr/share/doc/python-uniconvertor/README.Debian for more info"))
			_warned_about_font[fontname] = 1
		if fontname != config.preferences.fallback_font:
			return GetFont(config.preferences.fallback_font)
		raise ValueError, 'Cannot find font %s.' % fontname
	return Font(fontname)
Ejemplo n.º 23
0
 def SetTrafoAndRadii(self, trafo, radius1, radius2):
     undo = self.SetTrafoAndRadii, self.trafo, self.radius1, self.radius2
     self.trafo = trafo
     if radius1 <= 0 or radius2 <= 0:
         self.radius1 = 0
         self.radius2 = 0
         if __debug__:
             if radius1 > 0 or radius2 > 0:
                 warn(INTERNAL,
                      'Rectangle radius corrected: r1 = %g, r2 = %g',
                      radius1, radius2)
     else:
         self.radius1 = radius1
         self.radius2 = radius2
     self._changed()
     return undo
Ejemplo n.º 24
0
	def __getattr__(self, attr):
		try:
			access = self._object.script_access[attr]
		except KeyError:
			if not safe_special_methods.get(attr):
				warn(USER,'Cant access attribute %s of %s in safe user script', attr, self._object)
			raise AttributeError, attr
		if access == SCRIPT_UNDO:
			return UndoMethodWrapper(getattr(self._object, attr), self._document)
		elif access == SCRIPT_GET:
			return getattr(self._object, attr)
		elif access == SCRIPT_OBJECT:
			return ObjectMethodWrapper(getattr(self._object, attr), self._document)
		elif access == SCRIPT_OBJECTLIST:
			return ObjectListMethodWrapper(getattr(self._object, attr), self._document)
		else:
			raise AttributeError, attr
Ejemplo n.º 25
0
 def init_var(self):
     lo, hi = self.range
     value = self.value
     if lo is None:
         if hi is not None:
             if value > hi:
                 value = hi
     else:
         if hi is None:
             if value < lo:
                 value = lo
         else:
             value = max(lo, min(hi, value))
     if value != self.value:
         warn(USER,
              'Initial value in parameter %s of plugin %s out of range',
              self.name, self.panel.title)
     self.var.set(value)
Ejemplo n.º 26
0
	def init_var(self):
		lo, hi = self.range
		value = self.value
		if lo is None:
			if hi is not None:
				if value > hi:
					value = hi
		else:
			if hi is None:
				if value < lo:
					value = lo
			else:
				value = max(lo, min(hi, value))
		if value != self.value:
			warn(USER,
					'Initial value in parameter %s of plugin %s out of range',
					self.name, self.panel.title)
		self.var.set(value)
Ejemplo n.º 27
0
def Undo(info):
    # execute a single undoinfo
    func = info[0]
    if type(func) == StringType:
        text = func
        func = info[1]
        args = info[2:]
    else:
        args = info[1:]
        text = None
    try:
        redo = apply(func, args)
        if text is not None and callable(redo[0]):
            return (text, ) + redo
        else:
            return redo
    except:
        warn(INTERNAL, 'Exception in undo:\ninfo: %s\nfunc: %s\nargs: %s',
             info, func, args)
        warn_tb(INTERNAL)
Ejemplo n.º 28
0
def Undo(info):
	# execute a single undoinfo
	func = info[0]
	if type(func) == StringType:
		text = func
		func = info[1]
		args = info[2:]
	else:
		args = info[1:]
		text = None
	try:
		redo = apply(func, args)
		if text is not None and callable(redo[0]):
			return (text,) + redo
		else:
			return redo
	except:
		warn(INTERNAL, 'Exception in undo:\ninfo: %s\nfunc: %s\nargs: %s',
				info, func, args)
		warn_tb(INTERNAL)
Ejemplo n.º 29
0
 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
Ejemplo n.º 30
0
    def CallObjectMethod(self, aclass, methodname, args):
        if len(self.objects) == 1:
            if self.editor is not None:
                obj = self.editor
                if not obj.compatible(aclass):
                    warn(
                        INTERNAL,
                        "EditSelection.GetObjectMethod: " "editor %s is not compatible with class %s",
                        self.editor,
                        aclass,
                    )
                    return NullUndo
            else:
                obj = self.objects[0][-1]
                if not isinstance(obj, aclass):
                    warn(INTERNAL, "EditSelection.GetObjectMethod: " "object is not instance of %s", aclass)
                    return NullUndo
            try:
                method = getattr(obj, methodname)
            except AttributeError:
                warn(INTERNAL, "EditSelection.GetObjectMethod: " "no method %s for class %s", methodname, aclass)
                return NullUndo

            undo = apply(method, args)
            if undo is None:
                undo = NullUndo
            return undo
        return NullUndo
Ejemplo n.º 31
0
    def CallObjectMethod(self, aclass, methodname, args):
        if len(self.objects) == 1:
            if self.editor is not None:
                obj = self.editor
                if not obj.compatible(aclass):
                    warn(
                        INTERNAL, 'EditSelection.GetObjectMethod: '
                        'editor %s is not compatible with class %s',
                        self.editor, aclass)
                    return NullUndo
            else:
                obj = self.objects[0][-1]
                if not isinstance(obj, aclass):
                    warn(
                        INTERNAL, 'EditSelection.GetObjectMethod: '
                        'object is not instance of %s', aclass)
                    return NullUndo
            try:
                method = getattr(obj, methodname)
            except AttributeError:
                warn(
                    INTERNAL, 'EditSelection.GetObjectMethod: '
                    'no method %s for class %s', methodname, aclass)
                return NullUndo

            undo = apply(method, args)
            if undo is None:
                undo = NullUndo
            return undo
        return NullUndo
def load_drawing_from_file(file, filename='', doc_class=None):
    # Note: the doc_class argument is only here for plugin interface
    # compatibility with 0.7 (especiall e.g. gziploader)
    line = file.readline()
    # XXX ugly hack for riff-based files, e.g. Corel's CMX. The length
    # might contain newline characters.
    if line[:4] == 'RIFF' and len(line) < 12:
        line = line + file.read(12 - len(line))
    #print line
    for info in filters.import_plugins:
        match = info.rx_magic.match(line)
        if match:
            loader = info(file, filename, match)
            try:
                try:
                    if do_profile:
                        import profile
                        warn(INTERNAL, 'profiling...')
                        prof = profile.Profile()
                        prof.runctx('loader.Load()', globals(), locals())
                        prof.dump_stats(
                            os.path.join(info.dir, info.module_name + '.prof'))
                        warn(INTERNAL, 'profiling... (done)')
                        doc = loader.object
                    else:
                        #t = time.clock()
                        doc = loader.Load()
                        #print 'load in', time.clock() - t, 'sec.'
                    messages = loader.Messages()
                    if messages:
                        doc.meta.load_messages = messages
                    return doc
                except Exception, value:
                    raise SketchLoadError(_("Parsing error: ") + str(value))

            finally:
                info.UnloadPlugin()
    else:
        raise SketchLoadError(_("unrecognised file type"))
Ejemplo n.º 33
0
    def build_dlg(self):
        top = self.top
        row = 0

        for row in range(len(self.info.parameters)):
            name, type, value, prange, label = self.info.parameters[row]
            try:
                #print name, type, value, prange, label
                var = parameter_types[type](self, name, value, prange, label)
                var.build_widgets(top, row)
                self.vars.append(var)
            except KeyError:
                warn(USER, 'Unknown plugin parameter type %s' % type)
                continue
        row = row + 1
        top.columnconfigure(0, weight=0)
        top.columnconfigure(1, weight=1)
        top.columnconfigure(2, weight=0)
        top.columnconfigure(3, weight=0)

        frame = self.create_std_buttons(top)
        frame.grid(row=row, columnspan=4, sticky='ew')
Ejemplo n.º 34
0
 def __getattr__(self, attr):
     try:
         access = self._object.script_access[attr]
     except KeyError:
         if not safe_special_methods.get(attr):
             warn(USER,
                  'Cant access attribute %s of %s in safe user script',
                  attr, self._object)
         raise AttributeError, attr
     if access == SCRIPT_UNDO:
         return UndoMethodWrapper(getattr(self._object, attr),
                                  self._document)
     elif access == SCRIPT_GET:
         return getattr(self._object, attr)
     elif access == SCRIPT_OBJECT:
         return ObjectMethodWrapper(getattr(self._object, attr),
                                    self._document)
     elif access == SCRIPT_OBJECTLIST:
         return ObjectListMethodWrapper(getattr(self._object, attr),
                                        self._document)
     else:
         raise AttributeError, attr
 def convert_color(self, color_spec):
     try:
         c = self.color_cache.get(color_spec)
         if c:
             return c
         if color_spec[0] == 'RGB' and len(color_spec) == 4:
             c = CreateRGBColor(color_spec[1], color_spec[2], color_spec[3])
         elif color_spec[0] == 'RGB' and len(color_spec) == 5:
             c = CreateRGBAColor(color_spec[1], color_spec[2],
                                 color_spec[3], color_spec[4])
         elif color_spec[0] == 'CMYK' and len(color_spec) == 5:
             c = CreateCMYKColor(color_spec[1], color_spec[2],
                                 color_spec[3], color_spec[4])
         elif color_spec[0] == 'CMYK' and len(color_spec) == 6:
             c = CreateCMYKAColor(color_spec[1], color_spec[2],
                                  color_spec[3], color_spec[4],
                                  color_spec[5])
         elif color_spec[0] == 'SPOT' and len(color_spec) == 10:
             c = CreateSPOTColor(color_spec[3], color_spec[4],
                                 color_spec[5], color_spec[6],
                                 color_spec[7], color_spec[8],
                                 color_spec[9], color_spec[2],
                                 color_spec[1])
         elif color_spec[0] == 'SPOT' and len(color_spec) == 11:
             c = CreateSPOTAColor(color_spec[3], color_spec[4],
                                  color_spec[5], color_spec[6],
                                  color_spec[7], color_spec[8],
                                  color_spec[9], color_spec[10],
                                  color_spec[2], color_spec[1])
         else:
             c = apply(ParseSketchColor, 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
Ejemplo n.º 36
0
	def build_dlg(self):
		top = self.top
		row = 0

		for row in range(len(self.info.parameters)):
			name, type, value, prange, label = self.info.parameters[row]
			try:
				#print name, type, value, prange, label
				var = parameter_types[type](self, name, value, prange, label)
				var.build_widgets(top, row)
				self.vars.append(var)
			except KeyError:
				warn(USER, 'Unknown plugin parameter type %s' % type)
				continue
		row = row + 1
		top.columnconfigure(0, weight=0)
		top.columnconfigure(1, weight=1)
		top.columnconfigure(2, weight=0)
		top.columnconfigure(3, weight=0)


		frame = self.create_std_buttons(top)
		frame.grid(row=row, columnspan=4, sticky='ew')
Ejemplo n.º 37
0
	def __init__(self, paths = None, properties = None, duplicate = None):
		if duplicate is not None:
			if paths is None:
				paths = []
				for path in duplicate.paths:
					paths.append(path.Duplicate())
				self.paths = tuple(paths)
			else:
				# This special case uses the properties kwarg now, I
				# hope.
				warn(INTERNAL, 'Bezier object created with paths and duplicte')
				print_stack()
				if type(paths) != type(()):
					paths = (paths,)
				self.paths = paths
		elif paths is not None:
			if type(paths) != type(()):
				paths = (paths,)
			self.paths = paths
		else:
			self.paths = (CreatePath(),)

		Primitive.__init__(self, properties = properties, duplicate=duplicate)
def read_font_dirs():
    #print 'read_font_dirs'
    if __debug__:
        import time
        start = time.clock()

    rx_sfd = re.compile(r'^.*\.sfd$')
    for directory in config.font_path:
        #print directory
        try:
            filenames = os.listdir(directory)
        except os.error, exc:
            warn(USER,
                 _("Cannot list directory %s:%s\n"
                   "ignoring it in font_path"), directory, str(exc))
            continue
        dirfiles = filter(rx_sfd.match, filenames)
        for filename in dirfiles:
            filename = os.path.join(directory, filename)
            #print filename
            try:
                file = open(filename, 'r')
                line_nr = 0
                for line in file.readlines():
                    line_nr = line_nr + 1
                    line = strip(line)
                    if not line or line[0] == '#':
                        continue
                    info = map(intern, split(line, ','))
                    if len(info) == 6:
                        psname = info[0]
                        fontlist.append(tuple(info[:-1]))
                        _add_ps_filename(psname, info[-1])
                        fontmap[psname] = tuple(info[1:-1])
                    elif len(info) == 2:
                        psname, basename = info
                        _add_ps_filename(psname, basename)
                    else:
                        warn(INTERNAL,
                             '%s:%d: line must have exactly 6 fields',
                             filename, line_nr)
                file.close()
            except IOError, value:
                warn(USER,
                     _("Cannot load sfd file %(filename)s:%(message)s;"
                       "ignoring it"),
                     filename=filename,
                     message=value.strerror)
Ejemplo n.º 39
0
class Bounded:

	_lazy_attrs = {'coord_rect' : 'update_rects',
					'bounding_rect' : 'update_rects'}

	def __init__(self):
		pass

	def del_lazy_attrs(self):
		for key in self._lazy_attrs.keys():
			try:
				delattr(self, key)
			except:
				pass

	def update_rects(self):
		# compute the various bounding rects and other attributes that
		# use `lazy evaluation'. This method MUST be implemented by
		# derived classes. It MUST set self.bounding_rect and
		# self.coord_rect and other attributes where appropriate.
		pass

	def __getattr__(self, attr):
		# if a lazy attribute is accessed, compute it.
		method = self._lazy_attrs.get(attr)
		if method:
			getattr(self, method)()
			# now it should work... use self.__dict__ directly to avoid
			# recursion if the method is buggy
			try:
				return self.__dict__[attr]
			except KeyError, msg:
				warn(INTERNAL, '%s did not compute %s for %s.', method, attr, self)
		if attr[:2] == attr[-2:] == '__':
			#if attr in ('__nonzero__', '__len__'):
			#	 print_stack()
			pass
		else:
			warn(INTERNAL, "%s instance doesn't have an attribute %s", self.__class__, attr)
		raise AttributeError, attr
Ejemplo n.º 40
0
def read_font_dirs():
	#print 'read_font_dirs'
	if __debug__:
		import time
		start = time.clock()

	rx_sfd = re.compile(r'^.*\.sfd$')
	for directory in config.font_path:
		#print directory
		try:
			filenames = os.listdir(directory)
		except os.error, exc:
			warn(USER, _("Cannot list directory %s:%s\n"
							"ignoring it in font_path"),
					directory, str(exc))
			continue
		dirfiles = filter(rx_sfd.match, filenames)
		for filename in dirfiles:
			filename = os.path.join(directory, filename)
			#print filename
			try:
				file = open(filename, 'r')
				line_nr = 0
				for line in file.readlines():
					line_nr = line_nr + 1
					line = strip(line)
					if not line or line[0] == '#':
						continue
					info = map(intern, split(line, ','))
					if len(info) == 6:
						psname = info[0]
						fontlist.append(tuple(info[:-1]))
						_add_ps_filename(psname, info[-1])
						fontmap[psname] = tuple(info[1:-1])
					elif len(info) == 2:
						psname, basename = info
						_add_ps_filename(psname, basename)
					else:
						warn(INTERNAL,'%s:%d: line must have exactly 6 fields',
								filename, line_nr)
				file.close()
			except IOError, value:
				warn(USER, _("Cannot load sfd file %(filename)s:%(message)s;"
								"ignoring it"),
						filename = filename, message = value.strerror)
Ejemplo n.º 41
0
 def GetObjectMethod(self, aclass, method):
     if len(self.objects) == 1:
         if self.editor is not None:
             obj = self.editor
             if not obj.compatible(aclass):
                 warn(INTERNAL, "EditSelection.GetObjectMethod: " "editor is not compatible with class %s", aclass)
                 return None
         else:
             obj = self.objects[0][-1]
             if not isinstance(obj, aclass):
                 warn(INTERNAL, "EditSelection.GetObjectMethod: " "object is not instance of %s", aclass)
                 return None
         try:
             return getattr(obj, method)
         except AttributeError:
             warn(INTERNAL, "EditSelection.GetObjectMethod: " "no method %s for class %s", method, aclass)
             pass
     return None
    def GetObjectMethod(self, aclass, method):
	if len(self.objects) == 1:
	    if self.editor is not None:
		obj = self.editor
		if not obj.compatible(aclass):
		    warn(INTERNAL, 'EditSelection.GetObjectMethod: '
			 'editor is not compatible with class %s', aclass)
		    return None
	    else:
		obj = self.objects[0][-1]
		if not isinstance(obj, aclass):
		    warn(INTERNAL, 'EditSelection.GetObjectMethod: '
			 'object is not instance of %s', aclass)
		    return None
	    try:
		return getattr(obj, method)
	    except AttributeError:
		warn(INTERNAL, 'EditSelection.GetObjectMethod: '
		     'no method %s for class %s', method, aclass)
		pass
	return None
Ejemplo n.º 43
0
def parse_header(file, info):
    # Parse the header section of FILE and store the information found
    # in the INFO object which is assumed to be an instance of EpsInfo.
    #
    # This works for the %%Trailer section as well so that parsing the
    # beginning (until %%EndComments) and end (from %%Trailer) if
    # necessary with the same INFO object should get all information
    # available.
    line = file.readline()
    last_key = ''
    while line:
        match = rx_dsccomment.match(line)
        if match:
            key = match.group(1)
            value = strip(line[match.end(0):])
            if key == 'EndComments' or key == 'EOF':
                break

            if key == '+':
                key = last_key
            else:
                last_key = ''

            if key == 'BoundingBox':
                if value != ATEND:
                    # the bounding box should be given in UINTs
                    # but may also (incorrectly) be float.
                    info.BoundingBox = tuple(map(atof, split(value)))
                else:
                    info.atend = 1
            elif key == 'DocumentNeededResources':
                if value != ATEND:
                    if value:
                        [type, value] = split(value, None, 1)
                        if type == 'font':
                            info.NeedResources(type, split(value))
                        else:
                            # XXX: might occasionally be interesting for the
                            # user
                            warn(INTERNAL, 'needed resource %s %s ignored',
                                 type, value)
                else:
                    info.atend = 1
            elif key == 'DocumentNeededFonts':
                if value != ATEND:
                    info.NeedResources('font', split(value))
                else:
                    info.atend = 1
            elif key == 'DocumentSuppliedResources':
                if value != ATEND:
                    if value:
                        [type, value] = split(value, None, 1)
                        if type == 'font':
                            info.NeedResources(type, split(value))
                        else:
                            # XXX: might occasionally be interesting for the
                            # user
                            warn(INTERNAL, 'supplied resource %s %s ignored',
                                 type, value)
                else:
                    info.atend = 1
            else:
                setattr(info, key, value)
            #
            last_key = key
        else:
            # the header comments end at a line not beginning with %X,
            # where X is a printable character not in SPACE, TAB, NL
            # XXX: It is probably wrong to do this in the %%Trailer
            if line[0] != '%':
                break
            if len(line) == 1 or line[1] not in endcommentchars:
                break
        line = file.readline()
Ejemplo n.º 44
0
					function, rest = tokens
				else:
					function = tokens[0]
					rest = ''
				if type(function) == type(0):
					function = funclist.get(function)
					if function:
						function(rest)
				line = self.readline()
				
		except SketchLoadError, value:
			warn_tb(INTERNAL)
			raise SketchLoadError('%d:%s' % (self.lineno, str(value))), None,\
					sys.exc_traceback
		except:
			if load._dont_handle_exceptions:
				warn(INTERNAL, 'XFigLoader: error reading line %d:%s',
						self.lineno, `line`)
				raise
			raise SketchLoadError(_("error in line %d:\n%s")
									% (self.lineno, `line`)), None,\
									sys.exc_traceback
		self.end_all()
		self.object.load_Completed()
		return self.object





Ejemplo n.º 45
0
def read_afm_file(filename):
	afm = streamfilter.LineDecode(open(filename, 'r'))

	attribs = {'ItalicAngle': 0.0}
	charmetrics = None
	font_encoding = [encoding.notdef] * 256

	while 1:
		line = afm.readline()
		if not line:
			break
		try:
			[key, value] = split(line, None, 1)
		except ValueError:
			# this normally means that a line contained only a keyword
			# but no value or that the line was empty
			continue
		try:
			action = converters[key]
		except KeyError:
			continue
		if action:
			attribs[key] = action(value)
		elif key == 'StartCharMetrics':
			charmetrics, font_encoding = read_char_metrics(afm)
			break
		else:
			# EndFontMetrics
			break

	if not charmetrics:
		raise ValueError, \
				'AFM files without individual char metrics not yet supported.'

	if attribs.get('EncodingScheme', StandardEncoding) == StandardEncoding:
		enc = encoding.iso_latin_1
	else:
		enc = font_encoding

	try:
		rescharmetrics = map(operator.getitem, [charmetrics] * len(enc), enc)
	except KeyError:
		# Some iso-latin-1 glyphs are not defined in the font. Try the
		# slower way and report missing glyphs.
		length = len(enc)
		rescharmetrics = [(0, 0,0,0,0)] * length
		for idx in range(length):
			name = enc[idx]
			try:
				rescharmetrics[idx] = charmetrics[name]
			except KeyError:
				# missing character...
				warn(INTERNAL, '%s: missing character %s', filename, name)

	# some fonts don't define ascender and descender (psyr.afm for
	# instance). use the values from the font bounding box instead. This
	# is not really a good idea, but how do we solve this?
	#
	# If psyr.afm is the only afm-file where these values are missing
	# (?) we could use the values from the file s050000l.afm shipped
	# with ghostscript (or replace psyr.afm with that file).
	#
	# This is a more general problem since many of the values Sketch
	# reads from afm files are only optional (including ascender and
	# descender).
	if not attribs.has_key('Ascender'):
		attribs['Ascender'] = attribs['FontBBox'][3]
	if not attribs.has_key('Descender'):
		attribs['Descender'] = attribs['FontBBox'][1]

	return (CreateFontMetric(attribs['Ascender'], attribs['Descender'],
								attribs['FontBBox'], attribs['ItalicAngle'],
								rescharmetrics),
			enc)
Ejemplo n.º 46
0
				# Lib.
				lib_pkg = create_packages(package + '.Lib')
				lib_pkg.__path__.append(filename)
			elif recurse:
				# an ordinary directory and we should recurse into it to
				# find more modules, so do that.
				_search_dir(filename, recurse - 1, package + '.' + file)
		elif filename[-3:] == '.py':
			try:
				module_name = os.path.splitext(os.path.basename(filename))[0]
				vars = {'_':_}	# hack
				cfg = extract_cfg(filename)
				exec cfg in config_types, vars
				infoclass = vars.get('type')
				if infoclass is None:
					warn(USER, _("No plugin-type information in %(filename)s"),
							filename = filename)
				else:
					del vars['type']
					del vars['_']
					info = apply(infoclass, (module_name, dir), vars)
					info.package = package
			except:
				warn_tb(INTERNAL, 'In config file %s', filename)
				warn(USER, _("can't read configuration information from "
								"%(filename)s"),
						filename =	 filename)
				


def find_export_plugin(name):
	return export_formats.get(name)
Ejemplo n.º 47
0
	def __dlg_closed(self, dialog, name):
		try:
			del self.dialogs[name]
		except:
			# This might happen if the dialog is buggy...
			warn(INTERNAL, 'dialog %s alread removed from dialog list', name)
Ejemplo n.º 48
0
def parse_header(file, info):
	# Parse the header section of FILE and store the information found
	# in the INFO object which is assumed to be an instance of EpsInfo.
	#
	# This works for the %%Trailer section as well so that parsing the
	# beginning (until %%EndComments) and end (from %%Trailer) if
	# necessary with the same INFO object should get all information
	# available.
	line = file.readline()
	last_key = ''
	while line:
		match = rx_dsccomment.match(line)
		if match:
			key = match.group(1)
			value = strip(line[match.end(0):])
			if key == 'EndComments' or key == 'EOF':
				break

			if key == '+':
				key = last_key
			else:
				last_key = ''

			if key == 'BoundingBox':
				if value != ATEND:
					# the bounding box should be given in UINTs
					# but may also (incorrectly) be float.
					info.BoundingBox = tuple(map(atof, split(value)))
				else:
					info.atend = 1
			elif key == 'DocumentNeededResources':
				if value != ATEND:
					if value:
						[type, value] = split(value, None, 1)
						if type == 'font':
							info.NeedResources(type, split(value))
						else:
							# XXX: might occasionally be interesting for the
							# user
							warn(INTERNAL, 'needed resource %s %s ignored',
									type, value)
				else:
					info.atend = 1
			elif key == 'DocumentNeededFonts':
				if value != ATEND:
					info.NeedResources('font', split(value))
				else:
					info.atend = 1
			elif key == 'DocumentSuppliedResources':
				if value != ATEND:
					if value:
						[type, value] = split(value, None, 1)
						if type == 'font':
							info.NeedResources(type, split(value))
						else:
							# XXX: might occasionally be interesting for the
							# user
							warn(INTERNAL, 'supplied resource %s %s ignored',
									type, value)
				else:
					info.atend = 1
			else:
				setattr(info, key, value)
			#
			last_key = key
		else:
			# the header comments end at a line not beginning with %X,
			# where X is a printable character not in SPACE, TAB, NL
			# XXX: It is probably wrong to do this in the %%Trailer
			if line[0] != '%':
				break
			if len(line) == 1 or line[1] not in endcommentchars:
				break
		line = file.readline()
Ejemplo n.º 49
0
                lib_pkg = create_packages(package + '.Lib')
                lib_pkg.__path__.append(filename)
            elif recurse:
                # an ordinary directory and we should recurse into it to
                # find more modules, so do that.
                _search_dir(filename, recurse - 1, package + '.' + file)
        elif filename[-3:] == '.py' and not filename == '__init__.py':
            try:
                module_name = os.path.splitext(os.path.basename(filename))[0]
                vars = {'_': _}  # hack
                cfg = extract_cfg(filename)
                exec cfg in config_types, vars
                infoclass = vars.get('type')
                if infoclass is None:
                    warn(USER,
                         _("No plugin-type information in %(filename)s"),
                         filename=filename)
                else:
                    del vars['type']
                    del vars['_']
                    info = apply(infoclass, (module_name, dir), vars)
                    info.package = package
            except:
                warn_tb(INTERNAL, 'In config file %s', filename)
                warn(USER,
                     _("can't read configuration information from "
                       "%(filename)s"),
                     filename=filename)


def find_export_plugin(name):