Beispiel #1
0
def rebind_key(keystring, is_bound):
    if is_bound:
        print("binding", keystring)
        keybinder.bind(keystring, relay_key, keystring)
    else:
        print("unbinding", keystring)
        keybinder.unbind(keystring)
Beispiel #2
0
 def __init__(self):
     # =>public window props
     Gtk.Window.__init__(self,
                         title="Kimia-Dict (V " + glob.VERSION + ")"
                         # type_hint=Gdk.WindowTypeHint.TOOLBAR
                         )
     self.set_default_size(800, 500)
     self.set_icon_from_file("./assets/img/logo.png")
     self.set_position(Gtk.WindowPosition.CENTER)
     #=>connect to destory main window
     # self.connect("destroy", self.on_destroy)
     self.connect("delete_event", self.on_delete)
     #=>connect to key events of main window
     self.connect("key-press-event", self.on_key_press_event)
     # =>set toolbar
     MainBox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
     MainToolbar = menu.ToolBar()
     MainBox.pack_start(MainToolbar, False, False, 0)
     # =>set search box
     MainSearch = search.SearchBox()
     MainBox.pack_start(MainSearch, False, False, 10)
     # =>set content
     sw = Gtk.ScrolledWindow()
     mcontent = search.content
     sw.add_with_viewport(mcontent)
     MainBox.pack_start(sw, True, True, 0)
     # =>add MainBox to main window
     self.add(MainBox)
     # =>init keybinder
     Keybinder.init()
     # =>handle global shortuct by 'shortcut_callback'
     Keybinder.bind(glob.KEYDISPLAY, self.show_shortcut_callback,
                    "keystring %s (user data)" % glob.KEYDISPLAY)
     # =>show all widgets and window
     self.show_all()
Beispiel #3
0
    def bootstrap(self):
        self._items = []
        section = self.options.get('simple-section', self.SIMPLE_SECTION)
        default_type = self.options.get('simple-section-default', self.SIMPLE_SECTION_DEFAULT)

        if not self.klemmbrett.config.has_section(section):
            raise KeyError("No config section %s defined" % (section,))

        for label, value in self.klemmbrett.config.items(section):
            target = default_type
            if self._TYPE_SEPERATOR in label:
                target, label = label.split(self._TYPE_SEPERATOR, 1)

            self._items.append((label, {target: value}))

        prefix = self.options.get('complex-section-prefix', self.COMPLEX_SECTION_PREFIX)

        for section in self.klemmbrett.config.sections():
            if not section.startswith(prefix):
                continue

            options = dict(self.klemmbrett.config.items(section))
            label = section[len(prefix):]

            self._items.append((label, options))

            if "shortcut" in options:
                _keybinder.bind(
                    options['shortcut'],
                    _ft.partial(self.set, widget = None, text = label),
                )
Beispiel #4
0
    def set_hotkey(self, accel_name):
        if self._current_accel_name:
            Keybinder.unbind(self._current_accel_name)
            self._current_accel_name = None

        Keybinder.bind(accel_name, self.on_hotkey_press)
        self._current_accel_name = accel_name
Beispiel #5
0
    def bootstrap(self):
        """
            Setup all destinations and shortcuts and start the rpc server
        """
        self._destinations = self.get_destinations()

        # initialize standard stuff
        #_notify.init("Klemmbrett")
        self._current_suggestion = None

        # binding to accept the suggested text into the clipboard
        _keybinder.bind(
            self.options.get('accept-suggestion-shortcut',
                             self.DEFAULT_ACCEPT_BINDING),
            self._accept_suggestion,
        )

        _keybinder.bind(
            self.options.get('user-history-shortcut',
                             self.DEFAULT_USERHISTORY_BINDING),
            self._show_histories,
        )

        _plugins.PopupPlugin.bootstrap(self)
        self._start_server()
Beispiel #6
0
def _enable(eventname, exaile, eventdata):
    global initialized
    if not initialized:
        Keybinder.init()
        initialized = True
    for k in KEYS:
        Keybinder.bind(k, on_media_key, exaile)
Beispiel #7
0
    def __init__(self, silent = False):
        super(KazamSuperIndicator, self).__init__()
        self.blink_icon = BLINK_STOP_ICON
        self.blink_state = False
        self.blink_mode = BLINK_SLOW
        self.recording = False
        self.silent = silent
        logger.debug("Indicatior silent: {0}".format(self.silent))

        self.menu = Gtk.Menu()

        self.menuitem_settings = Gtk.MenuItem(_("Settings"))
        self.menuitem_settings.set_sensitive(True)
        self.menuitem_settings.connect("activate", self.on_menuitem_settings_activate)

        self.menuitem_separator1 = Gtk.SeparatorMenuItem()

        self.menuitem_start = Gtk.MenuItem(_("Start recording"))
        self.menuitem_start.set_sensitive(True)
        self.menuitem_start.connect("activate", self.on_menuitem_start_activate)

        self.menuitem_pause = Gtk.CheckMenuItem(_("Pause recording"))
        self.menuitem_pause.set_sensitive(False)
        self.menuitem_pause.connect("toggled", self.on_menuitem_pause_activate)

        self.menuitem_finish = Gtk.MenuItem(_("Finish recording"))
        self.menuitem_finish.set_sensitive(False)
        self.menuitem_finish.connect("activate", self.on_menuitem_finish_activate)

        self.menuitem_separator2 = Gtk.SeparatorMenuItem()

        self.menuitem_quit = Gtk.MenuItem(_("Quit"))
        self.menuitem_quit.connect("activate", self.on_menuitem_quit_activate)

        self.menu.append(self.menuitem_settings)
        self.menu.append(self.menuitem_separator1)
        self.menu.append(self.menuitem_start)
        self.menu.append(self.menuitem_pause)
        self.menu.append(self.menuitem_finish)
        self.menu.append(self.menuitem_separator2)
        self.menu.append(self.menuitem_quit)

        self.menu.show_all()

        #
        # Setup keybindings - Hardcore way
        #
        try:
            from gi.repository import Keybinder
            logger.debug("Trying to bind hotkeys.")
            Keybinder.init()
            Keybinder.bind("<Super><Ctrl>R", self.cb_hotkeys, "start-request")
            Keybinder.bind("<Super><Ctrl>F", self.cb_hotkeys, "stop-request")
            Keybinder.bind("<Super><Ctrl>P", self.cb_hotkeys, "pause-request")
            Keybinder.bind("<Super><Ctrl>W", self.cb_hotkeys, "show-request")
            Keybinder.bind("<Super><Ctrl>Q", self.cb_hotkeys, "quit-request")
            self.recording = False
        except ImportError:
            logger.info("Unable to import Keybinder, hotkeys not available.")
