Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Inkscape 1.0 and Python3 #27

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
122 changes: 67 additions & 55 deletions extension/latextext.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
from lxml import etree


MAC = "Mac OS"
MAC = "Darwin"
WINDOWS = "Windows"
PLATFORM = platform.system()
PY3 = int(platform.python_version()[0]) >= 3

STANDALONE = False
LOG_LEVEL = 3
Expand Down Expand Up @@ -70,7 +71,7 @@ def log_message(msg_level, *msg):
print(*msg)
else:
for m in msg:
inkex.debug(m)
inkex.utils.debug(m)


def set_log_level(l):
Expand All @@ -95,9 +96,7 @@ class SvgTransformer:

# matrix multiplication helper function
def _matmult(self, a, b):
zip_b = zip(*b)
# uncomment next line if python 3 :
# zip_b = list(zip_b)
zip_b = list(zip(*b)) if PY3 else zip(*b)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's a redundant use of list(...) but this works just fine on Python 2, no need to make it conditional.

return [[sum(ele_a * ele_b for ele_a, ele_b in zip(row_a, col_b))
for col_b in zip_b] for row_a in a]

Expand Down Expand Up @@ -227,8 +226,8 @@ def __init__(self, infile, options):
self.options = options
self.svg_input = infile

self.defaults = dict2obj({"scale": 1.0, "depth": 0.0, "fontsize": 10,
"preamble": "","packages": "amsmath,amssymb","math": False,
self.defaults = dict2obj({"scale": 1.0, "depth": 0.0, "fontsize": 10,
"preamble": "","packages": "amsmath,amssymb","math": False,
"newline": False})

# load from file or use existing document root
Expand Down Expand Up @@ -587,8 +586,18 @@ def render(self, latex_code, preamble_file=None, package_list="", fontsize=10, s
# Convert PDF to SVG
if PLATFORM == WINDOWS:
PDF2SVG_PATH = os.path.join(os.path.realpath(EXT_PATH), 'pdf2svg')
if PLATFORM == MAC:
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if PLATFORM == MAC:
elif PLATFORM == MAC:

unless you hate windows users (which is unfair, they already go through enough as it is :P)

if os.path.exists('/opt/local/bin/pdf2svg'):
PDF2SVG_PATH = '/opt/local/bin'
elif os.path.exists('/usr/local/bin/pdf2svg'):
PDF2SVG_PATH = '/usr/local/bin'
elif shutil.which("pdf2svg"):
PDF2SVG_PATH = os.path.dirname(shutil.which("pdf2svg"))
else:
log_error('PDF2SVG_PATH not found.')
else:
PDF2SVG_PATH = ''

self._exec_command([os.path.join(PDF2SVG_PATH, 'pdf2svg'), os.path.join(tmp_path, 'tmp.pdf'), os.path.join(tmp_path, 'tmp.svg'), '1'])

tree = etree.parse(os.path.join(tmp_path, 'tmp.svg'))
Expand All @@ -607,45 +616,39 @@ def render(self, latex_code, preamble_file=None, package_list="", fontsize=10, s
# Init for standalone or Inkscape extension run mode

# commandline options shared by standalone application and inkscape extension
def add_options(parser):
parser.add_option("-o", "--outfile", dest="outfile",
help="write to output file or directory", metavar="FILE")
parser.add_option("-p", "--preamble", dest="preamble",
help="latex preamble file", metavar="FILE")
parser.add_option("-k", "--packages", dest="packages",
help="comma separated list of additional latex packages to be loaded", metavar="LIST")
parser.add_option("-f", "--fontsize", dest="fontsize", type="int",
help="latex base font size")
parser.add_option("-s", "--scale", dest="scale", type="float",
help="apply additional scaling")
parser.add_option("-d", "--depth", dest="depth", type="int",
help="maximum search depth for grouped text elements")
parser.add_option("-n", "--newline", dest="newline",
action="store_true",
help="insert \\\\ at every line break")
parser.add_option("-m", "--math", dest="math",
action="store_true",
help="encapsulate all text in math mode")
parser.add_option("-c", "--clean",
action="store_true", dest="clean",
help="remove all renderings")
def add_arguments(parser):
parser.add_argument("-o", "--outfile", dest="outfile",
help="write to output file or directory", metavar="FILE")
parser.add_argument("-p", "--preamble", dest="preamble",
help="latex preamble file", metavar="FILE")
parser.add_argument("-k", "--packages", dest="packages",
help="comma separated list of additional latex packages to be loaded",
metavar="LIST")
parser.add_argument("-f", "--fontsize", dest="fontsize", type=int,
help="latex base font size")
parser.add_argument("-s", "--scale", dest="scale", type=float,
help="apply additional scaling")
parser.add_argument("-d", "--depth", dest="depth", type=int,
help="maximum search depth for grouped text elements")
parser.add_argument("-c", "--clean",
action="store_true", dest="clean",
help="remove all renderings")


if STANDALONE is False:
# Create an Inkscape extension
class RenderLatexEffect(inkex.Effect):
def __init__(self):
inkex.Effect.__init__(self)
add_options(self.OptionParser)
self.OptionParser.set_conflict_handler("resolve")
self.OptionParser.add_option("-l", "--log", type='inkbool',
action="store", dest="debug", default=False,
add_arguments(self.arg_parser)
self.arg_parser.add_argument("-l", "--log", type=inkex.utils.Boolean,
dest="debug", default=False,
help="show log messages in inkscape")
self.OptionParser.add_option("-n", "--newline", dest="newline",
action="store", type='inkbool',
self.arg_parser.add_argument("-n", "--newline", dest="newline",
type=inkex.utils.Boolean,
help="insert \newline at every line break")
self.OptionParser.add_option("-m", "--math", type='inkbool',
action="store", dest="math",
self.arg_parser.add_argument("-m", "--math", type=inkex.utils.Boolean,
dest="math",
help="encapsulate all text in math mode")

def effect(self):
Expand All @@ -657,39 +660,48 @@ def effect(self):
# Create a standalone commandline application
def main_standalone():
# parse commandline arguments
from optparse import OptionParser
parser = OptionParser(usage="usage: %prog [options] SVGfile(s)")
add_options(parser)
parser.add_option("-v", "--verbose", default=False,
action="store_true", dest="verbose")
(options, args) = parser.parse_args()

if options.verbose is True:
import argparse
parser = argparse.ArgumentParser(conflict_handler='resolve')
add_arguments(parser)
parser.add_argument("-n", "--newline", dest="newline",
action="store_true",
help="insert \\\\ at every line break")
parser.add_argument("-m", "--math", dest="math",
action="store_true",
help="encapsulate all text in math mode")
parser.add_argument("-v", "--verbose", default=False,
action="store_true", dest="verbose")
parser.add_argument("svg", type=str, nargs='+',
metavar="FILE",
help="SVGfile(s)")
args = parser.parse_args()

if args.verbose is True:
set_log_level(log_level_debug)

# expand wildcards
args = [glob.glob(arg) if '*' in arg else arg for arg in args]
files = [glob.glob(arg) if '*' in arg else arg for arg in args.svg]

if len(args) < 1:
if len(files) < 1:
log_error('No input file specified! Call with -h argument for usage instructions.')
sys.exit(1)
elif len(args) > 2 and options.outfile and not os.path.isdir(options.outfile):
elif len(files) > 2 and args.outfile and not os.path.isdir(args.outfile):
log_error('If more than one input file is specified -o/--outfile has to point to a directory.')
sys.exit(1)

# main loop, run the SVG processor for each input file
for infile in args:
if options.outfile:
if os.path.isdir(options.outfile):
outfile = os.path.join(options.outfile, os.path.basename(infile))
for infile in files:
if args.outfile:
if os.path.isdir(args.outfile):
outfile = os.path.join(args.outfile, os.path.basename(infile))
else:
outfile = options.outfile
outfile = args.outfile
else:
outfile = infile

log_info("Rendering " + infile + " -> " + outfile)

svgprocessor = SvgProcessor(infile, options)
svgprocessor = SvgProcessor(infile, args)

try:
result = svgprocessor.run()
Expand All @@ -708,6 +720,6 @@ def main_standalone():
if STANDALONE is False:
# run the extension
effect = RenderLatexEffect()
effect.affect()
effect.run()
else:
main_standalone()