-
Notifications
You must be signed in to change notification settings - Fork 8
/
xdm99.py
executable file
·1682 lines (1520 loc) · 71.3 KB
/
xdm99.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
# xdm99: A disk manager for TI disk images
#
# Copyright (c) 2015-2024 Ralph Benzinger <xdt99@endlos.net>
#
# This program is part of the TI 99 Cross-Development Tools (xdt99).
#
# xdt99 is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import sys
import re
import datetime
import os
import argparse
from xcommon import Util, RContainer, CommandProcessor, GlobStore, Console, Warnings
VERSION = '3.5.2'
CONFIG = 'XDM99_CONFIG'
# Sector-based disk image
class ContainerError(Exception):
pass
class Disk:
"""sector-based TI disk image file"""
BYTES_PER_SECTOR = 256
DEFAULT_SECTORS_PER_TRACK = 9
DEFAULT_TRACKS = 40
MAX_SECTORS = 1600
BLANK_BYTE = b'\xe5'
DISK_NAME_LEN = 0x0a
TOTAL_SECTORS = 0x0a
TOTAL_SECTORS_END = 0x0c
SECTORS_PER_TRACK = 0x0c
DSK_ID = 0x0d
DSK_ID_END = 0x10
DISK_PROTECTED = 0x10
TRACKS_PER_SIDE = 0x11
SIDES = 0x12
DENSITY = 0x13
ALLOC_BITMAP = 0x38
RESERVED = 0x14
DATA = 0x100
def __init__(self, image, console, init=False):
if len(image) < 2 * Disk.BYTES_PER_SECTOR:
raise ContainerError('Invalid disk image')
self.image = image
self.console = console
self.catalog = {}
self.read_sectors = []
# meta data
sector_0 = self.get_sector(0)
if sector_0[0] == 0x00 and sector_0[21:23] == b'\x00\xfe':
raise ContainerError('Track dump images not supported')
try:
self.name = sector_0[:self.DISK_NAME_LEN].decode()
except UnicodeDecodeError:
self.name = 'INVALID '
self.console.warn('Disk name contains invalid Unicode', category=Warnings.IMAGE)
self.total_sectors = Util.ordn(sector_0[Disk.TOTAL_SECTORS:Disk.TOTAL_SECTORS_END])
self.sectors_per_track = sector_0[Disk.SECTORS_PER_TRACK]
self.dsk_id = sector_0[Disk.DSK_ID:Disk.DSK_ID_END]
self.protected = sector_0[Disk.DISK_PROTECTED] # int, not boolean
self.tracks_per_side = sector_0[Disk.TRACKS_PER_SIDE]
self.sides = sector_0[Disk.SIDES]
self.density = sector_0[Disk.DENSITY]
self.alloc_bitmap = sector_0[Disk.ALLOC_BITMAP:]
if self.dsk_id != b'DSK':
self.console.warn('Disk image not initialized', category=Warnings.IMAGE)
if len(self.image) < self.total_sectors * Disk.BYTES_PER_SECTOR:
self.console.warn('Disk image truncated', category=Warnings.IMAGE)
self.used_sectors = 0
try:
for i in range(Util.used(self.total_sectors, 8)):
self.used_sectors += bin(self.alloc_bitmap[i]).count('1')
except IndexError:
self.console.warn('Allocation map corrupted', category=Warnings.ALLOCATION)
self._check_geometry()
self._init_catalog()
self._check_allocation()
self.modified = init # mark if disk image was modified and needs to be saved
@staticmethod
def blank_image(geometry, name):
"""return initialized disk image"""
sectors, sides, density, sectors_per_track, tracks = Disk.parse_geometry(geometry)
sector_0 = (b'%-10b%2b%cDSK ' % (name.encode()[:10],
Util.chrn(sectors),
sectors_per_track) + # header
bytes((tracks or Disk.DEFAULT_TRACKS, sides, density)) +
bytes(0x24) + # reserved
b'\x03' + bytes(sectors // 8 - 1) + # allocation map
b'\xff' * (Disk.BYTES_PER_SECTOR - sectors // 8 - Disk.ALLOC_BITMAP))
return (sector_0 +
bytes(Disk.BYTES_PER_SECTOR) + # blank sector 1
Disk.BLANK_BYTE * ((sectors - 2) * Disk.BYTES_PER_SECTOR)) # sectors 2 and up
@staticmethod
def parse_geometry(geometry, no_sectors=False):
"""get disk size and layout from geometry string"""
try:
sectors = Util.xint(geometry)
if no_sectors:
raise ContainerError('Invalid disk geometry: ' + geometry)
sides = 2 if (sectors - 1) % 720 >= 360 else 1
density = 2 if sectors > 720 else 1 # favor DSSD over SSDD
sectors_per_track = density * Disk.DEFAULT_SECTORS_PER_TRACK
tracks = Disk.DEFAULT_TRACKS
except ValueError:
if geometry.upper() == 'CF':
sectors = 1600
sides = density = 1
sectors_per_track = 20
tracks = 80
else:
m = re.match(r'([12SD])S([12SD])D(?:(\d+)T)?', geometry.upper())
if not m:
raise ContainerError('Invalid disk geometry: ' + geometry)
sides = 1 if m.group(1) in '1S' else 2
density = 1 if m.group(2) in '1S' else 2
sectors_per_track = Disk.DEFAULT_SECTORS_PER_TRACK * density
tracks = int(m.group(3)) if m.group(3) else Disk.DEFAULT_TRACKS
sectors = sides * tracks * sectors_per_track
if not 2 < sectors <= Disk.MAX_SECTORS or sectors % 8 != 0:
raise ContainerError('Invalid disk size')
return sectors, sides, density, sectors_per_track, tracks
def _check_geometry(self):
"""check geometry against sector count"""
if self.total_sectors != self.sides * self.tracks_per_side * self.sectors_per_track:
self.console.warn('Sector count does not match disk geometry', category=Warnings.GEOMETRY)
if self.total_sectors % 8 != 0:
self.console.warn('Sector count is not multiple of 8', category=Warnings.GEOMETRY)
def _init_catalog(self):
"""read all files from disk"""
sector_1 = self.get_sector(1)
sector_count = 0
for i in range(0, Disk.BYTES_PER_SECTOR, 2):
# get file descriptor
fd_index = Util.ordn(sector_1[i:i + 2])
if fd_index == 0:
break
try:
fd_sector = self.get_sector(fd_index, b'FDR#%d' % fd_index)
except IndexError:
self.console.warn('File descriptor index corrupted')
continue
fd = FileDescriptor.create_from_fdr_sector(fd_sector)
# get file contents
data = self._read_file(fd)
self.catalog[fd.name] = File(fd=fd, data=data, console=self.console)
sector_count += fd.total_sectors + 1
# consistency check
if sector_count != self.used_sectors - 2:
self.console.warn('Used sector mismatch: found {} file sectors, expected {}'.format(
sector_count, self.used_sectors - 2))
def _read_file(self, fd):
"""read file contents based on FDR cluster data"""
parts = []
offset = -1
for i in range(0, len(fd.clusters) - 2, 3):
start = fd.clusters[i] | (fd.clusters[i + 1] & 0x0f) << 8
if start == 0:
break
prev_offset = offset
offset = fd.clusters[i + 1] >> 4 | fd.clusters[i + 2] << 4
for j in range(offset - prev_offset):
try:
parts.append(self.get_sector(start + j, fd.name))
except IndexError:
self.console.warn(f'{fd.name:s}: File contents corrupted')
fd.error = True
continue
data = b''.join(parts)
return data
def _check_allocation(self):
"""check sector allocation for consistency"""
reads = {n: [] for n in range(self.total_sectors)}
allocated = []
for i in range(Util.used(self.total_sectors, 8)):
try:
b = self.alloc_bitmap[i]
except IndexError:
break
for bit in range(8):
allocated.append(b & (1 << bit) != 0)
# unallocated sectors
for sector_no, context in self.read_sectors:
reads[sector_no].append(context)
if context and not allocated[sector_no]:
self.console.warn(f'{context}: Used sector {sector_no} not allocated')
if file_ := self.catalog.get(context):
file_.fd.error = True
# sectors allocated to multiple files
for sector_no, files in reads.items():
if len(files) <= 1:
continue
self.console.warn(f"Sector {sector_no} claimed by multiple files: {'/'.join(files)}")
for name in files:
if file_ := self.catalog.get(name):
file_.fd.error = True
def _rebuild_disk(self):
"""rebuild disk metadata after changes to file catalog"""
required_sectors = sum(self.catalog[n].fd.total_sectors for n in self.catalog)
# preferred start at sector >22
first_free = next_free_sector = min(max(2 + len(self.catalog), 0x22), self.total_sectors - required_sectors)
if first_free < 2 + len(self.catalog):
raise ContainerError('Disk full, lacking {} sectors'.format(2 + len(self.catalog) - first_free))
sector_1 = b''
index = 2
for idx, file_ in sorted(self.catalog.items()):
# put file data into single cluster
data = file_.data + bytes(Util.pad(len(file_.data), Disk.BYTES_PER_SECTOR))
for i in range(file_.fd.total_sectors):
self.set_sector(next_free_sector + i, data[Disk.BYTES_PER_SECTOR * i:Disk.BYTES_PER_SECTOR * (i + 1)])
# build file descriptor
if file_.fd.total_sectors > 0:
start = next_free_sector
offset = file_.fd.total_sectors - 1
else:
start = offset = 0
file_.fd.clusters = (bytes((start & 0xff, start >> 8 | (offset & 0xf) << 4, offset >> 4)) +
bytes(Disk.BYTES_PER_SECTOR - 0x1c - 3))
self.set_sector(index, file_.fd.get_disk_or_v9t9_header())
# update FDR index in sector 1
sector_1 += Util.chrn(index)
next_free_sector += file_.fd.total_sectors
index += 1
sector_1 += bytes(Disk.BYTES_PER_SECTOR - len(sector_1))
self.set_sector(1, sector_1)
# update allocation bitmap in sector 0 (used: 0..i-1, ff..nf-1)
assert 0 < index <= first_free <= next_free_sector
mask = int('1' * (next_free_sector - first_free) +
'0' * (first_free - index) + '1' * index, 2) # bitmap as bits, parsed into (very large) int
bytes_ = []
for i in range(self.total_sectors // 8):
bytes_.append(bytes((mask & 0xff,))) # byte-ize int from the tail
mask >>= 8
self.alloc_bitmap = b''.join(bytes_) + b'\xff' * (Disk.BYTES_PER_SECTOR - Disk.ALLOC_BITMAP - len(bytes_))
sector_0 = self.get_sector(0)
self.set_sector(0, sector_0[:self.ALLOC_BITMAP] + self.alloc_bitmap)
self.modified = True
@staticmethod
def is_formatted(image):
"""is disk formatted?"""
return image[Disk.DSK_ID:Disk.DSK_ID_END] == b'DSK'
def set_geometry(self, sides=1, density=1, sectors_per_track=DEFAULT_SECTORS_PER_TRACK, tracks=40, cf=False):
"""override geometry of disk image"""
if cf:
self.sides = self.density = 1
self.tracks_per_side = 80 # all values must fit in one byte!
self.sectors_per_track = 20
else:
if sides:
self.sides = sides
if density:
self.density = density
if tracks:
self.tracks_per_side = tracks
self.sectors_per_track = sectors_per_track
self.image = (self.image[:Disk.SECTORS_PER_TRACK] + bytes((self.sectors_per_track,)) +
self.image[Disk.DSK_ID:Disk.TRACKS_PER_SIDE] +
bytes((self.tracks_per_side, self.sides, self.density)) + self.image[Disk.RESERVED:])
self.console.clear_warnings(Warnings.GEOMETRY)
self._check_geometry()
self.modified = True
def resize_disk(self, new_size):
"""resize image to given sector count"""
if not 2 < new_size <= Disk.MAX_SECTORS:
raise ContainerError(f'Invalid disk size, expected between 2 and {Disk.MAX_SECTORS} sectors')
if self.total_sectors % 8 != 0 or new_size % 8 != 0:
raise ContainerError('Old and new disk size must be multiple of 8 sectors')
old_size = self.total_sectors
self.total_sectors = new_size
self.used_sectors = 0
self._rebuild_disk()
self.image = (self.image[:Disk.DISK_NAME_LEN] + Util.chrn(new_size) +
self.image[Disk.SECTORS_PER_TRACK:new_size * self.BYTES_PER_SECTOR] +
self.BLANK_BYTE * ((new_size - old_size) * self.BYTES_PER_SECTOR))
@staticmethod
def trim_sectors(image):
"""shrink image to actually existing sectors (for xvm99)"""
total_sectors = Util.ordn(image[Disk.TOTAL_SECTORS:Disk.TOTAL_SECTORS_END])
return image[:total_sectors * Disk.BYTES_PER_SECTOR]
def fix_disk(self):
"""rebuild disk with non-erroneous files"""
for name, file_ in self.catalog.items():
if file_.fd.error:
del self.catalog[name]
self._rebuild_disk()
def rename_disk(self, name):
"""rename disk"""
self.name = name
if len(self.name.encode()) > Disk.DISK_NAME_LEN:
raise ContainerError('Encoded name is too long')
self.image = self.name.encode() + b' ' * (Disk.DISK_NAME_LEN - len(self.name)) + self.image[Disk.DISK_NAME_LEN:]
self.modified = True
def get_sector(self, sector_no, context=None):
"""retrieve sector from image"""
if sector_no > 0 and sector_no >= self.total_sectors:
if sector_no < len(self.image) // Disk.BYTES_PER_SECTOR:
self.console.warn('Total sectors not set properly')
else:
raise IndexError('Invalid sector number')
if context:
self.read_sectors.append((sector_no, context))
offset = sector_no * Disk.BYTES_PER_SECTOR
return self.image[offset:offset + Disk.BYTES_PER_SECTOR]
def set_sector(self, sector_no, data):
"""write sector to image"""
if sector_no > self.total_sectors:
raise IndexError('Invalid sector number')
if len(data) != Disk.BYTES_PER_SECTOR:
raise ValueError(f'Invalid data for sector {sector_no:d}: found {len(data):d} bytes, ' +
f'expected {Disk.BYTES_PER_SECTOR:d}')
offset = sector_no * Disk.BYTES_PER_SECTOR
self.image = self.image[:offset] + data + self.image[offset + Disk.BYTES_PER_SECTOR:]
self.modified = True
def glob_files(self, patterns):
"""return listing of filenames matching glob pattern"""
return Util.glob(self, patterns)
def get_file(self, name):
"""get File object from disk catalog"""
try:
return self.catalog[name]
except KeyError:
raise ContainerError(f'File {name} not found on disk')
def add_files(self, files):
"""add or update files"""
for file in files:
self.catalog[file.fd.name] = file
self._rebuild_disk()
def remove_files(self, names):
"""remove files from image"""
for name in names:
try:
del self.catalog[name]
except KeyError:
raise ContainerError(f'File {name} not found')
self._rebuild_disk()
def rename_files(self, names):
"""rename files in image"""
# rename dry-run
for old, new in names:
try:
self.catalog[old].fd.name = new
except KeyError:
raise ContainerError(f'File {old} not found')
try:
self.catalog[new] = self.catalog[old]
except KeyError:
raise ContainerError(f'File {new} not found')
del self.catalog[old]
self._rebuild_disk()
def protect_files(self, names):
"""toggle protection for given files"""
for name in names:
try:
file = self.catalog[name]
except KeyError:
raise ContainerError(f'File {name} not found')
file.fd.toggle_protection()
self._rebuild_disk()
def get_tifiles_file(self, name):
"""get file in TIFILES format from disk catalog"""
file = self.get_file(name)
return file.get_as_tifiles()
def get_sdd99_file(self, name, loadtype=0):
"""get file in SDD99 format from disk catalog"""
file = self.get_file(name)
return file.get_as_sdd99(loadtype=loadtype)
def get_v9t9_file(self, name):
"""get file in v9t9 format from disk catalog"""
file = self.get_file(name)
return file.get_as_v9t9()
def get_image(self):
"""return disk image"""
return self.image
def get_info(self):
"""return information about disk image"""
return '{:10s}: {:c} {:d} used {:d} free {:d} KB {:d}S/{:d}D {:d}T {:d} S/T\n'.format(
self.name,
self.protected,
self.used_sectors,
self.total_sectors - self.used_sectors,
self.total_sectors * Disk.BYTES_PER_SECTOR // 1024,
self.sides,
self.density,
self.tracks_per_side,
self.sectors_per_track)
def get_catalog(self):
"""return formatted disk catalog"""
return ''.join(self.catalog[n].fd.get_info() for n in sorted(self.catalog))
# Archives
class Archive:
"""ARK archive manipulation
Directory entry format:
Bytes 0-9: Filename
10: Flags
11: Records per sector
12-13: Sector count
14: EOF offset
15: Record length
16-17: Record count (reversed)
Note that created and modified dates are not included in archive!
Directory sectors:
Entries ... END! at end of sector
Data sectors ...
Offset derived from sector count in directory entry
"""
def __init__(self, cdata=None, name='ARK', console=None):
self.name = name
self.console = console or Xdm99Console()
self.catalog = {} # files in archive: {name: File}
self.lzw = LZW()
if cdata is None:
self.archive = bytes(252) + b'END!' # new, empty archive
self.cdata = self.lzw.compress(self.archive)
self.modified = True
return
self.cdata = cdata
self.archive = self.lzw.decompress(cdata)
self.modified = False
# get files stored in archive
directory = None
for s in range(Util.used(len(self.archive), 256)):
offset = (s + 1) * 256
if self.archive[offset - 4:offset] == b'END!': # end of directory marker
directory = self.archive[:offset]
break
if not directory:
raise ContainerError('Malformed archive')
i = 0 # directory index
j = len(directory) # data index
while i < len(directory):
if self.archive[i] == 0:
# move to next sector
i = Util.trunc(i + 256, 256)
continue
try:
# get catalog entry
name = self.archive[i:i + 10].decode().rstrip()
sectors = Util.ordn(self.archive[i + 12:i + 14])
fd = FileDescriptor(name=name,
flags=self.archive[i + 10],
records_per_sector=self.archive[i + 11],
total_sectors=sectors,
eof_offset=self.archive[i + 14],
record_len=self.archive[i + 15],
lv3_records=Util.rordw(self.archive[i + 16:i + 18]))
# get data for catalog entry
data = self.archive[j:j + sectors * 256]
if name in self.catalog:
self.console.warn('Duplicate name in archive: ' + name)
self.catalog[name] = File(fd=fd, data=data)
# next file in archive
i += 18
j += sectors * 256
except UnicodeDecodeError:
self.console.warn(b'Invalid filename in archive: ' + self.archive[i:i + 10])
def _rebuild_archive(self):
"""rebuild archive and compressed archive"""
file_recs = []
names = sorted(self.catalog.keys())
for name in names:
file = self.catalog[name]
rec_count = file.fd.total_sectors if file.fd.flags & 0x80 else file.fd.lv3_records # quirk
file_recs.append((file.fd.name.encode() + b' ')[:10] +
bytes((file.fd.flags,
file.fd.records_per_sector,
file.fd.total_sectors >> 8, file.fd.total_sectors & 0xff,
file.fd.eof_offset,
file.fd.record_len,
rec_count & 0xff, rec_count >> 8)))
entries = b''.join(file_recs)
directory = entries + bytes(Util.pad(len(entries) + 4, 256)) + b'END!'
data = b''.join(self.catalog[name].get_data() for name in names)
assert len(data) % Disk.BYTES_PER_SECTOR == 0
self.archive = directory + data
self.cdata = self.lzw.compress(self.archive)
self.modified = True
def glob_files(self, patterns):
"""glob files"""
return Util.glob(self, patterns)
def get_file(self, filename):
"""extract file from archive"""
try:
return self.catalog[filename]
except KeyError:
raise ContainerError(f'File {filename} not found in archive')
def add_files(self, files):
"""add file to archive"""
for file in files:
self.catalog[file.fd.name] = file
self._rebuild_archive()
def remove_files(self, filenames):
"""delete entries from archive"""
for name in filenames:
try:
del self.catalog[name]
except KeyError:
raise ContainerError(f'File {name} not found in archive')
self._rebuild_archive()
def rename_files(self, renames):
"""rename entries in archive"""
for old, new in renames:
try:
file = self.catalog[old]
except KeyError:
raise ContainerError(f'File {old} not found in archive')
try:
file.fd.name = new
self.catalog[new] = file
except KeyError:
raise ContainerError(f'File {new} not found in archive')
del self.catalog[old]
self._rebuild_archive()
def protect_files(self, filenames):
"""toggle protection status of files in archive"""
for name in filenames:
try:
file = self.catalog[name]
except KeyError:
raise ContainerError(f'File {name} not found in archive')
file.fd.toggle_protection()
self._rebuild_archive()
def get_tifiles_file(self, name):
"""get file in TIFILES format from disk catalog"""
file = self.get_file(name)
return file.get_as_tifiles()
def get_sdd99_file(self, name, loadtype=0):
"""get file in SDD99 format from disk catalog"""
file = self.get_file(name)
return file.get_as_sdd99(loadtype=loadtype)
def get_v9t9_file(self, name):
"""get file in v9t9 format from disk catalog"""
file = self.get_file(name)
return file.get_as_v9t9()
def get_info(self):
"""return information about archive"""
return 'Archive: {:10s} Size (c/u): {} B / {} B Ratio: {:.1f}%\n'.format(
self.name,
len(self.cdata),
len(self.archive),
100 * len(self.cdata) / len(self.archive))
def get_catalog(self):
"""return formatted archive catalog"""
return ''.join(file.get_info() for file in self.catalog.values())
def get_image(self, astifiles=False):
"""create archive file"""
if astifiles:
return File.create_new(name=self.name, format_='INT/FIX128', data=self.cdata).get_as_tifiles()
return self.cdata
class Bitstream:
"""translates sequence of bits into bytes, and vice versa"""
def __init__(self, data=None, width=9):
if data is None:
self.data = b'' # for writing
self.datalen = 0
else:
self.data = data + bytes(2) # padding to read final bits correctly
self.datalen = len(data)
self.dataval = [] # for writing
self.width = width
self.initial_width = width
self.currpos = 0 # in bits
def read(self):
"""read value of next bits of current width"""
if self.currpos + self.width > self.datalen * 8:
raise StopIteration
byte_index = self.currpos // 8
value = Util.ordn(self.data[byte_index:byte_index + 3])
value = (value << (self.currpos % 8)) & 0xffffff
value >>= (24 - self.width)
self.currpos += self.width
return value
def write(self, value):
"""write value to stream"""
bit_offset = self.currpos % 8
value = (value << (24 - self.width)) >> bit_offset
n = self.width
if bit_offset != 0:
self.dataval[-1] |= value >> 16
value = (value << 8) & 0xffffff
n -= 8 - bit_offset
while n > 0:
self.dataval.append(value >> 16)
value = (value << 8) & 0xffffff
n -= 8
self.currpos += self.width
def array(self):
"""return data written to Bitstream"""
return bytes(self.dataval)
def putback(self):
"""unread last value"""
self.currpos -= self.width
def reset(self):
"""reset width"""
self.width = self.initial_width
class LZW:
"""compresses and decompresses data with LZW algorighm"""
RESET = 256 # extensions for ARK archives
DONE = 257
NEXT = 258
@staticmethod
def compress(data):
"""actually compress data
self.patterns: {int array: int}
"""
patterns = {(i,): i for i in range(LZW.NEXT)}
bstream = Bitstream()
bstream.write(LZW.RESET)
next_code = LZW.NEXT
w = ()
i = 0
while i < len(data):
b = data[i]
p = w + (b,)
if p in patterns:
w = p
else:
bstream.write(patterns[w])
if next_code >> bstream.width:
if bstream.width == 12:
bstream.write(LZW.RESET)
bstream.reset()
patterns = {(i,): i for i in range(LZW.NEXT)}
next_code = LZW.NEXT
w = ()
continue
else:
bstream.width += 1
patterns[p] = next_code
next_code += 1
w = (b,)
i += 1
bstream.write(patterns[w])
bstream.write(LZW.DONE)
return bstream.array()
@staticmethod
def decompress(cdata):
"""actually decompress data
self.patterns: {int: int array}
The int array only containes values 0 <= n <= 255
"""
patterns = {i: (i,) for i in range(LZW.NEXT)}
bstream = Bitstream(cdata) # compressed data consists of up to 12-bit values
next_code = LZW.NEXT
w = ()
data = [] # uncompressed data consists of 8-bit values
while True:
try:
n = bstream.read()
if n == LZW.RESET:
bstream.reset()
patterns = {i: (i,) for i in range(LZW.NEXT)}
next_code = LZW.NEXT
w = ()
continue
elif n == LZW.DONE:
break
if not w:
w = (n,)
data.extend(patterns[n])
continue
if n > next_code:
raise ContainerError('Invalid archive')
try:
e = patterns[n]
except KeyError:
e = w + (w[0],)
data.extend(e)
patterns[next_code] = w + (e[0],)
next_code += 1
w = e
if next_code >> bstream.width:
if bstream.width == 12:
continue # keep width and continue
if bstream.read() == LZW.DONE:
break
bstream.putback()
bstream.width += 1
except StopIteration:
raise ContainerError('Incomplete archive ended without STOP code')
return bytes(data)
# Files
class FileError(Exception):
pass
class FileDescriptor:
"""file meta data descriptor based on TI disk image format"""
DISPLAY = 0x00
PROGRAM = 0x01
INTERNAL = 0x02
UNKNOWN = 0x03
FIXED = 0x00
VARIABLE = 0x80
PROTECTED = 0x08
FILE_NAME_LEN = 0x0a
FLAGS = 0x0c
RECORDS_PER_SECTOR = 0x0d
TOTAL_SECTORS = 0x0e
TOTAL_SECTORS_END = 0x10
EOF_OFFSET = 0x10
RECORD_LEN = 0x11
LV3_RECORDS_LOW = 0x12
LV3_RECORDS_HIGH = 0x13
FILE_CLUSTER = 0x1c
CREATED = 0x14
CREATED_END = 0x18
MODIFIED = 0x18
MODIFIED_END = 0x1c
TIF_TOTAL_SECTORS = 0x08
TIF_TOTAL_SECTORS_END = 0x0a
TIF_FLAGS = 0x0a
TIF_RECORDS_PER_SECTOR = 0x0b
TIF_EOF_OFFSET = 0x0c
TIF_RECORD_LEN = 0x0d
TIF_LV3_RECORDS_LOW = 0x0e
TIF_LV3_RECORDS_HIGH = 0x0f
TIF_FILE_NAME = 0x10
TIF_CREATED = 0x1e
TIF_CREATED_END = 0x22
TIF_MODIFIED = 0x22
TIF_MODIFIED_END = 0x26
def __init__(self, flags=0, records_per_sector=0, total_sectors=0, eof_offset=0, record_len=0, lv3_records=0,
name=None, created=None, modified=None, clusters=None, hostfn=None):
self.error = False
self.name = name
self.flags = flags
self.total_sectors = total_sectors
self.eof_offset = eof_offset
self.lv3_records = lv3_records
self.records_per_sector = records_per_sector
self.record_len = record_len
self.created = created or FileDescriptor.encode_date(datetime.datetime.now()) # time and date
self.modified = modified or self.created
self.clusters = clusters
self.hostfn = hostfn
# compute dependent values
self.type = (FileDescriptor.DISPLAY, FileDescriptor.PROGRAM,
FileDescriptor.INTERNAL, FileDescriptor.UNKNOWN)[self.flags & 0x03]
self.mode = FileDescriptor.VARIABLE if self.flags & 0x80 else FileDescriptor.FIXED
self.format = ('DIS/', 'PROGRAM', 'INT/', 'unknown')[self.flags & 0x03] # display format
if self.type in (FileDescriptor.DISPLAY, FileDescriptor.INTERNAL):
self.format += ('VAR ' if self.mode == FileDescriptor.VARIABLE else 'FIX ') + str(self.record_len)
self.protected = self.flags & 0x08
self.size = self.get_filesize()
@staticmethod
def create(name, format_):
"""create new empty file descriptor"""
m_fmt = re.match(r'([PDIB])[ROGAMISNT]*(?:/?([VF])[ARIX]*\s*(\d+))?', format_.upper())
if not m_fmt:
raise FileError('Unknown file format: ' + format_)
# build flags for specified format
fmt_type = m_fmt.group(1)
if fmt_type == 'P': # P, D, or I
flags = FileDescriptor.PROGRAM
record_len = records_per_sector = 0
else:
fmt_mode = m_fmt.group(2) # F or V
flags = ((FileDescriptor.INTERNAL if fmt_type == 'I' else FileDescriptor.DISPLAY) |
(FileDescriptor.FIXED if fmt_mode == 'F' else FileDescriptor.VARIABLE))
fmt_len = m_fmt.group(3)
record_len = int(fmt_len) if fmt_len else 80
records_per_sector = ((Disk.BYTES_PER_SECTOR if fmt_mode == 'F' else Disk.BYTES_PER_SECTOR - 2) //
record_len) % Disk.BYTES_PER_SECTOR # mod for DF1
created = modified = FileDescriptor.encode_date(datetime.datetime.now())
return FileDescriptor(name=name, flags=flags, record_len=record_len, records_per_sector=records_per_sector,
created=created, modified=modified)
@staticmethod
def create_from_fdr_sector(sector):
"""create file descriptor from FDR sector"""
if len(sector) < 0x20:
raise FileError('Invalid file descriptor')
try:
name = sector[:FileDescriptor.FILE_NAME_LEN].decode().rstrip()
except UnicodeDecodeError:
raise FileError('Invalid Unicode filename')
flags = sector[FileDescriptor.FLAGS]
records_per_sector = sector[FileDescriptor.RECORDS_PER_SECTOR]
total_sectors = Util.ordn(sector[FileDescriptor.TOTAL_SECTORS:FileDescriptor.TOTAL_SECTORS_END])
eof_offset = sector[FileDescriptor.EOF_OFFSET]
record_len = sector[FileDescriptor.RECORD_LEN]
created = sector[FileDescriptor.CREATED:FileDescriptor.CREATED_END] # time, date
modified = sector[FileDescriptor.MODIFIED:FileDescriptor.MODIFIED_END]
clusters = sector[FileDescriptor.FILE_CLUSTER:]
lv3_records = ((sector[FileDescriptor.LV3_RECORDS_HIGH] << 8) |
sector[FileDescriptor.LV3_RECORDS_LOW]) # only correct for FIXED files
return FileDescriptor(name=name, flags=flags, records_per_sector=records_per_sector,
total_sectors=total_sectors, eof_offset=eof_offset, record_len=record_len,
created=created, modified=modified, clusters=clusters, lv3_records=lv3_records)
@staticmethod
def create_from_tif_header(header, hostfn=None):
"""create file descriptor from TIFILES header"""
if len(header) < 0x26 or not File.is_tifiles(header):
raise FileError('Invalid TIFILES header')
total_sectors = Util.ordn(header[FileDescriptor.TIF_TOTAL_SECTORS:FileDescriptor.TIF_TOTAL_SECTORS_END])
flags = header[FileDescriptor.TIF_FLAGS] & 0x83
records_per_sector = header[FileDescriptor.TIF_RECORDS_PER_SECTOR]
eof_offset = header[FileDescriptor.TIF_EOF_OFFSET]
record_len = header[FileDescriptor.TIF_RECORD_LEN]
lv3_records = ((header[FileDescriptor.TIF_LV3_RECORDS_HIGH] << 8) |
header[FileDescriptor.TIF_LV3_RECORDS_LOW]) # only correct for FIXED files
if header[0x10] == 0x00:
# short TIFILES: use file properties
name = Util.tiname(hostfn)
dt = datetime.datetime.fromtimestamp(os.path.getctime(hostfn))
created = FileDescriptor.encode_date(dt)
dt = datetime.datetime.fromtimestamp(os.path.getmtime(hostfn))
modified = FileDescriptor.encode_date(dt)
else:
# long TIFILES: use header data
try:
name = header[FileDescriptor.TIF_FILE_NAME:
FileDescriptor.TIF_FILE_NAME + FileDescriptor.FILE_NAME_LEN].decode().rstrip()
except UnicodeDecodeError:
name = 'FILE'
created = header[FileDescriptor.TIF_CREATED:FileDescriptor.TIF_CREATED_END]
modified = header[FileDescriptor.TIF_MODIFIED:FileDescriptor.TIF_MODIFIED_END]
return FileDescriptor(name=name, flags=flags, records_per_sector=records_per_sector, eof_offset=eof_offset,
total_sectors=total_sectors, record_len=record_len, lv3_records=lv3_records,
created=created, modified=modified)
def get_filesize(self):
"""returns file size, excluding FDR (supports SDD99 extension)"""
return (self.total_sectors * Disk.BYTES_PER_SECTOR -
Util.pad(self.eof_offset, Disk.BYTES_PER_SECTOR)) # excludes FDR
def toggle_protection(self):
self.protected = not self.protected
self.flags ^= FileDescriptor.PROTECTED
@staticmethod
def encode_date(dt):
"""convert datetime object into FDR date and time word"""
date = (dt.year % 100) << 9 | dt.month << 5 | dt.day
time = dt.hour << 11 | dt.minute << 5 | dt.second // 2
return Util.chrn(time) + Util.chrn(date)
@staticmethod
def decode_date(qword):
"""extract date and time information from header data"""
time = Util.ordn(qword[0:2])
date = Util.ordn(qword[2:4])
try:
return datetime.datetime(
(date >> 9) + (1900 if date >> 9 >= 70 else 2000), # 1970 is cut-off year for 1900s
date >> 5 & 0x0f,
date & 0x1f,
time >> 11,
time >> 5 & 0x3f,
(time & 0x0f) * 2)
except ValueError:
return None
def get_disk_or_v9t9_header(self, v9t9=False):
"""return FDR as disk image sector"""
if self.total_sectors == 0xffff:
raise FileError('File too large for disk/v9t9 (max. 16 MB)')
records = self.total_sectors if self.mode == FileDescriptor.VARIABLE else self.lv3_records # per definition
return (b'%-10b' % self.name.encode()[:10] +
bytes((0, 0,
self.flags,
self.records_per_sector,
self.total_sectors >> 8, self.total_sectors & 0xff,
self.eof_offset,
self.record_len,
records & 0xff, records >> 8,
*Util.bval(self.created + self.modified))) +
(bytes(100) if v9t9 else self.clusters))
def get_tifiles_header(self, sdd99_loadtype=None):
"""return FDR as TIFILES header"""
if sdd99_loadtype is None:
if self.total_sectors > 0xffff:
raise FileError('File too large for TIFILES format (max. 16 MB)')
suffix = b' ' * 88
else:
suffix = (b' ' * 8 +
b'SDD99\x01' +
bytes((sdd99_loadtype, 0, (self.total_sectors >> 24) & 0xff, (self.total_sectors >> 16) & 0xff)) +
Util.chrn(self.lv3_records, 2) +
b' ' * 0x44)
records = self.total_sectors if self.mode == FileDescriptor.VARIABLE else self.lv3_records # per definition
return (b'\x07TIFILES' +
bytes((self.total_sectors >> 8, self.total_sectors & 0xff,
self.flags,
self.records_per_sector,
self.eof_offset,
self.record_len,
records & 0xff, (records >> 8) & 0xff)) +
b'%-10b' % self.name.encode()[:10] +
bytes((0, 0, 0xff, 0xff, *Util.bval(self.created + self.modified), 0, 0)) +
suffix)
def get_info(self):
"""return information about file"""
date_str = FileDescriptor.decode_date(self.modified)
return '{:10s} {:4d} {:11s} {:6d} B {:>9s} {:1s} {:>19s} {:s} {:1s}\n'.format(
self.name,
self.total_sectors + 1,
self.format,
self.size,
'{:3d} recs'.format(self.lv3_records) if self.type != FileDescriptor.PROGRAM else '',
'P' if self.protected else '',
'' if date_str is None else str(date_str),
('' if self.modified == self.created == bytes(4) or date_str is None else
'C' if self.modified == self.created else 'M'),
'ERR' if self.error else '')
class File: