Esempio n. 1
0
	def __init__(self, window, webview, config):
		self.window = window
		self.webview = webview
		self.config = config
		self.blinking = False
		
		self.tray = appindicator.Indicator("example-simple-client", "QQ", appindicator.CATEGORY_APPLICATION_STATUS)
		self.tray.set_status(appindicator.STATUS_ACTIVE)
		self.iconChange('QQ.png')
		
		menu = gtk.Menu()
		item1 = gtk.MenuItem('显示/隐藏窗口')
		item1.connect("activate", self.click_tray)
		menu.append(item1)
		item2 = gtk.MenuItem('配置...')
		item2.connect("activate", self.click_config)
		menu.append(item2)
		item3 = gtk.ImageMenuItem(gtk.STOCK_QUIT)		
		item3.set_label('退出')
		item3.connect("activate", gtk.main_quit)
		menu.append(item3)
		menu.show_all()
		self.tray.set_menu(menu)
		
		self.webview.connect('title-changed', self.title_changed)
		keybinder.bind(self.config.hot_key, self.keybind_callback)
Esempio n. 2
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)
Esempio n. 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 = item[1]),
                )
Esempio n. 4
0
File: hotot.py Progetto: fma16/Hotot
 def init_hotkey(self):
     try:
         keybinder.bind(
               config.settings['shortcut_summon_hotot']
             , self.on_hotkey_compose)
     except:
         pass
Esempio n. 5
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)
Esempio n. 6
0
	def __init__(self):
		#try loading the config file
		# if it doesn't exist, create one
		try:
			self.configFile = expanduser("~") + "/.puut/puut.conf"
			#load configuration
			self.config = {}
			exec(open(self.configFile).read(),self.config)
		except IOError:
			self.setupPuut()
			call(["notify-send", "Puut: Setup config", "Setup your user data at '~/.puut/puut.conf'"])
			sys.exit(1)

		#testing if server & credentials are correct
		r = requests.get(self.config["serverAddress"] + "/info", auth=(self.config["user"],self.config["password"]))
		if not (r.text=="PUUT"):
			call(["notify-send", "Puut: Server error", "Contacting the server was unsuccessful, are credentials and server correct?\nResponse was: "+ r.text])
			sys.exit(1)		
		
		#setting up keyhooks
		for self.idx, self.val in enumerate(self.config["keys"]):
			keybinder.bind(self.val, self.hotkeyFired, self.idx) 

		#setup GTK Status icon
		self.statusicon = gtk.StatusIcon()
		self.statusicon.set_from_file("icon.png") 
		self.statusicon.connect("popup-menu", self.right_click_event)
		self.statusicon.set_tooltip("StatusIcon Example")
 def __bind(self, key, field):
     try:
         self.__try_unbind(key)
     except:
         pass
         
     keybinder.bind(key, lambda(text): self.__handle_callback(text, self.func[field]), "Global binding for %s pressed(%s)" % (field, key))
     self.logdebug("Bound %s" % key)
Esempio n. 8
0
	def change_s_dialog_key(self, gconfclient=None, gconfentry=None, gconfvalue=None, d=None):
		try:
			keybinder.unbind(self.prev_sel_dialog_key)
		except:
			pass

		keybinder.bind(prefs.get_sel_dialog_key(), lambda: self.s_dialog.show())
		self.prev_sel_dialog_key = prefs.get_sel_dialog_key()
Esempio n. 9
0
	def change_prefs_dialog_key(self, gconfclient=None, gconfentry=None, gconfvalue=None, d=None):
		try:
			keybinder.unbind(self.prev_prefs_dialog_key)
		except:
			pass

		keybinder.bind(prefs.get_prefs_dialog_key(), lambda: prefs.PreferencesDialog())
		self.prev_prefs_dialog_key = prefs.get_prefs_dialog_key()
Esempio n. 10
0
 def init_hotkey(self):
     try:
         import keybinder
         keybinder.bind(
               config.settings['shortcut_summon_hotot']
             , self.on_hotkey_compose)
     except:
         pass
	def bind_tails(chain, callback, timeout):
		links = chain.split("-")
		head = links[0]
		tails = links[1:]
		if links != ['']:
			keybinder.bind(head, lambda : bind_tails("-".join(tails), callback, timeout))
			gobject.timeout_add(timeout, lambda : keybinder.unbind(head))
		else:
			callback()
Esempio n. 12
0
	def bind_with_keybinder(self):
		x = commands.getoutput('xmodmap')
		if x.find('Super_L') == '-1' and Globals.Settings['Bind_Key'] == 'Super_L':
			os.system("xmodmap -e 'keycode 115 = Super_L'")
			os.system('xmodmap -e "add mod4 = Super_L"')
		try:
			import keybinder as bindkey
			bindkey.bind(Globals.Settings['Bind_Key'], self.ToggleMenu)			
			print 'python keybinder found - binding'
		except:
			self.bind_with_deskbar()
Esempio n. 13
0
def run():    

    for action in configuration.conf_data:
        keybind = action['keybind']
        function_name = action['function']
        function = callable_actions[function_name]
        parameters = action['parameters']
        dispacher_parameters = [function, parameters]
        keybinder.bind(keybind, dispatcher ,dispacher_parameters)        

    gtk.main()
 def __init__(self, applet = None, iid = None):
     self.mask = 0x00 #the original mask. Neither caps nor num lock is on.
     self.applet = applet
     self.appletContainer = gtk.Table(1,2, True)
     #self.applet.connect("destroy", self.cleanup)
     #Add an indicator in, and add it to the applet
     #TODO Have the icon resize with panel size changes.
     self.capsLockIndicatorIcon = gtk.Image()
     self.capsLockIndicatorIcon.set_tooltip_text("Indicates the state of the Caps Lock key.")
     self.appletContainer.attach(self.capsLockIndicatorIcon,0,1,0,1)
     
     #set up the num lock icon
     self.numLockIndicatorIcon = gtk.Image()
     self.numLockIndicatorIcon.hide()
     self.numLockIndicatorIcon.set_tooltip_text("Num Lock key on.") 
     self.appletContainer.attach(self.numLockIndicatorIcon, 1,2,0,1)
     
     #create a notifier to display info.
     #we shall use one notifier because Ubuntu's notification system sucks.         
     pynotify.init("lockindicator-applet")
     self.lockNotifier = pynotify.Notification("None", "None") #random values.
     self.applet.add(self.appletContainer)
     self.applet.show_all()        
     
     #connect the Caps and Num Lock key to a class method
     keybinder.bind("Caps_Lock", self.lockPressed)
     keybinder.bind("Num_Lock", self.lockPressed)
     
     #set up the XKB Wrapper and get the display info
     self.xkbWrapper = XkbWrapper()
     try:
         displayInfo = self.xkbWrapper.openDisplayAndInitXkb(None, 1, 0)
     except OSError as osError:
         print osError.args[0]
     
     self.displayHandle = displayInfo['display_handle']
     self.deviceSpec = self.xkbWrapper.constants_xkb['XkbUseCoreKbd']
     
     #get the first starting state. Don't bother notification icons.
     self.mask = self.xkbWrapper.getIndicatorStates(self.displayHandle, self.deviceSpec).value
     if self.mask & CAPS_LOCK_MASK:
         self.capsLockIndicatorIcon.set_from_file("%s/share/lockindicator-applet/CapsLockIndicator-ON.png"
                                                      %INSTALL_PREFIX)
         self.capsLockIndicatorIcon.show()
     else:
         self.capsLockIndicatorIcon.set_from_file("%s/share/lockindicator-applet/CapsLockIndicator-OFF.png"
                                                      %INSTALL_PREFIX)
         self.capsLockIndicatorIcon.show()
     
     #do the same for num lock            
     if self.mask & NUM_LOCK_MASK:
         self.numLockIndicatorIcon.set_from_file("%s/share/lockindicator-applet/NumLockIndicator.png"
                                                 %INSTALL_PREFIX)
         self.numLockIndicatorIcon.show()
