Exemplo n.º 1
0
def main(args):
    from frags.cmdopts import parse_args

    (setup.options, args) = parse_args(args)

    # fixed options
    setup.options.use_bbox = True
    setup.options.prettyXML = False

    input_txt = setup.options.input_txt
    input_svg = setup.options.input_svg
    output_svg = setup.options.output_svg

    if not input_txt:
        log.error("Rules file not provided, use switch -r or --rules")
        sys.exit(1)
    elif not os.path.exists(input_txt):
        log.error("Rules file '%s' don't exist", input_txt)
        sys.exit(1)

    if not input_svg:
        log.error("Input SVG file not provided, use switch -i or --input")
        sys.exit(1)
    elif not os.path.exists(input_svg):
        log.error("Input SVG file '%s' don't exist", input_svg)
        sys.exit(1)

    if not output_svg:
        log.error("Output SVG file not provided, use switch -i or --output")
        sys.exit(1)
    elif os.path.exists(output_svg) and not setup.options.frags_overwrite_file:
        log.error(
            "File %s already exists, and cannot be overwritten.  Use switch -f or --force-overwrite to change this behaviour.",
            output_svg)
        sys.exit(1)

    # 1. Load SVG file
    XML = xml.dom.minidom.parse(input_svg)

    # 1.1. Create 'defs' tag (if doesn't exists), and add xlink namespace
    if not XML.getElementsByTagName('defs'):
        XML.documentElement.insertBefore(XML.createElement('defs'),
                                         XML.documentElement.firstChild)

    if not XML.documentElement.getAttribute('xmlns:xlink'):
        XML.documentElement.setAttribute('xmlns:xlink',
                                         "http://www.w3.org/1999/xlink")

    if True:
        # XXX: hack; for unknown reason expat do not read id attribute
        # and getElementById always fails
        ID = {}
        frags.collect_Id(XML, ID)

        def my_getElementById(id):
            try:
                return ID[id]
            except KeyError:
                return None

        XML.getElementById = my_getElementById

    # 1.2. find all text objects
    text_objects = {}  # text -> node
    for node in XML.getElementsByTagName('text'):
        try:
            text = frags.get_text(node, setup.options.frags_strip)
            # add to list
            if text in text_objects:
                text_objects[text].append(node)
            else:
                text_objects[text] = [node]
        except ValueError:
            pass
    #for

    # 2. Load & parse replace pairs
    input = open(input_txt, 'r').read()

    from frags.parse_subst import parse
    repl_defs = frags.Dict()  # valid defs
    text_nodes = set()  # text nodes to remove/hide
    try:
        for item in parse(input):
            ((kind, value), tex, options) = item

            if tex is None:  # i.e. "this"
                if kind == 'string':
                    if setup.options.frags_strip:
                        tex = value.strip()
                    else:
                        tex = value
                elif kind == 'id':
                    node = XML.getElementById(value[1:])
                    if frags.istextnode(node):
                        tex = frags.get_text(node)

            if tex is None:
                log.error(
                    "Keyword 'this' is not allowed for rect/points object")
                continue

            if kind == 'string':
                if setup.options.frags_strip:
                    value = value.strip()

                try:
                    for node in text_objects[value]:
                        text_nodes.add(node)
                        repl_defs[tex] = ((kind, node), tex, options)
                except KeyError:
                    log.warning(
                        "String '%s' doesn't found in SVG, skipping repl",
                        value)

            elif kind == 'id':
                object = XML.getElementById(value[1:])
                if object:
                    # "forget" id, save object
                    if object.nodeName in ['rect', 'ellipse', 'circle']:
                        repl_defs[tex] = ((kind, object), tex, options)
                    elif object.nodeName == 'text':
                        repl_defs[tex] = (('string', object), tex, options)
                    else:
                        log.warning(
                            "Object with id=%s is not text, rect, ellipse nor circle - skipping repl",
                            value)
                else:
                    log.warning(
                        "Object with id=%s doesn't found in SVG, skipping repl",
                        value)

            else:  # point, rect -- no additional tests needed
                repl_defs[tex] = ((kind, value), tex, options)

    except frags.parse_subst.SyntaxError, e:
        log.error("Syntax error: %s", str(e))
        sys.exit(1)
