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), )
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
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
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)
def unbinder(self, items): for keystring in items: try: Keybinder.unbind(items[keystring]) except: pass HotKeysConfig.binded = False
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)
def cancel(self): if not self._callback: return for keystring in self._worked: Keybinder.unbind(keystring) del self._worked[:] self._callback = None
def unbind(self): try: keybinder.unbind(self.prevbinding) self.bound = False except KeyError: # if the requested keybinding is not bound, a KeyError will be thrown pass
def init_keybinder(self, config): """Initialise keybinder and bind some keys (toggle, copy, paste)""" Keybinder.init() Keybinder.set_use_cooked_accelerators(False) self.bind_all_key(config['key_toggle_visibility'], config['key_copy_to_clipboard'], config['key_paste_from_clipboard'])
def setup(self, _): self.hold() # Keep the app running even without a window self.window = window = UlauncherWindow.get_instance() window.set_application(self) window.set_keep_above(True) window.position_window() window.init_theme() # this will trigger to show frequent apps if necessary window.show_results([]) if self.settings.get_property('show-indicator-icon'): self.appindicator = AppIndicator(self) self.appindicator.switch(True) if IS_X11: # bind hotkey Keybinder.init() accel_name = self.settings.get_property('hotkey-show-app') # bind in the main thread GLib.idle_add(self.bind_hotkey, accel_name) ExtensionServer.get_instance().start() time.sleep(0.01) ExtensionRunner.get_instance().run_all()
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()
def __init__(self, config_files): super(Klemmbrett, self).__init__() self._clipboard = _gtk.Clipboard.get(_gdk.SELECTION_CLIPBOARD) self._primary = _gtk.Clipboard.get(_gdk.SELECTION_PRIMARY) self.config = _config.Config() self.config.read(config_files) _keybinder.init() # configure klemmbrett self._plugins = dict() self._load_plugins() self._sync = _util.humanbool( self.config.get('klemmbrett', 'sync', True)) self.selection = None self._clipboard.connect('owner-change', self._clipboard_owner_changed) self._primary.connect('owner-change', self._clipboard_owner_changed) try: _notify.init("Klemmbrett") except _dbus.exceptions.DBusException: _log.error( "Could not register with notification interface, notifications will not work properly", exc_info=True)
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()
def finish_initializing(self, builder): """ Set up the main window """ super(UlauncherWindow, self).finish_initializing(builder) self.results_nav = None self.builder = builder self.window = self.get_widget('ulauncher_window') self.input = self.get_widget('input') self.prefs_btn = self.get_widget('prefs_btn') self.result_box = builder.get_object("result_box") self.input.connect('changed', self.on_input_changed) self.prefs_btn.connect('clicked', self.on_mnu_preferences_activate) self.set_keep_above(True) self.AboutDialog = AboutUlauncherDialog self.PreferencesDialog = PreferencesUlauncherDialog self.position_window() self.init_styles() # bind hotkey Keybinder.init() accel_name = Settings.get_instance().get_property('hotkey-show-app') # bind in the main thread GLib.idle_add(self.bind_show_app_hotkey, accel_name) start_app_watcher()
def _init_keys(self): Keybinder.init() def bind_toggle_key(self, key): self.bind_toggle_key(key) return False # to not be called again. GLib.idle_add(bind_toggle_key, self, catapult.conf.toggle_key)
def run_keybinder(callback): Keybinder.init() Keybinder.bind('<Ctrl><Alt>space', callback) try: GLib.MainLoop().run() except KeyboardInterrupt: GLib.MainLoop().quit()
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
def __init__(self, superkey='<Super>'): self.montab = MonTab() self.super = superkey nmons = self.montab.screen.get_n_monitors() self.monkeys = [chr(ord('1') + n) for n in range(nmons)] Keybinder.init() Keybinder.set_use_cooked_accelerators(False)
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 ")
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 ")
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()
def on_child_exit(self, pid, errcode, proc): Keybinder.unbind(conf.get(proc.name, 'KEY')) Process.__instances__.remove(proc) if errcode != 0: raise OSError('Terminal {} crashed'.format(self.name)) if conf.getboolean(self.name, 'Restart'): Process(self.name) del self else: sys.exit()
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()
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
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() # 2015-10-10, Joshua Chen # configure the shortcut keys Keybinder.bind("<Ctrl><Shift>F1", self.cb_hotkeys, "start-request") Keybinder.bind("<Ctrl><Shift>F12", self.cb_hotkeys, "stop-request") Keybinder.bind("<Ctrl><Shift>F8", self.cb_hotkeys, "pause-request") # Keybinder.bind("<Ctrl>W", self.cb_hotkeys, "show-request") Keybinder.bind("<Ctrl><Shift>F11", self.cb_hotkeys, "quit-request") self.recording = False except ImportError: logger.info("Unable to import Keybinder, hotkeys not available.")
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
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
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)
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()
def __init__(self): self.indicator = AppIndicator3.Indicator.new( 'tasker', 'tasker', AppIndicator3.IndicatorCategory.APPLICATION_STATUS) Keybinder.init() 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() Gtk.main()
def show_preferences(self, widget): widget.set_sensitive(False) preferences = Preferences() Keybinder.unbind(self.new_task_keybind) Keybinder.unbind(self.show_tasks_keybind) response = preferences.run() if response == Gtk.ResponseType.ACCEPT: preferences.save() self.load_preferences() self.load_todos() self.set_icon() widget.set_sensitive(True) preferences.destroy()
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}")
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)
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)
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
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)
def hide_app(self, key_bind_hide, user_data): self.last_event_time = Keybinder.get_current_event_time() print("Event time:", self.last_event_time) self.wnck.force_update() self.active_workspace = self.wnck.get_active_workspace() # print("Workspaces:", self.wnck.get_workspaces()) # print("Active workspace:", self.active_workspace) # print("Last active workspace:", self.last_active_workspace) # if self.is_present: print("Hiding app") if self.parent.is_drop_down: self.hide() else: self.iconify() self.is_present = False else: print("Showing app") if self.parent.is_drop_down: if self.last_active_workspace != self.active_workspace: self.last_active_workspace = self.active_workspace self.hide() self.show() # self.present() # self.set_icon_from_file(config.file_program_icon) self.present_with_time(self.last_event_time) self.main_box.active_term.grab_focus() self.is_present = True
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)
def on_activate(self, app): ''' This method will activate the window, most of the time. This method gets called when the application is first run, so it needs to check if the hide flag was specified, if it was, it won't actually activate the window, and it won't populate the window with any data. The reason for this is because the data that needs to be displayed is inside a collection, which may be locked, asking the user for a password on login, which is when by default the application is run, will be an unintuitive experience. The password may be in the 'Login' keyring, in which case the collection will be unlocked automatically, but we can't rely on that, and so the data is only unlocked and loaded when the application is first shown. This will slow the first show a bit, but if the password to unlock the collection is required, the user will know why that popup asking for a password is showing. Also when the collection is first unlock, and the user doesn't input the correct password, or just cancels the popup, there will be different behaviour depending on whether the application was run initially hidden or not. We feel it's best to return the window to the previous state to deliver a more intuitive experience to the user. So if the window is hidden, then it's shown, and needs a password to unlock the collection, if that password query fails, it returns to being hidden. If the application is being started without the hide flag and a password query fails, then the application is shutdown. ''' if self.hide_flag: self.hide_flag = False return # If the collection wasn't created quit if not self.main_view.secret.collection: self.quit() return if self.main_view.secret.unlock(): # The app can start hidden to speed up showing it later, # but I wouldn't want to ask for a collection password right after # the user logs in, particularly because the collection would be # locked and the user would have to input the password again later # when showing the window. So I populate the buttons on the first # show instead. I also set the started_hidden flag, this makes the # app never quit when coming from hiding and the unlock fails, # it will just keep hidden. if self.first_run: self.first_run = False self.started_hidden = True self.main_view.init_buttons() self.window.show() if platform.system() == 'Windows': current_event_time = 0 else: current_event_time = Keybinder.get_current_event_time() # This line will produce warnings on journalctl when passman # is activated without using the keyboard shortcut. # This happens because Gtk doesn't set this as the current event, # and so we have no object to get the time from. self.window.get_window().focus(current_event_time) else: # If the application starts hidden, I prefer to return the app to # the previous state, hidden, instead of quitting. if not self.started_hidden: self.quit()
def relay_key(key): print("Relaying", key) time = keybinder.get_current_event_time() s_id = "kupfer-%d_TIME%s" % (os.getpid(), time) bus = dbus.Bus() obj = bus.get_object(SERV, OBJ, introspect=False) iface = dbus.Interface(obj, IFACE) iface.RelayKeysFromDisplay(key, os.getenv("DISPLAY", ":0"), s_id)
def finish_initializing(self, builder): """Called while initializing this instance in __new__ finish_initializing should be called after parsing the UI definition and creating a UlauncherWindow object with it in order to finish initializing the start of the new UlauncherWindow instance. """ # Get a reference to the builder and set up the signals. self.builder = builder self.ui = builder.get_ui(self, True) self.PreferencesDialog = None # class self.preferences_dialog = None # instance self.results_nav = None self.window = self.ui['ulauncher_window'] self.input = self.ui['input'] self.prefs_btn = self.ui['prefs_btn'] self.result_box = self.ui["result_box"] self.input.connect('changed', self.on_input_changed) self.prefs_btn.connect('clicked', self.on_mnu_preferences_activate) self.set_keep_above(True) self.PreferencesDialog = PreferencesUlauncherDialog self.settings = Settings.get_instance() self.fix_window_width() self.position_window() self.init_theme() # this will trigger to show frequent apps if necessary self.show_results([]) if not is_wayland_compatibility_on(): # bind hotkey Keybinder.init() accel_name = self.settings.get_property('hotkey-show-app') # bind in the main thread GLib.idle_add(self.bind_show_app_hotkey, accel_name) start_app_watcher() ExtensionServer.get_instance().start() time.sleep(0.01) ExtensionRunner.get_instance().run_all() ExtensionDownloader.get_instance().download_missing()
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()
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
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")
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)
def is_available(): """ Return True if keybindings are available. """ if Keybinder is None: return False else: try: return Keybinder.supported() except AttributeError: return True
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"
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)
def show_window(self): # works only when the following methods are called in that exact order self.position_window() self.window.set_sensitive(True) self.window.present() if not is_wayland_compatibility_on(): self.present_with_time(Keybinder.get_current_event_time()) if not self.input.get_text(): # make sure frequent apps are shown if necessary self.show_results([]) elif self.settings.get_property('clear-previous-query'): self.input.set_text('') else: self.input.grab_focus()