def initNoCustomAssetsSetting(): """ Checks if the NoCustomAssets setting is enabled when running as a mod. """ global _noCustomAssetsSettingInitDone if _noCustomAssetsSettingInitDone: return if isMod(): global _noCustomAssets # EF: don't check game option because BUG is initialized only once at startup # if CyGame().isOption(GameOptionTypes.GAMEOPTION_LOCK_MODS): # _noCustomAssets = True # BugUtil.debug("BugPath - Lock Modified Assets is set") # else: if getModDir() and getModFolder(): BugUtil.debug("BugPath - checking for NoCustomAssets") try: from configobj import ConfigObj config = ConfigObj(join(getModDir(), getModFolder() + ".ini"), encoding="utf_8") _noCustomAssets = config["CONFIG"].as_bool("NoCustomAssets") except: BugUtil.trace("BugPath - failed to parse mod INI file for NoCustomAssets") BugUtil.info("BugPath - NoCustomAssets is %s", _noCustomAssets) _noCustomAssetsSettingInitDone = True
def initNoCustomAssetsSetting(): """ Checks if the NoCustomAssets setting is enabled when running as a mod. """ global _noCustomAssetsSettingInitDone if _noCustomAssetsSettingInitDone: return if isMod(): global _noCustomAssets # EF: don't check game option because BUG is initialized only once at startup # if CyGame().isOption(GameOptionTypes.GAMEOPTION_LOCK_MODS): # _noCustomAssets = True # BugUtil.debug("BugPath - Lock Modified Assets is set") # else: if getModDir() and getModFolder(): BugUtil.debug("BugPath - checking for NoCustomAssets") try: from configobj import ConfigObj config = ConfigObj(join(getModDir(), getModFolder() + ".ini"), encoding='utf_8') _noCustomAssets = config["CONFIG"].as_bool("NoCustomAssets") except: BugUtil.trace( "BugPath - failed to parse mod INI file for NoCustomAssets" ) BugUtil.info("BugPath - NoCustomAssets is %s", _noCustomAssets) _noCustomAssetsSettingInitDone = True
def unknown_starttag(self, tag, attrs): try: #BugUtil.debug("BugConfig - %s", self.format(tag, attrs)) self._handler, self._element = self._handler.startChild(self._element, tag, attrs) self._stack.append((self._handler, self._element)) except: BugUtil.trace("BugConfig - failure parsing %s at line %d" % (self._path, self.lineno))
def _handleDefaultEvent(self, eventType, argsList): if self.EventHandlerMap.has_key(eventType): for eventHandler in self.EventHandlerMap[eventType]: try: eventHandler(argsList) except: BugUtil.trace("Error in %s event handler %s", eventType, eventHandler)
def initDataFolder(): """ Finds the first directory that contains a folder named SETTINGS_FOLDER. """ global _dataFolderInitDone if _dataFolderInitDone: return BugUtil.debug("BugPath - initializing data folder") # K-Mod. If it doesn't already exist, create the folder in the user directory. dir = join(getRootDir(), getModName(), SETTINGS_FOLDER) if dir != None: if not isdir(dir): # copy the default settings from the K-Mod folder. default_dir = join(getModDir(), SETTINGS_FOLDER) if isdir(default_dir): try: safeInfoPath("BugPath - copying settings to '%s'", dir) # copytree is suppose to create the missing parent directores, but apparently it doesn't work. So I need to do this: try: os.makedirs(join(getRootDir(), getModName())) except OSError: pass # sucks. shutil.copytree(default_dir, dir) except: BugUtil.trace("Failed to copy settings") if not isdir(dir): # Second attempt: create the directory manually try: safeInfoPath("BugPath - creating '%s'", dir) os.makedirs(dir) except OSError: BugUtil.trace("Failed to create directory '%s'", dir) # K-Mod end dataDirs = ( join(getRootDir(), getModName()), # My Games\BTS\BUG Mod join(getUserDir(), getModName()), # My Games\BUG Mod join(getAppDir(), getModName()), # Civ4\BTS\BUG Mod join(getModDir(), DATA_FOLDER), # Civ4\BTS\Mods\BUG Mod 3.6\Data join(getModDir()), # Civ4\BTS\Mods\BUG Mod 3.6 ) for dir in dataDirs: if setDataDir(dir): break else: BugUtil.error("No valid data directory containing %s found", SETTINGS_FOLDER) _dataFolderInitDone = True # <advc.009> setDataDir tries to locate INFO_FOLDER in the same place # as SETTINGS_FOLDER, but settings need to be in \My Games\, whereas # info is in the program folder. I don't see how this can work in standalone # BUG (same code there) either - perhaps it doesn't; haven't tried it. global _infoDir for dir in dataDirs: _infoDir = join(dir, INFO_FOLDER) if isdir(_infoDir): # Show the troublesome path in the System tab too BugConfigTracker.add("Info_Directory", _infoDir) break
def initRootFolder(): """ Finds the directory that contains the CivilizationIV.ini file and the user's documents directory. """ global _rootFolderInitDone if _rootFolderInitDone: return BugUtil.debug("BugPath - initializing system folders") global _rootDir, _userDir # override root dir from CvAltRoot try: import CvAltRoot altRootDir = CvAltRoot.rootDir if not setRootDir(altRootDir): BugUtil.error( "Directory from CvAltRoot.py is not valid or does not contain CivilizationIV.ini" ) except ImportError: BugUtil.debug("BugPath - CvAltRoot module not present") except AttributeError: BugUtil.error("CvAltRoot.py module has no rootDir setting") except IOError, (errno, strerror): BugUtil.trace("Error accessing directory from CvAltRoot.py: [%d] %s", errno, strerror)
def processSetupFile(): """ Reads and processes the GameSetUpCheck.txt file. """ filename = BugPath.findDataFile("GameSetUpCheck.txt", "GameSetUpCheck") if not filename: BugUtil.error("Cannot find GameSetUpCheck.txt") else: try: BugUtil.debug("GameSetUpCheck - processing GameSetUpCheck.txt") fp = open(filename, 'r') for line in fp: BugUtil.debug("GameSetUpCheck - %s", line) (type, key, value) = line.split(",") if (type == 'minHOFOpponents'): minHOFOpponents.append(int(value.strip())) elif (type == 'maxHOFOpponents'): maxHOFOpponents.append(int(value.strip())) elif (type == 'reqHOFGameOptions'): hofGameOptionRequirements.append(int(value.strip())) elif (type == 'hofAllowedMapScripts'): hofAllowedMapScripts[key.strip()] = int(value.strip()) elif (type == 'hofAllowedCylindrical'): hofAllowedCylindrical[key.strip()] = int(value.strip()) elif (type == 'hofAllowedToroidal'): hofAllowedToroidal[key.strip()] = int(value.strip()) elif (type == 'balancedOptionIndex'): balancedOptionIndex[key.strip()] = int(value.strip()) elif (type == 'worldWrapOptionIndex'): worldWrapOptionIndex[key.strip()] = int(value.strip()) elif (type == 'allowedWorldWrapValue'): allowedWorldWrapValue[key.strip()] = int(value.strip()) elif (type == 'modCRC'): global modCRC modCRC = key elif (type == 'dllCRC'): global dllCRC dllCRC = key elif (type == 'shaderCRC'): global shaderCRC shaderCRC = key elif (type == 'pythonCRC'): global pythonCRC pythonCRC = key elif (type == 'xmlCRC'): global xmlCRC xmlCRC = key else: BugUtil.warn("Unknown type '%s' in GameSetUpCheck.txt", type) fp.close() return True except: BugUtil.trace("Error processing GameSetUpCheck.txt") try: fp.close() except: pass return False
def callHandler(self, handler, argsList): try: if argsList is None: return handler() else: return handler(argsList) except: BugUtil.trace("Error in %s callback handler %s", handler.__module__, self.name)
def callInits(): """Calls all of the stored init functions in the order they were added.""" BugUtil.debug("BugInit - calling init functions...") while g_initQueue: name, func = g_initQueue.pop(0) try: func() except: BugUtil.trace("BugInit - init '%s' failed" % name)
def callListener(self, listener, argsList, result): try: if argsList is None: value = listener(result) else: value = listener(argsList, result) if value is not None: BugUtil.warn("BugGameUtils - %s - ignoring %s listener's return value %r", self.name, listener.__module__, value) except: BugUtil.trace("Error in %s callback listener %s", listener.__module__, self.name)
def makeDir(name): # Creates a new directory in the dataDir folder. path = join(_modDir, name) if path and not os.path.isdir(path): try: os.makedirs(path) return path except IOError: import BugUtil BugUtil.trace("Cannot create directory '%s' in '%s", name, _modDir) return path
def read(self): try: self.path = BugPath.findSettingsFile(self.name) if not self.path: self.create() else: self.config = ConfigObj(self.path, encoding='utf_8') except IOError: self.path = None self.config = None BugUtil.trace("BugOptions - error reading file '%s'", self.name)
def _handleOnSaveEvent(self, eventType, argsList): """Handles OnSave events by concatenating the results obtained from each handler to form an overall consolidated save string. """ result = "" if self.EventHandlerMap.has_key(eventType): for eventHandler in self.EventHandlerMap[eventType]: try: result += eventHandler(argsList) except: BugUtil.trace("Error in %s event handler %s", eventType, eventHandler) return result
def makeDir(name): """ Creates a new directory in the dataDir folder. """ path = join(getDataDir(), name) if path and not isdir(path): try: safeInfoPath("BugPath - creating '%s'", path) os.makedirs(path) return path except IOError: BugUtil.trace("Cannot create directory '%s' in '%s", name, getDataDir()) return path
def unknown_endtag(self, tag): try: #BugUtil.debug("BugConfig - end <%s>", tag) handler, element = self._stack.pop() if self._stack: self._handler, self._element = self._stack[-1] self._handler.endChild(self._element, handler, element) else: self._handler = None self._element = None handler.end(element) except: BugUtil.trace("BugConfig - failure parsing %s at line %d" % (self._path, self.lineno))
def makeDir(name): """ Creates a new directory in the dataDir folder. """ path = join(getDataDir(), name) if path and not isdir(path): try: safeInfoPath("BugPath - creating '%s'", path) os.makedirs(path) return path except OSError: BugUtil.trace("Cannot create directory '%s' in '%s", name, getDataDir()) return path
def parse(self, path): self._path = path self.start() file = open(path) try: self.feed(file.read()) except: file.close() self.close() BugUtil.trace("BugConfig - failure parsing %s at line %d", path, self.lineno) raise file.close() self.close()
def initDataFolder(): """ Finds the first directory that contains a folder named SETTINGS_FOLDER. """ global _dataFolderInitDone if _dataFolderInitDone: return BugUtil.debug("BugPath - initializing data folder") # K-Mod. If it doesn't already exist, create the folder in the user directory. dir = join(getRootDir(), getModName(), SETTINGS_FOLDER) if dir != None: if not isdir(dir): # copy the default settings from the K-Mod folder. default_dir = join(getModDir(), SETTINGS_FOLDER) if isdir(default_dir): try: safeInfoPath("BugPath - copying settings to '%s'", dir) # copytree is suppose to create the missing parent directores, but apparently it doesn't work. So I need to do this: try: os.makedirs(join(getRootDir(), getModName())) except OSError: pass # sucks. shutil.copytree(default_dir, dir) except: BugUtil.trace("Failed to copy settings") if not isdir(dir): # Second attempt: create the directory manually try: safeInfoPath("BugPath - creating '%s'", dir) os.makedirs(dir) except OSError: BugUtil.trace("Failed to create directory '%s'", dir) # K-Mod end dataDirs = ( join(getRootDir(), getModName()), # My Games\BTS\BUG Mod join(getUserDir(), getModName()), # My Games\BUG Mod join(getAppDir(), getModName()), # Civ4\BTS\BUG Mod join(getModDir(), DATA_FOLDER), # Civ4\BTS\Mods\BUG Mod 3.6\Data join(getModDir()), # Civ4\BTS\Mods\BUG Mod 3.6 ) for dir in dataDirs: if setDataDir(dir): break else: BugUtil.error("No valid data directory containing %s found", SETTINGS_FOLDER) _dataFolderInitDone = True
def _handleConsumableEvent(self, eventType, argsList): """Handles events that can be consumed by the handlers, such as keyboard or mouse events. If a handler returns non-zero, processing is terminated, and no subsequent handlers are invoked. (Changed) """ if self.EventHandlerMap.has_key(eventType): bHandled = False for eventHandler in self.EventHandlerMap[eventType]: try: A = eventHandler(argsList) if A: bHandled = True except: BugUtil.trace("Error in %s event handler %s", eventType, eventHandler) if bHandled: return 1 return 0
def _handleConsumableEvent(self, eventType, argsList): """Handles events that can be consumed by the handlers, such as keyboard or mouse events. If a handler returns non-zero, processing is terminated, and no subsequent handlers are invoked. """ if self.EventHandlerMap.has_key(eventType): for eventHandler in self.EventHandlerMap[eventType]: try: result = eventHandler(argsList) if (result > 0): return result except: BugUtil.trace("Error in %s event handler %s", eventType, eventHandler) return 0
def parse(self, path): self._path = path self.start() try: file = open(path) try: while True: s = file.read(BLOCK_SIZE) if not s: break self.feed(s) self.close() finally: file.close() except IOError: BugUtil.trace("BugConfig - IOError parsing %s", path) raise except BugUtil.ConfigError: BugUtil.trace("BugConfig - failure parsing %s at line %d", path, self.lineno) raise except: BugUtil.trace("BugConfig - failure parsing %s at line %d", path, self.lineno) raise
def initModFolder(): """ Checks if BUG is running as a mod and sets the folder and name if so. """ global _modFolderInitDone if _modFolderInitDone: return if not CyGame().isFinalInitialized(): BugUtil.debug("BugInit - game not fully initialized") return BugUtil.debug("BugPath - initializing mod folder") global _modDir, _modFolder try: replay = CyReplayInfo() replay.createInfo(0) modDir = replay.getModName().replace('\\', r'/') except: BugUtil.trace("replay not ready") else: if modDir and len(modDir) > 2: if not setModDir(abspath(modDir)): BugUtil.error("Replay provided invalid mod directory") if not _modDir: BugUtil.debug("BugPath - checking CvModFolder") try: import CvModFolder modFolder = CvModFolder.modFolder except ImportError: BugUtil.debug("BugPath - CvModFolder module not present") except AttributeError: BugUtil.error("CvModFolder.py module has no modFolder setting") else: if not setModDir(join(getRootDir(), MODS_FOLDER, modFolder)): if not setModDir(join(getAppDir(), MODS_FOLDER, modFolder)): BugUtil.error( "Cannot find mod folder using '%s' from CvModFolder.py", modFolder) if not _modFolder: BugUtil.debug("BugPath - no mod directory found") _modFolderInitDone = True
def initRootFolder(): """ Finds the directory that contains the CivilizationIV.ini file and the user's documents directory. """ global _rootFolderInitDone if _rootFolderInitDone: return BugUtil.debug("BugPath - initializing system folders") global _rootDir, _userDir # override root dir from CvAltRoot try: import CvAltRoot altRootDir = CvAltRoot.rootDir if not setRootDir(altRootDir): BugUtil.error("Directory from CvAltRoot.py is not valid or does not contain CivilizationIV.ini") except ImportError: BugUtil.debug("BugPath - CvAltRoot module not present") except AttributeError: BugUtil.error("CvAltRoot.py module has no rootDir setting") except IOError, (errno, strerror): BugUtil.trace("Error accessing directory from CvAltRoot.py: [%d] %s", errno, strerror)
def initModFolder(): """ Checks if BUG is running as a mod and sets the folder and name if so. """ global _modFolderInitDone if _modFolderInitDone: return if not CyGame().isFinalInitialized(): BugUtil.debug("BugInit - game not fully initialized") return BugUtil.debug("BugPath - initializing mod folder") global _modDir, _modFolder try: replay = CyReplayInfo() replay.createInfo(0) modDir = replay.getModName().replace("\\", r"/") except: BugUtil.trace("replay not ready") else: if modDir and len(modDir) > 2: if not setModDir(abspath(modDir)): BugUtil.error("Replay provided invalid mod directory") if not _modDir: BugUtil.debug("BugPath - checking CvModFolder") try: import CvModFolder modFolder = CvModFolder.modFolder except ImportError: BugUtil.debug("BugPath - CvModFolder module not present") except AttributeError: BugUtil.error("CvModFolder.py module has no modFolder setting") else: if not setModDir(join(getRootDir(), MODS_FOLDER, modFolder)): if not setModDir(join(getAppDir(), MODS_FOLDER, modFolder)): BugUtil.error("Cannot find mod folder using '%s' from CvModFolder.py", modFolder) if not _modFolder: BugUtil.debug("BugPath - no mod directory found") _modFolderInitDone = True
def write(self): if self.fileExists(): if self.isDirty(): BugUtil.debug("BugOptions - writing INI file '%s'", self.name) try: self.config.write() self.dirty = False except IOError: BugUtil.trace("BugOptions - failed writing INI file '%s'", self.path) elif self.isLoaded(): self.path = BugPath.createSettingsFile(self.name) if self.path: BugUtil.debug("BugOptions - writing new INI file '%s'", self.name) try: file = open(self.path, "w") self.config.write(file) file.close() self.dirty = False except IOError: BugUtil.trace("BugOptions - failed creating INI file '%s'", self.path) else: BugUtil.error("BugOptions - Cannot locate settings folder") else: BugUtil.warn("BugOptions - INI file '%s' was never read", self.name)
def write(self): if self.fileExists(): if self.isDirty(): BugUtil.debug("BugOptions - writing INI file '%s'", self.name) try: self.config.write() self.dirty = False except IOError: print "IOError" BugUtil.trace("BugOptions - failed writing INI file '%s'", self.path) elif self.isLoaded(): if self.path: BugUtil.debug("BugOptions - writing new INI file '%s'", self.name) try: file = open(self.path, "w") self.config.write(file) file.close() self.dirty = False except IOError: BugUtil.trace("BugOptions - failed creating INI file '%s'", self.path) else: BugUtil.error("BugOptions - Cannot locate settings folder") else: BugUtil.warn("BugOptions - INI file '%s' was never read", self.name)
def parse(self, path): try: file = open(path) try: while True: s = file.read(512) if not s: break self.feed(s) finally: file.close() except IOError: BugUtil.trace("BugConfig - IOError parsing %s" % path) except BugUtil.ConfigError: BugUtil.trace("BugConfig - failure parsing %s at line %d" % (path, self.lineno)) except: BugUtil.trace("BugConfig - failure parsing %s at line %d" % (path, self.lineno)) raise self.close()
def _getCallback(self, name): try: return self._callbacks[name] except KeyError: BugUtil.trace("Unknown GameUtils callback %s", name) raise