Esempio n. 15
0
 def init_shortcuts(self):
     #Global shortcuts:
     if os.name == "nt":
         show_id = wx.NewId()
         #TODO: RegisterHotKey works only on win, add sth for linux
         self.app.RegisterHotKey(show_id, 
             wx.MOD_CONTROL | wx.MOD_ALT, ord('P'))
         self.Bind(wx.EVT_HOTKEY, self.toggle_minimize, id=show_id)
     else:
         import keybinder
         keybinder.bind("<Ctrl><Alt>p", 
             lambda: wx.CallAfter(self.toggle_minimize))
Esempio n. 16
0
 def __init__(self, window, webview, config):
     self.window = window
     self.webview = webview
     self.config = config
     self.blinking = False
     self.tray = gtk.StatusIcon()
     self.tray.set_from_file(const.ICON)
     self.tray.set_tooltip(const.NAME + ' ' + const.VERSION)
     self.tray.connect('activate', self.click_tray)
     self.tray.connect('popup-menu', self.popup)
     self.webview.connect('title-changed', self.title_changed)
     keybinder.bind(self.config.hot_key, self.keybind_callback)
Esempio n. 17
0
	def __init__(self, window, webview, config):
		self.window = window
		self.webview = webview
		self.config = config
		self.blinking = False
		self.tray = gtk.StatusIcon()
		self.tray.set_from_file(const.ICON)
		self.tray.set_tooltip(const.NAME + ' ' + const.VERSION)
		self.tray.connect('activate', self.click_tray)
		self.tray.connect('popup-menu', self.popup)
		self.webview.connect('title-changed', self.title_changed)
		keybinder.bind(self.config.hot_key, self.keybind_callback)
Esempio n. 18
0
 def __init__(self, parent):
     self.parent = parent
     conf.add_plugin_defaults(self.meta, self.module)
     try:
         for i, keyname in enumerate(
                 conf.switch_key.split(",")):  # allow multiple keys
             keybinder.bind(
                 keyname, self.switch,
                 ((-1 if i else +1)))  # forward +1 or backward -1
     except:
         log.ERR("plugin global_key: Key `%s` could not be registered" %
                 conf.switch_key)
Esempio n. 19
0
def init_keybinder(player):
    try:
        import keybinder
    except ImportError:
        return False

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

    return True
Esempio n. 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)
Esempio n. 21
0
File: boxes.py Progetto: jmmk/boxes
    def __init__(self, desktop):
        super(SelectionGrid, self).__init__()

        dimensions = desktop.availableGeometry()
        self.screen_width = dimensions.width()
        self.screen_height = dimensions.height()

        self.windows = WindowHelper()

        self.load_config()
        keybinder.bind(self.settings['hotkey'], self.toggle)
        self.construct_grid()
        self.init_grid_ui()
Esempio n. 22
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)
Esempio n. 23
0
    def change_prefs_dialog_key(self,
                                gconfclient=None,
                                gconfentry=None,
                                gconfvalue=None,
                                d=None):
        try:
            keybinder.unbind(self.prev_prefs_dialog_key)
        except:
            pass

        keybinder.bind(prefs.get_prefs_dialog_key(),
                       lambda: prefs.PreferencesDialog())
        self.prev_prefs_dialog_key = prefs.get_prefs_dialog_key()
Esempio n. 24
0
    def change_s_dialog_key(self,
                            gconfclient=None,
                            gconfentry=None,
                            gconfvalue=None,
                            d=None):
        try:
            keybinder.unbind(self.prev_sel_dialog_key)
        except:
            pass

        keybinder.bind(prefs.get_sel_dialog_key(),
                       lambda: self.s_dialog.show())
        self.prev_sel_dialog_key = prefs.get_sel_dialog_key()
Esempio n. 25
0
 def btnsave_clicked(self, widget):
     self.config.login_password = self.txtPassword.get_text()
     self.config.proxy_uri = self.txtProxyUri.get_text()
     self.config.save_path = self.dcbtnSavePath.get_current_folder()
     try:
         keybinder.unbind(self.config.hot_key)
     except:
         pass
     self.config.hot_key = self.txtHotkey.get_text()
     keybinder.bind(self.config.hot_key, self.tray.keybind_callback)
     self.webview.init_proxy()
     self.config.save()
     utils.notification('保存配置成功', '部分配置重启程序后生效')
     self.window.destroy()
Esempio n. 26
0
	def btnsave_clicked(self, widget):
		self.config.login_password = self.txtPassword.get_text()
		self.config.proxy_uri = self.txtProxyUri.get_text()
		self.config.save_path = self.dcbtnSavePath.get_current_folder()
		try:
			keybinder.unbind(self.config.hot_key)
		except:
			pass
		self.config.hot_key = self.txtHotkey.get_text()
		keybinder.bind(self.config.hot_key, self.tray.keybind_callback)
		self.webview.init_proxy()
		self.config.save()
		utils.notification('保存配置成功', '部分配置重启程序后生效')
		self.window.destroy()
Esempio n. 27
0
 def bindKeys(self):
   for toggle in self._hotkeys:
     if not (self._hotkeys[toggle] == "DISABLED"):
       try:  keybinder.unbind(self._hotkeys[toggle])
       except: pass
     
       # Default bad hotkeys
       if not gtk.accelerator_parse(self._hotkeys[toggle])[0] and not self._hotkeys[toggle] == self._defaults[toggle]:
         self._hotkeys[toggle] = self._defaults[toggle]
     
       try:
           keybinder.bind(self._hotkeys[toggle], self.keyboard_callback, toggle)
       
       except: pass