Beispiel #8
0
def run_keybinder(callback):
    Keybinder.init()
    Keybinder.bind('<Ctrl><Alt>space', callback)

    try:
        GLib.MainLoop().run()
    except KeyboardInterrupt:
        GLib.MainLoop().quit()
Beispiel #9
0
 def initialize(self):
     """
     Unbind previous hotkeys, re-read config & bind new hotkeys.
     """
     for operation, key in self.hotkeys.items():
         Keybinder.unbind(key)
     self.hotkeys = self.load_keys()
     for operation, key in self.hotkeys.items():
         Keybinder.bind(key, self.fire_hook, operation)
def run_keybinder(callback):
    # for wayland
    DBusGMainLoop(set_as_default=True)
    dbus_menu = DbusMenu()
    Keybinder.bind('<Alt>space', callback, dbus_menu)
    #GLib.timeout_add_seconds(1, callback)
    try:
        GLib.MainLoop().run()
    except KeyboardInterrupt:
        GLib.MainLoop().quit()
Beispiel #11
0
 def __init__(self):
 
     self.recorder = Recorder()
         
     keybinder.init()
     keybinder.bind('<Control>Escape', self.callback, None)
     
     self.overlay = Overlay()
     self.overlay.connect('trigger', lambda *args: self.start_recording(*self.overlay.get_selection()))
     self.overlay.show_all()
Beispiel #12
0
    def bind_show_app_hotkey(self, accel_name):
        if self._current_accel_name == accel_name:
            return

        if self._current_accel_name:
            Keybinder.unbind(self._current_accel_name)
            self._current_accel_name = None

        logger.info("Trying to bind app hotkey: %s" % accel_name)
        Keybinder.bind(accel_name, self.cb_toggle_visibility)
        self._current_accel_name = accel_name
Beispiel #13
0
    def __init__(self):
        self.indicator = appindicator.Indicator.new(APPINDICATOR_ID, self.get_current_state_icon(), appindicator.IndicatorCategory.SYSTEM_SERVICES)
        self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
        self.indicator.set_menu(self.build_menu())
        self.update_mic_state()
        Notify.init(APPINDICATOR_ID)

        Keybinder.init()
        Keybinder.set_use_cooked_accelerators(False)
        Keybinder.bind(keystr, self.callback_toggle_mic, "keystring %s (user data)" % keystr)
        print ("Press '" + keystr + "' to toggle microphone mute")
Beispiel #14
0
 def set_app_show(self, new):
     '''
     This is a specific method to set just the show accelerator.
     We use the value from gsettings to first unbind the current
     key, so in the process of changing the hotkey, we expect the
     API user to first call this method and later change gsettings.
     '''
     if platform.system() == 'Windows':
         self.app.set_hotkey(new)
     else:
         Keybinder.unbind(self.shortcuts['app-show'])
         Keybinder.bind(new, self.app.on_show)
Beispiel #15
0
    def __init__(self, data):
        """Create a new UIObject instance, including loading its uiFile and
           all UI-related objects.

           Instance attributes:

           data     -- An instance of a pykickstart Handler object.  The Hub
                       never directly uses this instance.  Instead, it passes
                       it down into Spokes when they are created and applied.
                       The Hub simply stores this instance so it doesn't need
                       to be passed by the user.
           skipTo   -- If this attribute is set to something other than None,
                       it must be the name of a class (as a string).  Then,
                       the interface will skip to the first instance of that
                       class in the action list instead of going on to
                       whatever the next action is normally.

                       Note that actions may only skip ahead, never backwards.
                       Also, standalone spokes may not skip to an individual
                       spoke off a hub.  They can only skip to the hub
                       itself.
        """
        common.UIObject.__init__(self, data)

        if self.__class__ is GUIObject:
            raise TypeError("GUIObject is an abstract class")

        self.skipTo = None
        self.applyOnSkip = False

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain(self.translationDomain)
        self._window = None

        if self.builderObjects:
            self.builder.add_objects_from_file(self._findUIFile(),
                                               self.builderObjects)
        else:
            self.builder.add_from_file(self._findUIFile())

        self.builder.connect_signals(self)

        # Keybinder from GI needs to be initialized before use
        Keybinder.init()
        Keybinder.bind("<Shift>Print", self._handlePrntScreen, [])

        self._automaticEntry = False
        self._autostepRunning = False
        self._autostepDone = False
        self._autostepDoneCallback = None

        # this indicates if the screen is the last spoke to be processed for a hub
        self.lastAutostepSpoke = False
Beispiel #16
0
    def __init__(self):
        self.app = "xkb-indicator"
        self.indicator = appindicator.Indicator.new(
            self.app,
            "ibus-keyboard",
            category=appindicator.IndicatorCategory.OTHER)
        self.indicator.set_status(appindicator.IndicatorStatus.ACTIVE)
        self.indicator.set_menu(self.build_menu())
        self.indicator.set_label(label(), self.app)

        Keybinder.bind("<Alt>space", self.toggle)
        Keybinder.init()
