Ejemplo n.º 1
0
def key_gtk2openbox(key, mods):
	result = ""
	if mods:
		s = gtk.accelerator_name(0, mods)
		svec = [replace_table_gtk2openbox[i] for i in s[1:-1].split('><')]
		result = '-'.join(svec)
	if key:
		k = gtk.accelerator_name(key, 0)
		if result != "":
			result += '-'
		result += k
	return result
Ejemplo n.º 2
0
    def refresh_model(self):
        """ Initializes the model from data provided by the keybinding
        manager. """
        self.treestore.clear()
        section_order = list(
            set(d['group'] for d in keybindings.BINDING_INFO.values()))
        section_order.sort()
        section_parent_map = {}
        for section_name in section_order:
            row = [section_name, None, False]
            row.extend([
                None,
            ] * self.accel_column_num)
            section_parent_map[section_name] = self.treestore.append(None, row)

        action_treeiter_map = self.action_treeiter_map = {}
        # Sort actions by action name
        actions = sorted(keybindings.BINDING_INFO.items(),
                         key=lambda item: item[1]['title'])
        for action_name, action_data in actions:
            title = action_data['title']
            group_name = action_data['group']
            old_bindings = self.keymanager.get_bindings_for_action(action_name)
            acc_list = [
                "",
            ] * self.accel_column_num
            for idx in range(0, self.accel_column_num):
                if len(old_bindings) > idx:
                    acc_list[idx] = gtk.accelerator_name(*old_bindings[idx])

            row = [title, action_name, True]
            row.extend(acc_list)
            treeiter = self.treestore.append(section_parent_map[group_name],
                                             row)
            action_treeiter_map[action_name] = treeiter
Ejemplo n.º 3
0
 def handle_key_event(self, event):
     '''
     Internal function to handle key event.
     '''
     modifiers = []
     
     # Add Ctrl modifier.
     if event.state & gtk.gdk.CONTROL_MASK:
         modifiers.append("Ctrl")    
         
     # Add Super modifiers.
     if event.state & gtk.gdk.SUPER_MASK:
         modifiers.append("Super")
         
     # Add Hyper modifiers.
     if event.state & gtk.gdk.HYPER_MASK:
         modifiers.append("Hyper")
         
     # Add Alt modifier.
     if event.state & gtk.gdk.MOD1_MASK:
         modifiers.append("Alt")    
         
     if event.state & gtk.gdk.SHIFT_MASK:
         modifiers.append("Shift")    
     modifiers.append(gtk.accelerator_name(event.keyval, 0))
     key_name = " + ".join(modifiers)
     
     if key_name in self.keymap:
         self.keymap[key_name]()
	def add(self, accel, callback, data=None):
		num = len(accel.accelerators)
		mapping = self.accelerators

		for i in range(num):
			parsed = gtk.accelerator_parse(accel.accelerators[i])

			if not gtk.accelerator_valid(*parsed):
				return

			named = gtk.accelerator_name(*parsed)
			inmap = named in mapping

			if i == num - 1 and inmap:
				# Last one cannot be in the map
				return
			elif inmap and isinstance(mapping[named], AccelCallback):
				# It's already mapped...
				return
			else:
				if not inmap:
					mapping[named] = {}

				if i == num - 1:
					mapping[named] = AccelCallback(accel, callback, data)

				mapping = mapping[named]
Ejemplo n.º 5
0
        def on_accel_edited(renderer, path, accel_key, accel_mods,
                            hardware_keycode):
            iter = self.treestore.get_iter(path)
            col = column + 3  # accel cells start from 3 position
            old_accel = self.treestore.get(iter, col)[0]
            new_accel = gtk.accelerator_name(accel_key, accel_mods)
            self.treestore.set_value(iter, col, new_accel)
            action_name = self.treestore.get_value(iter, 1)
            affected_action = self.keymanager.edit_accel(
                action_name, new_accel, old_accel)

            # Find affected row and cell
            if affected_action == action_name:
                for idx in range(0, self.accel_column_num):
                    if idx != column and self.treestore.get(
                            iter, idx + 3)[0] == new_accel:
                        self.treestore.set_value(iter, idx + 3, "")
            elif affected_action is not None:
                titer = self.action_treeiter_map[affected_action]
                for idx in range(0, self.accel_column_num):
                    if self.treestore.get(titer, idx + 3)[0] == new_accel:
                        self.treestore.set_value(titer, idx + 3, "")

            # updating gtk accelerator for label in menu
            if self.keymanager.get_bindings_for_action(action_name)[0] == (
                    accel_key, accel_mods):
                gtk.accel_map_change_entry(
                    '<Actions>/mcomix-main/%s' % action_name, accel_key,
                    accel_mods, True)
Ejemplo n.º 6
0
    def _on_accelerator_entry_key_press(self, entry, event):
        """Callback for handling key events in the accelerator
        entry. Accelerators are added by pressing Ctrl, Shift and/or
        Alt in combination with the desired key. Delete and Backspace
        can be used to clear the entry. No other types of editing is
        possible."""

        # Tab must be handled as normal. Otherwise we can't move from
        # the entry.
        if event.keyval == gtk.keysyms.Tab:
            return False

        modifiers = event.get_state() & gtk.accelerator_get_default_mod_mask()
        modifiers = int(modifiers)

        # Check if we should clear the entry
        clear_keys = [gtk.keysyms.Delete,
                      gtk.keysyms.KP_Delete,
                      gtk.keysyms.BackSpace]

        if modifiers == 0:
            if event.keyval in clear_keys:
                entry.set_text('')
            return True

        # Check if the accelerator is valid and add it to the entry
        if gtk.accelerator_valid(event.keyval, modifiers):
            accelerator = gtk.accelerator_name(event.keyval, modifiers)
            entry.set_text(accelerator)

        return True
