Exemplo n.º 1
0
	def post_launch_check(self,game_launch_status=None,**kwargs):
		if game_launch_status and game_launch_status['launch_process'] and not self.settings.get('ext_launchers').get('close_kodi'):
			from subprocess import TimeoutExpired
			dp = xbmcgui.DialogProgress()
			dp.create(loc_str(30377),loc_str(30380))
			dp.update(0,loc_str(30380))
			perc = 0
			finished=False
			check=None
			while not finished:
				try:
					check = game_launch_status['launch_process'].wait(timeout=WAIT_FOR_PROCESS_EXIT)
				except TimeoutExpired:
					perc=perc+10
					dp.update(perc%100,loc_str(30380))
					finished=False
					check=None
				if dp.iscanceled():
					finished=True
					dp.close()
					break
				if isinstance(check,int):
					finished = True
					dp.close()
					break
				if finished:
					dp.close()
					break
			del dp
			if not self.settings.get('ext_launchers').get('close_kodi') and self.settings.get('ext_launchers').get('stop_audio_controller') and self.settings.get('ext_launchers').get('environment') not in ['android','android_ra32','android_aarch64']:
				xbmc.log(msg='IAGL:  Re-Enabling Audio and Controller Input',level=xbmc.LOGDEBUG)
				xbmc.audioResume()
				xbmc.enableNavSounds(True)
				xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Settings.SetSettingValue","params":{"setting":"input.enablejoystick","value":true},"id":"1"}')
