forked from qgis2web/qgis2web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexp2js.py
287 lines (250 loc) · 7.96 KB
/
exp2js.py
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
from qgis.core import QgsExpression
import re
import json
whenfunctions = []
binary_ops = [
"||", "&&",
"==", "!=", "<=", ">=", "<", ">", "~",
"LIKE", "NOT LIKE", "ILIKE", "NOT ILIKE", "===", "!==",
"+", "-", "*", "/", "//", "%", "^",
"+"
]
unary_ops = ["!", "-"]
def gen_func_stubs():
"""
Generate function stubs for QGIS functions.
"""
funcs = QgsExpression.Functions()
functions = []
temp = """function %s(values, context) {
return false;
};
"""
for func in funcs:
name = func.name()
if name.startswith("$"):
continue
newfunc = temp % ("fnc_" + name)
functions.append(newfunc)
return "\n".join(functions)
def compile(expstr, name=None, mapLib=None):
"""
Convert a QgsExpression into a JS function.
"""
return exp2func(expstr, name, mapLib)
def exp2func(expstr, name=None, mapLib=None):
"""
Convert a QgsExpression into a JS function.
"""
global whenfunctions
whenfunctions = []
exp = QgsExpression(expstr)
js = walkExpression(exp.rootNode(), mapLib=mapLib)
if name is None:
import random
import string
name = ''.join(random.choice(string.ascii_lowercase) for _ in range(4))
name += "_eval_expression"
temp = """
function %s(context) {
// %s
var feature = context.feature;
%s
if (feature.properties) {
return %s;
} else {
return %s;
}
}""" % (name,
exp.dump(),
"\n".join(whenfunctions),
js,
js.replace("feature.properties['", "feature['"))
return temp, name, exp.dump()
def walkExpression(node, mapLib):
try:
if node.nodeType() == QgsExpression.ntBinaryOperator:
jsExp = handle_binary(node, mapLib)
elif node.nodeType() == QgsExpression.ntUnaryOperator:
jsExp = handle_unary(node, mapLib)
elif node.nodeType() == QgsExpression.ntInOperator:
jsExp = handle_in(node, mapLib)
elif node.nodeType() == QgsExpression.ntFunction:
jsExp = handle_function(node, mapLib)
elif node.nodeType() == QgsExpression.ntLiteral:
jsExp = handle_literal(node)
elif node.nodeType() == QgsExpression.ntColumnRef:
jsExp = handle_columnRef(node, mapLib)
elif node.nodeType() == QgsExpression.ntCondition:
jsExp = handle_condition(node,mapLib)
except:
jsExp = "true"
return jsExp
def handle_condition(node, mapLib):
global condtioncounts
subexps = re.findall("WHEN(\s+.*?\s+)THEN(\s+.*?\s+)", node.dump())
QgsMessageLog.logMessage(subexps, "qgis2web", level=QgsMessageLog.INFO)
count = 1;
js = ""
for sub in subexps:
when = sub[0].strip()
then = sub[1].strip()
QgsMessageLog.logMessage(then, "qgis2web", level=QgsMessageLog.INFO)
whenpart = QgsExpression(when)
thenpart = QgsExpression(then)
whenjs = walkExpression(whenpart.rootNode(), mapLib)
thenjs = walkExpression(thenpart.rootNode(), mapLib)
style = "if" if count == 1 else "else if"
js += """
%s %s {
return %s;
}
""" % (style, whenjs, thenjs)
js = js.strip()
count += 1
elsejs = "null"
if "ELSE" in node.dump():
elseexps = re.findall("ELSE(\s+.*?\s+)END", node.dump())
elsestr = elseexps[0].strip()
exp = QgsExpression(elsestr)
elsejs = walkExpression(exp.rootNode(), mapLib)
funcname = "_CASE()"
temp = """function %s {
%s
else {
return %s;
}
};""" % (funcname, js, elsejs)
whenfunctions.append(temp)
return funcname
def handle_binary(node, mapLib):
op = node.op()
retOp = binary_ops[op]
left = node.opLeft()
right = node.opRight()
retLeft = walkExpression(left, mapLib)
retRight = walkExpression(right, mapLib)
if retOp == "LIKE":
return "(%s.indexOf(%s) > -1)" % (retLeft[:-1],
re.sub("[_%]", "", retRight))
elif retOp == "NOT LIKE":
return "(%s.indexOf(%s) == -1)" % (retLeft[:-1],
re.sub("[_%]", "", retRight))
elif retOp == "ILIKE":
return "(%s.toLowerCase().indexOf(%s.toLowerCase()) > -1)" % (
retLeft[:-1],
re.sub("[_%]", "", retRight))
elif retOp == "NOT ILIKE":
return "(%s.toLowerCase().indexOf(%s.toLowerCase()) == -1)" % (
retLeft[:-1],
re.sub("[_%]", "", retRight))
elif retOp == "~":
return "/%s/.test(%s)" % (retRight[1:-2], retLeft[:-1])
elif retOp == "//":
return "(Math.floor(%s %s %s))" % (retLeft, retOp, retRight)
else:
return "(%s %s %s)" % (retLeft, retOp, retRight)
def handle_unary(node, mapLib):
op = node.op()
operand = node.operand()
retOp = unary_ops[op]
retOperand = walkExpression(operand, mapLib)
return "%s %s " % (retOp, retOperand)
def handle_in(node, mapLib):
operand = node.node()
retOperand = walkExpression(operand, mapLib)
list = node.list().dump()
retList = json.dumps(list)
if node.isNotIn():
notIn = "!"
else:
notIn = ""
return "%s%s.indexOf(%s) > -1 " % (notIn, retList, retOperand)
def handle_literal(node):
val = node.value()
quote = ""
if val is None:
val = "null"
elif isinstance(val, basestring):
quote = "'"
val = val.replace("\n", "\\n")
return "%s%s%s" % (quote, unicode(val), quote)
def handle_function(node, mapLib):
fnIndex = node.fnIndex()
func = QgsExpression.Functions()[fnIndex]
args = node.args().list()
retFunc = (func.name())
retArgs = []
for arg in args:
retArgs.append(walkExpression(arg, mapLib))
retArgs = ",".join(retArgs)
return "fnc_%s([%s], context)" % (retFunc, retArgs)
def handle_columnRef(node, mapLib):
if mapLib is None:
return "feature['%s'] " % node.name()
if mapLib == "Leaflet":
return "feature.properties['%s'] " % node.name()
else:
return "feature.get('%s') " % node.name()
def render_examples():
lines = [
"""var feature = {
COLA: 1,
COLB: 2,
WAT: 'Hello World'
};""",
"""var context = {
feature: feature,
variables: {}
};"""
]
def render_call(name):
callstr = "var result = {0}(context);".format(name)
callstr += "\nconsole.log(result);"
return callstr
def render_example(exp):
data, name, dump = exp2func(exp, mapLib="Leaflet")
lines.append(data)
lines.append(render_call(name))
import os
if not os.path.exists("examples"):
os.mkdir("examples")
with open("examples\qgsfunctions.js", "w") as f:
# Write out the functions first.
funcs = gen_func_stubs()
f.write(funcs)
with open("examples\qgsexpression.js", "w") as f:
exp = "(1 + 1) * 3 + 5"
render_example(exp)
exp = "NOT @myvar = format('some string %1 %2', 'Hello', 'World')"
render_example(exp)
exp = """
CASE
WHEN to_int(123.52) = @myvar THEN to_real(123)
WHEN (1 + 2) = 3 THEN 2
ELSE to_int(1)
END
OR (2 * 2) + 5 = 4"""
render_example(exp)
exp = """
CASE
WHEN "COLA" = 1 THEN 1
WHEN (1 + 2) = 3 THEN 2
ELSE 3
END
"""
render_example(exp)
f.writelines("\n\n".join(lines))
def compile_to_file(exp, name=None, mapLib=None, filename="expressions.js"):
"""
Generate JS function to file from exp and append it to the end of the given file name.
:param exp: The expression to export to JS
:return: The name of the function you can call.
"""
functionjs, name, _ = compile(exp, name=name, mapLib=mapLib)
with open(filename, "a") as f:
f.write("\n\n")
f.write(functionjs)
return name
if __name__ == "__main__":
render_examples()