Beispiel #17
0
    def __init__(self, data):
        """Create a new UIObject instance, including loading its uiFile and
           all UI-related objects.

           Instance attributes:

           data     -- An instance of a pykickstart Handler object.  The Hub
                       never directly uses this instance.  Instead, it passes
                       it down into Spokes when they are created and applied.
                       The Hub simply stores this instance so it doesn't need
                       to be passed by the user.
           skipTo   -- If this attribute is set to something other than None,
                       it must be the name of a class (as a string).  Then,
                       the interface will skip to the first instance of that
                       class in the action list instead of going on to
                       whatever the next action is normally.

                       Note that actions may only skip ahead, never backwards.
                       Also, standalone spokes may not skip to an individual
                       spoke off a hub.  They can only skip to the hub
                       itself.
        """
        common.UIObject.__init__(self, data)

        if self.__class__ is GUIObject:
            raise TypeError("GUIObject is an abstract class")

        self.skipTo = None
        self.applyOnSkip = False

        self.builder = Gtk.Builder()
        self.builder.set_translation_domain(self.translationDomain)
        self._window = None

        if self.builderObjects:
            self.builder.add_objects_from_file(self._findUIFile(), self.builderObjects)
        else:
            self.builder.add_from_file(self._findUIFile())

        self.builder.connect_signals(self)

        # Keybinder from GI needs to be initialized before use
        Keybinder.init()
        Keybinder.bind("<Shift>Print", self._handlePrntScreen, [])

        self._automaticEntry = False
        self._autostepRunning = False
        self._autostepDone = False
        self._autostepDoneCallback = None

        # this indicates if the screen is the last spoke to be processed for a hub
        self.lastAutostepSpoke = False
Beispiel #18
0
 def __init__(self):
     self.indicator = AppIndicator3.Indicator.new(
         'tasker', 'tasker',
         AppIndicator3.IndicatorCategory.APPLICATION_STATUS)
     self.load_preferences()
     self.indicator.set_menu(self.build_menu())
     self.indicator.set_label('', '')
     self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
     self.set_icon(True)
     self.load_todos()
     Keybinder.init()
     Keybinder.bind('<Super><Ctrl>T', self.callback)
     Gtk.main()
Beispiel #19
0
    def __init__(self, silent = False):
        super(KazamSuperIndicator, self).__init__()
        self.blink_icon = BLINK_STOP_ICON
        self.blink_state = False
        self.blink_mode = BLINK_SLOW
        self.recording = False
        self.silent = silent
        logger.debug("Indicatior silent: {0}".format(self.silent))

        self.menu = Gtk.Menu()

        self.menuitem_start = Gtk.MenuItem(_("Start recording"))
        self.menuitem_start.set_sensitive(True)
        self.menuitem_start.connect("activate", self.on_menuitem_start_activate)

        self.menuitem_pause = Gtk.CheckMenuItem(_("Pause recording"))
        self.menuitem_pause.set_sensitive(False)
        self.menuitem_pause.connect("toggled", self.on_menuitem_pause_activate)

        self.menuitem_finish = Gtk.MenuItem(_("Finish recording"))
        self.menuitem_finish.set_sensitive(False)
        self.menuitem_finish.connect("activate", self.on_menuitem_finish_activate)

        self.menuitem_separator = Gtk.SeparatorMenuItem()

        self.menuitem_quit = Gtk.MenuItem(_("Quit"))
        self.menuitem_quit.connect("activate", self.on_menuitem_quit_activate)

        self.menu.append(self.menuitem_start)
        self.menu.append(self.menuitem_pause)
        self.menu.append(self.menuitem_finish)
        self.menu.append(self.menuitem_separator)
        self.menu.append(self.menuitem_quit)

        self.menu.show_all()

        #
        # Setup keybindings - Hardcore way
        #
        try:
            from gi.repository import Keybinder
            logger.debug("Trying to bind hotkeys.")
            Keybinder.init()
            Keybinder.bind("<Super><Ctrl>R", self.cb_hotkeys, "start-request")
            Keybinder.bind("<Super><Ctrl>F", self.cb_hotkeys, "stop-request")
            Keybinder.bind("<Super><Ctrl>P", self.cb_hotkeys, "pause-request")
            Keybinder.bind("<Super><Ctrl>W", self.cb_hotkeys, "show-request")
            Keybinder.bind("<Super><Ctrl>Q", self.cb_hotkeys, "quit-request")
            self.recording = False
        except ImportError:
            logger.info("Unable to import Keybinder, hotkeys not available.")
Beispiel #20
0
    def bind(self):
        if self.bound:
            self.unbind()

        try:
            print('Binding shortcut %s to popup glipper' %
                  self.key_combination)
            keybinder.bind(self.key_combination, self.on_keyboard_shortcut)
            self.bound = True
        except KeyError:
            # if the requested keybinding conflicts with an existing one, a KeyError will be thrown
            self.bound = False

        self.emit('changed', self.bound)
Beispiel #21
0
    def bind_hotkey(self, accel_name):
        if not IS_X11 or self._current_accel_name == accel_name:
            return

        if self._current_accel_name:
            Keybinder.unbind(self._current_accel_name)
            self._current_accel_name = None

        logger.info("Trying to bind app hotkey: %s", accel_name)
        Keybinder.bind(accel_name, lambda _: self.window.show_window())
        self._current_accel_name = accel_name
        if FIRST_RUN:
            display_name = Gtk.accelerator_get_label(*Gtk.accelerator_parse(accel_name))
            show_notification("Ulauncher", f"Hotkey is set to {display_name}")
Beispiel #22
0
    def bind_show_app_hotkey(self, accel_name):
        if is_wayland_compatibility_on():
            return

        if self._current_accel_name == accel_name:
            return

        if self._current_accel_name:
            Keybinder.unbind(self._current_accel_name)
            self._current_accel_name = None

        logger.info("Trying to bind app hotkey: %s" % accel_name)
        Keybinder.bind(accel_name, self.toggle_window)
        self._current_accel_name = accel_name
        self.notify_hotkey_change(accel_name)
Beispiel #23
0
    def __init__(self):
        self.bound_keys = []
        self.workarea = Workarea()
        self.callable_actions = dict
        self.__define_callable_actions()

        notify2.init("Azulejo")
        Keybinder.init()

        Keybinder.bind("<Super>y", WindowTools.print_window_info, None)
        Keybinder.bind("<Super>c", self.switch_config_files, None)

        self.bind_keys(configuration.get_config_data_first_time())

        Gtk.main()
Beispiel #24
0
    def bind_show_app_hotkey(self, accel_name):
        if is_wayland_compatibility_on():
            return

        if self._current_accel_name == accel_name:
            return

        if self._current_accel_name:
            Keybinder.unbind(self._current_accel_name)
            self._current_accel_name = None

        logger.info("Trying to bind app hotkey: %s", accel_name)
        Keybinder.bind(accel_name, self.toggle_window)
        self._current_accel_name = accel_name
        self.notify_hotkey_change(accel_name)
