File: actioncollection.py

package info (click to toggle)
frescobaldi 3.0.0~git20161001.0.eec60717%2Bds1-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 19,792 kB
  • ctags: 5,843
  • sloc: python: 37,853; sh: 180; makefile: 69
file content (362 lines) | stat: -rw-r--r-- 13,381 bytes parent folder | download | duplicates (2)
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
# This file is part of the Frescobaldi project, http://www.frescobaldi.org/
#
# Copyright (c) 2008 - 2014 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.

"""
In this module are two classes, ActionCollection and ShortcutCollection.
Both must be inherited to do something useful.

ActionCollection keeps a fixed list of QActions, set as instance attributes in
the createActions() method. The icons and default shortcuts may also be set in
the same method. The texts should be set in the translateUI() method.

The ActionCollection then keeps track of possibly changed keyboard shortcuts by
loading them from the config and connecting to the app.settingsChanged() signal.

ShortcutCollection keeps a variable list of QActions, for which default
shortcuts must be set in the createDefaultShortcuts() method.

This actions must not be connected to, but they are only used to set keyboard
shortcuts for a module that needs not to be loaded initially for the shortcuts
to work. If a shortcut is pressed, the real action is queried using the
realAction() method, which should return the corresponding action in the UI.
That one is than triggered.

The module may provide the user with a means to change the keyboard shortcuts,
which then should call setShortcuts() to do it. The module may also query the
currently set shortcuts for an action using shortcuts().
"""


import weakref

from PyQt5.QtCore import QSettings, Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QAction

import app


class ActionCollectionBase(object):
    """Abstract base class. Can load and keep a list of QActions.

    You must subclass this class and provide a name for the actioncollection
    in the 'name' class attribute.
    
    """
    def __init__(self, widget=None):
        self._widget = weakref.ref(widget) if widget else lambda: None
        self._actions = {}  # maps name to action
        self._defaults = {} # maps name to default list of shortcuts
        app.settingsChanged.connect(self.load)
    
    def widget(self):
        """Returns the widget given on construction or None."""
        return self._widget()
        
    def setDefaultShortcuts(self, name, shortcuts):
        """Set a default list of QKeySequence objects for the named action."""
        self._defaults[name] = shortcuts
        
    def defaultShortcuts(self, name):
        """Returns the default shortcuts (list of QKeySequences) for the action.
        
        If not defined, returns None.
        
        """
        return self._defaults.get(name)
        
    def actions(self):
        """Returns the dictionary with actions."""
        return self._actions
        
    def defaults(self):
        """Returns the dictionary with actions that have a default shortcut."""
        return self._defaults
        
    def shortcuts(self, name):
        """Returns the list of shortcuts for the named action, or None."""
        try:
            return self._actions[name].shortcuts()
        except KeyError:
            pass
    
    def setShortcuts(self, name, shortcuts):
        """Implement to set the shortcuts list for our action."""
        pass
    
    def settingsGroup(self):
        """Returns settings group to load/save shortcuts from or to."""
        s = QSettings()
        scheme = s.value("shortcut_scheme", "default", str)
        s.beginGroup("shortcuts/{0}/{1}".format(scheme, self.name))
        return s
        
    def load(self):
        """Implement to load shortcuts from our settingsGroup()."""
        pass
    
    def title(self):
        """If this returns a meaningful title, actions can be grouped in the shortcut settings dialog."""
        pass


class ActionCollection(ActionCollectionBase):
    """Keeps a fixed list of QActions as instance attributes.
    
    Subclass this and add the actions as instance attributes in
    the createActions() method.
    
    You can set the default shortcuts directly in the actions in the
    createActions() method, it is not needed to use the setDefaultShortcuts()
    method for that.
    
    Set the titles for the actions in the translateUI() method.
    
    """
    def __init__(self, parent=None):
        """Creates the ActionCollection.
        
        parent is an optional widget that is also the parent for the created actions.
        
        """
        super(ActionCollection, self).__init__(parent)
        self.createActions(parent)
        self._actions = dict(i for i in self.__dict__.items() if not i[0].startswith('_'))
        self.storeDefaults()
        self.load(False) # load the shortcuts without resettings defaults
        app.translateUI(self)
        
    def createActions(self, parent=None):
        """Should add actions as instance attributes.
        
        The QActions should get icons and shortcuts. Texts should be set
        in translateUI(). The actions are created with the parent given on instantiation.
        
        """
        pass

    def translateUI(self):
        """Should (re)translate all the titles of the actions."""
        pass
    
    def storeDefaults(self):
        """Saves the preset default QKeySequence lists for the actions."""
        for name, action in self._actions.items():
            if action.shortcuts():
                self.setDefaultShortcuts(name, action.shortcuts())

    def setShortcuts(self, name, shortcuts):
        """Sets the shortcuts list for our action. Use an empty list to remove the shortcuts."""
        action = self.actions().get(name)
        if not action:
            return
        
        default = self.defaultShortcuts(name)
        setting = self.settingsGroup()
        action.setShortcuts(shortcuts)
        setting.setValue(name, shortcuts)
        if default:
            if shortcuts == default:
                setting.remove(name)
            else:
                setting.setValue(name, shortcuts)
        else:
            if shortcuts:
                setting.setValue(name, shortcuts)
            else:
                setting.remove(name)
    
    def load(self, restoreDefaults=True):
        """Reads keyboard shortcuts from the settings.
        
        If restoreDefaults == True, resets the other shortcuts to their default
        values. If restoreDefaults == False, does not touch the other shortcuts.
        
        """
        settings = self.settingsGroup()
        keys = settings.allKeys()
        for name in keys:
            try:
                shortcuts = settings.value(name, [], QKeySequence)
            except TypeError:
                # PyQt5 raises TypeError when an empty list was stored
                shortcuts = []
            try:
                self._actions[name].setShortcuts(shortcuts)
            except KeyError:
                settings.remove(name)
        if restoreDefaults:
            for name in self._actions:
                if name not in keys:
                    self._actions[name].setShortcuts(self._defaults.get(name) or [])