Ejemplo n.º 7
0
 def keyPressCommand(self, event):
     '''
 Create command lines for variuos key presses.
 
 @param event: Key press at-spi event.
 @type event: Accessibility.DeviceEvent
 '''
     if event.id in self.MODIFIERS or \
           event.event_string.startswith('ISO'):
         return
     if event.modifiers in (0, gtk.gdk.SHIFT_MASK) and \
           gtk.gdk.keyval_to_unicode(event.id):
         self.typed_text += unichr(gtk.gdk.keyval_to_unicode(event.id))
     else:
         if self.frame_name:
             self.commands_queue.put_nowait('waittillguiexist("%s")\n' % \
                                              self.frame_name)
             self.frame_name = ''
         if self.typed_text:
             self.commands_queue.put_nowait('generatekeyevent("%s")\n' % \
                                              self.typed_text)
             self.typed_text = ''
         self.commands_queue.put_nowait('generatekeyevent("%s")\n' % \
                                          gtk.accelerator_name(event.id,
                                                               event.modifiers))
Ejemplo n.º 8
0
    def create_entry(self, actwrap):
        d = gtk.Dialog(parent=None,
                       flags=gtk.DIALOG_MODAL,
                       title='Enter new keypress',
                       buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        action = actwrap.action
        e = gtk.Entry()
        e.show()
        d.vbox.pack_start(e, expand=False)
        key, mod = gtk.accel_map_lookup_entry(action.accel_path)
        accel = gtk.accelerator_name(key, mod)
        e.set_text(accel)

        def _response(dlg, response):
            d.hide()
            if response == gtk.RESPONSE_ACCEPT:
                newaccel = e.get_text()
                action.set_accel(newaccel)
                actwrap.reset_markup()
                key, mod = gtk.accelerator_parse(newaccel)
                gtk.accel_map_change_entry(action.accel_path, key, mod, True)
            d.destroy()

        d.connect('response', _response)
        d.run()
    def set_accelerator(self, keyval, mod):
        # Check whether accelerator already exists
        self.remove_accelerator(self.current_node)

        name = gtk.accelerator_name(keyval, mod)

        if name == '':
            self.current_node.shorcut = None
            self.save_current_tool()
            return True

        col = self.accelerator_collision(name, self.current_node)

        if col:
            dialog = gtk.MessageDialog(
                self.dialog, gtk.DIALOG_MODAL, gtk.MESSAGE_ERROR,
                gtk.BUTTONS_OK,
                _('This accelerator is already bound to %s') %
                (', '.join(map(lambda x: x.name, col)), ))

            dialog.run()
            dialog.destroy()

            self.add_accelerator(self.current_node)
            return False

        self.current_node.shortcut = name
        self.add_accelerator(self.current_node)
        self.save_current_tool()

        return True
Ejemplo n.º 10
0
 def create_toggle_button(self,
                          name,
                          action,
                          index,
                          text='',
                          accel_key=None):
     '''
     create a togglebutton
     @param name: the button's name, a string
     @param action: one of ACTION Type Constants 
     @param index: the button's index in button list, an int num
     @param text: the button's tooltip text, a string
     '''
     button = ToggleButtonItem(
         (app_theme.get_pixbuf("action/" + name + "_normal.png"),
          app_theme.get_pixbuf("action/" + name + "_press.png"),
          app_theme.get_pixbuf("action/" + name + "_hover.png"),
          app_theme.get_pixbuf("action/" + name + "_press.png"), None),
         index, self._toggle_button_group.set_index,
         self._toggle_button_group.get_index)
     button.connect("pressed", self._toggle_button_pressed)
     button.connect("toggled", self._toggle_button_toggled, action)
     button.connect("enter-notify-event", self._show_tooltip, text)
     button.set_name(name)
     #self.toolbox.pack_start(button)
     self._toggle_button_group.pack_start(button)
     self._toggle_button_list.append(button)
     if accel_key:
         self.__button_accelerator_dict[gtk.accelerator_name(
             *gtk.accelerator_parse(accel_key))] = button
Ejemplo n.º 11
0
    def next (self):
       while self.to_traverse != []:
	 (w, prefix, level) = self.to_traverse.pop ()

	 if isinstance (w, gtk.MenuItem):
	   accel_path = ""
	   result = None
	   for m in w.get_children():
	     if isinstance (m, gtk.Label):
		accel_path = prefix + m.get_text()
		accel = ""
		if isinstance (m, gtk.AccelLabel):
		   key = gtk.accel_map_lookup_entry (prefix + m.get_text())
		   if key and key[0] != 0:
		      accel = gtk.accelerator_name (key[0], key[1])
		result = (w, accel_path, accel, level)

	   if w.get_submenu ():
	     self.to_traverse = self.to_traverse + \
		[(c, accel_path + "/", level + 1) \
		 for c in w.get_submenu ()]
	   if result:
	     return result

	 elif isinstance (w, gtk.Container):
	   self.to_traverse = self.to_traverse + \
	      [(c, prefix, level + 1) for c in w.get_children ()]
       raise StopIteration
Ejemplo n.º 12
0
    def refresh_model(self):
        """ Initializes the model from data provided by the keybinding
        manager. """
        self.treestore.clear()
        section_order = list(set(d['group']
             for d in keybindings.BINDING_INFO.values()))
        section_order.sort()
        section_parent_map = {}
        for section_name in section_order:
            row = [section_name, None, False]
            row.extend( [None,] * self.accel_column_num)
            section_parent_map[section_name] =  self.treestore.append(
                None, row
            )

        action_treeiter_map = self.action_treeiter_map = {}
        # Sort actions by action name
        actions = sorted(keybindings.BINDING_INFO.items(),
                key=lambda item: item[1]['title'])
        for action_name, action_data in actions:
            title = action_data['title']
            group_name = action_data['group']
            old_bindings = self.keymanager.get_bindings_for_action(action_name)
            acc_list =  ["", ] * self.accel_column_num
            for idx in range(0, self.accel_column_num):
                if len(old_bindings) > idx:
                    acc_list[idx] = gtk.accelerator_name(*old_bindings[idx])

            row = [title, action_name, True]
            row.extend(acc_list)
            treeiter = self.treestore.append(
                section_parent_map[group_name],
                row
            )
            action_treeiter_map[action_name] = treeiter
	def on_wirelessHotkeyButton_changed(self, button = None, key = None, mods = None):
		if key == 0 and mods == 0:
			new = "disable"
		else:
			new = gtk.accelerator_name(key, mods)
		session = self.__connect_session_options()
		session.SetWirelessHotkey(self.__convert_gtk_to_xbindkeys(new))
Ejemplo n.º 14
0
    def on_key_edited(self, renderer, path, keycode, mask, keyval, model):
        """Callback that handles key edition in cellrenderer. It makes
        some tests to validate the key, like looking for already in
        use keys and look for [A-Z][a-z][0-9] to avoid problems with
        these common keys. If all tests are ok, the value will be
        stored in gconf.
        """
        giter = model.get_iter(path)
        gconf_path = model.get_value(giter, 0)

        oldkey = model.get_value(giter, 2)
        hotkey = KeyEntry(keycode, mask)
        key = gtk.accelerator_name(keycode, mask)
        keylabel = gtk.accelerator_get_label(keycode, mask)

        # we needn't to change anything, the user is trying to set the
        # same key that is already set.
        if oldkey == hotkey:
            return False

        # looking for already used keybindings
        def each_key(model, path, subiter):
            keyentry = model.get_value(subiter, 2)
            if keyentry and keyentry == hotkey:
                msg = _('The shortcut "%s" is already in use.') % keylabel
                raise ShowableError(_("Error setting keybinding."), msg, -1)

        model.foreach(each_key)

        # avoiding problems with common keys
        if (mask == 0 and keycode != 0) and (
            (keycode >= ord("a") and keycode <= ord("z"))
            or (keycode >= ord("A") and keycode <= ord("Z"))
            or (keycode >= ord("0") and keycode <= ord("9"))
        ):
            dialog = gtk.MessageDialog(
                self.get_widget("config-window"),
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                gtk.MESSAGE_WARNING,
                gtk.BUTTONS_OK,
                _(
                    'The shortcut "%s" cannot be used '
                    "because it will become impossible to "
                    "type using this key.\n\n"
                    "Please try with a key such as "
                    "Control, Alt or Shift at the same "
                    "time.\n"
                )
                % key,
            )
            dialog.run()
            dialog.destroy()
            return False

        # setting new value in ui
        giter = model.get_iter(path)
        model.set_value(giter, 2, hotkey)

        # setting the new value in gconf
        self.client.set_string(gconf_path, key)
Ejemplo n.º 15
0
    def new(cls, gtk_action, parent):
        """Create a new GAction from a GtkAction and a GtkActionGroup"""
        # This code is similar to code in the loader, investigate
        # if we can use more code reusage
        name = gtk_action.get_name()
        label = gtk_action.get_property('label')
        short_label = gtk_action.get_property('short-label')
        is_important = gtk_action.get_property('is-important')
        tooltip = gtk_action.get_property('tooltip')
        stock_id = gtk_action.get_property('stock-id') or None
        gaction = cls(parent, name, label, short_label, is_important,
                      tooltip, stock_id)

        # check if it has accelerator
        accel_entry = gtk.accel_map_lookup_entry('<Actions>/%s/%s' %
                                                 (parent.name, name))
        if accel_entry:
            key, modifier = accel_entry
            if key != 0:
                gaction.accelerator = gtk.accelerator_name(key, modifier)

        # check if it has signal handler
        callback = gtk_action.get_data('handler')
        if callback:
            gaction.callback = callback

        return gaction
Ejemplo n.º 16
0
    def set_accelerator(self, keyval, mod):
        # Check whether accelerator already exists
        self.remove_accelerator(self.current_node)

        name = gtk.accelerator_name(keyval, mod)

        if name == '':
            self.current_node.shorcut = None
            self.save_current_tool()
            return True
            
        col = self.accelerator_collision(name, self.current_node)
        
        if col:
            dialog = gtk.MessageDialog(self.dialog,
                                       gtk.DIALOG_MODAL,
                                       gtk.MESSAGE_ERROR,
                                       gtk.BUTTONS_OK,
                                       _('This accelerator is already bound to %s') % (', '.join(map(lambda x: x.name, col)),))

            dialog.run()
            dialog.destroy()
            
            self.add_accelerator(self.current_node)
            return False

        self.current_node.shortcut = name
        self.add_accelerator(self.current_node)
        self.save_current_tool()

        return True
Ejemplo n.º 17
0
    def handle_key_event(self, event):
        '''
        Internal function to handle key event.
        '''
        modifiers = []

        # Add Ctrl modifier.
        if event.state & gtk.gdk.CONTROL_MASK:
            modifiers.append("Ctrl")

        # Add Super modifiers.
        if event.state & gtk.gdk.SUPER_MASK:
            modifiers.append("Super")

        # Add Hyper modifiers.
        if event.state & gtk.gdk.HYPER_MASK:
            modifiers.append("Hyper")

        # Add Alt modifier.
        if event.state & gtk.gdk.MOD1_MASK:
            modifiers.append("Alt")

        if event.state & gtk.gdk.SHIFT_MASK:
            modifiers.append("Shift")
        modifiers.append(gtk.accelerator_name(event.keyval, 0))
        key_name = " + ".join(modifiers)

        if key_name in self.keymap:
            self.keymap[key_name]()
Ejemplo n.º 18
0
 def _on_capture_keypress(self, entry, event):
     # svn.gnome.org/viewcvs/gazpacho/trunk/gazpacho/actioneditor.py
     # Tab must be handled as normal. Otherwise we can't move from
     # the entry.
     if event.keyval == gtk.keysyms.Tab and not self._full_button.get_active():
         return False
     modifiers = event.get_state() & gtk.accelerator_get_default_mod_mask()
     modifiers = int(modifiers)
     # Check if we should clear the entry
     clear_keys = [gtk.keysyms.Delete,
                   gtk.keysyms.KP_Delete,
                   gtk.keysyms.BackSpace]
     if modifiers == 0 and not self._full_button.get_active():
         if event.keyval in clear_keys:
             entry.set_text('')
             self._current.set_value('')
         return True
     # Check if the accelerator is valid and add it to the entry
     if gtk.accelerator_valid(event.keyval, modifiers) or \
        self._full_button.get_active():
         accelerator = gtk.accelerator_name(event.keyval, modifiers)
         if self.free_accelerator(accelerator, self._current):
             entry.set_text(accelerator)
             self._current.set_value(accelerator)
         # deactive the dangerouse button again :-)
         self._full_button.set_active(False)
     return True
 def on_cpuHotkeyButton_changed(self, button=None, key=None, mods=None):
     if key == 0 and mods == 0:
         new = "disable"
     else:
         new = gtk.accelerator_name(key, mods)
     session = self.__connect_session_options()
     session.SetCpuHotkey(self.__convert_gtk_to_xbindkeys(new))
Ejemplo n.º 20
0
 def on_accel_edited(self, cellrenderer, path, accel_key, accel_mods, keycode):
     """
         Updates accelerators display in the list
     """
     accel = gtk.accelerator_name(accel_key, accel_mods)
     iter = self.list.get_iter(path)
     self.list.set_value(iter, 1, accel)
Ejemplo n.º 21
0
 def keyPressCommand(self, event):
     if event.id in self.MODIFIERS or \
           (event.event_string.startswith('ISO') and \
              event.event_string != 'ISO_Left_Tab'):
         return
     if isinstance(event, pyatspi.event.DeviceEvent):
         # If it's a fake one, then it is a global WM hotkey, no need for context.
         self._prependContext()
     if event.modifiers in (0, gtk.gdk.SHIFT_MASK) and \
           gtk.gdk.keyval_to_unicode(event.id):
         self.typed_text += unichr(gtk.gdk.keyval_to_unicode(event.id))
     else:
         if self.frame_name:
             if isinstance(event, pyatspi.event.DeviceEvent):
                 self.commands_queue.put_nowait(
                   'sequence.append(WaitForWindowActivate("%s", None))\n' % \
                     self.frame_name.replace('"','\"'))
             self.frame_name = ''
         if self.last_focused:
             name, path, role = self.last_focused
             self.commands_queue.put_nowait(
                 '%ssequence.append(WaitForFocus("%s", acc_role=pyatspi.%s))\n' % \
                 (self._focus_comment, name.replace('"','\"'), repr(role)))
             self.last_focused = None
         if self.typed_text:
             self.commands_queue.put_nowait(
               'sequence.append(TypeAction("%s"))\n' % \
                 self.typed_text.replace('"','\"'))
             self.typed_text = ''
         self.commands_queue.put_nowait(
           'sequence.append(KeyComboAction("%s"))\n' % \
             gtk.accelerator_name(event.id, event.modifiers))
Ejemplo n.º 22
0
 def create_entry(self, actwrap):
     d = gtk.Dialog(parent=None,
                    flags=gtk.DIALOG_MODAL,
                    title='Enter new keypress',
                    buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                             gtk.STOCK_OK, gtk.RESPONSE_ACCEPT)
                    )
     action = actwrap.action
     e = gtk.Entry()
     e.show()
     d.vbox.pack_start(e, expand=False)
     key, mod = gtk.accel_map_lookup_entry(action.accel_path)
     accel = gtk.accelerator_name(key, mod)
     e.set_text(accel)
     def _response(dlg, response):
         d.hide()
         if response == gtk.RESPONSE_ACCEPT:
             newaccel = e.get_text()
             action.set_accel(newaccel)
             actwrap.reset_markup()
             key, mod = gtk.accelerator_parse(newaccel)
             gtk.accel_map_change_entry(action.accel_path, key, mod, True)
         d.destroy()
     d.connect('response', _response)
     d.run()