Beispiel #25
0
def plugin_main(app, fullpath):
    import gi
    gi.require_version('Notify', '0.7')
    gi.require_version('Keybinder', '3.0')

    from gi.repository import Keybinder, Notify

    global notification
    notification = Notify.Notification()

    Keybinder.init()
    Keybinder.bind("<Ctrl><Alt>v", lambda *a: grab_notify(app))
    Keybinder.bind("<Ctrl><Alt>m", lambda *a: notifier(app))
    Notify.init("anubad")
    notification.set_icon_from_pixbuf(app.pixbuf_logo)
Beispiel #26
0
def bind_key(keystr, keybinding_target=KEYBINDING_DEFAULT):
    """
    Bind @keystr, unbinding any previous key for @keybinding_target.
    If @keystr is a false value, any previous key will be unbound.
    """
    keybinding_target = int(keybinding_target)

    if Keybinder is None:
        return False

    def callback(keystr):
        return GetKeyboundObject()._keybinding(keybinding_target)

    if not _is_sane_keybinding(keystr):
        pretty.print_error(__name__, "Refusing to bind key", repr(keystr))
        return False

    succ = True
    if keystr:
        try:
            succ = Keybinder.bind(keystr, callback)
            pretty.print_debug(__name__, "binding", repr(keystr))
            GetKeyboundObject().emit_bound_key_changed(keystr, True)
        except KeyError as exc:
            pretty.print_error(__name__, exc)
            succ = False
    if succ:
        old_keystr = get_currently_bound_key(keybinding_target)
        if old_keystr and old_keystr != keystr:
            Keybinder.unbind(old_keystr)
            pretty.print_debug(__name__, "unbinding", repr(old_keystr))
            GetKeyboundObject().emit_bound_key_changed(old_keystr, False)
        _register_bound_key(keystr, keybinding_target)
    return succ
Beispiel #27
0
 def _bind(self, hotkey, func):
     gtk_hotkey = self._gtk_hotkey(hotkey)
     bound = Keybinder.bind(gtk_hotkey, lambda *args, **kwargs: func())
     if bound:
         logger.debug("Bound hotkey %r (gtk_hotkey = %r)", hotkey, gtk_hotkey)
     else:
         logger.error("Unable to bind hotkey %r (gtk_hotkey = %r)", hotkey, gtk_hotkey)
Beispiel #28
0
    def __init__(self, name, callback):
        self._callback = callback
        self._worked = []

        for keystring, action in self._EVENTS.items():
            if Keybinder.bind(keystring, self._bind_cb, None):
                self._worked.append(keystring)
Beispiel #29
0
    def register_callbacks(self):
        """Connect the GTK+ signals we care about"""
        self.connect('key-press-event', self.on_key_press)
        self.connect('button-press-event', self.on_button_press)
        self.connect('delete_event', self.on_delete_event)
        self.connect('destroy', self.on_destroy_event)
        self.connect('window-state-event', self.on_window_state_changed)
        self.connect('focus-out-event', self.on_focus_out)
        self.connect('focus-in-event', self.on_focus_in)

        # Attempt to grab a global hotkey for hiding the window.
        # If we fail, we'll never hide the window, iconifying instead.
        if self.config['keybindings']['hide_window'] != None:
            if display_manager() == 'X11':
                try:
                    self.hidebound = Keybinder.bind(
                        self.config['keybindings']['hide_window'].replace('<Shift>',''),
                        self.on_hide_window)
                except (KeyError, NameError):
                    pass

                if not self.hidebound:
                    err('Unable to bind hide_window key, another instance/window has it.')
                    self.hidefunc = self.iconify
                else:
                    self.hidefunc = self.hide
Beispiel #30
0
    def register_callbacks(self):
        """Connect the GTK+ signals we care about"""
        self.connect('key-press-event', self.on_key_press)
        self.connect('button-press-event', self.on_button_press)
        self.connect('delete_event', self.on_delete_event)
        self.connect('destroy', self.on_destroy_event)
        self.connect('window-state-event', self.on_window_state_changed)
        self.connect('focus-out-event', self.on_focus_out)
        self.connect('focus-in-event', self.on_focus_in)

        # Attempt to grab a global hotkey for hiding the window.
        # If we fail, we'll never hide the window, iconifying instead.
        if self.config['keybindings']['hide_window'] != None:
            if display_manager() == 'X11':
                try:
                    self.hidebound = Keybinder.bind(
                        self.config['keybindings']['hide_window'].replace(
                            '<Shift>', ''), self.on_hide_window)
                except (KeyError, NameError):
                    pass

                if not self.hidebound:
                    err('Unable to bind hide_window key, another instance/window has it.'
                        )
                    self.hidefunc = self.iconify
                else:
                    self.hidefunc = self.hide
Beispiel #31
0
def bind_key(keystr, keybinding_target=KEYBINDING_DEFAULT):
    """
    Bind @keystr, unbinding any previous key for @keybinding_target.
    If @keystr is a false value, any previous key will be unbound.
    """
    keybinding_target = int(keybinding_target)

    if Keybinder is None:
        return False

    def callback(keystr):
        return GetKeyboundObject()._keybinding(keybinding_target)

    if not _is_sane_keybinding(keystr):
        pretty.print_error(__name__, "Refusing to bind key", repr(keystr))
        return False

    succ = True
    if keystr:
        try:
            succ = Keybinder.bind(keystr, callback)
            pretty.print_debug(__name__, "binding", repr(keystr))
            GetKeyboundObject().emit_bound_key_changed(keystr, True)
        except KeyError as exc:
            pretty.print_error(__name__, exc)
            succ = False
    if succ:
        old_keystr = get_currently_bound_key(keybinding_target)
        if old_keystr and old_keystr != keystr:
            Keybinder.unbind(old_keystr)
            pretty.print_debug(__name__, "unbinding", repr(old_keystr))
            GetKeyboundObject().emit_bound_key_changed(old_keystr, False)
        _register_bound_key(keystr, keybinding_target)
    return succ