Exemplo n.º 2
0
 def __audioSuspend(self):
     if __addon__.getSetting(
             util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
         log.debug("Suspending audio")
         xbmc.executebuiltin("PlayerControl(Stop)")
         xbmc.enableNavSounds(False)
         xbmc.audioSuspend()
Exemplo n.º 3
0
    def test_sound(self, listItem=None):
        try:
            self.oe.dbg_log('sound::test_sound', 'enter_function', 0)

            str_sound_dev = self.oe.read_setting('system', 'snd-dev')
            if str_sound_dev != 'none':
                xbmc.executebuiltin('PlayerControl(Stop)')
                xbmc.audioSuspend()
                xbmc.enableNavSounds(False)
                time.sleep(2)
                snd_card = re.search('card ([\d]+)', str_sound_dev).group(1)
                snd_dev = re.search('device ([\d]+)', str_sound_dev).group(1)
                subprocess.Popen(self.SND_TEST % (int(snd_card), int(snd_dev)),
                                 shell=True,
                                 close_fds=True,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.STDOUT)

                xbmcDialog = xbmcgui.Dialog()
                answer = xbmcDialog.ok('Test Sound', ' ',
                                       'Device: %s' % str_sound_dev)

                self.oe.execute('killall -9 speaker-test', 0)
                time.sleep(1)
                xbmc.audioResume()
                xbmc.enableNavSounds(True)

        except Exception, e:
            self.oe.dbg_log('sound::test_sound', 'ERROR: (' + repr(e) + ')')
    def postExecution(self, toggle_screen_flag):

        # --- Stop Kodi some time ---
        delay_tempo_ms = self.settings['delay_tempo']
        log_verb('postExecution() Pausing {0} ms'.format(delay_tempo_ms))
        xbmc.sleep(delay_tempo_ms)

        # --- Toggle Kodi windowed/fullscreen if requested ---
        if toggle_screen_flag:
            log_verb('postExecution() Toggling Kodi fullscreen')
            kodi_toogle_fullscreen()
        else:
            log_verb('postExecution() Toggling Kodi fullscreen DEACTIVATED in Launcher')

        # --- Resume audio engine if it was suspended ---
        # Calling xmbc.audioResume() takes a loong time (2/4 secs) if audio was not properly suspended!
        # Also produces this in Kodi's log:
        # WARNING: CActiveAE::StateMachine - signal: 0 from port: OutputControlPort not handled for state: 7
        #   ERROR: ActiveAE::Resume - failed to init
        if self.kodi_audio_suspended:
            log_verb('postExecution() Kodi audio engine was suspended before launching')
            log_verb('postExecution() Resuming Kodi audio engine')
            xbmc.audioResume()
            xbmc.enableNavSounds(True)
            xbmc.sleep(100)
        else:
            log_verb('_run_before_execution() DO NOT resume Kodi audio engine')

        # --- Resume joystick engine if it was suspended ---
        if self.kodi_joystick_suspended:
            log_verb('postExecution() Kodi joystick engine was suspended before launching')
            log_verb('postExecution() Resuming Kodi joystick engine')
            # response = xbmc.executeJSONRPC(c_str)
            # log_debug('JSON      ''{0}'''.format(c_str))
            # log_debug('Response  ''{0}'''.format(response))
            log_verb('postExecution() Not supported on Kodi Krypton!')
        else:
            log_verb('postExecution() DO NOT resume Kodi joystick engine')

        # --- Resume Kodi playing if it was paused. If it was stopped, keep it stopped. ---
        media_state_action = self.settings['media_state_action']
        media_state_str = ['Stop', 'Pause', 'Let Play'][media_state_action]
        log_verb('postExecution() media_state_action is "{0}" ({1})'.format(media_state_str, media_state_action))
        log_verb('postExecution() self.kodi_was_playing is {0}'.format(self.kodi_was_playing))
        if self.kodi_was_playing and media_state_action == 1:
            log_verb('postExecution() Calling xbmc.Player().play()')
            xbmc.Player().play()
        log_debug('postExecution() function ENDS')
Exemplo n.º 5
0
	def showDialog(self,score):
		LOG("Show Dialog")
		self.score = str(score)
		self.lblScore.setLabel(str(score))
		while self.username == '':
			self.setUsername(unikeyboard(self.username, "Enter New Player Name"))
			if self.dlgSubmit.username == '':
				self.dlgSubmit.setUsername(self.username)
		self.dlgHighScores.addScore(self.username,str(score))
		self.gameID = self.getGameID(self.gamename)
		self.btnSubmit.setEnabled(True)
		xbmc.enableNavSounds(True)
		self.listen = True
		self.doModal() #leaves xbmcgui locked
		xbmc.enableNavSounds(False)
		LOG("SD7")
		self.dlgHighScores.saveHighScores()
		xbmcgui.unlock()
		LOG("SD8")
		return self.retVal
Exemplo n.º 6
0
def sound(status):
    xbmc.enableNavSounds(status)
Exemplo n.º 7
0
def resumeXbmc():
    if pauseXBMC == "true":
        xbmc.audioResume()
        xbmc.enableNavSounds(True)
Exemplo n.º 8
0
def pauseXbmc():
    if pauseXBMC == "true":
        xbmc.executebuiltin("PlayerControl(Stop)")
        xbmc.audioSuspend()
        xbmc.enableNavSounds(False)
def launchNonXbox(cmd, romCollection, gameRow, settings, precmd, postcmd, roms, gui, listitem):
	Logutil.log("launchEmu on non-xbox", util.LOG_LEVEL_INFO)							
				
	screenModeToggled = False
		
	encoding = 'utf-8'
	#HACK: sys.getfilesystemencoding() is not supported on all systems (e.g. Android)
	try:
		encoding = sys.getfilesystemencoding()
	except:
		pass
		 
	
	#use libretro core to play game
	if(romCollection.useBuiltinEmulator):
		Logutil.log("launching game with internal emulator", util.LOG_LEVEL_INFO)
		rom = roms[0]
		gameclient = romCollection.gameclient
		#HACK: use alternateGameCmd as gameclient
		if(gameRow[util.GAME_alternateGameCmd] != None and gameRow[util.GAME_alternateGameCmd] != ""):
			gameclient = str(gameRow[util.GAME_alternateGameCmd])
		Logutil.log("Preferred gameclient: " +gameclient, util.LOG_LEVEL_INFO)
		Logutil.log("Setting platform: " +romCollection.name, util.LOG_LEVEL_INFO)
		
		if(listitem == None):
			listitem = xbmcgui.ListItem(rom, "0", "", "")
		
		parameters = { "platform": romCollection.name }
		if(gameclient != ""):
			parameters["gameclient"] = gameclient
		listitem.setInfo( type="game", infoLabels=parameters)
		Logutil.log("launching rom: " +rom, util.LOG_LEVEL_INFO)		
		gui.player.play(rom, listitem)
		#xbmc.executebuiltin('PlayMedia(\"%s\", platform=%s, gameclient=%s)' %(rom, romCollection.name, romCollection.gameclient))
		return
	
	if (not romCollection.useEmuSolo):
		#screenMode = xbmc.executehttpapi("GetSystemInfoByName(system.screenmode)").replace("<li>","")
		screenMode = xbmc.getInfoLabel("System.Screenmode")
		Logutil.log("screenMode: " +screenMode, util.LOG_LEVEL_INFO)
		isFullScreen = screenMode.endswith("Full Screen")
		
		toggleScreenMode = settings.getSetting(util.SETTING_RCB_TOGGLESCREENMODE).upper() == 'TRUE'
		
		if(isFullScreen and toggleScreenMode):
			Logutil.log("Toggle to Windowed mode", util.LOG_LEVEL_INFO)
			#this minimizes xbmc some apps seems to need it
			try:
				xbmc.executehttpapi("Action(199)")
			except:
				xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}')
			
			screenModeToggled = True
		
	Logutil.log("launch emu", util.LOG_LEVEL_INFO)
	
	#pre launch command
	if(precmd.strip() != '' and precmd.strip() != 'call'):
		Logutil.log("Got to PRE", util.LOG_LEVEL_INFO)
		os.system(precmd.encode(encoding))
	
	preDelay = settings.getSetting(SETTING_RCB_PRELAUNCHDELAY)
	if(preDelay != ''):
		preDelay = int(float(preDelay))
		xbmc.sleep(preDelay)
	
	#change working directory
	path = os.path.dirname(romCollection.emulatorCmd)
	if(os.path.isdir(path)):
		try:
			os.chdir(path)
		except:
			pass
	
		
	#pause audio
	suspendAudio = settings.getSetting(util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE'
	if(suspendAudio):
		xbmc.executebuiltin("PlayerControl(Stop)")
		xbmc.enableNavSounds(False)
		xbmc.audioSuspend()
	
	if(romCollection.usePopen):
		import subprocess
		process = subprocess.Popen(cmd.encode(encoding), shell=True)
		process.wait()
	else:
		try:
			os.system(cmd.encode(encoding))
		except:
			os.system(cmd.encode('utf-8'))
	
	Logutil.log("launch emu done", util.LOG_LEVEL_INFO)		
	
	postDelay = settings.getSetting(SETTING_RCB_POSTLAUNCHDELAY)
	if(postDelay != ''):
		postDelay = int(float(postDelay))
		xbmc.sleep(postDelay)
	
	#resume audio
	if(suspendAudio):
		xbmc.audioResume()
		xbmc.enableNavSounds(True)
	
	#post launch command
	if(postcmd.strip() != '' and postcmd.strip() != 'call'):
		Logutil.log("Got to POST: " + postcmd.strip(), util.LOG_LEVEL_INFO)
		os.system(postcmd.encode(encoding))
	
	if(screenModeToggled):
		Logutil.log("Toggle to Full Screen mode", util.LOG_LEVEL_INFO)
		#this brings xbmc back
		try:
			xbmc.executehttpapi("Action(199)")
		except:
			xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}')
Exemplo n.º 10
0
	def play_music(self, media):
		xbmc.enableNavSounds(False)
		self.PLAYER.play(media)
		xbmc.sleep(100)
		xbmc.enableNavSounds(True)
		self.delay = 2000