Esempio n. 28
0
 def bind_keys(self):
     if bind_global:
         keybinder.bind(
             self.config.get_item('global_play_pause'), self.play_pause)
         keybinder.bind(self.config.get_item('global_next'), self.next_song)
         keybinder.bind(
             self.config.get_item('global_previous'), self.previous_song)
         keybinder.bind(self.config.get_item('global_star'), self.star_song)
    def __init__(self):
        self.keystr = "<Ctrl>A"
        keybinder.bind(self.keystr, self.enter_new_task, "Keystring %s (user data)" % self.keystr)
        # Get the default client
        self.client = gconf.client_get_default()
        self.client.add_dir ("/apps/tyme", gconf.CLIENT_PRELOAD_NONE)

        self.ind = appindicator.Indicator("tyme-indicator", "indicator-messages", appindicator.CATEGORY_APPLICATION_STATUS)
        self.ind.set_status(appindicator.STATUS_ACTIVE)
        self.ind.set_attention_icon("new-messages-red")

        self.menu_setup()
        self.ind.set_menu(self.menu)
        self.tasks = []
        self.initialize_tyme_connector()
Esempio n. 30
0
 def bind_keys(self):
     if bind_global:
         keybinder.bind(self.config.get_item('global_play_pause'),
                        self.play_pause)
         keybinder.bind(self.config.get_item('global_next'), self.next_song)
         keybinder.bind(self.config.get_item('global_previous'),
                        self.previous_song)
         keybinder.bind(self.config.get_item('global_star'), self.star_song)
Esempio n. 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.
	"""
    try:
        import keybinder
    except ImportError:
        pretty.print_error(
            __name__, "Could not import keybinder, "
            "keybindings disabled!")
        return False

    keybinding_target = int(keybinding_target)
    callback = lambda: 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, exc:
            pretty.print_error(__name__, exc)
            succ = False
Esempio n. 32
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:
            try:
                self.hidebound = keybinder.bind(
                    self.config['keybindings']['hide_window'],
                    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
Esempio n. 33
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:
            try:
                self.hidebound = keybinder.bind(
                    self.config['keybindings']['hide_window'],
                    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
Esempio n. 34
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.
	"""
	try:
		import keybinder
	except ImportError:
		pretty.print_error(__name__, "Could not import keybinder, "
				"keybindings disabled!")
		return False

	keybinding_target = int(keybinding_target)
	callback = lambda : 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, exc:
			pretty.print_error(__name__, exc)
			succ = False
Esempio n. 35
0
 def reload_global(self):
     for action, keys in self.global_keybinder.iteritems():
         param = None
         if isinstance(action, tuple):
             action, param = action
         if not isinstance(keys, list):
             keys = [keys]
         if param:
             func = getattr(self.gshell, action)(param)
         else:
             func = getattr(self.gshell, action)
         for key in keys:
             if hasattr(self.gshell, action):
                 if param:
                     func = getattr(self.gshell, action)(param)
                 else:
                     func = getattr(self.gshell, action)
                 keybinder.bind(key, func)
Esempio n. 36
0
 def bind(self, k):
     if not keybinding:
         return
     kb_output = keybinder.bind(modifiers+funkey+str(k), self.keypress, None, fake_key, k)
     if not kb_output:
         if modifiers: mod = '>+<'.join(modifiers.split('><'))+'+'
         else: mod = ''
         print 'Error! Check configuration or try custom key modifiers ("{}{}{}")'.format(mod, funkey, k)
     self.keybindings[k] = kb_output
    def __init__(self):
        self.keystr = "<Ctrl>A"
        keybinder.bind(self.keystr, self.enter_new_task,
                       "Keystring %s (user data)" % self.keystr)
        # Get the default client
        self.client = gconf.client_get_default()
        self.client.add_dir("/apps/tyme", gconf.CLIENT_PRELOAD_NONE)

        self.ind = appindicator.Indicator(
            "tyme-indicator", "indicator-messages",
            appindicator.CATEGORY_APPLICATION_STATUS)
        self.ind.set_status(appindicator.STATUS_ACTIVE)
        self.ind.set_attention_icon("new-messages-red")

        self.menu_setup()
        self.ind.set_menu(self.menu)
        self.tasks = []
        self.initialize_tyme_connector()
Esempio n. 38
0
    def __init__(self, status_icon):

        self.messages = []
        self.disable_libnotify = False
        self.username = ""
        self.password = ""
        self.interval = 35
        self.last_id = None
        self.loglevel = "debug"
        self.logger = logging.getLogger(APP_NAME)
        self.logger.setLevel(LOG_LEVELS.get(self.loglevel, logging.INFO))
        self.dialog = None
        self.force_update = False

        if not os.path.exists(CONFIG_DIR):
            os.mkdir(CONFIG_DIR)

        if not os.path.exists(CONFIG_FILE):
            # Create a config file with default values
            self._save_config()

        if not os.path.exists(DATA_DIR):
            os.mkdir(DATA_DIR)

        if not os.path.exists(CACHE_DIR):
            os.mkdir(CACHE_DIR)

        Thread.__init__(self, name=SRV_NAME)
        self.logger.debug("Thread started")

        self._load_config()

        self.updates_locked = False
        self.status_icon = status_icon

        self.status_icon.set_from_file(os.path.join(CURRENT_DIR, "icons", "twitter-inactive.svg"))

        self.status_icon.connect("button-press-event", self.button_press)
        try:
            keybinder.bind("F12", self.key_press, self.status_icon)
        except KeyError:
            self.logger.error("Unable to use <F12>. Hotkey is already bound")

        status_icon.set_visible(True)
Esempio n. 39
0
 def on_gkeys_changed(self, arg=None, dialog=True):
     functions = {
                  "gkeys_select_next_group": self.gkey_select_next_group,
                  "gkeys_select_previous_group": \
                             self.gkey_select_previous_group,
                  "gkeys_select_next_window": \
                             self.gkey_select_next_window_in_group,
                  "gkeys_select_previous_window": \
                             self.gkey_select_previous_window_in_group,
                }
     translations = {
        'gkeys_select_next_group': _('Select next group'),
        'gkeys_select_previous_group': _('Select previous group'),
        'gkeys_select_next_window': _('Select next window in group'),
        'gkeys_select_previous_window': _('Select previous window in group')
                    }
     for (s, f) in functions.items():
         if self.gkeys[s] is not None:
             keybinder.unbind(self.gkeys[s])
             self.gkeys[s] = None
         if not self.globals.settings[s]:
             # The global key is not in use
             continue
         keystr = self.globals.settings['%s_keystr'%s]
         try:
             if keybinder.bind(keystr, f):
                 # Key succesfully bound.
                 self.gkeys[s]= keystr
                 error = False
             else:
                 error = True
                 reason = ""
                 # Keybinder sometimes doesn't unbind faulty binds.
                 # We have to do it manually.
                 try:
                     keybinder.unbind(keystr)
                 except:
                     pass
         except KeyError:
             error = True
             reason = _("The key is already bound elsewhere.")
         if error:
             message = _("Error: DockbarX couldn't set global keybinding '%(keystr)s' for %(function)s.")%{'keystr':keystr, 'function':translations[s]}
             text = "%s %s"%(message, reason)
             print text
             if dialog:
                 md = gtk.MessageDialog(
                         None,
                         gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                         gtk.MESSAGE_ERROR, gtk.BUTTONS_CLOSE,
                         text
                                       )
                 md.run()
                 md.destroy()
