Advertisement
Guest User

Untitled

a guest
Mar 10th, 2018
210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 21.68 KB | None | 0 0
  1. import os, sys, re
  2. import time, zipfile, glob, shutil
  3.  
  4. import dbupdate, util
  5. from gamedatabase import *
  6. from util import *
  7. from util import __addon__
  8. from util import Logutil as log
  9. import xbmc, xbmcgui, xbmcvfs
  10.  
  11.  
  12. KODI_JSONRPC_TOGGLE_FULLSCREEN = '{"jsonrpc": "2.0", "method": "Input.ExecuteAction", "params": {"action": "togglefullscreen"}, "id": "1"}'
  13.  
  14.  
  15. class RCBLauncher(object):
  16. def __init__(self):
  17. self.env = (os.environ.get("OS", "win32"), "win32", )[os.environ.get("OS", "win32") == "xbox"]
  18. log.debug("Running environment detected as {0}".format(self.env))
  19.  
  20. # Do we need to escape commands before executing?
  21. self.escapeCmd = __addon__.getSetting(util.SETTING_RCB_ESCAPECOMMAND).upper() == 'TRUE'
  22.  
  23. self.romCollection = None
  24.  
  25. def launchEmu(self, gdb, gui, gameId, config, listitem):
  26. log.info("Begin launcher.launchEmu")
  27.  
  28. gameRow = Game(gdb).getObjectById(gameId)
  29. if gameRow is None:
  30. log.error("Game with id %s could not be found in database" % gameId)
  31. return
  32.  
  33. try:
  34. self.romCollection = config.romCollections[str(gameRow[util.GAME_romCollectionId])]
  35. except KeyError:
  36. log.error("Cannot get rom collection with id: " + str(gameRow[util.GAME_romCollectionId]))
  37. gui.writeMsg(util.localize(32034))
  38. return
  39.  
  40. gui.writeMsg(util.localize(32163) + " " + gameRow[util.ROW_NAME])
  41.  
  42. # Remember viewstate
  43. gui.saveViewState(False)
  44.  
  45. cmd = ""
  46. precmd = ""
  47. postcmd = ""
  48.  
  49. filenameRows = File(gdb).getRomsByGameId(gameRow[util.ROW_ID])
  50. log.info("files for current game: " + str(filenameRows))
  51.  
  52. cmd, precmd, postcmd, roms = self.__buildCmd(gui, filenameRows, gameRow, False)
  53.  
  54. if not self.romCollection.useBuiltinEmulator:
  55. if cmd == '':
  56. log.info("No cmd created. Game will not be launched.")
  57. return
  58. if precmd.strip() == '' or precmd.strip() == 'call':
  59. log.info("No precmd created.")
  60.  
  61. if postcmd.strip() == '' or postcmd.strip() == 'call':
  62. log.info("No postcmd created.")
  63.  
  64. # solo mode
  65. if self.romCollection.useEmuSolo:
  66.  
  67. self.__copyLauncherScriptsToUserdata()
  68.  
  69. # communicate with service via settings
  70. __addon__.setSetting(util.SETTING_RCB_LAUNCHONSTARTUP, 'true')
  71.  
  72. # invoke script file that kills xbmc before launching the emulator
  73. basePath = os.path.join(util.getAddonDataPath(), 'scriptfiles')
  74.  
  75. if self.env == "win32":
  76. if __addon__.getSetting(util.SETTING_RCB_USEVBINSOLOMODE).lower() == 'true':
  77. # There is a problem with quotes passed as argument to windows command shell. This only works with "call"
  78. # use vb script to restart xbmc
  79. cmd = 'call \"' + os.path.join(basePath,
  80. 'applaunch-vbs.bat') + '\" ' + cmd
  81. else:
  82. # There is a problem with quotes passed as argument to windows command shell. This only works with "call"
  83. cmd = 'call \"' + os.path.join(basePath, 'applaunch.bat') + '\" ' + cmd
  84. else:
  85. cmd = os.path.join(basePath, 'applaunch.sh ') + cmd
  86. else:
  87. # use call to support paths with whitespaces
  88. if self.env == "win32":
  89. cmd = 'call ' + cmd
  90.  
  91. # update LaunchCount
  92. launchCount = gameRow[util.GAME_launchCount]
  93. Game(gdb).update(('launchCount',), (launchCount + 1,), gameRow[util.ROW_ID], True)
  94. gdb.commit()
  95.  
  96. log.info("cmd: " + cmd)
  97. log.info("precmd: " + precmd)
  98. log.info("postcmd: " + postcmd)
  99.  
  100. try:
  101. pathname = util.getAddonDataPath()
  102. filename = os.path.join(pathname,
  103. 'rcb_lcdsmartie.txt')
  104. fh = open(filename, 'w')
  105. fh.write('%s\n%s' %(romCollection.name,
  106. gameRow[util.ROW_NAME]))
  107. fh.close()
  108.  
  109. __launchNonXbox(cmd, romCollection, gameRow, settings, precmd, postcmd, roms, gui, listitem)
  110.  
  111. fh = open (filename, 'w')
  112. fh.write('RCB Emuladores\n > Elige Juego')
  113. fh.close()
  114.  
  115. gui.writeMsg("")
  116.  
  117. except Exception, (exc):
  118. log.error("Error while launching emu: " + str(exc))
  119. gui.writeMsg(util.localize(32035) + ": " + str(exc))
  120.  
  121. log.info("End launcher.launchEmu")
  122.  
  123. def __buildCmd(self, gui, filenameRows, gameRow, calledFromSkin):
  124. log.info("launcher.buildCmd")
  125.  
  126. compressedExtensions = ['7z', 'zip']
  127.  
  128. cmd = ""
  129. precmd = ""
  130. postcmd = ""
  131.  
  132. emuCommandLine = self.romCollection.emulatorCmd
  133. log.info("emuCommandLine: " + emuCommandLine)
  134. log.info("preCmdLine: " + self.romCollection.preCmd)
  135. log.info("postCmdLine: " + self.romCollection.postCmd)
  136.  
  137. # handle savestates
  138. stateFile = self.__checkGameHasSaveStates(gameRow, filenameRows)
  139.  
  140. if stateFile == '':
  141. emuParams = self.romCollection.emulatorParams
  142. else:
  143. emuParams = self.romCollection.saveStateParams
  144. if self.escapeCmd:
  145. stateFile = re.escape(stateFile)
  146. emuParams = emuParams.replace('%statefile%', stateFile)
  147. emuParams = emuParams.replace('%STATEFILE%', stateFile)
  148. emuParams = emuParams.replace('%Statefile%', stateFile)
  149.  
  150. # params could be: {-%I% %ROM%}
  151. # we have to repeat the part inside the brackets and replace the %I% with the current index
  152. emuParams, partToRepeat = self.__prepareMultiRomCommand(emuParams)
  153.  
  154. # ask for disc number if multidisc game
  155. diskName = ""
  156. if self.romCollection.diskPrefix != '' and '%I%' not in emuParams:
  157. log.info("Getting Multiple Disc Parameter")
  158. options = []
  159. for disk in filenameRows:
  160. gamename = os.path.basename(disk[0])
  161. match = re.search(self.romCollection.diskPrefix.lower(), str(gamename).lower())
  162. if match:
  163. disk = gamename[match.start():match.end()]
  164. options.append(disk)
  165. if len(options) > 1 and not calledFromSkin:
  166. diskNum = xbmcgui.Dialog().select(util.localize(32164) + ': ', options)
  167. if diskNum < 0:
  168. # don't launch game
  169. log.info("No disc was chosen. Won't launch game")
  170. return "", "", "", None
  171. else:
  172. diskName = options[diskNum]
  173. log.info("Chosen Disc: %s" % diskName)
  174.  
  175. # insert game specific command
  176. gameCmd = ''
  177. if gameRow[util.GAME_gameCmd] is not None:
  178. gameCmd = str(gameRow[util.GAME_gameCmd])
  179. # be case insensitive with (?i)
  180. emuParams = re.sub('(?i)%gamecmd%', gameCmd, emuParams)
  181.  
  182. log.info("emuParams: " + emuParams)
  183.  
  184. fileindex = int(0)
  185. for fileNameRow in filenameRows:
  186. rom = fileNameRow[0]
  187. log.info("rom: " + str(rom))
  188.  
  189. if self.romCollection.makeLocalCopy:
  190. localDir = os.path.join(util.getTempDir(), self.romCollection.name)
  191. if xbmcvfs.exists(localDir + '\\'):
  192. log.info("Trying to delete local rom files")
  193. dirs, files = xbmcvfs.listdir(localDir)
  194. for f in files:
  195. xbmcvfs.delete(os.path.join(localDir, f))
  196. localRom = os.path.join(localDir, os.path.basename(str(rom)))
  197. log.info("Creating local copy: " + str(localRom))
  198. if xbmcvfs.copy(rom, localRom):
  199. log.info("Local copy created")
  200. rom = localRom
  201.  
  202. # If it's a .7z file
  203. # Don't extract zip files in case of savestate handling and when called From skin
  204. filext = rom.split('.')[-1]
  205. roms = [rom]
  206. if filext in compressedExtensions and not self.romCollection.doNotExtractZipFiles and stateFile == '' and not calledFromSkin:
  207. roms = self.__handleCompressedFile(gui, filext, rom, emuParams)
  208. log.debug("roms compressed = " + str(roms))
  209. if len(roms) == 0:
  210. return "", "", "", None
  211.  
  212. # no use for complete cmd as we just need the game name
  213. if self.romCollection.useBuiltinEmulator:
  214. log.debug("roms = " + str(roms))
  215. return "", "", "", roms
  216.  
  217. del rom
  218.  
  219. for rom in roms:
  220. precmd = ""
  221. postcmd = ""
  222. if fileindex == 0:
  223. emuParams = self.__replacePlaceholdersInParams(emuParams, rom, gameRow)
  224. if self.escapeCmd:
  225. emuCommandLine = re.escape(emuCommandLine)
  226.  
  227. if self.romCollection.name in ['Linux', 'Macintosh', 'Windows']:
  228. cmd = self.__replacePlaceholdersInParams(emuCommandLine, rom, gameRow)
  229. else:
  230. cmd = '\"' + emuCommandLine + '\" ' + emuParams.replace('%I%', str(fileindex))
  231. else:
  232. newrepl = partToRepeat
  233. newrepl = self.__replacePlaceholdersInParams(newrepl, rom, gameRow)
  234. if self.escapeCmd:
  235. emuCommandLine = re.escape(emuCommandLine)
  236.  
  237. newrepl = newrepl.replace('%I%', str(fileindex))
  238. cmd += ' ' + newrepl
  239.  
  240. cmdprefix = ''
  241.  
  242. if self.env == "win32":
  243. cmdprefix = 'call '
  244.  
  245. precmd = cmdprefix + self.__replacePlaceholdersInParams(self.romCollection.preCmd, rom, gameRow)
  246. postcmd = cmdprefix + self.__replacePlaceholdersInParams(self.romCollection.postCmd, rom, gameRow)
  247.  
  248. fileindex += 1
  249.  
  250. # A disk was chosen by the user, select it here
  251. if diskName:
  252. log.info("Choosing Disk: " + str(diskName))
  253. match = re.search(self.romCollection.diskPrefix.lower(), cmd.lower())
  254. replString = cmd[match.start():match.end()]
  255. cmd = cmd.replace(replString, diskName)
  256.  
  257. return cmd, precmd, postcmd, roms
  258.  
  259. def __checkGameHasSaveStates(self, gameRow, filenameRows):
  260.  
  261. if self.romCollection.saveStatePath == '':
  262. log.debug("No save state path set")
  263. return ''
  264.  
  265. rom = filenameRows[0][0]
  266. saveStatePath = self.__replacePlaceholdersInParams(self.romCollection.saveStatePath, rom, gameRow)
  267.  
  268. saveStateFiles = glob.glob(saveStatePath)
  269.  
  270. if len(saveStateFiles) == 0:
  271. log.debug("No save state files found")
  272. return ''
  273.  
  274. log.info('saveStateFiles found: ' + str(saveStateFiles))
  275.  
  276. # don't select savestatefile if ASKNUM is requested in Params
  277. if re.search('(?i)%ASKNUM%', self.romCollection.saveStateParams):
  278. return saveStateFiles[0]
  279.  
  280. options = [util.localize(32165)]
  281. for f in saveStateFiles:
  282. options.append(os.path.basename(f))
  283. selectedFile = xbmcgui.Dialog().select(util.localize(32166), options)
  284. # If selections is canceled or "Don't launch statefile" option
  285. if selectedFile < 1:
  286. return ''
  287.  
  288. return saveStateFiles[selectedFile - 1]
  289.  
  290. def __prepareMultiRomCommand(self, emuParams):
  291. obIndex = emuParams.find('{')
  292. cbIndex = emuParams.find('}')
  293. partToRepeat = ''
  294. if obIndex > -1 and cbIndex > 1:
  295. partToRepeat = emuParams[obIndex+1:cbIndex]
  296. emuParams = emuParams.replace("{", "")
  297. emuParams = emuParams.replace("}", "")
  298.  
  299. return emuParams, partToRepeat
  300.  
  301. def __handleCompressedFile(self, gui, filext, rom, emuParams):
  302.  
  303. log.info("__handleCompressedFile")
  304.  
  305. # Note: Trying to delete temporary files (from zip or 7z extraction) from last run
  306. # Do this before launching a new game. Otherwise game could be deleted before launch
  307. tempDir = os.path.join(util.getTempDir(), 'extracted', self.romCollection.name)
  308. # check if folder exists
  309. if not xbmcvfs.exists(tempDir +'\\'):
  310. log.info("Create temporary folder: " +tempDir)
  311. xbmcvfs.mkdir(tempDir)
  312.  
  313. try:
  314. if xbmcvfs.exists(tempDir +'\\'):
  315. log.info("Trying to delete temporary rom files")
  316. #can't use xbmcvfs.listdir here as it seems to cache the file list and RetroPlayer won't find newly created files anymore
  317. files = os.listdir(tempDir)
  318. for f in files:
  319. #RetroPlayer places savestate files next to the roms. Don't delete these files.
  320. fname, ext = os.path.splitext(f)
  321. if(ext not in ('.sav', '.xml', '.png')):
  322. xbmcvfs.delete(os.path.join(tempDir, f))
  323. except Exception, (exc):
  324. log.error("Error deleting files after launch emu: " + str(exc))
  325. gui.writeMsg(util.localize(32036) + ": " + str(exc))
  326.  
  327. roms = []
  328.  
  329. log.info("Treating file as a compressed archive")
  330. compressed = True
  331.  
  332. try:
  333. names = self.__getNames(filext, rom)
  334. except Exception, (exc):
  335. log.error("Error handling compressed file: " + str(exc))
  336. return []
  337.  
  338. if names is None:
  339. log.error("Error handling compressed file")
  340. return []
  341.  
  342. chosenROM = -1
  343.  
  344. # check if we should handle multiple roms
  345. match = False
  346. if self.romCollection.diskPrefix != '':
  347. match = re.search(self.romCollection.diskPrefix.lower(), str(names).lower())
  348.  
  349. if '%I%' in emuParams and match:
  350. log.info("Loading %d archives" % len(names))
  351.  
  352. try:
  353. archives = self.__getArchives(filext, rom, names)
  354. except Exception, (exc):
  355. log.error("Error handling compressed file: " +str(exc))
  356. return []
  357.  
  358. if archives is None:
  359. log.warning("Error handling compressed file")
  360. return []
  361. for archive in archives:
  362. newPath = os.path.join(tempDir, archive[0])
  363. fp = open(newPath, 'wb')
  364. fp.write(archive[1])
  365. fp.close()
  366. roms.append(newPath)
  367.  
  368. elif len(names) > 1:
  369. log.info("The Archive has %d files" % len(names))
  370. chosenROM = xbmcgui.Dialog().select('Choose a ROM', names)
  371. elif len(names) == 1:
  372. log.info("Archive only has one file inside; picking that one")
  373. chosenROM = 0
  374. else:
  375. log.error("Archive had no files inside!")
  376. return []
  377.  
  378. if chosenROM != -1:
  379. # Extract all files to %TMP%
  380. archives = self.__getArchives(filext, rom, names)
  381. if archives is None:
  382. log.warn("Error handling compressed file")
  383. return []
  384. for archive in archives:
  385. newPath = os.path.join(tempDir, archive[0])
  386. log.info("Putting extracted file in %s" % newPath)
  387. fo = open(str(newPath), 'wb')
  388. fo.write(archive[1])
  389. fo.close()
  390.  
  391. # Point file name to the chosen file and continue as usual
  392. roms = [os.path.join(tempDir, names[chosenROM])]
  393.  
  394. return roms
  395.  
  396. def __replacePlaceholdersInParams(self, emuParams, rom, gameRow):
  397.  
  398. if self.escapeCmd:
  399. rom = re.escape(rom)
  400.  
  401. # TODO: Wanted to do this with re.sub:
  402. # emuParams = re.sub(r'(?i)%rom%', rom, emuParams)
  403. # --> but this also replaces \r \n with linefeed and newline etc.
  404.  
  405. # full rom path ("C:\Roms\rom.zip")
  406. emuParams = emuParams.replace('%rom%', rom)
  407. emuParams = emuParams.replace('%ROM%', rom)
  408. emuParams = emuParams.replace('%Rom%', rom)
  409.  
  410. # romfile ("rom.zip")
  411. romfile = os.path.basename(rom)
  412. emuParams = emuParams.replace('%romfile%', romfile)
  413. emuParams = emuParams.replace('%ROMFILE%', romfile)
  414. emuParams = emuParams.replace('%Romfile%', romfile)
  415.  
  416. # romname ("rom")
  417. romname = os.path.splitext(os.path.basename(rom))[0]
  418. emuParams = emuParams.replace('%romname%', romname)
  419. emuParams = emuParams.replace('%ROMNAME%', romname)
  420. emuParams = emuParams.replace('%Romname%', romname)
  421.  
  422. # gamename
  423. gamename = unicode(gameRow[util.ROW_NAME])
  424. emuParams = emuParams.replace('%game%', gamename)
  425. emuParams = emuParams.replace('%GAME%', gamename)
  426. emuParams = emuParams.replace('%Game%', gamename)
  427.  
  428. # ask num
  429. if re.search('(?i)%ASKNUM%', emuParams):
  430. options = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
  431. number = unicode(xbmcgui.Dialog().select(util.localize(32167), options))
  432. emuParams = emuParams.replace('%asknum%', number)
  433. emuParams = emuParams.replace('%ASKNUM%', number)
  434. emuParams = emuParams.replace('%Asknum%', number)
  435.  
  436. # ask text
  437. if re.search('(?i)%ASKTEXT%', emuParams):
  438. command = xbmcgui.Dialog().input(util.localize(32168), type=xbmcgui.INPUT_ALPHANUM)
  439.  
  440. emuParams = emuParams.replace('%asktext%', command)
  441. emuParams = emuParams.replace('%ASKTEXT%', command)
  442. emuParams = emuParams.replace('%Asktext%', command)
  443.  
  444. return emuParams
  445.  
  446. def __copyLauncherScriptsToUserdata(self):
  447. log.info('__copyLauncherScriptsToUserdata')
  448.  
  449. oldBasePath = os.path.join(util.getAddonInstallPath(), 'resources', 'scriptfiles')
  450. newBasePath = os.path.join(util.getAddonDataPath(), 'scriptfiles')
  451.  
  452. files = []
  453. # Copy applaunch shell script/batch file
  454. if self.env == 'win32':
  455. files.append('applaunch.bat')
  456. else:
  457. files.append('applaunch.sh')
  458.  
  459. # Copy VBS files
  460. if self.env == 'win32' and __addon__.getSetting(util.SETTING_RCB_USEVBINSOLOMODE).lower() == 'true':
  461. files += ['applaunch-vbs.bat', 'LaunchKodi.vbs', 'Sleep.vbs']
  462.  
  463. for f in files:
  464. if not xbmcvfs.exists(os.path.join(newBasePath, f)):
  465. log.debug("Copying file {0} from {1} to {2}".format(f, oldBasePath, newBasePath))
  466. if not xbmcvfs.copy(os.path.join(oldBasePath, f), os.path.join(newBasePath, f)):
  467. log.warn("Error copying file")
  468.  
  469. def __audioSuspend(self):
  470. if __addon__.getSetting(util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
  471. log.debug("Suspending audio")
  472. xbmc.executebuiltin("PlayerControl(Stop)")
  473. xbmc.enableNavSounds(False)
  474. xbmc.audioSuspend()
  475.  
  476. def __audioResume(self):
  477. if __addon__.getSetting(util.SETTING_RCB_SUSPENDAUDIO).upper() == 'TRUE':
  478. log.debug("Resuming audio")
  479. xbmc.audioResume()
  480. xbmc.enableNavSounds(True)
  481.  
  482. def __preDelay(self):
  483. preDelay = __addon__.getSetting(SETTING_RCB_PRELAUNCHDELAY)
  484. if preDelay != '':
  485. log.debug("Pre delaying by {0}ms".format(preDelay))
  486. xbmc.sleep(int(float(preDelay)))
  487.  
  488. def __postDelay(self):
  489. postDelay = __addon__.getSetting(SETTING_RCB_POSTLAUNCHDELAY)
  490. if postDelay != '':
  491. log.debug("Post delaying by {0}ms".format(postDelay))
  492. xbmc.sleep(int(float(postDelay)))
  493.  
  494. def __getEncoding(self):
  495. # HACK: sys.getfilesystemencoding() is not supported on all systems (e.g. Android)
  496. try:
  497. encoding = sys.getfilesystemencoding()
  498. except Exception as e:
  499. log.warn("Unable to get filesystem encoding, defaulting to UTF-8")
  500. encoding = 'utf-8'
  501.  
  502. return encoding
  503.  
  504. def __executePreCommand(self, precmd):
  505. # pre launch command
  506. if precmd.strip() != '' and precmd.strip() != 'call':
  507. log.info("Got to PRE: " + precmd.strip())
  508. os.system(precmd.encode(self.__getEncoding()))
  509.  
  510. def __executeCommand(self, cmd):
  511. # change working directory
  512. path = os.path.dirname(self.romCollection.emulatorCmd)
  513. if os.path.isdir(path):
  514. try:
  515. os.chdir(path)
  516. except OSError:
  517. log.warn("Unable to chdir to {0}".format(path))
  518.  
  519. if self.romCollection.usePopen:
  520. import subprocess
  521. process = subprocess.Popen(cmd.encode(self.__getEncoding()), shell=True)
  522. process.wait()
  523. else:
  524. os.system(cmd.encode(self.__getEncoding()))
  525.  
  526. def __executePostCommand(self, postcmd):
  527. # post launch command
  528. if postcmd.strip() != '' and postcmd.strip() != 'call':
  529. log.info("Got to POST: " + postcmd.strip())
  530. os.system(postcmd.encode(self.__getEncoding()))
  531.  
  532. def __launchNonXbox(self, cmd, gameRow, precmd, postcmd, roms, gui, listitem):
  533. log.info("launchEmu on non-xbox")
  534.  
  535. screenModeToggled = False
  536.  
  537. # use libretro core to play game
  538. if self.romCollection.useBuiltinEmulator:
  539. log.info("launching game with internal emulator")
  540. rom = roms[0]
  541. gameclient = self.romCollection.gameclient
  542. # HACK: use alternateGameCmd as gameclient
  543. if gameRow[util.GAME_alternateGameCmd] is not None and gameRow[util.GAME_alternateGameCmd] != "":
  544. gameclient = str(gameRow[util.GAME_alternateGameCmd])
  545. log.info("Preferred gameclient: " + gameclient)
  546. log.info("Setting platform: " + self.romCollection.name)
  547.  
  548. if listitem is None:
  549. listitem = xbmcgui.ListItem(rom, "0", "", "")
  550.  
  551. parameters = {"platform": self.romCollection.name}
  552. if gameclient != "":
  553. parameters["gameclient"] = gameclient
  554. listitem.setInfo(type="game", infoLabels=parameters)
  555. log.info("launching rom: " + rom)
  556.  
  557. gui.player.play(rom, listitem)
  558. # xbmc.executebuiltin('PlayMedia(\"%s\", platform=%s, gameclient=%s)' %(rom, romCollection.name, romCollection.gameclient))
  559. return
  560.  
  561. if not self.romCollection.useEmuSolo:
  562. screenMode = xbmc.getInfoLabel("System.Screenmode")
  563. log.info("screenMode: " + screenMode)
  564. isFullScreen = screenMode.endswith("Full Screen")
  565.  
  566. toggleScreenMode = __addon__.getSetting(util.SETTING_RCB_TOGGLESCREENMODE).upper() == 'TRUE'
  567.  
  568. if isFullScreen and toggleScreenMode:
  569. log.info("Toggling to windowed mode")
  570. # this minimizes xbmc some apps seems to need it
  571. xbmc.executeJSONRPC(KODI_JSONRPC_TOGGLE_FULLSCREEN)
  572.  
  573. screenModeToggled = True
  574.  
  575. log.info("launch emu")
  576.  
  577. self.__executePreCommand(precmd)
  578.  
  579. self.__preDelay()
  580.  
  581. self.__audioSuspend()
  582.  
  583. self.__executeCommand(cmd)
  584.  
  585. log.info("launch emu done")
  586.  
  587. self.__postDelay()
  588.  
  589. self.__audioResume()
  590.  
  591. self.__executePostCommand(postcmd)
  592.  
  593. if screenModeToggled:
  594. log.info("Toggle to Full Screen mode")
  595. # this brings xbmc back
  596. xbmc.executeJSONRPC(KODI_JSONRPC_TOGGLE_FULLSCREEN)
  597.  
  598. # Compressed files functions
  599. def __getNames(self, type, filepath):
  600. return {'zip': self.__getNamesZip,
  601. '7z': self.__getNames7z}[type](filepath)
  602.  
  603. def __getNames7z(self, filepath):
  604.  
  605. try:
  606. import py7zlib
  607. except ImportError as e:
  608. xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(32039), util.localize(32129))
  609. msg = ("You have tried to launch a .7z file but you are missing required libraries to extract the file. "
  610. "You can download the latest RCB version from RCBs project page. It contains all required libraries.")
  611. log.error(msg)
  612. log.error("Error: " + str(e))
  613. return None
  614.  
  615. fp = open(str(filepath), 'rb')
  616. archive = py7zlib.Archive7z(fp)
  617. names = archive.getnames()
  618. fp.close()
  619. return names
  620.  
  621. def __getNamesZip(self, filepath):
  622. fp = open(str(filepath), 'rb')
  623. archive = zipfile.ZipFile(fp)
  624. names = archive.namelist()
  625. fp.close()
  626. return names
  627.  
  628. def __getArchives(self, type, filepath, archiveList):
  629. return {'zip': self.__getArchivesZip,
  630. '7z': self.__getArchives7z}[type](filepath, archiveList)
  631.  
  632. def __getArchives7z(self, filepath, archiveList):
  633.  
  634. try:
  635. import py7zlib
  636. except ImportError:
  637. xbmcgui.Dialog().ok(util.SCRIPTNAME, util.localize(32039), util.localize(32129))
  638. msg = ("You have tried to launch a .7z file but you are missing required libraries to extract the file. "
  639. "You can download the latest RCB version from RCBs project page. It contains all required libraries.")
  640. log.error(msg)
  641. return None
  642.  
  643. fp = open(str(filepath), 'rb')
  644. archive = py7zlib.Archive7z(fp)
  645. archivesDecompressed = [(name, archive.getmember(name).read())for name in archiveList]
  646. fp.close()
  647. return archivesDecompressed
  648.  
  649. def __getArchivesZip(self, filepath, archiveList):
  650. fp = open(str(filepath), 'rb')
  651. archive = zipfile.ZipFile(fp)
  652. archivesDecompressed = [(name, archive.read(name)) for name in archiveList]
  653. fp.close()
  654. return archivesDecompressed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement