summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/asymptote/GUI/xasyFile.py
blob: 7516fc7d3b5330d7fd2f26ed1c7c6b412150ac89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env python
###########################################################################
#
# xasyFile implements the loading, parsing, and saving of an xasy file.
#
#
# Author: Orest Shardt
# Created: June 29, 2007
#
############################################################################

from string import *
from xasy2asy import *
import re

class xasyParseError(Exception):
  """A parsing error"""
  pass

class xasyFileError(Exception):
  """An i/o error or other error not related to parsing"""
  pass

def parseFile(inFile):
  """Parse a file returning a list of xasyItems"""
  lines = inFile.read()
  lines = lines.splitlines()
  #lines = [line for line in lines.splitlines() if not line.startswith("//")]
  result = []
  if lines[0] != "initXasyMode();":
    raise xasyFileError("Invalid file format: First line must be \"initXasyMode();\"")
  lines.pop(0)
  lineCount = 2
  lineNum = len(lines)
  while lineNum > 0:
    line = lines[0]
    lines.pop(0)
    if not line.isspace() and len(line)>0:
      try:
        #print ("Line {:d}: {:s}".format(lineCount,line))
        lineResult = parseLine(line.strip(),lines)
      except:
        raise xasyParseError("Parsing error: line {:d} in {:s}\n{:s}".format(lineCount,inFile.name,line))

      if lineResult != None:
        result.append(lineResult)
        #print ("\tproduced: {:s}".format(str(lineResult)))
    lineCount += lineNum-len(lines)
    lineNum = len(lines)
  return result

transformPrefix = "xformStack"
scriptPrefix = "startScript(); {"
scriptSuffix = "} endScript();"
def extractScript(lines):
  """Find the code belonging to a script item"""
  theScript = ""
  line = lines.pop(0)
  level = 1
  while level > 0:
    check = line.lstrip()
    while check.endswith(scriptSuffix):
      level -= 1
      line = line[:len(line)-len(scriptSuffix)]
      check = line.lstrip()
    if check.startswith(scriptPrefix):
      level += 1
    theScript += line + "\n"
    if level > 0:
      line = lines.pop(0)

  global pendingTransformsD
  ts = pendingTransformsD[:]
  pendingTransformsD = []
  return xasyScript(None,script=theScript,transforms=ts[:])

pendingTransforms = []
pendingTransformsD = []
def addTransform(index,t,active=1):
  """Place a transform in the list of transforms, expanding the list as needed"""
  while len(pendingTransformsD) < index+1:
    pendingTransformsD.append(identity())
  deleted = int(active==0)
  pendingTransformsD[index]=asyTransform(t,deleted)

def parseIndexedTransforms(args):
  """Parse a list of indexedTransforms, adding them to the current list of transforms"""
  global pendingTransformsD
  pendingTransformsD = []
  args = args.replace("indexedTransform","")
  false = 0
  tList = [eval(a) for a in ")?(".join(args.split("),(")).split("?")]
  for a in tList:
    addTransform(*a)

def parseTransformExpression(line):
  """Parse statements related to the xformStack
  
  Syntax:
    xformStack.push(transform)
      e.g.: xformStack.push((0,0,1,0,0,1)); //the identity
    xformStack.add(indexedTransform(index,transform)[,...])
      e.g.: xformStack.add(indexedTransform(1,(0,0,1,0,0,1));
  """
  global pendingTransforms
  stackCmd = line[len(transformPrefix)+1:line.find("(")]
  if line[-2:] != ");":
    raise xasyParseError("Invalid syntax")
  args = line[line.find("(")+1:-2]
  if stackCmd == "push":
    t = asyTransform(eval(args))
    pendingTransforms.append(t)
  elif stackCmd == "add":
    parseIndexedTransforms(args)
  else:
    raise xasyParseError("Invalid transform stack command.")
  return None

def parseLabel(line):
  """Parse an asy Label statement, returning an xasyText item"""
  if not (line.startswith("Label(") and line.endswith(",align=SE)")):
    raise xasyParseError("Invalid syntax")
  args = line[6:-1]
  loc2 = args.rfind(",align=SE")
  loc1 = args.rfind(",",0,loc2-1)
  loc = args.rfind(",(",0,loc1-1)
  if loc < 2:
    raise xasyParseError("Invalid syntax")
  text = args[1:loc-1]
  location = eval(args[loc+1:args.find("),",loc)+1])
  pen = args[loc:loc2]
  pen = pen[pen.find(",")+1:]
  pen = pen[pen.find(",")+1:]
  pen = pen[pen.find(",")+1:]
  global pendingTransforms
  return xasyText(text,location,parsePen(pen),pendingTransforms.pop())

def parseLabelCommand(line):
  """Parse a label command returning an xasyText object
  
  Syntax:
    label(Label(text,location,pen,align=SE));
      e.g.: label(Label("Hello world!",(0,0),rgb(0,0,0)+0.5,align=SE));
  """
  if line[-2:] != ");":
    raise xasyParseError("Invalid syntax")
  arguments = line[6:-2]
  return parseLabel(arguments)