Beispiel #32
0
    def __init__(self, name, callback):
        self._callback = callback
        self._worked = []

        for keystring, action in self._EVENTS.items():
            if Keybinder.bind(keystring, self._bind_cb, None):
                self._worked.append(keystring)
Beispiel #33
0
 def on_exaile_loaded(self):
     if not self.__exaile:
         return  # Plugin has been disabled in the meantime
     Keybinder.init()
     for k in KEYS:
         if not Keybinder.bind(k, on_media_key, self.__exaile):
             LOGGER.warning("Failed to set key binding using Keybinder.")
             self.__exaile.plugins.disable_plugin(__name__)
             return
Beispiel #34
0
 def bind_key(cls):
     Keybinder.init()
     shortcut = MetaData.get_snapshoot_shortcut()
     if Keybinder.bind(shortcut, cls.callback, ""):
         if cls.old_key_shortcut is not None:
             Keybinder.unbind(cls.old_key_shortcut)
         cls.old_key_shortcut = shortcut
     else:
         logging.error("Bind shortcut key failed ")
Beispiel #35
0
 def bind_key(cls):
     Keybinder.init()
     shortcut = MetaData.get_snapshoot_shortcut()
     if Keybinder.bind(shortcut,cls.callback,""):
         if cls.old_key_shortcut is not None:
             Keybinder.unbind(cls.old_key_shortcut)
         cls.old_key_shortcut = shortcut
     else:
         logging.error("Bind shortcut key failed ")
Beispiel #36
0
 def bind_toggle_key(self, key):
     self.unbind_toggle_key()
     self.debug(f"Binding toggle key {key}")
     success = Keybinder.bind(key, self.toggle)
     if success:
         self._toggle_key = key
         return success
     else:
         self.debug(f"Failed to bind toggle key {key}")
         return success
Beispiel #37
0
    def handleKeys(self):
        if len(self.boundKeys)>0:
            for key in self.boundKeys:
                #keybinder.unbind(key)
                pass
            self.boundKeys = []

        config = configparser.ConfigParser()
        config.read(self.keyCfg)
        sections = config.sections()

        for s in sections:
            self.cmd = cmd = config.get(s, 'Exec')
            key = config.get(s, 'Key')
            try:
                keybinder.bind(key, self.callback, cmd)
                self.boundKeys.append(key)
            except:
                print("Error: can't bind ", key, "key")
Beispiel #38
0
 def on_startup(self, app):
     '''
     This method handles the startup signal.
     As per GNOME guidelines this is where most of
     the work to create the window should be done.
     '''
     self.create_directories()
     
     self.settings = Gio.Settings(schema=self.schema_id + '.preferences')
     self.win_settings = Gio.Settings(schema=self.schema_id + '.window')
     self.width = self.win_settings['width']
     self.height = self.win_settings['height']
     self.general_settings = self.settings.get_child('general')
     self.set_autostart(self.general_settings['autostart'])
     self.closehide = self.general_settings['closehide']
     self.about_dialog = None
     self.preferences_dialog = None
     logging.basicConfig(filename=self.log_file, level=logging.DEBUG,
                         format='%(asctime)s %(levelname)s: %(message)s')
     
     self.window = Gtk.ApplicationWindow(application=app)
     self.window.connect('size-allocate', self.on_size_allocate)
     self.window.connect('delete-event', self.on_window_delete)
     self.window.set_title(self.title)
     self.window.set_default_size(self.width, self.height)
     self.window.set_position(Gtk.WindowPosition.MOUSE)
     self.window.set_titlebar(HeaderBar(self))
     # We need to set the icon here as a backup, the gnome system monitor
     # for instance, and for whatever reason, doesn't choose the right icon
     # sometimes, particularly after hiding the window, and showing again.
     self.window.set_icon_name(self.icon)
     self.main_view = MainView(self)
     self.window.add(self.main_view)
     
     self.add_actions()
     builder = Gtk.Builder.new_from_file(self.gui_ui)
     app_menu = builder.get_object('app_menu')
     self.set_app_menu(app_menu)
     
     Keybinder.init()
     shortcuts = self.settings.get_child('shortcuts')
     Keybinder.bind(shortcuts['app-show'], self.on_show)
Beispiel #39
0
def bind(binding, func, *args, **kwargs):
    """Wrapper for keybinder.bind() allowing kwargs."""

    def run(_, __): func(*args, **kwargs)
    try:
        Keybinder.unbind(binding)
    except:
        pass
    success = Keybinder.bind(binding, run, None)
    if not success:
        print "Error binding '%s'" % binding
Beispiel #40
0
 def add_global_shortcut(self):
     '''
     This method adds a global shortcut,
     the shortcut used to show the application.
     '''
     shortcuts = self.settings.get_child('shortcuts')
     if platform.system() == 'Windows':
         self.modifiers = {
             Gdk.ModifierType.SHIFT_MASK: ['VK_SHIFT'],
             Gdk.ModifierType.CONTROL_MASK: ['VK_CONTROL'],
             Gdk.ModifierType.MOD1_MASK: ['VK_MENU'],
             Gdk.ModifierType.SUPER_MASK: ['VK_LWIN', 'VK_RWIN']
         }
         hook_manager = pyHook.HookManager()
         hook_manager.KeyDown = self.on_keyboard_event
         self.set_hotkey(shortcuts['app-show'])
         hook_manager.HookKeyboard()
     else:
         Keybinder.init()
         Keybinder.bind(shortcuts['app-show'], self.on_show)
Beispiel #41
0
def init_keybinder(player):
    try:
        import gi
        gi.require_version("Keybinder", "3.0")
        from gi.repository import Keybinder
    except (ValueError, ImportError):
        return False

    Keybinder.init()

    signals = {
        "XF86AudioPrev": "prev",
        "XF86AudioNext": "next",
        "XF86AudioStop": "stop",
        "XF86AudioPlay": "play"
    }
    for sig, action in signals.items():
        Keybinder.bind(sig, make_keybinder_cb(player, action), None)

    return True
