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 __audioSuspend(self):
     if __addon__.getSetting(
             util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
         log.debug("Suspending audio")
         xbmc.executebuiltin("PlayerControl(Stop)")
         xbmc.enableNavSounds(False)
         xbmc.audioSuspend()
Example #3
0
def Open_Netflix():
    import subprocess, sys
    xbmc.audioSuspend()
    ret = xbmc.executeJSONRPC(
        '{ "jsonrpc": "2.0", "id": 0, "method": "Settings.getSettingValue", "params": {"setting":"screensaver.mode" } }'
    )
    jsn = json.loads(ret)
    saver_mode = jsn['result']['value']
    xbmc.executeJSONRPC(
        '{ "jsonrpc": "2.0", "id": 0, "method":"Settings.setSettingValue", "params": {"setting":"screensaver.mode", "value":""} } '
    )
    browser = xbmcaddon.Addon('plugin.video.kodilivetv').getSetting('browser')
    if 'linux' in sys.platform:
        if browser == "Chrome":
            CHROME = os.path.join('/', 'opt', 'google', 'chrome',
                                  'google-chrome')
            if not os.path.isfile(CHROME):
                CHROME = os.path.join('/', 'usr', 'bin', 'google-chrome')
            subprocess.call([
                CHROME, '--start-maximized', '--disable-translate',
                '--disable-new-tab-first-run', '--no-default-browser-check',
                '--no-first-run', '--kiosk',
                '--app=https://www.netflix.com/browse'
            ])
            #process = subprocess.Popen(os.path.join(os.path.join(addonDir),"chrome.sh"), shell=True)
        else:
            CHROMIUM = os.path.join('/', 'usr', 'bin', 'chromium')
            if not os.path.isfile(CHROMIUM):
                CHROMIUM = os.path.join('/', 'usr', 'bin', 'chromium-browser')
            subprocess.call([
                CHROMIUM, '--start-maximized', '--disable-translate',
                '--disable-new-tab-first-run', '--no-default-browser-check',
                '--no-first-run', '--kiosk',
                '--app=https://www.netflix.com/browse'
            ])
            #process = subprocess.Popen(os.path.join(os.path.join(addonDir),"chromium.sh"), shell=True)
        #process.wait()
    if 'win32' in sys.platform:
        if browser == "Chrome":
            process = subprocess.Popen(os.path.join(os.path.join(addonDir),
                                                    "chrome.cmd"),
                                       shell=True)
        else:
            process = subprocess.Popen(os.path.join(os.path.join(addonDir),
                                                    "iexplore.cmd"),
                                       shell=True)
        process.wait()
    if 'darwin' in sys.platform:
        CHROME = os.path.join('/', 'Applications', 'Google Chrome.app',
                              'Contents', 'MacOS', 'Google Chrome')
        subprocess.call([
            CHROMIUM, '--start-fullscreen', '--kiosk',
            'https://www.netflix.com/browse'
        ])
        #process = subprocess.Popen(os.path.join(os.path.join(addonDir),"darwin.sh"), shell=True)
        #process.wait()
    xbmc.audioResume()
    xbmc.executeJSONRPC(
        '{ "jsonrpc": "2.0", "id": 0, "method": "Settings.SetSettingValue", "params": {"setting":"screensaver.mode", "value": "'
        + saver_mode + '" } }')
Example #4
0
    def playInternal(self, video_id, series_id):
        xbmc.audioSuspend()
        self.disable_screensaver()

        if generic_utility.get_setting('disable_lirc') == 'true':
            xbmc.executebuiltin('LIRC.Stop')

        try:
            self.launch_browser('http://netflix.com/watch/%s' % video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification(
                'Error launching browser. See logfile')

        self.enable_screensaver()
        xbmc.audioResume()
        if generic_utility.get_setting('disable_lirc') == 'true':
            xbmc.executebuiltin('LIRC.Start')
        try:
            self.update_playcount(video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification(
                'Cannot update playcount. See logfile')
        self.close()
Example #5
0
    def playInternal (self, video_id, series_id):
        xbmc.audioSuspend()
        self.disable_screensaver()

        if generic_utility.get_setting('disable_lirc') == 'true':
            xbmc.executebuiltin('LIRC.Stop')

        try:
            self.launch_browser('http://netflix.com/watch/%s' % video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification('Error launching browser. See logfile')

        self.enable_screensaver()
        xbmc.audioResume()
        if generic_utility.get_setting('disable_lirc') == 'true':
            xbmc.executebuiltin('LIRC.Start')

        if generic_utility.get_setting('sync_viewstate') == 'true':
            try:
                self.update_playcount(video_id)
            except:
                generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
                generic_utility.notification('Cannot update playcount. See logfile')
        self.close()
Example #6
0
def launchSteam():
    basePath = os.path.join(getAddonDataPath(), 'scripts')
    if osAndroid:
        cmd = "com.valvesoftware.android.steam.community"
        log('attempting to launch: "%s"' % cmd)
        xbmc.executebuiltin('XBMC.StartAndroidActivity("%s")' % cmd)
        kodiBusyDialog()
        sys.exit()
    elif osWin:
        steamlauncher = os.path.join(basePath, 'SteamLauncher-AHK.exe')
        cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (
            steamlauncher, steamWin, kodiWin, quitKodiSetting, kodiPortable,
            preScript, postScript)
        #log('Windows UTF-8 command: "%s"' % cmdutf8)
    elif osOsx:
        steamlauncher = os.path.join(basePath, 'steam-launch.sh')
        cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (
            steamlauncher, steamOsx, kodiOsx, quitKodiSetting, kodiPortable,
            preScript, postScript)
    elif osLinux:
        steamlauncher = os.path.join(basePath, 'steam-launch.sh')
        cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (
            steamlauncher, steamLinux, kodiLinux, quitKodiSetting,
            kodiPortable, preScript, postScript)
    try:
        log('attempting to launch: %s' % cmd)
        print cmd.encode('utf-8')
        if suspendAudio == 'true':
            xbmc.audioSuspend()
            log('Audio suspended')
        if quitKodiSetting == '1' and suspendAudio == 'true':
            proc_h = subprocess.Popen(cmd.encode(txt_encode),
                                      shell=True,
                                      close_fds=False)
            kodiBusyDialog()
            log('Waiting for Steam to exit')
            while proc_h.returncode is None:
                xbmc.sleep(1000)
                proc_h.poll()
            log('Start resuming audio....')
            xbmc.audioResume()
            log('Audio resumed')
            del proc_h
        else:
            subprocess.Popen(cmd.encode(txt_encode),
                             shell=True,
                             close_fds=True)
            kodiBusyDialog()

    except:
        log('ERROR: failed to launch: %s' % cmd)
        print cmd.encode(txt_encode)
        dialog.notification(language(50123), language(50126), addonIcon, 5000)
def launchSteam():
    if osAndroid:
        cmd = "com.valvesoftware.android.steam.community"
        log('attempting to launch: "%s"' % cmd)
        xbmc.executebuiltin('XBMC.StartAndroidActivity("%s")' % cmd)
        kodiBusyDialog()
        sys.exit()
    elif osWin:
        steamlauncher = os.path.join(scripts_path, 'steam-launcher.exe')
        cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (
            steamlauncher, steamWin, kodiWin, quitKodiSetting, kodiPortable,
            preScript, postScript, steamParameters, forceKillKodi, desktopMode)
    elif osOsx:
        steamlauncher = os.path.join(scripts_path, 'steam-launcher.sh')
        cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (
            steamlauncher, steamOsx, kodiOsx, quitKodiSetting, kodiPortable,
            preScript, postScript, steamParameters, forceKillKodi, desktopMode)
    elif osLinux:
        steamlauncher = os.path.join(scripts_path, 'steam-launcher.sh')
        cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" %s' % (
            steamlauncher, steamLinux, kodiLinux, quitKodiSetting,
            kodiPortable, preScript, postScript, steamParameters,
            forceKillKodi, desktopMode,
            "> " + steamlauncher.replace('.sh', '.log'))
    try:
        log('attempting to launch: %s' % cmd)
        print cmd.encode('utf-8')
        if suspendAudio == 'true':
            xbmc.audioSuspend()
            log('Audio suspended')
        if quitKodiSetting != '0' and suspendAudio == 'true':
            proc_h = subprocess.Popen(cmd.encode(txt_encode),
                                      shell=True,
                                      close_fds=False)
            kodiBusyDialog()
            log('Waiting for Steam to exit')
            while proc_h.returncode is None:
                xbmc.sleep(1000)
                proc_h.poll()
            log('Start resuming audio....')
            xbmc.audioResume()
            log('Audio resumed')
            del proc_h
        else:
            subprocess.Popen(cmd.encode(txt_encode),
                             shell=True,
                             close_fds=True)
            kodiBusyDialog()
    except:
        log('ERROR: failed to launch: %s' % cmd)
        print cmd.encode(txt_encode)
        dialog.notification(language(50212), language(50215), addonIcon, 5000)
def playInit():

    global xbmcAudioSuspended

    #Try and suspend XBMC's AudioEngine if it is present and has exclusive access to the audio device
    #also inhibit auto shutdown of XBMC
    try:
        xbmc.executebuiltin('XBMC.InhibitIdleShutdown(True)', False)
        xbmc.audioSuspend()
        logNotice("Suspended XBMC AE")
        xbmcAudioSuspended = True
    except Exception as inst:
        logNotice("Unable to suspend XBMC AE: " + str(inst))
        pass
def playInit():

    global xbmcAudioSuspended

    #Try and suspend XBMC's AudioEngine if it is present and has exclusive access to the audio device
    #also inhibit auto shutdown of XBMC
    try:
        xbmc.executebuiltin('XBMC.InhibitIdleShutdown(True)', False)
        xbmc.audioSuspend();
        logNotice("Suspended XBMC AE")
        xbmcAudioSuspended = True
    except Exception as inst:
        logNotice("Unable to suspend XBMC AE: " + str(inst))
        pass
 def lowerVolume(self):
     try:
         # If we are after a zero volume then we have the option to suspend
         # the Audio Engine
         if Settings.isUseAudioSuspend():
             xbmc.audioSuspend()
         elif self.screensaverVolume > -1:
             vol = self.screensaverVolume
             # Make sure the volume still has a value, otherwise we see the mute symbol
             if vol < 1:
                 vol = 1
             log("Player: volume goal: %d%%" % vol)
             self._setVolume(vol)
         else:
             log("Player: No reduced volume option set")
     except:
         log("VolumeDrop: %s" % traceback.format_exc(), xbmc.LOGERROR)
Example #11
0
 def lowerVolume(self):
     try:
         # If we are after a zero volume then we have the option to suspend
         # the Audio Engine
         if Settings.isUseAudioSuspend():
             xbmc.audioSuspend()
         elif self.screensaverVolume > -1:
             vol = self.screensaverVolume
             # Make sure the volume still has a value, otherwise we see the mute symbol
             if vol < 1:
                 vol = 1
             log("Player: volume goal: %d%%" % vol)
             self._setVolume(vol)
         else:
             log("Player: No reduced volume option set")
     except:
         log("VolumeDrop: %s" % traceback.format_exc(), xbmc.LOGERROR)
    def playInternal (self, video_id, series_id):
        xbmc.audioSuspend()
        self.disable_screensaver()

        try:
            self.launch_browser('https://www.netflix.com/watch/%s' % video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification('Error launching browser. See logfile')

        self.enable_screensaver()
        xbmc.audioResume()
        try:
            self.update_playcount(video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification('Cannot update playcount. See logfile')
        self.close()
Example #13
0
def launchSteam():
	basePath = os.path.join(getAddonDataPath(), 'scripts')
	if osAndroid:
		cmd = "com.valvesoftware.android.steam.community"
		log('attempting to launch: "%s"' % cmd)
		xbmc.executebuiltin('XBMC.StartAndroidActivity("%s")' % cmd)
		kodiBusyDialog()
		sys.exit()
	elif osWin:
		steamlauncher = os.path.join(basePath, 'SteamLauncher-AHK.exe')
		cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (steamlauncher, steamWin, kodiWin, quitKodiSetting, kodiPortable, preScript, postScript)
		#log('Windows UTF-8 command: "%s"' % cmdutf8)
	elif osOsx:
		steamlauncher = os.path.join(basePath, 'steam-launch.sh')
		cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (steamlauncher, steamOsx, kodiOsx, quitKodiSetting, kodiPortable, preScript, postScript)
	elif osLinux:
		steamlauncher = os.path.join(basePath, 'steam-launch.sh')
		cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (steamlauncher, steamLinux, kodiLinux, quitKodiSetting, kodiPortable, preScript, postScript)
	try:
		log('attempting to launch: %s' % cmd)
		print cmd.encode('utf-8')
		if suspendAudio == 'true':
			xbmc.audioSuspend()
			log('Audio suspended')
		if quitKodiSetting == '1' and suspendAudio == 'true':
			proc_h = subprocess.Popen(cmd.encode(txt_encode), shell=True, close_fds=False)
			kodiBusyDialog()
			log('Waiting for Steam to exit')
			while proc_h.returncode is None:
				xbmc.sleep(1000)
				proc_h.poll()
			log('Start resuming audio....')
			xbmc.audioResume()
			log('Audio resumed')
			del proc_h		
		else:
			subprocess.Popen(cmd.encode(txt_encode), shell=True, close_fds=True)
			kodiBusyDialog()


	except:
		log('ERROR: failed to launch: %s' % cmd)
		print cmd.encode(txt_encode)
		dialog.notification(language(50123), language(50126), addonIcon, 5000)
Example #14
0
def launch_playnite():
    # if this.os_android:
    #   cmd = "com.valvesoftware.android.steam.community"
    #   log('attempting to launch: "%s"' % cmd)
    #   xbmc.executebuiltin('XBMC.StartAndroidActivity("%s")' % cmd)
    #   kodi_busy_dialog()
    #   sys.exit()
    # elif this.os_win:
    if this.os_win:
        playnitelauncher = str(
            PurePath(scripts_path).joinpath('playnite-launcher.exe'))
        log(f'playnite launcher exe: {playnitelauncher}')
        playniteWin = this.playnite_desktop_win if this.desktop_mode == True else this.playnite_fullscreen_win
        cmd = f'"{playnitelauncher}" "{playniteWin}" "{this.kodi_win}" "{str(this.quit_kodi)}" "{str(this.kodi_portable).lower()}" "{this.pre_script}" "{this.post_script}" "{this.playnite_parameters}" "{str(this.force_kill_kodi)}"'
    # elif this.os_osx:
    #   playnitelauncher = os.path.join(scripts_path, 'playnite-launcher.sh')
    #   cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (playnitelauncher, this.playnite_osx, this.kodi_osx, str(this.quit_kodi), str(this.kodi_portable).lower(), this.pre_script, this.post_script, this.playnite_parameters, str(this.force_kill_kodi))
    # elif this.os_linux:
    #   playnitelauncher = os.path.join(scripts_path, 'playnite-launcher.sh')
    #   cmd = '"%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s" "%s"' % (playnitelauncher, this.playnite_linux, this.kodi_linux, str(this.quit_kodi), str(this.kodi_portable).lower(), this.pre_script, this.post_script, this.playnite_parameters, str(this.force_kill_kodi))
    try:
        log(f'attempting to launch: {cmd}')
        if this.suspend_audio == True:
            xbmc.audioSuspend()
            log('audio suspended')
        if this.quit_kodi != 0 and this.suspend_audio == True:
            proc_h = subprocess.Popen(cmd, shell=True, close_fds=False)
            kodi_busy_dialog()
            log('waiting for Playnite to exit')
            while proc_h.returncode is None:
                xbmc.sleep(1000)
                proc_h.poll()
            log('start resuming audio....')
            xbmc.audioResume()
            log('audio resumed')
            del proc_h
        else:
            subprocess.Popen(cmd, shell=True, close_fds=True)
            kodi_busy_dialog()
    except:
        log(f'ERROR: failed to launch: {cmd}')
        dialog.notification(language(50212), language(50215), addonIcon, 5000)
    def playInternal(self, video_id, series_id):
        xbmc.audioSuspend()
        self.disable_screensaver()

        try:
            self.launch_browser('https://www.netflix.com/watch/%s' % video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification(
                'Error launching browser. See logfile')

        self.enable_screensaver()
        xbmc.audioResume()
        try:
            self.update_playcount(video_id)
        except:
            generic_utility.log(traceback.format_exc(), xbmc.LOGERROR)
            generic_utility.notification(
                'Cannot update playcount. See logfile')
        self.close()
Example #16
0
sep = ' '
string = sep.join(args)

# Evaluate DEBUG in settings.xml and assign log path
if __addon__.getSetting('DEBUG') == 'true':
    output = user_log
elif __addon__.getSetting('DEBUG') == 'false':
    output = '/dev/null'

# Copy environment
env = os.environ.copy()
# Add libs folder to environment
env['LD_LIBRARY_PATH'] = os.path.join(__cwd__, 'libs')

# Suspend XBMC's audio stream 
try:
    xbmc.audioSuspend()
except:
    pass

# Launch RetroArch with selected flags and environment
p = subprocess.Popen([helper_script, service, string, output], env=env, preexec_fn=os.setpgrp)
# Wait for process to terminate before continuing
p.wait()

# Enable XBMC's audio stream
try:
    xbmc.audioResume()
except:
    pass
Example #17
0
def emulator_launcher():
    prevent_video_playback('start')
    selected_game = ''.join(args.get('filename'))
    launcher_script = ''.join(args.get('launcher_script'))
    rom_path = ''.join(args.get('rom_path'))
    folder_url = build_url({
        'mode': 'folder',
        'foldername': ''.join(args.get('foldername'))
    })
    f = open(RESTART_FILE, 'w')
    f.write(folder_url)
    f.close()
    system_config = os.path.join(
        SYSTEMS_CONFIG_PATH, ''.join(args.get('foldername')) + '-config.xml')
    tree = ET.parse(system_config)
    root = tree.getroot()
    if selected_game:
        for item in root.findall('game_variations'):
            for game in item.iter('game'):
                if ''.join(args.get('game_name')) in game.attrib['name']:
                    if os.path.exists(os.path.join(rom_path, selected_game)):
                        game_variation_list = []
                        game_variation_list.append(selected_game, )
                        for game_variation in os.listdir(
                                os.path.join(rom_path, selected_game)):
                            game_variation_list.append(
                                os.path.splitext(game_variation)[0], )
                        selected_var_game = dialog.select(
                            language(50200), game_variation_list)
                        if selected_var_game == -1:
                            sys.exit()
                        elif selected_var_game == 0:
                            break
                        else:
                            selected_var_game = game_variation_list[
                                selected_var_game]
                        rom_path = os.path.join(rom_path, selected_game)
                        selected_game = selected_var_game
                        if not args.get('alt_launcher'):
                            if game.find('launcher').text:
                                launcher_script = game.find('launcher').text
                    else:
                        log_message = 'Directory does not exist: ' + os.path.join(
                            rom_path, selected_game)
                        log(log_message, language(50109))
        if not args.get('alt_launcher'):
            for item in root.findall('alt_launchers'):
                for game in item.iter('game'):
                    if selected_game in game.attrib['name']:
                        launcher_script = game.find('launcher').text
        if args.get('rom_extensions') == ['false']:
            search_item = os.path.join(rom_path, selected_game + '.*')
            rom_full_path_list = glob.glob('%s' % search_item)
            rom_full_path = ''.join(rom_full_path_list[0])
        else:
            file_types = []
            file_types = ''.join(args.get('rom_extensions')).split(' ')
            for file_type in file_types:
                file_type = '.' + file_type
                rom_full_path = os.path.join(rom_path,
                                             selected_game) + file_type
                if os.path.isfile(rom_full_path):
                    break
        if not rom_full_path:
            file_check(''.join(search_item), search_item)
        rom_extension = os.path.splitext(rom_full_path)[1]
        rom_file = os.path.basename(rom_full_path)
        if launcher_script == 'kodi_retroplayer':
            listitem = xbmcgui.ListItem(rom_file, "0", "", "")
            parameters = {
                'Platform': ''.join(args.get('foldername')),
                'Title': ''.join(args.get('game_name')),
                'URL': rom_full_path
            }
            listitem.setInfo(type='game', infoLabels=parameters)
            xbmc.Player().play(rom_full_path, listitem)
        else:
            launcher_script_command = os.path.join(LAUNCHER_SCRIPTS,
                                                   launcher_script)
            file_check(launcher_script_command, launcher_script_command)
            cmd = '"%s" "%s" "%s" "%s" "%s" "%s"' % (
                launcher_script_command, ''.join(args.get('foldername')),
                selected_game, rom_full_path, rom_file, rom_extension)
            log('Attempted command is:', False)
            log(cmd, False)
            if suspendAudio == 'true':
                xbmc.audioSuspend()
                log('Suspending Kodi audio', False)
            if backgroundKodi == 'true':
                proc_h = subprocess.Popen(cmd.encode(txt_encode),
                                          shell=True,
                                          close_fds=False)
                while proc_h.returncode is None:
                    xbmc.sleep(500)
                    proc_h.poll()
                del proc_h
            else:
                subprocess.Popen(cmd.encode(txt_encode),
                                 shell=True,
                                 close_fds=True)
            prevent_video_playback('stop')
            xbmc.audioResume()
    else:
        log('No selected game', language(50110))
config = None
try:
    with open(config_file, 'r') as f:
        config_str = f.read()

    # parse json settings for config settings
    # this is Python 2 so no need to decode to utf-8
    config = json.JSONDecoder().decode(config_str)
except:
    None  # config will remain None

# Stop anything playing as we will be suspending audio engine
#xbmc.Player.stop() # needs an argument!

# Suspend audio engine for Kodi to release PulseAudio
xbmc.audioSuspend()

# Run PulseAudio setup commands
subprocess.call(['pactl', 'load-module', 'module-udev-detect'])
time.sleep(2)
subprocess.call(['pactl', 'load-module', 'module-rtp-recv'])
time.sleep(5)

# Can't assume that either of these settings were loaded
#xbmcgui.Dialog().ok(addonname,
#    'pactl'+'set-card-profile'+config['card-profile']+'output:'+config['card-output'])
#xbmcgui.Dialog().ok(addonname,
#    'pactl'+'set-default-sink'+config['default-sink'])

try:
    subprocess.call([
Example #19
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"}')
Example #21
0
def pauseXbmc():
  xbmc.executebuiltin("PlayerControl(Stop)")
  xbmc.audioSuspend()
  xbmc.enableNavSounds(False)  
  time.sleep(1)
    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)
Example #23
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()
Example #24
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
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"}'
            )
Example #26
0
def emulator_launcher():
	prevent_video_playback('start')
	selected_game = ''.join(args.get('filename'))
	launcher_script = ''.join(args.get('launcher_script'))
	rom_path = ''.join(args.get('rom_path'))
	folder_url = build_url({'mode': 'folder', 'foldername': ''.join(args.get('foldername'))})
	f = open(RESTART_FILE, 'w')
	f.write(folder_url)
	f.close()
	system_config = os.path.join(SYSTEMS_CONFIG_PATH, ''.join(args.get('foldername')) + '-config.xml')
	tree = ET.parse(system_config)
	root = tree.getroot()
	if selected_game:
		for item in root.findall('game_variations'):
			for game in item.iter('game'):
				if ''.join(args.get('game_name')) in game.attrib['name']:
					if os.path.exists(os.path.join(rom_path, selected_game)):
						game_variation_list = []
						game_variation_list.append( selected_game, )
						for game_variation in os.listdir(os.path.join(rom_path, selected_game)):
							game_variation_list.append( os.path.splitext(game_variation)[0], )
						selected_var_game = dialog.select(language(50200), game_variation_list)
						if selected_var_game == -1:
							sys.exit()
						elif selected_var_game == 0:
							break
						else:
							selected_var_game = game_variation_list[selected_var_game]
						rom_path = os.path.join(rom_path, selected_game)
						selected_game = selected_var_game
						if not args.get('alt_launcher'):
							if game.find('launcher').text:
								launcher_script = game.find('launcher').text
					else:
						log_message = 'Directory does not exist: ' + os.path.join(rom_path, selected_game)
						log(log_message, language(50109))
		if not args.get('alt_launcher'):
			for item in root.findall('alt_launchers'):
				for game in item.iter('game'):
					if selected_game in game.attrib['name']:
						launcher_script = game.find('launcher').text
		if args.get('rom_extensions') == ['false']:
			search_item = os.path.join(rom_path, selected_game + '.*')
			rom_full_path_list = glob.glob('%s' % search_item)
			rom_full_path = ''.join(rom_full_path_list[0])
		else:
			file_types = []
			file_types = ''.join(args.get('rom_extensions')).split(' ')
			for file_type in file_types:
				file_type = '.' + file_type
				rom_full_path = os.path.join(rom_path, selected_game) + file_type
				if os.path.isfile(rom_full_path):
					break
		if not rom_full_path:
			file_check(''.join(search_item), search_item)
		rom_extension = os.path.splitext(rom_full_path)[1]
		rom_file = 	os.path.basename(rom_full_path)
		if launcher_script == 'kodi_retroplayer':
			listitem = xbmcgui.ListItem(rom_file, "0", "", "")
			parameters = {'Platform': ''.join(args.get('foldername')), 'Title': ''.join(args.get('game_name')), 'URL': rom_full_path}
			listitem.setInfo( type='game', infoLabels=parameters)
			xbmc.Player().play(rom_full_path, listitem)
		else:
			launcher_script_command = os.path.join(LAUNCHER_SCRIPTS, launcher_script)
			file_check(launcher_script_command, launcher_script_command)
			cmd = '"%s" "%s" "%s" "%s" "%s" "%s"' % (launcher_script_command, ''.join(args.get('foldername')), selected_game, rom_full_path, rom_file, rom_extension)
			log('Attempted command is:', False)
			log(cmd, False)
			if suspendAudio == 'true':
				xbmc.audioSuspend()
				log('Suspending Kodi audio', False)
			if backgroundKodi == 'true':
				proc_h = subprocess.Popen(cmd.encode(txt_encode), shell=True, close_fds=False)
				while proc_h.returncode is None:
					xbmc.sleep(500)
					proc_h.poll()
				del proc_h		
			else:
				subprocess.Popen(cmd.encode(txt_encode), shell=True, close_fds=True)
			prevent_video_playback('stop')
			xbmc.audioResume()
	else:
		log('No selected game', language(50110))
Example #27
0
    def launch_game(self, game_id):
        binary_path = self.config_helper.binary_path
        scripts_path = self.config_helper.launchscripts_path

        player = xbmc.Player()
        if player.isPlayingVideo():
            player.stop()

        isResumeMode = bool(self.plugin.getSetting('last_run'))
        showIntro = self.plugin.getSettingBool('show_intro')
        codec = self.config_helper.config['codec']

        if isResumeMode:
            xbmc.audioSuspend()
        else:
            self.plugin.setSettingString('last_run', game_id)

        xbmc.executebuiltin("Dialog.Close(busydialog)")
        xbmc.executebuiltin("Dialog.Close(notification)")
        xbmc.executebuiltin("InhibitScreensaver(true)")

        try:
            if showIntro and not isResumeMode:
                player.play(self.config_helper.addon_path +
                            'resources/statics/loading.mp4')
                time.sleep(10)
                player.stop()

            t0 = time.monotonic()
            subprocess.run([scripts_path + 'prescript.sh', binary_path, codec],
                           cwd=scripts_path,
                           start_new_session=True)
            launch_cmd = subprocess.Popen(
                [scripts_path + 'launch.sh', game_id],
                cwd=binary_path,
                start_new_session=True)
            launch_cmd.wait()
            subprocess.run([scripts_path + 'postscript.sh', binary_path],
                           cwd=scripts_path,
                           start_new_session=True)

        except Exception as e:
            print("Failed to execute moonlight process.")
            print(e)
        finally:
            xbmc.audioResume()
            xbmc.executebuiltin("InhibitScreensaver(false)")

            # Less than 10 seconds passed.
            if time.monotonic() - t0 < 10:
                result = xbmcgui.Dialog().yesno(
                    "",
                    "It seems that moonlight-embedded might have crashed. Create an automatic bug report?"
                )
                if result:
                    output = subprocess.check_output(
                        [scripts_path + '../../create_bug_report.sh'],
                        encoding='utf-8',
                        cwd=scripts_path + '../../',
                        start_new_session=True)
                    xbmcgui.Dialog().ok(
                        "",
                        "Report your bug on GitHub or Forums with this URL: " +
                        output)
            else:
                xbmcgui.Dialog().notification(
                    'Information', game_id +
                    ' is still running on host. Resume via Luna, ensuring to quit before the host is restarted!',
                    xbmcgui.NOTIFICATION_INFO, False)
    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')
    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)