Ejemplo n.º 23
0
def is_accel(event, accel):
    """Checks if the given gtk.gdk.Event matches an accelerator string

    example: is_accel(event, "<shift><ctrl>z")
    """
    if event.type != gtk.gdk.KEY_PRESS:
        return False

    # ctrl+shift+x gives us ctrl+shift+X and accelerator_parse returns
    # lowercase values for matching, so lowercase it if possible
    keyval = event.keyval
    if not keyval & ~0xFF:
        keyval = ord(chr(keyval).lower())

    default_mod = gtk.accelerator_get_default_mod_mask()
    accel_keyval, accel_mod = gtk.accelerator_parse(accel)

    # If the accel contains non default modifiers matching will never work and
    # since no one should use them, complain
    non_default = accel_mod & ~default_mod
    if non_default:
        print_w("Accelerator '%s' contains a non default modifier '%s'." %
            (accel, gtk.accelerator_name(0, non_default) or ""))

    # Remove everything except default modifiers and compare
    return (accel_keyval, accel_mod) == (keyval, event.state & default_mod)
Ejemplo n.º 24
0
 def keyPressCommand(self, event):
   '''
   Create command lines for variuos key presses.
   
   @param event: Key press at-spi event.
   @type event: Accessibility.DeviceEvent
   '''
   if event.id in self.MODIFIERS or \
         event.event_string.startswith('ISO'):
     return
   if event.modifiers in (0, gtk.gdk.SHIFT_MASK) and \
         gtk.gdk.keyval_to_unicode(event.id):
     self.typed_text += unichr(gtk.gdk.keyval_to_unicode(event.id))
   else:
     if self.frame_name:
       self.commands_queue.put_nowait('waittillguiexist("%s")\n' % \
                                        self.frame_name)
       self.frame_name = ''
     if self.typed_text:
       self.commands_queue.put_nowait('generatekeyevent("%s")\n' % \
                                        self.typed_text)
       self.typed_text = ''
     self.commands_queue.put_nowait('generatekeyevent("%s")\n' % \
                                      gtk.accelerator_name(event.id,
                                                           event.modifiers))