Exemplo n.º 11
0
    def showImageQueue(self, image_queue):
        image_queue.reset()
        image = image_queue.next()

        start = time.time()
        end = time.time() + image_queue.duration
        musicEnd = [end - image_queue.musicFadeOut]

        info = self.ImageQueueInfo(image_queue, musicEnd)

        self.window.initialize()
        self.window.setTransition('none')

        xbmc.enableNavSounds(False)

        self.playMusic(image_queue)

        if xbmc.getCondVisibility('Window.IsVisible(visualisation)'):
            DEBUG_LOG('Closing visualisation window')
            xbmc.executebuiltin('Action(back)')

        self.window.setTransition(image_queue.transition,
                                  image_queue.transitionDuration)

        action = None

        try:
            while image:
                DEBUG_LOG(' -IMAGE.QUEUE: {0}'.format(image))

                action = self.showImageFromQueue(image, info, first=True)

                if action:
                    if action == 'NEXT':
                        image = image_queue.next(extend=True) or image
                        continue
                    elif action == 'PREV':
                        image = image_queue.prev() or image
                        continue
                    elif action == 'BIG_NEXT':
                        self.window.setSkipNotice('+3')
                        image = image_queue.next(count=3, extend=True) or image
                        continue
                    elif action == 'BIG_PREV':
                        self.window.setSkipNotice('-3')
                        image = image_queue.prev(count=3) or image
                        continue
                    elif action == 'BACK':
                        DEBUG_LOG(
                            ' -IMAGE.QUEUE: Skipped after {0}secs'.format(
                                int(time.time() - start)))
                        return False
                    elif action == 'SKIP':
                        DEBUG_LOG(
                            ' -IMAGE.QUEUE: Skipped after {0}secs'.format(
                                int(time.time() - start)))
                        return True
                    else:
                        if action is True:
                            image_queue.mark(image)

                        image = image_queue.next(start)
                else:
                    return
        finally:
            kodiutil.setGlobalProperty('paused', '')
            xbmc.enableNavSounds(True)
            self.stopMusic(action != 'BACK' and image_queue or None)
            if self.window.hasAction():
                if self.window.getAction() == 'BACK':
                    return False
            self.window.clear()

        DEBUG_LOG(' -IMAGE.QUEUE: Finished after {0}secs'.format(
            int(time.time() - start)))
        return True
