-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgeosLib.py
2250 lines (1900 loc) · 66.7 KB
/
geosLib.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
# -*- coding: utf-8 -*-
import sys
import os
import datetime
import struct
import zipfile
import gzip
import unicodedata
import PIL
import PIL.Image
import PIL.ImageDraw
import pprint
pp = pprint.pprint
import pdb
kwdbg = 0
kwlog = 1
import time
#
# constants
#
# unused and incomplete (yet)
# intention is to use it with rtf & html conversion
#
# for IDs look here https://www.lyonlabs.org/commodore/onrequest/geos/geoFont.pdf
#
# mappings by github user gitjeff2
fontmapping = {
# geosfontid -> (geos font name, real world font name ;-)
0: ('BSW', 'Geneva'),
1: ('University', ''),
2: ('California', 'Helvetica'),
3: ('Roma', 'Times'),
4: ('Dwinelle', 'Old English'),
5: ('Cory', 'Data 70'),
6: ('Tolman', 'Comic Sans'),
7: ('Bubble', ''),
8: ('Fontknox', ''),
9: ('Harmon', 'Courier'),
10: ('Mykonos', ''),
11: ('Boalt', ''),
12: ('Stadium', ''),
14: ('Evans', ''),
13: ('Tilden', ''),
15: ('Durant', ''),
16: ('Telegraph', ''),
17: ('Superb', 'Broadway'),
18: ('Bowditch', 'Palatino'),
19: ('Ormond', 'Microgramma Extended'),
20: ('Elmwood', ''),
21: ('Hearst', ''),
21: ('Brennens (BUG)', ''),
23: ('Channing', ''),
24: ('Putnam', ''),
25: ('LeConte', 'Chicago'),
52: ('Callaghan', 'Stencil'),
866: ('Lewis', 'Playbill'),
# the following need a font id
# xx:('Barrows', 'Courier'),
# xx:('Birge', 'Mistral'),
# xx:('Lewis', 'Playbill'),
# xx:('Oxford', 'Monotype Tektura'),
}
c64colors = {
0: (0,0,0),
1: (255,255,255),
2: (0x88,0,0),
3: (0xaa,0xff,0xee),
4: (0xcc,0x44,0xcc),
5: (0x00,0xcc,0x55),
6: (0x00,0x00,0xaa),
7: (0xee,0xee,0x77),
8: (0xdd,0x88,0x55),
9: (0x66,0x44,0x00),
10: (0xff,0x77,0x77),
11: (0x33,0x33,0x33),
12: (0x77,0x77,0x77),
13: (0xaa,0xff,0x66),
14: (0x00,0x88,0xff),
15: (0xbb,0xbb,0xbb)}
geosFileTypes = {
0: 'Non-GEOS file',
1: 'BASIC Program',
2: 'Assembly program',
3: 'Data file',
4: 'System file',
5: 'Desk Accessory',
6: 'Application',
7: 'Application Data',
8: 'Font file',
9: 'Printer driver',
10: 'Input driver',
11: 'Disk Device',
12: 'System Boot file',
13: 'Temporary',
14: 'Auto Executing',
15: 'Input 128'}
filetypesWithAuthor = (
1, 2, 4, 5, 6, 9, 10, 14, 15)
programTypes = (
1, 2, 4, 5, 6, 9, 10, 11, 12, 14, 15)
dosFileTypes = {
0: 'DEL',
1: 'SEQ',
2: 'PRG',
3: 'USR',
4: 'REL',
5: 'CBM'}
fourtyEightyFlags = {
0: "GEOS 64/128 40 columns",
64: "GEOS 64/128 40/80 columns",
128: "GEOS 64 40 columns",
192: "GEOS 128 80 columns"}
# a lot of names are surrounded by this
stripchars = ''.join( (chr(0),chr(0xa0)) )
#
# disk image constants
#
# drive geometries
sectorTables = {
'.d64': (
( 0, 0, 0),
( 1, 17, 21),
(18, 24, 19),
(25, 30, 18),
(31, 35, 17)),
'.d71': (
( 0, 0, 0),
# side 1
( 1, 17, 21),
(18, 24, 19),
(25, 30, 18),
(31, 35, 17),
# side 2
(36, 52, 21),
(53, 59, 19),
(60, 65, 18),
(66, 70, 17)),
'.d81': (
( 0, 0, 0),
# side 1
( 1, 40, 40),
# side 2
(41, 80, 40))
}
minMaxTrack = {
'.d81': (1,80),
'.d71': (1,70),
'.d64': (1,35)}
extToImagesize = {
# ext, filesize, sector count
'.d64': ((174848, 683),),
'.d81': ((819200, 3200),),
'.d71': ((349696, 1366),
(349696+1366, 1366)) }
imagesizeToExt = {
# filesize, ext, sector count
174848: ( '.d64', 683),
175531: ( '.d64', 683),
819200: ( '.d81', 3200),
349696: ( '.d71', 1366),
351062: ( '.d71', 1366)}
dirSectorsForDrives = {
'.d64': (18, 0),
'.d71': (18, 0),
'.d81': (40, 0)}
# TO DO: .D71
dirSectorStructures = {
# the first entry is the struct unpack string
# the second entry are names to be attached in a dict
'.d64': ("<b b c c 140s 16s 2x 2s x 2s 4x b b 11s 5s 67x",
"tr sc format dosv1 bam dnam diskid dosv2 dsktr dsksc geoformat geoversion"),
'.d81': ("<b b cx 16s 2x 2s x 2s 2x 3x 96s 16x 16s 2x 9x b b 11s 5s 3x 64x",
"tr sc fmt dnam dskid dosv power64 geoname dsktr dsksc geoformat geoversion")}
#
# some image globals
#
# it seems the "official" geoColorChoice is:
# fg: color0
# bg: color15
bgcol = c64colors[15]
if kwdbg:
bgcol = c64colors[14]
#
# create color and bw "empty" image bands for the empty records in a geoPaint file
#
# color
bytes = [ chr(bgcol[0]),chr(bgcol[1]),chr(bgcol[2]) ] * (640*16)
bytes = ''.join( bytes )
coldummy = PIL.Image.frombytes('RGB', (640,16), bytes, decoder_name='raw')
# bw
bytes = [ chr(255) ] * 1280
bytes = ''.join( bytes )
bwdummy = PIL.Image.frombytes('1', (640,16), bytes, decoder_name='raw')
# currently accepted GEOS file types for conversion; fonts have their own file type
acceptedTypes = (
'Paint Image V1.0',
'Paint Image V1.1',
'Paint Image v1.1',
'photo album V1.0',
'photo album V2.1',
'Photo Scrap V1.0',
'Photo Scrap V1.1',
'Write Image V1.0',
'Write Image V1.1',
'Write Image V2.0',
'Write Image V2.1',
'text album V1.0',
'text album V2.1',
'Text Scrap V1.0',
'Text Scrap V1.1',
'Text Scrap V2.0')
# all the GEOS text file types
textTypes = (
'Write Image V1.0',
'Write Image V1.1',
'Write Image V2.0',
'Write Image V2.1',
'text album V1.0',
'text album V2.1',
'Text Scrap V1.0',
'Text Scrap V1.1',
'Text Scrap V2.0')
imageTypes = (
'Paint Image V1.0',
'Paint Image V1.1',
'Paint Image v1.1',
'photo album V1.0',
'photo album V2.1',
'Photo Scrap V1.0',
'Photo Scrap V1.1')
geoWriteVersions = {
'Write Image V1.0': 10,
'Write Image V1.1': 11,
'Write Image V2.0': 20,
'Write Image V2.1': 21}
albumWithNameTypes = (
'photo album V2.1',
'text album V2.1')
#
# tools
#
def datestring(dt = None, dateonly=False, nospaces=False):
if not dt:
now = str(datetime.datetime.now())
else:
now = str(dt)
if not dateonly:
now = now[:19]
else:
now = now[:10]
if nospaces:
now = now.replace(" ", "_")
return now
def makeunicode( s, enc="utf-8", normalizer='NFC'):
try:
if type(s) != unicode:
s = unicode(s, enc)
except:
pass
s = unicodedata.normalize(normalizer, s)
return s
def iterateFolders( infolder, validExtensions=('.d64', '.d71', '.d81',
'.zip', '.gz', '.cvt',
'.prg', '.seq') ):
"""Iterator that walks a folder and returns all files."""
# for folder in dirs:
lastfolder = ""
for root, dirs, files in os.walk( infolder ):
root = makeunicode( root )
result = {}
pathlist = []
for thefile in files:
thefile = makeunicode( thefile )
basename, ext = os.path.splitext(thefile)
typ = ext.lower()
if thefile.startswith('.'):
continue
filepath = os.path.join( root, thefile )
dummy, folder = os.path.split( root )
if kwdbg or 1:
if root != lastfolder:
lastfolder = root
print
print "FOLDER:", repr( root )
filepath = makeunicode( filepath )
if typ not in validExtensions:
# check for cvt file by scanning
f = open(filepath, 'rb')
data = f.read(4096)
f.close()
format = data[0x1e:0x3a]
formatOK = False
if format.startswith("PRG formatted GEOS file"):
formatOK = True
elif format.startswith("SEQ formatted GEOS file"):
broken = True
if not formatOK:
continue
typ = '.cvt'
if kwlog or 1:
print "FILE:", repr(filepath)
yield typ, filepath
def getCompressedFile( path, acceptedOnly=False ):
"""Open a gzip or zip compressed file. Return the GEOS and c64 files in
contained disk image(s)
"""
result = {}
# limit size of files to 10MB
# use a size limit?
if 0: #s.st_size > 10*2**20:
s = os.stat( path )
return result
folder, filename = os.path.split( path )
basename, ext = os.path.splitext( filename )
if ext.lower() == '.gz':
f = gzip.open(path, 'rb')
foldername = basename + '_gz'
result[foldername] = []
file_content = f.read()
f.close()
# only return those streams that have a chance of being an image
if len(file_content) in imagesizeToExt:
di = DiskImage( stream=file_content, tag=path )
if acceptedOnly:
for u in di.files:
if u.header.className in acceptedTypes:
result[foldername].append( u )
else:
result[foldername].extend(di.files)
return result
elif ext.lower() == '.zip':
foldername = basename + '_zip'
try:
handle = zipfile.ZipFile(path, 'r')
files = handle.infolist()
except Exception, err:
print "ZIP ERROR", err
return result
for zf in files:
print "ZIPFILE:", repr( zf.filename )
try:
h = handle.open(zf)
data = h.read()
except Exception, err:
continue
if len(data) in imagesizeToExt:
zfoldername = '/'.join( (foldername, zf.filename) )
result[zfoldername] = []
# pdb.set_trace()
di = DiskImage( stream=data, tag=path )
if acceptedOnly:
for u in di.files:
if u.header.className in acceptedTypes:
result[zfoldername].append( u )
else:
result[zfoldername].extend( di.files )
return result
return result
class ImageBuffer(list):
"""For debugging purposes mostly. Has a built in memory dump in
monitor format."""
def __init__(self):
super(ImageBuffer, self).__init__()
def dump(self):
hexdump( self )
def hexdump( s, col=32 ):
"""Using this for debugging was so memory lane..."""
cols = {
8: ( 7, 0xfffffff8),
16: (15, 0xfffffff0),
32: (31, 0xffffffe0),
64: (63, 0xffffffc0)}
if not col in cols:
col = 16
minorMask, majorMask = cols.get(col)
d = False
mask = col-1
if type(s) in( list, tuple): #ImageBuffer):
d = True
for i,c in enumerate(s):
if d:
t = hex(c)[2:]
else:
t = hex(ord(c))[2:]
t = t.rjust(2, '0')
# spit out address
if i % col == 0:
a = hex(i)[2:]
a = a.rjust(4,'0')
sys.stdout.write(a+': ')
sys.stdout.write(t+' ')
# spit out ascii line
if i & minorMask == minorMask:
offs = i & majorMask
for j in range(col):
c2 = s[offs+j]
d2 = ord(c2)
if 32 <= d2 < 127:
sys.stdout.write( c2 )
else:
sys.stdout.write( '.' )
sys.stdout.write('\n')
def getAlbumNamesChain( vlir ):
"""extract clip names for (Photo|Text) Album V2.x"""
clipnames = [ "" ] * 127
clipnameschain = 256
if vlir.header.className in ("photo album V2.1", "text album V2.1"):
# scan for last chain
if (0,0) in vlir.chains:
clipnameschain = vlir.chains.index( (0,0) ) - 1
if clipnameschain < 2:
return 256, clipnames
clipnamesstream = vlir.chains[clipnameschain]
if len( clipnamesstream ) < 17:
return 256, clipnames
noofentries = ord(clipnamesstream[0])
if len(clipnamesstream) != (noofentries + 1) * 17 + 1:
if kwlog:
print "len(clipnamesstream)", len(clipnamesstream)
print "(noofentries + 1) * 17 + 1", (noofentries + 1) * 17 + 1
#if kwdbg:
# pdb.set_trace()
# print
return 256, clipnames
for i in range(noofentries):
base = 1 + i*17
namebytes = clipnamesstream[base:base+16]
namebytes = namebytes.replace( chr(0x00), "" )
namebytes = namebytes.replace( '/', "-" )
namebytes = namebytes.replace( ':', "_" )
try:
clipnames[i] = namebytes
except IndexError, err:
print
print err
# pdb.set_trace()
print
return clipnameschain, clipnames
#
# file tools
#
#
# geos image conversion
#
def expandImageStream( s ):
"""Expand a 640x16 compressed image stream as encountered in geoPaint files."""
n = len(s)
j = -1
image = ImageBuffer()
log = []
while j < n-1:
j += 1
code = ord(s[j])
items = []
roomleft = (n-1) - j
if 0: #code == 0:
break
if code in (64, 128):
if kwdbg:
print "blank code 64,128 encountered."
#pdb.set_trace()
continue
if code < 64:
if roomleft < 1:
j += 1
continue
data = s[j+1:j+code+1]
for i in data:
items.append( ord(i) )
j += len(data)
image.extend( items )
continue
elif 64 <= code < 128:
if roomleft < 8:
j += 8
continue
c = code & 63
pattern = s[j+1:j+9]
pn = len(pattern)
cnt = pn * c
for i in range(c):
for k in range(pn):
p = pattern[k]
items.append( ord(p) )
j += pn
image.extend( items )
continue
elif 128 <= code:
if roomleft < 1:
j += 1
continue
c = code - 128
data = ord(s[j+1])
t = [data] * c
items = t
image.extend( items )
j += 1
continue
if kwdbg:
log.append( items )
return image
def expandScrapStream( s ):
"""Expand a variable compressed image stream as encountered in 'Photo Album',
'Photo Scrap' and geoWrite files."""
n = len(s)
j = -1
image = []
while j < n-1:
j += 1
code = ord(s[j])
roomleft = (n-1) - j
if code in (0,128,220):
if kwdbg:
print "ILLEGAL OPCODES..."
# pdb.set_trace()
print
continue
elif code < 128:
if roomleft < 1:
j += 1
continue
data = ord(s[j+1])
t = [data] * code
image.extend( t )
j += 1
continue
elif 128 <= code <= 219:
c = code - 128
if roomleft < c:
j += c
continue
data = s[j+1:j+c+1]
for i in data:
image.append( ord(i) )
j += c
continue
else:
# 220...255
patsize = code -220
if roomleft < patsize+1:
j += patsize+1
continue
repeat = ord(s[j+1])
size = repeat * patsize
pattern = s[j+2:j+2+patsize]
for i in range( repeat ):
for p in pattern:
image.append( ord(p) )
j += patsize+1
continue
return image
def photoScrap( s ):
"""Convert binary scrap format data into a BW and a COLOR PNG."""
# empty record
if s in ( None, (0,255), (0,0)):
return False, False
if len(s) < 3:
return False, False
cardsw = ord(s[0])
w = cardsw * 8
h = ord(s[2]) * 256 + ord(s[1])
if w == 0 or h == 0:
return False, False
elif w > 4096 or h > 4096:
return False, False
cardsh = h >> 3
image = expandScrapStream(s[3:])
if image:
return imageband2PNG( image, cardsw, h, 0 )
return False, False
def geoPaintBand( s ):
if s in ( None, (0,255), (0,0)):
return False, False
cardsw = 80
cardsh = 2
image = expandImageStream(s)
col, bw = imageband2PNG( image, cardsw, cardsh*8, 1 )
if kwdbg and 0:
col.save("lastband_col.png")
bw.save("lastband_bw.png")
return col, bw
def imageband2PNG( image, cardsw, h, isGeoPaint):
"""Convert a list of expanded image bytes into a PNG. Due to my
misunderstanding the formats, the last parameter was necessary.
geoPaint and scrap format differ huge in how the image is stored
and this should have been handled in expandXXXStream().
See the 'if isGeoPaint:' part.
"""
cardsh = h >> 3
if h & 7 != 0:
cardsh += 1
w = cardsw * 8
# h = cardsh * 8
eightZeroBytes = [0] * 8
noofcards = cardsw * cardsh
noofbytes = noofcards * 8
noofcolorbands = cardsh
# holds a list of card colors; one list per row
colorbands = []
# check sizes
n = len(image)
bitmapsize = cardsw * h
colormapsize = noofcards
gap = 8
expectedSize = bitmapsize + gap + colormapsize
# repair section
if n < bitmapsize:
# actual bits missing
# fill with 0
# one colored image
if kwdbg:
#pdb.set_trace()
print "BITMAP BITS MISSING", bitmapsize - n
# fill bitmap up
image.extend( [0] * (bitmapsize - n) )
# add gap
image.extend( eightZeroBytes )
# add color map
image.extend( [191] * colormapsize )
n = len(image)
elif n == bitmapsize:
# one colored image
if kwdbg:
print "ONLY BITMAP BITS"
# add gap
image.extend( eightZeroBytes )
# add color map
image.extend( [191] * colormapsize )
n = len(image)
elif n == bitmapsize + colormapsize:
# colored image not created by geoPaint (I guess)
if kwdbg:
#pdb.set_trace()
print "COLOR GAP MISSING"
i0 = image[:bitmapsize]
c0 = image[bitmapsize:]
image = []
image.extend( i0 )
image.extend( eightZeroBytes )
image.extend( c0 )
n = len(image)
elif n == expectedSize:
# should be all ok and parts sitting where they're expected to be
pass
else:
# TBD
# Here is still work todo
#
# It's difficult to estimate what's here and what's missing.
if n > expectedSize:
i0 = image[:bitmapsize]
c0 = image[-colormapsize:]
legap = image[bitmapsize:-colormapsize]
#pdb.set_trace()
#hexdump( legap )
image = []
image.extend( i0 )
image.extend( [0] * 8 )
image.extend( c0 )
n = len(image)
else:
if kwlog or 1:
print
print "UNUSUAL SIZE!!"
print "cardsw, cardsh", cardsw, cardsh
print "cardsw * cardsh", cardsw * cardsh
print "n", n
print "expectedSize", expectedSize
#if kwdbg and 0:
# pdb.set_trace()
print
# extract color data
offset = cardsw * h + 8
for row in range(cardsh):
base = offset + row * cardsw
end = base + cardsw
band = image[base:end]
if len(band) < cardsw:
if kwdbg:
print "color band extend", (cardsw -len(band))
band.extend( [191] * (cardsw -len(band)) )
colorbands.append( band )
# bring the image bytes into the right order
if isGeoPaint:
# this is only for geoPaint files
bytes = [ chr(0) ] * noofbytes
ROWS = cardsh
COLS = cardsw
BYTESPERCARD = 8
BYTESPERROW = COLS * BYTESPERCARD
idx = -1
for row in range(ROWS):
for col in range(COLS):
for byte in range(BYTESPERCARD):
idx += 1
src = 0 + (BYTESPERROW * row) + col * BYTESPERCARD + byte
# 0-15
base = row * BYTESPERCARD
dst = base * 80 + byte * 80 + col
# dst = base * cardsw + byte * cardsw + col
try:
byte = image[idx]
except IndexError:
byte = 0
if dst >= noofbytes:
#pdb.set_trace()
print row
print col
print byte
print row * BYTESPERCARD
bytes[dst] = byte
else:
# scraps are easy
bytes = image[:]
# separate
colbytes = [chr(i) for i in bytes]
# invert bw bitmap
# looks better most of the cases
bwbytes = [chr(i ^ 255) for i in bytes]
# for the bitmap image
bwbytes = ''.join( bwbytes )
try:
bwimg = PIL.Image.frombytes('1', (w,h), bwbytes, decoder_name='raw')
except Exception, err:
print
print err
# pdb.set_trace()
return None, None
# a bw source for the color image; cards get copied in bw mode
colbytes = ''.join(colbytes)
colsource = PIL.Image.frombytes('1', (w,h), colbytes, decoder_name='raw')
# new image
colimg = PIL.Image.new('RGB', (w,h), (1,1,1))
for row in range(cardsh):
# create the color image by
# 1. painting background color 8x8 cards (draw.rectangle below)
# 2. drawing the cards foreground data in bw with fg coloring (draw.bitmap)
base = row * cardsw
for col in range(cardsw):
idx = base + col
color = colorbands[row][col]
bgi = color & 15
bg = c64colors[bgi]
fgi = (color >> 4) & 15
fg = c64colors[fgi]
draw = PIL.ImageDraw.Draw( colimg )
# get coordinates for copy/paste
x = col * 8
y = row * 8
# fill the card with background color
draw.rectangle( (x,y,x+8,y+8), fill=bg)
# copy the bitmap data
bwcard = colsource.crop( (x,y,x+8,y+8) )
bwcard.load()
card = bwcard.copy()
# paste the bw bitmap into a color imaga, coloring the card
draw.bitmap( (x,y), card, fill=fg)
return (colimg, bwimg)
def convertGeoPaintFile( vlir, folder ):
# gpf, gdh
outnamebase = vlir.dirEntry.fileName
outnamebase = outnamebase.replace(":", "_")
outnamebase = outnamebase.replace("/", "_")
print repr(outnamebase)
colimg = PIL.Image.new('RGB', (80*8,90*8), 1)
bwimg = PIL.Image.new('1', (80*8,90*8), 1)
# pdb.set_trace()
for i,chain in enumerate(vlir.chains):
if chain == (0,0):
break
# if chain == (0,255):
if type(chain) in (list, tuple):
#print "EMPTY BAND!"
col, bw = coldummy.copy(), bwdummy.copy()
else:
col, bw = geoPaintBand( chain )
if not col:
# print "NO BAND!"
col = coldummy.copy()
colimg.paste( col, (0,i*16,640,(i+1)*16))
if not bw:
bw = bwdummy.copy()
bwimg.paste( bw, (0,i*16,640,(i+1)*16))
if not os.path.exists( folder ):
os.makedirs( folder )
outfilecol = os.path.join( folder, outnamebase + "_col.png" )
outfilebw = os.path.join( folder, outnamebase + "_bw.png" )
if not os.path.exists( outfilecol ):
colimg.save(outfilecol)
if not os.path.exists( outfilebw ):
bwimg.save(outfilebw)
def convertPhotoAlbumFile( vlir, folder ):
# f, gpf
outnamebase = vlir.dirEntry.fileName
outnamebase = outnamebase.replace(":", "_")
outnamebase = outnamebase.replace("/", "_")
# folder = gpf.folder
print repr(outnamebase)
classname = vlir.header.className
clipnameschain = -1
clipnames = [ "" ] * 127
if classname in albumWithNameTypes:
clipnameschain, clipnames = getAlbumNamesChain( vlir )
for i,chain in enumerate(vlir.chains):
if chain in ((0,0), (0,255), None, False):
continue
if classname in albumWithNameTypes and i == clipnameschain:
# names record
continue
col, bw = photoScrap( chain )
clipname = ""
if clipnames[i]:
clipname = '-"' + clipnames[i] + '"'
if col:
if not os.path.exists( folder ):
os.makedirs( folder )
filename = (outnamebase
+ '-' + str(i+1).rjust(3,'0')
+ clipname + "_col.png")
filename = filename.replace('/', '_')
of = os.path.join( folder, filename )
if not os.path.exists( of ):
col.save( of )
else:
print "No color image for vlir: %i" % i
if bw:
if not os.path.exists( folder ):
os.makedirs( folder )
filename = (outnamebase
+ '-' + str(i+1).rjust(3,'0')
+ clipname + "_bw.png")
filename = filename.replace('/', '_')
of = os.path.join( folder, filename )
if not os.path.exists( of ):
bw.save( of )
else:
print "No bw image for vlir: %i" % i
def convertPhotoScrapFile( vlir, folder):
outnamebase = vlir.dirEntry.fileName
outnamebase = outnamebase.replace(":", "_")
outnamebase = outnamebase.replace("/", "_")
# folder = gpf.folder
print repr(outnamebase)
for i,chain in enumerate(vlir.chains):
if chain == (0,0):
break
if chain == (0,255):
continue
col, bw = photoScrap( chain )