Ejemplo n.º 25
0
 def keyPressCommand(self, event):
   if event.id in self.MODIFIERS or \
         (event.event_string.startswith('ISO') and \
            event.event_string != 'ISO_Left_Tab'):
     return
   if isinstance(event, pyatspi.event.DeviceEvent):
     # If it's a fake one, then it is a global WM hotkey, no need for context.
     self._prependContext()
   if event.modifiers in (0, gtk.gdk.SHIFT_MASK) and \
         gtk.gdk.keyval_to_unicode(event.id):
     self.typed_text += unichr(gtk.gdk.keyval_to_unicode(event.id))
   else:
     if self.frame_name:
       if isinstance(event, pyatspi.event.DeviceEvent):
         self.commands_queue.put_nowait(
           'sequence.append(WaitForWindowActivate("%s", None))\n' % \
             self.frame_name.replace('"','\"'))
       self.frame_name = ''
     if self.last_focused:
       name, path, role = self.last_focused
       self.commands_queue.put_nowait(
           '%ssequence.append(WaitForFocus("%s", acc_role=pyatspi.%s))\n' % \
           (self._focus_comment, name.replace('"','\"'), repr(role)))
       self.last_focused = None
     if self.typed_text:
       self.commands_queue.put_nowait(
         'sequence.append(TypeAction("%s"))\n' % \
           self.typed_text.replace('"','\"'))
       self.typed_text = ''
     self.commands_queue.put_nowait(
       'sequence.append(KeyComboAction("%s"))\n' % \
         gtk.accelerator_name(event.id, event.modifiers))