Esempio n. 40
0
    def __init__(self, app):
        self.window = app.window
        self.webview = app.webview
        self.config = app.config
        self.app = app
        self.blinking = False

        self.icon = self.app.get_app_icon()
        self.icon_alt = self.app.get_app_icon(get_alt=True)

        self.makePopup()

        self.isUnity = utils.is_unity()
        if self.isUnity:
            self.makeUnityTray()
        else:
            self.makeTray()
        if self.config["hot_key"]:
            import keybinder
            keybinder.bind(self.config["hot_key"], self.keybind_callback)
Esempio n. 41
0
 def bind_keybinder(self):
     try:
         import keybinder
     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
Esempio n. 42
0
    def setup(self):
        self.wind = gtk.Window()
        self.wind.set_decorated(False)
        self.wind.set_default_size(DEFAULT_WIDTH, -1)
        self.wind.connect("key-press-event", self.escape_listener)

        vbox = gtk.VBox()

        self.wind.add(vbox)

        self.query_box = gtk.Entry()
        vbox.add(self.query_box)

        self.query_box.connect("key-press-event", self.ctrl_enter_listener)
        self.query_box.connect("changed", self.query_input_listener)

        self.entries = ResultBox(FileContentProvider(FILE_PATH))
        vbox.add(self.entries)

        keybinder.bind(KEY_STRING, self.keybinder_callback)

        self.wind.show_all()
def bind_keychain(chain, callback, timeout=400):
	"""Bind a callable object to a globally available key sequence.
	
	Arguments:
	chain		-- a string describing the key sequence.
	callback	-- a callable object
	timeout		-- how much time to wait before unbinding. (default: 400ms)
	"""
	def bind_tails(chain, callback, timeout):
		links = chain.split("-")
		head = links[0]
		tails = links[1:]
		if links != ['']:
			keybinder.bind(head, lambda : bind_tails("-".join(tails), callback, timeout))
			gobject.timeout_add(timeout, lambda : keybinder.unbind(head))
		else:
			callback()

	links = chain.split("-")
	head = links[0]
	tails = links[1:]
	keybinder.bind(head, lambda : bind_tails("-".join(tails), callback, timeout))
Esempio n. 44
0
 def __bind(self, raw_key, field):
     key = deepin_to_keybinder(raw_key)
     try:
         self.__try_unbind(key)
     except:    
         pass
     
     try:
         result = keybinder.bind(key, lambda : self.__handle_callback(key, self.func[field]))
     except:    
         result = False
     else:    
         if not result:
             dbus_notify.set_summary(_("DMusic"))
             dbus_notify.set_body(_("Failed to bind %s !") % utils.xmlescape(raw_key))
             dbus_notify.notify()
     return result    
Esempio n. 45
0
def bind(key, fun):
    if not keybinder.bind(key, fun):
        sys.stderr.write('Could not bind: ' + key)
        return False
    return True
 def bind(self, modifiers, key, handler, param=None):
     """
     Bind a key to an handler function
     """
     keys = modifiers + key
     return keybinder.bind(keys, handler, param)
Esempio n. 47
0
    ewmh.set_desktop_layout_checked(ewmh.Orientation.Horz,
                                    len(config.desktops), 1,
                                    ewmh.StartingCorner.TopLeft).check()
    ewmh.request_number_of_desktops_checked(len(config.desktops)).check()

# Is this a horizontal or vertical pager?
if config.width > config.height:
    orient = 'H'
elif config.width < config.height:
    orient = 'V'
else:  # weirdo, could go either way
    orient = 'V'

# Grab keybindings
for key_string, fun in keybinds.iteritems():
    if not keybinder.bind(key_string, fun):
        print >> sys.stderr, 'could not bind %s' % key_string

# Start loading information
desk_num = ewmh.get_number_of_desktops().reply()
desk_names = ewmh.get_desktop_names().reply()
root_geom = ewmh.get_desktop_geometry().reply()

activewin = ewmh.get_active_window().reply()
desktop = ewmh.get_current_desktop().reply()
stacking = ewmh.get_client_list_stacking().reply()
visibles = ewmh.get_visible_desktops().reply()