Beispiel #42
0
 def add_global_shortcut(self):
     '''
     This method adds a global shortcut,
     the shortcut used to show the application.
     '''
     shortcuts = self.settings.get_child('shortcuts')
     if platform.system() == 'Windows':
         self.modifiers = {Gdk.ModifierType.SHIFT_MASK:
                               ['VK_SHIFT'],
                           Gdk.ModifierType.CONTROL_MASK:
                               ['VK_CONTROL'],
                           Gdk.ModifierType.MOD1_MASK:
                               ['VK_MENU'],
                           Gdk.ModifierType.SUPER_MASK:
                               ['VK_LWIN', 'VK_RWIN']}
         hook_manager = pyHook.HookManager()
         hook_manager.KeyDown = self.on_keyboard_event
         self.set_hotkey(shortcuts['app-show'])
         hook_manager.HookKeyboard()
     else:
         Keybinder.init()
         Keybinder.bind(shortcuts['app-show'], self.on_show)
Beispiel #43
0
    def bind_keys(self, config_data):
        for action in config_data:
            keybinds = action['keybind']
            function_name = action['function']
            function = self.callable_actions[function_name]
            parameters = action['parameters']
            dispacher_parameters = [function, keybinds, parameters]

            for keybind in keybinds:
                if Keybinder.bind(keybind, self.dispatcher, dispacher_parameters):
                    self.bound_keys.append(keybind)
                else:
                    print keybind, "was not bound successfully"
Beispiel #44
0
    def bind_tab(self, bind=True):
        if bind:
            Keybinder.bind(self.super + 'Tab', self.tab_key, False)
            Keybinder.bind(self.super + '<Shift>Tab', self.tab_key, True)

            for i, key in enumerate(self.monkeys):
                Keybinder.bind(self.super + '<Ctrl>' + key, self.tab_key,
                               False, i)
                Keybinder.bind(self.super + '<Ctrl><Shift>' + key,
                               self.tab_key, False, i)
        else:
            Keybinder.unbind(self.super + 'Tab')
            Keybinder.unbind(self.super + '<Shift>Tab')

            for i, key in enumerate(self.monkeys):
                Keybinder.unbind(self.super + '<Ctrl>' + key)
                Keybinder.unbind(self.super + '<Ctrl><Shift>' + key)
Beispiel #45
0
    def __init__(self):
        self.display = display.Display()

        Keybinder.init()
        Keybinder.bind("<Ctrl>9", self.on_snippets_activated)

        menu = Gtk.Menu()

        item = Gtk.MenuItem()
        item.set_label("Editor")
        item.connect("activate", self.on_editor_activated)
        item.show()
        menu.append(item)

        item = Gtk.MenuItem()
        item.set_label("Exit")
        item.connect("activate", Gtk.main_quit)
        item.show()
        menu.append(item)

        self.status_icon = AppIndicator3.Indicator.new(
            "linux-snippets",
            "onboard-mono",
            AppIndicator3.IndicatorCategory.APPLICATION_STATUS
        )
        self.status_icon.set_icon_theme_path(os.getcwd()+"/res/")
        self.status_icon.set_icon("icon")

        self.status_icon.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
        self.status_icon.set_menu(menu)

        self.editor = e_w.EditorWindow()
        self.editor.connect("delete-event", self.on_window_deleted)

        self.snippets = sn_w.SnippetsWindow(self.on_snippets_completed)
        self.snippets.connect("delete-event", self.on_window_deleted)
Beispiel #46
0
    def bind_tab(self, bind=True):
        if bind:
            Keybinder.bind(self.super + 'Tab', self.tab_key, False)
            Keybinder.bind(self.super + '<Shift>Tab', self.tab_key, True)

            for i, key in enumerate(self.monkeys):
                Keybinder.bind(self.super + '<Ctrl>' + key,
                               self.tab_key, False, i)
                Keybinder.bind(self.super + '<Ctrl><Shift>' + key,
                               self.tab_key, False, i)
        else:
            Keybinder.unbind(self.super + 'Tab')
            Keybinder.unbind(self.super + '<Shift>Tab')

            for i, key in enumerate(self.monkeys):
                Keybinder.unbind(self.super + '<Ctrl>' + key)
                Keybinder.unbind(self.super + '<Ctrl><Shift>' + key)
Beispiel #47
0
    def bind_keybinder(self):
        try:
            import gi
            gi.require_version('Keybinder', '3.0')
            # Gdk needed for Keybinder
            from gi.repository import Keybinder, Gdk
            Keybinder.init()
        except:
            return False

        Keybinder.bind('XF86AudioPlay', self.window.playpause, None)
        Keybinder.bind('XF86AudioStop', self.window.user_pause, None)
        Keybinder.bind('XF86AudioNext', self.window.next_song, None)
        Keybinder.bind('XF86AudioPrev', self.window.bring_to_top, None)

        logging.info("Bound media keys with keybinder")
        self.method = 'keybinder'
        return True
Beispiel #48
0
 def bind_keybinder(self):
     try:
         import gi
         gi.require_version('Keybinder', '3.0')
         # Gdk needed for Keybinder
         from gi.repository import Keybinder
         Keybinder.init()
     except (ValueError, ImportError):
         return False
     
     Keybinder.bind('XF86AudioPlay', self.window.playpause, None)
     Keybinder.bind('XF86AudioStop', self.window.user_pause, None)
     Keybinder.bind('XF86AudioNext', self.window.next_song, None)
     Keybinder.bind('XF86AudioPrev', self.window.bring_to_top, None)
     
     logging.info("Bound media keys with keybinder")
     self.method = 'keybinder'
     return True