Ejemplo n.º 26
0
 def accel_group_callback(self, group, acceleratable, keyval, modifier):
     accel_name = gtk.accelerator_name(keyval, modifier)
     if accel_name in self.__button_accelerator_dict:
         button = self.__button_accelerator_dict[accel_name]
         button.pressed()
         button.released()
         #button.clicked()
         self.set_button_active(button.get_name(), True)
Ejemplo n.º 27
0
 def accel_group_callback(self, group, acceleratable, keyval, modifier):
     accel_name = gtk.accelerator_name(keyval, modifier)
     if accel_name in self.__button_accelerator_dict:
         button = self.__button_accelerator_dict[accel_name]
         button.pressed()
         button.released()
         #button.clicked()
         self.set_button_active(button.get_name(), True)
Ejemplo n.º 28
0
 def get_accel_name(self):
     '''
     converts the accelerator keyval and modifier mask into a string
     @return: a acceleratot string
     '''
     if self.state is None or self.keyval is None:
         return ''
     return accelerator_name(self.keyval, self.state)
Ejemplo n.º 29
0
    def update_label(self, key, mods):
        text = ""
        for mod in mod_table:
            if mods & mod:
                text = text + mod_table[mod]

        self.mod = text
        self.key = gtk.accelerator_name(key, 0)
        self.label1.set_text(self.mod + self.key)
Ejemplo n.º 30
0
    def GotKey(self, widget, key, mods):
        self.shortcut = gtk.accelerator_name(key, mods)
        for mod in KeyModifier:
            if "%s_L" % mod in self.shortcut:
                self.shortcut = self.shortcut.replace("%s_L" % mod, "<%s>" % mod)
            if "%s_R" % mod in self.shortcut:
                self.shortcut = self.shortcut.replace("%s_R" % mod, "<%s>" % mod)

        gtk.main_quit()
