File: expand.py

package info (click to toggle)
frescobaldi 1.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 4,240 kB
  • ctags: 2,434
  • sloc: python: 15,614; lisp: 28; sh: 25; makefile: 2
file content (454 lines) | stat: -rw-r--r-- 18,032 bytes parent folder | download
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
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008, 2009, 2010 by Wilbert Berendsen
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# See http://www.gnu.org/licenses/ for more information.

from __future__ import unicode_literals

"""
Expand Manager, manages expansions.
"""
import re

from PyQt4.QtCore import Qt
from PyQt4.QtGui import (
    QFont, QSplitter, QTextEdit, QTreeWidget, QTreeWidgetItem, QVBoxLayout)

from PyKDE4.kdecore import KConfig, KGlobal, i18n
from PyKDE4.kdeui import (
    KDialog, KKeySequenceWidget, KMessageBox, KStandardGuiItem,
    KTreeWidgetSearchLine, KVBox)
from PyKDE4.ktexteditor import KTextEditor

import ly.parse, ly.pitch

from kateshell.app import cacheresult
from kateshell.shortcut import ShortcutClient
from frescobaldi_app.highlight import LilyPondHighlighter


class ExpandManager(ShortcutClient):
    def __init__(self, mainwin):
        self.mainwin = mainwin
        ShortcutClient.__init__(self, mainwin.expansionShortcuts)
        self.expansions = KConfig("expansions", KConfig.NoGlobals, "appdata")
        # delete shortcut actions that do not exist here anymore
        self.shakeHands(self.expansionsList())
        
    def actionTriggered(self, name):
        return self.doExpand(name)
        
    def populateAction(self, name, action):
        action.setText(self.description(name))
        
    def expand(self):
        """
        Reads the last word in the current document. If it is not
        an expansion, open the expansion dialog. If the string matches
        multiple possible expansions, also open the dialog with the matching
        expansions shown.
        """
        doc = self.mainwin.currentDocument()
        cursor = doc.view.cursorPosition()
        lastWord = re.split("\W+",
            doc.line()[:cursor.column()])[-1]
        
        if lastWord and self.expansionExists(lastWord):
            # delete entered expansion name
            begin = KTextEditor.Cursor(cursor)
            begin.setColumn(begin.column() - len(lastWord))
            # write the expansion
            self.doExpand(lastWord, remove=KTextEditor.Range(begin, cursor))
            return
        # open dialog and let the user choose
        self.expansionDialog().show()
        
    @cacheresult
    def expansionDialog(self):
        return ExpansionDialog(self)

    def expansionExists(self, name):
        return (self.expansions.hasGroup(name) and
                self.expansions.group(name).hasKey("Name"))

    def expansionsList(self):
        """
        Return list of all defined shortcuts.
        """
        return [name for name in self.expansions.groupList()
                     if self.expansions.group(name).hasKey("Name")]

    def description(self, name):
        """
        Return the description for the expansion name.
        """
        return self.expansions.group(name).readEntry("Name", "")
    
    def doExpand(self, expansion, remove=None):
        """
        Perform the given expansion, must exist.
        if remove is given, use doc.replaceText to replace that Range.
        """
        doc = self.mainwin.currentDocument()
        
        group = self.expansions.group(expansion)
        text = group.readEntry("Text", "")
        
        # where to insert the text:
        cursor = remove and remove.start() or doc.view.cursorPosition()
        
        # translate pitches (marked by @)
        # find the current language
        lang = ly.parse.documentLanguage(doc.textToCursor(cursor))
        writer = ly.pitch.pitchWriter[lang or "nederlands"]
        reader = ly.pitch.pitchReader["nederlands"]
        
        def repl(matchObj):
            pitch = matchObj.group(1)
            result = reader(pitch)
            if result:
                note, alter = result
                return writer(note, alter)
            return matchObj.group()
            
        text = re.sub(r"@([a-z]+)(?!\.)", repl, text)
            
        # if the expansion starts with a backslash and the character just 
        # before the cursor is also a backslash, don't repeat it.
        if (text.startswith("\\") and cursor.column() > 0
            and doc.line()[cursor.column()-1] == "\\"):
            text = text[1:]
        
        doc.manipulator().insertTemplate(text, cursor, remove)

    def addExpansion(self, text = None):
        """ Open the expansion dialog with a new expansion given in text. """
        dlg = self.expansionDialog()
        dlg.show()
        dlg.addItem(text)