clients = {}
monitors = []
xtophys = []
Esempio n. 48
0
    def start(self):
        self.START = time.time() // 1
        self.ui.build_menu(self.datatype, self.title, self.datalist,
                           self.offset, self.index, self.step, self.START)
        self.ui.build_process_bar(
            self.player.process_location, self.player.process_length,
            self.player.playing_flag, self.player.pause_flag,
            self.storage.database['player_info']['playing_mode'])
        self.stack.append([
            self.datatype, self.title, self.datalist, self.offset, self.index
        ])
        if bind_global:
            keybinder.bind(self.config.get_item("global_play_pause"),
                           self.play_pause)
            keybinder.bind(self.config.get_item("global_next"), self.next_song)
            keybinder.bind(self.config.get_item("global_previous"),
                           self.previous_song)
        while True:
            datatype = self.datatype
            title = self.title
            datalist = self.datalist
            offset = self.offset
            idx = index = self.index
            step = self.step
            stack = self.stack
            djstack = self.djstack
            self.screen.timeout(500)
            key = self.screen.getch()
            if bind_global:
                keybinder.gtk.main_iteration(False)
            self.ui.screen.refresh()

            # term resize
            if key == -1:
                self.ui.update_size()
                self.player.update_size()

            # 退出
            if key == ord('q'):
                break

            # 退出并清除用户信息
            if key == ord('w'):
                self.storage.database['user'] = {
                    "username": "",
                    "password": "",
                    "user_id": "",
                    "nickname": "",
                }
                try:
                    os.remove(self.storage.cookie_path)
                except:
                    break
                break

            # 上移
            elif key == ord('k'):
                self.index = carousel(offset,
                                      min(len(datalist), offset + step) - 1,
                                      idx - 1)
                self.START = time.time()

            # 下移
            elif key == ord('j'):
                self.index = carousel(offset,
                                      min(len(datalist), offset + step) - 1,
                                      idx + 1)
                self.START = time.time()

            # 数字快捷键
            elif ord('0') <= key <= ord('9'):
                if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help':
                    continue
                idx = key - ord('0')
                self.ui.build_menu(self.datatype, self.title, self.datalist,
                                   self.offset, idx, self.step, self.START)
                self.ui.build_loading()
                self.dispatch_enter(idx)
                self.index = 0
                self.offset = 0

            # 向上翻页
            elif key == ord('u'):
                if offset == 0:
                    continue
                self.START = time.time()
                self.offset -= step

                # e.g. 23 - 10 = 13 --> 10
                self.index = (index - step) // step * step

            # 向下翻页
            elif key == ord('d'):
                if offset + step >= len(datalist):
                    continue
                self.START = time.time()
                self.offset += step

                # e.g. 23 + 10 = 33 --> 30
                self.index = (index + step) // step * step

            # 前进
            elif key == ord('l') or key == 10:
                if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help':
                    continue
                self.START = time.time()
                self.ui.build_loading()
                self.dispatch_enter(idx)
                self.index = 0
                self.offset = 0

            # 回退
            elif key == ord('h'):
                # if not main menu
                if len(self.stack) == 1:
                    continue
                self.START = time.time()
                up = stack.pop()
                self.datatype = up[0]
                self.title = up[1]
                self.datalist = up[2]
                self.offset = up[3]
                self.index = up[4]
                self.at_playing_list = False

            # 搜索
            elif key == ord('f'):
                # 8 is the 'search' menu
                self.dispatch_enter(8)

            # 播放下一曲
            elif key == ord(']'):
                self.next_song()

            # 播放上一曲
            elif key == ord('['):
                self.previous_song()

            # 增加音量
            elif key == ord('='):
                self.player.volume_up()

            # 减少音量
            elif key == ord('-'):
                self.player.volume_down()

            # 随机播放
            elif key == ord('?'):
                if len(self.storage.database["player_info"]
                       ["player_list"]) == 0:
                    continue
                self.player.shuffle()
                time.sleep(0.1)

            # 喜爱
            elif key == ord(','):
                self.request_api(self.netease.fm_like,
                                 self.player.get_playing_id())

            # 删除FM
            elif key == ord('.'):
                if self.datatype == 'fmsongs':
                    if len(self.storage.database["player_info"]
                           ["player_list"]) == 0:
                        continue
                    self.player.next()
                    self.request_api(self.netease.fm_trash,
                                     self.player.get_playing_id())
                    time.sleep(0.1)

            # 下一FM
            elif key == ord('/'):
                if self.datatype == 'fmsongs':
                    if len(self.storage.database["player_info"]
                           ["player_list"]) == 0:
                        continue
                    self.player.next()
                    time.sleep(0.1)

            # 播放、暂停
            elif key == ord(' '):
                # If not open a new playing list, just play and pause.
                try:
                    if self.datalist[idx]['song_id'] == self.player.playing_id:
                        self.player.play_and_pause(
                            self.storage.database['player_info']['idx'])
                        time.sleep(0.1)
                        continue
                except:
                    pass
                # If change to a new playing list. Add playing list and play.
                if datatype == 'songs':
                    self.resume_play = False
                    self.player.new_player_list('songs', self.title,
                                                self.datalist, -1)
                    self.player.end_callback = None
                    self.player.play_and_pause(idx)
                    self.at_playing_list = True
                elif datatype == 'djchannels':
                    self.resume_play = False
                    self.player.new_player_list('djchannels', self.title,
                                                self.datalist, -1)
                    self.player.end_callback = None
                    self.player.play_and_pause(idx)
                    self.at_playing_list = True
                elif datatype == 'fmsongs':
                    self.resume_play = False
                    self.storage.database['player_info']['playing_mode'] = 0
                    self.player.new_player_list('fmsongs', self.title,
                                                self.datalist, -1)
                    self.player.end_callback = self.fm_callback
                    self.player.play_and_pause(idx)
                    self.at_playing_list = True
                else:
                    self.player.play_and_pause(
                        self.storage.database['player_info']['idx'])
                time.sleep(0.1)

            # 加载当前播放列表
            elif key == ord('p'):
                if len(self.storage.database['player_info']
                       ['player_list']) == 0:
                    continue
                if not self.at_playing_list:
                    self.stack.append([
                        self.datatype, self.title, self.datalist, self.offset,
                        self.index
                    ])
                    self.at_playing_list = True
                self.datatype = self.storage.database['player_info'][
                    'player_list_type']
                self.title = self.storage.database['player_info'][
                    'player_list_title']
                self.datalist = []
                for i in self.storage.database['player_info']['player_list']:
                    self.datalist.append(self.storage.database['songs'][i])
                self.index = self.storage.database['player_info']['idx']
                self.offset = self.storage.database['player_info'][
                    'idx'] / self.step * self.step
                if self.resume_play:
                    if self.datatype == "fmsongs":
                        self.player.end_callback = self.fm_callback
                    else:
                        self.player.end_callback = None
                    self.storage.database['player_info']['idx'] = -1
                    self.player.play_and_pause(self.index)
                    self.resume_play = False

            # 播放模式切换
            elif key == ord('P'):
                self.storage.database['player_info']['playing_mode'] = \
                    (self.storage.database['player_info']['playing_mode'] + 1) % 5

            # 添加到打碟歌单
            elif key == ord('a'):
                if datatype == 'songs' and len(datalist) != 0:
                    self.djstack.append(datalist[idx])
                elif datatype == 'artists':
                    pass

            # 加载打碟歌单
            elif key == ord('z'):
                self.stack.append([datatype, title, datalist, offset, index])
                self.datatype = 'songs'
                self.title = '网易云音乐 > 打碟'
                self.datalist = self.djstack
                self.offset = 0
                self.index = 0

            # 添加到收藏歌曲
            elif key == ord('s'):
                if (datatype == 'songs'
                        or datatype == 'djchannels') and len(datalist) != 0:
                    self.collection.append(datalist[idx])

            # 加载收藏歌曲
            elif key == ord('c'):
                self.stack.append([datatype, title, datalist, offset, index])
                self.datatype = 'songs'
                self.title = '网易云音乐 > 收藏'
                self.datalist = self.collection
                self.offset = 0
                self.index = 0

            # 从当前列表移除
            elif key == ord('r'):
                if (datatype == 'songs'
                        or datatype == 'djchannels') and len(datalist) != 0:
                    self.datalist.pop(idx)
                    self.index = carousel(
                        offset,
                        min(len(datalist), offset + step) - 1, idx)

            # 当前项目下移
            elif key == ord("J"):
                if datatype != 'main' and len(
                        datalist) != 0 and idx + 1 != len(self.datalist):
                    self.START = time.time()
                    song = self.datalist.pop(idx)
                    self.datalist.insert(idx + 1, song)
                    self.index = idx + 1
                    # 翻页
                    if self.index >= offset + step:
                        self.offset = offset + step

            # 当前项目上移
            elif key == ord("K"):
                if datatype != 'main' and len(datalist) != 0 and idx != 0:
                    self.START = time.time()
                    song = self.datalist.pop(idx)
                    self.datalist.insert(idx - 1, song)
                    self.index = idx - 1
                    # 翻页
                    if self.index < offset:
                        self.offset = offset - step

            elif key == ord('m'):
                if datatype != 'main':
                    self.stack.append(
                        [datatype, title, datalist, offset, index])
                    self.datatype = self.stack[0][0]
                    self.title = self.stack[0][1]
                    self.datalist = self.stack[0][2]
                    self.offset = 0
                    self.index = 0

            elif key == ord('g'):
                if datatype == 'help':
                    webbrowser.open_new_tab(
                        'https://github.com/darknessomi/musicbox')

            self.ui.build_process_bar(
                self.player.process_location, self.player.process_length,
                self.player.playing_flag, self.player.pause_flag,
                self.storage.database['player_info']['playing_mode'])
            self.ui.build_menu(self.datatype, self.title, self.datalist,
                               self.offset, self.index, self.step, self.START)

        self.player.stop()
        self.cache.quit()
        self.storage.save()
        curses.endwin()