Ejemplo n.º 31
0
    def GotKey(self, widget, key, mods):
        self.shortcut = gtk.accelerator_name (key, mods)
        for mod in KeyModifier:
            if "%s_L" % mod in self.shortcut:
                self.shortcut = self.shortcut.replace ("%s_L" % mod, "<%s>" % mod)
            if "%s_R" % mod in self.shortcut:
                self.shortcut = self.shortcut.replace ("%s_R" % mod, "<%s>" % mod)

        gtk.main_quit()
 def get_accel_name(self):
     '''
     converts the accelerator keyval and modifier mask into a string
     @return: a acceleratot string
     '''
     if self.state is None or self.keyval is None:
         return ''
     if self.keyval == 0 and self.state == gtk.gdk.SUPER_MASK:
         return 'Super'
     return gtk.accelerator_name(self.keyval, self.state)
Ejemplo n.º 33
0
 def get_accel_name(self):
     '''
     converts the accelerator keyval and modifier mask into a string
     @return: a acceleratot string
     '''
     if self.state is None or self.keyval is None:
         return ''
     if self.keyval == 0 and self.state == gtk.gdk.SUPER_MASK:
         return 'Super'
     return gtk.accelerator_name(self.keyval, self.state)
Ejemplo n.º 34
0
	def kbd_entry_press(self, widget, event, data=None):
		# capture keypresses here
		k = gtk.gdk.keyval_name(event.keyval)
		if k in self.modifier_keyvals:
			return
		modifiers = event.state & self.modifiers_mask
		label = gtk.accelerator_name(event.keyval, modifiers)
		widget.set_text(label)
		print 'Key %s pressed.' % label
		gtk.gdk.keyboard_ungrab()
Ejemplo n.º 35
0
    def __create_model(self):
        store = gtk.ListStore(
            gobject.TYPE_PYOBJECT,
            gobject.TYPE_STRING)

        ids = gtk.stock_list_ids()
        ids.sort()

        for data in ids:
            info = StockItemInfo(stock_id=data)
            stock_item = gtk.stock_lookup(data)

            if stock_item:
                info.stock_item = stock_item
            else:
                # stock_id, label, modifier, keyval, translation_domain
                info.stock_item =('', '', 0, 0, '')

            # only show icons for stock IDs that have default icons
            icon_set = gtk.icon_factory_lookup_default(info.stock_id)
            if icon_set is None:
                info.small_icon = None
            else:
                # See what sizes this stock icon really exists at
                sizes = icon_set.get_sizes()
                n_sizes = len(sizes)

                # Use menu size if it exists, otherwise first size found
                size = sizes[0];
                i = 0;
                while(i < n_sizes):
                    if(sizes[i] == gtk.ICON_SIZE_MENU):
                        size = gtk.ICON_SIZE_MENU
                        break
                    i += 1

                info.small_icon = self.render_icon(info.stock_id, size)

                if(size != gtk.ICON_SIZE_MENU):
                    # Make the result the proper size for our thumbnail
                    w, h = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)

                    scaled = info.small_icon.scale_simple(w, h, 'bilinear')
                    info.small_icon = scaled

            if info.stock_item[3] == 0:
                info.accel_str = ""
            else:
                info.accel_str = \
                    gtk.accelerator_name(info.stock_item[3], info.stock_item[2])

            iter = store.append()
            store.set(iter, 0, info, 1, info.stock_id)

        return store
Ejemplo n.º 36
0
    def on_accel_edited(self, renderer, path, accel_key, accel_mods, hardware_keycode):
        iter = self.actions.get_iter(path)
        accel = accelerator_name(accel_key, accel_mods)
        name = self.actions.get_value(iter, 0)
        path = shortcuts.get_path_by_name(name)

        accel_map_change_entry(path, accel_key, accel_mods, True)
        shortcuts.names_by_key.clear()

        self.actions.set_value(iter, 1, accel)
        self.actions.set_value(iter, 4, self.get_weight(path, accel_key, accel_mods))
Ejemplo n.º 37
0
 def on_accel_edited(self, renderer, path, accel_key, accel_mods, hardware_keycode):
     iter = self.actions.get_iter(path)
     accel = accelerator_name(accel_key, accel_mods)
     name = self.actions.get_value(iter, 0)
     
     shortcuts[name] = accel
     
     self.actions.set_value(iter, 1, accel)
     self.actions.set_value(iter, 4, WEIGHT_BOLD)
     
     replace_accelerator(name, accel, False)
Ejemplo n.º 38
0
 def _cellAccelEdit(self, cell, path, accel_key, accel_mods, code, model):
     """ Accelerator is modified """
     self.show_input = gtk.accelerator_get_label(accel_key, accel_mods)
     self.new_task_binding = gtk.accelerator_name(accel_key, accel_mods)
     if check_invalidity(self.new_task_binding, accel_key, accel_mods):
         self._show_warning(gtk.Button(_("Warning")), self.show_input)
         return
     self.binding_backup = self.new_task_binding
     iter = model.get_iter(path)
     model.set_value(iter, 1, self.show_input)
     save_new_binding(self.new_task_binding, self.button.get_active())
