| 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
 | from defconQt.baseCodeEditor import CodeEditor, CodeHighlighter
from PyQt5.QtCore import Qt
from PyQt5.QtGui import (QColor, QFont, QKeySequence, QTextCharFormat,
                         QTextCursor)
from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QMessageBox
# TODO: implement search and replace
class MainEditWindow(QMainWindow):
    def __init__(self, font=None, parent=None):
        super(MainEditWindow, self).__init__(parent)
        self.font = font
        self.editor = FeatureTextEditor(self.font.features.text, self)
        self.resize(600, 500)
        fileMenu = QMenu("&File", self)
        fileMenu.addAction("&Save...", self.save, QKeySequence.Save)
        fileMenu.addSeparator()
        fileMenu.addAction("Reload from UFO", self.reload)
        fileMenu.addAction("E&xit", self.close, QKeySequence.Quit)
        self.menuBar().addMenu(fileMenu)
        self.setCentralWidget(self.editor)
        self.setWindowTitle("Font features", self.font)
        # now arm `undoAvailable` to `setWindowModified`
        self.editor.undoAvailable.connect(self.setWindowModified)
    def setWindowTitle(self, title, font):
        if font is not None:
            puts = "[*]%s – %s %s" % (
                title, self.font.info.familyName, self.font.info.styleName)
        else:
            puts = "[*]%s" % title
        super(MainEditWindow, self).setWindowTitle(puts)
    def closeEvent(self, event):
        if self.editor.document().isModified():
            name = QApplication.applicationName()
            closeDialog = QMessageBox(
                QMessageBox.Question,
                name,
                "Save your changes?",
                QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel,
                self
            )
            closeDialog.setInformativeText(
                "Your changes will be lost if you don’t save them."
            )
            closeDialog.setModal(True)
            ret = closeDialog.exec_()
            if ret == QMessageBox.Save:
                self.save()
                event.accept()
            elif ret == QMessageBox.Discard:
                event.accept()
            else:
                event.ignore()
    def reload(self):
        self.font.reloadFeatures()
        self.editor.setPlainText(self.font.features.text)
    def save(self):
        self.editor.write(self.font.features)
class FeatureTextEditor(CodeEditor):
    def __init__(self, text=None, parent=None):
        super(FeatureTextEditor, self).__init__(text, parent)
        self.openBlockDelimiter = '{'
        self.highlighter = FeatureTextHighlighter(self.document())
    def write(self, features):
        features.text = self.toPlainText()
    def keyPressEvent(self, event):
        key = event.key()
        if key == Qt.Key_Return:
            cursor = self.textCursor()
            indentLvl = self.findLineIndentLevel(cursor)
            newBlock = False
            cursor.movePosition(QTextCursor.PreviousCharacter,
                                QTextCursor.KeepAnchor)
            if cursor.selectedText() == self.openBlockDelimiter:
                # We don't add a closing tag if there is text right
                # below with the same indentation level because in
                # that case the user might just be looking to add a
                # new line
                ok = cursor.movePosition(QTextCursor.Down)
                if ok:
                    downIndentLvl = self.findLineIndentLevel(cursor)
                    cursor.select(QTextCursor.LineUnderCursor)
                    if (cursor.selectedText().strip() == ''
                            or downIndentLvl <= indentLvl):
                        newBlock = True
                    cursor.movePosition(QTextCursor.Up)
                else:
                    newBlock = True
                indentLvl += 1
            cursor.select(QTextCursor.LineUnderCursor)
            if newBlock:
                txt = cursor.selectedText().lstrip(" ").split(" ")
                if len(txt) > 1:
                    if len(txt) < 3 and txt[-1][-1] == self.openBlockDelimiter:
                        feature = txt[-1][:-1]
                    else:
                        feature = txt[1]
                else:
                    feature = None
            cursor.movePosition(QTextCursor.EndOfLine)
            cursor.insertText("\n")
            newLineSpace = "".join(self.indent for _ in range(indentLvl))
            cursor.insertText(newLineSpace)
            if newBlock:
                cursor.insertText("\n")
                newLineSpace = "".join((newLineSpace[:-len(self.indent)], "} ",
                                        feature, ";"))
                cursor.insertText(newLineSpace)
                cursor.movePosition(QTextCursor.Up)
                cursor.movePosition(QTextCursor.EndOfLine)
                self.setTextCursor(cursor)
        else:
            super(FeatureTextEditor, self).keyPressEvent(event)
keywordPatterns = [
    "Ascender", "Attach", "CapHeight", "CaretOffset", "CodePageRange",
    "Descender", "FontRevision", "GlyphClassDef", "HorizAxis.BaseScriptList",
    "HorizAxis.BaseTagList", "HorizAxis.MinMax", "IgnoreBaseGlyphs",
    "IgnoreLigatures", "IgnoreMarks", "LigatureCaretByDev",
    "LigatureCaretByIndex", "LigatureCaretByPos", "LineGap", "MarkAttachClass",
    "MarkAttachmentType", "NULL", "Panose", "RightToLeft", "TypoAscender",
    "TypoDescender", "TypoLineGap", "UnicodeRange", "UseMarkFilteringSet",
    "Vendor", "VertAdvanceY", "VertAxis.BaseScriptList",
    "VertAxis.BaseTagList", "VertAxis.MinMax", "VertOriginY",
    "VertTypoAscender", "VertTypoDescender", "VertTypoLineGap", "XHeight",
    "anchorDef", "anchor", "anonymous", "anon", "by", "contour", "cursive",
    "device", "enumerate", "enum", "exclude_dflt", "featureNames", "feature",
    "from", "ignore", "include_dflt", "include", "languagesystem", "language",
    "lookupflag", "lookup", "markClass", "mark", "nameid", "name",
    "parameters", "position", "pos", "required", "reversesub", "rsub",
    "script", "sizemenuname", "substitute", "subtable", "sub", "table",
    "useExtension", "valueRecordDef", "winAscent", "winDescent"
]
class FeatureTextHighlighter(CodeHighlighter):
    def __init__(self, parent=None):
        super(FeatureTextHighlighter, self).__init__(parent)
        keywordFormat = QTextCharFormat()
        keywordFormat.setForeground(QColor(34, 34, 34))
        keywordFormat.setFontWeight(QFont.Bold)
        self.highlightingRules.append(("\\b(%s)\\b"
                                       % ("|".join(keywordPatterns)),
                                       keywordFormat))
        singleLineCommentFormat = QTextCharFormat()
        singleLineCommentFormat.setForeground(Qt.darkGray)
        self.highlightingRules.append(("#[^\n]*", singleLineCommentFormat))
        groupFormat = QTextCharFormat()
        groupFormat.setFontWeight(QFont.Bold)
        groupFormat.setForeground(QColor(96, 106, 161))
        self.highlightingRules.append(("@[A-Za-z0-9_.]+", groupFormat))
 |