Esempio n. 49
0
    def __init__(self, logger, nodetach):
        gtk.Window.__init__(self)

        self.timer = None
        self.logger = logger

        self.options = self.load_state()
        if not self.options:
            self.options = {
                'timeout': 2.5,
                'position': POS_BOTTOM,
                'size': SIZE_MEDIUM,
                'mode': MODE_NORMAL,
                'hotkey': '<Ctrl>F1',
                }

        if not nodetach:
            self.logger.debug("Detach from the parent.")
            self.drop_tty()

        self.set_skip_taskbar_hint(True)
        self.set_skip_pager_hint(True)
        self.set_keep_above(True)
        self.set_decorated(False)
        self.stick()
        self.set_property('accept-focus', False)
        self.set_property('focus-on-map', False)
        self.set_position(gtk.WIN_POS_CENTER)
        bgcolor = gtk.gdk.color_parse("black")
        self.modify_bg(gtk.STATE_NORMAL, bgcolor)
        self.set_opacity(0.7)

        gobject.signal_new("text-changed", gtk.Label, 
                        gobject.SIGNAL_RUN_FIRST, gobject.TYPE_NONE, ())
        self.label = gtk.Label()
        self.label.set_justify(gtk.JUSTIFY_RIGHT)
        self.label.set_ellipsize(pango.ELLIPSIZE_START)
        self.label.connect("text-changed", self.on_label_change)
        self.label.show()
        self.add(self.label)

        self.screen_width = gtk.gdk.screen_width()   
        self.screen_height = gtk.gdk.screen_height() 
        self.set_window_size(self.options['size'])

        self.set_gravity(gtk.gdk.GRAVITY_CENTER)
        self.set_xy_position(self.options['position'])

        self.listenkbd = ListenKbd(self.label, logger=self.logger, 
                                   mode=self.options['mode'])
        self.listenkbd.start()

        menu = gtk.Menu()

        show_item = gtk.CheckMenuItem(_("Show keys"))
        show_item.set_active(True)
        show_item.connect("toggled", self.on_show_keys)
        show_item.show()
        menu.append(show_item)

        preferences_item = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        preferences_item.connect("activate", self.on_preferences_dialog)
        preferences_item.show()
        menu.append(preferences_item)


        about_item = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        about_item.connect("activate", self.on_about_dialog)
        about_item.show()
        menu.append(about_item)

        separator_item = gtk.SeparatorMenuItem()
        separator_item.show()
        menu.append(separator_item)

        image = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        image.connect("activate", self.quit)
        image.show()
        menu.append(image)
        menu.show()

        try:
            import appindicator
            self.systray = appindicator.Indicator(APP_NAME, 
                           'indicator-messages', 
                            appindicator.CATEGORY_APPLICATION_STATUS)
            self.systray.set_status(appindicator.STATUS_ACTIVE)
            self.systray.set_attention_icon("indicator-messages-new")
            self.systray.set_icon(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.set_menu(menu)
            self.logger.debug("Using AppIndicator.")
        except(ImportError):
            self.systray = gtk.StatusIcon()
            self.systray.set_from_icon_name(
                    "preferences-desktop-keyboard-shortcuts")
            self.systray.connect("popup-menu", 
                    self.on_statusicon_popup, menu)
            self.logger.debug("Using StatusIcon.")

        self.connect("delete-event", self.quit)
        keybinder.bind(self.options['hotkey'], self.hotkey_cb, show_item)
Esempio n. 50
0
 def _bind_term(self):
     try:
         keybinder.bind('<Control><Alt>X', self.abrir_terminal)
     except (KeyError, NameError):
         pass
Esempio n. 51
0
        move_method = getattr(self, 'move_' + direction)
        #print 'Moving window to: %s' % direction
        move_method(window)


if __name__ == '__main__':
    MagicKey = '<Super><Alt>'
    x = Productivity()
    #x.init()
    keystr_right = MagicKey + "Right"
    keystr_left = MagicKey + "Left"
    keystr_left = MagicKey + "Down"
    keystr_left = MagicKey + "Up"

    keybinder.bind(keystr_right, x.main, "right")
    keybinder.bind(keystr_left, x.main, "left")
    keybinder.bind(keystr_left, x.main, "down")
    keybinder.bind(keystr_left, x.main, "up")

    status_bar = appindicator.Indicator(
        "Some indicator", "Message?", appindicator.CATEGORY_APPLICATION_STATUS)
    status_bar.set_status(appindicator.STATUS_ACTIVE)
    status_bar.set_attention_icon("indicator-messages-new")
    some_menu = gtk.Menu()

    for i in range(3):
        rnd_txt = "Test menu item #%s" % i
        some_element = gtk.MenuItem(rnd_txt)
        #some_element.connect("activate", callback, rnd_txt)
Esempio n. 52
0
#!/usr/bin/env python
"""
example.py

Created in 2010 by Ulrik Sverdrup <*****@*****.**>
This work is placed in the public domain.
"""
import gtk
import keybinder


def callback(user_data):
    print "Handling", user_data
    gtk.main_quit()


if __name__ == '__main__':
    keystr = "<Ctrl>A"
    keybinder.bind(keystr, callback, "Keystring %s (user data)" % keystr)
    print "Press", keystr, "to handle keybinding and quit"
    gtk.main()
Esempio n. 53
0
def main():
    keybinder.bind('<Super>Up', notifyDelta, 5)
    keybinder.bind('<Super>Down', notifyDelta, -5)
    keybinder.bind('XF86AudioRaiseVolume', notifyDelta, 5)
    keybinder.bind('XF86AudioLowerVolume', notifyDelta, -5)
    keybinder.bind('<Super>0', toggleMute, None)
    keybinder.bind('XF86AudioMute', toggleMute, None)
    gtk.mainloop()
Esempio n. 54
0
    def start(self):
        # Hong, Return the time in seconds since the epoch as a floating point number.
        self.START = time.time() // 1
        self.ui.build_menu(self.datatype, self.title, self.datalist,
                           self.offset, self.index, self.step, self.START)
        self.ui.build_process_bar(
            self.player.process_location, self.player.process_length,
            self.player.playing_flag, self.player.pause_flag,
            self.storage.database['player_info']['playing_mode'])
        self.stack.append([
            self.datatype, self.title, self.datalist, self.offset, self.index
        ])
        if bind_global:
            keybinder.bind(self.config.get_item("global_play_pause"),
                           self.play_pause)
            keybinder.bind(self.config.get_item("global_next"), self.next_song)
            keybinder.bind(self.config.get_item("global_previous"),
                           self.previous_song)
        while True:
            datatype = self.datatype
            title = self.title
            datalist = self.datalist
            offset = self.offset
            idx = index = self.index
            step = self.step
            stack = self.stack
            djstack = self.djstack
            self.screen.timeout(500)
            key = self.screen.getch()
            if bind_global:
                keybinder.gtk.main_iteration(False)
            self.ui.screen.refresh()

            # term resize
            if key == -1:
                self.ui.update_size()
                self.player.update_size()

            # 退出
            # Hong, ord(), Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object,
            # or the value of the byte when the argument is an 8-bit string.
            if key == ord('q'):
                break

            # 退出并清除用户信息
            if key == ord('w'):
                self.storage.database['user'] = {
                    "username": "",
                    "password": "",
                    "user_id": "",
                    "nickname": "",
                }
                try:
                    os.remove(self.storage.cookie_path)
                except:
                    break
                break

            # 上移
            elif key == ord('k'):
                # turn page if at beginning
                if idx == offset:
                    if offset == 0:
                        continue
                    self.offset -= step
                    # 移动光标到最后一列
                    self.index = offset - 1
                else:
                    self.index = carousel(
                        offset,
                        min(len(datalist), offset + step) - 1, idx - 1)
                self.START = time.time()

            # 下移
            elif key == ord('j'):
                # turn page if at end
                if idx == min(len(datalist), offset + step) - 1:
                    if offset + step >= len(datalist):
                        continue
                    self.offset += step
                    # 移动光标到第一列
                    self.index = offset + step
                else:
                    self.index = carousel(
                        offset,
                        min(len(datalist), offset + step) - 1, idx + 1)
                self.START = time.time()

            # 数字快捷键
            elif ord('0') <= key <= ord('9'):
                if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help':
                    continue
                idx = key - ord('0')
                self.ui.build_menu(self.datatype, self.title, self.datalist,
                                   self.offset, idx, self.step, self.START)
                self.ui.build_loading()
                self.dispatch_enter(idx)
                self.index = 0
                self.offset = 0

            # 向上翻页
            elif key == ord('u'):
                if offset == 0:
                    continue
                self.START = time.time()
                self.offset -= step

                # e.g. 23 - 10 = 13 --> 10
                self.index = (index - step) // step * step

            # 向下翻页
            elif key == ord('d'):
                if offset + step >= len(datalist):
                    continue
                self.START = time.time()
                self.offset += step

                # e.g. 23 + 10 = 33 --> 30
                self.index = (index + step) // step * step

            # 前进
            elif key == ord('l') or key == 10:
                if self.datatype == 'songs' or self.datatype == 'djchannels' or self.datatype == 'help' or len(
                        self.datalist) <= 0:
                    continue
                self.START = time.time()
                self.ui.build_loading()
                self.dispatch_enter(idx)
                self.index = 0
                self.offset = 0

            # 回退
            elif key == ord('h'):
                # if not main menu
                if len(self.stack) == 1:
                    continue
                self.START = time.time()
                up = stack.pop()
                self.datatype = up[0]
                self.title = up[1]
                self.datalist = up[2]
                self.offset = up[3]
                self.index = up[4]
                self.at_playing_list = False

            # 搜索
            elif key == ord('f'):
                # 8 is the 'search' menu
                self.dispatch_enter(8)

            # 播放下一曲
            elif key == ord(']'):
                self.next_song()

            # 播放上一曲
            elif key == ord('['):
                self.previous_song()

            # 增加音量
            elif key == ord('='):
                self.player.volume_up()

            # 减少音量
            elif key == ord('-'):
                self.player.volume_down()

            # 随机播放
            elif key == ord('?'):
                if len(self.storage.database["player_info"]
                       ["player_list"]) == 0:
                    continue
                self.player.shuffle()
                time.sleep(0.1)

            # 喜爱
            elif key == ord(','):
                return_data = self.request_api(self.netease.fm_like,
                                               self.player.get_playing_id())
                if return_data != -1:
                    if platform.system() == 'Darwin':
                        os.system(
                            '/usr/bin/osascript -e \'display notification "Added successfully"\''
                        )
                    else:
                        os.system('/usr/bin/notify-send "Added successfully"')

            # 删除FM
            elif key == ord('.'):
                if self.datatype == 'fmsongs':
                    if len(self.storage.database["player_info"]
                           ["player_list"]) == 0:
                        continue
                    self.player.next()
                    return_data = self.request_api(
                        self.netease.fm_trash, self.player.get_playing_id())
                    if return_data != -1:
                        if platform.system() == 'Darwin':
                            os.system(
                                '/usr/bin/osascript -e \'display notification "Deleted successfully"\''
                            )
                        else:
                            os.system(
                                '/usr/bin/notify-send "Deleted successfully"')
                    time.sleep(0.1)

            # 下一FM
            elif key == ord('/'):
                if self.datatype == 'fmsongs':
                    if len(self.storage.database["player_info"]
                           ["player_list"]) == 0:
                        continue
                    self.player.next()
                    time.sleep(0.1)

            # 播放、暂停
            elif key == ord(' '):
                # If not open a new playing list, just play and pause.
                try:
                    if self.datalist[idx]['song_id'] == self.player.playing_id:
                        self.player.play_and_pause(
                            self.storage.database['player_info']['idx'])
                        time.sleep(0.1)
                        continue
                except:
                    pass
                # If change to a new playing list. Add playing list and play.
                if datatype == 'songs':
                    self.resume_play = False
                    self.player.new_player_list('songs', self.title,
                                                self.datalist, -1)
                    self.player.end_callback = None
                    self.player.play_and_pause(idx)
                    self.at_playing_list = True
                elif datatype == 'djchannels':
                    self.resume_play = False
                    self.player.new_player_list('djchannels', self.title,
                                                self.datalist, -1)
                    self.player.end_callback = None
                    self.player.play_and_pause(idx)
                    self.at_playing_list = True
                elif datatype == 'fmsongs':
                    self.resume_play = False
                    self.storage.database['player_info']['playing_mode'] = 0
                    self.player.new_player_list('fmsongs', self.title,
                                                self.datalist, -1)
                    self.player.end_callback = self.fm_callback
                    self.player.play_and_pause(idx)
                    self.at_playing_list = True
                else:
                    self.player.play_and_pause(
                        self.storage.database['player_info']['idx'])
                time.sleep(0.1)

            # 加载当前播放列表
            elif key == ord('p'):
                self.show_playing_song()

            # 播放模式切换
            elif key == ord('P'):
                self.storage.database['player_info']['playing_mode'] = \
                    (self.storage.database['player_info']['playing_mode'] + 1) % 5

            # 添加到打碟歌单
            elif key == ord('a'):
                if datatype == 'songs' and len(datalist) != 0:
                    self.djstack.append(datalist[idx])
                elif datatype == 'artists':
                    pass

            # 加载打碟歌单
            elif key == ord('z'):
                self.stack.append([datatype, title, datalist, offset, index])
                self.datatype = 'songs'
                self.title = '网易云音乐 > 打碟'
                self.datalist = self.djstack
                self.offset = 0
                self.index = 0

            # 添加到收藏歌曲
            elif key == ord('s'):
                if (datatype == 'songs'
                        or datatype == 'djchannels') and len(datalist) != 0:
                    self.collection.append(datalist[idx])
                    if platform.system() == 'Darwin':
                        os.system(
                            '/usr/bin/osascript -e \'display notification "Added successfully"\''
                        )
                    else:
                        os.system('/usr/bin/notify-send "Added successfully"')

            # 加载收藏歌曲
            elif key == ord('c'):
                self.stack.append([datatype, title, datalist, offset, index])
                self.datatype = 'songs'
                self.title = '网易云音乐 > 收藏'
                self.datalist = self.collection
                self.offset = 0
                self.index = 0

            # 从当前列表移除
            elif key == ord('r'):
                if (datatype == 'songs'
                        or datatype == 'djchannels') and len(datalist) != 0:
                    self.datalist.pop(idx)
                    self.index = carousel(
                        offset,
                        min(len(datalist), offset + step) - 1, idx)

            # 当前项目下移
            elif key == ord("J"):
                if datatype != 'main' and len(
                        datalist) != 0 and idx + 1 != len(self.datalist):
                    self.START = time.time()
                    song = self.datalist.pop(idx)
                    self.datalist.insert(idx + 1, song)
                    self.index = idx + 1
                    # 翻页
                    if self.index >= offset + step:
                        self.offset = offset + step

            # 当前项目上移
            elif key == ord("K"):
                if datatype != 'main' and len(datalist) != 0 and idx != 0:
                    self.START = time.time()
                    song = self.datalist.pop(idx)
                    self.datalist.insert(idx - 1, song)
                    self.index = idx - 1
                    # 翻页
                    if self.index < offset:
                        self.offset = offset - step

            elif key == ord('m'):
                if datatype != 'main':
                    self.stack.append(
                        [datatype, title, datalist, offset, index])
                    self.datatype = self.stack[0][0]
                    self.title = self.stack[0][1]
                    self.datalist = self.stack[0][2]
                    self.offset = 0
                    self.index = 0

            elif key == ord('g'):
                if datatype == 'help':
                    webbrowser.open_new_tab(
                        'https://github.com/darknessomi/musicbox')

            # 开始下载
            elif key == ord("C"):
                s = self.datalist[idx]
                cache_thread = threading.Thread(
                    target=self.player.cacheSong1time,
                    args=(s['song_id'], s['song_name'], s['artist'],
                          s['mp3_url']))
                cache_thread.start()

            elif key == ord('i'):
                if self.player.playing_id != -1:
                    webbrowser.open_new_tab('http://music.163.com/#/song?id=' +
                                            str(self.player.playing_id))

            self.ui.build_process_bar(
                self.player.process_location, self.player.process_length,
                self.player.playing_flag, self.player.pause_flag,
                self.storage.database['player_info']['playing_mode'])
            self.ui.build_menu(self.datatype, self.title, self.datalist,
                               self.offset, self.index, self.step, self.START)

        self.player.stop()
        self.cache.quit()
        self.storage.save()
        curses.endwin()
Esempio n. 55
0
    pointer = w.get_pointer()

    f = open(base_name + '/screenshot_' + filename + '.txt', 'w')
    f.write('%s,%s' % (pointer[0] - X, pointer[1] - Y))
    f.close()

    pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, False, 8, sz[0], sz[1])
    pb = pb.get_from_drawable(w, w.get_colormap(), X, Y, 0, 0, sz[0], sz[1])
    if (pb != None):
        pb.save(base_name + '/screenshot_' + filename + '.png', 'png')
        print "Screenshot " + filename + " saved."
    else:
        print "Unable to get the screenshot."