Ejemplo n.º 39
0
    def on_key_edited(self, renderer, path, keycode, mask, keyval, model):
        """Callback that handles key edition in cellrenderer. It makes
        some tests to validate the key, like looking for already in
        use keys and look for [A-Z][a-z][0-9] to avoid problems with
        these common keys. If all tests are ok, the value will be
        stored in gconf.
        """
        giter = model.get_iter(path)
        gconf_path = model.get_value(giter, 0)

        oldkey = model.get_value(giter, 2)
        hotkey = KeyEntry(keycode, mask)
        key = gtk.accelerator_name(keycode, mask)
        keylabel = gtk.accelerator_get_label(keycode, mask)

        # we needn't to change anything, the user is trying to set the
        # same key that is already set.
        if oldkey == hotkey:
            return False

        # looking for already used keybindings
        def each_key(model, path, subiter):
            keyentry = model.get_value(subiter, 2)
            if keyentry and keyentry == hotkey:
                msg = _("The shortcut \"%s\" is already in use.") % keylabel
                raise ShowableError(_('Error setting keybinding.'), msg, -1)

        model.foreach(each_key)

        # avoiding problems with common keys
        if ((mask == 0 and keycode != 0)
                and ((keycode >= ord('a') and keycode <= ord('z')) or
                     (keycode >= ord('A') and keycode <= ord('Z')) or
                     (keycode >= ord('0') and keycode <= ord('9')))):
            dialog = gtk.MessageDialog(
                self.get_widget('config-window'),
                gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                gtk.MESSAGE_WARNING, gtk.BUTTONS_OK,
                _("The shortcut \"%s\" cannot be used "
                  "because it will become impossible to "
                  "type using this key.\n\n"
                  "Please try with a key such as "
                  "Control, Alt or Shift at the same "
                  "time.\n") % key)
            dialog.run()
            dialog.destroy()
            return False

        # setting new value in ui
        giter = model.get_iter(path)
        model.set_value(giter, 2, hotkey)

        # setting the new value in gconf
        self.client.set_string(gconf_path, key)
Ejemplo n.º 40
0
 def setup_accelerator(self):
     accelerator = stock.get_accelerator(self._stock_id)
     logger.debug(str(accelerator))
     try:
         if accelerator[1] > 0:
             self.toolitem.props.accelerator = gtk.accelerator_name(
                 accelerator[1], accelerator[0])
     except:
         logger.error(
             'Could not set up accelerator; if toogletoolbutton, update your sugar version'
         )
Ejemplo n.º 41
0
 def _cellAccelEdit(self, cell, path, accel_key, accel_mods, code, model):
     """ Accelerator is modified """
     self.show_input = gtk.accelerator_get_label(accel_key, accel_mods)
     self.new_task_binding = gtk.accelerator_name(accel_key, accel_mods)
     if check_invalidity(self.new_task_binding, accel_key, accel_mods):
         self._show_warning(gtk.Button(_("Warning")), self.show_input)
         return
     self.binding_backup = self.new_task_binding
     iter = model.get_iter(path)
     model.set_value(iter, 1, self.show_input)
     save_new_binding(self.new_task_binding, self.button.get_active())
Ejemplo n.º 42
0
    def _on_mnemonic_activate(self, widget, group_cycling, keyval):
        """
        Callback for the mnemonic activate signal. If we're currently
        editing the accelerator we have to disable the usual mnemonic
        action and use the keyval for as an accelerator value.
        """
        if self._accel_editing:
            key = gtk.accelerator_name(keyval, self.mnemonic_modifier)
            self.accelerator.set_text(key)
            return True

        return False
Ejemplo n.º 43
0
    def replace_generics(self, name, keys):
        if name in self.default_generics and set(self.default_generics[name]) == set(keys):
            self.changed_generics.pop(name, None)
        else:
            if keys or name in self.default_generics:
                self.changed_generics[name] = [(gtk.accelerator_name(*km), pr) for km, pr in keys]
            else:
                self.changed_generics.pop(name, None)

        self.generic_shortcuts.setdefault(name, [])[:] = []
        for km, pr in keys:
            self.generic_shortcuts[name].append((km, pr))
Ejemplo n.º 44
0
    def on_accel_edited(self, renderer, path, accel_key, accel_mods,
                        hardware_keycode):
        iter = self.actions.get_iter(path)
        accel = accelerator_name(accel_key, accel_mods)
        name = self.actions.get_value(iter, 0)

        shortcuts[name] = accel

        self.actions.set_value(iter, 1, accel)
        self.actions.set_value(iter, 4, WEIGHT_BOLD)

        replace_accelerator(name, accel, False)
Ejemplo n.º 45
0
	def on_dialoggetkey_key_press_event(self, _widget, event):
		self.imagekeybindingaux.hide()
		self.labelkeybindingaux.hide()
		self._press_time = event.time

		keyval, state = self.translate_keyboard_event(event)
		keyname = gtk.accelerator_name(keyval, state)
		if keyname == 'Escape':
			self._return(None)
		elif keyname == 'BackSpace':
			self._return('')
		self.update_accelerator_label(keyval, state)
Ejemplo n.º 46
0
	def on_dialoggetkey_key_press_event(self, widget, event):
		self.imagekeybindingaux.hide()
		self.labelkeybindingaux.hide()
		self._press_time = event.time

		keyval, state = self.translate_keyboard_event(widget, event)
		keyname = gtk.accelerator_name(keyval, state)
		if keyname == 'Escape':
			self._return(None)
		elif keyname == 'BackSpace':
			self._return('')
		self.update_accelerator_label(keyval, state)
	def activate(self, key, mod):
		named = gtk.accelerator_name(key, mod)

		if not named in self.accelerators:
			return None

		accel = self.accelerators[named]

		if isinstance(accel, AccelCallback):
			return accel
		else:
			return AccelGroup(self, named, accel)