Exemplo n.º 2
0
def main(args):
	from frags.cmdopts import parse_args

	(setup.options, args) = parse_args(args)
	
	# fixed options
	setup.options.use_bbox  = True
	setup.options.prettyXML = False

	input_txt = setup.options.input_txt
	input_svg = setup.options.input_svg
	output_svg = setup.options.output_svg

	if not input_txt:
		log.error("Rules file not provided, use switch -r or --rules")
		sys.exit(1)
	elif not os.path.exists(input_txt):
		log.error("Rules file '%s' don't exist", input_txt)
		sys.exit(1)
	
	if not input_svg:
		log.error("Input SVG file not provided, use switch -i or --input")
		sys.exit(1)
	elif not os.path.exists(input_svg):
		log.error("Input SVG file '%s' don't exist", input_svg)
		sys.exit(1)
	
	if not output_svg:
		log.error("Output SVG file not provided, use switch -i or --output")
		sys.exit(1)
	elif os.path.exists(output_svg) and not setup.options.frags_overwrite_file:
		log.error("File %s already exists, and cannot be overwritten.  Use switch -f or --force-overwrite to change this behaviour.", output_svg)
		sys.exit(1)


	# 1. Load SVG file
	XML = xml.dom.minidom.parse(input_svg)

	# 1.1. Create 'defs' tag (if doesn't exists), and add xlink namespace
	if not XML.getElementsByTagName('defs'):
		XML.documentElement.insertBefore(
			XML.createElement('defs'),
			XML.documentElement.firstChild
		)

	if not XML.documentElement.getAttribute('xmlns:xlink'):
		XML.documentElement.setAttribute('xmlns:xlink', "http://www.w3.org/1999/xlink")

	if True:
		# XXX: hack; for unknown reason expat do not read id attribute
		# and getElementById always fails
		ID = {}
		frags.collect_Id(XML, ID)

		def my_getElementById(id):
			try:
				return ID[id]
			except KeyError:
				return None
		XML.getElementById = my_getElementById


	# 1.2. find all text objects
	text_objects = {} # text -> node
	for node in XML.getElementsByTagName('text'):
		try:
			text = frags.get_text(node, setup.options.frags_strip)
			# add to list
			if text in text_objects:
				text_objects[text].append(node)
			else:
				text_objects[text] = [node]
		except ValueError:
			pass
	#for

	# 2. Load & parse replace pairs
	input = open(input_txt, 'r').read()

	from frags.parse_subst import parse
	repl_defs  = frags.Dict() # valid defs
	text_nodes = set()        # text nodes to remove/hide
	try:
		for item in parse(input):
			((kind, value), tex, options) = item

			if tex is None: # i.e. "this"
				if kind == 'string':
					if setup.options.frags_strip:
						tex = value.strip()
					else:
						tex = value
				elif kind == 'id':
					node = XML.getElementById(value[1:])
					if frags.istextnode(node):
						tex = frags.get_text(node)

			if tex is None:
				log.error("Keyword 'this' is not allowed for rect/points object")
				continue

			if kind == 'string':
				if setup.options.frags_strip:
					value = value.strip()

				try:
					for node in text_objects[value]:
						text_nodes.add(node)
						repl_defs[tex] = ((kind, node), tex, options)
				except KeyError:
					log.warning("String '%s' doesn't found in SVG, skipping repl", value)

			elif kind == 'id':
				object = XML.getElementById(value[1:])
				if object:
					# "forget" id, save object
					if object.nodeName in ['rect', 'ellipse', 'circle']:
						repl_defs[tex] = ((kind, object), tex, options)
					elif object.nodeName == 'text':
						repl_defs[tex] = (('string', object), tex, options)
					else:
						log.warning("Object with id=%s is not text, rect, ellipse nor circle - skipping repl", value)
				else:
					log.warning("Object with id=%s doesn't found in SVG, skipping repl", value)

			else: # point, rect -- no additional tests needed
				repl_defs[tex] = ((kind, value), tex, options)

	except frags.parse_subst.SyntaxError, e:
		log.error("Syntax error: %s", str(e))
		sys.exit(1)
Exemplo n.º 3
0
            # there are more then one referenco to this TeX object, so
            # we have to **define** it, and then reference to, with <use>
            eq_id = 'svgfrags-%x' % eq_id_n
            eq_id_n += 1
            SVG.lastpage.setAttribute('id', eq_id)
            XML.getElementsByTagName('defs')[0].appendChild(SVG.lastpage)
        else:
            # just one reference, use node crated by SVGDocument
            equation = SVG.lastpage
            eq_id = None

        # process
        for ((kind, value), tex, options) in items:
            px, py = options.position
            if px == 'inherit':
                if frags.istextnode(value):
                    px = frags.get_anchor(value)
                else:
                    px = 0.0

            # bounding box of equation
            (xmin, ymin, xmax, ymax) = SVG.lastbbox

            # enlarge with margin values
            xmin -= options.margin[0]
            xmax += options.margin[1]
            ymin -= options.margin[2]
            ymax += options.margin[3]

            # and calculate bbox's dimensions
            dx = xmax - xmin
Exemplo n.º 4
0
			# we have to **define** it, and then reference to, with <use>
			eq_id    = 'svgfrags-%x' % eq_id_n
			eq_id_n += 1
			SVG.lastpage.setAttribute('id', eq_id)
			XML.getElementsByTagName('defs')[0].appendChild(SVG.lastpage)
		else:
			# just one reference, use node crated by SVGDocument
			equation = SVG.lastpage
			eq_id = None

		
		# process
		for ((kind, value), tex, options) in items:
			px, py = options.position
			if px == 'inherit':
				if frags.istextnode(value):
					px = frags.get_anchor(value)
				else:
					px = 0.0
			
			# bounding box of equation
			(xmin, ymin, xmax, ymax) = SVG.lastbbox

			# enlarge with margin values
			xmin -= options.margin[0]
			xmax += options.margin[1]
			ymin -= options.margin[2]
			ymax += options.margin[3]

			# and calculate bbox's dimensions
			dx = xmax - xmin