-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgeoslib.leo
More file actions
3393 lines (2810 loc) · 100 KB
/
geoslib.leo
File metadata and controls
3393 lines (2810 loc) · 100 KB
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
<?xml version="1.0" encoding="utf-8"?>
<!-- Created by Leo: http://leoeditor.com/leo_toc.html -->
<leo_file xmlns:leo="http://leoeditor.com/namespaces/leo-python-editor/1.1" >
<leo_header file_format="2" tnodes="0" max_tnode_index="0" clone_windows="0"/>
<globals body_outline_ratio="0.5" body_secondary_ratio="0.5">
<global_window_position top="50" left="50" height="500" width="700"/>
<global_log_window_position top="0" left="0" height="0" width="0"/>
</globals>
<preferences/>
<find_panel_settings/>
<vnodes>
<v t="karstenw.20220612162505.2" a="E"><vh>NewHeadline</vh>
<v t="karstenw.20220612162552.1" a="E"><vh>@clean geosLib.py</vh>
<v t="karstenw.20220612162656.1"><vh>Declarations</vh></v>
<v t="karstenw.20220612162816.1"><vh>Python3 stuff</vh></v>
<v t="karstenw.20220612162841.1" a="E"><vh>+ CONSTANTS +</vh>
<v t="karstenw.20260331132823.1"><vh>+ FONT +</vh></v>
<v t="karstenw.20260331132859.1"><vh>+ FILE TYPES +</vh></v>
<v t="karstenw.20260331132946.1"><vh>+ DRIVE +</vh></v>
<v t="karstenw.20260331133043.1"><vh>+ COLORS +</vh></v>
<v t="karstenw.20260402132956.1"><vh>+ IMAGE +</vh></v>
</v>
<v t="karstenw.20220612162656.2"><vh>makeFilledPILImage</vh></v>
<v t="karstenw.20230112142409.1" a="E"><vh>+ TOOLS +</vh>
<v t="karstenw.20220612162656.3"><vh>datestring</vh></v>
<v t="karstenw.20220612162656.4"><vh>makeunicode</vh></v>
<v t="karstenw.20220612162656.5"><vh>iterateFolders</vh></v>
<v t="karstenw.20220612162656.6"><vh>getCompressedFile</vh></v>
<v t="karstenw.20220612162656.10"><vh>hexdump</vh></v>
<v t="karstenw.20220612162656.37"><vh>cleanupString</vh></v>
<v t="karstenw.20220612162656.7"><vh>class ImageBuffer</vh>
<v t="karstenw.20220612162656.8"><vh>__init__</vh></v>
<v t="karstenw.20220612162656.9"><vh>dump</vh></v>
</v>
</v>
<v t="karstenw.20230112142616.1" a="E"><vh>+ GEOS +</vh>
<v t="karstenw.20230112142932.1" a="E"><vh>+ FILE +</vh>
<v t="karstenw.20220612162656.11"><vh>getAlbumNamesChain</vh></v>
</v>
<v t="karstenw.20230112142942.1" a="E"><vh>+ IMAGE +</vh>
<v t="karstenw.20220612162656.12"><vh>expandImageStream</vh></v>
<v t="karstenw.20220612162656.13"><vh>expandScrapStream</vh></v>
<v t="karstenw.20220612162656.14"><vh>photoScrap</vh></v>
<v t="karstenw.20220612162656.15"><vh>geoPaintBand</vh></v>
<v t="karstenw.20220612162656.16"><vh>imageband2PNG</vh></v>
<v t="karstenw.20220612162656.17"><vh>convertGeoPaintFile</vh></v>
<v t="karstenw.20220612162656.18"><vh>convertPhotoAlbumFile</vh></v>
<v t="karstenw.20220612162656.19"><vh>convertPhotoScrapFile</vh></v>
</v>
<v t="karstenw.20260331135902.1"><vh>+ GEOWRITE CONVERSIONS +</vh>
<v t="karstenw.20220612162656.20"><vh>class ItemCollector</vh>
<v t="karstenw.20220612162656.21"><vh>__init__</vh></v>
<v t="karstenw.20220612162656.22"><vh>initDoc</vh></v>
<v t="karstenw.20220612162656.23"><vh>finishDoc</vh></v>
<v t="karstenw.20220612162656.24"><vh>addHTML</vh></v>
<v t="karstenw.20220612162656.25"><vh>addRTF</vh></v>
<v t="karstenw.20220612162656.26"><vh>addTEXT</vh></v>
<v t="karstenw.20220612162656.27"><vh>addImage</vh></v>
<v t="karstenw.20220612162656.28"><vh>addFont</vh></v>
<v t="karstenw.20220612162656.29"><vh>getFontID</vh></v>
<v t="karstenw.20220612162656.30"><vh>rtfFontDict</vh></v>
</v>
<v t="karstenw.20220612162656.31"><vh>getGeoWriteStream</vh></v>
<v t="karstenw.20220612162656.32"><vh>convertWriteImage</vh></v>
</v>
<v t="karstenw.20260331140048.1" a="E"><vh>+ DISK IMAGE +</vh>
<v t="karstenw.20220612162656.33"><vh>class CBMConvertFile</vh>
<v t="karstenw.20220612162656.34"><vh>__init__</vh></v>
</v>
<v t="karstenw.20220612162656.35"><vh>class VLIRFile</vh>
<v t="karstenw.20220612162656.36"><vh>__init__</vh></v>
</v>
<v t="karstenw.20220612162656.38" a="E"><vh>class GEOSHeaderBlock</vh>
<v t="karstenw.20220612162656.39"><vh>__init__</vh></v>
<v t="karstenw.20220612162656.40"><vh>prnt</vh></v>
</v>
<v t="karstenw.20220612162656.41"><vh>class GEOSDirEntry</vh>
<v t="karstenw.20220612162656.42"><vh>__init__</vh></v>
<v t="karstenw.20220612162656.43"><vh>prnt</vh></v>
<v t="karstenw.20220612162656.44"><vh>smallprnt</vh></v>
</v>
<v t="karstenw.20220612162656.45" a="E"><vh>class DiskImage</vh>
<v t="karstenw.20220612162656.46"><vh>getTrackOffsetList</vh></v>
<v t="karstenw.20220612162656.47"><vh>readfile</vh></v>
<v t="karstenw.20220612162656.48"><vh>getTS</vh></v>
<v t="karstenw.20220612162656.49"><vh>getChain</vh></v>
<v t="karstenw.20220612162656.50"><vh>getDirEntries</vh></v>
<v t="karstenw.20220612162656.51"><vh>printDirectory</vh></v>
<v t="karstenw.20220612162656.52"><vh>__init__</vh></v>
</v>
</v>
<v t="karstenw.20260331140104.1" a="E"><vh>+ FONT +</vh>
<v t="karstenw.20220612162656.53"><vh>class FontRecord</vh>
<v t="karstenw.20220612162656.54"><vh>__init__</vh></v>
</v>
<v t="karstenw.20220612162656.55"><vh>getFontChain</vh></v>
<v t="karstenw.20220612162656.56"><vh>convertFontFile</vh></v>
</v>
</v>
</v>
<v t="karstenw.20220612162605.1"><vh>@clean macpaintLib.py</vh>
<v t="karstenw.20220612162654.1"><vh>Declarations</vh></v>
<v t="karstenw.20220612162654.2"><vh>datestring</vh></v>
<v t="karstenw.20220612162654.3"><vh>makeunicode</vh></v>
<v t="karstenw.20220612162654.4"><vh>iterateFolders</vh></v>
<v t="karstenw.20220612162654.5"><vh>getCompressedFile</vh></v>
<v t="karstenw.20220612162654.6"><vh>class ImageBuffer</vh>
<v t="karstenw.20220612162654.7"><vh>__init__</vh></v>
<v t="karstenw.20220612162654.8"><vh>dump</vh></v>
</v>
<v t="karstenw.20220612162654.9"><vh>hexdump</vh></v>
<v t="karstenw.20220612162654.10"><vh>unpackBits</vh></v>
<v t="karstenw.20220612162654.11"><vh>imageband2PNG</vh></v>
</v>
<v t="karstenw.20220612162628.1"><vh>@clean README.md</vh></v>
<v t="karstenw.20220612162635.1"><vh>@clean setup.py</vh>
<v t="karstenw.20220612162652.1"><vh>Declarations</vh></v>
</v>
<v t="karstenw.20260403150017.1" a="E"><vh>examples</vh>
<v t="karstenw.20260403150022.1"><vh>@clean examples/c64ColorsPNG.py</vh>
<v t="karstenw.20260403150108.1"><vh>Declarations</vh></v>
</v>
<v t="karstenw.20260403150244.1" a="E"><vh>@clean examples/geosConvertAll.py</vh>
<v t="karstenw.20260403150255.1"><vh>Declarations</vh></v>
<v t="karstenw.20260403150923.1"><vh>__main__</vh></v>
</v>
</v>
</v>
</vnodes>
<tnodes>
<t tx="karstenw.20220612162505.2"></t>
<t tx="karstenw.20220612162552.1">@language python
@tabwidth -4
@others
</t>
<t tx="karstenw.20220612162605.1">
# -*- coding: utf-8 -*-
@others
if __name__ == '__main__':
for input in sys.argv[1:]:
path = os.path.abspath( os.path.expanduser( input ))
folder, filename = os.path.split( path )
basename, ext = os.path.splitext( filename )
if os.path.isdir( path ):
files = iterateFolders( path )
else:
files = ( (ext.lower(), path), )
for typ,path in files:
f = open(path, 'rb')
s = f.read()
f.close()
# pdb.set_trace()
folder, filename = os.path.split( path )
basename, ext = os.path.splitext( filename )
dest = os.path.abspath( "./macpaintExports/" )
if not os.path.exists( dest ):
os.makedirs( dest )
dest = os.path.join( dest, basename + ".png")
if s.startswith( bytes( (0,0,0,2) ) ): #(chr(0),chr(0),chr(0),chr(2)) ):
s = s[640:]
if typ in (".mac", ".mpnt", ".pnt", ".pntg", ".pic"):
print( path )
image = unpackBits( s )
img = imageband2PNG( image, 72, 720)
img.save( dest )
@language python
@tabwidth -4
</t>
<t tx="karstenw.20220612162628.1">### geosLib
geosLib is a Python library to convert [GEOS](https://www.c64-wiki.de/index.php/GEOS) geoPaint, geoWrite, Photo Album and Photo Scrap files to modern formats.
Image files can be converted to PNG.
Text formats can be converted to RTFD, HTML and TXT.
GEOS font files are rendered as PNG for each size.
### Inspiration, Code Template and "broken CVT logic"
[geowrite2rtf](https://github.com/mist64/geowrite2rtf) by [Michael Steil](http://www.pagetable.com/). If you haven't seen his [c64talk](https://www.youtube.com/watch?v=ZsRRCnque2E), go watch it.
### Requirements
+ [pillow](https://github.com/python-pillow/Pillow)
### Usage:
```shell
# for geoPaint, Photo Album, Photo Scrap, geoWrite, Text Album and Text Scrap in CBM Convert files format (CVT):
python convertCVTFiles.py *.cvt
# for geos font files in any format (d64, d81, zipped, gzipped, cvt):
# the PNG files are written to a directory "./geosFonts"
python geosCollectAllFonts.py files or folders
# to collect everything in directories "./geosExports" and "./geosFonts"
python geosConvertAll.py files or folders
```
### To do:
+ Text Album files
+ Some differences between "Write Image V2.0" and "Write Image V2.1"
+ geoPublish format? If someone has a pointer please write up an issue.
### Summary
+ Send CBM-CVT files to CBMConvertFile and cbm disk image files (.d64, .d81) to DiskImage. Look at geosFiletypeScanner's usage of geosLib.getCompressedFile() on how to handle gzip and zip files.
+ IOW: get your geos file into a VLIRFile structure. The name is misleading since SEQ files go there too. That's what any of the conversion functions in geosLib expect.
### Update
+ Welcome the new addition 'macpaintLib.py'. For the start it will be kept in it's own file but will be integrated after maturing. It uses a lot of common code and is very beta.
+ Currently it converts all but one from all the macpaint files I could find on the net with a speed of ca. 15docs/sec.
+ sources so far:
+ [http://cd.textfiles.com/carousel344/PIC](http://cd.textfiles.com/carousel344/PIC)
+ [http://cd.textfiles.com/vgaspectrum/mac/mac1](http://cd.textfiles.com/vgaspectrum/mac/mac1)
+ [http://cd.textfiles.com/vgaspectrum/mac/mac2](http://cd.textfiles.com/vgaspectrum/mac/mac2)
+ If you find more macpaint files, please create an issue
+ Usage
```
python macpaintLib.py /Path/To/Folder/with/MacPaint/Files/
```
this will create a folder macpaintExports at the same location from where the script is started.
</t>
<t tx="karstenw.20220612162635.1">@others
@language python
@tabwidth -4
</t>
<t tx="karstenw.20220612162652.1">from distutils.core import setup
setup(name='geosLib',
version='1.0',
py_modules=['geosLib'],
)
</t>
<t tx="karstenw.20220612162654.1">import sys
import os
import datetime
import struct
import zipfile
import gzip
import unicodedata
import PIL
import PIL.Image
import PIL.ImageDraw
# import cStringIO
import pprint
pp = pprint.pprint
import pdb
kwdbg = 0
kwlog = 0
import time
#
# constants
#
# to be filled out
quickdraw1Colors = {}
pictPrefix = chr(0) * 512
#
# tools
#
</t>
<t tx="karstenw.20220612162654.10">def unpackBits( s ):
resultBytes = bytearray(0)
# 72 bytes times 720 lines
totalBytes = 72 * 720 #len(resultBytes)
byteIndex = 0
done = False
# check for header
# Before extracting the image data from a MacPaint file in a non-Macintosh
# environment, you must determine if a MacBinary header is prepended. This is best
# done by reading the bytes at offsets 101 through 125 and checking to see if they
# are all zero. The byte at offset 2 should be in the range of 1 to 63, and the DWORDs
# at offsets 83 and 87 should be in the range of 0 to 007FFFFFh. If all of these
# checks are true, then a MacBinary header is present.
# check 1 bytes[101:126] are zero
# check 2 byte[2] in range( 1,63 )
# check 3
s = s[640:]
totalBytes = len( s )
# pdb.set_trace()
def handleOpcode( data, idx ):
op = data[idx]
while ( byteIndex < totalBytes and not done):
try:
c = s[byteIndex]
byteIndex += 1
except Exception as err:
print()
print(err)
print( "1 byteIndex >= totalBytes", byteIndex, totalBytes )
done = True
break
co = c
# print( hex(co) )
if co < 128:
#print( "POSITIVE OPCODE", hex(co) )
debugList = [co]
for i in range( co+1 ):
# c = f.read(1); q = f.tell()
try:
c = s[byteIndex]
byteIndex += 1
except Exception as err:
print()
print(err)
print( "2 byteIndex >= totalBytes", byteIndex, totalBytes )
done = True
break
resultBytes.append( c )
debugList.append( c )
#hexdump( debugList )
else:
#print( "NEGATIVE OPCODE", hex(co) )
debugList = [co]
co -= 256
co = -co
try:
c = s[byteIndex]
byteIndex += 1
except Exception as err:
print()
print(err)
print( "3 byteIndex >= totalBytes", byteIndex, totalBytes )
done = True
break
for i in range(co+1):
resultBytes.append( c )
debugList.append( c )
#hexdump( debugList )
return resultBytes
</t>
<t tx="karstenw.20220612162654.11">
def imageband2PNG( imageBytes, cardsw, h):
"""Convert a list of expanded imageBytes bytes into a PNG.
"""
cardsh = h >> 3
if h & 7 != 0:
cardsh += 1
w = cardsw * 8
noofcards = cardsw * cardsh
noofbytes = cardsw * h
# check sizes
n = len(imageBytes)
expectedSize = noofbytes
# repair section
if n < expectedSize:
# actual bits missing
# fill with 0
if kwlog or 1:
print( "BITMAP BITS MISSING", expectedSize - n )
# fill bitmap up
imageBytes.extend( [0] * (expectedSize - n) )
n = len(imageBytes)
elif n == noofbytes:
# everything's ok
if kwlog:
print( "BITMAP OK" )
elif n > noofbytes:
if kwlog or 1:
print( "BITMAP TOO BIG", n )
imageBytes = imageBytes[:noofbytes]
n = len(imageBytes)
# invert bw bitmap
# looks better most of the cases
bwbytes = [ i ^ 255 for i in imageBytes]
# for the bitmap image
#bwbytes = ''.join( bwbytes )
bwimg = PIL.Image.frombytes('1', (w,h), bytes(bwbytes), decoder_name='raw')
return bwimg
</t>
<t tx="karstenw.20220612162654.2">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
</t>
<t tx="karstenw.20220612162654.3">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
</t>
<t tx="karstenw.20220612162654.4">def iterateFolders( infolder, validExtensions=False ):
"""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 0:
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( b"PRG formatted GEOS file"):
formatOK = True
elif format.startswith( b"SEQ formatted GEOS file"):
broken = True
if not formatOK:
continue
typ = '.cvt'
if kwlog and 1:
print( "FILE:", filepath )
yield typ, filepath
</t>
<t tx="karstenw.20220612162654.5">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 as err:
print( "ZIP ERROR", err )
return result
for zf in files:
print( "ZIPFILE:", zf.filename )
try:
h = handle.open(zf)
data = h.read()
except Exception as 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
</t>
<t tx="karstenw.20220612162654.6">class ImageBuffer(list):
"""For debugging purposes mostly. Has a built in memory dump in
monitor format."""
@others
</t>
<t tx="karstenw.20220612162654.7">def __init__(self):
super(ImageBuffer, self).__init__()
</t>
<t tx="karstenw.20220612162654.8">def dump(self):
hexdump( self )
</t>
<t tx="karstenw.20220612162654.9">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, bytes, bytearray): #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]
if d:
d2 = chr(c2)
else:
d2 = c2
if 32 <= c2 < 127:
sys.stdout.write( d2 )
else:
sys.stdout.write( '.' )
sys.stdout.write('\n')
sys.stdout.write('\n')
sys.stdout.flush()
#
# file tools
#
#
# macpaint image conversion
#
</t>
<t tx="karstenw.20220612162656.1"># -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import os
import time
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 = 0
</t>
<t tx="karstenw.20220612162656.10">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, bytes, bytearray): #ImageBuffer):
d = True
for i,c in enumerate(s):
if d:
t = hex(c)[2:]
else:
t = hex( 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 = c2
if 32 <= d2 < 127:
sys.stdout.write( chr(c2) )
else:
sys.stdout.write( '.' )
sys.stdout.write('\n')
</t>
<t tx="karstenw.20220612162656.11">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 = clipnamesstream[0]
if len(clipnamesstream) != (noofentries + 1) * 17 + 1:
if kwlog:
print("len(clipnamesstream) %i" % len(clipnamesstream))
print("(noofentries + 1) * 17 + 1 %i" % (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 as err:
print()
print(err)
# pdb.set_trace()
print()
return clipnameschain, clipnames
</t>
<t tx="karstenw.20220612162656.12">def expandImageStream( stream ):
"""Expand a 640x16 compressed image stream as encountered in geoPaint files.
Returns a bytearray
"""
streamlength = len(stream)
idx = -1
# image = ImageBuffer()
image = bytearray(0)
log = []
while idx < streamlength-1:
idx += 1
code = stream[idx]
# current collector
items = bytearray(0)
roomleft = (streamlength-1) - idx
if 0: #code == 0:
break
if code in (64, 128):
if kwdbg:
print("blank code 64,128 encountered.")
#pdb.set_trace()
continue
# 0 .. 63
if code < 64:
if roomleft < 1:
idx += 1
continue
data = stream[idx+1:idx+code+1]
for i in data:
items.append( i )
idx += len(data)
image.extend( items )
continue
# 64 .. 127
elif 64 <= code < 128:
#
if roomleft < 8:
idx += 8
continue
# extract count
c = code & 63
# read pattern ( 8 bytes )
pattern = stream[idx+1:idx+9]
patternlength = len(pattern)
# patternrepeatbytes
cnt = patternlength * c
for i in range(c):
for k in range(patternlength):
p = pattern[k]
items.append( p )
idx += patternlength
image.extend( items )
continue
elif 128 <= code:
if roomleft < 1:
idx += 1
continue
c = code - 128
data = stream[idx+1]
t = [data] * c
items = t
image.extend( items )
idx += 1
continue
if kwdbg:
log.append( items )
return image
</t>
<t tx="karstenw.20220612162656.13">def expandScrapStream( stream ):
"""Expand a variable compressed image stream as encountered in 'Photo Album',
'Photo Scrap' and geoWrite files.
Returns a bytearray
"""
streamlength = len(stream)
idx = -1
image = bytearray(0)
while idx < streamlength-1:
idx += 1
code = stream[idx]
roomleft = (streamlength-1) - idx
if code in (0,128,220):
if kwdbg:
print("ILLEGAL OPCODES...")
# pdb.set_trace()
print
continue
elif code < 128:
if roomleft < 1:
idx += 1
continue
data = stream[idx+1]
t = [data] * code
image.extend( t )
idx += 1
continue
elif 128 <= code <= 219:
c = code - 128
if roomleft < c:
idx += c
continue
data = stream[idx+1:idx+c+1]
for i in data:
image.append( i )
idx += c
continue
else:
# 220...255
patsize = code -220
if roomleft < patsize+1:
idx += patsize+1
continue
repeat = stream[idx+1]
size = repeat * patsize
pattern = stream[idx+2:idx+2+patsize]
for i in range( repeat ):
for p in pattern:
image.append( p )
idx += patsize+1
continue
return image
</t>
<t tx="karstenw.20220612162656.14">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 = s[0]
w = cardsw * 8
h = s[2] * 256 + 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
</t>
<t tx="karstenw.20220612162656.15">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
</t>
<t tx="karstenw.20220612162656.16">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.
"""
# pdb.set_trace()
# height in cards
cardsh = h >> 3
if h & 7 != 0:
cardsh += 1
# width in pixels
w = cardsw * 8
# h = cardsh * 8
eightZeroBytes = bytes( [0] * 8 )
noofcards = cardsw * cardsh
noofbytes = noofcards * 8
noofcolorbands = cardsh
# holds a list of card colors; one list per row
colorbands = bytearray(0)
# 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: %i" % (bitmapsize - n,) )
# fill bitmap up
image.extend( [0] * (bitmapsize - n) )
# add gap
image.extend( eightZeroBytes )