Skip to content

Commit

Permalink
WIP th2 file stack
Browse files Browse the repository at this point in the history
  • Loading branch information
speleo3 committed May 12, 2024
1 parent d722992 commit 38fd4bb
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 20 deletions.
66 changes: 49 additions & 17 deletions extensions/th2_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,14 +147,24 @@ def getlayer(role, type):
node.set('height', '%d' % (x))
node.set('width', '%d' % (2 * spacing))

# currentlayer = root
currentlayer = root.xpath('svg:g[@id="layer-scrap0"]', namespaces=inkex.NSS)[0]
currentlayer = root
# currentlayer = root.xpath('svg:g[@id="layer-scrap0"]', namespaces=inkex.NSS)[0]

layer_stack = [currentlayer]
file_stack: list["FileRecord"] = []

class FileRecord:
def __init__(self, patharg: str):
searchpath = [file_stack[-1].dirname] if file_stack else []
self.filename = find_in_pwd(patharg, searchpath)
self.dirname = os.path.dirname(self.filename)
self.f_handle = open(self.filename, 'rb')
self.f_enum = enumerate(self.f_handle)
def __del__(self):
self.f_handle.close()

# open th2 file
filename = find_in_pwd(th2pref.argv[0])
dirname = os.path.dirname(filename)
f_handle = open(filename, 'rb')
f_enum = enumerate(f_handle)
file_stack.append(FileRecord(th2pref.argv[0]))

doc_x = 0
doc_y = 0
Expand Down Expand Up @@ -214,9 +224,13 @@ def reverseD(d):
def f_readline():
global line_nr
try:
line_nr, line = next(f_enum)
line_nr, line = next(file_stack[-1].f_enum)
except StopIteration:
return ''
file_stack.pop()
layer_stack.pop()
global currentlayer
currentlayer = layer_stack[-1] if layer_stack else root
return f_readline() if file_stack else ''
line = line.rstrip(b'\r\n')
line = line.decode(encoding)
if line.endswith('\\'):
Expand Down Expand Up @@ -284,7 +298,7 @@ def parse_XTHERION(a):
y = str(-1 * float(m.group(2)))
if href != '':
try:
href = find_in_pwd(href, [dirname])
href = find_in_pwd(href, [file_stack[-1].dirname])
except IOError:
errormsg('image not found: ' + repr(href[:128]))
if href.endswith('.xvi'):
Expand Down Expand Up @@ -321,8 +335,8 @@ def parse_XTHERION(a):
doc_y = floatscale(a[5])
doc_width = floatscale(a[4]) - doc_x
doc_height = doc_y - floatscale(a[3])
scrap_transform = 'translate(%f,%f)' % (-doc_x, doc_y)
scrap_transform_inv = 'translate(%f,%f)' % (doc_x, -doc_y)
# scrap_transform = 'translate(%f,%f)' % (-doc_x, doc_y)
# scrap_transform_inv = 'translate(%f,%f)' % (doc_x, -doc_y)


def parse_scrap(a):
Expand All @@ -346,9 +360,10 @@ def parse_scrap(a):
'labe': etree.SubElement(e, 'g', {inkscape_groupmode: 'layer', inkscape_label: u'Labels'}),
}

root.append(e)
global currentlayer
currentlayer.append(e)
currentlayer = e
layer_stack.append(e)

while True:
line = f_readline()
Expand All @@ -360,7 +375,8 @@ def parse_scrap(a):
break
parse(a)

currentlayer = root
layer_stack.pop()
currentlayer = layer_stack[-1]

def parse_area(a_in):
lines = []
Expand Down Expand Up @@ -617,6 +633,22 @@ def parse_point(a):
set_props(e, 'point', a[3], options)
getlayer('point', type).insert(0, e)


def parse_input(a):
assert a[0] == "input"
assert len(a) == 2
file_stack.append(FileRecord(a[1]))

e = etree.Element('g')
e.set(inkscape_groupmode, "layer")
e.set(inkscape_label, ' '.join(a))

global currentlayer
currentlayer.append(e)
currentlayer = e
layer_stack.append(e)


parsedict = {
'##XTHERION##': parse_XTHERION,
'##INKSCAPE##': parse_INKSCAPE,
Expand All @@ -628,7 +660,7 @@ def parse_point(a):
'map': parse_BLOCK2COMMENT,
'centerline': parse_BLOCK2COMMENT,
'centreline': parse_BLOCK2COMMENT,
'input': parse_LINE2COMMENT,
'input': parse_input,
}

while True:
Expand All @@ -643,18 +675,18 @@ def parse_point(a):

parse(a)

f_handle.close()
assert not file_stack

if doc_width and doc_height:
root.set('width', str(doc_width))
root.set('height', str(doc_height))

# FIXME: Metric scaling breaks round tripping th2 -> svg -> th2, the final th2
# will be scaled wrong and not fit XVI background images anymore.
if False:
if 1:
root.set('width', f"{doc_width * cm_per_dots}cm")
root.set('height', f"{doc_height * cm_per_dots}cm")
root.set('viewBox', f"0 0 {doc_width} {doc_height}")
root.set('viewBox', f"{doc_x} {-doc_y} {doc_width} {doc_height}")

e = root.xpath('svg:g[@id="layer-scan"]', namespaces=inkex.NSS)[0]
e.set('transform', scrap_transform + ' scale(1,-1) scale(%f)' % (1./th2pref.basescale))
Expand Down
4 changes: 1 addition & 3 deletions extensions/th2_output.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,8 @@ def fstr2(x: float, dbl_dig=15, max_dig=20) -> str:
digits = dbl_dig - math.ceil(math.log10(abs(x)))
except ValueError:
digits = 0
digits = max(0, min(digits, max_dig))
digits = max(1, min(digits, max_dig))
s = f"{x:.{digits}f}"
if digits == 0:
s += ".0"
return fstr_trim_zeros(s)


Expand Down

0 comments on commit 38fd4bb

Please sign in to comment.