class ShortcutCollection(ActionCollectionBase):
    """An ActionCollection type that only saves actions that have a keyboard shortcut.
    
    Should always be instantiated with a visible widget (preferably MainWindow)
    as parent.
    
    Use the setShortcuts() method to set a list (possibly empty) of QKeySequence
    objects.  Every change causes other instances of the same-named collection
    to reload.
    
    This serves two purposes:
    1. save keyboard shortcuts for actions created by the user or from a very large list
    2. make the keyboard shortcuts working even if the component the actions are
       contained in is not even loaded yet.
       
       To make this work, implement the realAction() method to instantiate the widget the
       action is meant for and then return the real action.
       
    """
    # save weak references to other instances with the same name and sync then.
    others = {}
    
    # shortcut context to use by default
    shortcutContext = Qt.WindowShortcut
    
    def __init__(self, widget):
        """Creates the ShortcutCollection.
        
        The widget is required as actions are added to it, so their keyboard
        shortcuts get triggered.
        
        """
        super(ShortcutCollection, self).__init__(widget)
        self.createDefaultShortcuts()
        self.load()
        self.others.setdefault(self.name, []).append(weakref.ref(self))
    
    def createDefaultShortcuts(self):
        """Should set some default shortcut lists using setDefaultShortcuts()."""
        pass
        
    def load(self):
        """Reads keyboard shortcuts from the settings.  Instantiates QActions as needed."""
        # clears all actions
        for a in self._actions.values():
            a.setParent(None)
        self._actions = {}
        # then set defaults
        for name, shortcuts in self.defaults().items():
            self.action(name).setShortcuts(shortcuts)
        # then load
        settings = self.settingsGroup()
        for name in settings.allKeys():
            try:
                shortcuts = settings.value(name, [], QKeySequence)
            except TypeError:
                # PyQt5 raises TypeError when an empty list was stored
                shortcuts = []
            if not shortcuts:
                if not self.removeAction(name):
                    # if it did not exist, remove key from config
                    settings.remove(name)
            else:
                self.action(name).setShortcuts(shortcuts)
    
    def setShortcuts(self, name, shortcuts):
        """Sets the shortcuts list for our action. Use an empty list to remove the shortcuts."""
        if shortcuts:
            self.action(name).setShortcuts(shortcuts)
            self.settingsGroup().setValue(name, shortcuts)
        else:
            self.removeAction(name)
            if name in self.defaults():
                # save empty list because there exists a default value
                self.settingsGroup().setValue(name, [])
            else:
                self.settingsGroup().remove(name)
        self.reloadOthers()
    
    def restoreDefaultShortcuts(self, name):
        """Resets the shortcuts for the specified action to their default value."""
        shortcuts = self.defaultShortcuts(name)
        if shortcuts:
            self.action(name).setShortcuts(shortcuts)
        else:
            self.removeAction(name)
        self.settingsGroup().remove(name)
        self.reloadOthers()
        
    def removeAction(self, name):
        """(Internal) Removes the named action, returning True it it did exist."""
        try:
            a = self._actions[name]
        except KeyError:
            return False
        a.setParent(None)
        del self._actions[name]
        return True
        
    def action(self, name):
        """Returns a QAction for the name, instantiating it if necessary."""
        try:
            a = self._actions[name]
        except KeyError:
            a = self._actions[name] = QAction(self.widget())
            a.setShortcutContext(self.shortcutContext)
            a.triggered.connect(lambda: self.triggerAction(name))
            self.widget().addAction(a)
        return a
    
    def triggerAction(self, name):
        """Called when the user presses a saved keyboard shortcut."""
        a = self.realAction(name)
        if a:
            a.trigger()
            
    def realAction(self, name):
        """Implement this to return the real action the name refers to,
        
        This is called when the text and icon are needed (e.g. when the shortcut
        dialog is opened) or when our "shadow" action keyboard shortcut is triggered.
        
        The function may return None, e.g. when the action our name refers to does
        not exist anymore.  In that case our action is also removed.
        
        """
        pass
    
    def actions(self):
        """Returns our real actions instead of the shadow ones."""
        d = {}
        changed = False
        for name in list(self._actions):
            a = self.realAction(name)
            if a:
                d[name] = a
            else:
                self.removeAction(name)
                changed = True
        if changed:
            self.reloadOthers()
        return d
    
    def reloadOthers(self):
        """Reload others managing the same shortcuts (e.g. in case of multiple mainwindows)."""
        for ref in self.others[self.name][:]:
            other = ref()
            if not other:
                self.others[self.name].remove(ref)
            elif other is not self:
                other.load()