if mode == 'wait_key':
    print 'Press ctrl-alt-q to capture, ctrl-alt-w to toggle 3sec loop...'
    import keybinder
    keybinder.bind('<Ctrl><Mod1>q', advance, state)
    keybinder.bind('<Ctrl><Mod1>w', toggle_auto_advance, state)
    gtk.main()
elif mode == 'wait_time':
    while True:
        countdown(wait_time)
        advance(state)
else:
    while True:
        advance(state)
        time.sleep(config.CAPTURE_DELAY)
Esempio n. 56
0
    """ hide """

    def hide(self, widget, data=None):
        self.tab = self.notebook.get_current_page()
        self.window.hide_all()
        self.window.isHide = True


if __name__ == "__main__":
    interfaz = Interfaz()

    pynotify.init("Proyecto Centrux")
    nota = pynotify.Notification("Huemul - GNU/Linux Forense",
                                 message="Al pulsar " + interfaz.bindtecla +
                                 " se desplegara la barra de accesos rapidos",
                                 icon="emblem-debian")
    nota.set_timeout(5000)
    nota.show()

    interfaz.crearTabs()
    keystr = interfaz.bindtecla
    keybinder.bind(keystr, interfaz.ocultarMostrar, "None")

    keystr = "<Ctrl>e"
    keybinder.bind(keystr, interfaz.hide, "None")

    interfaz.window.show_all()
    interfaz.window.hide_all()

    interfaz.main()
Esempio n. 57
0
    try:
        opts, args = getopt.getopt(argv[1:], 'h')
    except getopt.GetoptError, err:
        print str(err)
        usage()
        sys.exit(1)
        
    for o, a in opts:
        if o in ('-h', '--help'):
            '显示帮助信息'
            usage()
            sys.exit(0)
        else:
            print 'unknown arguments.'
            usage()
            sys.exit(2)
    # 如果发现已经存在这个vs,就不再启动
    if find_same_process("vs.py"):
        print "The vs.py was executing."
        return
    
    # 连接快捷键
    keybinder1 = keybinder.bind("F12",  on_start_pressed)
    keybinder2 = keybinder.bind("<control>F12",  on_stop_pressed)
    
    gtk.main()

if __name__ == '__main__':
    #  主入口  
    main(sys.argv)