-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBRFNTify.py
2083 lines (1647 loc) · 68.5 KB
/
BRFNTify.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
# -*- coding: latin-1 -*-
# BRFNTify - Editor for Nintendo BRFNT font files
# Version Next Beta 1
# Copyright (C) 2009-2019 Tempus, RoadrunnerWMC
# This file is part of BRFNTify.
# BRFNTify 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.
# BRFNTify 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 BRFNTify. If not, see <http://www.gnu.org/licenses/>.
# BRFNTify.py
# This is the main executable for BRFNTify
# Imports
import contextlib
import functools
import io
import os
import struct
import sys
import traceback
import unicodedata
from PyQt5 import QtCore, QtGui, QtWidgets
Qt = QtCore.Qt
import TPLLib
# Globals
version = 'Beta 1'
Font = None
ENCODINGS = ['UCS-2', 'UTF-16', 'CP932', 'CP1252']
def module_path():
"""
This will get us the program's directory, even if we are frozen
using PyInstaller
"""
if hasattr(sys, 'frozen') and hasattr(sys, '_MEIPASS'): # PyInstaller
if sys.platform == 'darwin': # macOS
# sys.executable is /x/y/z/brfntify.app/Contents/MacOS/brfntify
# We need to return /x/y/z/brfntify.app/Contents/Resources/
macos = os.path.dirname(sys.executable)
if os.path.basename(macos) != 'MacOS':
return None
return os.path.join(os.path.dirname(macos), 'Resources')
else: # Windows, Linux
return os.path.dirname(sys.executable)
if __name__ == '__main__':
return os.path.dirname(os.path.abspath(__file__))
return None
@contextlib.contextmanager
def blockSignalsFrom(qobject):
orig = qobject.blockSignals(True)
try:
yield
finally:
qobject.blockSignals(orig)
def GetIcon(name):
"""
Helper function to grab a specific icon
"""
return QtGui.QIcon('data/icon-%s.png' % name)
def createHorzLine():
"""
Helper to create a horizontal line widget
"""
f = QtWidgets.QFrame()
f.setFrameStyle(QtWidgets.QFrame.HLine | QtWidgets.QFrame.Sunken)
return f
@functools.lru_cache(1024)
def getCharacterName(c):
"""
Return the Unicode character name for c (a string of length 1)
"""
# ASCII control characters don't have officially defined Unicode
# names (just Unicode aliases), so unicodedata.name() refuses to
# name them. That's annoying. So we provide names for them manually.
OVERRIDES = {
'\x00': 'Null',
'\x01': 'Start Of Heading',
'\x02': 'Start Of Text',
'\x03': 'End Of Text',
'\x04': 'End Of Transmission',
'\x05': 'Enquiry',
'\x06': 'Acknowledge',
'\x07': 'Bell',
'\x08': 'Backspace',
'\x09': 'Character Tabulation',
'\x0A': 'Line Feed',
'\x0B': 'Line Tabulation',
'\x0C': 'Form Feed (FF)',
'\x0D': 'Carriage Return (CR)',
'\x0E': 'Shift Out',
'\x0F': 'Shift In',
'\x10': 'Data Link Escape',
'\x11': 'Device Control One',
'\x12': 'Device Control Two',
'\x13': 'Device Control Three',
'\x14': 'Device Control Four',
'\x15': 'Negative Acknowledge',
'\x16': 'Synchronous Idle',
'\x17': 'End Of Transmission Block',
'\x18': 'Cancel',
'\x19': 'End Of Medium',
'\x1A': 'Substitute',
'\x1B': 'Escape',
'\x1C': 'Information Separator Four',
'\x1D': 'Information Separator Three',
'\x1E': 'Information Separator Two',
'\x1F': 'Information Separator One',
}
name = OVERRIDES.get(c)
if name is not None:
return name
name = unicodedata.name(c, None)
if name is None:
return '(Unknown)'
else:
return name.title()
class Window(QtWidgets.QMainWindow):
"""
Main window
"""
def __init__(self):
super().__init__(None)
self.savename = ''
self.view = ViewWidget()
self.brfntScene = QtWidgets.QGraphicsScene()
self.setCentralWidget(self.view)
self.setWindowTitle('BRFNTify Next')
ico = QtGui.QIcon()
ico.addPixmap(QtGui.QPixmap('data/icon-logobig.png'))
ico.addPixmap(QtGui.QPixmap('data/icon-logosmall.png'))
self.setWindowIcon(ico)
self.fontDock = FontMetricsDock(self)
self.fontDock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
self.charDock = CharMetricsDock(self)
self.charDock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
self.prevDock = TextPreviewDock(self)
self.prevDock.setVisible(False)
self.prevDock.setAllowedAreas(Qt.TopDockWidgetArea | Qt.BottomDockWidgetArea)
self.prevDock.setFeatures(self.prevDock.features() | QtWidgets.QDockWidget.DockWidgetVerticalTitleBar)
self.addDockWidget(Qt.LeftDockWidgetArea, self.fontDock)
self.addDockWidget(Qt.RightDockWidgetArea, self.charDock)
self.addDockWidget(Qt.BottomDockWidgetArea, self.prevDock)
self.brfntScene.selectionChanged.connect(self.charDock.updateGlyph)
self.CreateMenus()
def CreateMenus(self):
"""
Helper function to create the menus
"""
# create the actions
self.actions = {}
self.CreateAction('open', self.HandleOpen, GetIcon('open'), '&Open...', 'Open a font file', QtGui.QKeySequence.Open)
self.CreateAction('save', self.HandleSave, GetIcon('save'), '&Save', 'Save the font file', QtGui.QKeySequence.Save)
self.CreateAction('saveas', self.HandleSaveAs, GetIcon('saveas'), 'Save &as...', 'Save the font file to a new filename', QtGui.QKeySequence.SaveAs)
self.CreateAction('exportasimg', self.HandleExportAsImage, None, '&Export as Image...', 'Export all characters as an image', 'Ctrl+E')
self.CreateAction('importfromimg', self.HandleImportFromImage, None, '&Import from Image...', 'Import all characters from an image', 'Ctrl+I')
self.CreateAction('generate', self.HandleGenerate, None, '&Generate', 'Generate a font from one installed on your computer', 'Ctrl+G')
self.SetOutputEnabled(False)
# Dock show/hide actions are created later
self.CreateAction('leading', self.HandleLeading, GetIcon('leading'), '&Leading', 'Show or hide leading lines (the height of each line of text)', 'Ctrl+1')
self.CreateAction('ascent', self.HandleAscent, GetIcon('ascent'), '&Ascent', 'Show or hide ascent lines (the height of capital letters)', 'Ctrl+2')
self.CreateAction('baseLine', self.HandleBaseline, GetIcon('baseLine'), '&Baseline', 'Show or hide baseLines (the bottom)', 'Ctrl+3')
self.CreateAction('widths', self.HandleWidths, GetIcon('widths'), '&Widths', 'Show or hide the widths of each character', 'Ctrl+4')
self.actions['leading'].setCheckable(True)
self.actions['ascent'].setCheckable(True)
self.actions['baseLine'].setCheckable(True)
self.actions['widths'].setCheckable(True)
self.CreateAction('about', self.HandleAbout, GetIcon('about'), '&About', 'About BRFNTify Next', 'Ctrl+H')
self.actions['fontmetrics'] = self.fontDock.toggleViewAction()
self.actions['fontmetrics'].setText('&Font Metrics')
self.actions['fontmetrics'].setStatusTip('Show or hide the Font Metrics window')
self.actions['fontmetrics'].setShortcut('Ctrl+Q')
self.actions['charmetrics'] = self.charDock.toggleViewAction()
self.actions['charmetrics'].setText('&Character Metrics')
self.actions['charmetrics'].setStatusTip('Show or hide the Character Metrics window')
self.actions['charmetrics'].setShortcut('Ctrl+W')
self.actions['textprev'] = self.prevDock.toggleViewAction()
self.actions['textprev'].setText('&Text Preview')
self.actions['textprev'].setStatusTip('Show or hide the Text Preview window')
self.actions['textprev'].setShortcut('Ctrl+R')
# create a menubar
m = self.menuBar()
self.fileMenu = QtWidgets.QMenu('&File', self)
self.fileMenu.addAction(self.actions['open'])
self.fileMenu.addAction(self.actions['save'])
self.fileMenu.addAction(self.actions['saveas'])
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.actions['exportasimg'])
self.fileMenu.addAction(self.actions['importfromimg'])
self.fileMenu.addSeparator()
self.fileMenu.addAction(self.actions['generate'])
m.addMenu(self.fileMenu)
self.viewMenu = QtWidgets.QMenu('&View', self)
self.viewMenu.addAction(self.actions['fontmetrics'])
self.viewMenu.addAction(self.actions['charmetrics'])
self.viewMenu.addAction(self.actions['textprev'])
self.viewMenu.addSeparator()
self.viewMenu.addAction(self.actions['leading'])
self.viewMenu.addAction(self.actions['ascent'])
self.viewMenu.addAction(self.actions['baseLine'])
self.viewMenu.addAction(self.actions['widths'])
m.addMenu(self.viewMenu)
self.helpMenu = QtWidgets.QMenu('&Help', self)
self.helpMenu.addAction(self.actions['about'])
m.addMenu(self.helpMenu)
# create a statusbar
self.status = self.statusBar()
# add stuff to it
self.zoomInBtn = QtWidgets.QToolButton()
self.zoomInBtn.setText('Zoom In')
self.zoomInBtn.setAutoRaise(True)
self.zoomInBtn.clicked.connect(lambda: self.HandleZoom('+'))
self.zoomInBtn.setShortcut('Ctrl++')
self.zoomOutBtn = QtWidgets.QToolButton()
self.zoomOutBtn.setText('Zoom Out')
self.zoomOutBtn.setAutoRaise(True)
self.zoomOutBtn.clicked.connect(lambda: self.HandleZoom('-'))
self.zoomOutBtn.setShortcut('Ctrl+-')
self.zoomBtn = QtWidgets.QToolButton()
self.zoomBtn.setText('100%')
self.zoomBtn.setAutoRaise(True)
self.zoomBtn.clicked.connect(lambda: self.HandleZoom('%'))
lyt = QtWidgets.QHBoxLayout()
lyt.setContentsMargins(0,0,0,0)
lyt.addWidget(self.zoomInBtn)
lyt.addWidget(self.zoomOutBtn)
lyt.addWidget(self.zoomBtn)
w = QtWidgets.QWidget()
w.setLayout(lyt)
self.status.addPermanentWidget(w)
def CreateAction(self, shortname, function, icon, text, statustext, shortcut, toggle=False):
"""
Helper function to create an action
"""
if icon is not None:
act = QtWidgets.QAction(icon, text, self)
else:
act = QtWidgets.QAction(text, self)
if shortcut is not None: act.setShortcut(shortcut)
if statustext is not None: act.setStatusTip(statustext)
if toggle:
act.setCheckable(True)
act.triggered.connect(function)
self.actions[shortname] = act
def SetOutputEnabled(self, enabled):
"""
Enables or disables Save, Save As, Export and Import.
"""
self.actions['save'].setEnabled(enabled)
self.actions['saveas'].setEnabled(enabled)
self.actions['exportasimg'].setEnabled(enabled)
self.actions['importfromimg'].setEnabled(enabled)
def sizeHint(self):
"""
Size hint
"""
return QtCore.QSize(1280, 512)
def ShowErrorBox(self, caption):
"""
Show a nice error box for the current exception
"""
toplbl = QtWidgets.QLabel(caption)
exc_type, exc_value, tb = sys.exc_info()
fl = io.StringIO()
traceback.print_exception(exc_type, exc_value, tb, file=fl)
fl.seek(0)
btm = fl.read()
txtedit = QtWidgets.QPlainTextEdit(btm)
txtedit.setReadOnly(True)
buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(toplbl)
layout.addWidget(txtedit)
layout.addWidget(buttonBox)
dlg = QtWidgets.QDialog()
dlg.setLayout(layout)
dlg.setModal(True)
dlg.setMinimumWidth(384)
dlg.setWindowTitle('Error')
buttonBox.accepted.connect(dlg.accept)
dlg.exec_()
def HandleOpen(self):
"""
Open a Binary Revolution Font (.brfnt) file for editing
"""
global Font
# File Dialog
fn = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose a Font', '', 'Wii font files (*.brfnt);;All Files(*)')[0]
if not fn: return
# Put the whole thing in a try-except clause
try:
with open(fn, 'rb') as f:
tmpf = f.read()
Font = BRFNT(tmpf)
self.fontDock.updateFields()
self.brfntScene.clear()
self.brfntScene.setSceneRect(
0,
0,
Font.cellWidth * 30,
Font.cellHeight * (len(Font.glyphs) / 30) + 1)
x = 0
y = 0
i = 0
for item in Font.glyphs:
if i >= 30:
x = 0
y = y + item.pixmap.height()
i = 0
item.setPos(x, y)
self.brfntScene.addItem(item)
x = x + item.pixmap.width()
i += 1
self.view.updateDisplay()
self.view.setScene(self.brfntScene)
self.prevDock.updatePreview()
self.view.columns = 1
self.view.updateLayout()
self.savename = fn
self.setWindowTitle('BRFNTify Next - %s' % fn.replace('\\', '/').split('/')[-1])
self.SetOutputEnabled(True)
except Exception as e:
self.ShowErrorBox('An error occured while trying to load this file. Please refer to the information below for more details.')
def HandleSave(self):
"""
Save the font file back to the original file
"""
if not self.savename:
self.HandleSaveAs()
return
data = self.Save()
if data:
with open(self.savename, 'wb') as f:
f.write(data)
def HandleSaveAs(self):
"""
Save the font file to a new file
"""
fn = QtWidgets.QFileDialog.getSaveFileName(self, 'Choose a new filename', '', 'Wii font files (*.brfnt);;All Files(*)')[0]
if not fn: return
self.savename = fn
self.setWindowTitle('BRFNTify Next - %s' % fn.replace('\\', '/').split('/')[-1])
self.HandleSave()
def HandleExportAsImage(self):
"""
Export all character graphics as an image
"""
fn = QtWidgets.QFileDialog.getSaveFileName(self, 'Choose a PNG file', '', 'PNG image file (*.png);;All Files(*)')[0]
if not fn: return
Font.exportImage().save(fn)
def HandleImportFromImage(self):
"""
Import all character graphics from an image
"""
fn = QtWidgets.QFileDialog.getOpenFileName(self, 'Choose a PNG file', '', 'PNG image file (*.png);;All Files(*)')[0]
if not fn: return
try: pix = QtGui.QImage(fn)
except: return
Font.importImage(pix)
self.update()
self.prevDock.updatePreview()
def Save(self):
"""
Save the font file and return its data
"""
try:
return Font.save()
except Exception as e:
self.ShowErrorBox('An error occured while trying to save this file. Please refer to the information below for more details.')
def HandleGenerate(self):
"""
Generate a font
"""
dlg = GenerateDialog()
if dlg.exec_() == QtWidgets.QDialog.Accepted:
# Create a bunch of glyphs, I guess.
chars = dlg.chars.text()
global Font
Font = BRFNT.generate(dlg.selectedFont(), chars, dlg.fg, dlg.bg)
x = 0
y = 0
i = 0
self.brfntScene.clear()
self.brfntScene.setSceneRect(0, 0, 5000, 5000)
for item in Font.glyphs:
if i >= 30:
x = 0
y = y + item.pixmap.height()
i = 0
item.setPos(x, y)
self.brfntScene.addItem(item)
x = x + item.pixmap.width()
i += 1
self.fontDock.updateFields()
self.view.updateDisplay()
self.view.setScene(self.brfntScene)
self.prevDock.updatePreview()
self.view.columns = 1
self.view.updateLayout()
self.setWindowTitle('BRFNTify Next - untitled')
self.SetOutputEnabled(True)
def HandleLeading(self, toggled):
"""
Handle the user toggling Leading
"""
self.view.updateLeading(toggled)
def HandleAscent(self, toggled):
"""
Handle the user toggling Ascent
"""
self.view.updateAscent(toggled)
def HandleBaseline(self, toggled):
"""
Handle the user toggling Baseline
"""
self.view.updateBaseline(toggled)
def HandleWidths(self, toggled):
"""
Handle the user toggling Widths
"""
self.view.updateWidths(toggled)
def HandleAbout(self):
"""
Handle the user clicking About
"""
try:
with open('readme.md', 'r', encoding='utf-8') as f:
readme = f.read()
except:
readme = 'BRFNTify %s by Tempus, RoadrunnerWMC\n(No readme.md found!)\nLicensed under GPL' % version
txtedit = QtWidgets.QPlainTextEdit(readme)
txtedit.setReadOnly(True)
buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok)
layout = QtWidgets.QVBoxLayout()
layout.addWidget(txtedit)
layout.addWidget(buttonBox)
dlg = QtWidgets.QDialog()
dlg.setLayout(layout)
dlg.setModal(True)
dlg.setMinimumWidth(512)
dlg.setWindowTitle('About')
buttonBox.accepted.connect(dlg.accept)
dlg.exec_()
zoomLevels = [20.0, 35.0, 50.0, 65.0, 80.0, 90.0, 100.0, 125.0, 150.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0]
zoomidx = zoomLevels.index(100.0)
def HandleZoom(self, btn):
"""
Handle ANY of the zoom buttons being clicked
"""
oldz = self.zoomLevels[self.zoomidx]
if btn == '+': self.zoomidx += 1
elif btn == '-': self.zoomidx -= 1
elif btn == '%': self.zoomidx = self.zoomLevels.index(100.0)
if self.zoomidx < 0: self.zoomidx = 0
if self.zoomidx > len(self.zoomLevels) - 1: self.zoomidx = len(self.zoomLevels) - 1
z = self.zoomLevels[self.zoomidx]
self.zoomBtn.setText('%d%%' % int(z))
self.zoomInBtn.setEnabled(self.zoomidx < len(self.zoomLevels) - 1)
self.zoomOutBtn.setEnabled(self.zoomidx > 0)
self.view.scale(z/oldz, z/oldz)
self.view.zoom = z
self.view.updateLayout()
class GenerateDialog(QtWidgets.QDialog):
"""
Allows the user to generate a glyph table from an installed font
"""
fg = Qt.black
bg = Qt.transparent
def __init__(self):
super().__init__()
self.setWindowTitle('Generate a Font')
# Font and style group box
fontGroupBox = QtWidgets.QGroupBox('Font and Style')
self.fontCombo = QtWidgets.QFontComboBox()
self.sizeCombo = QtWidgets.QComboBox()
self.weightValue = QtWidgets.QSpinBox()
self.italicCheckbox = QtWidgets.QCheckBox('Italic')
self.findSizes(self.fontCombo.currentFont())
self.weightValue.setMaximum(99)
self.weightValue.setValue(50)
self.fontCombo.currentFontChanged.connect(self.findSizes)
fontLayout = QtWidgets.QFormLayout(fontGroupBox)
fontLayout.addRow('Font:', self.fontCombo)
fontLayout.addRow('Size:', self.sizeCombo)
fontLayout.addRow('Weight:', self.weightValue)
fontLayout.addRow('', QtWidgets.QLabel('<small>Default is 50. Bold is 75. <a href="https://doc.qt.io/qt-5/qfont.html#Weight-enum">More information.</a></small>'))
fontLayout.addRow(self.italicCheckbox)
# Colors group box
colorsGroupBox = QtWidgets.QGroupBox('Colors')
self.fgLabel = QtWidgets.QLabel()
self.bgLabel = QtWidgets.QLabel()
fgBtn = QtWidgets.QPushButton('Choose...')
bgBtn = QtWidgets.QPushButton('Choose...')
fg = QtGui.QPixmap(48, 24)
fg.fill(self.fg)
bg = QtGui.QPixmap(48, 24)
bg.fill(self.bg)
self.fgLabel.setPixmap(fg)
self.bgLabel.setPixmap(bg)
fgBtn.clicked.connect(self.fgBtnClick)
bgBtn.clicked.connect(self.bgBtnClick)
fgLayout = QtWidgets.QHBoxLayout()
fgLayout.addWidget(self.fgLabel)
fgLayout.addWidget(fgBtn)
bgLayout = QtWidgets.QHBoxLayout()
bgLayout.addWidget(self.bgLabel)
bgLayout.addWidget(bgBtn)
colorsLayout = QtWidgets.QFormLayout(colorsGroupBox)
colorsLayout.addRow('Foreground:', fgLayout)
colorsLayout.addRow('Background:', bgLayout)
# Characters group box
charsGroupBox = QtWidgets.QGroupBox('Characters')
self.chars = QtWidgets.QLineEdit()
self.chars.setText(''.join([chr(x) for x in range(0x20, 0x7F)]))
charsLayout = QtWidgets.QVBoxLayout(charsGroupBox)
charsLayout.addWidget(self.chars)
# Button box and overall layout
buttonBox = QtWidgets.QDialogButtonBox(QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel)
buttonBox.accepted.connect(self.accept)
buttonBox.rejected.connect(self.reject)
L = QtWidgets.QGridLayout(self)
L.addWidget(fontGroupBox, 0, 0)
L.addWidget(colorsGroupBox, 0, 1)
L.addWidget(charsGroupBox, 1, 0, 1, 2)
L.addWidget(buttonBox, 2, 0, 1, 2)
def findSizes(self, font):
"""
Add font sizes to self.sizeCombo
"""
fontDatabase = QtGui.QFontDatabase()
currentSize = self.sizeCombo.currentText()
with blockSignalsFrom(self.sizeCombo):
self.sizeCombo.clear()
if fontDatabase.isSmoothlyScalable(font.family(), fontDatabase.styleString(font)):
self.sizeCombo.setEditable(True)
for size in QtGui.QFontDatabase.standardSizes():
self.sizeCombo.addItem(str(size))
else:
self.sizeCombo.setEditable(False)
addedAny = False
for size in fontDatabase.smoothSizes(font.family(), fontDatabase.styleString(font)):
self.sizeCombo.addItem(str(size))
addedAny = True
if not addedAny:
for size in QtGui.QFontDatabase.standardSizes():
self.sizeCombo.addItem(str(size))
sizeIndex = self.sizeCombo.findText(currentSize)
if sizeIndex == -1:
self.sizeCombo.setCurrentIndex(max(0, self.sizeCombo.count() // 3))
else:
self.sizeCombo.setCurrentIndex(sizeIndex)
def fgBtnClick(self):
"""
User clicked the Choose... button for the foreground color
"""
dlg = QtWidgets.QColorDialog(self)
dlg.setOption(dlg.ShowAlphaChannel, True)
dlg.setCurrentColor(self.fg)
dlg.open()
dlg.finished.connect(lambda state: self.fgBtnClick2(state, dlg))
def fgBtnClick2(self, state, dlg):
"""
Called when the user closes the color dialog
"""
if state != dlg.Accepted: return
self.fg = dlg.currentColor()
fg = QtGui.QPixmap(48, 24)
fg.fill(self.fg)
self.fgLabel.setPixmap(fg)
def bgBtnClick(self):
"""
User clicked the Choose... button for the background color
"""
dlg = QtWidgets.QColorDialog(self)
dlg.setOption(dlg.ShowAlphaChannel, True)
dlg.setCurrentColor(self.bg)
dlg.open()
dlg.finished.connect(lambda state: self.bgBtnClick2(state, dlg))
def bgBtnClick2(self, state, dlg):
"""
Called when the user closes the color dialog
"""
if state != dlg.Accepted: return
self.bg = dlg.currentColor()
bg = QtGui.QPixmap(48, 24)
bg.fill(self.bg)
self.bgLabel.setPixmap(bg)
def selectedFont(self):
"""
Return a QFont representing the font the user selected, with
appropriate point size and styling options.
"""
font = self.fontCombo.currentFont()
font.setPointSize(int(self.sizeCombo.currentText()))
font.setWeight(self.weightValue.value())
font.setItalic(self.italicCheckbox.isChecked())
return font
class Glyph(QtWidgets.QGraphicsItem):
"""
Class for a character glyph
"""
def __init__(self, pixmap, char, leftMargin=0, charWidth=0, fullWidth=0):
super().__init__()
self.char = char
self.leftMargin = leftMargin
self.charWidth = charWidth
self.fullWidth = fullWidth
self.pixmap = pixmap
self.boundingRect = QtCore.QRectF(0,0,pixmap.width(),pixmap.height())
self.selectionRect = QtCore.QRectF(0,0,pixmap.width()-1,pixmap.height()-1)
self.setFlag(self.ItemIsMovable, False)
self.setFlag(self.ItemIsSelectable, True)
self.setFlag(self.ItemIsFocusable, True)
def value(self, encoding):
"""
Get the glyph's value in the given encoding
"""
return charToValue(self.char, encoding)
def updateToolTip(self, encoding):
"""
Update the glyph's tooltip
"""
if self.char is None:
name = '<p>Unknown glyph</p>'
else:
name = (
('<p style="font-size: 24pt;">&#%d;</p>' % ord(self.char))
+ ('<p>Value: 0x%X</p>' % self.value(encoding))
)
text = '<p>Character:</p>' + name
self.setToolTip(text)
def boundingRect(self):
"""
Required for Qt
"""
return self.boundingRect
def contextMenuEvent(self, e):
"""
Handle right-clicking the glyph
"""
QtWidgets.QGraphicsItem.contextMenuEvent(self, e)
menu = QtWidgets.QMenu()
menu.addAction('Import...', self.handleImport)
menu.addAction('Export...', self.handleExport)
menu.exec_(e.screenPos())
def handleExport(self):
"""
Handle the pixmap being exported
"""
# Get the name
fn = QtWidgets.QFileDialog.getSaveFileName(window, 'Choose a PNG file', '', 'PNG image file (*.png);;All Files(*)')[0]
if not fn: return
# Save it
self.pixmap.save(fn)
def handleImport(self):
"""
Handle a new pixmap being imported
"""
# Get the name
fn = QtWidgets.QFileDialog.getOpenFileName(window, 'Choose a PNG file', '', 'PNG image file (*.png);;All Files(*)')[0]
if not fn: return
# Open it
try: pix = QtGui.QPixmap(fn)
except: return
# Resize it if needed
tooWide = pix.width() > self.pixmap.width()
tooTall = pix.height() > self.pixmap.height()
if tooWide and tooTall:
pix = pix.scaled(self.pixmap.width(), self.pixmap.height())
elif tooWide:
pix = pix.scaledToWidth(self.pixmap.width())
elif tooTall:
pix = pix.scaledToHeight(self.pixmap.height())
# Set it
self.pixmap = pix
self.update()
window.prevDock.updatePreview()
def paint(self, painter, option, widget):
"""
Paint the object
"""
painter.drawPixmap(0, 0, self.pixmap)
if self.isSelected():
painter.setPen(QtGui.QPen(Qt.blue, 1, Qt.SolidLine))
painter.drawRect(self.selectionRect)
painter.fillRect(self.selectionRect, QtGui.QColor.fromRgb(255, 255, 255, 64))
def FindGlyph(char):
"""
Return a Glyph object for the string character, or None if none exists
"""
default = None
for glyph in Font.glyphs:
if glyph.char == char:
return glyph
elif ord(glyph.char) == Font.defaultChar:
default = glyph
return default
class FontMetricsDock(QtWidgets.QDockWidget):
"""
A dock widget that displays font-wide metrics
"""
typeList = ['0', '1', '2'] # TODO: check exactly what the valid values are
endiannessList = ['Big', 'Little']
formatList = ['I4', 'I8', 'IA4', 'IA8', 'RGB565', 'RGB4A3', 'RGBA8', 'Unknown', 'CI4', 'CI8', 'CI14x2', 'Unknown', 'Unknown', 'Unknown', 'CMPR/S3TC']
updating = False
def __init__(self, parent):
super().__init__(parent)
self.setWindowTitle('Font Metrics')
self.setupGui()
def setupGui(self):
self.edits = {
'fontType': QtWidgets.QComboBox(self),
'endianness': QtWidgets.QComboBox(self),
'encoding': QtWidgets.QComboBox(self),
'texFormat': QtWidgets.QComboBox(self),
'charsPerRow': QtWidgets.QSpinBox(self),
'charsPerColumn': QtWidgets.QSpinBox(self),
'defaultChar': QtWidgets.QLineEdit(self),
'leftMargin': QtWidgets.QSpinBox(self),
'charWidth': QtWidgets.QSpinBox(self),
'fullWidth': QtWidgets.QSpinBox(self),
'leading': QtWidgets.QSpinBox(self),
'ascent': QtWidgets.QSpinBox(self),
'descent': QtWidgets.QSpinBox(self),
'baseLine': QtWidgets.QSpinBox(self),
'width': QtWidgets.QSpinBox(self),
'height': QtWidgets.QSpinBox(self),
}
self.edits['fontType'].addItems(self.typeList)
self.edits['endianness'].addItems(self.endiannessList)
self.edits['encoding'].addItems(ENCODINGS)
self.edits['texFormat'].addItems(self.formatList)
self.edits['charsPerRow'].setMaximum(0xFFFF)
self.edits['charsPerColumn'].setMaximum(0xFFFF)
self.edits['defaultChar'].setMaxLength(1)
self.edits['defaultChar'].setMaximumWidth(30)
self.edits['leftMargin'].setRange(-0x80, 0x7F)
self.edits['charWidth'].setRange(1, 0x100)
self.edits['fullWidth'].setRange(-0x7F, 0x80)
self.edits['leading'].setRange(-0x7F, 0x80)
self.edits['ascent'].setMaximum(0xFF)
self.edits['descent'].setMaximum(0xFF)
self.edits['baseLine'].setRange(-0x7F, 0x80)
self.edits['width'].setRange(1, 0x100)
self.edits['height'].setRange(1, 0x100)
for name, e in self.edits.items():
def makeHandler(name):
def handler():
self.boxChanged(name)
return handler
if isinstance(e, QtWidgets.QComboBox):
e.currentIndexChanged.connect(makeHandler(name))
elif isinstance(e, QtWidgets.QSpinBox):
e.valueChanged.connect(makeHandler(name))
elif isinstance(e, QtWidgets.QLineEdit):
e.textChanged.connect(makeHandler(name))
for e in self.edits.values(): e.setEnabled(False)
textPropsBox = QtWidgets.QGroupBox('Text Properties')
textPropsLyt = QtWidgets.QFormLayout(textPropsBox)
textPropsLyt.addRow('Font Type:', self.edits['fontType'])
textPropsLyt.addRow('Endianness:', self.edits['endianness'])
textPropsLyt.addRow('Encoding:', self.edits['encoding'])
textPropsLyt.addRow('Default Char:', self.edits['defaultChar'])
texturesBox = QtWidgets.QGroupBox('Textures')
texturesLyt = QtWidgets.QFormLayout(texturesBox)
texturesLyt.addRow('Texture Format:', self.edits['texFormat'])
texturesLyt.addRow('Chars Per Row:', self.edits['charsPerRow'])
texturesLyt.addRow('Chars Per Column:', self.edits['charsPerColumn'])
texturesLyt.addRow('Width:', self.edits['width'])
texturesLyt.addRow('Height:', self.edits['height'])
metricsBox = QtWidgets.QGroupBox('Metrics')
metricsLyt = QtWidgets.QFormLayout(metricsBox)
metricsLyt.addRow('Left Margin:', self.edits['leftMargin'])
metricsLyt.addRow('Char Width:', self.edits['charWidth'])
metricsLyt.addRow('Full Width:', self.edits['fullWidth'])
metricsLyt.addRow('Leading:', self.edits['leading'])
metricsLyt.addRow('Ascent:', self.edits['ascent'])
metricsLyt.addRow('Descent:', self.edits['descent'])
metricsLyt.addRow('Baseline:', self.edits['baseLine'])