def parseDrawCommand(line):
  """Parse a draw command returning an xasyShape object
  
  Syntax:
    draw(path,pen);
      e.g.: draw((0,0)..controls(0.33,0.33)and(0.66,0.66)..(1,1),rgb(1,0,1)+1.5);
  """
  if line[-2:] != ");":
    raise xasyParseError("Invalid syntax")
  args = line[5:-2]
  loc = args.rfind(",rgb")
  path = args[:loc]
  pen = args[loc+1:]
  global pendingTransforms
  return xasyShape(parsePathExpression(path),parsePen(pen),pendingTransforms.pop())

def parseFillCommand(line):
  """Parse a fill command returning an xasyFilledShape object
  
  Syntax:
    fill(cyclic path,pen);
      e.g.: fill((0,0)..controls(0.33,0.33)and(0.66,0.66)..(1,1)..controls(0.66,0)and(0.33,0)..cycle,rgb(1,0,1)+1.5);
  """
  if line[-2:] != ");":
    raise xasyParseError("Invalid syntax")
  args = line[5:-2]
  loc = args.rfind(",rgb")
  path = args[:loc]
  pen = args[loc+1:]
  global pendingTransforms
  return xasyFilledShape(parsePathExpression(path),parsePen(pen),pendingTransforms.pop())

def parsePen(pen):
  """Parse a pen expression returning an asyPen
  
  Syntax:
    color+width[+options]
      e.g.: rgb(0,0,0)+1.5+evenodd
      e.g.: rgb(0,1,0)+1.23
  """
  try:
    tokens = pen.split("+")
    color = eval(tokens[0][3:])
    width = float(tokens[1])
    if len(tokens)>2:
      options = "+".join(tokens[2:])
    else:
      options = ""
    return asyPen(color,width,options)
  except:
    raise xasyParseError("Invalid pen")

def parsePathExpression(expr):
  """Parse an asy path returning an asyPath()"""
  result = asyPath()
  expr = "".join(expr.split())
  #print (expr)
  if expr.find("controls") != -1:
    #parse a path with control points
    tokens = expr.split("..")
    nodes = [a for a in tokens if not a.startswith("controls")]
    for a in range(len(nodes)):
      if nodes[a] != "cycle":
        nodes[a] = eval(nodes[a])
    controls = [[eval(b) for b in a.replace("controls", "").split("and")] for a in tokens if a.startswith("controls")]
    result.initFromControls(nodes, controls)
  else:
    #parse a path without control points
    tokens = re.split(r"(::|--|\.\.)",expr)
    linkSet = re.findall("::|--|\.\.",expr)
    nodeSet = [a for a in tokens if not re.match(r"::|--|\.\.",a)]
    #print (nodeSet)
    for a in range(len(nodeSet)):
      if nodeSet[a] != "cycle":
        nodeSet[a] = eval(nodeSet[a])
    #print (nodeSet)
    result.initFromNodeList(nodeSet, linkSet)
  return result

def takeUntilSemicolon(line,lines):
  """Read and concatenate lines until the collected lines end with a semicolon"""
  data = line
  while not data.endswith(";"):
    newline = lines.pop(0)
    data += newline
  return data

def parseLine(line,lines):
  """Parse a line of the file"""
  if len(line)==0 or line.isspace() or line.startswith("//"):
    return None
  elif line.startswith(scriptPrefix):
    return extractScript(lines)
  elif line.startswith(transformPrefix):
    return parseTransformExpression(takeUntilSemicolon(line,lines))
  elif line.startswith("label("):
    return parseLabelCommand(takeUntilSemicolon(line,lines))
  elif line.startswith("draw("):
    return parseDrawCommand(takeUntilSemicolon(line,lines))
  elif line.startswith("fill("):
    return parseFillCommand(takeUntilSemicolon(line,lines))
  elif line.startswith("exitXasyMode();"):
    return None
  raise Exception("Could not parse the line")

fileHeader = """initXasyMode();
// This file was generated by xasy. It may be edited manually, however, a strict
// syntax must be followed. It is advised that manually scripted items be added
// in the form of a script either by using xasy or by mimicking the format of an
// xasy-generated script item.
// Please consult the documentation or the examples provided for details.
"""

fileFooter = """// This is the end of the file
exitXasyMode();

"""

def saveFile(file,xasyItems):
  """Write a list of xasyItems to a file"""
  file.write(fileHeader)
  for item in xasyItems:
    file.write(item.getCode()+"\n\n")
  file.write(fileFooter)

if __name__ == '__main__':
  root = Tk()
  try:
    name = raw_input("enter file name (\"../../xasyTest.asy\"):")
    if name == '':
      name = "../../xasyTest.asy"
    f = open(name,"rt")
  except:
    print ("Could not open file.")
    asy.quit()
    sys.exit(1)

  fileItems = [] 
  try:
    fileItems = parseFile(f)
    res = [str(a) for a in fileItems]
    print ("----------------------------------")
    print ("Objects in {:s}".format(f.name))
    print ("----------------------------------")
    for a in res:
      print (a)
    print ("----------------------------------")
    print ("successful parse")
    f.close()
  except:
    f.close()
    print ("parse failed")
    raise

  print ("making a file")
  f = open("testfile.asy","wt")
  saveFile(f,fileItems)
  f.close()
  root.configure(width=500,height=500)
  root.title("Results")
  canv = Canvas(root,width=500,height=500)
  canv.pack()
  for i in fileItems[1].imageList:
    canv.create_image(250+i.bbox[0],250-i.bbox[3],anchor = NW, image=i.image)
    Button(root,image=i.image).pack(side=LEFT)
  root.mainloop()