-
Notifications
You must be signed in to change notification settings - Fork 44
/
DEUtils.py
304 lines (239 loc) · 7.91 KB
/
DEUtils.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
# coding=utf8
'''
Copyright (R) 2015 Vincent.H <forever.h@gmail.com>
Published under Apache 2.0 License (http://www.apache.org/licenses/LICENSE-2.0.html).
-------------------------------------------------------------------------------------
This module include some util functions.
'''
import csv
from ExtParser import parse_string
import wx
import os, sys, re
import ply.lex as lex
def resource_path(relative_path):
""" Get absolute path to resource, works for "--onefile" in PyInstaller. """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def escape_dot_string(s):
s = s.strip()
if len(s) == 0: return s
# Kill '\n' at the end of s.
while 1:
if len(s) > 0 and s[-1] == '\n':
s = s[:-1]
else:
break
R_PAIR = [('\\l', '*!&@SL'),
('\\n', '*!&@SN'),
('\\r', '*!&@SR'),
('\\"', '*!&@SQ'),
('\\\\', '*!&@SS'),
]
SQ = '*!&@SQ'
SS = '*!&@SS'
# Protect all r.
for rp in R_PAIR:
s = s.replace(rp[0], rp[1])
r_sq = re.compile(r'(?<!\\)"')
r_ss = re.compile(r'(?<!\\)\\')
# Replace '"' and '\'
s = r_sq.sub(SQ, s)
s = r_ss.sub(SS, s)
# Turn back rp
for rp in R_PAIR:
s = s.replace(rp[1], rp[0])
return s
def remove_double_quote(s):
'''Remove double quote if nessary.'''
if not isinstance(s, basestring):
return s
s = s.strip()
if s == '':
return ''
if s[0] == '"' and s[-1] == '"':
s = s[1:-1]
return s
def add_double_quote(s):
'''Add double quote around s if nessary.'''
if not isinstance(s, basestring):
return s
s = s.strip()
if s == '':
return '""'
### OK, some ugly thing on some graphviz version. The '\' at the end never
### allowed. So add a space in this case.
if len(s) > 0 and s[-1] == '\\':
s += ' '
if not (s[0] == '"' and s[-1] == '"'):
s = '"'+s+'"'
return s
def __pos2xy(block_str, pos):
lines = block_str.split('\n')
if pos > len(block_str):
return len(lines)-1, len(lines[-1])
l_begin = 0
for _y in range(len(lines)):
l = lines[_y]
if l_begin <= pos <= l_begin+len(l): # Find the line.
x = pos - l_begin; y = _y
break
l_begin += len(l) +1 # 1 means a '\n'.
return x, y
def smart_indent(block_str, indent_str):
'''Smart add indent_str to the beginning of each line of string.'''
if len(block_str) == 0:
return ''
# Build a lexer.
tokens = ('QUOTED_STRING',)
t_QUOTED_STRING = r'(\"(\\"|[^"])*?\")'
def t_error(t):
t.lexer.skip(1)
lexer = lex.lex()
# Mark quoted block.
lexer.input(block_str)
comment_blocks = []
while True:
tok = lexer.token()
if not tok:
break
r = tok.lexpos, tok.lexpos+len(tok.value)
comment_blocks.append(r)
# Find lines need to skip.
skip_lines = []
for cm in comment_blocks:
_, y0 = __pos2xy(block_str, cm[0])
_, y1 = __pos2xy(block_str, cm[1])
if y1 > y0: # Cross lines comment found.
skip_lines += [y0+1+i for i in range(y1-y0)]
# Add indent now.
lines = block_str.split('\n')
result = []
for x in range(len(lines)):
l = lines[x]
if x not in skip_lines:
result.append(indent_str + l)
else:
result.append(l)
result = '\n'.join(result)
if block_str[-1] == '\n':
result += '\n'
return result
def to_unicode(s):
"Try convert 's' into unicode anyway."
s = s.strip()
u_str = None
try:
u_str = unicode(s)
except:
u_str = s.decode('utf8')
return u_str.encode('utf8')
def gen_arrow_image(arrowtype, out_filepath):
script = '''
digraph G {
rankdir=LR;
margin="0.01";
edge [colorscheme="blues3", color=3];
node [fontname="sans-serif", colorscheme="x11", fontsize=12, color="lightgray", fontcolor="lightgray", height=0.6, width=0, shape="box", style="invis", penwidth=1];
"n1" [label=""];
"n2" [label=""];
"n1" -> "n2" [arrowhead="dot"];
}
'''
g = parse_string(script)
e1 = g.get_edge('"n1"', '"n2"')[0]
e1.get_attributes()['arrowhead'] = add_double_quote('%s'%arrowtype)
g.write(out_filepath, 'dot', 'png')
return
def get_colors_in_schcme(scheme_name):
### Build dict of scheme.
# X11.
if scheme_name == 'x11':
in_f = open(resource_path('resource/color_scheme/rgb.txt'))
in_f.readline() # Skip 1st line.
x11_dict = {}
while 1:
line = in_f.readline()
if line == "":
break
c = line[:11]
r,g,b = map(int, [c[:3], c[4:7], c[8:]])
c_name = line[11:].strip()
x11_dict[c_name] = (r,g,b)
return x11_dict
# Svg.
elif scheme_name == 'svg':
svg_dict = {}
in_f = open(resource_path('resource/color_scheme/svg.csv'), 'rb')
cr = csv.reader(in_f, delimiter=',')
for row in cr:
svg_dict[row[0]] = tuple(map(int, row[1:]))
in_f.close()
return svg_dict
# Colorbrewer.
else:
all_cb_dict = {}
in_f = open(resource_path('resource/color_scheme/colorbrewer.csv'), 'rb')
cr = csv.reader(in_f, delimiter=',')
for row in cr:
cb_name, cb_idx = row[0].split('.')
if cb_name not in all_cb_dict:
all_cb_dict[cb_name] = {}
all_cb_dict[cb_name][cb_idx] = tuple(map(int, row[1:]))
in_f.close()
return all_cb_dict[scheme_name]
return None
def get_image_resource(item_type, attr_name, value_str):
'''Get image resouce by item_type(in ['node', 'edge', 'graph']), attr_name and value_str(in enum list).'''
if item_type == 'node' and attr_name == 'shape':
fn = resource_path('resource/node_shape/%s.png'%value_str)
img = wx.Image(fn)
return img
elif item_type == 'edge' and attr_name in ['arrowhead', 'arrowtail']:
fn = resource_path('resource/edge_arrowtype/%s.png'%value_str)
img = wx.Image(fn)
return img
elif item_type is None and attr_name == 'colorscheme':
fn = resource_path('resource/palette/%s.png'%value_str)
img = wx.Image(fn)
return img
return None
def normalize_imglist(image_list):
'''
Make image in list to the same size.
The image_list should be a list of wxBitmap.
Return a wxImageList as result.
'''
max_w, max_h = (0,0)
for img in image_list:
w,h = img.GetSize()
if w > max_w: max_w = w
if h > max_h: max_h = h
il = wx.ImageList(max_w, max_h)
for img in image_list:
w,h = img.GetSize()
if w==max_w and h==max_h:
il.Add(img.ConvertToBitmap())
else:
pos_x = int((max_w-w)/2)
pos_y = int((max_h-h)/2)
new_img = wx.EmptyImage(max_w, max_h)
new_img.Clear(0xff)
new_img.Paste(img, pos_x, pos_y)
il.Add(new_img.ConvertToBitmap())
return il
if __name__ == '__main__':
s = r'''
AAAA
ABCD "
ABCD
ABCD"
"ABCD\""
"ABCD"
"ABC"
'''
print len(smart_indent(s, ' '*4))
#print gen_CB_palette_img('PuBu')