-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
832 lines (713 loc) · 33.2 KB
/
main.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
from math import ceil, log2
import os
from os.path import exists
from datetime import datetime, time
FF8BYTES = 18446744073709551615 #VALOR INTEIRO DE FF PRA 8 BYTES
def clear():
#clears terminal
os.system('cls' if os.name == 'nt' else 'clear')
def read_boot(image):
name = image.read(7)
blocks_quantity = int.from_bytes(image.read(8), 'little')
block_size = 2**int.from_bytes(image.read(1), 'little')
boot_pointer = int.from_bytes(image.read(8), 'little')
bitmap_size = ceil(blocks_quantity/ (8* block_size))
dict = {'name': name,
'blocks_quantity': blocks_quantity,
'block_size' : block_size,
'boot_pointer' : boot_pointer,
'bitmap_size' : bitmap_size}
return dict
def Read_Folder(image, boot_info, isRoot):
next_block = 0
if isRoot:
image.seek(24)
folder_content = []
concatenate = False
while next_block != FF8BYTES:
next_block = int.from_bytes(image.read(8), 'little')
if isRoot:
super_block_size = 1
size_used = 32
else:
super_block_size = int.from_bytes(image.read(8), 'little')
size_used = 16
isRoot = False
size_left = boot_info['block_size'] * super_block_size - size_used
mini_block_attribute = image.read(1)
if mini_block_attribute == b'\x40':
concatenate = True
while size_left:
thing_name = ''
while mini_block_attribute == b'\x80' and size_left:
image.seek(15, 1)
mini_block_attribute = image.read(1)
size_left -= 16
if mini_block_attribute == b'\x00':
break
if not concatenate:
thing_size = int.from_bytes(image.read(7), 'little')
first_block = int.from_bytes(image.read(8), 'little')
size_left -= 16
thing_attribute = mini_block_attribute
mini_block_attribute = image.read(1)
while mini_block_attribute == b'\x40' and size_left:
thing_name += image.read(15).decode('ASCII')
size_left -= 16
mini_block_attribute = image.read(1)
thing_name = thing_name.split(chr(0))[0]
if concatenate:
folder_content[-1][0] += thing_name
concatenate = False
else:
folder_content.append([thing_name, thing_size, first_block, thing_attribute])
if next_block and next_block != FF8BYTES:
image = WalkImage(image, boot_info, next_block)
image.seek(image.tell()-1)
return folder_content
def ShowFolder(folder_content, image, boot_info):
clear()
max_name = 0
for content in folder_content:
if len(content[0])>max_name:
max_name = len(content[0])
max_name += 3
for index in range(len(folder_content)):
content = folder_content[index]
line = str(index)+' - '
if content[-1][0]//16 == 1: #verifica se o nibble à esquerda é 1
line += '/'+content[0]+' '*(max_name-len(content[0]))+str(content[1])+'B'
else:
line += content[0]+' '*(max_name-len(content[0]))+str(content[1])+'B'
print(line)
UserInterface(folder_content, image, boot_info)
pass
def OpenThing(folder_content, cmd, image, boot_info):
thing_index = int(cmd[2:])
image = WalkImage(image, boot_info, folder_content[thing_index][2])
if folder_content[thing_index][-1][0]//16 == 1:
folder_content = Read_Folder(image, boot_info, folder_content[thing_index][2]==0)
ShowFolder(folder_content, image, boot_info)
else:
ShowFile(image, boot_info, folder_content, thing_index)
def UpdateBitmap(image, boot_info, blocks_used):
image = WalkImage(image, boot_info, 1)
for blocks in blocks_used:
image.seek(boot_info['block_size'] + (blocks)//8)
# write 1 to bitmap at position of blocks used
byte = image.read(1)
byte = byte[0] | (1 << 7 - (blocks)%8)
image.seek(boot_info['block_size'] + (blocks)//8)
image.write(bytes([byte]))
def CreateBlockSet(image, boot_info, size):
#bitmap_size is the number of blocks used by the bitmap
# go to the bitmap
image = WalkImage(image, boot_info, 1)
# numbers of blocks needed to store the file
blocks_needed = ceil((size + 16)/boot_info['block_size'])
# list the starting block and sequence of free blocks next to it
free_blocks = []
free_blocks.append([])
blocks_for_thing = []
# all blocks are free are with value 0
blocks_left = boot_info['blocks_quantity']
set = 0
i = 0
checked = 0
while blocks_left:
#bitmap_byte read one byte at a time of the bitmap
bitmap_byte = image.read(1)
# checks each bit of the byte
for j in range(8):
if not blocks_left:
break
# checks if it is free and adds it to the list of free blocks
if (~bitmap_byte[0]) & (1 << 8-(j+1)):
free_blocks[set].append(i*8+j)
else:
if free_blocks[set]:
set += 1
free_blocks.append([])
blocks_left -= 1
for j in range(checked, len(free_blocks)):
if len(free_blocks[j]) >= blocks_needed:
blocks_for_thing += free_blocks[j][:blocks_needed]
blocks_for_thing.sort()
UpdateBitmap(image, boot_info, blocks_for_thing)
CreateBlocks(image, boot_info, blocks_for_thing)
return blocks_for_thing
checked = len(free_blocks[j]) - 1
i += 1
#sum all the elements inside free_blocks list
sum = 0
for i in range(len(free_blocks)):
sum += len(free_blocks[i])
if sum < blocks_needed:
exit("ERRO: Não houve espaço disponível na imagem. Operação interrompida!")
#sort the list of lists of free blocks by the size of the list
free_blocks.sort(key=len, reverse=True)
size_get = 0
for i in range(len(free_blocks)):
size_get_iteration = min(size - size_get, len(free_blocks[i]) * boot_info['block_size'] - 16)
size_get += size_get_iteration
blocks_get_iteration = ceil(size_get_iteration/boot_info['block_size'])
blocks_for_thing += free_blocks[i][:blocks_get_iteration]
if size_get >= size:
blocks_for_thing.sort()
UpdateBitmap(image, boot_info, blocks_for_thing)
CreateBlocks(image, boot_info, blocks_for_thing)
return blocks_for_thing
def CreateBlocks(image, boot_info, blocks_for_thing):
first_block = blocks_for_thing[0]
image = WalkImage(image, boot_info, first_block)
superblock_size = 1
for block in blocks_for_thing:
# keep counting the sequence for a superblock
if block == first_block + superblock_size:
superblock_size += 1
# if the sequence ended, write this superblock and go to the start of the next sequence
else:
image.write(int.to_bytes(block, 8, 'little'))
image.write(int.to_bytes(superblock_size, 8, 'little'))
superblock_size = 1
image.seek(block * boot_info['block_size'])
first_block = block
image.write(int.to_bytes(FF8BYTES, 8, 'little'))
image.write(int.to_bytes(superblock_size, 8, 'little'))
def ReadFreeMiniblocks(image, boot_info, miniblocks_needed, current_block):
next_block = 0
miniblocks_free = 0
first_miniblock_free = None
superblock_size = 0
while next_block != FF8BYTES:
next_block = int.from_bytes(image.read(8), 'little')
if current_block == 0:
superblock_size = boot_info['block_size']
size_left = boot_info['block_size'] - 32
else:
superblock_size = int.from_bytes(image.read(8), byteorder='little')
size_left = superblock_size * boot_info['block_size'] - 16
count = 0
while size_left:
# save miniblock as a list of 16 bytes
miniblock = image.read(16)
# check if the first byte is 00
if miniblock[0] == 0:
miniblocks_free += 1
if first_miniblock_free is None:
first_miniblock_free = count
else:
miniblocks_free = 0
first_miniblock_free = None
size_left -= 16
count += 1
if miniblocks_free == miniblocks_needed:
return miniblocks_free, first_miniblock_free, current_block, superblock_size
if next_block != FF8BYTES:
current_block = next_block
return miniblocks_free, first_miniblock_free, current_block, superblock_size
def WriteMiniBlock(image, type, size, block):
image.write(type)
image.write(int.to_bytes(size, 7, 'little'))
image.write(int.to_bytes(block, 8, 'little'))
def WriteMiniBlockName(image, text):
image.write(b'\x40')
image.write(text.encode('ASCII'))
image.write(b'\x00' * (15 - len(text)))
def CreateNewDir(image, boot_info, parent_block):
blocks = CreateBlockSet(image, boot_info, 80)
image = WalkImage(image, boot_info, blocks[0])
image.write(int.to_bytes(FF8BYTES, 8, 'little'))
image.write(int.to_bytes(1, 8, 'little'))
WriteMiniBlock(image, b'\x10', 0, blocks[0])
WriteMiniBlockName(image, ".")
WriteMiniBlock(image, b'\x10', 0, parent_block)
WriteMiniBlockName(image, "..")
return blocks[0]
def CreateDirectory(folder_content, cmd, image, boot_info):
dir_name = cmd[2:]
miniblocks_needed = 1 + (ceil(len(dir_name)/15))
blocks = None
dir_size_needed = miniblocks_needed * 16
# get the first byte and see if it is free, go on this until you find one
# check if it has enough, if it doesn't, ask to create more blocks with the next
# if you create a new one, then you need to update the next block(or check if you just allocated the next one and increase its size)
current_block = folder_content[0][2]
image = WalkImage(image, boot_info, folder_content[0][2])
if folder_content[0][2] == 0:
image.seek(24, 1)
miniblocks_free, first_miniblock_free, current_block, superblock_size = ReadFreeMiniblocks(image, boot_info, miniblocks_needed, current_block)
sequential = True
if miniblocks_free < miniblocks_needed:
# if you don't have enough, create more blocks
blocks = CreateBlockSet(image, boot_info, dir_size_needed - miniblocks_free * 16)
if blocks[0] == folder_content[0][2] + superblock_size:
image = WalkImage(image, boot_info, current_block)
x = int.from_bytes(image.read(8), 'little')
image.write((superblock_size + len(blocks)).to_bytes(8, byteorder='little'))
image = WalkImage(image, boot_info, blocks[0])
next_block = int.from_bytes(image.read(8), 'little')
superblock_size += int.from_bytes(image.read(8), byteorder='little')
image = WalkImage(image, boot_info, blocks[0])
image.write(int.to_bytes(0, 16, byteorder='little'))
image = WalkImage(image, boot_info, current_block)
image.write(int.to_bytes(next_block, 8, byteorder='little'))
image.write(int.to_bytes(superblock_size, 8, byteorder='little'))
else:
image = WalkImage(image, boot_info, current_block)
next_block = blocks[0]
if folder_content[0][2] == 0:
image.seek(24, 1)
image.write((next_block).to_bytes(8, byteorder='little'))
superblock_size = 1
else:
image.write((next_block).to_bytes(8, byteorder='little'))
superblock_size = int.from_bytes(image.read(8), byteorder='little')
sequential = False
# create the directory
first_block_new_dir = CreateNewDir(image, boot_info, folder_content[0][2])
name_len = len(dir_name)
if sequential:
# só escreve
offset = 16
if folder_content[0][2] == 0:
offset = 32
image.seek(current_block * boot_info['block_size'] + first_miniblock_free * 16 + offset)
WriteMiniBlock(image, b'\x10', 0, first_block_new_dir)
while name_len > 15:
WriteMiniBlockName(image, dir_name[:15])
dir_name = dir_name[15:]
name_len -= 15
WriteMiniBlockName(image, dir_name[:name_len])
else:
if folder_content[0][2] == 0:
if first_miniblock_free is None:
image = WalkImage(image, boot_info, next_block * boot_info['block_size'])
next_block = int.from_bytes(image.read(8), byteorder='little')
superblock_size = int.from_bytes(image.read(8), byteorder='little')
else:
image.seek(24)
next_block = int.from_bytes(image.read(8), byteorder='little')
superblock_size = 1
image.seek(first_miniblock_free * 16, 1)
else:
if first_miniblock_free is None:
image = WalkImage(image, boot_info, next_block * boot_info['block_size'])
next_block = int.from_bytes(image.read(8), byteorder='little')
superblock_size = int.from_bytes(image.read(8), byteorder='little')
else:
image = WalkImage(image, boot_info, current_block * boot_info['block_size'])
next_block = int.from_bytes(image.read(8), byteorder='little')
superblock_size = int.from_bytes(image.read(8), byteorder='little')
image.seek(first_miniblock_free * 16, 1)
WriteMiniBlock(image, b'\x10', 0, first_block_new_dir)
offset = 0
if folder_content[0][2] == 0:
offset = 1
size_left = superblock_size * boot_info['block_size'] - ((first_miniblock_free + 2 + offset) * 16)
while name_len >= 15:
if size_left == 0:
image = WalkImage(image, boot_info, next_block)
next_block = int.from_bytes(image.read(8), byteorder='little')
superblock_size = int.from_bytes(image.read(8), byteorder='little')
size_left = superblock_size * boot_info['block_size'] - 16
WriteMiniBlockName(image, dir_name[:min(15, size_left)])
dir_name = dir_name[15:]
name_len -= 15
size_left -= 16
image = WalkImage(image, boot_info, folder_content[0][2])
folder_content = Read_Folder(image, boot_info, folder_content[0][2] == 0)
ShowFolder(folder_content, image, boot_info)
def TransferToDisc(folder_content, cmd, image, boot_info):
# start all the variables needed
file = b''
file_number = int(cmd[2:])
super_block_begin = folder_content[file_number][2]
size_left = folder_content[file_number][1]
image = WalkImage(image, boot_info, super_block_begin)
# read all the blocks of the file and get the data in raw format
next_block = 0
while next_block != FF8BYTES and size_left:
next_block = int.from_bytes(image.read(8), 'little')
block_size = int.from_bytes(image.read(8), 'little')
read_block = block_size * boot_info['block_size'] # TO-DO: é - 16 ou nao?
size_taken = min(read_block, size_left)
file += image.read(size_taken)
size_left -= size_taken
# TO-DO: se importar em pedir se o usuário deseja que seja escrito little endian ou big endian antes de escrever?
# write file to disc as bytes
filename = input('Digite o nome do arquivo em que deseja salvar\n')
with open(filename, 'wb') as f:
f.write(file)
image = WalkImage(image, boot_info, folder_content[0][2])
folder_content = Read_Folder(image, boot_info, folder_content[0][2] == 0)
ShowFolder(folder_content, image, boot_info)
def WriteToSuperMini(folder_content, cmd, image, boot_info):
file_name = cmd[2:]
file_size = os.path.getsize(file_name)
#store position to insert miniblock
#go back one position due to Read_Folder extra read
folder_position = image.tell()
file_to_copy = open(file_name, 'rb')
block_sequence = CreateBlockSet(image, boot_info, file_size)
if block_sequence == None:
return
super_blocks = []
block_set = []
#Build super_blocks in a structure segemented insuperblocks and blocks
for block in range(len(block_sequence)):
block_set.append(block_sequence[block])
if len(block_sequence)-1 == block:
super_blocks.append(block_set[:])
block_set = []
elif block_sequence[block]+1 != block_sequence[block+1]:
super_blocks.append(block_set[:])
block_set = []
#Copia conteudo para os superblocos
for super_block in range(len(super_blocks)):
#go to beginning of superblock
image = WalkImage(image, boot_info, super_blocks[super_block][0])
#check if it is the last superblock
if len(super_blocks)-1 == super_block:
image.write(b'\xff\xff\xff\xff\xff\xff\xff\xff')
else:
image.write(super_blocks[super_block+1][0].to_bytes(1, 'little'))
image.write(len(super_blocks[super_block]).to_bytes(8,'little'))
space_left_in_superblock = len(super_blocks[super_block])*boot_info['block_size']-16
super_block_content = file_to_copy.read(space_left_in_superblock)
image.write(super_block_content)
#create file miniblock now that we have the first block
image.seek(folder_position)
image.write(b'\x20')
image.write(file_size.to_bytes(7, 'little'))
image.write(super_blocks[0][0].to_bytes(8, 'little'))
#store folder position gp go back after counting
folder_position = image.tell()
#count available space for the name in folder block
available_space_for_name = 0
while image.read(1) == b'\x00':
available_space_for_name += 15
image.read(15)
#if theres no space in superblock allocate space for the rest of it
estouro_de_nome = False
if available_space_for_name < len(file_name):
estouro_de_nome = True
extra_name_size = ceil((len(file_name)-available_space_for_name)/15)+(len(file_name)-available_space_for_name)
name_block_sequence = CreateBlockSet(image, boot_info, extra_name_size)
if name_block_sequence == None: return
#write name miniblocks
image.seek(folder_position)
name_miniblocks = [(file_name[i:i+15]) for i in range(0, len(file_name), 15)]
superblock_to_write = -1
for name_miniblock in name_miniblocks:
if image.read(1) != b'\x00':
WalkImage(image, boot_info, name_block_sequence[superblock_to_write])
#image.read(16)
image.write(int.to_bytes(FF8BYTES, 8, 'little'))
image.write(int.to_bytes(len(name_block_sequence), 8, 'little'))
else:
image.seek(image.tell()-1)
image.write(b'\x40')
image.write(bytes(name_miniblock, 'ASCII'))
image.write(b'\x00'*(15-len(name_miniblocks[-1])))
#update folder content
folder_content.append([file_name, file_size, super_blocks[0][0], b'\x20'])
if estouro_de_nome:
#set folder next superblock
WalkImage(image, boot_info, folder_content[0][2])
#test if it is root first block, skip bootrecord if it is, go back if its not
if image.read(7) == b'supmini':
image.read(17)
else:
image.seek(image.tell()-7)
image.write(name_block_sequence[0].to_bytes(8, byteorder='little'))
ShowFolder(folder_content, image, boot_info)
pass
def ShowFile(image, boot_info, folder_content, thing_index):
next_block = 0
size_in_bytes = folder_content[thing_index][1]
file_extension = folder_content[thing_index][0].split('.')
content = b''
while next_block != FF8BYTES:
next_block = int.from_bytes(image.read(8), 'little')
super_block_size = int.from_bytes(image.read(8), 'little')
size_left_in_block = boot_info['block_size'] * super_block_size - 16
content += image.read(min(size_in_bytes, size_left_in_block))
size_in_bytes -= size_left_in_block
print(content)
UserInterface(folder_content, image, boot_info)
pass
def WalkImage(image, boot_info, block):
image.seek(block * boot_info['block_size'])
return image
def CreateImage(image_name, blocks_quantity, block_size_log2):
block_size = int(2**block_size_log2)
image = open(image_name, 'wb')
image.write(b'supmini')
image.write(blocks_quantity.to_bytes(8, byteorder='little'))
image.write(block_size_log2.to_bytes(1, byteorder='little'))
boot_pointer = 0
image.write(boot_pointer.to_bytes(8, byteorder='little'))
root_next_block = FF8BYTES
image.write(root_next_block.to_bytes(8, byteorder='little'))
root_miniblock_atribute = 16
image.write(root_miniblock_atribute.to_bytes(16, byteorder='little'))
root_miniblock_name = 11840
image.write(root_miniblock_name.to_bytes(16, byteorder='little'))
size_left_in_block_0 = block_size - 64
image.write((0).to_bytes(size_left_in_block_0, byteorder='little'))
bitmap = '1'
bitmap_size_in_blocks = ceil(blocks_quantity/(8*block_size))
bitmap += '1'*bitmap_size_in_blocks
number_of_free_blocks = blocks_quantity - (bitmap_size_in_blocks+1)
bitmap += '0'*number_of_free_blocks
number_of_unusable_bitmap_bits = (bitmap_size_in_blocks*block_size*8)-len(bitmap)
bitmap += '1'*number_of_unusable_bitmap_bits
bitmap_int_value = int(bitmap,2)
bytes_used_in_bitmap_for_bitmap_blocks = ceil(len(bitmap)/8)
image.write(bitmap_int_value.to_bytes(bytes_used_in_bitmap_for_bitmap_blocks, byteorder='big'))
remaning_bytes = (blocks_quantity-(bitmap_size_in_blocks+1))*block_size
if remaning_bytes > 1048576: #se falta mais que 1 megabyte
print('Aguarde, formatação em andamento.')
batch_writes = remaning_bytes//1048576
batch = (0).to_bytes(1048576, byteorder='little')
for i in range(batch_writes):
if i%512==0:
print(f'{round((100*i)/batch_writes)}% concluída.')
image.write(batch)
final_bytes = remaning_bytes%1048576
if final_bytes!=0:
image.write((0).to_bytes(final_bytes, byteorder='little'))
print(f'100% concluída.')
else:
image.write((0).to_bytes(remaning_bytes, byteorder='little'))
print('Formatação realizada com sucesso. Aguarde para reiniciar a aplicação.')
image.close()
exit()
def CriarImagem():
image_name = input('Insira o nome da imagem que deseja criar com sufixo \'.img\'. Ex: \'teste.img\'\n')
print('Insira o número de blocos da imagem SuperMini.')
blocks_quantity = int(input('O número deve ser entre 4 e 2^64.\n'))
while blocks_quantity<4 or blocks_quantity>2**64:
blocks_quantity = int(input('O número deve ser entre 4 e 2^64.\n'))
print('\nInsira o expoente de 2 para o tamanho de bloco da imagem SuperMini.')
block_size = int(input('O número deve ser entre 9 (512 B/bloco) e 12 (4096 B/bloco).\n'))
while block_size<9 or block_size>12:
block_size = int(input('O número deve ser entre 9 (512 B/bloco) e 12 (4096 B/bloco).\n'))
CreateImage(image_name, blocks_quantity, block_size)
pass
def MenuFormat(boot_info):
size = boot_info['blocks_quantity']*boot_info['block_size']
current_size = 0
while current_size != size:
current_quantity = boot_info['blocks_quantity']
print(f'Insira o número de blocos da imagem SuperMini. (O atual número é de {current_quantity} blocos)')
blocks_quantity = int(input('O número deve ser entre 4 e 2^64.\n'))
while blocks_quantity<4 or blocks_quantity>2**64:
blocks_quantity = int(input('O número deve ser entre 4 e 2^64.\n'))
current_quantity = boot_info['block_size']
current_quantity_log2 = int(log2(current_quantity))
print(f'\nInsira o expoente de 2 para o tamanho de bloco da imagem SuperMini. (O atual tamanho é de 2^{current_quantity_log2} ({current_quantity} B/bloco))')
block_size = int(input('O número deve ser entre 9 (512 B/bloco) e 12 (4096 B/bloco).\n'))
while block_size<9 or block_size>12:
block_size = int(input('O número deve ser entre 9 (512 B/bloco) e 12 (4096 B/bloco).\n'))
current_size = blocks_quantity*(2**block_size)
if current_size!=size:
clear()
print(f'ERRO! O tamanho final do disco deve ser de {size} B! O tamanho informado é de {current_size} B.\n')
return blocks_quantity, block_size
def FormatImg(folder_content, cmd, image, boot_info):
print('ATENÇÃO: A imagem atual será formatada e todos os dados serão perdidos.')
choice = input('Deseja continuar? (S/N) ')
if choice.upper() != 'S':
ShowFolder(folder_content, image, boot_info)
else:
clear()
blocks_quantity, block_size = MenuFormat(boot_info)
current_image_name = image.name
image.close()
CreateImage(current_image_name, blocks_quantity, block_size)
pass
def RemoveInfo(block_begin, image, boot_info):
next_block = 0
current_block = block_begin
blocks_list = []
while next_block != FF8BYTES:
image.seek(current_block * boot_info['block_size'])
next_block = int.from_bytes(image.read(8), 'little')
block_size = int.from_bytes(image.read(8), 'little')
blocks_list += [x for x in range(current_block, current_block + block_size, 1)]
image.seek(current_block * boot_info['block_size'])
image.write((0).to_bytes(block_size * boot_info['block_size'], byteorder='little'))
current_block = next_block
return blocks_list
def RemoveContent(folder_content, file_number, image, boot_info):
offset = 0
if folder_content[0][2] == 0:
offset = 24
image.seek(folder_content[0][2] * boot_info['block_size'] + offset)
current_file = -1
next_block = 0
current_block = folder_content[0][2]
offset = 0
size_left = 0
while next_block != FF8BYTES:
next_block = int.from_bytes(image.read(8), 'little')
if current_block == 0:
block_size = 0
size_left = boot_info['block_size'] * block_size - 32
offset = 32
else:
block_size = int.from_bytes(image.read(8), 'little')
size_left = boot_info['block_size'] * block_size - 16
offset = 16
while size_left:
extension = image.read(1)
if extension == b'\x10' or extension == b'\x20':
current_file += 1
image.seek(15, 1)
if current_file == file_number:
break
size_left = -16
offset += 16
if current_file == file_number:
break
current_block = next_block
image.seek(current_block * boot_info['block_size'] + offset)
# achou o ponteiro inicial, agora continuar excluindo, se acabar o bloco, ir pro próximo
blocks_used = 1 + ceil(len(folder_content[file_number][0])/16)
while blocks_used:
image.write(b'\x80')
image.seek(15, 1)
blocks_used -= 1
size_left = -16
if size_left == 0:
image.seek(next_block * boot_info['block_size'])
next_block = int.from_bytes(image.read(8), 'little')
block_size = int.from_bytes(image.read(8), 'little')
size_left = boot_info['block_size'] * block_size - 16
def RemoveBitmap(image, blocks_list, boot_info):
for item in blocks_list:
image.seek(boot_info['block_size'] + (item)//8)
byte = image.read(1)
mask = ~(1 << 7 - (item)%8)
print(mask)
# stop the code
byte = byte[0] & ~(1 << 7 - (item)%8)
image.seek(-1, 1)
image.write(bytes([byte]))
def Remove(folder_content, cmd, image, boot_info):
if int (cmd[2:]) == 0:
print('ERRO! Não é possível remover o próprio diretório.')
UserInterface(folder_content, image, boot_info)
elif int (cmd[2:]) == 1 and folder_content[0][2] != 0:
print('ERRO! Não é possível remover o diretório anterior.')
UserInterface(folder_content, image, boot_info)
else:
print('ATENÇÃO: Os dados atuais serão perdidos.')
choice = input('Deseja continuar? (S/N) ')
blocks_list = []
if choice.upper() == 'S':
file_number = int(cmd[2:])
block_begin = folder_content[file_number][2]
if folder_content[file_number][3] == b'\x10':
image.seek(folder_content[file_number][2] * boot_info['block_size'])
content_inside = Read_Folder(image, boot_info, False)
if len(content_inside) > 2:
print('ERRO! Não é possível remover um diretório que contém arquivos.')
UserInterface(folder_content, image, boot_info)
return
RemoveContent(folder_content, file_number, image, boot_info)
blocks_list = RemoveInfo(block_begin, image, boot_info)
RemoveBitmap(image, blocks_list, boot_info)
image.seek(folder_content[0][2] * boot_info['block_size'])
folder_content = Read_Folder(image, boot_info, True if folder_content[0][2] == 0 else False)
ShowFolder(folder_content, image, boot_info)
def Fechar(folder_content, cmd, image, boot_info):
clear()
print('Obrigado por utilizar o SuperMini!')
now = datetime.now().time()
if now >= time(5,00) and now <= time(12,00):
print('++++++Tenha um ótimo dia!++++++')
elif now > time(12,00) and now <= time(18,00):
print('******Tenha uma ótima tarde!******')
else:
print('------Tenha uma ótima noite!------')
exit()
def ShowHelp(folder_content, cmd, image, boot_info):
clear()
print('Todos os comandos seguem a seguinte sintaxe: \'X args\'')
print('Substitua X pela letra correspondente ao comando desejada e args pelos parâmetros necessários ao comando.')
print('Não esqueça de colocar um espaço entre o comando e seus parâmetros!')
print()
print('Os seguintes comandos podem ser utilizados:')
print('A - Abrir arquivo/diretório. O parâmetro passado deve ser o índice exibido no diretório atual')
print(' Ex: A 12')
print('C - Criar diretório. O parâmetro passado deve ser o nome do diretório.')
print(' Ex: C nova_pasta')
print('R - Exclusão de arquivo/pasta. O parâmetro passado deve ser o índice exibido no diretório atual.')
print(' Ex: R 4')
print('E - Escrever um arquivo no SuperMini. O parâmetro deve ser o nome do arquivo a ser lido do disco para o SuperMini.')
print(' Ex: E teste.txt. ATENÇÃO: O arquivo a ser escrito no SuperMini deve se encontrar na mesma pasta que a aplicação')
print('F - Formatar. Nenhum parâmetro é passado.')
print(' Ex: F')
print('S - Sair. Encerra a aplicação. Nenhum parâmetro é passado.')
print(' Ex: S')
print('T - Transferir do SuperMini para o disco. O parâmetro deve ser o índice do arquivo a ser transferido.')
print(' Ex: T 12')
print()
back_input = input('Insira X para voltar ao diretório anterior.\n')
while back_input.upper() != 'X':
back_input = input('Insira X para voltar ao diretório anterior.\n')
ShowFolder(folder_content, image, boot_info)
pass
def UserInterface(folder_content, image, boot_info):
print('-------------------------------------------')
print('Insira um comando. Insira H para ver ajuda.')
commands = ['A', 'C', 'E', 'F', 'H', 'S', 'T', 'R']
#Abrir, Criar Diretorio, Escrever no SuperMini, Formatar, Transferir para disco
cmd = input()
while cmd[0].upper() not in commands or (cmd[0].upper()=='A' and int(cmd[2:])>=len(folder_content)):
cmd = input('Comando inválido. Digite novamente.\n')
command_dict = {
'A': OpenThing,
'C': CreateDirectory,
'E': WriteToSuperMini,
'R': Remove,
'F': FormatImg,
'H': ShowHelp,
'S': Fechar,
'T': TransferToDisc
}
command_dict[cmd[0].upper()](folder_content, cmd, image, boot_info)
pass
def Startup():
print('-'*27)
print('| BEM-VINDO AO SUPERMINI! |')
print('-'*27)
cmd = input('Insira a ação desejada:\nA - Abrir uma imagem\nC - Criar uma imagem\n')
while cmd.upper()!='A' and cmd.upper()!='C':
cmd = input('Comando inválido. Digite novamente.\n')
if cmd.upper() == 'A':
invalid_image = True
while invalid_image:
filename = input('Digite o nome da imagem SuperMini que deseja acessar\n')
while not exists(filename):
filename = input('Arquivo não encontrado!\n')
image = open(filename, 'rb+')
boot_info = read_boot(image)
if boot_info['name'] != b'supmini':
print('-'*91)
print('ERRO: A imagem selecionada não está formatada no sistema SuperMini! Selecione outra imagem.')
print('-'*91)
else:
invalid_image = False
root_content = Read_Folder(image, boot_info, True)
elif cmd.upper() == 'C':
CriarImagem()
return image, boot_info, root_content
def main():
image, boot_info, root_content = Startup()
ShowFolder(root_content, image, boot_info)
if '__main__' == __name__:
main()