Ejemplo n.º 48
0
    def __create_model(self):
        store = gtk.ListStore(gobject.TYPE_PYOBJECT, gobject.TYPE_STRING)

        ids = gtk.stock_list_ids()
        ids.sort()

        for data in ids:
            info = StockItemInfo(stock_id=data)
            stock_item = gtk.stock_lookup(data)

            if stock_item:
                info.stock_item = stock_item
            else:
                # stock_id, label, modifier, keyval, translation_domain
                info.stock_item = ('', '', 0, 0, '')

            # only show icons for stock IDs that have default icons
            icon_set = gtk.icon_factory_lookup_default(info.stock_id)
            if icon_set is None:
                info.small_icon = None
            else:
                # See what sizes this stock icon really exists at
                sizes = icon_set.get_sizes()
                n_sizes = len(sizes)

                # Use menu size if it exists, otherwise first size found
                size = sizes[0]
                i = 0
                while (i < n_sizes):
                    if (sizes[i] == gtk.ICON_SIZE_MENU):
                        size = gtk.ICON_SIZE_MENU
                        break
                    i += 1

                info.small_icon = self.render_icon(info.stock_id, size)

                if (size != gtk.ICON_SIZE_MENU):
                    # Make the result the proper size for our thumbnail
                    w, h = gtk.icon_size_lookup(gtk.ICON_SIZE_MENU)

                    scaled = info.small_icon.scale_simple(w, h, 'bilinear')
                    info.small_icon = scaled

            if info.stock_item[3] == 0:
                info.accel_str = ""
            else:
                info.accel_str = \
                    gtk.accelerator_name(info.stock_item[3], info.stock_item[2])

            iter = store.append()
            store.set(iter, 0, info, 1, info.stock_id)

        return store
Ejemplo n.º 49
0
 def set_label(self, key=None, mods=None):
     if self.label:
         if key != None and mods != None:
             self.emit("current-changed", key, mods)
         gtk.Button.set_label(self, self.label)
         return
     if key == None and mods == None:
         key = self.key
         mods = self.mods
     label = gtk.accelerator_name(key, mods)
     if not len(label):
         label = _("Disabled")
     gtk.Button.set_label(self, label)
Ejemplo n.º 50
0
 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 = file(constants.KEYBINDINGS_CONF_PATH, "w")
     json.dump(action_to_keys, fp, indent=2)
     fp.close()
Ejemplo n.º 51
0
 def HandleGrabberChanged(grabber, key, mods, label, selector):
     new = gtk.accelerator_name(key, mods)
     mods = ""
     for mod in KeyModifier:
         if "%s_L" % mod in new:
             new = new.replace("%s_L" % mod, "<%s>" % mod)
         if "%s_R" % mod in new:
             new = new.replace("%s_R" % mod, "<%s>" % mod)
         if "<%s>" % mod in new:
             mods += "%s|" % mod
     mods.rstrip("|")
     label.set_text(self.GetLabelText(new))
     selector.current = mods
Ejemplo n.º 52
0
 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()
Ejemplo n.º 53
0
def button_press_name(button, mods):
    """Converts button number & modifier mask to a prefs-storable string.

    Analogous to `gtk.accelerator_name()`.  Buttonpress names look similar to
    GDK accelerator names, for example ``<Control><Shift>Button2`` or
    ``<Primary><Alt>Button4`` for newer versions of GTK.  If the button is
    equal to zero (see `button_press_parse()`), `None` is returned.

    """
    button = int(button)
    mods = int(mods)
    if button <= 0:
        return None
    mods = gdk.ModifierType(mods)
    modif_name = gtk.accelerator_name(0, mods)
    return modif_name + "Button%d" % (button, )
Ejemplo n.º 54
0
	def on_dialoggetkey_key_release_event(self, widget, event):
		if not self._press_time:
			return
		keyval, state = self.translate_keyboard_event(widget, event)
		self.update_accelerator_label(0, 0)

		if gtk.accelerator_valid(keyval, state):
			key = gtk.accelerator_name(keyval, state)
			if (self._previous_key is not None and
					key == self._previous_key):
				self._return(None)
				return
			if self._check_callback is None or self._check_callback(key):
				self._return(key)
			else:
				self.imagekeybindingaux.show()
				self.labelkeybindingaux.show()
Ejemplo n.º 55
0
    def handle_keypress(self, xevent):  # type: (XKeyPress) -> None
        """Dispatch C{XKeyPress} events to their callbacks."""
        keysig = (xevent.detail, xevent.state)
        if keysig not in self._keys:
            logging.error(
                "Received an event for an unrecognized keybind: "
                "%s, %s", xevent.detail, xevent.state)
            return

        # Display a meaningful debug message
        # FIXME: Only call this code if --debug
        # FIXME: Proper "index" arg for keycode_to_keysym
        ksym = self.xdisp.keycode_to_keysym(keysig[0], 0)
        kbstr = gtk.accelerator_name(ksym, keysig[1])  # pylint: disable=E1101
        logging.debug("Received keybind: %s", kbstr)

        # Call the associated callback
        self._keys[keysig]()