Exemplo n.º 12
0
def launchNonXbox(cmd, romCollection, gameRow, settings, precmd, postcmd, roms,
                  gui, listitem):
    Logutil.log("launchEmu on non-xbox", util.LOG_LEVEL_INFO)

    screenModeToggled = False

    encoding = 'utf-8'
    #HACK: sys.getfilesystemencoding() is not supported on all systems (e.g. Android)
    try:
        encoding = sys.getfilesystemencoding()
    except:
        pass

    #use libretro core to play game
    if (romCollection.useBuiltinEmulator):
        Logutil.log("launching game with internal emulator",
                    util.LOG_LEVEL_INFO)
        rom = roms[0]
        gameclient = romCollection.gameclient
        #HACK: use alternateGameCmd as gameclient
        if (gameRow[util.GAME_alternateGameCmd] != None
                and gameRow[util.GAME_alternateGameCmd] != ""):
            gameclient = str(gameRow[util.GAME_alternateGameCmd])
        Logutil.log("Preferred gameclient: " + gameclient, util.LOG_LEVEL_INFO)
        Logutil.log("Setting platform: " + romCollection.name,
                    util.LOG_LEVEL_INFO)

        if (listitem == None):
            listitem = xbmcgui.ListItem(rom, "0", "", "")

        parameters = {"platform": romCollection.name}
        if (gameclient != ""):
            parameters["gameclient"] = gameclient
        listitem.setInfo(type="game", infoLabels=parameters)
        Logutil.log("launching rom: " + rom, util.LOG_LEVEL_INFO)
        gui.player.play(rom, listitem)
        #xbmc.executebuiltin('PlayMedia(\"%s\", platform=%s, gameclient=%s)' %(rom, romCollection.name, romCollection.gameclient))
        return

    if (not romCollection.useEmuSolo):
        #screenMode = xbmc.executehttpapi("GetSystemInfoByName(system.screenmode)").replace("<li>","")
        screenMode = xbmc.getInfoLabel("System.Screenmode")
        Logutil.log("screenMode: " + screenMode, util.LOG_LEVEL_INFO)
        isFullScreen = screenMode.endswith("Full Screen")

        toggleScreenMode = settings.getSetting(
            util.SETTING_RCB_TOGGLESCREENMODE).upper() == 'TRUE'

        if (isFullScreen and toggleScreenMode):
            Logutil.log("Toggle to Windowed mode", util.LOG_LEVEL_INFO)
            #this minimizes xbmc some apps seems to need it
            try:
                xbmc.executehttpapi("Action(199)")
            except:
                xbmc.executeJSONRPC(
                    '{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}'
                )

            screenModeToggled = True

    Logutil.log("launch emu", util.LOG_LEVEL_INFO)

    #pre launch command
    if (precmd.strip() != '' and precmd.strip() != 'call'):
        Logutil.log("Got to PRE", util.LOG_LEVEL_INFO)
        os.system(precmd.encode(encoding))

    preDelay = settings.getSetting(SETTING_RCB_PRELAUNCHDELAY)
    if (preDelay != ''):
        preDelay = int(float(preDelay))
        xbmc.sleep(preDelay)

    #change working directory
    path = os.path.dirname(romCollection.emulatorCmd)
    if (os.path.isdir(path)):
        try:
            os.chdir(path)
        except:
            pass

    #pause audio
    suspendAudio = settings.getSetting(
        util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE'
    if (suspendAudio):
        xbmc.executebuiltin("PlayerControl(Stop)")
        xbmc.enableNavSounds(False)
        xbmc.audioSuspend()

    if (romCollection.usePopen):
        import subprocess
        process = subprocess.Popen(cmd.encode(encoding), shell=True)
        process.wait()
    else:
        try:
            os.system(cmd.encode(encoding))
        except:
            os.system(cmd.encode('utf-8'))

    Logutil.log("launch emu done", util.LOG_LEVEL_INFO)

    postDelay = settings.getSetting(SETTING_RCB_POSTLAUNCHDELAY)
    if (postDelay != ''):
        postDelay = int(float(postDelay))
        xbmc.sleep(postDelay)

    #resume audio
    if (suspendAudio):
        xbmc.audioResume()
        xbmc.enableNavSounds(True)

    #post launch command
    if (postcmd.strip() != '' and postcmd.strip() != 'call'):
        Logutil.log("Got to POST: " + postcmd.strip(), util.LOG_LEVEL_INFO)
        os.system(postcmd.encode(encoding))

    if (screenModeToggled):
        Logutil.log("Toggle to Full Screen mode", util.LOG_LEVEL_INFO)
        #this brings xbmc back
        try:
            xbmc.executehttpapi("Action(199)")
        except:
            xbmc.executeJSONRPC(
                '{"jsonrpc":"2.0","method":"Input.ExecuteAction","params":{"action":"togglefullscreen"},"id":"1"}'
            )
    def preExecution(self, title, toggle_screen_flag):
        
        # --- User notification ---
        if self.settings['display_launcher_notify']:
            kodi_notify('Launching {0}'.format(title))

        # --- Stop/Pause Kodi mediaplayer if requested in settings ---
        self.kodi_was_playing = False
        # id="media_state_action" default="0" values="Stop|Pause|Let Play"
        media_state_action = self.settings['media_state_action']
        media_state_str = ['Stop', 'Pause', 'Let Play'][media_state_action]
        log_verb('_run_before_execution() media_state_action is "{0}" ({1})'.format(media_state_str, media_state_action))
        if media_state_action == 0 and xbmc.Player().isPlaying():
            log_verb('_run_before_execution() Calling xbmc.Player().stop()')
            xbmc.Player().stop()
            xbmc.sleep(100)
            self.kodi_was_playing = True
        elif media_state_action == 1 and xbmc.Player().isPlaying():
            log_verb('_run_before_execution() Calling xbmc.Player().pause()')
            xbmc.Player().pause()
            xbmc.sleep(100)
            self.kodi_was_playing = True

        # --- Force audio suspend if requested in "Settings" --> "Advanced"
        # >> See http://forum.kodi.tv/showthread.php?tid=164522
        self.kodi_audio_suspended = False
        if self.settings['suspend_audio_engine']:
            log_verb('_run_before_execution() Suspending Kodi audio engine')
            xbmc.audioSuspend()
            xbmc.enableNavSounds(False)
            xbmc.sleep(100)
            self.kodi_audio_suspended = True
        else:
            log_verb('_run_before_execution() DO NOT suspend Kodi audio engine')

        # --- Force joystick suspend if requested in "Settings" --> "Advanced"
        # >> See https://forum.kodi.tv/showthread.php?tid=287826&pid=2627128#pid2627128
        # >> See https://forum.kodi.tv/showthread.php?tid=157499&pid=1722549&highlight=input.enablejoystick#pid1722549
        # >> See https://forum.kodi.tv/showthread.php?tid=313615
        self.kodi_joystick_suspended = False
        # if self.settings['suspend_joystick_engine']:
            # log_verb('_run_before_execution() Suspending Kodi joystick engine')
            # >> Research. Get the value of the setting first
            # >> Apparently input.enablejoystick is not supported on Kodi Krypton anymore.
            # c_str = ('{"id" : 1, "jsonrpc" : "2.0",'
            #          ' "method" : "Settings.GetSettingValue",'
            #          ' "params" : {"setting":"input.enablejoystick"}}')
            # response = xbmc.executeJSONRPC(c_str)
            # log_debug('JSON      ''{0}'''.format(c_str))
            # log_debug('Response  ''{0}'''.format(response))

            # c_str = ('{"id" : 1, "jsonrpc" : "2.0",'
            #          ' "method" : "Settings.SetSettingValue",'
            #          ' "params" : {"setting" : "input.enablejoystick", "value" : false} }')
            # response = xbmc.executeJSONRPC(c_str)
            # log_debug('JSON      ''{0}'''.format(c_str))
            # log_debug('Response  ''{0}'''.format(response))
            # self.kodi_joystick_suspended = True

            # log_error('_run_before_execution() Suspending Kodi joystick engine not supported on Kodi Krypton!')
        # else:
            # log_verb('_run_before_execution() DO NOT suspend Kodi joystick engine')

        # --- Toggle Kodi windowed/fullscreen if requested ---
        if toggle_screen_flag:
            log_verb('_run_before_execution() Toggling Kodi fullscreen')
            kodi_toogle_fullscreen()
        else:
            log_verb('_run_before_execution() Toggling Kodi fullscreen DEACTIVATED in Launcher')

        # --- Pause Kodi execution some time ---
        delay_tempo_ms = self.settings['delay_tempo']
        log_verb('_run_before_execution() Pausing {0} ms'.format(delay_tempo_ms))
        xbmc.sleep(delay_tempo_ms)
        log_debug('_run_before_execution() function ENDS')
Exemplo n.º 14
0
def sound(status):
    xbmc.enableNavSounds(status)
Exemplo n.º 15
0
			up.makeBackup()
			up.issueUpdate(version)
			view.close()
			return True
		elif async: 
			xbmcgui.Dialog().ok( self.script, _( 99 ) % (self.version) ) #not be asked again
			view.state = STATE_READY
			lock.release()
	elif not async:
		xbmcgui.Dialog().ok( _(0), _( 95 ) ) # up to date
	return False
			
if __name__ == '__main__':
    try:
		#sys.stderr = open(ROOT_DIR+"err.txt",'w')
		xbmc.enableNavSounds(False)
		lock = threading.Lock()
		random.seed(time.time())
		board = Board(10,20)
		controller = BoardController(board)
		t = Tetris()
		t.loadSettings()
		t.setController(controller)
		t.startTimer()
		t.doModal()
		t.stopTimer()
		t.saveSettings()
		del t,controller,board
		xbmc.enableNavSounds(True)
    except:
        traceback.print_exc()
Exemplo n.º 16
0
		def launch(self,launch_files=None,**kwargs):
			import subprocess
			netplay_command = False #Hard code for now, add context menu and windowxml button to launch with netplay
			capture_launch_log = True #Hard code for now, to add as an advanced setting
			current_output = list()
			if capture_launch_log:
				from queue import Queue, Empty
				from threading import Thread
			if launch_files and launch_files.get('post_process_launch_file') and launch_files.get('ext_launch_cmd') and launch_files.get('ext_launch_cmd')!='none':
				self.current_command = launch_files.get('ext_launch_cmd').replace('%ROM_PATH%',str(launch_files.get('post_process_launch_file')))

				if netplay_command: #To be implemented soon
					xbmc.log(msg='IAGL:  Launch game with netplay requested',level=xbmc.LOGDEBUG)
				else:
					xbmc.log(msg='IAGL:  Launch game without netplay requested',level=xbmc.LOGDEBUG)
					self.current_command = self.current_command.replace(' %NETPLAY_COMMAND%','')

				if any([x in self.current_command for x in ['%ADDON_DIR%','%APP_PATH_RA%','%APP_PATH_DEMUL%','%APP_PATH_DOLPHIN%','%APP_PATH_EPSXE%','%APP_PATH_FS_UAE%','%APP_PATH_MAME%','%APP_PATH_PJ64%','%CFG_PATH%','%RETROARCH_CORE_DIR%','%ROM_PATH%','%ROM_RAW%']]):
					command_map = {'%ADDON_DIR%':self.directory.get('addon').get('path'),
									'%APP_PATH_RA%':get_launch_parameter(self.settings.get('ext_launchers').get('ra').get('app_path'),'%APP_PATH_RA%'),
									'%APP_PATH_DEMUL%':next(iter([str(x.get('app_path')) for x in self.settings.get('ext_launchers').get('other_ext_cmds') if x.get('app_path_cmd_replace')=='%APP_PATH_DEMUL%']),'%APP_PATH_DEMUL%'),
									'%APP_PATH_DOLPHIN%':next(iter([str(x.get('app_path')) for x in self.settings.get('ext_launchers').get('other_ext_cmds') if x.get('app_path_cmd_replace')=='%APP_PATH_DOLPHIN%']),'%APP_PATH_DOLPHIN%'),
									'%APP_PATH_EPSXE%':next(iter([str(x.get('app_path')) for x in self.settings.get('ext_launchers').get('other_ext_cmds') if x.get('app_path_cmd_replace')=='%APP_PATH_EPSXE%']),'%APP_PATH_EPSXE%'),
									'%APP_PATH_FS_UAE%':next(iter([str(x.get('app_path')) for x in self.settings.get('ext_launchers').get('other_ext_cmds') if x.get('app_path_cmd_replace')=='%APP_PATH_FS_UAE%']),'%APP_PATH_FS_UAE%'),
									'%APP_PATH_MAME%':next(iter([str(x.get('app_path')) for x in self.settings.get('ext_launchers').get('other_ext_cmds') if x.get('app_path_cmd_replace')=='%APP_PATH_MAME%']),'%APP_PATH_MAME%'),
									'%APP_PATH_PJ64%':next(iter([str(x.get('app_path')) for x in self.settings.get('ext_launchers').get('other_ext_cmds') if x.get('app_path_cmd_replace')=='%APP_PATH_PJ64%']),'%APP_PATH_PJ64%'),
									'%CFG_PATH%':get_launch_parameter(self.settings.get('ext_launchers').get('ra').get('cfg_path'),'%CFG_PATH%'),
									'%ROM_PATH%':str(launch_files.get('post_process_launch_file')),
									'%ROM_FILENAME%':os.path.split(str(launch_files.get('post_process_launch_file')))[-1],
									'%ROM_BASE_PATH%':os.path.split(str(launch_files.get('post_process_launch_file')))[0]}
					for k,v in command_map.items():
						self.current_command = self.current_command.replace(k,v)
					if '%RETROARCH_CORE_DIR%' in self.current_command: #Check this seperately because polling the RA config takes time, and it's rarely used
						ra_cfg = get_ra_libretro_config(self.settings.get('ext_launchers').get('ra').get('cfg_path'),self.settings.get('ext_launchers').get('ra').get('app_path'))
						self.current_command = self.current_command.replace('%RETROARCH_CORE_DIR%',ra_cfg.get('libretro_directory'))		

				if xbmc.Player().isPlaying():
					xbmc.Player().stop()
					xbmc.sleep(500) #If sleep is not called, Kodi will crash - does not like playing video and then swiching to a game
					
				if not any([x in self.current_command for x in ['%ADDON_DIR%','%APP_PATH_RA%','%APP_PATH_DEMUL%','%APP_PATH_DOLPHIN%','%APP_PATH_EPSXE%','%APP_PATH_FS_UAE%','%APP_PATH_MAME%','%APP_PATH_PJ64%','%CFG_PATH%','%NETPLAY_COMMAND%','%RETROARCH_CORE_DIR%','%ROM_PATH%','%ROM_RAW%']]):
					if not self.settings.get('ext_launchers').get('close_kodi') and self.settings.get('ext_launchers').get('stop_audio_controller') and self.settings.get('ext_launchers').get('environment') not in ['android','android_ra32','android_aarch64']:
						xbmc.log(msg='IAGL:  Disabling Audio and Controller Input',level=xbmc.LOGDEBUG)
						xbmc.audioSuspend()
						xbmc.enableNavSounds(False)
						xbmc.executeJSONRPC('{"jsonrpc":"2.0","method":"Settings.SetSettingValue","params":{"setting":"input.enablejoystick","value":false},"id":"1"}')
					
					if self.settings.get('ext_launchers').get('environment') in ['android','android_ra32','android_aarch64'] and self.settings.get('ext_launchers').get('send_stop_command'):
						android_stop_commands = dict(zip(['android','android_ra32','android_aarch64'],['/system/bin/am force-stop com.retroarch','/system/bin/am force-stop com.retroarch','/system/bin/am force-stop com.retroarch.ra32','/system/bin/am force-stop com.retroarch.aarch64']))
						xbmc.log(msg='IAGL:  Sending Android Stop Command: %(android_stop_command)s' % {'android_stop_command': android_stop_commands.get(self.settings.get('ext_launchers').get('environment'))}, level=xbmc.LOGDEBUG)
						stop_process=subprocess.call(android_stop_commands.get(self.settings.get('ext_launchers').get('environment')),stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=True)
						xbmc.log(msg='IAGL:  Android returned %(stop_process)s' % {'stop_process': stop_process}, level=xbmc.LOGDEBUG)

					launch_process=subprocess.Popen(self.current_command,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=True)
					if not self.settings.get('ext_launchers').get('close_kodi') and capture_launch_log:
						q = Queue()
						t = Thread(target=enqueue_output, args=(launch_process.stdout, q))
						t.daemon = True # thread dies with the program
						t.start()
					
					if not self.settings.get('ext_launchers').get('close_kodi') and capture_launch_log:
						xbmc.sleep(WAIT_FOR_PLAYER_TIME)
						while True:
							try:
								current_line = q.get_nowait()
							except:
								current_line = None
							if current_line and len(current_output)<500: #Read up to first 500 lines of output if available
								current_output.append(current_line.decode('utf-8').replace('\n','').replace('\r',''))
							else:
								break
					if launch_process.poll() is None or (current_output and any(['starting: intent' in x.lower() for x in current_output]) and not any(['error: activity' in x.lower() for x in current_output])):
						self.launch_status['launch_process_success'] = True
						self.launch_status['launch_process_message'] = 'Sent launch command for %(game)s'%{'game':self.game.get('info').get('originaltitle')}
						self.launch_status['launch_process'] = launch_process
						self.launch_status['launch_log'] = current_output
						xbmc.log(msg='IAGL:  Sent external launch command for game %(game)s'%{'game':self.game.get('info').get('originaltitle')},level=xbmc.LOGINFO)
						xbmc.log(msg='IAGL:  %(command)s'%{'command':self.current_command},level=xbmc.LOGINFO)
						if capture_launch_log and current_output:
							xbmc.log(msg='IAGL:  External launch log for %(game)s'%{'game':self.game.get('info').get('originaltitle')},level=xbmc.LOGDEBUG)
							for co in current_output:
								xbmc.log(msg='IAGL:  %(log)s'%{'log':co},level=xbmc.LOGDEBUG)
					else:
						self.launch_status['launch_process_success'] = False
						self.launch_status['launch_process_message'] = 'Sent launch command for %(game)s but it is not running'%{'game':self.game.get('info').get('originaltitle')}
						self.launch_status['launch_process'] = None
						self.launch_status['launch_log'] = current_output
						xbmc.log(msg='IAGL:  Sent external launch command for game %(game)s but it does not appear to be running'%{'game':self.game.get('info').get('originaltitle')},level=xbmc.LOGERROR)
						xbmc.log(msg='IAGL:  %(command)s'%{'command':self.current_command},level=xbmc.LOGERROR)
						if capture_launch_log and current_output:
							xbmc.log(msg='IAGL:  External launch for %(game)s'%{'game':self.game.get('info').get('originaltitle')},level=xbmc.LOGDEBUG)
							for co in current_output:
								xbmc.log(msg='IAGL:  %(log)s'%{'log':co},level=xbmc.LOGDEBUG)
				else:
					self.launch_status['launch_process_success'] = False
					self.launch_status['launch_process_message'] = 'Launch command malformed for %(game)s'%{'game':self.game.get('info').get('originaltitle')}
					self.launch_status['launch_process'] = None
					self.launch_status['launch_log'] = None
					xbmc.log(msg='IAGL:  The external launch command for game %(game)s is not well formed'%{'game':self.game.get('info').get('originaltitle')},level=xbmc.LOGERROR)
					xbmc.log(msg='IAGL:  %(command)s'%{'command':self.current_command},level=xbmc.LOGERROR)
			else:
				xbmc.log(msg='IAGL:  Badly formed external launch command %(cmd)s'%{'cmd':self.current_command},level=xbmc.LOGERROR)
				return None
			return self.launch_status
Exemplo n.º 17
0
	def __audioResume(self):
		if __addon__.getSetting(util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
			log.debug("Resuming audio")
			xbmc.audioResume()
			xbmc.enableNavSounds(True)
Exemplo n.º 18
0
	def __audioSuspend(self):
		if __addon__.getSetting(util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
			log.debug("Suspending audio")
			xbmc.executebuiltin("PlayerControl(Stop)")
			xbmc.enableNavSounds(False)
			xbmc.audioSuspend()
Exemplo n.º 19
0

def play():
    if isPlaybackPaused(): xbmc.Player().pause()  #trigger


def pause():
    if not isPlaybackPaused(): xbmc.Player().pause()  #trigger


#	xbmcgui.Dialog().ok(addonname, str(isPlaybackPaused()))
#	xbmcgui.Dialog().ok(addonname, str(isMuted()))

# Main execution
if len(sys.argv) == 2:
    xbmc.enableNavSounds(True)

    if sys.argv[1] != "MESSAGE":
        if "/cms/cached/voice/" in sys.argv[1]:
            if tts_stop == "true": xbmc.stopSFX()
            if media_unpause == "true": play()
            if tts_notification == "true":
                xbmc.executebuiltin(
                    'XBMC.Notification(TTS arrived, trying to say it..., ' +
                    notification_time + ')')
            xbmc.playSFX(sys.argv[1], False)
        elif sys.argv[1] == "ping":
            pass
        elif sys.argv[1] == "ringtone":
            if media_unpause == "true": play()
            if tts_notification == "true":
Exemplo n.º 20
0
    def _run_rom(self, launcherID, romName):
        if (self.launchers.has_key(launcherID)):
            launcher = self.launchers[launcherID]
            if (launcher["roms"].has_key(romName)):
                rom = self.launchers[launcherID]["roms"][romName]
                romfile = os.path.basename(rom["filename"])
                if ( rom["altapp"] != "" ):
                    application = rom["altapp"]
                else:
                    application = launcher["application"]
                apppath = os.path.dirname(application)
                rompath = os.path.dirname(rom["filename"])
                romname = os.path.splitext(romfile)[0]
    
                if ( os.path.exists(apppath) ) :
                    if ( os.path.exists(rom["filename"]) ) :
                        files = []
                        filesnames = []
                        ext3s = ['.cd1', '-cd1', '_cd1', ' cd1']
                        for ext3 in ext3s:
                            cleanromname = re.sub('(\[.*?\]|\{.*?\}|\(.*?\))', '', romname)
                            if ( cleanromname.lower().find(ext3) > -1 ):
                                temprompath = os.path.dirname(rom["filename"])
                                try:
                                    filesnames = os.listdir(temprompath)
                                except:
                                    notification(addonName + " - " + addonString(30612).encode('utf-8'),addonString(30610).encode('utf-8'),"",3000)
                                namestem = cleanromname[:-len(ext3)]

                                for filesname in filesnames:
                                    altname=re.findall('\{.*?\}',filesname)
                                    searchname = re.sub('(\[.*?\]|\{.*?\}|\(.*?\))', '', filesname)
                                    if searchname[0:len(namestem)] == namestem and searchname[len(namestem):len(namestem)+len(ext3) - 1]  == ext3[:-1]:
                                        for romext in launcher["romext"].split("|"):
                                            if searchname[-len(romext):].lower() == romext.lower() :
                                                Discnum = searchname[(len(namestem)+len(ext3)-1):searchname.rfind(".")]
                                                try:
                                                    int(Discnum)
                                                    if not altname:
                                                        files.append([Discnum, xbmc.getLocalizedString(427)+" "+Discnum, os.path.join(os.path.dirname(rom["filename"]),filesname)])
                                                    else:
                                                        files.append([Discnum, altname[0][1:-1], os.path.join(os.path.dirname(rom["filename"]),filesname)])
                                                except:
                                                    pass
                                if len(files) > 0:
                                    files.sort(key=lambda x: int(x[0]))
                                    discs = []
                                    for file in files:
                                        discs.append(file[1])
                                    dialog = xbmcgui.Dialog()
                                    type3 = dialog.select("%s:" % addonString_servicefeatherence(32423).encode('utf-8'), discs)
                                    if type3 > -1 :
                                        myresult = files[type3]
                                        rom["filename"] = myresult[2]
                                        romfile = os.path.basename(rom["filename"])
                                        rompath = os.path.dirname(rom["filename"])
                                        romname = os.path.splitext(romfile)[0]
                                    else:
                                        return ""

                        if ( rom["altarg"] != "" ):
                            arguments = rom["altarg"]
                        else:
                            arguments = launcher["args"]
                        arguments = arguments.replace("%rom%" , rom["filename"]).replace("%ROM%" , rom["filename"])
                        arguments = arguments.replace("%romfile%" , romfile).replace("%ROMFILE%" , romfile)
                        arguments = arguments.replace("%romname%" , romname).replace("%ROMNAME%" , romname)
                        arguments = arguments.replace("%rombasename%" , base_filename(romname)).replace("%ROMBASENAME%" , base_filename(romname))
                        arguments = arguments.replace("%apppath%" , apppath).replace("%APPPATH%" , apppath)
                        arguments = arguments.replace("%rompath%" , rompath).replace("%ROMPATH%" , rompath)
                        arguments = arguments.replace("%romtitle%" , rom["name"]).replace("%ROMTITLE%" , rom["name"])
                        arguments = arguments.replace("%romspath%" , launcher["rompath"]).replace("%ROMSPATH%" , launcher["rompath"])

                        if ( os.path.basename(application).lower().replace(".exe" , "") == "xbmc" ):
                            xbmc.executebuiltin('XBMC.' + arguments)
                        else:
                            if ( xbmc.Player().isPlaying() ) or 1 + 1 == 2:
								xbmc.Player().stop()
								xbmc.sleep(self.settings[ "start_tempo" ]+100)
								try:
									xbmc.audioSuspend()
								except:
								    pass
                            if (launcher["minimize"] == "true"):
                                _toogle_fullscreen()
                            try:
                                xbmc.enableNavSounds(False)                                 
                            except:
                                pass
                            xbmc.sleep(self.settings[ "start_tempo" ])
                            if (os.environ.get( "OS", "xbox" ) == "xbox"):
                                f=open(SHORTCUT_FILE, "wb")
                                f.write("<shortcut>\n")
                                f.write("    <path>" + application + "</path>\n")
                                f.write("    <custom>\n")
                                f.write("       <game>" + rom["filename"] + "</game>\n")
                                f.write("    </custom>\n")
                                f.write("</shortcut>\n")
                                f.close()
                                xbmc.executebuiltin('XBMC.Runxbe(' + SHORTCUT_FILE + ')')
                            else:
                                if (sys.platform == 'win32'):
                                    if ( launcher["lnk"] == "true" ) and ( launcher["romext"] == "lnk" ):
                                        os.system("start \"\" \"%s\"" % (arguments))
                                    else:
                                        if ( application.split(".")[-1] == "bat" ):
                                            info = subprocess_hack.STARTUPINFO()
                                            info.dwFlags = 1
                                            info.wShowWindow = 0
                                        else:
                                            info = None
                                        startproc = subprocess_hack.Popen(r'%s %s' % (application, arguments), cwd=apppath, startupinfo=info)
                                        startproc.wait()
                                elif (sys.platform.startswith('linux')):
                                    if ( self.settings[ "lirc_state" ] ):
                                        xbmc.executebuiltin('LIRC.stop')
                                    os.system("\"%s\" %s " % (application, arguments))
                                    if ( self.settings[ "lirc_state" ] ):
                                        xbmc.executebuiltin('LIRC.start')
                                elif (sys.platform.startswith('darwin')):
                                    os.system("\"%s\" %s " % (application, arguments))
                                else:
                                    notification(addonName + " - " + addonString(30612).encode('utf-8'),addonString(30609).encode('utf-8'),"",3000)
                            xbmc.sleep(self.settings[ "start_tempo" ])
                            try:
                                xbmc.enableNavSounds(True)                            
                            except:
                                pass
                            if (launcher["minimize"] == "true"):
                                _toogle_fullscreen()
                            try:
								xbmc.audioResume()
                            except:
								pass
                    else:
                        notification(addonString(30611).encode('utf-8') % os.path.basename(rom["filename"]),'You should download the game first!','',3000)
                else:
                    notification(addonName + " - " + addonString(30612).encode('utf-8'),addonString(30611).encode('utf-8') % os.path.basename(launcher["application"]),"",3000)
Exemplo n.º 21
0
 def __audioResume(self):
     if __addon__.getSetting(
             util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
         log.debug("Resuming audio")
         xbmc.audioResume()
         xbmc.enableNavSounds(True)
Exemplo n.º 22
0
def pauseXbmc():
  xbmc.executebuiltin("PlayerControl(Stop)")
  xbmc.audioSuspend()
  xbmc.enableNavSounds(False)  
  time.sleep(1)
Exemplo n.º 23
0
import xbmc
#####	Start markings for the log file.
print "| dis-enable_navsounds.py loaded."
if xbmc.getCondVisibility( 'Skin.HasSetting(DisabledSounds)' ):
	xbmc.enableNavSounds(0)
else:
	xbmc.enableNavSounds(1)
Exemplo n.º 24
0
def resumeXbmc():
  xbmc.audioResume()
  xbmc.enableNavSounds(True)
Exemplo n.º 25
0
    def _run_launcher(self, launcherID):
        if (self.launchers.has_key(launcherID)):
            launcher = self.launchers[launcherID]
            apppath = os.path.dirname(launcher["application"])
            if ( os.path.basename(launcher["application"]).lower().replace(".exe" , "") == "xbmc" ) or ("xbmc-fav-" in launcher["application"]) or ("xbmc-sea-" in launcher["application"]):
                xbmc.executebuiltin('XBMC.%s' % launcher["args"])
            else:
                if ( os.path.exists(apppath) ) :
                    arguments = launcher["args"].replace("%apppath%" , apppath).replace("%APPPATH%" , apppath)
                    if xbmc.Player().isPlaying() or 1 + 1 == 2:
						xbmc.Player().stop()
						xbmc.sleep(self.settings[ "start_tempo" ]+100)
						try:
							xbmc.audioSuspend()
						except:
							pass
                    if (launcher["minimize"] == "true"):
                        _toogle_fullscreen()
                    try:
                        xbmc.enableNavSounds(False)                                 
                    except:
                        pass
                    xbmc.sleep(self.settings[ "start_tempo" ])
                    if (os.environ.get( "OS", "xbox" ) == "xbox"):
                        xbmc.executebuiltin('XBMC.Runxbe(' + launcher["application"] + ')')
                    else:
                        if (sys.platform == 'win32'):
                            if ( launcher["application"].split(".")[-1] == "lnk" ):
                                os.system("start \"\" \"%s\"" % (launcher["application"]))
                            else:
                                if ( launcher["application"].split(".")[-1] == "bat" ):
                                    info = subprocess_hack.STARTUPINFO()
                                    info.dwFlags = 1
                                    info.wShowWindow = 0
                                else:
                                    info = None
                                startproc = subprocess_hack.Popen(r'%s %s' % (launcher["application"], arguments), cwd=apppath, startupinfo=info)
                                startproc.wait()
                        elif (sys.platform.startswith('linux')):
                            if ( self.settings[ "lirc_state" ] ):
                                xbmc.executebuiltin('LIRC.stop')
                            os.system("\"%s\" %s " % (launcher["application"], arguments))
                            if ( self.settings[ "lirc_state" ] ):
                                xbmc.executebuiltin('LIRC.start')
                        elif (sys.platform.startswith('darwin')):
                            os.system("\"%s\" %s " % (launcher["application"], arguments))
                        else:
                            notification(addonName + " - " + addonString(30612).encode('utf-8'),addonString(30609).encode('utf-8'),"",3000)
                    xbmc.sleep(self.settings[ "start_tempo" ])
                    if (launcher["minimize"] == "true"):
                        _toogle_fullscreen()
                    try:
                        xbmc.enableNavSounds(True)                            
                    except:
                        pass
					
                    try:
						xbmc.audioResume()
                    except:
						pass
                else:
                    notification(addonName + " - " + addonString(30612).encode('utf-8'),addonString(30611).encode('utf-8') % os.path.basename(launcher["application"]),"",3000)
Exemplo n.º 26
0
    def showImageQueue(self, image_queue):
        image_queue.reset()
        image = image_queue.next()

        start = time.time()
        end = time.time() + image_queue.duration
        musicEnd = [end - image_queue.musicFadeOut]

        info = self.ImageQueueInfo(image_queue, musicEnd)

        self.window.initialize()
        self.window.setTransition('none')

        xbmc.enableNavSounds(False)

        self.playMusic(image_queue)

        if xbmc.getCondVisibility('Window.IsVisible(visualisation)'):
            DEBUG_LOG('Closing visualisation window')
            xbmc.executebuiltin('Action(back)')

        self.window.setTransition(image_queue.transition, image_queue.transitionDuration)

        action = None

        try:
            while image:
                DEBUG_LOG(' -IMAGE.QUEUE: {0}'.format(image))

                action = self.showImageFromQueue(image, info, first=True)

                if action:
                    if action == 'NEXT':
                        image = image_queue.next(extend=True) or image
                        continue
                    elif action == 'PREV':
                        image = image_queue.prev() or image
                        continue
                    elif action == 'BIG_NEXT':
                        self.window.setSkipNotice('+3')
                        image = image_queue.next(count=3, extend=True) or image
                        continue
                    elif action == 'BIG_PREV':
                        self.window.setSkipNotice('-3')
                        image = image_queue.prev(count=3) or image
                        continue
                    elif action == 'BACK':
                        DEBUG_LOG(' -IMAGE.QUEUE: Skipped after {0}secs'.format(int(time.time() - start)))
                        return False
                    elif action == 'SKIP':
                        DEBUG_LOG(' -IMAGE.QUEUE: Skipped after {0}secs'.format(int(time.time() - start)))
                        return True
                    else:
                        if action is True:
                            image_queue.mark(image)

                        image = image_queue.next(start)
                else:
                    return
        finally:
            kodiutil.setGlobalProperty('paused', '')
            xbmc.enableNavSounds(True)
            self.stopMusic(action != 'BACK' and image_queue or None)
            if self. window.hasAction():
                if self.window.getAction() == 'BACK':
                    return False
            self.window.clear()

        DEBUG_LOG(' -IMAGE.QUEUE: Finished after {0}secs'.format(int(time.time() - start)))
        return True