我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xbmcgui.Window()。
def done(title, dest, downloaded): playing = xbmc.Player().isPlaying() text = xbmcgui.Window(10000).getProperty('GEN-DOWNLOADED') if len(text) > 0: text += '[CR]' if downloaded: text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR forestgreen]Download succeeded[/COLOR]') else: text += '%s : %s' % (dest.rsplit(os.sep)[-1], '[COLOR red]Download failed[/COLOR]') xbmcgui.Window(10000).setProperty('GEN-DOWNLOADED', text) if (not downloaded) or (not playing): xbmcgui.Dialog().ok(title, text) xbmcgui.Window(10000).clearProperty('GEN-DOWNLOADED')
def __init__(self): try: self.addon = xbmcaddon.Addon(id=ADDON_ID) self.win = xbmcgui.Window(10000) self.cache = SimpleCache() auth_token = self.get_authkey() if auth_token: self.parse_params() self.sp = spotipy.Spotify(auth=auth_token) me = self.sp.me() self.userid = me["id"] self.usercountry = me["country"] self.local_playback, self.playername, self.connect_id = self.active_playback_device() if self.action: action = "self." + self.action eval(action)() else: self.browse_main() self.precache_library() else: xbmcplugin.endOfDirectory(handle=self.addon_handle) except Exception as exc: log_exception(__name__, exc) xbmcplugin.endOfDirectory(handle=self.addon_handle)
def run(): try: xbmc.executebuiltin("ActivateWindow(10147)") window = xbmcgui.Window(10147) xbmc.sleep(100) window.getControl(1).setLabel(translate(32000)) window.getControl(5).setText(translate(32065)) while xbmc.getCondVisibility("Window.IsActive(10147)"): xbmc.sleep(100) ret = xbmcgui.Dialog().yesno(translate(32000), translate(32067)) if ret: xbmc.executebuiltin("RunAddon(script.keymap)") except: traceback.print_stack() xbmc.executebuiltin("XBMC.Notification('"+translate(32000)+"','"+translate(32066)+"','2000','')")
def onInit(self): # define controls self.win = xbmcgui.Window(10001) self.background = self.getControl(1001) self.cover = self.getControl(1002) self.play = self.getControl(1101) self.pause = self.getControl(1102) self.progress = self.getControl(3001) self.shuffle = self.getControl(1008) # self.repeat = self.getControl(1007) self.inLib = self.getControl(1009) self.next = self.getControl(1005) self.previous = self.getControl(1006) self.repeat_all = self.getControl(1201) self.repeat_one = self.getControl(1202) self.repeat_off = self.getControl(1203) self.volume_button = self.getControl(1011)
def showText(heading, text): id = 10147 xbmc.executebuiltin('ActivateWindow(%d)' % id) xbmc.sleep(100) win = xbmcgui.Window(id) retry = 50 while (retry > 0): try: xbmc.sleep(10) retry -= 1 win.getControl(1).setLabel(heading) win.getControl(5).setText(text) return except: pass
def get_cached_item(self, cache_id): """Returns an item from the in memory cache Parameters ---------- cache_id : :obj:`str` ID of the cache entry Returns ------- mixed Contents of the requested cache item or none """ ret = None current_window = xbmcgui.getCurrentWindowId() window = xbmcgui.Window(current_window) try: cached_items = pickle.loads(window.getProperty('memcache')) ret = cached_items.get(cache_id) except EOFError: ret = None return ret
def set_location(self, url, replace=False): """Set URL location Parameters ---------- url : :obj:`str` Window URL ret : bool Return to location prior to activation Returns ------- bool Window was activated """ cmd = 'Container.Update({},{})'.format(url, str(replace)) return xbmc.executebuiltin(cmd)
def __init__(self, *args, **kwargs): try: self.log("[SC] player 1") self.estimateFinishTime = '00:00:00' self.realFinishTime = '00:00:00' self.itemDuration = 0 self.watchedTime = 0 self.win = xbmcgui.Window(10000) self.scid = None self.ids = None self.itemDBID = None self.itemType = None self.parent = kwargs.get('parent') self.se = None self.ep = None self.popup = None self.thread = None self.stream = None self.upNextEnable = True self.libItem = None except Exception: self.log("SC Chyba MyPlayer: %s" % str(traceback.format_exc()))
def get_settings_types(): """ Devuelve un diccionario con los parametros (key) de la configuracion global y sus tipos (value) :return: dict """ WIN10000 = xbmcgui.Window(10000) settings_types = WIN10000.getProperty(PLUGIN_NAME + "_settings_types") if not settings_types: infile = open(os.path.join(get_runtime_path(), "resources", "settings.xml")) data = infile.read() infile.close() matches = re.findall('<setting id="([^"]*)" type="([^"]*)', data) settings_types = "{%s}" % ",".join("'%s': '%s'" % tup for tup in matches) WIN10000.setProperty(PLUGIN_NAME + "_settings_types", settings_types) return eval(settings_types)
def start_info_actions(infos, params): for info in infos: if info == 'autocomplete': listitems = AutoCompletion.get_autocomplete_items(params["id"], params.get("limit", 10)) elif info == 'selectautocomplete': if params.get("handle"): xbmcplugin.setResolvedUrl(handle=int(params.get("handle")), succeeded=False, listitem=xbmcgui.ListItem()) try: window = xbmcgui.Window(10103) except Exception: return None window.setFocusId(300) get_kodi_json(method="Input.SendText", params='{"text":"%s", "done":false}' % params.get("id")) return None # xbmc.executebuiltin("SendClick(103,32)") pass_list_to_skin(data=listitems, handle=params.get("handle", ""), limit=params.get("limit", 20))
def getAutoSource(): # If the VPN has changed, then reset all the numbers addon = xbmcaddon.Addon("service.vpn.manager") last_vpn = addon.getSetting("ip_service_last_vpn") current_vpn = addon.getSetting("vpn_provider_validated") if (not last_vpn == current_vpn): addon.setSetting("ip_service_last_vpn", current_vpn) resetIPServices() # Get the last source we tried to use from the home window or use the first if this is first time through source = xbmcgui.Window(10000).getProperty("VPN_Manager_Last_IP_Service") if source == "": # Record that we're using the first one xbmcgui.Window(10000).setProperty("VPN_Manager_Last_IP_Service", ip_sources[1]) return ip_sources[1] else: index = ip_sources.index(source) if index > 1: if getWorkingValue(index) >= getErrorValue(index - 1): setWorkingValue(index, 0) index = index - 1 return ip_sources[index]
def getCycleLock(): # If the lock is forced, don't wait, just return (ie don't queue) if xbmcgui.Window(10000).getProperty("VPN_Manager_Cycle_Lock") == "Forced Locked" : return False # If there's already a queue on the lock, don't wait, just return if not xbmcgui.Window(10000).getProperty("VPN_Manager_Cycle_Lock_Queued") == "" : return False # Loop until we get the lock or time out after 5 seconds xbmcgui.Window(10000).setProperty("VPN_Manager_Cycle_Lock_Queued", "Queued") i = 0 while i < 5 and not xbmcgui.Window(10000).getProperty("VPN_Manager_Cycle_Lock") == "": xbmc.sleep(1000) i = i + 1 # Free the queue so another call can wait on it xbmcgui.Window(10000).setProperty("VPN_Manager_Cycle_Lock_Queued", "") # Return false if a forced lock happened whilst we were queuing if xbmcgui.Window(10000).getProperty("VPN_Manager_Cycle_Lock") == "Forced Locked" : return False # Return false if the lock wasn't obtained because of a time out if i == 5 : return False xbmcgui.Window(10000).setProperty("VPN_Manager_Cycle_Lock", "Locked") return True
def onInit(self): #init self.log("fTVscreensaver Started") self.WINDOW = xbmcgui.Window(10000) self.kodi_tvshows = list() self.kodi_videos = list() self.WINDOW.setProperty('fTVscreensaver.Ready',"") self.abort_requested = False self.started = False self.exit_monitor = self.ExitMonitor(self.exit) #get settings self.DimEnabled = addon.getSetting('DimEnabled') self.DimTimer = addon.getSetting('DimTimer') self.DimLevel = addon.getSetting('DimLevel') self.ScrollSpeed = addon.getSetting('scrollspeed') #set dim if self.DimEnabled == 'true': xbmcgui.Window(10000).setProperty('fTVscreensaver.Dim', '1') xbmcgui.Window(10000).setProperty('fTVscreensaver.DimTimer', self.DimTimer) xbmcgui.Window(10000).setProperty('fTVscreensaver.DimLevel', self.DimLevel) #set scrollspeed xbmcgui.Window(10000).setProperty('fTVscreensaver.Scrollspeed', self.ScrollSpeed) #grab images and set properties self.scanContent() self.slideshow()
def get(version): try: import xbmc,xbmcgui,xbmcaddon,xbmcvfs f = xbmcvfs.File(xbmcaddon.Addon().getAddonInfo('changelog')) text = f.read() ; f.close() label = '%s - %s' % (xbmc.getLocalizedString(24054), xbmcaddon.Addon().getAddonInfo('name')) id = 10147 xbmc.executebuiltin('ActivateWindow(%d)' % id) xbmc.sleep(100) win = xbmcgui.Window(id) retry = 50 while (retry > 0): try: xbmc.sleep(10) win.getControl(1).setLabel(label) win.getControl(5).setText(text) retry = 0 except: retry -= 1 return '1' except: return '1'
def getCurrentViewId(): win = xbmcgui.Window(xbmcgui.getCurrentWindowId()) return str(win.getFocusId())
def show_message(message, title=xbmcaddon.Addon().getLocalizedString(50107)): if not message: return xbmc.executebuiltin("ActivateWindow(%d)" % (10147, )) win = xbmcgui.Window(10147) xbmc.sleep(100) win.getControl(1).setLabel(title) win.getControl(5).setText(message)
def showMessage(message, title = lang(50001)): if not message: return xbmc.executebuiltin("ActivateWindow(%d)" % 10147) win = xbmcgui.Window(10147) xbmc.sleep(100) win.getControl(1).setLabel(title) win.getControl(5).setText(message)
def _fetch(self): log_msg("Spotify radio track buffer invoking recommendations() via spotipy", xbmc.LOGDEBUG) try: auth_token = xbmc.getInfoLabel("Window(Home).Property(spotify-token)").decode("utf-8") client = spotipy.Spotify(auth_token) tracks = client.recommendations( seed_tracks=[t["id"] for t in self._buffer[0: 5]], limit=self.FETCH_SIZE)["tracks"] log_msg("Spotify radio track buffer got %d results back" % len(tracks)) return tracks except Exception: log_exception("SpotifyRadioTrackBuffer", "Failed to fetch recommendations, returning empty result") return []
def __init__(self, storage_id, window_id=10000): self._id = storage_id self._window = xbmcgui.Window(window_id) try: self['__keys__'] except KeyError: self['__keys__'] = []
def get_mem_storage(self, storage_id='', window_id=10000): """ Creates an in-memory storage for this addon with :class:`dict`-like interface The storage can store picklable Python objects as long as Kodi is running and storage contents can be shared between Python processes. Different addons have separate storages, so storages with the same names created with this method do not conflict. Example:: addon = Addon() storage = addon.get_mem_storage() foo = storage['foo'] storage['bar'] = bar :param storage_id: optional storage ID (case-insensitive). :type storage_id: str :param window_id: the ID of a Kodi Window object where storage contents will be stored. :type window_id: int :return: in-memory storage for this addon :rtype: MemStorage """ if storage_id: storage_id = '{0}_{1}'.format(self.id, storage_id) return MemStorage(storage_id, window_id)
def __get_window_instance(cls): """ Returns the current window instance from KODI :returns: xmbcguiWindow -- Window instance """ return xbmcgui.Window(xbmcgui.getCurrentWindowId())
def property(self, name, value=None): if value is None: value = '' xbmcgui.Window(12600).setProperty(name, value)
def move(item): import xbmc, xbmcgui item_focus = item.extra wnd = xbmcgui.Window(xbmcgui.getCurrentWindowId()) id = wnd.getFocusId() return xbmc.executebuiltin('Control.Move('+str(id)+','+item_focus+')')
def __init__(self): '''Initialize our caching class''' self._win = xbmcgui.Window(10000) self._monitor = xbmc.Monitor() self.check_cleanup() self._log_msg("Initialized")
def __init__(self, api_key=None): '''Initialize our Module''' if api_key: self.api_key = api_key self.cache = SimpleCache() self._win = xbmcgui.Window(10000) self._addon = xbmcaddon.Addon(ADDON_ID) addonversion = self._addon.getAddonInfo('version').decode("utf-8") self.cache.global_checksum = addonversion self._log_msg("Initialized")
def __init__(self, *args, **kwargs): self.window = xbmcgui.Window(WINDOW_FULLSCREEN_VIDEO) viewport_w, viewport_h = self._get_skin_resolution() # Adjust size based on viewport, we are using 1080p coordinates self._shown = False self._text = "" self._label = xbmcgui.ControlLabel(int(viewport_w*0.7), int(viewport_h*0.10), int(viewport_w*0.3), int(viewport_h*0.8), self._text,alignment=0)
def set_main_menu_selection(self, type): """Persist the chosen main menu entry in memory Parameters ---------- type : :obj:`str` Selected menu item """ current_window = xbmcgui.getCurrentWindowId() xbmcgui.Window(current_window).setProperty('main_menu_selection', type)
def get_main_menu_selection(self): """Gets the persisted chosen main menu entry from memory Returns ------- :obj:`str` The last chosen main menu entry """ current_window = xbmcgui.getCurrentWindowId() window = xbmcgui.Window(current_window) return window.getProperty('main_menu_selection')
def setup_memcache(self): """Sets up the memory cache if not existant""" current_window = xbmcgui.getCurrentWindowId() window = xbmcgui.Window(current_window) try: cached_items = window.getProperty('memcache') # no cache setup yet, create one if len(cached_items) < 1: window.setProperty('memcache', pickle.dumps({})) except EOFError: pass
def invalidate_memcache(self): """Invalidates the memory cache""" current_window = xbmcgui.getCurrentWindowId() window = xbmcgui.Window(current_window) try: window.setProperty('memcache', pickle.dumps({})) except EOFError: pass
def __init__(self, provider, settings, addon): xbmcprovider.XBMCMultiResolverContentProvider.__init__(self, provider, settings, addon) provider.parent = self sctop.uid = provider.uid self.provider = provider self.win = xbmcgui.Window(10000) self.noImage = os.path.join(self.addon_dir(), 'resources', 'img', 'no-image.png') #self._settings() self.cache = sctop.cache self.provider.cache = self.cache self.timer = 0
def action(self, data): if self.scid is None: return url = "%s/Stats" % (sctop.BASE_URL) data.update({'est': self.estimateFinishTime}) data.update({'se': self.se, 'ep': self.ep}) data.update({'ver': sctop.addonInfo('version')}) try: data.update({'state': bool(xbmc.getCondVisibility("!Player.Paused"))}) data.update({'ws': xbmcgui.Window(10000).getProperty('ws.ident'), 'vip': xbmcgui.Window(10000).getProperty('ws.vip')}) data.update({'vd': xbmcgui.Window(10000).getProperty('ws.days')}) data.update({'skin':xbmc.getSkinDir()}) if 'bitrate' in self.stream: util.debug("[SC] action bitrate") data.update({'bt': self.stream['bitrate']}) else: util.debug("[SC] action no bitrate") except: pass try: if self.itemDuration > 0: data.update({'dur': self.itemDuration}) except Exception: pass self.log("[SC] action: %s" % str(data)) url = self.parent.provider._url(url) sctop.post_json(url, data, {'X-UID': sctop.uid})
def userData(self, all=False): if self.token is not None: headers,req = self._create_request('/',{'wst':self.token}) try: util.info('[SC] userData') data = post(self._url('api/user_data/'), req, headers=headers) except: self.clearToken() return False util.info('[SC] userdata dat: %s' % data) xml = ET.fromstring(data) if not xml.find('status').text == 'OK': self.clearToken() return False if all == True: return xml util.debug("[SC] userInfo: %s %s" % (xml.find('ident').text, xml.find('vip').text)) if xml.find('vip').text == '1': xbmcgui.Window(10000).setProperty('ws.vip', '1') xbmcgui.Window(10000).setProperty('ws.ident', xml.find('ident').text) xbmcgui.Window(10000).setProperty('ws.days', xml.find('vip_days').text) return int(xml.find('vip_days').text) else: xbmcgui.Window(10000).setProperty('ws.vip', '0') return False
def getToken(self): try: if self.cache is None: self.w = xbmcgui.Window(10000) token = self.w.getProperty('ws.token') else: token = self.cache.get('ws.token') if token is not None and token != '': self.token = token else: self.token = None except: util.info('[SC] token ERR %s' % str(traceback.format_exc())) self.token = None
def listMenu(self): """Create menu list (submenu items). [internal]""" icon = os.path.join(common.Paths.imgDir, 'new_search.png') self.addMenuItem('.search.new', menu=False, iconImage=icon, title='[B]%s[/B]' % _('New search')) icon = os.path.join(common.Paths.imgDir, 'search_item.png') for query in self.history: self.addMenuItem('.search.query', iconImage=icon, query=query, title=query) #wnd = xbmcgui.Window(xbmcgui.getCurrentWindowId()) #wnd.getControl(wnd.getFocusId()).selectItem(self._selectItem) xbmcplugin.endOfDirectory(self._addonHandle, cacheToDisc=False) return True
def getConnected(self): return xbmcgui.Window(10000).getProperty("VPN_Manager_Connected_Profile_Name")
def setAPICommand(self, profile): # Set up the API command for the main service to act upon # Shouldn't need to call this directly xbmcgui.Window(10000).setProperty("VPN_Manager_API_Command", profile)
def getCurrent(self): # Compare the current connected VPN to the list of primary VPNs to see if one of the possible # filtered connections is in use. Used by isFiltered, shouldn't be called directly found = -1 current = xbmcgui.Window(10000).getProperty("VPN_Manager_Connected_Profile_Name") if current == "": return found # Adjust 10 below if changing number of conn_max for i in range (0, 10): if not self.primary_vpns[i] == "" and current == self.primary_vpns[i]: found = i+1 return found