Beispiel #49
0
	def __init__(self):
		Gtk.Window.__init__(self, type=Gtk.WindowType.TOPLEVEL)
		Keybinder.init()

		# Deactivating WM keybindings
		keybindings = Gio.Settings.new('org.gnome.desktop.wm.keybindings')
		wm_hotkey = lambda t: keybindings.get_value(t)[0]
		if wm_hotkey('switch-input-source') or wm_hotkey('switch-input-source-backward'):
			self.show_message("Unity-Kbd-Switcher is going to deactivate the following WM keybindings\n"
				+ "You can set them later in settings if you'll decide to discontinue using.\n"
				+ "\n"
				+ "switch-input-source: " + wm_hotkey('switch-input-source') + "\n"
				+ "switch-input-source-backward: " + wm_hotkey('switch-input-source-backward') + "\n")
			keybindings.set_value('switch-input-source', GLib.Variant('as', ['']))
			keybindings.set_value('switch-input-source-backward', GLib.Variant('as', ['']))

		# Initializing GSettings
		self.source_settings = Gio.Settings.new('org.gnome.desktop.input-sources')
		self.source_settings.connect("changed::current", self.on_current_changed)
		self.source_settings.connect("changed::sources", self.on_sources_changed)

		# Loading config
		rc = "%s/.kbdrc" % os.getenv("HOME")
		if not os.path.isfile(rc):
			self.generate_default_rc(rc)
		keymap = {}
		execfile(rc)
		self.keymap = keymap

		self.current_layout = None
		self.on_sources_changed(None, None)
		self.on_current_changed(None, None)

		# Binding global hotkeys
		for key in self.keymap.keys():
			print "Binding %s" % key
			if not Keybinder.bind(key, self.on_global_key_activated, None):
				self.show_message("Could not bind '%s'" % key)
		
		# Usual Gtk Stuff
		self.connect("destroy", Gtk.main_quit)
		self.connect("delete_event", Gtk.main_quit)
		signal.signal(signal.SIGINT, signal.SIG_DFL)
		internals.app = self
		Gtk.main()
Beispiel #50
0
    def __init__(self, player):
        self.player = player
        self.logger = logging.getLogger('KeyboardClient')

        try:
            import gi
            gi.require_version('Keybinder', '3.0')
            from gi.repository import Keybinder
            Keybinder.init()
            Keybinder.bind('XF86AudioPlay', self._on_XF86AudioPlay)
            Keybinder.bind('XF86AudioNext', self._on_XF86AudioNext)
            Keybinder.bind('XF86AudioPrev', self._on_XF86AudioPrev)
        except ValueError:
            self.logger.warning(
                'Keybinder is needed on Linux for MediaKey binding')
Beispiel #51
0
	def __init__(self, keys=False, spacing=3):
		super().__init__()

		self.icon = Gtk.Label()
		self.text = Gtk.Label()
		box = Gtk.Box(spacing=spacing)
		box.pack_start(self.icon, False, False, 0)
		box.pack_start(self.text, False, False, 0)
		self.add(box)

		self.icon.show()
		self.text.show()
		box.show()
		self.show()

		self.build_popup()

		self.set_events(Gdk.EventMask.BUTTON_PRESS_MASK)
		self.connect("button-press-event", self.click)

		self.pulse_bus = dbus.connection.Connection(pulse_bus_address())
		self.pulse_core = self.pulse_bus.get_object(None, "/org/pulseaudio/core1")

		self.pulse_core.ListenForSignal("org.PulseAudio.Core1.FallbackSinkUpdated", [self.pulse_core], dbus_interface="org.PulseAudio.Core1")
		self.pulse_core.ListenForSignal("org.PulseAudio.Core1.FallbackSinkUnset", [self.pulse_core], dbus_interface="org.PulseAudio.Core1")

		self.default_sink = None
		self.updateSink(self.pulse_core.Get("org.PulseAudio.Core1", "FallbackSink", dbus_interface=PROPS))

		self.pulse_bus.add_signal_receiver(self.updateSink, "FallbackSinkUpdated")
		self.pulse_bus.add_signal_receiver(self.unsetSink, "FallbackSinkUnset")
		self.pulse_bus.add_signal_receiver(self.updateVolume, "VolumeUpdated")
		self.pulse_bus.add_signal_receiver(self.updateMute, "MuteUpdated")

		if keys:
			Keybinder.bind("AudioMute", self.toggleMute)
			Keybinder.bind("AudioRaiseVolume", self.changeVolume, +5)
			Keybinder.bind("AudioLowerVolume", self.changeVolume, -5)
Beispiel #52
0
    def run(self):
        # self.win = Gtk.Window()
        self.win = Gtk.Window(type=Gtk.WindowType.POPUP)
        self.win.set_border_width(1)

        width = 400
        relative_top = 0.25

        self.win.set_size_request(width, -1)

        self.win.move(
            (Gdk.Screen.get_default().width() / 2) - width / 2,
            Gdk.Screen.get_default().height() * relative_top,
        )

        self.win.connect("delete-event", Gtk.main_quit)
        self.win.connect("show", self.handle_show)

        self.win.set_type_hint(Gdk.WindowTypeHint.UTILITY)

        self.win.set_resizable(False)

        self.win.set_decorated(False)

        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
        vbox.set_homogeneous(False)
        self.win.add(vbox)

        self.entry = Gtk.Entry()

        self.entry.override_font(
            Pango.FontDescription.from_string(self.config["entry_font"]))

        self.entry.connect("key-press-event", self.handle_key_press)
        self.entry.connect("changed", self.handle_input)

        vbox.pack_start(self.entry, False, True, 0)

        self.store = Gtk.ListStore(GdkPixbuf.Pixbuf, str, object)

        self.tree = Gtk.TreeView(self.store)

        self.tree.override_font(Pango.FontDescription.from_string(self.config["name_font"]))
        self.tree.set_headers_visible(False)

        self.tree.get_selection().set_mode(Gtk.SelectionMode.BROWSE)

        self.content_renderer = Gtk.CellRendererText()
        content_column = Gtk.TreeViewColumn("Name", self.content_renderer, markup=1)

        self.icon_renderer = Gtk.CellRendererPixbuf()
        icon_column = Gtk.TreeViewColumn("Icon", self.icon_renderer, pixbuf=0)

        self.tree.append_column(icon_column)
        self.tree.append_column(content_column)

        self.tree.set_search_column(-1)

        def handle_selection_changed(selection):
            tree_iter = selection.get_selected()[1]

            if not tree_iter:
                return

            self.tree.scroll_to_cell(self.store.get_path(tree_iter))

        self.tree.get_selection().connect("changed", handle_selection_changed)

        self.scrolled = Gtk.ScrolledWindow()
        self.scrolled.set_policy(Gtk.PolicyType.ALWAYS, Gtk.PolicyType.AUTOMATIC)


        self.scrolled.add(self.tree)

        vbox.pack_start(self.scrolled, False, False, 0)

        signal.signal(signal.SIGINT, signal.SIG_DFL)

        accel_group = Gtk.AccelGroup()

        def connect_accel(accel, func):
            accel_group.connect(accel[0], accel[1], 0, func)

        def connection_multiple_accels(accels, func):
            for accel in accels:
                connect_accel(accel, func)

        hide_accel = Gtk.accelerator_parse("Escape")
        connect_accel(hide_accel, self.hide)

        quit_accel = Gtk.accelerator_parse("<Ctrl>q")
        connect_accel(quit_accel, Gtk.main_quit)

        launch_accel = Gtk.accelerator_parse("Return")
        connect_accel(launch_accel, self.launch_choice)

        Keybinder.init()
        Keybinder.bind(self.config["show_binding"], self.show, None)

        self.win.add_accel_group(accel_group)
        self.win.show_all()
        self.scrolled.hide()

        # Gdk.keyboard_grab(self.win.get_window(), False, Gdk.CURRENT_TIME)

        Gtk.main()
