[go: up one dir, main page]

Menu

[r1450]: / mcomix / keybindings.py  Maximize  Restore  History

Download this file

341 lines (278 with data), 16.4 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
# -*- coding: utf-8 -*-
""" Dynamic hotkey management
This module handles global hotkeys that were previously hardcoded in events.py.
All menu accelerators are handled using GTK's built-in accelerator map. The map
doesn't seem to support multiple keybindings for one action, though, so this
module takes care of the problem.
At runtime, other modules can register a callback for a specific action name.
This action name has to be registered in BINDING_INFO, or an Exception will be
thrown. The module can pass a list of default keybindings. If the user hasn't
configured different bindings, the default ones will be used.
Afterwards, the action will be stored together with its keycode/modifier in a
dictionary:
(keycode: int, modifier: GdkModifierType) =>
(action: string, callback: func, args: list, kwargs: dict)
Default keybindings will be stored here at initialization:
action-name: string => [keycodes: list]
Each action_name can have multiple keybindings.
"""
import os
import shutil
import gtk
import json
from collections import defaultdict
from mcomix import constants
from mcomix import log
#: Bindings defined in this dictionary will appear in the configuration dialog.
#: If 'group' is None, the binding cannot be modified from the preferences dialog.
BINDING_INFO = {
# Navigation between pages, archives, directories
'previous_page' : { 'title' : _('Previous page'), 'group' : _('Navigation') },
'next_page' : { 'title' : _('Next page'), 'group' : _('Navigation') },
'previous_page_ff' : { 'title': _('Back ten pages'), 'group': _('Navigation') },
'next_page_ff' : { 'title': _('Forward ten pages'), 'group': _('Navigation') },
'previous_page_dynamic' : { 'title': _('Previous page (dynamic)'), 'group': _('Navigation') },
'next_page_dynamic' : { 'title': _('Next page (dynamic)'), 'group': _('Navigation') },
'previous_page_singlestep': { 'title': _('Previous page (always one page)'), 'group': _('Navigation') },
'next_page_singlestep': { 'title': _('Next page (always one page)'), 'group': _('Navigation') },
'first_page' : { 'title': _('First page'), 'group': _('Navigation') },
'last_page' : { 'title': _('Last page'), 'group': _('Navigation') },
'go_to' : { 'title': _('Go to page'), 'group': _('Navigation') },
'next_archive' : { 'title': _('Next archive'), 'group': _('Navigation') },
'previous_archive' : { 'title': _('Previous archive'), 'group': _('Navigation') },
'next_directory' : { 'title': _('Next directory'), 'group': _('Navigation') },
'previous_directory' : { 'title': _('Previous directory'), 'group': _('Navigation') },
# Scrolling
'scroll_left_bottom' : { 'title' : _('Scroll to bottom left'), 'group' : _('Scroll')},
'scroll_middle_bottom' : { 'title' : _('Scroll to bottom center'), 'group' : _('Scroll')},
'scroll_right_bottom' : { 'title' : _('Scroll to bottom right'), 'group' : _('Scroll')},
'scroll_left_middle' : { 'title' : _('Scroll to middle left'), 'group' : _('Scroll')},
'scroll_middle' : { 'title' : _('Scroll to center'), 'group' : _('Scroll')},
'scroll_right_middle' : { 'title' : _('Scroll to middle right'), 'group' : _('Scroll')},
'scroll_left_top' : { 'title' : _('Scroll to top left'), 'group' : _('Scroll')},
'scroll_middle_top' : { 'title' : _('Scroll to top center'), 'group' : _('Scroll')},
'scroll_right_top' : { 'title' : _('Scroll to top right'), 'group' : _('Scroll')},
'scroll_down' : { 'title' : _('Scroll down'), 'group' : _('Scroll') },
'scroll_up' : { 'title' : _('Scroll up'), 'group' : _('Scroll') },
'scroll_right' : { 'title' : _('Scroll right'), 'group' : _('Scroll') },
'scroll_left' : { 'title' : _('Scroll left'), 'group' : _('Scroll') },
'smart_scroll_up' : { 'title' : _('Smart scroll up'), 'group' : _('Scroll') },
'smart_scroll_down' : { 'title' : _('Smart scroll down'), 'group' : _('Scroll') },
# View
'zoom_in' : { 'title' : _('Zoom in'), 'group' : _('Zoom')},
'zoom_out' : { 'title' : _('Zoom out'), 'group' : _('Zoom')},
'zoom_original' : { 'title' : _('Normal size'), 'group' : _('Zoom')},
'keep_transformation' : { 'title': _('Keep transformation'), 'group': _('Transformation') },
'rotate_90' : { 'title': _('Rotate 90 degrees CW'), 'group': _('Transformation') },
'rotate_180' : { 'title': _('Rotate 180 degrees'), 'group': _('Transformation') },
'rotate_270' : { 'title': _('Rotate 90 degrees CCW'), 'group': _('Transformation') },
'flip_horiz' : { 'title': _('Flip horizontally'), 'group': _('Transformation') },
'flip_vert' : { 'title': _('Flip vertically'), 'group': _('Transformation') },
'no_autorotation' : { 'title': _('Never autorotate'), 'group': _('Transformation') },
'rotate_90_width' : { 'title': _('Rotate 90 degrees CW'), 'group': _('Autorotate by width') },
'rotate_270_width' : { 'title': _('Rotate 90 degrees CCW'), 'group': _('Autorotate by width') },
'rotate_90_height' : { 'title': _('Rotate 90 degrees CW'), 'group': _('Autorotate by height') },
'rotate_270_height' : { 'title': _('Rotate 90 degrees CCW'), 'group': _('Autorotate by height') },
'double_page' : { 'title': _('Double page mode'), 'group': _('View mode') },
'manga_mode' : { 'title': _('Manga mode'), 'group': _('View mode') },
'invert_scroll' : { 'title': _('Invert smart scroll'), 'group': _('View mode') },
'lens' : { 'title': _('Magnifying lens'), 'group': _('View mode') },
'stretch' : { 'title': _('Stretch small images'), 'group': _('View mode') },
'best_fit_mode' : { 'title': _('Best fit mode'), 'group': _('View mode') },
'fit_width_mode' : { 'title': _('Fit width mode'), 'group': _('View mode') },
'fit_height_mode' : { 'title': _('Fit height mode'), 'group': _('View mode') },
'fit_size_mode' : { 'title': _('Fit size mode'), 'group': _('View mode') },
'fit_manual_mode' : { 'title': _('Manual zoom mode'), 'group': _('View mode') },
# General UI
'exit_fullscreen' : { 'title' : _('Exit from fullscreen'), 'group' : _('User interface')},
'osd_panel' : { 'title' : _('Show OSD panel'), 'group' : _('User interface') },
'minimize' : { 'title' : _('Minimize'), 'group' : _('User interface') },
'fullscreen' : { 'title': _('Fullscreen'), 'group': _('User interface') },
'toolbar' : { 'title': _('Show/hide toolbar'), 'group': _('User interface') },
'menubar' : { 'title': _('Show/hide menubar'), 'group': _('User interface') },
'statusbar' : { 'title': _('Show/hide statusbar'), 'group': _('User interface') },
'scrollbar' : { 'title': _('Show/hide scrollbars'), 'group': _('User interface') },
'thumbnails' : { 'title': _('Thumbnails'), 'group': _('User interface') },
'hide_all' : { 'title': _('Show/hide all'), 'group': _('User interface') },
'slideshow' : { 'title': _('Start slideshow'), 'group': _('User interface') },
# File operations
'delete' : { 'title' : _('Delete'), 'group' : _('File') },
'refresh_archive' : { 'title': _('Refresh'), 'group': _('File') },
'close' : { 'title': _('Close'), 'group': _('File') },
'quit' : { 'title': _('Quit'), 'group': _('File') },
'save_and_quit' : { 'title': _('Save and quit'), 'group': _('File') },
'extract_page' : { 'title': _('Save As'), 'group': _('File') },
'comments' : { 'title': _('Archive comments'), 'group': _('File') },
'properties' : { 'title': _('Properties'), 'group': _('File') },
'preferences' : { 'title': _('Preferences'), 'group': _('File') },
'edit_archive' : { 'title': _('Edit archive'), 'group': _('File') },
'open' : { 'title': _('Open'), 'group': _('File') },
'enhance_image' : { 'title': _('Enhance image'), 'group': _('File') },
'library' : { 'title': _('Library'), 'group': _('File') },
}
# Generate 9 entries for executing command 1 to 9
for i in range(1, 10):
BINDING_INFO['execute_command_%d' %i] = {
'title' : _('Execute external command') + u' (%d)' % i,
'group' : _('External commands')
}
class _KeybindingManager(object):
def __init__(self, window):
#: Main window instance
self._window = window
self._action_to_callback = {} # action name => (func, args, kwargs)
self._action_to_bindings = defaultdict(list) # action name => [ (key code, key modifier), ]
self._binding_to_action = {} # (key code, key modifier) => action name
self._migrate_from_old_bindings()
self._initialize()
def register(self, name, bindings, callback, args=[], kwargs={}):
""" Registers an action for a predefined keybinding name.
@param name: Action name, defined in L{BINDING_INFO}.
@param bindings: List of keybinding strings, as understood
by L{gtk.accelerator_parse}. Only used if no
bindings were loaded for this action.
@param callback: Function callback
@param args: List of arguments to pass to the callback
@param kwargs: List of keyword arguments to pass to the callback.
"""
assert name in BINDING_INFO, "'%s' isn't a valid keyboard action." % name
# Load stored keybindings, or fall back to passed arguments
keycodes = self._action_to_bindings[name]
if keycodes == []:
keycodes = [gtk.accelerator_parse(binding) for binding in bindings ]
for keycode in keycodes:
if keycode in self._binding_to_action.keys():
if self._binding_to_action[keycode] != name:
log.warning(_('Keybinding for "%(action)s" overrides hotkey for another action.'),
{"action": name})
log.warning('Binding %s overrides %r', keycode, self._binding_to_action[keycode])
else:
self._binding_to_action[keycode] = name
self._action_to_bindings[name].append(keycode)
# Add gtk accelerator for labels in menu
if len(self._action_to_bindings[name]) > 0:
key, mod = self._action_to_bindings[name][0]
gtk.accel_map_change_entry('<Actions>/mcomix-main/%s' % name, key, mod, True)
self._action_to_callback[name] = (callback, args, kwargs)
def edit_accel(self, name, new_binding, old_binding):
""" Changes binding for an action
@param name: Action name
@param new_binding: Binding to be assigned to action
@param old_binding: Binding to be removed from action [ can be empty: "" ]
@return None: new_binding wasn't in any action
action name: where new_binding was before
"""
assert name in BINDING_INFO, "'%s' isn't a valid keyboard action." % name
nb = gtk.accelerator_parse(new_binding)
old_action_with_nb = self._binding_to_action.get(nb)
if old_action_with_nb is not None:
# The new key is already bound to an action, erase the action
self._binding_to_action.pop(nb)
self._action_to_bindings[old_action_with_nb].remove(nb)
if old_binding and name != old_action_with_nb:
# The action already had a key that is now being replaced
ob = gtk.accelerator_parse(old_binding)
self._binding_to_action[nb] = name
# Remove action bound to the key.
if ob in self._binding_to_action:
self._binding_to_action.pop(ob)
if ob in self._action_to_bindings[name]:
idx = self._action_to_bindings[name].index(ob)
self._action_to_bindings[name].pop(idx)
self._action_to_bindings[name].insert(idx, nb)
else:
self._binding_to_action[nb] = name
self._action_to_bindings[name].append(nb)
self.save()
return old_action_with_nb
def clear_accel(self, name, binding):
""" Remove binding for an action """
assert name in BINDING_INFO, "'%s' isn't a valid keyboard action." % name
ob = gtk.accelerator_parse(binding)
self._action_to_bindings[name].remove(ob)
self._binding_to_action.pop(ob)
self.save()
def clear_all(self):
""" Removes all keybindings. The changes are only persisted if
save() is called afterwards. """
self._action_to_callback = {}
self._action_to_bindings = defaultdict(list)
self._binding_to_action = {}
def execute(self, keybinding):
""" Executes an action that has been registered for the
passed keyboard event. If no action is bound to the passed key, this
method is a no-op. """
if keybinding in self._binding_to_action:
action = self._binding_to_action[keybinding]
func, args, kwargs = self._action_to_callback[action]
self._window.emit_stop_by_name('key_press_event')
return func(*args, **kwargs)
# Some keys enable additional modifiers (NumLock enables GDK_MOD2_MASK),
# which prevent direct lookup simply by being pressed.
# XXX: Looking up by key/modifier probably isn't the best implementation,
# so limit possible states to begin with?
for stored_binding, action in self._binding_to_action.iteritems():
stored_keycode, stored_flags = stored_binding
if stored_keycode == keybinding[0] and stored_flags & keybinding[1]:
func, args, kwargs = self._action_to_callback[action]
self._window.emit_stop_by_name('key_press_event')
return func(*args, **kwargs)
def save(self):
""" Stores the keybindings that have been set to disk. """
# Collect keybindings for all registered actions
action_to_keys = {}
for action, bindings in self._action_to_bindings.iteritems():
if bindings is not None:
action_to_keys[action] = [
gtk.accelerator_name(keyval, modifiers) for
(keyval, modifiers) in bindings
]
fp = open(constants.KEYBINDINGS_CONF_PATH, "w")
json.dump(action_to_keys, fp, indent=2)
fp.close()
def _initialize(self):
""" Restore keybindings from disk. """
try:
fp = open(constants.KEYBINDINGS_CONF_PATH, "r")
stored_action_bindings = json.load(fp)
fp.close()
except Exception, e:
log.error(_("Couldn't load keybindings: %s"), e)
stored_action_bindings = {}
for action in BINDING_INFO.iterkeys():
if action in stored_action_bindings:
bindings = [
gtk.accelerator_parse(keyname)
for keyname in stored_action_bindings[action] ]
self._action_to_bindings[action] = bindings
for binding in bindings:
self._binding_to_action[binding] = action
else:
self._action_to_bindings[action] = []
def get_bindings_for_action(self, name):
""" Returns a list of (keycode, modifier) for the action C{name}. """
return self._action_to_bindings[name]
def _migrate_from_old_bindings(self):
""" This method deals with upgrading from MComix 1.0 and older to
MComix 1.01, which integrated all UI hotkeys into this class. Simply
remove old files and start from default values. """
gtkrc = os.path.join(constants.CONFIG_DIR, 'keybindings-gtk.rc')
if os.path.isfile(gtkrc):
# In case the user has made modifications to his files,
# keep the old ones around for reference.
if not os.path.isfile(gtkrc + '.delete-me'):
shutil.move(gtkrc, gtkrc + '.delete-me')
if os.path.isfile(constants.KEYBINDINGS_CONF_PATH) and \
not os.path.isfile(constants.KEYBINDINGS_CONF_PATH + '.delete-me'):
shutil.move(constants.KEYBINDINGS_CONF_PATH,
constants.KEYBINDINGS_CONF_PATH + '.delete-me')
_manager = None
def keybinding_manager(window):
""" Returns a singleton instance of the keybinding manager. """
global _manager
if _manager:
return _manager
else:
_manager = _KeybindingManager(window)
return _manager
# vim: expandtab:sw=4:ts=4