forked from DRGN-DRC/Melee-Modding-Wizard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.py
2064 lines (1622 loc) · 81.7 KB
/
tools.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/python
# This file's encoding: UTF-8, so that non-ASCII characters can be used in strings.
#
# ███╗ ███╗ ███╗ ███╗ ██╗ ██╗ ------- -------
# ████╗ ████║ ████╗ ████║ ██║ ██║ # -=======---------------------------------------------------=======- #
# ██╔████╔██║ ██╔████╔██║ ██║ █╗ ██║ # ~ ~ Written by DRGN of SmashBoards (Daniel R. Cappel); May, 2020 ~ ~ #
# ██║╚██╔╝██║ ██║╚██╔╝██║ ██║███╗██║ # [ Built with Python v2.7.16 and Tkinter 8.5 ] #
# ██║ ╚═╝ ██║ ██║ ╚═╝ ██║ ╚███╔███╔╝ # -======---------------------------------------------------======- #
# ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ------ ------
# - - Melee Modding Wizard - -
# External dependencies
import os
import ttk
import time
import math
import codecs
import psutil
import win32gui
import subprocess
import win32process
import tkFileDialog
import Tkinter as Tk
from ruamel import yaml
from shutil import copy
from binascii import hexlify
from ScrolledText import ScrolledText
from PIL import ImageGrab, Image, ImageTk
# Internal dependencies
import globalData
import FileSystem.hsdStructures as hsdStructures
from newTkDnD.tkDnD import TkDnD
from FileSystem.disc import Disc
from codeMods import CodeLibraryParser
from FileSystem import CharCostumeFile
from basicFunctions import msg, saveAndShowTempFileData, uHex, cmdChannel, printStatus, humansize
from guiSubComponents import (
BasicWindow, CharacterColorChooser, ColoredLabelButton,
VerticalScrolledFrame, cmsg, Dropdown, exportSingleFileWithGui,
getNewNameFromUser, LabelButton )
#class NumberConverter( BasicWindow ):
class ImageDataLengthCalculator( BasicWindow ):
def __init__( self, root ):
BasicWindow.__init__( self, root, 'Image Data Length Calculator' )
# Set up the input elements
# Width
ttk.Label( self.window, text='Width:' ).grid( column=0, row=0, padx=5, pady=2, sticky='e' )
self.widthEntry = ttk.Entry( self.window, width=5, justify='center' )
self.widthEntry.grid( column=1, row=0, padx=5, pady=2 )
# Height
ttk.Label( self.window, text='Height:' ).grid( column=0, row=1, padx=5, pady=2, sticky='e' )
self.heightEntry = ttk.Entry( self.window, width=5, justify='center' )
self.heightEntry.grid( column=1, row=1, padx=5, pady=2 )
# Input Type
ttk.Label( self.window, text='Image Type:' ).grid( column=0, row=2, padx=5, pady=2, sticky='e' )
self.typeEntry = ttk.Entry( self.window, width=5, justify='center' )
self.typeEntry.grid( column=1, row=2, padx=5, pady=2 )
# Result Multiplier
ttk.Label( self.window, text='Result Multiplier:' ).grid( column=0, row=3, padx=5, pady=2, sticky='e' )
self.multiplierEntry = ttk.Entry( self.window, width=5, justify='center' )
self.multiplierEntry.insert( 0, '1' ) # Default
self.multiplierEntry.grid( column=1, row=3, padx=5, pady=2 )
# Bind the event listeners for calculating the result
for inputWidget in [ self.widthEntry, self.heightEntry, self.typeEntry, self.multiplierEntry ]:
inputWidget.bind( '<KeyRelease>', self.calculateResult )
# Set the output elements
ttk.Label( self.window, text='Required File or RAM space:' ).grid( column=0, row=4, columnspan=2, padx=20, pady=5 )
# In hex bytes
self.resultEntryHex = ttk.Entry( self.window, width=20, justify='center' )
self.resultEntryHex.grid( column=0, row=5, padx=5, pady=5 )
ttk.Label( self.window, text='bytes (hex)' ).grid( column=1, row=5, padx=5, pady=5 )
# In decimal bytes
self.resultEntryDec = ttk.Entry( self.window, width=20, justify='center' )
self.resultEntryDec.grid( column=0, row=6, padx=5, pady=5 )
ttk.Label( self.window, text='(decimal)' ).grid( column=1, row=6, padx=5, pady=5 )
def calculateResult( self, event ):
try:
widthValue = self.widthEntry.get()
if not widthValue: return
elif '0x' in widthValue: width = int( widthValue, 16 )
else: width = int( widthValue )
heightValue = self.heightEntry.get()
if not heightValue: return
elif '0x' in heightValue: height = int( heightValue, 16 )
else: height = int( heightValue )
typeValue = self.typeEntry.get()
if not typeValue: return
elif '0x' in typeValue: _type = int( typeValue, 16 )
else: _type = int( typeValue )
multiplierValue = self.multiplierEntry.get()
if not multiplierValue: return
elif '0x' in multiplierValue: multiplier = int( multiplierValue, 16 )
else: multiplier = float( multiplierValue )
# Calculate the final amount of space required.
imageDataLength = hsdStructures.ImageDataBlock.getDataLength( width, height, _type )
finalSize = int( math.ceil(imageDataLength * multiplier) ) # Can't have fractional bytes, so we're rounding up
self.resultEntryHex.delete( 0, 'end' )
self.resultEntryHex.insert( 0, uHex(finalSize) )
self.resultEntryDec.delete( 0, 'end' )
self.resultEntryDec.insert( 0, humansize(finalSize) )
except:
self.resultEntryHex.delete( 0, 'end' )
self.resultEntryHex.insert( 0, 'Invalid Input' )
self.resultEntryDec.delete( 0, 'end' )
class AsmToHexConverter( BasicWindow ):
""" Tool window to convert assembly to hex and vice-verca. """
def __init__( self, mod=None ):
BasicWindow.__init__( self, globalData.gui.root, 'ASM <-> HEX Converter', offsets=(160, 100), resizable=True, topMost=False, minsize=(460, 350) )
# Display info and a few controls
topRow = ttk.Frame( self.window )
ttk.Label( topRow, text=('This assembles PowerPC assembly code into raw hex,\nor disassembles raw hex into PowerPC assembly.'
#"\n\nNote that this functionality is also built into the entry fields for new code in the 'Add New Mod to Library' interface. "
#'So you can use your assembly source code in those fields and it will automatically be converted to hex during installation. '
'\nComments preceded with "#" will be ignored.'), wraplength=480 ).grid( column=0, row=0, rowspan=4 )
ttk.Label( topRow, text='Beautify Hex:' ).grid( column=1, row=0 )
options = [ '1 Word Per Line', '2 Words Per Line', '3 Words Per Line', '4 Words Per Line', '5 Words Per Line', '6 Words Per Line', 'No Whitespace' ]
Dropdown( topRow, options, default=options[1], command=self.beautifyChanged ).grid( column=1, row=1 )
self.assembleSpecialSyntax = Tk.BooleanVar( value=False )
ttk.Checkbutton( topRow, text='Assemble Special Syntax', variable=self.assembleSpecialSyntax ).grid( column=1, row=2, pady=5 )
self.assemblyDetectedLabel = ttk.Label( topRow, text='Assembly Detected: ' ) # Leave space for true/false string
self.assemblyDetectedLabel.grid( column=1, row=3 )
topRow.grid( column=0, row=0, padx=40, pady=(7, 7), sticky='ew' )
# Configure the top row, so it expands properly on window-resize
topRow.columnconfigure( 0, weight=1, minsize=400 )
topRow.columnconfigure( 0, weight=1 )
self.lengthString = Tk.StringVar( value='' )
self.mod = mod
self.syntaxInfo = []
self.isAssembly = False
self.blocksPerLine = 2
# Create the header row
headersRow = ttk.Frame( self.window )
ttk.Label( headersRow, text='ASM' ).grid( row=0, column=0, sticky='w' )
ttk.Label( headersRow, textvariable=self.lengthString ).grid( row=0, column=1 )
ttk.Label( headersRow, text='HEX' ).grid( row=0, column=2, sticky='e' )
headersRow.grid( column=0, row=1, padx=40, pady=(7, 0), sticky='ew' )
# Configure the header row, so it expands properly on window-resize
headersRow.columnconfigure( 'all', weight=1 )
# Create the text entry fields and center conversion buttons
entryFieldsRow = ttk.Frame( self.window )
self.sourceCodeEntry = ScrolledText( entryFieldsRow, width=30, height=20 )
self.sourceCodeEntry.grid( rowspan=2, column=0, row=0, padx=5, pady=7, sticky='news' )
ttk.Button( entryFieldsRow, text='->', command=self.asmToHexCode ).grid( column=1, row=0, pady=30, sticky='s' )
ttk.Button( entryFieldsRow, text='<-', command=self.hexCodeToAsm ).grid( column=1, row=1, pady=30, sticky='n' )
self.hexCodeEntry = ScrolledText( entryFieldsRow, width=30, height=20 )
self.hexCodeEntry.grid( rowspan=2, column=2, row=0, padx=5, pady=7, sticky='news' )
entryFieldsRow.grid( column=0, row=2, sticky='nsew' )
# Configure the above columns, so that they expand proportionally upon window resizing
entryFieldsRow.columnconfigure( 0, weight=1 )
entryFieldsRow.columnconfigure( 1, weight=0 ) # No weight to this row, since it's just the buttons
entryFieldsRow.columnconfigure( 2, weight=1 )
entryFieldsRow.rowconfigure( 'all', weight=1 )
bottomRow = ttk.Frame( self.window )
# Add the assembly time display (as an Entry widget so we can select text from it)
self.assemblyTimeDisplay = Tk.Entry( bottomRow, width=25, borderwidth=0 )
self.assemblyTimeDisplay.configure( state="readonly" )
self.assemblyTimeDisplay.grid( column=0, row=0, sticky='w', padx=(25, 0) )
# Determine the include paths to be used here, and add a button at the bottom of the window to display them
self.detectContext()
ttk.Button( bottomRow, text='View Include Paths', command=self.viewIncludePaths ).grid( column=1, row=0, ipadx=7 )
#ttk.Button( bottomRow, text='Save Hex to File', command=self.saveHexToFile ).grid( column=2, row=0, ipadx=7, sticky='e', padx=40 )
buttonsFrame = ttk.Frame( bottomRow )
ColoredLabelButton( buttonsFrame, 'saveToFile', self.saveHexToFile, 'Save Hex to File' ).pack( side='right', padx=8 )
ColoredLabelButton( buttonsFrame, 'saveToClipboard', self.copyHexToClipboard, 'Copy Hex to Clipboard' ).pack( side='right', padx=8 )
buttonsFrame.grid( column=2, row=0, ipadx=7, sticky='e', padx=40 )
bottomRow.grid( column=0, row=3, pady=(2, 6), sticky='ew' )
bottomRow.columnconfigure( 'all', weight=1 )
# Add the assembly time display (as an Entry widget so we can select text from it)
# self.assemblyTimeDisplay = Tk.Entry( self.window, width=25, borderwidth=0 )
# self.assemblyTimeDisplay.configure( state="readonly" )
# self.assemblyTimeDisplay.place( x=10, rely=1.0, y=-27 )
# # Determine the include paths to be used here, and add a button at the bottom of the window to display them
# self.detectContext()
# ttk.Button( self.window, text='View Include Paths', command=self.viewIncludePaths ).grid( column=0, row=3, pady=(2, 6), ipadx=7 )
# ttk.Button( self.window, text='Save Hex to File', command=self.saveHexToFile ).place( relx=1.0, rely=1.0, x=-150, y=-31 )
# Configure this window's expansion as a whole, so that only the text entry row can expand when the window is resized
self.window.columnconfigure( 0, weight=1 )
self.window.rowconfigure( 0, weight=0 )
self.window.rowconfigure( 1, weight=0 )
self.window.rowconfigure( 2, weight=1 )
self.window.rowconfigure( 3, weight=0 )
def updateAssemblyTimeDisplay( self, textInput ):
self.assemblyTimeDisplay.configure( state="normal" )
self.assemblyTimeDisplay.delete( 0, 'end' )
self.assemblyTimeDisplay.insert( 0, textInput )
self.assemblyTimeDisplay.configure( state="readonly" )
def asmToHexCode( self ):
# Clear the hex code field and info labels
self.hexCodeEntry.delete( '1.0', 'end' )
self.updateAssemblyTimeDisplay( '' )
self.lengthString.set( 'Length: ' )
self.assemblyDetectedLabel['text'] = 'Assembly Detected: '
# Get the ASM to convert
asmCode = self.sourceCodeEntry.get( '1.0', 'end' )
# Evaluate the code and pre-process it (scan it for custom syntaxes and assemble everything else)
tic = time.clock()
results = globalData.codeProcessor.evaluateCustomCode( asmCode, self.includePaths, validateConfigs=False )
returnCode, codeLength, hexCode, self.syntaxInfo, self.isAssembly = results
toc = time.clock()
# Check for errors (hexCode should include warnings from the assembler)
if returnCode not in ( 0, 100 ):
cmsg( hexCode, 'Assembly Error', parent=self.window )
return
# Swap back in custom sytaxes
if self.syntaxInfo and not self.assembleSpecialSyntax.get():
hexCode = globalData.codeProcessor.restoreCustomSyntaxInHex( hexCode, self.syntaxInfo, codeLength, self.blocksPerLine )
# Beautify and insert the new hex code
elif self.blocksPerLine > 0:
hexCode = globalData.codeProcessor.beautifyHex( hexCode, blocksPerLine=self.blocksPerLine )
self.hexCodeEntry.insert( 'end', hexCode )
# Update the code length display
self.lengthString.set( 'Length: ' + uHex(codeLength) )
if self.isAssembly:
self.assemblyDetectedLabel['text'] = 'Assembly Detected: True '
else:
self.assemblyDetectedLabel['text'] = 'Assembly Detected: False'
# Update the assembly time display with appropriate units
assemblyTime = round( toc - tic, 9 )
if assemblyTime > 1:
units = 's' # In seconds
else:
assemblyTime = assemblyTime * 1000
if assemblyTime > 1:
units = 'ms' # In milliseconds
else:
assemblyTime = assemblyTime * 1000
units = 'us' # In microseconds
self.updateAssemblyTimeDisplay( 'Assembly Time: {} {}'.format(assemblyTime, units) )
def hexCodeToAsm( self ):
# Delete the current assembly code, and clear the assembly time label
self.sourceCodeEntry.delete( '1.0', 'end' )
self.updateAssemblyTimeDisplay( '' )
self.assemblyDetectedLabel['text'] = 'Assembly Detected: '
# Get the HEX code to disassemble
hexCode = self.hexCodeEntry.get( '1.0', 'end' )
# Evaluate the code and pre-process it (scan it for custom syntaxes)
results = globalData.codeProcessor.evaluateCustomCode( hexCode, self.includePaths, validateConfigs=False )
returnCode, codeLength, hexCode, self.syntaxInfo, self.isAssembly = results
if returnCode != 0:
self.lengthString.set( 'Length: ' )
return
# Disassemble the code into assembly
asmCode, errors = globalData.codeProcessor.disassemble( hexCode )
if errors:
cmsg( errors, 'Disassembly Error', parent=self.window )
return
if self.syntaxInfo and not self.assembleSpecialSyntax.get():
asmCode = self.restoreCustomSyntaxInAsm( asmCode )
# Replace the current assembly code
self.sourceCodeEntry.insert( 'end', asmCode )
# Update the code length display
self.lengthString.set( 'Length: ' + uHex(codeLength) )
if self.isAssembly:
self.assemblyDetectedLabel['text'] = 'Assembly Detected: True '
else:
self.assemblyDetectedLabel['text'] = 'Assembly Detected: False'
def restoreCustomSyntaxInAsm( self, asmLines ):
""" Swap out assembly code for the original custom syntax line that it came from. """
# Build a new list of ( offset, wordString ) so we can separate words included on the same line
specialWords = []
for offset, length, syntaxType, codeLine, names in self.syntaxInfo:
if syntaxType == 'sbs' or syntaxType == 'sym':
specialWords.append( (offset, length, syntaxType, codeLine) )
else:
# Extract names (eliminating whitespace associated with names) and separate hex groups
sectionChunks = codeLine.split( '[[' )
for i, chunk in enumerate( sectionChunks ):
if ']]' in chunk:
varName, chunk = chunk.split( ']]' )
sectionChunks[i] = '[[]]' + chunk
# Recombine the string and split on whitespace
newLine = ''.join( sectionChunks )
hexGroups = newLine.split() # Will now have something like [ '000000[[]]' ] or [ '40820008', '0000[[]]' ]
# Process each hex group
nameIndex = 0
groupParts = []
for group in hexGroups:
if ']]' in group:
specialWords.append( (offset, length, syntaxType, group.replace('[[]]', '[['+names[nameIndex]+']]')) )
nameIndex += 1
newLines = []
offset = 0
for line in asmLines.splitlines():
if specialWords and offset + 4 > specialWords[0][0]:
info = specialWords.pop( 0 )
if info[2] == 'opt':
length = info[1]
if length == 4:
newLines.append( '.long ' + info[3] )
elif length == 2:
newLines.append( '.word ' + info[3] )
else:
newLines.append( '.byte ' + info[3] )
else:
newLines.append( info[3] )
else:
newLines.append( line )
offset += 4
return '\n'.join( newLines )
def detectContext( self ):
""" This window should use the same .include context for whatever mod it was opened with.
If an associated mod is not found, fall back on the default import directories. """
if self.mod:
self.includePaths = self.mod.includePaths
else:
libraryFolder = globalData.getModsFolderPath()
self.includePaths = [ os.path.join(libraryFolder, '.include'), os.path.join(globalData.scriptHomeFolder, '.include') ]
def viewIncludePaths( self ):
""" Build and display a message to the user on assembly context and current paths. """
# Build the message to show the user
paths = [ os.getcwd() + ' <- Current Working Directory' ]
paths.extend( self.includePaths )
paths = '\n'.join( paths )
message = ( 'Assembly context (for ".include" file imports) has the following priority:'
"\n\n1) The current working directory (usually the program root folder)"
"\n2) Directory of the mod's code file (or the code's root folder with AMFS)"
"""\n3) The current Code Library's ".include" directory"""
"""\n4) The program root folder's ".include" directory""" )
if self.mod:
message += ( '\n\n\nThis instance of the converter is using assembly context for .include file imports based on {}. '
'The exact paths are as follows:\n\n{}'.format( self.mod.name, paths ) )
else:
message += ( '\n\n\nThis instance of the converter is using default assembly context for .include file imports. '
'The exact paths are as follows:\n\n' + paths )
cmsg( message, 'Include Paths', 'left', parent=self.window )
def saveHexToFile( self, event=None ):
""" Prompts the user for a save location, and then saves the hex code to file as binary. """
# Get the hex code and remove whitespace
hexCode = self.hexCodeEntry.get( '1.0', 'end' )
hexCode = ''.join( hexCode.split() )
if not hexCode:
msg( 'No hex code to save!', 'No Hex Code', warning=True, parent=self.window )
return
savePath = tkFileDialog.asksaveasfilename(
title="Where would you like to export the file?",
parent=self.window,
initialdir=globalData.getLastUsedDir(),
initialfile='Bin.bin',
defaultextension='bin',
filetypes=[( "Binary files", '*.bin' ), ( "Data archive files", '*.dat' ), ( "All files", "*.*" )] )
# The above will return an empty string if the user canceled
if not savePath:
globalData.gui.updateProgramStatus( 'File save canceled' )
return
# Save the hex code to file as binary
try:
with open( savePath, 'wb' ) as binFile:
binFile.write( bytearray.fromhex(hexCode) )
globalData.gui.updateProgramStatus( 'File saved to "{}"'.format(savePath) )
except IOError as e: # Couldn't create the file (likely a permission issue)
msg( 'Unable to create "' + savePath + '" file! This is likely due to a permissions issue. You might try saving to somewhere else.', 'Error', parent=self.window )
globalData.gui.updateProgramStatus( 'Unable to save; could not create the file at the destination' )
except ValueError as e: # Couldn't convert the hex to a bytearray
msg( 'Unable to convert the hex to binary; you may want to check for illegal characters.', 'Error', parent=self.window )
globalData.gui.updateProgramStatus( 'Unable to save; hex string could not be converted to bytearray' )
def copyHexToClipboard( self, event=None ):
hexCode = self.hexCodeEntry.get( '1.0', 'end' )
globalData.gui.root.clipboard_clear()
globalData.gui.root.clipboard_append( hexCode )
def _flushBuffer( self, pureHexBuffer, newLines ):
""" Helper method to the beautify update method below; this dumps hex code
that has been collected so far into the newLines list (properly formatted). """
if pureHexBuffer:
# Combine the hex collected so far into one string, and beautify it if needed
pureHex = ''.join( pureHexBuffer )
if self.blocksPerLine > 0:
pureHex = globalData.codeProcessor.beautifyHex( pureHex, blocksPerLine=self.blocksPerLine )
# Store hex and clear the hex buffer
newLines.append( pureHex )
pureHexBuffer = []
return pureHexBuffer, newLines
def beautifyChanged( self, widget, newValue ):
""" Called when the Beautify Hex dropdown option is changed.
Reformats the HEX output to x number of words per line. """
# Parse the current dropdown option for a block count
try:
self.blocksPerLine = int( newValue.split()[0] )
except:
self.blocksPerLine = 0
# Get hex code currently displayed if there is any
hexCode = self.hexCodeEntry.get( '1.0', 'end' )
if not hexCode: return
# Clear the hex code field and info labels
self.hexCodeEntry.delete( '1.0', 'end' )
newLines = []
pureHexBuffer = []
customSyntaxFound = False
for rawLine in hexCode.splitlines():
# Start off by filtering out comments, and skip empty lines
codeLine = rawLine.split( '#' )[0].strip()
if not codeLine: continue
elif CodeLibraryParser.isSpecialBranchSyntax( codeLine ): # e.g. "bl 0x80001234" or "bl <testFunction>"
customSyntaxFound = True
elif CodeLibraryParser.containsPointerSymbol( codeLine ): # Identifies symbols in the form of <<functionName>>
customSyntaxFound = True
elif '[[' in codeLine and ']]' in codeLine: # Identifies configuration option placeholders
customSyntaxFound = True
else:
customSyntaxFound = False
if customSyntaxFound:
pureHexBuffer, newLines = self._flushBuffer( pureHexBuffer, newLines )
newLines.append( codeLine )
else:
# Strip out whitespace and store the line
pureHex = ''.join( codeLine.split() )
pureHexBuffer.append( pureHex )
newLines = self._flushBuffer( pureHexBuffer, newLines )[1]
# Collapse the code lines to a string and reinsert it into the text widget
hexCode = '\n'.join( newLines )
self.hexCodeEntry.insert( 'end', hexCode )
class CodeLookup( BasicWindow ):
def __init__( self ):
BasicWindow.__init__( self, globalData.gui.root, 'Code Lookup', resizable=True, minsize=(520, 300) )
pady = 6
mainFrame = ttk.Frame( self.window )
controlPanel = ttk.Frame( mainFrame )
# Set up offset/address input
ttk.Label( controlPanel, text='Enter a DOL Offset or RAM Address:' ).grid( column=0, row=0, columnspan=2, padx=5, pady=(25, pady) )
validationCommand = globalData.gui.root.register( self.locationUpdated )
self.location = Tk.Entry( controlPanel, width=13,
justify='center',
relief='flat',
highlightbackground='#b7becc', # Border color when not focused
borderwidth=1,
highlightthickness=1,
highlightcolor='#0099f0',
validate='key',
validatecommand=(validationCommand, '%P') )
self.location.grid( column=0, row=1, columnspan=2, padx=5, pady=pady )
self.location.bind( "<KeyRelease>", self.initiateSearch )
ttk.Label( controlPanel, text='Function Name:' ).grid( column=0, row=2, columnspan=2, padx=30, pady=(pady, 0), sticky='w' )
self.name = Tk.Text( controlPanel, width=40, height=3, state="disabled" )
self.name.grid( column=0, row=3, columnspan=2, sticky='ew', padx=5, pady=pady )
ttk.Label( controlPanel, text='DOL Offset:' ).grid( column=0, row=4, padx=5, pady=pady )
self.dolOffset = Tk.Entry( controlPanel, width=24, borderwidth=0, state="disabled" )
self.dolOffset.grid( column=1, row=4, sticky='w', padx=(7, 0) )
ttk.Label( controlPanel, text='RAM Address:' ).grid( column=0, row=5, padx=5, pady=pady )
self.ramAddr = Tk.Entry( controlPanel, width=24, borderwidth=0, state="disabled" )
self.ramAddr.grid( column=1, row=5, sticky='w', padx=(7, 0) )
ttk.Label( controlPanel, text='Length:' ).grid( column=0, row=6, padx=5, pady=pady )
self.length = Tk.Entry( controlPanel, width=8, borderwidth=0, state="disabled" )
self.length.grid( column=1, row=6, sticky='w', padx=(7, 0) )
ttk.Label( controlPanel, text='Includes\nCustom Code:', justify='center' ).grid( column=0, row=7, padx=5, pady=pady )
self.hasCustomCode = Tk.StringVar()
ttk.Label( controlPanel, textvariable=self.hasCustomCode ).grid( column=1, row=7, sticky='w', padx=(7, 0) )
controlPanel.grid( column=0, row=0, rowspan=2, padx=4, sticky='n' )
ttk.Label( mainFrame, text='Function Code:' ).grid( column=1, row=0, padx=42, pady=2, sticky='ew' )
self.code = ScrolledText( mainFrame, width=28, state="disabled" )
self.code.grid( column=1, row=1, rowspan=2, sticky='nsew', padx=(12, 0) )
mainFrame.pack( expand=True, fill='both' )
# Configure this window's resize behavior
mainFrame.columnconfigure( 0, weight=0 )
mainFrame.columnconfigure( 1, weight=1 )
mainFrame.rowconfigure( 0, weight=0 )
mainFrame.rowconfigure( 1, weight=1 )
# Get and load a DOL file for reference
if globalData.disc:
self.dol = globalData.disc.dol
self.dolIsVanilla = False
gameId = globalData.disc.gameId
else:
# Get the vanilla disc path
vanillaDiscPath = globalData.getVanillaDiscPath()
if not vanillaDiscPath: # todo: add warning here
return
vanillaDisc = Disc( vanillaDiscPath )
vanillaDisc.loadGameCubeMediaFile()
gameId = vanillaDisc.gameId
self.dol = vanillaDisc.dol
self.dolIsVanilla = True
self.dol.load()
# Collect function symbols info from the map file
symbolMapPath = os.path.join( globalData.paths['maps'], gameId + '.map' )
with open( symbolMapPath, 'r' ) as mapFile:
self.symbols = mapFile.read()
self.symbols = self.symbols.splitlines()
def updateEntry( self, widget, textInput ):
widget.configure( state="normal" )
widget.delete( 0, 'end' )
widget.insert( 0, textInput )
widget.configure( state="readonly" )
def updateScrolledText( self, widget, textInput ):
""" For Text or ScrolledText widgets. """
widget.configure( state="normal" )
widget.delete( 1.0, 'end' )
widget.insert( 1.0, textInput )
widget.configure( state="disabled" )
# def clearControlPanel( self ):
# self.dolOffset.configure( state="normal" )
# self.dolOffset.delete( 0, 'end' )
# self.dolOffset.configure( state="readonly" )
# self.ramAddr.configure( state="normal" )
# self.ramAddr.delete( 0, 'end' )
# self.ramAddr.configure( state="readonly" )
# self.length.configure( state="normal" )
# self.length.delete( 0, 'end' )
# self.length.configure( state="readonly" )
def locationUpdated( self, locationString ):
""" Validates text input into the offset/address entry field, whether entered
by the user or programmatically. Ensures there are only hex characters.
If there are hex characters, this function will deny them from being entered. """
try:
if not locationString: # Text erased
return True
# Attempt to convert the hex string to decimal
int( locationString, 16 )
return True
except:
return False
def initiateSearch( self, event ):
locationString = self.location.get().strip().lstrip( '0x' )
# Get both the DOL offset and RAM address
cancelSearch = False
try:
if len( locationString ) == 8 and locationString.startswith( '8' ):
address = int( locationString, 16 )
offset = self.dol.offsetInDOL( address )
if address > self.dol.maxRamAddress:
cancelSearch = True
else:
offset = int( locationString, 16 )
address = self.dol.offsetInRAM( offset )
if offset < 0x100:
cancelSearch = True
except:
cancelSearch = True
if cancelSearch:
self.updateScrolledText( self.name, '' )
self.updateScrolledText( self.code, '' )
self.updateEntry( self.dolOffset, '' )
self.updateEntry( self.ramAddr, '' )
self.updateEntry( self.length, '' )
self.hasCustomCode.set( '' )
return
elif offset == -1:
self.updateScrolledText( self.name, '' )
self.updateScrolledText( self.code, '{} not found in the DOL'.format(self.location.get().strip()) )
self.updateEntry( self.dolOffset, '' )
self.updateEntry( self.ramAddr, '' )
self.updateEntry( self.length, '' )
self.hasCustomCode.set( '' )
return
# Look up info on this function in the map file
for i, line in enumerate( self.symbols ):
line = line.strip()
if not line or line.startswith( '.' ):
continue
# Parse the line (split on only the first 4 instances of a space)
functionStart, length, _, _, symbolName = line.split( ' ', 4 )
functionStart = int( functionStart, 16 )
length = int( length, 16 )
# Check if this is the target function
if address >= functionStart and address < functionStart + length:
dolFunctionStart = self.dol.offsetInDOL( functionStart )
break
else: # Above loop didn't break; symbol not found
self.updateScrolledText( self.name, '' )
self.updateScrolledText( self.code, 'Unable to find {} in the map file'.format(self.location.get().strip()) )
self.updateEntry( self.dolOffset, '' )
self.updateEntry( self.ramAddr, '' )
self.updateEntry( self.length, '' )
self.hasCustomCode.set( 'N/A' )
return
self.updateScrolledText( self.name, symbolName )
self.updateEntry( self.dolOffset, uHex(dolFunctionStart) + ' - ' + uHex(dolFunctionStart+length) )
self.updateEntry( self.ramAddr, uHex(functionStart) + ' - ' + uHex(functionStart+length) )
self.updateEntry( self.length, uHex(length) )
# Get the target function as a hex string
functionCode = self.dol.getData( dolFunctionStart, length )
hexCode = hexlify( functionCode )
# Disassemble the code into assembly
asmCode, errors = globalData.codeProcessor.disassemble( hexCode )
if errors:
self.updateScrolledText( self.code, 'Disassembly Error:\n\n' + errors )
else:
self.updateScrolledText( self.code, asmCode )
# Update text displaying whether this is purely vanilla code
if self.dolIsVanilla:
self.hasCustomCode.set( 'No' )
else: # todo
self.hasCustomCode.set( 'Unknown' )
class TriCspCreator( object ):
installationFolders = (
"C:\\Program Files\\GIMP 2\\bin",
"{}\\Programs\\GIMP 2\\bin".format(os.environ['LOCALAPPDATA'])
)
def __init__( self ):
self.config = {}
self.gimpDir = ''
self.gimpExe = ''
# Analyze the version of GIMP installed
self.checkGimpPath()
self.checkGimpProgramVersion()
self.checkGimpPluginDirectory()
# Update installed scripts (then no need to check version)
# todo
# Delete old GIMP .pyc plugins (I don't think GIMP will automatically re-build them if the scripts are updated)
# todo
# Double-check plugin versions
self.createCspScriptVersion = self.getScriptVersion( self.pluginDir, 'python-fu-create-tri-csp.py' )
self.finishCspScriptVersion = self.getScriptVersion( self.pluginDir, 'python-fu-finish-csp.py' )
# Load the CSP Configuration file, and assemble other needed paths
try:
self.triCspFolder = globalData.paths['triCsps']
self.pluginsFolder = os.path.join( self.triCspFolder, 'GIMP plug-ins' )
configFilePath = os.path.join( self.triCspFolder, 'CSP Configuration.yml' )
configFileName = os.path.basename( configFilePath )
# Read the config file (this method should allow for utf-8 encoding, and preserve comments when saving/dumping back to file)
with codecs.open( configFilePath, 'r', encoding='utf-8' ) as stream:
self.config = yaml.load( stream, Loader=yaml.RoundTripLoader )
self.settingsFiles = [
os.path.join( self.triCspFolder, 'Debugger.ini' ),
os.path.join( self.triCspFolder, 'Dolphin.ini' ),
os.path.join( self.triCspFolder, 'GFX.ini' )
]
self.configLoadErr = ''
except IOError: # Couldn't find the configuration file
self.configLoadErr = """Couldn't find the CSP config file at "{}".""".format( configFilePath )
except Exception as err: # Problem parsing the file
self.configLoadErr = 'There was an error while parsing the {} file:\n\n{}'.format(configFileName, err)
# Print out version info
print( '' )
print( ' Tri-CSP Creator version info:' )
print( ' GIMP: ' + self.gimpVersion )
print( ' create-tri-csp script: ' + self.createCspScriptVersion )
print( ' finish-csp script: ' + self.finishCspScriptVersion )
print( '' )
print( 'GIMP executable directory: ' + self.gimpDir )
print( 'GIMP Plug-ins directory: ' + self.pluginDir )
print( '' )
if self.configLoadErr:
print( self.configLoadErr )
else:
print( 'Tri-CSP Configuration file loaded successfully.' )
def initError( self ):
""" Assesses how the initialization methods went to determine if there are any problems.
If there are any problems, an error message will be returned. Returns an empty string on success. """
errorMsg = ''
if not self.gimpDir:
errorMsg = ( 'GIMP does not appear to be installed; '
'unable to find program folder among these paths:\n\n' + '\n'.join(self.installationFolders) )
elif not self.gimpExe:
errorMsg = 'Unable to find the GIMP console executable in "{}".'.format( self.gimpDir )
elif self.configLoadErr: # Unable to load the CSP configuration file
errorMsg = self.configLoadErr
elif self.createCspScriptVersion != '2.1' or self.finishCspScriptVersion != '2.3': #todo: remove hardcoding!
errorMsg = 'Differing versions of the GIMP plug-in scripts detected!'
return errorMsg
def checkGimpPath( self ):
""" Determines the absolute file path to the GIMP console executable
(the exe filename varies based on program version). """
# Check for the GIMP program folder
for directory in self.installationFolders:
if os.path.exists( directory ):
self.gimpDir = directory
break
else: # The loop above din't break; folders not found
self.gimpDir = ''
self.gimpExe = ''
return
# Check the files in the program folder for a 'console' executable
for fileOrFolderName in os.listdir( directory ):
if fileOrFolderName.startswith( 'gimp-console' ) and fileOrFolderName.endswith( '.exe' ):
self.gimpExe = fileOrFolderName
return
else: # The loop above didn't break; unable to find the exe
self.gimpDir = ''
self.gimpExe = ''
return
def checkGimpProgramVersion( self ):
returnCode, versionText = cmdChannel( '"{}\{}" --version'.format(self.gimpDir, self.gimpExe) )
if returnCode == 0:
self.gimpVersion = versionText.split()[-1]
else:
print( versionText ) # Should be an error message in this case
self.gimpVersion = '-1'
def checkGimpPluginDirectory( self ):
""" Checks known directory paths for GIMP versions 2.8 and 2.10. If both appear
to be installed, we'll check the version of the executable that was found. """
userFolder = os.path.expanduser( '~' ) # Resolves to "C:\Users\[userName]"
v8_Path = os.path.join( userFolder, '.gimp-2.8\\plug-ins' )
v10_Path = os.path.join( userFolder, 'AppData\\Roaming\\GIMP\\2.10\\plug-ins' )
if os.path.exists( v8_Path ) and os.path.exists( v10_Path ):
# Both versions seem to be installed. Use Gimp's version to decide which to use
major, minor, _ = self.gimpVersion.split( '.' )
if major != '2':
self.pluginDir = ''
if minor == '8':
self.pluginDir = v8_Path
else: # Hoping this path is good for other versions as well
self.pluginDir = v10_Path
elif os.path.exists( v8_Path ): self.pluginDir = v8_Path
elif os.path.exists( v10_Path ): self.pluginDir = v10_Path
else: self.pluginDir = ''
def getScriptVersion( self, pluginDir, scriptFile ):
""" Scans the given script (a filename) for a line like "version = 2.2\n" and parses it. """
scriptPath = os.path.join( pluginDir, scriptFile )
if os.path.exists( scriptPath ):
with open( scriptPath, 'r' ) as script:
for line in script:
line = line.strip()
if line.startswith( 'version' ) and '=' in line:
return line.split( '=' )[-1].strip()
return '-1'
def createSideImage( self, microMelee, charId, costumeId, charExtension ):
""" Installs code mods to the given Micro Melee disc image required for capturing CSP images,
and then launches Dolphin to collect a screenshot of a specific character costume. """
# Get target action states and frames for the screenshots
try:
characterDict = self.config[charId]
actionState = characterDict['actionState']
targetFrame = characterDict['frame']
faceLeft = characterDict.get( 'faceLeft', False )
grounded = characterDict.get( 'grounded', False )
camX = characterDict['camX']
camY = characterDict['camY']
camZ = characterDict['camZ']
targetFrameId = targetFrame >> 16 # Just need the first two bytes of the float for this
except KeyError as err:
msg( 'Unable to find CSP "{}" info for character ID 0x{:X} in "CSP Configuration.yml".'.format(err.message, charId), 'CSP Config Error' )
return ''
# Replace the character in the Micro Melee disc with the 20XX skin
origFile = microMelee.files[microMelee.gameId + '/' + microMelee.constructCharFileName(charId, costumeId, 'dat')]
newFile = globalData.disc.files[globalData.disc.gameId + '/' + globalData.disc.constructCharFileName(charId, costumeId, charExtension)]
microMelee.replaceFile( origFile, newFile )
# Copy over Nana too, if ICies are selected
if charId == 0xE: # Ice Climbers
colorAbbr = globalData.costumeSlots['Nn'][costumeId]
origFile = microMelee.files[microMelee.gameId + '/PlNn' + colorAbbr + '.dat' ]
newFile = globalData.disc.files[globalData.disc.gameId + '/PlNn' + colorAbbr + '.' + charExtension]
microMelee.replaceFile( origFile, newFile )
# Parse the Core Codes library for the codes needed for booting to match and setting up a pose
coreCodes = CodeLibraryParser()
coreCodesFolder = globalData.paths['coreCodes']
coreCodes.includePaths = [ os.path.join(coreCodesFolder, '.include'), os.path.join(globalData.scriptHomeFolder, '.include') ]
coreCodes.processDirectory( coreCodesFolder )
codesToInstall = []
# Customize the Asset Test mod to load the chosen characters/costumes
assetTest = coreCodes.getModByName( 'Asset Test' )
if not assetTest:
msg( 'Unable to find the Asset Test mod in the Core Codes library!', warning=True )
return ''
assetTest.configure( "Player 1 Character", charId )
assetTest.configure( "P1 Costume ID", costumeId )
assetTest.configure( "Player 2 Character", charId )
assetTest.configure( "P2 Costume ID", costumeId )
if charId == 0x13: # Special case for Sheik (for different lighting direction)
assetTest.configure( "Stage", 3 ) # Selecting Pokemon Stadium
else:
assetTest.configure( "Stage", 32 ) # Selecting FD
if faceLeft:
assetTest.configure( 'P1 Facing Direction', -1 )
assetTest.configure( 'P2 Facing Direction', -1 )
else:
assetTest.configure( 'P1 Facing Direction', 1 )
assetTest.configure( 'P2 Facing Direction', 1 )
codesToInstall.append( assetTest )
# Parse the Pose Codes
poseCodes = CodeLibraryParser()
poseCodesFolder = globalData.paths['triCsps']
poseCodes.includePaths = [ os.path.join(poseCodesFolder, '.include'), os.path.join(globalData.scriptHomeFolder, '.include') ]
poseCodes.processDirectory( poseCodesFolder )
# Check for a pose code specific to this character in the Pose Codes file
poseCodeName = globalData.charList[charId] + ' Pose Code'
poseCode = poseCodes.getModByName( poseCodeName )
if poseCode:
codesToInstall.append( poseCode )
else: # No specific, custom code for this character; use the general approach
# Configure code for setting the appropriate action state
# if charId == 1: # DK
# actionStateMod = coreCodes.getModByName( 'DK CSP Double-Jump' )
# if not actionStateMod:
# msg( 'Unable to find the DK CSP Double-Jump mod in the Core Codes library!', warning=True )
# return
#if charId == 1 or charId == 6: # DK or Link
# actionStateMod = coreCodes.getModByName( 'Force Jump for CSP' )
# if not actionStateMod:
# msg( 'Unable to find the Force Jump mod in the Core Codes library!', warning=True )
# return
# codesToInstall.append( actionStateMod )
# actionStateMod = coreCodes.getModByName( 'Enter Action State On Match Start' )
# if not actionStateMod:
# msg( 'Unable to find the Enter Action State On Match Start mod in the Core Codes library!', warning=True )
# return
# actionStateMod.configure( 'Action State ID', actionState )
# actionStateMod.configure( 'Start Frame', 0 )
# codesToInstall.append( coreCodes.getModByName('Zero-G Mode') )
# else:
actionStateMod = coreCodes.getModByName( 'Enter Action State On Match Start' )
if not actionStateMod:
msg( 'Unable to find the "Enter Action State On Match Start" mod in the Core Codes library!', warning=True )
return ''
# Convert the pose target frame to an int start frame
# startFrame = struct.unpack( '>f', struct.pack('>I', targetFrame) )[0]
# if startFrame <= 5:
# startFrame = 0
# else:
# startFrame = int( startFrame - 5 )
actionStateMod.configure( 'Action State ID', actionState )
actionStateMod.configure( 'Start Frame', 0 )