-
Notifications
You must be signed in to change notification settings - Fork 0
/
square-code.py
290 lines (254 loc) · 10.3 KB
/
square-code.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
#!/usr/bin/python
import sys, getopt
import os, os.path
import tempfile
import re, math
import platform
import lib.draw_layer as DL
class square_code:
def __init__(self):
self.version = 1.0
self.ifile = ''
self.ofile = ''
self.tmphandle = None
self.tmpname = ''
self.extensions = []
self.comments = False
self.font = None
self.font_size = 1
self.width = 1600
self.height = 1200
self.excludes = []
self.ws_filter = re.compile('\s\s+')
self.eol_filter = re.compile('[\r\n]+')
self.tab_filter = re.compile('\t+')
self.cpp_comment = re.compile('//.*')
self.hash_comment = re.compile('#.*')
self.c_comment = re.compile('/\*.*\*/')
self.multi_start = re.compile('/\*.*')
self.multi_end = re.compile('.*\*/')
def main(self, argv):
try:
opts, args = getopt.getopt(argv,
"?vi:o:ce:f:w:h:x:",
["help","version","in=","out=","keep-comments","ext=","font=","width=","height=","exclude="])
except getopt.GetoptError:
self.self_description();
sys.exit(2)
for opt, arg in opts:
if opt in ("-?", "--help"):
self_description();
sys.exit()
elif opt in ("-i", "--in"):
self.ifile = arg
elif opt in ("-o", "--out"):
self.ofile = arg
elif opt in ("-c", "--keep-comments"):
self.comments = True
elif opt in ("-e", "--ext"):
if (arg[0] != "."): arg = "."+arg
self.extensions.append(arg)
elif opt in ("-v", "--version"):
print self.version
sys.exit()
elif opt in ("-f", "--font"):
self.font = arg
elif opt in ("-w", "--width"):
self.width = int(arg)
elif opt in ("-h", "--height"):
self.height = int(arg)
elif opt in ("-x", "--exclude"):
self.excludes.append(re.compile(str(arg)))
if self.ifile == '' or self.ofile == '':
self.self_description();
print self.ifile
print self.ofile
sys.exit(2)
if DL.PIL_enabled:
self.draw_obj = DL.pil_layer()
print "Using python imaging library"
elif DL.Cairo_enabled:
self.draw_obj = DL.cairo_layer()
print "Using python cairo library"
else:
print 'Error: no image library found'
sys.exit(2)
if not(os.path.exists(self.ifile)):
print "File/directory does not exist: "+self.ifile
sys.exit(2)
try:
self.tmphandle, self.tmpname = tempfile.mkstemp()
except:
print "Error creating temporary file"
sys.exit(2)
self.tmphandle = os.fdopen(self.tmphandle,'r+')
self.gather_code(self.ifile)
self.tmphandle.seek(0)
everything = self.tmphandle.read()
self.tmphandle.close()
print "Total output is "+str(len(everything))+" characters"
user_font = self.font
self.font = self.font_file(user_font)
if self.font == None and user_font != None:
print "Warning: font '"+user_font+"' not found"
lines = self.split_lines(everything, self.width, self.height)
print "Image size: "+str(self.width)+"x"+str(self.height)
print "Font-size: "+str(self.font_size)
self.render(lines, self.width, self.height)
os.unlink(self.tmpname)
def render(self, lines, width, height):
im = self.draw_obj.get_image((0xff,0xff,0xff), width, height)
font = self.draw_obj.get_font(self.font, self.font_size)
x = 0
y = 0
counter = 1
num_lines = len(lines)
for line in lines:
print "\rWriting line " + str(counter) + "/" + str(num_lines),
counter += 1
self.draw_obj.write_text(im, x, y, line)
y += self.draw_obj.text_size(line)[1]
if os.path.splitext(self.ofile)[1] == '': self.ofile += ".png"
self.draw_obj.save(im, self.ofile)
# search system for font file
def font_file(self, name):
if name == None: None
search_path = '/usr/share/fonts'
if platform.system() == 'Windows':
search_path = 'C:\\Windows\\Fonts'
elif platform.system() == 'Darwin':
search_path = '/Library/Fonts'
for dirpath, dirs, files in os.walk(search_path):
for file in files:
if os.path.splitext(file)[0] == name or file == name:
return os.path.join(dirpath,file)
return None
# get ImageFont object for chosen font
def get_font(self, size):
if self.font == None: return ImageFont.load_default()
else: return ImageFont.truetype(self.font, size)
def split_lines(self, text, width, height):
size = 1
char_per_line = 1
sample_size = 20
sample = text[0:sample_size]
while True:
font_obj = self.draw_obj.get_font(self.font, size)
w, char_height = self.draw_obj.text_size(sample)
char_width = w / float(sample_size)
char_per_line = math.floor(width/char_width)
lines = math.ceil(len(text) / char_per_line)
# font is too big
if lines * char_height > height:
# use previous size
if size > 1:
size -= 1
break
if self.font == None:
print 'Error: cannot fit text to dimensions.'
print 'Try specifying a truetype font. Those are resizable.'
sys.exit(2)
elif size == 1:
print 'Error: cannot fit text to dimensions with selected font.'
sys.exit(2)
elif self.font == None:
# PIL font isn't resizable but technically fits
break
# try next size
size += 1
# find width using chosen size
self.font_size = size
font_obj = self.draw_obj.get_font(self.font, size)
w, char_height = self.draw_obj.text_size(sample)
char_width = w / float(sample_size)
char_per_line = math.floor(width/char_width)
lines = []
char_per_line = int(char_per_line)
while text != '':
if len(text) < char_per_line:
lines.append(text)
text = ''
else:
lines.append(text[0:char_per_line])
text = text[char_per_line:]
print "Writing "+str(len(lines))+" lines with "+str(char_per_line)+" characters each"
return lines
def gather_code(self, path):
directories = []
# if it's a file, process it
if os.path.isfile(path) and (self.extensions == [] or os.path.splitext(path)[1] in self.extensions):
excluded = False
for x in self.excludes:
chk = x.search(os.path.basename(path))
if chk != None:
excluded = True
break
if not(excluded):
self.codefile_to_temp(path)
elif os.path.isdir(path):
# process files in the current directory
# before going down another directory level
for entry in os.listdir(path):
if os.path.isdir(path+os.sep+entry):
directories.append(path+os.sep+entry)
elif os.path.isfile(path+os.sep+entry):
self.gather_code(path+os.sep+entry)
# process directories discovered earlier
for dir in directories:
excluded = False
for x in self.excludes:
chk = x.search(os.path.basename(dir))
if chk != None:
excluded = True
break
if not(excluded):
self.gather_code(dir)
def codefile_to_temp(self, path):
fp = open(path,'r')
str = ''
long_comment = False
for line in fp:
# in a multi-line comment. check for the end of it
if long_comment:
chk = self.multi_end.search(line)
if chk == None: continue
else:
line = self.multi_end.sub('',line)
long_comment = False
# change line endings and tabs to spaces
line = self.eol_filter.sub(' ',line)
line = self.tab_filter.sub(' ',line)
# remove comments
if not(self.comments):
# single line comments first
line = self.c_comment.sub('',line)
line = self.cpp_comment.sub('',line)
line = self.hash_comment.sub('',line)
# check for multi-line comments
if self.multi_start.search(line) != None:
line = self.multi_start.sub('',line)
long_comment = True
# knit all the lines together
str += line
# reduce multiple spaces to a single space
str = self.ws_filter.sub(' ',str)
# write to file
self.tmphandle.write(str+' ')
def multi_test(self,str):
return self.multi_start.search(str)
def self_description(self):
print 'square-code.py [-c -e <extension> -x <pattern> -f <font> -w <width> -h <height>] -i <input file/dir> -o <outputfile>'
print "-c/--keep-comments\t\tInclude comments"
print "-e/--ext <extension>\t\tInclude files with this extension"
print "\t\t\t\tMay be used multiple times"
print "-x/--exclude <pattern>\t\tIgnore files or directories matching the pattern"
print "\t\t\t\tMay be used multiple times"
print "-f/--font <font>\t\tSpecify font"
print "-w/--width <in pixels>\t\tSpecify image width"
print "-h/--height <in pixels>\t\tSpecify image height"
print "-i/--in <file/dir>\t\tInput file or directory"
print "-o/--out <file>\t\t\tOutput file name"
print "-h/--help\t\t\tPrint this"
if __name__ == "__main__":
obj = square_code()
obj.main(sys.argv[1:])