Debian Codegraph @

src/cursors/anicursorgen.py

raw symbols SCIP
1 #!/usr/bin/python2
2 # -*- coding: utf-8 -*-
3 # anicursorgen
4 # Copyright (C) 2015 Руслан Ижбулатов <lrn[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18 #
19 from __future__ import print_function
20
21 import sys
22 import os
23 import argparse
24 import shlex
25 import io
26 import struct
27 import math
28 from PIL import Image
29 from PIL import ImageFilter
30
31 p = struct.pack
32
33 program_name = 'anicursorgen'
34 program_version = 1.0
35
36 def main ():
37 parser = argparse.ArgumentParser (description='Creates .ani or .cur files from separate images and input metadata.',
38 add_help=False)
39 parser.add_argument ('-V', '--version', action='version', version='{}-{}'.format (program_name, program_version),
40 help='Display the version number and exit.')
41 parser.add_argument ('-h', '-?', action='help',
42 help='Display the usage message and exit.')
43 parser.add_argument ('-p', '--prefix', metavar='dir', default=None,
44 help='Find cursor images in the directory specified by dir. If not specified, the current directory is used.')
45 parser.add_argument ('-s', '--add-shadows', action='store_true', dest='add_shadows', default=False,
46 help='Generate shadows for cursors (disabled by default).')
47 parser.add_argument ('-n', '--no-shadows', action='store_false', dest='add_shadows', default=False,
48 help='Do not generate shadows for cursors (put after --add-shadows to cancel its effect).')
49
50 shadows = parser.add_argument_group (title='Shadow generation', description='Only relevant when --add-shadows is given')
51
52 shadows.add_argument ('-r', '--right-shift', metavar='%', type=float, default=9.375,
53 help='Shift shadow right by this percentage of the canvas size (default is 9.375).')
54 shadows.add_argument ('-d', '--down-shift', metavar='%', type=float, default=3.125,
55 help='Shift shadow down by this percentage of the canvas size (default is 3.125).')
56 shadows.add_argument ('-b', '--blur', metavar='%', type=float, default=3.125,
57 help='Blur radius, in percentage of the canvas size (default is 3.125, set to 0 to disable blurring).')
58 shadows.add_argument ('-c', '--color', metavar='%', default='0x00000040',
59 help='Shadow color in 0xRRGGBBAA form (default is 0x00000040).')
60
61 parser.add_argument ('input_config', default='-', metavar='input-config [output-file]', nargs='?',
62 help='Input config file (stdin by default).')
63 parser.add_argument ('output_file', default='-', metavar='', nargs='?',
64 help='Output cursor file (stdout by default).')
65
66 args = parser.parse_args ()
67
68 try:
69 if args.color[0] != '0' or args.color[1] not in ['x', 'X'] or len (args.color) != 10:
70 raise ValueError
71 args.color = (int (args.color[2:4], 16), int (args.color[4:6], 16), int (args.color[6:8], 16), int (args.color[8:10], 16))
72 except:
73 print ("Can't parse the color '{}'".format (args.color), file=sys.stderr)
74 parser.print_help ()
75 return 1
76
77 if args.prefix is None:
78 args.prefix = os.getcwd ()
79
80 if args.input_config == '-':
81 input_config = sys.stdin
82 else:
83 input_config = open (args.input_config, 'rb')
84
85 if args.output_file == '-':
86 output_file = sys.stdout
87 else:
88 output_file = open (args.output_file, 'wb')
89
90 result = make_cursor_from (input_config, output_file, args)
91
92 input_config.close ()
93 output_file.close ()
94
95 return result
96
97 def make_cursor_from (inp, out, args):
98 frames = parse_config_from (inp, args.prefix)
99
100 animated = frames_have_animation (frames)
101
102 if animated:
103 result = make_ani (frames, out, args)
104 else:
105 buf = make_cur (frames, args)
106 copy_to (out, buf)
107 result = 0
108
109 return result
110
111 def copy_to (out, buf):
112 buf.seek (0, io.SEEK_SET)
113 while True:
114 b = buf.read (1024)
115 if len (b) == 0:
116 break
117 out.write (b)
118
119 def frames_have_animation (frames):
120 sizes = set ()
121
122 for frame in frames:
123 if frame[4] == 0:
124 continue
125 if frame[0] in sizes:
126 return True
127 sizes.add (frame[0])
128
129 return False
130
131 def make_cur (frames, args, animated=False):
132 buf = io.BytesIO ()
133 buf.write (p ('<HHH', 0, 2, len (frames)))
134 frame_offsets = []
135
136 def frame_size_cmp (f1, f2):
137 if f1[0] < f2[0]:
138 return -1
139 elif f1[0] > f2[0]:
140 return 1
141 else:
142 return 0
143
144 frames = sorted (frames, frame_size_cmp, reverse=True)
145
146 for frame in frames:
147 width = frame[0]
148 if width > 255:
149 width = 0
150 height = width
151 buf.write (p ('<BBBB HH', width, height, 0, 0, frame[1], frame[2]))
152 size_offset_pos = buf.seek (0, io.SEEK_CUR)
153 buf.write (p ('<II', 0, 0))
154 frame_offsets.append ([size_offset_pos])
155
156 for i, frame in enumerate (frames):
157 frame_offset = buf.seek (0, io.SEEK_CUR)
158 frame_offsets[i].append (frame_offset)
159
160 frame_png = Image.open (frame[3])
161
162 if args.add_shadows:
163 succeeded, shadowed = create_shadow (frame_png, args)
164 if succeeded == 0:
165 frame_png.close ()
166 frame_png = shadowed
167
168 # Windows 10 fails to read PNG-compressed cursors for some reason
169 # and the information about storing PNG-compressed cursors is
170 # sparse. This is why PNG compression is not used.
171 # Previously this was conditional on cursor size (<= 48 to be uncompressed).
172 compressed = False
173
174 # On the other hand, Windows 10 refuses to read very large
175 # uncompressed animated cursor files, but does accept
176 # PNG-compressed animated cursors for some reason. Go figure.
177 if animated:
178 compressed = True
179
180 if compressed:
181 write_png (buf, frame, frame_png)
182 else:
183 write_cur (buf, frame, frame_png)
184
185 frame_png.close ()
186
187 frame_end = buf.seek (0, io.SEEK_CUR)
188 frame_offsets[i].append (frame_end - frame_offset)
189
190 for frame_offset in frame_offsets:
191 buf.seek (frame_offset[0])
192 buf.write (p ('<II', frame_offset[2], frame_offset[1]))
193
194 return buf
195
196 def make_framesets (frames):
197 framesets = []
198 sizes = set ()
199
200 # This assumes that frames are sorted
201 size = 0
202 for i, frame in enumerate (frames):
203 if size == 0 or frame[0] != size:
204 size = frame[0]
205 counter = 0
206
207 if size in sizes:
208 print ("Frames are not sorted: frame {} has size {}, but we have seen that already".format (i, size), file=sys.stderr)
209 return None
210
211 sizes.add (size)
212
213 if counter >= len (framesets):
214 framesets.append ([])
215
216 framesets[counter].append (frame)
217 counter += 1
218
219 for i in range (1, len (framesets)):
220 if len (framesets[i - 1]) != len (framesets[i]):
221 print ("Frameset {} has size {}, expected {}".format (i, len (framesets[i]), len (framesets[i - 1])), file=sys.stderr)
222 return None
223
224 for frameset in framesets:
225 for i in range (1, len (frameset)):
226 if frameset[i - 1][4] != frameset[i][4]:
227 print ("Frameset {} has duration {} for framesize {}, but {} for framesize {}".format (i, frameset[i][4], frameset[i][0], frameset[i - 1][4], frameset[i - 1][0]), file=sys.stderr)
228 return None
229
230 def frameset_size_cmp (f1, f2):
231 if f1[0][0] < f2[0][0]:
232 return -1
233 elif f1[0][0] > f2[0][0]:
234 return 1
235 else:
236 return 0
237
238 framesets = sorted (framesets, frameset_size_cmp, reverse=True)
239
240 return framesets
241
242 def make_ani (frames, out, args):
243 framesets = make_framesets (frames)
244 if framesets is None:
245 return 1
246
247 buf = io.BytesIO ()
248
249 buf.write (b'RIFF')
250 riff_len_pos = buf.seek (0, io.SEEK_CUR)
251 buf.write (p ('<I', 0))
252 riff_len_start = buf.seek (0, io.SEEK_CUR)
253
254 buf.write (b'ACON')
255 buf.write (b'anih')
256 buf.write (p ('<IIIIIIIIII', 36, 36, len (framesets), len (framesets), 0, 0, 32, 1, framesets[0][0][4], 0x01))
257
258 rates = set ()
259 for frameset in framesets:
260 rates.add (frameset[0][4])
261
262 if len (rates) != 1:
263 buf.write (b'rate')
264 buf.write (p ('<I', len (framesets) * 4))
265 for frameset in framesets:
266 buf.write (p ('<I', frameset[0][4]))
267
268 buf.write (b'LIST')
269 list_len_pos = buf.seek (0, io.SEEK_CUR)
270 buf.write (p ('<I', 0))
271 list_len_start = buf.seek (0, io.SEEK_CUR)
272
273 buf.write (b'fram')
274
275 for frameset in framesets:
276 buf.write (b'icon')
277 cur = make_cur (frameset, args, animated=True)
278 cur_size = cur.seek (0, io.SEEK_END)
279 aligned_cur_size = cur_size
280 #if cur_size % 4 != 0:
281 # aligned_cur_size += 4 - cur_size % 2
282 buf.write (p ('<i', cur_size))
283 copy_to (buf, cur)
284 pos = buf.seek (0, io.SEEK_END)
285 if pos % 2 != 0:
286 buf.write ('\x00' * (2 - (pos % 2)))
287
288 end_at = buf.seek (0, io.SEEK_CUR)
289 buf.seek (riff_len_pos, io.SEEK_SET)
290 buf.write (p ('<I', end_at - riff_len_start))
291 buf.seek (list_len_pos, io.SEEK_SET)
292 buf.write (p ('<I', end_at - list_len_start))
293
294 copy_to (out, buf)
295
296 return 0
297
298 def write_png (out, frame, frame_png):
299 frame_png.save (out, "png", optimize=True)
300
301 def write_cur (out, frame, frame_png):
302 pixels = frame_png.load ()
303
304 out.write (p ('<I II HH IIIIII', 40, frame[0], frame[0] * 2, 1, 32, 0, 0, 0, 0, 0, 0))
305
306 for y in reversed (range (frame[0])):
307 for x in range (frame[0]):
308 pixel = pixels[x, y]
309 out.write (p ('<BBBB', pixel[2], pixel[1], pixel[0], pixel[3]))
310
311 acc = 0
312 acc_pos = 0
313 for y in reversed (range (frame[0])):
314 wrote = 0
315 for x in range (frame[0]):
316 if pixels[x, y][3] <= 127:
317 acc = acc | (1 << acc_pos)
318 acc_pos += 1
319 if acc_pos == 8:
320 acc_pos = 0
321 out.write (chr (acc))
322 wrote += 1
323 if wrote % 4 != 0:
324 out.write (b'\x00' * (4 - wrote % 4))
325
326 def parse_config_from (inp, prefix):
327 frames = []
328
329 for line in inp.readlines ():
330 words = shlex.split (line.rstrip ('\n').rstrip ('\r'))
331
332 if len (words) < 4:
333 continue
334
335 try:
336 size = int (words[0])
337 hotx = int (words[1]) - 1
338 hoty = int (words[2]) - 1
339 filename = words[3]
340 if not os.path.isabs (filename):
341 filename = prefix + '/' + filename
342 except:
343 continue
344
345 if len (words) > 4:
346 try:
347 duration = int (words[4])
348 except:
349 continue
350 else:
351 duration = 0
352
353 frames.append ((size, hotx, hoty, filename, duration))
354
355 return frames
356
357 def create_shadow (orig, args):
358 blur_px = orig.size[0] / 100.0 * args.blur
359 right_px = int (orig.size[0] / 100.0 * args.right_shift)
360 down_px = int (orig.size[1] / 100.0 * args.down_shift)
361
362 shadow = Image.new ('RGBA', orig.size, (0, 0, 0, 0))
363 shadowize (shadow, orig, args.color)
364 shadow.load ()
365
366 if args.blur > 0:
367 crop = (int (math.floor (-blur_px)), int (math.floor (-blur_px)), orig.size[0] + int (math.ceil (blur_px)), orig.size[1] + int (math.ceil (blur_px)))
368 right_px += int (math.floor (-blur_px))
369 down_px += int (math.floor (-blur_px))
370 shadow = shadow.crop (crop)
371 flt = ImageFilter.GaussianBlur (blur_px)
372 shadow = shadow.filter (flt)
373 shadow.load ()
374
375 shadowed = Image.new ('RGBA', orig.size, (0, 0, 0, 0))
376 shadowed.paste (shadow, (right_px, down_px))
377 shadowed.crop ((0, 0, orig.size[0], orig.size[1]))
378 shadowed = Image.alpha_composite (shadowed, orig)
379
380 return 0, shadowed
381
382 def shadowize (shadow, orig, color):
383 o_pxs = orig.load ()
384 s_pxs = shadow.load ()
385 for y in range (orig.size[1]):
386 for x in range (orig.size[0]):
387 o_px = o_pxs[x, y]
388 if o_px[3] > 0:
389 s_pxs[x, y] = (color[0], color[1], color[2], int (color[3] * (o_px[3] / 255.0)))
390
391 if __name__ == '__main__':
392 sys.exit (main ())