-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFontraPakMain.py
More file actions
728 lines (573 loc) · 21.5 KB
/
Copy pathFontraPakMain.py
File metadata and controls
728 lines (573 loc) · 21.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
import asyncio
import json
import logging
import multiprocessing
import os
import pathlib
import secrets
import signal
import sys
import tempfile
import threading
import traceback
import webbrowser
from contextlib import aclosing
from dataclasses import dataclass
from datetime import datetime
from random import random
from urllib.parse import quote
from urllib.request import urlopen
import certifi
import psutil
from fontra import __version__ as fontraVersion
from fontra.backends import getFileSystemBackend, newFileSystemBackend
from fontra.backends.copy import copyFont
from fontra.backends.populate import populateBackend
from fontra.core.classes import DiscreteFontAxis
from fontra.core.server import FontraServer, findFreeTCPPort
from fontra.core.urlfragment import dumpURLFragment
from fontra.filesystem.projectmanager import FileSystemProjectManager
from fontTools.ttLib.woff2 import compress as woff2Compress
from PyQt6.QtCore import (
QEvent,
QObject,
QPoint,
QSettings,
QSize,
Qt,
QTimer,
pyqtSignal,
)
from PyQt6.QtWidgets import (
QApplication,
QCheckBox,
QFileDialog,
QGridLayout,
QLabel,
QMainWindow,
QMessageBox,
QPlainTextEdit,
QProgressDialog,
QPushButton,
QSizePolicy,
QWidget,
)
commonCSS = """
border-radius: 20px;
border-style: dashed;
font-size: 18px;
padding: 16px;
"""
neutralCSS = (
"""
background-color: rgba(255,255,255,128);
border: 5px solid lightgray;
"""
+ commonCSS
)
droppingCSS = (
"""
background-color: rgba(255,255,255,64);
border: 5px solid gray;
"""
+ commonCSS
)
mainText = """
<span style="font-size: 40px;">Drop font files here</span>
<br>
<br>
Your fonts will stay on your computer and will not be uploaded anywhere.
<br>
<br>
Fontra Pak reads and writes .ufo, .designspace, .fontra, and .rcjk, and has
partial support for reading and writing .glyphs and .glyphspackage files.
<br>
Additionally, it can read (but not write) .ttf, .otf, .woff, .woff2, and .ttx.
"""
fileTypes = [
# name, extension
("Fontra", "fontra"),
("Designspace", "designspace"),
("Unified Font Object", "ufo"),
("RoboCJK", "rcjk"),
]
fileTypesMapping = {
f"{name} (*.{extension})": f".{extension}" for name, extension in fileTypes
}
fileTypesMappingForNewFont = {
key: value for key, value in fileTypesMapping.items() if "rcjk" not in value
}
exportFileTypes = [
# name, extension
("TrueType", "ttf"),
("OpenType", "otf"),
("Webfont", "woff2"),
] + fileTypes
exportFileTypesMapping = {
f"{name} (*.{extension})": f".{extension}" for name, extension in exportFileTypes
}
exportExtensionMapping = {v: k for k, v in exportFileTypesMapping.items()}
latestReleasePageURL = "https://github.com/fontra/fontra-pak/releases/latest"
applicationSettings = QSettings("xyz.fontra", "FontraPak")
class FontraApplication(QApplication):
def __init__(self, argv, port):
self.port = port
super().__init__(argv)
def event(self, event):
"""Handle macOS FileOpen events."""
if event.type() == QEvent.Type.FileOpen:
openFile(event.file(), self.port)
else:
return super().event(event)
return True
def getFontPath(path, fileType, mapping):
extension = mapping[fileType]
if not path.endswith(extension):
path += extension
return path
class FontraMainWidget(QMainWindow):
def __init__(self, port):
super().__init__()
self.port = port
self.openProjects = set()
self.setWindowTitle("Fontra Pak")
self.resize(720, 480)
self.resize(applicationSettings.value("size", QSize(720, 480)))
self.move(applicationSettings.value("pos", QPoint(50, 50)))
self.setAcceptDrops(True)
self.label = QLabel(mainText)
self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.label.setStyleSheet(neutralCSS)
self.label.setSizePolicy(
QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding
)
self.label.setWordWrap(True)
# Helpful: https://www.pythontutorial.net/pyqt/pyqt-qgridlayout/
layout = QGridLayout()
button = QPushButton("&New Font...", self)
button.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
button.clicked.connect(self.newFont)
buttonDocs = QPushButton("Documentation", self)
buttonDocs.setToolTip("Open documentation website")
buttonDocs.setSizePolicy(QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed)
buttonDocs.clicked.connect(lambda: webbrowser.open("https://docs.fontra.xyz"))
layout.addWidget(button, 0, 0, alignment=Qt.AlignmentFlag.AlignLeft)
layout.addWidget(buttonDocs, 0, 1, alignment=Qt.AlignmentFlag.AlignRight)
layout.addWidget(self.label, 1, 0, 1, 2)
readOnlyCheckBox = QCheckBox("Open fonts in read-only mode")
readOnlyCheckBox.setCheckState(
Qt.CheckState.Checked
if applicationSettings.value("openFontsInReadOnlyMode", False, type=bool)
else Qt.CheckState.Unchecked
)
readOnlyCheckBox.stateChanged.connect(
lambda s: applicationSettings.setValue("openFontsInReadOnlyMode", bool(s))
)
layout.addWidget(readOnlyCheckBox, 2, 0)
self.sampleTextBox = QPlainTextEdit(
applicationSettings.value("editorSampleText", ""), self
)
self.sampleTextBox.setFixedHeight(50)
self.sampleTextBox.setPlaceholderText(
"Enter some text to launch into the editor view,\n"
+ "or leave empty to launch into the font overview"
)
self.sampleTextBox.textChanged.connect(
lambda: applicationSettings.setValue(
"editorSampleText", self.sampleTextBox.toPlainText()
)
)
layout.addWidget(QLabel("Sample text:"), 3, 0)
layout.addWidget(self.sampleTextBox, 4, 0, 1, 2)
layout.addWidget(QLabel(f"Fontra version {fontraVersion}"), 5, 0)
if sys.platform in {"darwin", "win32", "linux"}:
self.downloadButton = QPushButton("Download latest Fontra Pak", self)
self.downloadButton.setSizePolicy(
QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Fixed
)
self.downloadButton.clicked.connect(self.goToLatestDownload)
layout.addWidget(
self.downloadButton, 5, 1, alignment=Qt.AlignmentFlag.AlignRight
)
if "test-startup" not in sys.argv:
self.checkForUpdate(1500)
widget = QWidget()
widget.setLayout(layout)
self.setCentralWidget(widget)
self.show()
def closeEvent(self, event):
if self.openProjects:
response = showMessageDialog(
"There are still open fonts, are you sure you want to quit?",
"Quitting Fontra Pak will cause open browser tabs to stop working.",
buttons=QMessageBox.StandardButton.Close
| QMessageBox.StandardButton.Cancel,
defaultButton=QMessageBox.StandardButton.Cancel,
)
if response == QMessageBox.StandardButton.Cancel:
event.ignore()
applicationSettings.setValue("size", self.size())
applicationSettings.setValue("pos", self.pos())
def dragEnterEvent(self, event):
if event.mimeData().hasUrls():
event.accept()
self.label.setStyleSheet(droppingCSS)
else:
event.ignore()
def dragLeaveEvent(self, event):
self.label.setStyleSheet("background-color: lightgray;")
self.label.setStyleSheet(neutralCSS)
def dropEvent(self, event):
self.label.setStyleSheet(neutralCSS)
files = [u.toLocalFile() for u in event.mimeData().urls()]
for path in files:
openFile(path, self.port)
event.acceptProposedAction()
@property
def activeFolder(self):
activeFolder = applicationSettings.value(
"activeFolder", os.path.expanduser("~")
)
if not os.path.isdir(activeFolder):
activeFolder = os.path.expanduser("~")
return activeFolder
def newFont(self):
fontPath, fileType = QFileDialog.getSaveFileName(
self,
"New Font...",
os.path.join(self.activeFolder, "Untitled"),
";;".join(fileTypesMappingForNewFont),
)
if not fontPath:
# User cancelled
return
fontPath = getFontPath(fontPath, fileType, fileTypesMappingForNewFont)
applicationSettings.setValue("activeFolder", os.path.dirname(fontPath))
# Create a new empty project on disk
try:
asyncio.run(createNewFont(fontPath))
except Exception as e:
showMessageDialog("The new font could not be saved", repr(e))
return
if os.path.exists(fontPath):
openFile(fontPath, self.port)
def messageFromServer(self, item):
action, arguments = item
handler = getattr(self, action, None)
if handler is not None:
handler(*arguments)
else:
print("unknown server action:", action)
def exportAs(self, path, options):
sourcePath = pathlib.Path(path)
fileExtension = options["format"]
wFlags = self.windowFlags()
self.setWindowFlags(wFlags | Qt.WindowType.WindowStaysOnTopHint)
self.show()
self.setWindowFlags(wFlags)
self.show()
destPath, fileType = QFileDialog.getSaveFileName(
self,
"Export font...",
os.path.join(self.activeFolder, sourcePath.stem),
exportExtensionMapping["." + fileExtension],
)
if not destPath:
# User cancelled
return
destPath = getFontPath(destPath, fileType, exportFileTypesMapping)
applicationSettings.setValue("activeFolder", os.path.dirname(destPath))
destPath = pathlib.Path(destPath)
if sourcePath == destPath:
showMessageDialog(
"Cannot export font",
"The destination file cannot be the same as the source file",
)
return
self.doExportAs(sourcePath, destPath, fileExtension)
def doExportAs(self, sourcePath, destPath, fileExtension):
logFilePath = tempfile.NamedTemporaryFile().name
exportProcess = multiprocessing.Process(
target=exportFontToPath,
args=(sourcePath, destPath, fileExtension, logFilePath),
)
cancelled = False
def cancelExport():
nonlocal cancelled
cancelled = True
assert exportProcess.pid is not None
os.kill(exportProcess.pid, signal.SIGINT)
progressDialog = QProgressDialog(
f"Exporting “{os.path.basename(destPath)}”", "Cancel", 0, 0
)
progressCancelButton = QPushButton("Cancel")
progressCancelButton.clicked.connect(cancelExport)
progressDialog.setCancelButton(progressCancelButton)
progressDialog.setWindowTitle(f"Export as {fileExtension}")
progressDialog.show()
exportProcess.start()
def exportFinished():
if cancelled:
return
progressDialog.cancel()
try:
if exportProcess.exitcode:
with open(logFilePath, encoding="utf-8") as logFile:
logFile.seek(0)
logData = logFile.read()
logLines = logData.splitlines()
infoText = (
logLines[-1] if logLines else "The reason is not clear."
)
showMessageDialog(
"The font could not be exported",
infoText,
detailedText=logData,
)
finally:
os.unlink(logFilePath)
def exportProcessJoin():
exportProcess.join()
callInMainThread(exportFinished)
callInNewThread(exportProcessJoin)
def projectOpened(self, projectIdentifier):
self.openProjects.add(projectIdentifier)
def projectClosed(self, projectIdentifier):
self.openProjects.discard(projectIdentifier)
def checkForUpdate(self, msDelay):
QTimer.singleShot(msDelay, lambda: callInNewThread(self._checkForUpdate))
def _checkForUpdate(self):
if "dev" in fontraVersion:
return
print(f"Checking for update on {datetime.now()}")
latestVersion, downloadURL = fetchLatestReleaseInfo()
if downloadURL is not None and latestVersion != fontraVersion:
callInMainThread(
self.downloadButton.setText, "‼️ A new version is available ‼️"
)
else:
# Try again in a bit more than a day
hours = 24 + 4 * random()
minutes = hours * 60
seconds = minutes * 60
msDelay = seconds * 1000
callInMainThread(self.checkForUpdate, int(msDelay))
def goToLatestDownload(self):
_, downloadURL = fetchLatestReleaseInfo()
if downloadURL is None:
downloadURL = latestReleasePageURL
webbrowser.open(downloadURL)
def fetchLatestReleaseInfo() -> tuple[str, str | None]:
try:
return _fetchLatestReleaseInfo()
except Exception:
print("Failed to fetch release info")
traceback.print_exc()
return "0.0.0", None
def _fetchLatestReleaseInfo() -> tuple[str, str | None]:
url = "https://api.github.com/repos/fontra/fontra-pak/releases/latest"
response = urlopen(url)
latestRelease = json.loads(response.read().decode("utf-8"))
latestVersion = latestRelease["tag_name"]
assetNamePart = None
match sys.platform:
case "darwin":
assetNamePart = "MacOS"
case "win32":
assetNamePart = "Windows-Installer"
case "linux":
assetNamePart = "Linux"
if assetNamePart is None:
return latestVersion, None
[assetInfo] = [
asset for asset in latestRelease["assets"] if assetNamePart in asset["name"]
]
return latestVersion, assetInfo["browser_download_url"]
def exportFontToPath(sourcePath, destPath, fileExtension, logFilePath):
logFile = open(logFilePath, "w")
sys.stdout = sys.stderr = logFile
try:
asyncio.run(exportFontToPathAsync(sourcePath, destPath, fileExtension))
finally:
logFile.flush()
async def exportFontToPathAsync(sourcePath, destPath, fileExtension):
sourcePath = pathlib.Path(sourcePath)
destPath = pathlib.Path(destPath)
if fileExtension == "woff2":
with tempfile.TemporaryDirectory() as tmpDir:
tmpTtfPath = pathlib.Path(tmpDir) / (destPath.stem + ".ttf")
await exportFontToPathAsync(sourcePath, tmpTtfPath, "ttf")
woff2Compress(str(tmpTtfPath), str(destPath))
return
sourceBackend = getFileSystemBackend(sourcePath)
if fileExtension in {"ttf", "otf"}:
from fontra.workflow.workflow import Workflow
continueOnError = False
# For now, we drop discrete axes, and only export the default
axes = await sourceBackend.getAxes()
discreteAxisNames = [
axis.name for axis in axes.axes if isinstance(axis, DiscreteFontAxis)
]
dropDiscreteAxes = (
[dict(filter="subset-axes", dropAxisNames=discreteAxisNames)]
if discreteAxisNames
else []
)
config = dict(
steps=dropDiscreteAxes
+ [
dict(filter="decompose-composites", onlyVariableComposites=True),
dict(filter="propagate-anchors"),
dict(filter="drop-unreachable-glyphs"),
dict(
output="compile-fontmake",
destination=destPath.name,
options={"verbose": "DEBUG", "overlaps-backend": "pathops"},
),
]
)
workflow = Workflow(config=config, parentDir=sourcePath.parent)
async with workflow.endPoints(sourceBackend) as endPoints:
assert endPoints.endPoint is not None
for output in endPoints.outputs:
await output.process(destPath.parent, continueOnError=continueOnError)
else:
destBackend = newFileSystemBackend(destPath)
async with aclosing(sourceBackend), aclosing(destBackend):
await copyFont(sourceBackend, destBackend)
async def createNewFont(fontPath):
# Create a new empty project on disk
destBackend = newFileSystemBackend(fontPath)
await populateBackend(destBackend)
await destBackend.aclose()
def openFile(path, port):
path = pathlib.Path(path).resolve()
assert path.is_absolute()
parts = list(path.parts)
if not path.drive:
assert parts[0] == "/"
del parts[0]
path = "/".join(quote(part, safe="") for part in parts)
readOnly = applicationSettings.value("openFontsInReadOnlyMode", False, type=bool)
sampleText = applicationSettings.value("editorSampleText", "")
urlFragment = dumpURLFragment({"text": sampleText}) if sampleText else ""
view = "editor" if sampleText else "fontoverview"
readOnlyStr = "&read-only=true" if readOnly else ""
webbrowser.open(
f"http://localhost:{port}/{view}.html?project={path}{readOnlyStr}{urlFragment}"
)
def showMessageDialog(
message,
infoText,
detailedText=None,
icon=QMessageBox.Icon.Warning,
buttons=None,
defaultButton=None,
):
dialog = QMessageBox()
if icon is not None:
dialog.setIcon(icon)
dialog.setText(message)
dialog.setInformativeText(infoText)
if detailedText is not None:
dialog.setStyleSheet("QTextEdit { font-weight: regular; }")
dialog.setDetailedText(detailedText)
if buttons is not None:
dialog.setStandardButtons(buttons)
if defaultButton is not None:
dialog.setDefaultButton(defaultButton)
# FIXME: The following does *not* make "escape" equivalent to the default button
dialog.setEscapeButton(defaultButton)
return dialog.exec()
@dataclass
class FontraPakExportManager:
appQueue: multiprocessing.Queue
def getSupportedExportFormats(self):
return [typ for (_name, typ) in exportFileTypes]
async def exportAs(self, projectIdentifier, options):
self.appQueue.put(("exportAs", (projectIdentifier, options)))
@dataclass
class ProjectOpenListener:
appQueue: multiprocessing.Queue
def projectOpened(self, projectIdentifier: str) -> None:
self.appQueue.put(("projectOpened", (projectIdentifier,)))
def projectClosed(self, projectIdentifier: str) -> None:
self.appQueue.put(("projectClosed", (projectIdentifier,)))
def runFontraServer(host, port, queue):
logging.basicConfig(
format="%(asctime)s %(name)-17s %(levelname)-8s %(message)s",
level=logging.INFO,
datefmt="%Y-%m-%d %H:%M:%S",
)
projectManager = FileSystemProjectManager(
None,
exportManager=FontraPakExportManager(queue),
projectOpenListener=ProjectOpenListener(queue),
)
server = FontraServer(
host=host,
httpPort=port,
projectManager=projectManager,
versionToken=secrets.token_hex(4),
)
server.setup()
server.run(showLaunchBanner=False)
class CallInMainThreadScheduler(QObject):
signal = pyqtSignal(str)
def __init__(self):
super().__init__()
self.signal.connect(self.receive)
self.items = {}
def receive(self, identifier):
assert threading.current_thread() is threading.main_thread()
function, args, kwargs = self.items.pop(identifier)
function(*args, **kwargs)
def schedule(self, function, args, kwargs):
identifier = secrets.token_hex(4)
self.items[identifier] = function, args, kwargs
self.signal.emit(identifier)
_callInMainThreadScheduler = CallInMainThreadScheduler()
def callInMainThread(function, *args, **kwargs):
_callInMainThreadScheduler.schedule(function, args, kwargs)
def callInNewThread(function, *args, **kwargs):
thread = threading.Thread(target=function, args=args, kwargs=kwargs)
thread.start()
return thread
def queueGetter(queue, callback):
while True:
item = queue.get()
if item is None:
break
callInMainThread(callback, item)
def main():
os.environ["SSL_CERT_FILE"] = certifi.where()
queue = multiprocessing.Queue()
host = "localhost"
port = findFreeTCPPort(host=host)
serverProcess = multiprocessing.Process(
target=runFontraServer, args=(host, port, queue)
)
serverProcess.start()
app = FontraApplication(sys.argv, port)
def cleanup():
queue.put(None)
thread.join()
process = psutil.Process(serverProcess.pid)
for p in [process] + process.children(recursive=True):
if sys.platform != "win32":
p.send_signal(signal.SIGINT)
else:
p.terminate()
app.aboutToQuit.connect(cleanup)
mainWindow = FontraMainWidget(port)
thread = callInNewThread(queueGetter, queue, mainWindow.messageFromServer)
mainWindow.show()
if "test-startup" in sys.argv:
def delayedQuit():
print("test-startup")
app.quit()
QTimer.singleShot(1500, delayedQuit)
sys.exit(app.exec())
if __name__ == "__main__":
multiprocessing.freeze_support()
main()