Beispiel #53
0
example-gi-py3.py

Looked at a pull request that was built for py2.x, but
overwrote the original py instead of making a separate example.
I wouldn't have accepted that pull request either.

The keybinder.init() part wasn't in the original example.

[email protected]

public domain
"""

import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Keybinder', '3.0')

from gi.repository import Gtk
from gi.repository import Keybinder

def callback(keystr, user_data):
    print ("Handling", user_data)
    print ("Event time:", Keybinder.get_current_event_time())
    Gtk.main_quit()

if __name__ == '__main__':
    keystr = "<Ctrl><Alt>M"
    Keybinder.init()
    Keybinder.bind(keystr, callback, "keystring %s (user data)" % keystr)
    print ("Press", keystr, "to handle keybinding and quit")
    Gtk.main()
Beispiel #54
0
    if keystr == KeyBinds.pomodoro.value:
        handler.btn_pomodoro_clicked_cb(None)
    elif keystr == KeyBinds.short_break.value:
        handler.btn_short_break_clicked_cb(None)
    elif keystr == KeyBinds.long_break.value:
        handler.btn_long_break_clicked_cb(None)
    elif keystr == KeyBinds.timer.value:
        if handler.watch and handler.watch.is_alive():
            handler.btn_stop_clicked_cb(None)
        else:
            handler.btn_start_clicked_cb(None)
    elif keystr == KeyBinds.reset.value:
        handler.btn_reset_clicked_cb(None)
    elif keystr == KeyBinds.quit.value:
        handler.window_destroy_cb(None)


if __name__ == "__main__":
    handler = Handler
    builder = Gtk.Builder()
    builder.add_from_file("./pomodoro.glade")
    window = builder.get_object("window")
    lbl_time = builder.get_object("lbl_time")
    handler = Handler(lbl_time)
    builder.connect_signals(handler)
    window.show_all()
    Keybinder.init()
    for keystr in KeyBinds:
        Keybinder.bind(keystr.value, callback)
    Gtk.main()
Beispiel #55
0
	def bind_all_key(self, key_toggle, key_copy, key_paste):
		"""Bind all keys used with tida"""
		Keybinder.bind(key_toggle, self.callback_toggle_visibility, "asd")
		Keybinder.bind(key_copy, self.callback_copy, "asd")
		Keybinder.bind(key_paste, self.callback_paste, "asd")
    def __init__(self, fullscreen):
        """Create a new anaconda main window.

          :param bool fullscreen: if True, fullscreen the window, if false maximize
        """
        Gtk.Window.__init__(self)

        # Hide the titlebar when maximized if the window manager allows it.
        # This makes anaconda look full-screenish but without covering parts
        # needed to interact with the window manager, like the GNOME top bar.
        self.set_hide_titlebar_when_maximized(True)

        # The Anaconda and Initial Setup windows might sometimes get decorated with
        # a titlebar which contains the __init__.py header text by default.
        # As all Anaconda and Initial Setup usually have a very distinct title text
        # inside the window, the titlebar text is redundant and should be disabled.
        self.set_title(_(WINDOW_TITLE_TEXT))

        # Set the icon used in the taskbar of window managers that have a taskbar
        # The "anaconda" icon is part of fedora-logos
        self.set_icon_name("anaconda")

        # Treat an attempt to close the window the same as hitting quit
        self.connect("delete-event", self._on_delete_event)

        # Create a black, 50% opacity pixel that will be scaled to fit the lightbox overlay
        # The confusing list of unnamed parameters is:
        # bytes, colorspace (there is no other colorspace), has-alpha,
        # bits-per-sample (has to be 8), width, height,
        # rowstride (bytes between row starts, but we only have one row)
        self._transparent_base = GdkPixbuf.Pixbuf.new_from_bytes(GLib.Bytes.new([0, 0, 0, 127]),
                GdkPixbuf.Colorspace.RGB, True, 8, 1, 1, 1)

        # Contain everything in an overlay so the window can be overlayed with the transparency
        # for the lightbox effect
        self._overlay = Gtk.Overlay()
        self._overlay_img = None
        self._overlay.connect("get-child-position", self._on_overlay_get_child_position)

        self._overlay_depth = 0

        # Create a stack and a list of what's been added to the stack
        # Double the stack transition duration since the default 200ms is too
        # quick to get the point across
        self._stack = Gtk.Stack(transition_duration=400)
        self._stack_contents = set()

        # Create an accel group for the F12 accelerators added after window transitions
        self._accel_group = Gtk.AccelGroup()
        self.add_accel_group(self._accel_group)

        # Make the window big
        if fullscreen:
            self.fullscreen()
        else:
            self.maximize()

        self._overlay.add(self._stack)
        self.add(self._overlay)
        self.show_all()

        self._current_action = None

        # Help button mnemonics handling
        self._mnemonic_signal = None
        # we have a sensible initial value, just in case
        self._saved_help_button_label = _("Help!")

        # Apply the initial language attributes
        self._language = None
        self.reapply_language()

        # Keybinder from GI needs to be initialized before use
        Keybinder.init()
        Keybinder.bind("<Shift>Print", self._handle_print_screen, [])

        self._screenshot_index = 0