-
Notifications
You must be signed in to change notification settings - Fork 7
/
Metamorphosis.py
1817 lines (1547 loc) · 107 KB
/
Metamorphosis.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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import Iconolatry
import os
import re
import logging
import argparse
from time import perf_counter
from zlib import decompress
from struct import unpack_from, calcsize
from PIL import Image
from stat import S_IWRITE
from shutil import rmtree
from math import ceil
from subprocess import Popen, PIPE
from zipfile import ZipFile
from io import BytesIO
from itertools import chain
from shutil import make_archive
from tempfile import gettempdir
from hashlib import md5
from collections import OrderedDict
__version__ = "V (Reborn)"
__license__ = "GPL-3.0 License"
__author__ = u"Matteo ℱan <[email protected]>"
__copyright__ = "© Copyright 2018-2021"
__url__ = "https://github.com/SystemRage/Metamorphosis"
__summary__ = "The Ultimate Cursor Converter"
## _________________________________________
##| Support to "repeat"/"end repeat" loops |--------------------------------------------------------------------------------------------------------------
##|_________________________________________|
##
class Repeat(object):
def __init__(self, script):
self.script = script
self.start, self.stop, self.nloops = ([] for _ in range(3))
self.loop_expand()
def loop_limit(self):
""" Defines all start loops indexes ('repeat N'),
all stop loops indexes ('end repeat') and all number of repetitions ('N').
"""
for indx, line in enumerate(self.script):
if line.startswith('repeat'):
self.start.append(indx)
self.nloops.append(int(re.split('\s', line)[1]))
elif line.startswith('end'):
self.stop.append(indx)
def loop_flatten(self, lst):
""" Transforms a list of lists to a flat list. """
for elem in lst:
if hasattr(elem, '__iter__') and not isinstance(elem, (str, bytes)):
yield from self.loop_flatten(elem)
else:
yield elem
def loop_expand(self):
""" Expands not nested or nested loops or any combination of both. """
self.loop_limit()
while self.start != []:
## Calculate distances between first stop index with all start indexes.
dist = [self.stop[0] - self.start[i] for i in range(len(self.start))]
## Find index of distances where there's min positive distance.
min_dist = min(i for i in dist if i > 0)
index_min_dist = dist.index(min_dist)
## Create loop extension and calculate the number of elements to insert.
chunk = self.script[self.start[index_min_dist] + 1 : self.stop[0]] * self.nloops[index_min_dist]
nadj = (self.stop[0] - (self.start[index_min_dist] + 1)) * self.nloops[index_min_dist]
## Remove in the script the loop in exam and calculate the number of elements erased.
self.script[self.start[index_min_dist] : self.stop[0] + 1] = []
ndel = self.stop[0] + 1 - self.start[index_min_dist]
## Insert loop extension at right place and flatten.
self.script.insert(self.start[index_min_dist], chunk)
self.script = list(self.loop_flatten(self.script))
shift = nadj - ndel
## Shift all start indexes after the used one.
shifted_start = [x + shift for x in self.start[index_min_dist + 1::]]
self.start = self.start[0 : index_min_dist + 1] + shifted_start
## Shift all stop indexes after the first.
shifted_stop = [x + shift for x in self.stop[1::]]
self.stop = self.stop[0 : 1] + shifted_stop
## Update lists removing used elements.
self.start.pop(index_min_dist)
self.stop.pop(0)
self.nloops.pop(index_min_dist)
## _________________________________
##| Generic functions and variables |------------------------------------------------------------------------------------------------------------------------
##|_________________________________|
##
script_pattern = re.compile(r'(\d+)(?:-(\d+))?(?:,(\d+))?')
label = "*Converted by Metamorphosis, {}*".format(__copyright__)
working_path = os.path.abspath('.')
""" Cursor names.
the list of output file names are based on http://fedoraproject.org/wiki/Artwork/EchoCursors/NamingSpec.
NameCursorFX:((NameCursorXP), (NameCursorWindows), (LinkforLinux), (NamesCursorLinux))
"""
## TODO: To assign : dotbox, dot-box, dot_box, dot_box_mask, draped_box, draped-box, icon, target, zoom-in, zoom-out
cursor_namemap = {
# Cursor shape arrow.
0 : (('Arrow'), ('Arrow'), ('00normal_select'), ('default','arrow',
'top-left-arrow','top_left_arrow',
'left_ptr',
'x-cursor','X_cursor')),
# Cursor guide (arrow with ?).
1 : (('Help'), ('Help'), ('01help_select'), ('ask','dnd-ask',
'help','question_arrow','whats_this',
'5c6cd98b3f3ebcb1f9c7f1c204630408',
'left_ptr_help',
'd9ce0ab605698f320427677b458ad60b')),
# Cursor applications start.
2 : (('AppStarting'), ('AppStarting'),('02working_in_background'), ('progress','left_ptr_watch',
'08e8e1c95fe2fc01f976f1e063a24ccd',
'3ecb610c1bf2410f44200f48c40d3599')),
# Cursor wait.
3 : (('Wait'), ('Wait'), ('03busy'), ('wait','watch',
'0426c94ea35c87780ff01dc239897213')),
# Cursor precision selection.
4 : (('Cross'), ('Crosshair'), ('04precision_select'), ('crosshair','cross',
'diamond_cross',
'cross_reverse','tcross')),
# Cursor text.
5 : (('IBeam'), ('IBeam'), ('05text_select'), ('text','xterm',
'ibeam','vertical-text')),
# Cursor shape pen.
6 : (('Handwriting'), ('NWPen'), ('06handwriting'), ('pencil',)),
# Cursor area not allowed.
7 : (('NO'), ('No'), ('07unavailable'), ('no-drop','dnd-none','circle',
'03b6e0fcb3499374a867c041f52298f0',
'not-allowed','crossed_circle',
'forbidden','pirate')),
# Cursor resize two arrows pointing to N and S.
8 : (('SizeNS'), ('SizeNS'), ('08north_resize'), ('col-resize','sb_v_double_arrow',
'split_v','14fef782d02440884392942c11205230',
'n-resize','top_side','ns-resize','v_double_arrow',
'size_ver','00008160000006810000408080010102',
'top-tee','top_tee',
'double_arrow','double-arrow'
'up','sb_up_arrow')),
# Cursor resize two arrows pointing to N.
9 : (('SizeS'), ('SizeS'), ('09south_resize'), ('bottom-tee','bottom_tee','down',
'sb_down_arrow','s-resize',
'bottom_side')),
# Cursor resize two arrows pointing to W and E.
10 : (('SizeWE'), ('SizeWE'), ('10west_resize'), ('ew-resize','h_double_arrow',
'size_hor','028006030e0e7ebffc7f7070c0600140',
'left','sb_left_arrow','left-tee','left_tee',
'row-resize','sb_h_double_arrow','split_h',
'2870a09082c103050810ffdffffe0204',
'w-resize','left_side')),
# Cursor resize one arrow pointing to W.
11 : (('SizeE'), ('SizeE'), ('11east_resize'), ('e-resize','right_side','right','sb_right_arrow',
'right-tee','right_tee')),
# Cursor resize two arrows pointing to NW and SE.
12 : (('SizeNWSE'), ('SizeNWSE'), ('12northwest_resize'), ('nw-resize','top_left_corner','ul_angle',
'nwse-resize','fd_double_arrow','size_fdiag',
'c7088f0f3e6c8088236ef8e1e3e70000')),
# Cursor resize one arrow pointing to NW.
13 : (('SizeSE'), ('SizeSE'), ('13southeast_resize'), ('se-resize','lr_angle',
'bottom_right_corner')),
# Cursor resize two arrows pointing to NE and SW.
14 : (('SizeNESW'), ('SizeNESW'), ('14northeast_resize'), ('ne-resize','top_right_corner','ur_angle',
'nesw-resize','bd_double_arrow','size_bdiag',
'fcf1c3c7cd4491d801f1e1c78f100000')),
# Cursor resize one arrow pointing to NE.
15 : (('SizeSW'), ('SizeSW'), ('15southwest_resize'), ('sw-resize','ll_angle',
'bottom_left_corner')),
# Cursor resize with four arrows pointing to N/S/W/E.
16 : (('SizeAll'), ('SizeAll'), ('16move'), ('cell','plus','all-scroll','fleur',
'size_all')),
# Cursor arrow upside for an insertion point.
17 : (('UpArrow'), ('UpArrow'), ('17alternate_select'), ('top-right-arrow','right_ptr','move','dnd-move',
'4498f0e0c1937ffe01fd06f973665830',
'9081237383d90e509aa00f00170e968f',
'draft_large','draft_small'
'up-arrow','up_arrow','center_ptr')),
# Cursor shape hand.
18 : (('Hand'), ('Hand'), ('18hand'), ('alias','link','dnd-link',
'3085a0e285430894940527032f8b26df',
'640fb0e74195791501fd1ed57b41487f',
'9d800788f1b08800ae810202380a0822',
'e29285e634086352946a0e7090d73106',
'a2a266d0498c3104214a47bd64ab0fc8',
'b66166c04f8c3109214a4fbd64a50fc8',
'left-hand','hand1','pointer','hand2',
'grab','grabbing'
'pointing_hand','openhand','hand')),
# Cursor default with a small plus sign next to it.
19 : (('Button'), ('Button'), ('19button'), ('copy','dnd-copy',
'1081e37283d90000800003c07f3ef6bf',
'6407b0e94181790501fd1e167b474872'))
}
class ExtendAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string = None):
items = getattr(namespace, self.dest) or []
items.extend(values)
setattr(namespace, self.dest, items)
def metamorphosis_parser():
""" CLI parser. """
options = {}
morph_parser = argparse.ArgumentParser(description = __summary__, epilog = 'version: ' + __version__, add_help = False, allow_abbrev = False)
morph_parser.register('action', 'extend', ExtendAction)
morph_required = morph_parser.add_argument_group('required arguments')
morph_required.add_argument('-i', '--input', required = True, nargs = "+", action = "extend", default = [], type = str,
dest = "input",
help = "Path(s) of cursor file(s) or folder(s) to convert.")
morph_optional = morph_parser.add_argument_group('optional arguments')
morph_optional.add_argument('-h', '--help', action = "help", default = argparse.SUPPRESS,
help = "show this help message and exit")
morph_optional.add_argument('-o', '--output', action = "store", default = working_path, type = str,
dest = "output",
help = "Path of converted cursor(s). Default is your working directory.")
morph_optional.add_argument('-p', '--pack', action = 'store_true', default = False,
dest = "pack",
help = "Enable packing converted cursors. Disabled by default")
morph_optional.add_argument('-r', '--crop', action = 'store_false', default = True,
dest = "crop",
help = "Disable removing transparent border. Enabled by default.")
morph_optional.add_argument('-s', '--size', action = 'store', default = 16, choices = [16, 24, 32, 48, 64, 96], type = int,
dest = "size",
help = "Select size (in pixels) for converted cursors. Default is `16` pixels.")
morph_optional.add_argument('-c', '--color', action = 'store', default = 'rgb', choices = ['rgb', 'rbg', 'grb', 'brg', 'gbr', 'bgr'], type = str,
dest = "color",
help = "Select color change for converted cursors. Default is `rgb`.")
morph_optional.add_argument('-t', '--platform', action = 'store', default = 'Linux', choices = ['Linux', 'Windows'], type = str,
dest = "platform",
help = "Select destination OS for converted cursors. Default is `Linux` platform.")
try:
options.update(vars(morph_parser.parse_args()))
## Define size as tuple (width and height).
options['size'] = (options['size'], options['size'])
except Exception as e:
raise e
return options
## ________________________
##| Image editor functions |---------------------------------------------------------------------------------------------------------------------------------
##|________________________|
##
class Editor(object):
def __init__(self, parameters, options):
self.parameters = parameters
self.options = options
def resize_meth(self, image, method = Image.ANTIALIAS):
""" Resizes PIL image to a maximum size specified maintaining the aspect ratio.
Allows usage of different resizing methods and does not modify the image in place,
then creates an exact square image.
"""
w_fin, h_fin = self.options['size']
w_ini, h_ini = image.size
ini_aspect = float(w_ini) / float(h_ini)
fin_aspect = float(w_fin) / float(h_fin)
if ini_aspect >= fin_aspect:
## Set w to (final width).
## Set h to (final width / initial aspect ratio).
image = image.resize((w_fin, int((float(w_fin) / ini_aspect) + 0.5)), method)
else:
## Set w to (final height * initial aspect ratio).
## Set h to (final height).
image = image.resize((int((float(h_fin) * ini_aspect) + 0.5), h_fin), method)
## Create background transparent image.
thumbnail = Image.new('RGBA', self.options['size'], (255, 255, 255, 0))
thumbnail.paste(image, ((w_fin - image.size[0]) // 2, (h_fin - image.size[1]) // 2))
return thumbnail
def resize_exec(self, image_list):
""" Applies icon dimensions resize to image list and adjusts hotspots. """
w_fin, h_fin = self.options['size']
w_ini, h_ini = image_list[0].size
scale_x = w_fin / w_ini
scale_y = h_fin / h_ini
image_list = [self.resize_meth(image_list[i], method = Image.ANTIALIAS) for i in range(self.parameters['count'])]
## Scale hotspots.
self.parameters['hotx'] = int(0.5 * ceil(2.0 * (self.parameters['hotx'] * scale_x)))
self.parameters['hoty'] = int(0.5 * ceil(2.0 * (self.parameters['hoty'] * scale_y)))
return image_list
def slice(self, image_strip):
""" Gets images from strip image. """
image_w, image_h = image_strip.size
frame_w = int(image_w / self.parameters['count'])
image_list = [image_strip.crop((frame_w * i, 0, frame_w * (i + 1), image_h)) for i in range(self.parameters['count'])]
return image_list
def crop(self, image_list):
""" Crops border. """
bbox = [self.parameters['hotx'], self.parameters['hoty'],
self.parameters['hotx'] + 1, self.parameters['hoty'] + 1]
for i in range(self.parameters['count']):
tbbox = image_list[i].getbbox()
if tbbox is not None:
bbox[0] = min(bbox[0], tbbox[0])
bbox[1] = min(bbox[1], tbbox[1])
bbox[2] = max(bbox[2], tbbox[2])
bbox[3] = max(bbox[3], tbbox[3])
image_list = [image_list[i].crop(bbox) for i in range(self.parameters['count'])]
self.parameters['hotx'] -= bbox[0]
self.parameters['hoty'] -= bbox[1]
return image_list
def colorize(self, image):
""" Changes color cursor. """
## rgba --> original.
if self.options['color'] != 'rgb':
image = image.convert('RGBA')
r, g, b, a = image.split()
ch1, ch2, ch3 = list(self.options['color'])
## rbga --> swap green - blue.
## grba --> swap red - green.
## bgra --> inverted.
## brga --> inverted, swap red - green.
## gbra --> inverted, swap green - blue.
image = Image.merge('RGBA', (eval(ch1), eval(ch2), eval(ch3), a))
return image
def adjust(self, image, extended = True, custom = ''):
""" Executes some edit operations. """
if extended:
## Save image strip (format: img0-1.png).
path = os.path.join(process.original_dir, "img{:d}-{:d}.png".format(self.parameters['index'], self.parameters['status']))
image.save(path, 'PNG')
## Get every frame image from image strip.
image = self.slice(image)
## Crop transparent border (eventually).
if self.options['crop']:
image = self.crop(image)
## Resize.
if self.options['size'] != (0, 0):
image = self.resize_exec(image)
## Colorize and save images (format: img0-1_0.png).
for i in range(self.parameters['count']):
ima = self.colorize(image[i])
path = os.path.join(process.original_dir, ("{}".format(custom) if custom else
"img{:d}-{:d}_{:d}.png".format(self.parameters['index'], self.parameters['status'], i)))
ima.save(path, 'PNG')
## ______________________________________
##| Parsing script / animation functions |-------------------------------------------------------------------------------------------------------------------
##|______________________________________|
##
class Parser(object):
def __init__(self, parameters, options):
self.parameters = parameters
self.options = options
self.logger = logging.getLogger('Metamorphosis')
def cfg_writer(self, cfg, script_index, script_interval, custom = ''):
""" Support for config files writing. """
towrite = ''
if self.options['platform'] == 'Linux':
towrite += "{:d} {:d} {:d} ".format(self.options['size'][0], self.parameters['hotx'], self.parameters['hoty'])
path = (process.icocur_dir if self.options['platform'] == 'Windows' else process.original_dir)
extension = ('.cur' if self.options['platform'] == 'Windows' else '.png')
towrite += os.path.join(path, "img{:d}-{:d}_{:d}{}{} {:d}\n".format(self.parameters['index'],
self.parameters['status'], script_index, custom,
extension, script_interval))
cfg.write(towrite)
def script(self, cfg, script_data):
""" Creates the sequence script defined. """
is_parsed = True
try:
for line in script_data:
## Note examples:
## script_pattern.match('2-5,30').groups() --> ('2', '5', '30')
## script_pattern.match('6-10').groups() --> ('6', '10', None)
## script_pattern.match('1,3000').groups() --> ('1', None, '3000')
start_frame, stop_frame, interval = script_pattern.match(line).groups()
start_frame = int(start_frame)
stop_frame = (int(stop_frame) if stop_frame else start_frame)
interval = (int(interval) if interval else self.parameters['interval'])
step = (1 if stop_frame >= start_frame else -1)
## Note that the frame index in the script is 1-based.
if all(value <= self.parameters['count'] for value in [start_frame, stop_frame]):
for i in range(start_frame, stop_frame + step, step):
self.cfg_writer(cfg, i - 1, interval)
else:
self.logger.error('Error: cannot parse script line "{}" --> script indexes mismatch\n'.format(line))
is_parsed = False
break
except:
self.logger.error('Error: cannot parse script line "{}" --> script corrupted\n'.format(line))
is_parsed = False
return is_parsed
def animation(self, cfg):
""" Creates the sequence animation defined. """
if self.parameters['anim'] == 0:
# Case animation: NONE
for i in range(self.parameters['count']):
interval = (self.parameters['interval'] if i < self.parameters['count'] - 1 else 1000000)
self.cfg_writer(cfg, i, interval)
elif self.parameters['anim'] == 2:
# Case animation: LOOP
for i in range(self.parameters['count']):
self.cfg_writer(cfg, i, self.parameters['interval'])
elif self.parameters['anim'] == 3:
# Case animation: ALTERNATE
for i in chain(range(self.parameters['count']), range(self.parameters['count'] - 2, -1, -1)):
self.cfg_writer(cfg, i, self.parameters['interval'])
else:
self.logger.error('Error: unknown animation type: {:d}\n'.format(self.parameters['anim']))
## _______________________________________
##| Stardock cursors conversion functions |------------------------------------------------------------------------------------------------------------------
##|_______________________________________|
##
class Stardock(object):
def __init__(self, options):
self.options = options
self.logger = logging.getLogger('Metamorphosis')
def strip_frames(self, image_strip):
""" Gets image strip frames and adjust them. """
editor = Editor(self.parameters, self.options)
editor.adjust(image_strip)
def script_missing(self, cfg_file):
""" Defines operations when script missing. """
self.logger.warning('Warning: script missing: fallback to default animation for image index #{:d}, status {:d}\n'
.format(self.parameters['index'], self.parameters['status']))
## Use default animation.
parser = Parser(self.parameters, self.options)
parser.animation(cfg_file)
def script_exist(self, cfg_file, script_data):
""" Defines operations when script exists. """
## Log script lines.
self.logger.info('\tScript:\n\t\t{}\n'.format('\n\t\t'.join(script_data)))
## Eventually expand loops.
if 'end repeat' in script_data:
try:
script_data = Repeat(script_data).script
except:
self.logger.error('Error: cannot expand script --> script corrupted\n')
## Parse script.
parser = Parser(self.parameters, self.options)
is_parsed = parser.script(cfg_file, script_data)
if not is_parsed:
## Script not well formatted.
self.logger.warning('Warning: script corrupted: fallback to default animation for image index #{:d}, status {:d}\n'
.format(self.parameters['index'], self.parameters['status']))
cfg_file.seek(0)
## Using default animation.
parser.animation(self.options['size'][0])
def convert_FX(self, fileFX):
""" Extracts data from theme file `.cursorFX`, then creates `.ani`s or `X11`s. """
## Read data file.
with open(fileFX, 'rb') as file:
data = file.read()
## Extract header data.
self.logger.info('<------>< Info Extraction ><------>\n')
version, header_size, data_size, theme_type = unpack_from('<4I', data, 0)
info_size, = unpack_from('<I', data, header_size - 4)
self.logger.info(u'Header info:\n\n\tVersion: {}\n\tHeader size: {}\n\tData size: {}\n\tTheme type: {}\n\tInfo size: {}\n\n'
.format(version, header_size, data_size, theme_type, info_size))
## Extract remaining data.
data = decompress(data[header_size:])
try:
assert len(data) == data_size
except AssertionError:
self.logger.error('Error: file {} corrupted --> conversion aborted\n'.format(fileFX))
return
## Get theme info.
info = data[:info_size].decode('utf-16le').split('\0')[:-1]
## Handle theme info data.
if not info:
comment = 'missing'
## Theme name missing in datastream, get it from filename.
theme_name = os.path.splitext(os.path.basename(fileFX))[0]
else:
comment = " - ".join(list(" ".join(inf.splitlines()) for inf in info))
theme_name = info[0].strip()
theme_name = theme_name.replace(',', '_').replace(' ', '')
self.logger.info('Theme info:\n\n\t{}\n\n'.format(comment))
## Creation subfolders under `targets` folder.
process.create_subfolders(theme_name)
## Start processing data.
cur_pos = info_size
while cur_pos < len(data):
## Extract data.
pointer_type, size_of_header_without_script_1, size_of_header_and_image = unpack_from('<3I', data, cur_pos)
if pointer_type != 2:
self.logger.error('Error: found type #{:d}, not a pointer image --> conversion skipped\n'.format(pointer_type))
cur_pos += size_of_header_and_image
continue
(unknown_1, image_index, cursor_status,
unknown_2, frame_count, image_width, image_height, frame_interval, animation_type,
unknown_3, mouse_x, mouse_y,
size_of_header_with_script, size_of_image,
size_of_header_without_script_2, size_of_script) = unpack_from('<16I', data, cur_pos + calcsize('<3I'))
self.logger.info('<------>< Image Extraction ><------>\n')
self.logger.info(u'Image index #{}:\n\n\tType: {}\n\tUnknown_1: {}\n\tStatus: {}\n\tUnknown_2: {}\n\tFrame count: {}\n\t\
Image size: {} x {}\n\tFrame interval: {}\n\tUnknown_3: {}\n\tAnimation type: {}\n\tHotspot position: ({}, {})\n\tScript size: {}\n'
.format(image_index, pointer_type, unknown_1, cursor_status, unknown_2, frame_count,
image_width, image_height, frame_interval, unknown_3, animation_type, mouse_x, mouse_y, size_of_script))
self.parameters = {'index' : image_index,
'status' : cursor_status,
'count' : frame_count,
'interval' : frame_interval,
'hotx' : mouse_x,
'hoty' : mouse_y,
'anim' : animation_type
}
try:
assert size_of_header_without_script_1 == size_of_header_without_script_2
assert size_of_header_with_script == size_of_header_without_script_1 + size_of_script
assert size_of_header_and_image == size_of_header_with_script + size_of_image
assert size_of_image == image_width * image_height * 4
except AssertionError:
self.logger.error('Error: image #{:d} corrupted --> conversion skipped\n'.format(image_index))
cur_pos += size_of_header_and_image
continue
## Get strip image / strip image frames.
image_strip = Image.frombytes('RGBA', (image_width, image_height),
data[cur_pos + size_of_header_with_script : cur_pos + size_of_header_and_image],
'raw', 'BGRA', 0, -1)
self.strip_frames(image_strip)
## Create config file.
with open(process.config(self.parameters), 'w') as cfg_file:
if size_of_script > 0:
script_data = data[cur_pos + size_of_header_without_script_1 : cur_pos + size_of_header_with_script].decode('utf-16le')[:-1]
script_data = script_data.replace(';', '\n')
script_data = script_data.splitlines()
script_data = [re.sub(r'(?:(?<=\,|-)\s*|\s*(?=\,|-))', '', ' '.join(line.split())) for line in script_data]
self.script_exist(cfg_file, script_data)
elif size_of_script == 0:
self.script_missing(cfg_file)
## Generate.
gen_instance = process.generate(self.parameters, theme_name)
cur_pos += size_of_header_and_image
## Packing.
process.packing(gen_instance, theme_name, comment)
def convert_XP(self, fileXP):
""" Extracts data from theme file `.CurXPTheme`, then creates `.ani`s or `X11`s. """
## Open and read XP theme file.
try:
archive = ZipFile(fileXP, 'r')
scheme = archive.read('Scheme.ini')
scheme = scheme.decode('ascii').replace(';', '\r\n').split('\r\n')
## Fix for multi return carriage.
scheme = [line for line in scheme if line != '']
except:
self.logger.error('Error: file {} missing "Scheme.ini" --> conversion aborted\n'.format(fileXP))
return
## Get description content.
try:
comment = scheme[scheme.index('[Description]') + 1 ::]
comment = [line.strip() for line in comment if line.strip() != '']
comment = " - ".join(comment)
except ValueError:
comment = 'missing'
## Get theme name from file name.
theme_name = os.path.splitext(os.path.basename(fileXP))[0]
theme_name = theme_name.replace(',', '_').replace(' ', '')
self.logger.info('Theme info:\n\n\t{}\n\n'.format(comment))
## Creation subfolders under `targets` folder.
process.create_subfolders(theme_name)
## Get "Scheme.ini" data indexes.
indexes = [scheme.index(line) for line in scheme if line.startswith('[') and line != '[General]']
## Start processing data.
for i in range(len(indexes) - 1):
if not scheme[indexes[i]].endswith('_Script]'):
## Get data image.
image_data = scheme[indexes[i] + 1 : indexes[i + 1]]
name = scheme[indexes[i]].replace('_Down', '').replace('[', '').replace(']', '')
image_index, = [key for key, value in cursor_namemap.items() if name == value[0]]
## Prevents incorrect ordering.
self.parameters = {'index' : image_index,
'status' : 'StdCursor',
'count' : 'Frames',
'interval': 'Interval',
'anim' : 'Animation style',
'hotx1' : 'Hot spot x',
'hoty1' : 'Hot spot y',
'hotx2' : 'Hot spot x2',
'hoty2' : 'Hot spot y2',
'script' : 'FrameScript'
}
for line in image_data:
identifier, assign = line.split('=')
for key, value in self.parameters.items():
if value == identifier:
self.parameters[key] = int(assign)
## Impose some parameters if missing.
for key in ['status', 'anim', 'script']:
if not isinstance(self.parameters[key], int):
self.parameters[key] = 0
## Some preliminar parameters checks.
if (self.parameters['count'] in [0, 'Frames']) or \
(self.parameters['interval'] in [0, 'Interval']) or \
any(isinstance(self.parameters[key], str) for key in ['hotx1', 'hoty1', 'hotx2', 'hoty2']):
self.logger.error('Error: "Scheme.ini" corrupted --> cursor #{:d} skipped\n'.format(self.parameters['index']))
continue
else:
## Normalize variables like `.cursorFX` style.
# Status.
# for CursorXP --> CURSOR_STATUS_NORMAL = 0, CURSOR_STATUS_ERROR = 1
self.parameters['status'] = 1 - self.parameters['status']
if scheme[indexes[i]].endswith('_Down]'):
self.parameters['status'] = 2
# Animation.
# for CursorXP --> ANIMATION_TYPE_NONE = 0, ANIMATION_TYPE_LOOP = 1, ANIMATION_TYPE_ALTERNATE = 2
self.parameters['anim'] = (self.parameters['anim'] + 1 if self.parameters['anim'] else self.parameters['anim'])
## Fix for different hotspot couples.
if (self.parameters['hotx1'] != self.parameters['hotx2']) or (self.parameters['hoty1'] != self.parameters['hoty2']):
self.parameters['hotx'] = min(self.parameters['hotx1'], self.parameters['hotx2'])
self.parameters['hoty'] = min(self.parameters['hoty1'], self.parameters['hoty2'])
else:
self.parameters['hotx'] = self.parameters['hotx1']
self.parameters['hoty'] = self.parameters['hoty1']
for key in ['hotx1', 'hotx2', 'hoty1', 'hoty2']:
self.parameters.pop(key, None)
self.logger.info('<------>< Image Extraction ><------>\n')
self.logger.info(u'Image index #{}:\n\n\tStatus: {}\n\tFrame count: {}\n\tFrame interval: {}\n\t\
Animation type: {}\n\tHotspot position: ({}, {})\n\tScript status: {}\n'
.format(self.parameters['index'], self.parameters['status'], self.parameters['count'],
self.parameters['interval'], self.parameters['anim'],
self.parameters['hotx'], self.parameters['hoty'], self.parameters['script']))
## Get strip image / strip image frames.
if self.parameters['status'] in [1, 2]:
try:
image_strip = Image.open(BytesIO(archive.read(name + '.png')))
except:
self.logger.error('Error: strip image missing --> cursor #{:d} skipped\n'.format(self.parameters['index']))
continue
elif self.parameters['status'] == 0:
self.logger.error('Error: strip image missing --> cursor #{:d} skipped\n'.format(self.parameters['index']))
continue
self.strip_frames(image_strip)
## Create config file (no script).
if self.parameters['script'] == 0:
with open(process.config(self.parameters), 'w') as cfg_file:
self.script_missing(cfg_file)
## Generate.
gen_instance = process.generate(self.parameters, theme_name)
else:
## Create config file (with script).
if self.parameters['script'] == 1:
with open(process.config(self.parameters), 'w') as cfg_file:
script_data = scheme[indexes[i] + 1 : indexes[i + 1]]
script_data = [re.sub(r'(?:(?<=\,|-)\s*|\s*(?=\,|-))', '', ' '.join(line.replace(';', '').split()))
for line in script_data]
self.script_exist(cfg_file, script_data)
## Generate.
gen_instance = process.generate(self.parameters, theme_name)
## Packing.
process.packing(gen_instance, theme_name, comment)
## ___________________________________
##| X11 cursors conversion functions |---------------------------------------------------------------------------------------------------------------------
##|___________________________________|
##
class X11Cur(object):
def __init__(self, parameters):
self.parameters = parameters
self.logger = logging.getLogger('Metamorphosis')
def path_output(self):
""" Defines output file path. """
try:
custom_output = os.path.join(process.outputcurs_dir, self.parameters['custom'])
os.makedirs(custom_output, exist_ok = True)
return custom_output
except:
return process.outputcurs_dir
def theme_file(self, theme_name, description):
""" Creates "index.theme" file. """
description = re.sub(r'[^\x20-\x7e]', '', description)
themefile = "[Icon Theme]\n" + \
"Name={}\n".format(theme_name) + \
"Comment={}\n-{}\n".format(description, label) + \
"Example=default\n" + \
"Inherits=core"
with open(os.path.join(process.output_dir, 'index.theme'), 'w') as file:
file.write(themefile)
with open(os.path.join(process.output_dir, 'cursor.theme'), 'w') as file:
file.write(themefile)
def convert(self):
""" Creates `X11` cursors, using `xcursorgen` or byte-by-byte writer. """
self.logger.info('\n<------>< `X11` files creation ><------>\n')
## Get elements from cursor namemap.
outfilename, links = cursor_namemap[self.parameters['index']][2 : 4]
## Manage pressed cursors.
## for CursorFX / CursorXP --> CURSOR_STATUS_NORMAL = 1, CURSOR_STATUS_PRESSED = 2
if self.parameters['status'] == 2:
outfilename += '_pressed'
links = []
## Try `xcursorgen` job.
path_cfg = ' "' + process.config(self.parameters) + '"'
path_outcurs = ' "' + os.path.join(self.path_output(), outfilename) + '"'
proc = Popen('xcursorgen' + path_cfg + path_outcurs, shell = True, stdout = PIPE, stderr = PIPE)
out, err = proc.communicate()
code = proc.wait()
if code != 0:
err = ''.join(out.decode('ascii').splitlines())
if err == '':
err = '`xcursorgen` not installed or `xcursorgen` process trouble\n'
self.logger.error("Error: can't convert cursor #{:d} by `xcursorgen` --> {}".format(self.parameters['index'], err))
else:
ok = True
for link in links:
while True:
path = os.path.join(self.path_output(), link)
try:
os.symlink(outfilename, path)
break
except FileExistsError:
os.remove(path)
except:
self.logger.error('Error: failed creating symlink: "{}" --> "{}"\n'.format(outfilename, link))
ok = False
break
if ok:
self.logger.info('X11 cursor "{}" and symlinks ----> Done !!\n'.format(outfilename))
def pack(self, theme_name, description):
""" Packages `X11` theme. """
self.theme_file(theme_name, description)
## Create archive.
path_archive = ' "' + os.path.join(process.options['output'], "{}.tar.gz".format(theme_name)) + '"'
path_where = ' "{}" "{}"'.format(process.targets_dir, theme_name)
proc = Popen('tar -a -cf' + path_archive + ' -C' + path_where , shell = True, stdout = PIPE, stderr = PIPE)
out, err = proc.communicate()
code = proc.wait()
if code != 0:
err = ''.join(out.decode('ascii').splitlines())
if err == '':
err = '`tar` not installed or `tar` process trouble\n'
self.logger.error('Error: "{}" packaging skipped --> {}'.format(theme_name, err))
## _________________________________
##| MS `.cur` conversion functions |------------------------------------------------------------------------------------------------------------------------
##|_________________________________|
##
class MSCur(object):
def __init__(self, parameters):
self.parameters = parameters
self.logger = logging.getLogger('Metamorphosis')
def natural(self, string):
""" Natural sorting function. """
return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string)]
def convert(self):
""" Executes Iconolatry for `.png`s to `.cur`s conversion. """
self.logger.info('\n<------>< Microsoft `.cur` files creation ><------>')
pngs = [[os.path.join(process.original_dir, png)] for png in os.listdir(process.original_dir)
if "_" in png and re.search('img(.*)-(.*)_', png).groups() == (str(self.parameters['index']), str(self.parameters['status']))]
lung = len(pngs)
self.logger.info('\nConversion to `.cur` of set images index: {}, with status: {}\n'
.format(self.parameters['index'], self.parameters['status']))
encocur = Iconolatry.Encode(pngs,
paths_icocur = [process.icocur_dir] * lung,
names_icocur = [''] * lung,
formats_icocur = [('.cur', self.parameters['hotx'], self.parameters['hoty'])] * lung)
keys = sorted(encocur.all_icocur_written.keys(), key = self.natural)
sorted_encocur = OrderedDict((k, encocur.all_icocur_written[k]) for k in keys)
first = list(sorted_encocur.values())[0][0]
self.logger.info('\tMode: {} \n\tDepth: {}\n\tImage size: {}\n\tHotspot position: ({}, {})\n'
.format(first['mode'], first['depth'], first['size'], first['hotspot_x'], first['hotspot_y']))
## _________________________________
##| MS `.ani` conversion functions |------------------------------------------------------------------------------------------------------------------------
##|_________________________________|
##
class MSAni(object):
def __init__(self, parameters):
self.parameters = parameters
self.logger = logging.getLogger('Metamorphosis')
def int2byte(self, value, byteorder = 'little', padbytes = 4):
""" Transforms an integer into his hex representation (little or big endian).
Usually padbytes = 1 (8-bit), 2 (16-bit), 4 (32-bit), 8 (64-bit).
"""
lung = (value.bit_length() + 7) // 8
## Add padding, if needs.
pad = padbytes - lung
if pad < 0:
pad = 0
## Create bytes representation.
return value.to_bytes(lung + pad, byteorder = byteorder) or b'\0'
def ms2jiffies(self, value):
""" Converts from ms to jiffies. """
return int(0.5 * ceil(2.0 * (value / (1000 / 60))))
def jiffies2ms(self, value):
""" Converts from jiffies to ms. """
return int(0.5 * ceil(2.0 * (value * (1000 / 60))))
def unique(self, sequence):
""" Finds ordered unique values. """
seen = set()
seen_add = seen.add
return [x for x in sequence if not (x in seen or seen_add(x))]
def even(self, string):
""" Makes even a byte string. """
bytes_string = bytes(string, 'utf-8')
if len(bytes_string) % 2 != 0:
bytes_string += b'*'
return bytes_string
def pack(self, theme_name, description):
""" Packages `.ani` theme. """
## Create file `.inf`.
self.inf_file(theme_name, description)
## Do package.
make_archive(os.path.join(process.options['output'], theme_name), 'zip',
root_dir = process.output_dir,
base_dir = None)
def inf_file(self, theme_name, description):
""" Creates `.inf` file for Windows installation. """
scheme_reg = ['pointer', 'help', 'work', 'busy', 'cross',
'text', 'hand', 'unavailiable', 'vert', 'horz',
'dgn1', 'dgn2', 'move', 'alternate', 'link']
scheme_cur = [value[1] for key, value in cursor_namemap.items() if key in list(range(9)) + list(range(10,17,2)) + list(range(17,19))]
string_cur = ''
align = len(max(scheme_reg, key = len))
for reg, cur in zip(scheme_reg, scheme_cur):
string_cur += '{:<{align}} = "{}.ani"\n'.format(reg, cur, align = align)
scheme_inf = '; "{}" cursors pack installation file\n'.format(theme_name) + \
'; {}\n; {}\n'.format(description, label) + \
'; Right click on the file "Install.inf" and select "Install". Then in the Mouse control panel apply set cursors.' + '\n\n' + \
"[Version]\n" + "signature=""$CHICAGO$""" + '\n\n' + \
"[DefaultInstall]\n" + "CopyFiles = Scheme.Cur, Scheme.Txt\n" + \
"AddReg = Scheme.Reg" + '\n\n' + \
"[DestinationDirs]\n" + 'Scheme.Cur = 10,"%CUR_DIR%"\n' + \
'Scheme.Txt = 10,"%CUR_DIR%"' + '\n\n'+ \
"[Scheme.Reg]\n" + 'HKCU,"Control Panel\\Cursors\\Schemes","%SCHEME_NAME%",,"' + \
','.join('%10%\\%CUR_DIR%\\%{}%'.format(reg) for reg in scheme_reg) + '\n\n' + \
"; --Common Information\n\n" + \
"[Scheme.Cur]\n" + '\n'.join('{}.ani'.format(cur) for cur in scheme_cur) + '\n\n' + \
"[Scheme.Txt]" + '\n\n' + \
"[Strings]\n" + '{:<{align}} = "Cursors\\{}"\n'.format('CUR_DIR', theme_name, align = align) + \
'{:<{align}} = "{}"\n'.format('SCHEME_NAME', theme_name, align = align) + \
'{}'.format(string_cur)
with open(os.path.join(process.output_dir, 'Install.inf'), 'w') as file:
file.write(scheme_inf)
def find_value(self, data, position):
""" Gets chunk values. """
offset, = unpack_from('<H', data[position + 4 : position + 8])
value = data[position + 8 : position + 8 + offset]
return value
def find_chunk(self, data, name_chunk):
""" Finds chunk. """
try:
pos_chunk = re.search(name_chunk, data).start()
chunk = self.find_value(data, pos_chunk)
except AttributeError:
chunk = None
return chunk
def find_inam_iart(self, data):
""" Finds 'INAM' and 'IART' chunks values. """
inam = self.find_chunk(data, b'INAM')
iart = self.find_chunk(data, b'IART')
inam = (inam.decode('utf-8') if inam else '')
iart = (iart.decode('utf-8') if iart else '')
return inam, iart
def find_rate_seq(self, data):
""" Finds 'rate' and 'seq ' chunks values. """
rate = self.find_chunk(data, b'rate')
seq = self.find_chunk(data, b'seq ')
seq = ([unpack_from('<L', seq[i : i + 4])[0] for i in range(0, len(seq), 4)] if seq else [])
rate = ([self.jiffies2ms(unpack_from('<L', rate[i : i + 4])[0]) for i in range(0, len(rate), 4)] if rate else [])
return rate, seq
def convert(self, resized, theme_name):
""" Writes `.ani` cursor byte-to-byte. """
self.logger.info('<------>< Microsoft `.ani` file creation ><------>\n')
## Get parameters from config file.
with open(process.config(self.parameters), 'r') as cfg_file:
cfg_data = cfg_file.readlines()
cfg_data = [line.replace('\n', '') for line in cfg_data]
## Define global data for 'anih'.
anih_size, cb_size = (self.int2byte(36) for _ in range(2))
stored_as_cur = True
if stored_as_cur:
# these fields contain zeroes if the images are
# stored in icon or cursor resources.
iwidth, iheight, ibitcount, nplanes = (self.int2byte(0) for _ in range(4))
else:
# these fields contain non-zero values if images are
# stored as raw bitmaps.
iwidth = self.int2byte(resized[0])
iheight = self.int2byte(resized[1])
ibitcount = self.int2byte(32)
nplanes = self.int2byte(1)