class ExpansionDialog(KDialog):
    def __init__(self, manager):
        self.manager = manager
        KDialog.__init__(self, manager.mainwin)
        self.setCaption(i18n("Expansion Manager"))
        self.setButtons(KDialog.ButtonCode(
            KDialog.Help |
            KDialog.Ok | KDialog.Close | KDialog.User1 | KDialog.User2 ))
        self.setButtonGuiItem(KDialog.User1, KStandardGuiItem.remove())
        self.setButtonGuiItem(KDialog.User2, KStandardGuiItem.add())
        self.closeClicked.connect(self.reject)
        self.setDefaultButton(KDialog.Ok)
        self.setHelp("expand")
        
        layout = QVBoxLayout(self.mainWidget())
        layout.setContentsMargins(0, 0, 0, 0)
        
        search = KTreeWidgetSearchLine()
        search.setClickMessage(i18n("Search..."))
        layout.addWidget(search)
        
        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)
        layout.addWidget(splitter)

        tree = QTreeWidget()
        tree.setColumnCount(3)
        tree.setHeaderLabels((i18n("Name"), i18n("Description"), i18n("Shortcut")))
        tree.setRootIsDecorated(False)
        tree.setAllColumnsShowFocus(True)
        search.setTreeWidget(tree)
        splitter.addWidget(tree)
        
        box = KVBox()
        splitter.addWidget(box)
        
        key = KKeySequenceWidget(box)
        key.layout().setContentsMargins(0, 0, 0, 0)
        key.layout().insertStretch(0, 1)
        key.setEnabled(False)
        
        edit = QTextEdit(box)
        edit.setAcceptRichText(False)
        edit.setStyleSheet("QTextEdit { font-family: monospace; }")
        edit.item = None
        edit.dirty = False
        ExpandHighlighter(edit.document())
        
        # whats this etc.
        tree.setWhatsThis(i18n(
            "This is the list of defined expansions.\n\n"
            "Click on a row to see or change the associated text. "
            "Doubleclick a shortcut or its description to change it. "
            "You can also press F2 to edit the current shortcut.\n\n"
            "Use the buttons below to add or remove expansions.\n\n"
            "There are two ways to use the expansion: either type the "
            "shortcut in the text and then call the Expand function, or "
            "just call the Expand function (default shortcut: Ctrl+.), "
            "choose the expansion from the list and press Enter or click Ok."
            ))
            
        edit.setWhatsThis(
            "<html><head><style type='text/css'>"
            "td.short {{ font-family: monospace; font-weight: bold; }}"
            "</style></head><body>"
            "<p>{0}</p><table border=0 width=300 cellspacing=2><tbody>"
            "<tr><td class=short align=center>(|)</td><td>{1}</td></tr>"
            "<tr><td class=short align=center>@</td><td>{2}</td></tr>"
            "</tbody></table></body></html>".format(
            i18n("This is the text associated with the selected shortcut. "
                 "Some characters have special meaning:"),
            i18n("Place the cursor on this spot."),
            i18n("Translate the following pitch."),
            ))
        
        self.searchLine = search
        self.treeWidget = tree
        self.key = key
        self.edit = edit
        
        self.restoreDialogSize(config())
        
        # load the expansions
        for name in sorted(self.manager.expansionsList()):
            self.createItem(name, self.manager.description(name))

        tree.sortByColumn(1, Qt.AscendingOrder)
        tree.setSortingEnabled(True)
        tree.resizeColumnToContents(1)
        
        self.user1Clicked.connect(self.removeItem)
        self.user2Clicked.connect(self.addItem)
        edit.textChanged.connect(self.editChanged)
        search.textChanged.connect(self.checkMatch)
        tree.itemSelectionChanged.connect(self.updateSelection)
        tree.itemChanged.connect(self.itemChanged, Qt.QueuedConnection)
        key.keySequenceChanged.connect(self.keySequenceChanged)
    
    def createItem(self, name, description):
        """ Create a new item. """
        item = QTreeWidgetItem(self.treeWidget)
        item.groupName = name
        item.setFont(0, QFont("monospace"))
        item.setText(0, name)
        item.setText(1, description)
        item.setText(2, self.manager.shortcutText(name))
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEditable | Qt.ItemIsEnabled)
        return item
    
    def addItem(self, text=None):
        """
        Add a new empty item (or use the text in the edit if no previous item
        is selected). The new item becomes the selected item.
        If text is given, put it in the text edit widget.
        """
        num = 0
        name = "new"
        while self.manager.expansionExists(name):
            num += 1
            name = "new{0}".format(num)
        description = i18n("New Item")
        if num:
            description += " {0}".format(num)
        self.manager.expansions.group(name).writeEntry("Name", description)
        self.searchLine.clear() # otherwise strange things happen...
        item = self.createItem(name, description)
        if self.edit.item is None:
            # the user might have typed/pasted text in the edit already,
            # intending to add a new expansion.
            self.edit.item = item
            self.saveEditIfNecessary()
        self.setCurrentItem(item)
        self.treeWidget.setFocus()
        self.treeWidget.editItem(item, 0)
        self.edit.dirty = True # so that our (empty) text gets saved
        if text is not None:
            self.edit.setText(text)
    
    def removeItem(self):
        """ Remove the current item. """
        item = self.currentItem()
        if item:
            index = self.treeWidget.indexOfTopLevelItem(item)
            setIndex = index + 1 < self.treeWidget.topLevelItemCount()
            self.manager.expansions.deleteGroup(item.groupName)
            self.manager.removeShortcut(item.groupName)
            self.treeWidget.takeTopLevelItem(index)
            if setIndex:
                self.setCurrentItem(self.treeWidget.topLevelItem(index))
    
    def items(self):
        """ Return an iterator over all the items in our dialog. """
        return (self.treeWidget.topLevelItem(i)
                for i in range(self.treeWidget.topLevelItemCount()))
    
    def currentItem(self):
        """ Returns the currently selected item, if any. """
        items = self.treeWidget.selectedItems()
        if items and not items[0].isHidden():
            return items[0]
            
    def setCurrentItem(self, item):
        """ Sets the item to be the current and selected item. """
        item.setSelected(True)
        self.updateSelection()
        self.treeWidget.setCurrentItem(item)
        self.treeWidget.scrollToItem(item)

    def checkMatch(self, text):
        """ Called when the user types in the search line. """
        items = self.treeWidget.findItems(text, Qt.MatchExactly, 0)
        if len(items) == 1:
            self.setCurrentItem(items[0])
                
    def updateSelection(self):
        """ (Internal use) update the edit widget when selection changes. """
        items = self.treeWidget.selectedItems()
        self.saveEditIfNecessary()
        if items:
            name = items[0].text(0)
            group = self.manager.expansions.group(name)
            self.edit.setPlainText(group.readEntry("Text", ""))
            self.edit.item = items[0]
            self.edit.dirty = False
            # key shortcut widget
            self.key.setEnabled(True)
            self.manager.keyLoadShortcut(self.key, name)
        else:
            self.edit.item = None
            self.edit.clear()
            self.key.clearKeySequence()
            self.key.setEnabled(False)
    
    def itemChanged(self, item, column):
        """ Called when the user has edited an item. """
        if column == 0 and item.groupName != item.text(0):
            # The user has changed the mnemonic
            items = [i for i in self.items() if i.text(0) == item.text(0)]
            if len(items) > 1:
                KMessageBox.error(self.manager.mainwin, i18n(
                    "Another expansion already uses this name.\n\n"
                    "Please use a different name."))
                item.setText(0, item.groupName)
                self.treeWidget.editItem(item, 0)
            elif not re.match(r"\w+$", item.text(0)):
                KMessageBox.error(self.manager.mainwin, i18n(
                    "Please only use letters, numbers and the underscore "
                    "character in the expansion name."))
                item.setText(0, item.groupName)
                self.treeWidget.editItem(item, 0)
            else:
                # apply the changed mnemonic
                old, new = item.groupName, item.text(0)
                group = self.manager.expansions.group(new)
                group.writeEntry("Name", item.text(1))
                group.writeEntry("Text", self.manager.expansions.group(old).readEntry("Text", ""))
                self.manager.expansions.deleteGroup(old)
                # move the shortcut
                if self.manager.shortcut(old):
                    self.manager.setShortcut(new, self.manager.shortcut(old))
                self.manager.removeShortcut(old)
                item.groupName = item.text(0)
                self.treeWidget.scrollToItem(item)
        elif column == 1:
            group = self.manager.expansions.group(item.text(0))
            if item.text(1):
                group.writeEntry("Name", item.text(1))
                self.treeWidget.scrollToItem(item)
                self.treeWidget.resizeColumnToContents(1)
            else:
                KMessageBox.error(self.manager.mainwin, i18n(
                    "Please don't leave the description empty."))
                item.setText(1, group.readEntry("Name", ""))
                self.treeWidget.editItem(item, 1)
        elif column == 2:
            # User should not edit textual representation of shortcut
            item.setText(2, self.manager.shortcutText(item.text(0)))
    
    def editChanged(self):
        """ Marks our edit view as changed. """
        self.edit.dirty = True

    def saveEditIfNecessary(self):
        """ (Internal use) save the edit if it has changed. """
        if self.edit.dirty and self.edit.item:
            self.manager.expansions.group(self.edit.item.text(0)).writeEntry(
                "Text", self.edit.toPlainText())
            self.edit.dirty = False
    
    def keySequenceChanged(self, seq):
        """ Called when the user has changed the keyboard shortcut. """
        item = self.currentItem()
        if item:
            self.manager.keySaveShortcut(self.key, item.text(0), seq)
            item.setText(2, seq.toString())
            self.updateShortcuts()
        
    def updateShortcuts(self):
        """
        Checks if shortcuts have disappeared by stealing them from other
        keyboard shortcut dialogs.  And initialize the shortcut button to
        check for collisions.
        """
        names = self.manager.shortcuts()
        for item in self.items():
            if item.text(2) and item.text(0) not in names:
                item.setText(2, '')
            elif item.text(0) in names:
                item.setText(2, self.manager.shortcutText(item.text(0)))
        item = self.currentItem()
        if item:
            self.manager.keyLoadShortcut(self.key, item.text(0))
        self.manager.keySetCheckActionCollections(self.key)
    
    def show(self):
        self.updateShortcuts()
        KDialog.show(self)
        self.searchLine.setFocus()
        
    def done(self, result):
        self.saveEditIfNecessary()
        self.manager.expansions.sync()
        if result:
            items = self.treeWidget.selectedItems() or self.items()
            items = [item for item in items if not item.isHidden()]
            if len(items) == 1:
                expansion = items[0].text(0)
                self.manager.doExpand(expansion)
        self.saveDialogSize(config())
        KDialog.done(self, result)


class ExpandHighlighter(LilyPondHighlighter):
    """
    LilyPond Highlighter that also highlights some non-LilyPond input that
    the expander uses.
    """
    def highlightBlock(self, text):
        matches = []
        def repl(m):
            matches.append((m.start(), len(m.group())))
            return ' ' * len(m.group())
        text = re.compile(r"\(\|\)|@").sub(repl, text)
        super(ExpandHighlighter, self).highlightBlock(text)
        for start, count in matches:
            self.setFormat(start, count, self.formats['special'])


def config():
    return KGlobal.config().group("expand manager")