def initAppFolder():
    """
	Locates the directory that contains the BTS application.
	"""
    global _appFolderInitDone
    if _appFolderInitDone:
        return
    BugUtil.debug("BugPath - initializing application folder")
    global _appDir, _appFolder

    # Determine the app directory that holds the executable and Mods
    # as well as the folder name inside MY_GAMES_FOLDER that holds CustomAssets and Mods.
    if isMac():
        _appDir = os.getcwd()
    else:
        if isfile(sys.executable):
            # BugUtil.debug("BugPath - exe is '%s'", sys.executable)
            _appDir = dirname(sys.executable)
    if _appDir:
        _appFolder = basename(_appDir)
        safeInfoPath("BugPath - app dir is '%s'", _appDir)
        safeDebugPath("BugPath - app folder is '%s'", _appFolder)
    else:
        BugUtil.warn("BugPath - no executable found")
    _appFolderInitDone = True
def findMainModIniFile():
    """
	Locates and returns the path to the configuration file named for the mod or None if not found.
	"""
    if getModName():
        return findSettingsFile(getModName() + ".ini")
    BugUtil.warn("BugPath - mod name not set")
    return None
Beispiel #3
0
def getUnitIcon(iUnit):
	iUnit = gc.getUnitClassInfo(gc.getUnitInfo(iUnit).getUnitClassType()).getDefaultUnitIndex()
	try:
		return g_unitIcons[iUnit]
	except:
		BugUtil.warn("no GP icon for unit %d", iUnit)
		return u"%c" % CyGame().getSymbolID(FontSymbols.GREAT_PEOPLE_CHAR)
Beispiel #4
0
	def handle(self, element, root, tag, key, parents, module, clazz):
		if root:
			element.setState("config-handler", getHandler(root))
		else:
			if isRegistered(key):
				BugUtil.warn("BugConfig - <%s>.key %s handler already registered, ignoring", element.tag, key)
			else:
				handler = BugUtil.callFunction(module, clazz)
				registerHandler(tag, handler)
				# automatically include in enclosing <config> handler
				parent = element.getState("config-handler")
				if parent:
					parentHandlers = [parent]
				else:
					parentHandlers = []
				# add listed parents
				if parents:
					for parent in parents.split():
						if parent == "-":
							parentHandlers = []
						else:
							parentHandlers.append(getHandler(parent))
				# place in bug handler if none specified
				if not parentHandlers:
					parentHandlers.append(g_bugHandler)
				# register with each parent handler
				for parent in parentHandlers:
					parent.addValidChild(tag)
					#parent.addChildHandler(handler)
				element.setState("config-handler", handler)
Beispiel #5
0
	def hideSign (self, pPlot, ePlayer):
		""" Hides sign for given player at given plot if there's a current sign the same as the stored one. 
		Note that this function assumes gCurrentSigns is up-to-date so make sure you've updated first.
		"""
		if not pPlot or pPlot.isNone():
			BugUtil.warn("MapSigns.hideSign() was passed an invalid plot: %s" % (str(pPlot)))
			return False
		thisKey = self.__getKey(pPlot)
		if gCurrentSigns == None:
			BugUtil.debug("MapSigns.hideSign() finds no current signs so there's nothing to hide.")
			return False
		if self.hasPlotSigns(pPlot):
			szCaption = self.plotDict[thisKey].getSign(ePlayer)
			if gCurrentSigns.hasPlotSigns(pPlot):
				szExistingCaption = gCurrentSigns[pPlot].getSign(ePlayer)
				if szCaption and szCaption == szExistingCaption:
					BugUtil.debug("MapSigns.hideSign() found matching sign (%s) for player %d on plot %s; will remove it" % (szCaption, ePlayer, str(thisKey)))
					if ePlayer == -1:
						engine.removeLandmark(pPlot)
					else:
						engine.removeSign(pPlot, ePlayer)
					return True
				else:
					BugUtil.debug("MapSigns.hideSign() found sign for player %d saying (%s) instead of (%s) on plot %s; will leave alone." % (ePlayer, szExistingCaption, szCaption, str(thisKey)))
			else:
				BugUtil.debug("MapSigns.hideSign() found no sign on plot %s to remove" % (str(thisKey)))
		else:
			BugUtil.debug("MapSigns.hideSign() found no saved signs at all for plot %s" % (str(thisKey)))
		return False
Beispiel #6
0
	def _getPendingAlertMessageIcon(self, city, passes):
		if (passes):
			BugUtil.warn("%s passed pending occupation test, ignoring", city.getName())
			return (None, None)
		else:
			return (localText.getText("TXT_KEY_CIV4LERTS_ON_CITY_PENDING_PACIFIED", (city.getName(), )),
					HAPPY_ICON)
Beispiel #7
0
	def hideSign (self, pPlot, ePlayer):
		""" Hides sign for given player at given plot if there's a current sign the same as the stored one.
		Note that this function assumes gCurrentSigns is up-to-date so make sure you've updated first.
		"""
		if not pPlot or pPlot.isNone():
			BugUtil.warn("MapSigns.hideSign() was passed an invalid plot: %s" % (str(pPlot)))
			return False
		thisKey = self.__getKey(pPlot)
		if gCurrentSigns == None:
			print "MapSigns.hideSign() finds no current signs so there's nothing to hide."
			return False
		if self.hasPlotSigns(pPlot):
			szCaption = self.plotDict[thisKey].getSign(ePlayer)
			if gCurrentSigns.hasPlotSigns(pPlot):
				szExistingCaption = gCurrentSigns[pPlot].getSign(ePlayer)
				if szCaption and szCaption == szExistingCaption:
					if pPlot.isInViewport():
						print "MapSigns.hideSign() found matching sign (%s) for player %d on plot %s; will remove it" %(szCaption, ePlayer, str(thisKey))
						if ePlayer == -1:
							engine.removeLandmark(pPlot.cloneToViewport())
						else:
							engine.removeSign(pPlot.cloneToViewport(), ePlayer)
					return True
				else:
					print "MapSigns.hideSign() found sign for player %d saying (%s) instead of (%s) on plot %s; will leave alone." %(ePlayer, szExistingCaption, szCaption, str(thisKey))
			else:
				print "MapSigns.hideSign() found no sign on plot %s to remove" % str(thisKey)
		else:
			print "MapSigns.hideSign() found no saved signs at all for plot %s" % str(thisKey)
		return False
Beispiel #8
0
def init():
	"""Performs the one-time initialization of the BUG core and all mods."""
	global g_initDone
	if g_initDone:
		BugUtil.warn("BugInit - init() called again")
		return
	global g_initRunning
	if g_initRunning:
		BugUtil.warn("BugInit - init() already running")
		return
	g_initRunning = True
	
	BugUtil.debug("BugInit - initializing...")
	timer = BugUtil.Timer("BUG init")
	
	try:
		# test to see if global context is ready
		CvUtil.initDynamicFontIcons()
	except:
		BugUtil.debug("BugInit - global context not ready")
		g_initRunning = False
		return False
	
	loadMod("init")
	BugCore.initDone()
	timer.log("read configs").start()
	callInits()
	timer.log("call inits/events")
	
	timer.logTotal()
	g_initDone = True
	g_initRunning = False
	return True
Beispiel #9
0
	def handle(self, element, root, tag, key, parents, module, clazz):
		if root:
			element.setState("config-handler", getHandler(root))
		else:
			if isRegistered(key):
				BugUtil.warn("BugConfig - <%s>.key %s handler already registered, ignoring", element.tag, key)
			else:
				handler = BugUtil.callFunction(module, clazz)
				registerHandler(tag, handler)
				# automatically include in enclosing <config> handler
				parent = element.getState("config-handler")
				if parent:
					parentHandlers = [parent]
				else:
					parentHandlers = []
				# add listed parents
				if parents:
					for parent in parents.split():
						if parent == "-":
							parentHandlers = []
						else:
							parentHandlers.append(getHandler(parent))
				# place in bug handler if none specified
				if not parentHandlers:
					parentHandlers.append(g_bugHandler)
				# register with each parent handler
				for parent in parentHandlers:
					parent.addValidChild(tag)
					#parent.addChildHandler(handler)
				element.setState("config-handler", handler)
Beispiel #10
0
def init():
	"""Performs the one-time initialization of the BUG core and all mods."""
	global g_initDone
	if g_initDone:
		BugUtil.debug("BugInit - init() already complete")
		return
	if not CyGame().isFinalInitialized():
		BugUtil.debug("BugInit - game not fully initialized")
		return
	global g_initRunning
	if g_initRunning:
		BugUtil.warn("BugInit - init() already running")
		return
	g_initRunning = True
	
	BugUtil.debug("BugInit - initializing...")
	timer = BugUtil.Timer("BUG init")
	
	BugPath.init()
	timer.log("init paths").start()
	
	loadMod("init")
	BugCore.initDone()
	timer.log("read configs").start()
	
	callInits()
	timer.log("call inits/events")
	
	timer.logTotal()
	
	g_initDone = True
	g_initRunning = False
	return True
Beispiel #11
0
	def createOption(self, element, id, type, key, default, andId, dll, title, tooltip, dirtyBit, getter, setter):
		if type == "color":
			return self.createListOption(element, id, type, key, default, andId, dll, title, tooltip, dirtyBit, getter, setter, type, None, None)
		mod = element.getState("mod")
		id = qualify(mod._id, id)
		andId = qualify(mod._id, andId)
		dll = self.resolveDll(element, dll)
		option = None
		ini = element.getState("ini")
		if ini and not key:
			key = id
		if key:
			if not ini:
				BugUtil.warn("BugConfig - <option> %s outside <options> element has a key attribute; making it unsaved", id)
			else:
				section = element.getState("ini-section")
				if not section:
					BugUtil.warn("BugConfig - <option> %s inside <options> element must be inside a <section> element; making it unsaved", id)
				else:
					option = IniOption(mod, id, ini, section, key, type, default, andId, dll, title, tooltip, dirtyBit)
		if option is None:
			option = UnsavedOption(mod, id, type, default, andId, dll, title, tooltip, dirtyBit)
		self.addOption(mod, option, getter, setter)
		element.setState("option", option)
		return option
Beispiel #12
0
	def createOption(self, element, id, type, key, default, andId, dll, title, tooltip, dirtyBit, getter, setter):
		if type == "color":
			return self.createListOption(element, id, type, key, default, andId, dll, title, tooltip, dirtyBit, getter, setter, type, None, None)
		mod = element.getState("mod")
		id = qualify(mod._id, id)
		andId = qualify(mod._id, andId)
		dll = 1
		option = None
		ini = element.getState("ini")
		if ini and not key:
			key = id
		if key:
			if not ini:
				BugUtil.warn("BugConfig - <option> %s outside <options> element has a key attribute; making it unsaved", id)
			else:
				section = element.getState("ini-section")
				if not section:
					BugUtil.warn("BugConfig - <option> %s inside <options> element must be inside a <section> element; making it unsaved", id)
				else:
					option = IniOption(mod, id, ini, section, key, type, default, andId, dll, title, tooltip, dirtyBit)
		if option is None:
			option = UnsavedOption(mod, id, type, default, andId, dll, title, tooltip, dirtyBit)
		self.addOption(mod, option, getter, setter)
		element.setState("option", option)
		return option
Beispiel #13
0
	def _getPendingAlertMessageIcon(self, city, passes):
		if (passes):
			BugUtil.warn("%s passed pending occupation test, ignoring", city.getName())
			return (None, None)
		else:
			return (localText.getText("TXT_KEY_CIV4LERTS_ON_CITY_PENDING_PACIFIED", (city.getName(), )),
					HAPPY_ICON)
Beispiel #14
0
def init():
    """Performs the one-time initialization of the BUG core and all mods."""
    global g_initDone
    if g_initDone:
        BugUtil.debug("BugInit - init() already complete")
        return
    if not CyGame().isFinalInitialized():
        BugUtil.debug("BugInit - game not fully initialized")
        return
    global g_initRunning
    if g_initRunning:
        BugUtil.warn("BugInit - init() already running")
        return
    g_initRunning = True

    BugUtil.debug("BugInit - initializing...")
    timer = BugUtil.Timer("BUG init")

    BugPath.init()
    timer.log("init paths").start()

    loadMod("init")
    BugCore.initDone()
    timer.log("read configs").start()

    callInits()
    timer.log("call inits/events")

    timer.logTotal()

    g_initDone = True
    g_initRunning = False
    return True
def registerSymbolSynonym(key, symbol, synonym):
    if synonym in keySymbols:
        BugUtil.warn("FontUtil - ignoring duplicate synonym '%s' for key '%s'",
                     synonym, key)
    else:
        BugUtil.debug("FontUtil - registering synonym '%s'", synonym)
        keySymbols[synonym] = symbol
Beispiel #16
0
def initAppFolder():
    """
	Locates the directory that contains the BTS application.
	"""
    global _appFolderInitDone
    if _appFolderInitDone:
        return
    BugUtil.debug("BugPath - initializing application folder")
    global _appDir, _appFolder

    # Determine the app directory that holds the executable and Mods
    # as well as the folder name inside MY_GAMES_FOLDER that holds CustomAssets and Mods.
    if isMac():
        _appDir = os.getcwd()
    else:
        if isfile(sys.executable):
            #BugUtil.debug("BugPath - exe is '%s'", sys.executable)
            _appDir = dirname(sys.executable)
    if _appDir:
        _appFolder = basename(_appDir)
        safeInfoPath("BugPath - app dir is '%s'", _appDir)
        safeDebugPath("BugPath - app folder is '%s'", _appFolder)
    else:
        BugUtil.warn("BugPath - no executable found")
    _appFolderInitDone = True
Beispiel #17
0
    def onMouseOverPlot(self, argsList=None):
        """
        Called from CvOverlayScreenUtils when mousing over a plot when the screen is active.
        Updates the current plot and its x/y location.
        """

        # remove the current city
        g_DotMap.unhighlightCity()

        # get the current plot
        plot = CyInterface().getMouseOverPlot()
        x = plot.getX()
        y = plot.getY()

        # get the current player
        pPlayer = gc.getPlayer(PlayerUtil.getActivePlayerID())
        if not pPlayer or pPlayer.isNone():
            BugUtil.warn(
                "CvDotMapOverlayScreen.onMouseOverPlot() was passed an invalid player id: %s"
                % (str(ePlayer)))
            return False
        eTeam = pPlayer.getTeam()

        # update city location if plot is visible
        if plot.isRevealed(eTeam, False):
            self.currentPoint = (x, y)
            g_DotMap.highlightCity(self.currentPoint, self.currentColor)
            self.resetInterfaceMode()
Beispiel #18
0
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
Beispiel #19
0
def findMainModIniFile():
    """
	Locates and returns the path to the configuration file named for the mod or None if not found.
	"""
    if getModName():
        return findSettingsFile(getModName() + ".ini")
    BugUtil.warn("BugPath - mod name not set")
    return None
 def setSign(self, ePlayer, szCaption):
     """ Sets Caption for a given player on this plot. """
     if ePlayer in ([-1] + range(gc.getMAX_PLAYERS())):
         self.signDict[ePlayer] = szCaption
     else:
         BugUtil.warn(
             "EventSigns PlotSigns.setSign() was passed an invalid Player ID %s at Plot (%d,%d)"
             % (str(ePlayer), self.iX, self.iY))
 def removeSign(self, ePlayer):
     """ Removes Caption for a given player on this plot. """
     if ePlayer in self.signDict:
         del self.signDict[ePlayer]
     else:
         BugUtil.warn(
             "EventSigns PlotSigns.removeSign() failed to find a caption for Player %d at Plot (%d,%d)"
             % (ePlayer, self.iX, self.iY))
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
Beispiel #23
0
def widgetVersion(version, bugWidget, bugData1=None, bugData2=None, *args):
	"""
	Picks one of two WidgetTypes and parameters to return based on presence of BUG DLL and <version>.
	
	The bugWidget must be the name of the desired widget, e.g. "WIDGET_SET_PERCENT";
	the other widget should be the WidgetTypes constant, e.g. WidgetTypes.WIDGET_CHANGE_PERCENT.
	
	The default widget values are WidgetTypes.WIDGET_GENERAL, -1, -1. To specify a different set,
	pass them in as the 4th, 5th and 6th arguments.
	
	To return zero or one data values, pass None for the BUG values you want not to have returned;
	the same ones won't be returned if the BUG DLL isn't present. When overriding the non-BUG widget
	type, you must always pass in three values: the WidgetTypes and its two data values. The matching
	BUG ones that are None will not be returned, regardless of their own values.
	
	Any arguments after the widget arguments are added at the end of the returned tuple; use this
	when the function you are passing the arguments to takes more arguments after the widget values.
	
	Make sure to use a * to unpack the returned tuple when passing the arguments to your function.
	
	Example:
		screen.setButtonGFC( "MinCommerceRate", u"", "", 130, 50, 20, 20, 
							 *BugDll.widget("WIDGET_SET_PERCENT", eCommerce, 0, 
							 				WidgetTypes.WIDGET_CHANGE_PERCENT, eCommerce, -100, 
							 				ButtonStyles.BUTTON_STYLE_CITY_MINUS) )
	"""
	realArgs = []
	if len(args) >= 3 and isinstance(args[0], WidgetTypes):
		normalWidget, normalData1, normalData2 = args[:3]
		args = args[3:]
	else:
		normalWidget=WidgetTypes.WIDGET_GENERAL
		normalData1=-1
		normalData2=-1
	handled = False
	if isVersion(version):
		try:
			if isinstance(bugWidget, WidgetTypes):
				realArgs.append(bugWidget)
			else:
				realArgs.append(getattr(WidgetTypes, bugWidget))
			if bugData1 is not None:
				realArgs.append(bugData1)
			if bugData2 is not None:
				realArgs.append(bugData2)
			handled = True
		except AttributeError:
			BugUtil.warn("WidgetTypes.%s not found", bugWidget)
	if not handled:
		realArgs.append(normalWidget)
		if bugData1 is not None:
			realArgs.append(normalData1)
		if bugData2 is not None:
			realArgs.append(normalData2)
	if args:
		realArgs.extend(args)
	return realArgs
Beispiel #24
0
	def storeSign (self, pPlot, ePlayer, szCaption):
		""" Stores sign data in the appropraite PlotSigns element. """
		thisKey = self.__getKey(pPlot)
		if not thisKey:
			BugUtil.warn("MapSigns.storeSign() could not determine valid keyname for Plot %s." % (str(pPlot)))
			return False
		if not thisKey in self.plotDict:
			self.plotDict[thisKey] = PlotSigns(pPlot)
		self.plotDict[thisKey].setSign(ePlayer, szCaption)
def getProposedTradeData(getFunc, addFunc):
    for index in range(MAX_TRADE_DATA):
        data = getFunc(index)
        if data:
            addFunc(data)
        else:
            break
    else:
        BugUtil.warn("DiplomacyUtil.getProposedTradeData - reached %d items, ignoring rest", MAX_TRADE_DATA)
Beispiel #26
0
def widgetVersion(version, bugWidget, bugData1=None, bugData2=None, *args):
    """
	Picks one of two WidgetTypes and parameters to return based on presence of BUG DLL and <version>.
	
	The bugWidget must be the name of the desired widget, e.g. "WIDGET_SET_PERCENT";
	the other widget should be the WidgetTypes constant, e.g. WidgetTypes.WIDGET_CHANGE_PERCENT.
	
	The default widget values are WidgetTypes.WIDGET_GENERAL, -1, -1. To specify a different set,
	pass them in as the 4th, 5th and 6th arguments.
	
	To return zero or one data values, pass None for the BUG values you want not to have returned;
	the same ones won't be returned if the BUG DLL isn't present. When overriding the non-BUG widget
	type, you must always pass in three values: the WidgetTypes and its two data values. The matching
	BUG ones that are None will not be returned, regardless of their own values.
	
	Any arguments after the widget arguments are added at the end of the returned tuple; use this
	when the function you are passing the arguments to takes more arguments after the widget values.
	
	Make sure to use a * to unpack the returned tuple when passing the arguments to your function.
	
	Example:
		screen.setButtonGFC( "MinCommerceRate", u"", "", 130, 50, 20, 20, 
							 *BugDll.widget("WIDGET_SET_PERCENT", eCommerce, 0, 
							 				WidgetTypes.WIDGET_CHANGE_PERCENT, eCommerce, -100, 
							 				ButtonStyles.BUTTON_STYLE_CITY_MINUS) )
	"""
    realArgs = []
    if len(args) >= 3 and isinstance(args[0], WidgetTypes):
        normalWidget, normalData1, normalData2 = args[:3]
        args = args[3:]
    else:
        normalWidget = WidgetTypes.WIDGET_GENERAL
        normalData1 = -1
        normalData2 = -1
    handled = False
    if isVersion(version):
        try:
            if isinstance(bugWidget, WidgetTypes):
                realArgs.append(bugWidget)
            else:
                realArgs.append(getattr(WidgetTypes, bugWidget))
            if bugData1 is not None:
                realArgs.append(bugData1)
            if bugData2 is not None:
                realArgs.append(bugData2)
            handled = True
        except AttributeError:
            BugUtil.warn("WidgetTypes.%s not found", bugWidget)
    if not handled:
        realArgs.append(normalWidget)
        if bugData1 is not None:
            realArgs.append(normalData1)
        if bugData2 is not None:
            realArgs.append(normalData2)
    if args:
        realArgs.extend(args)
    return realArgs
Beispiel #27
0
	def __init__(self, mod, id, andId=None, dll=None):
		self.mod = mod
		self.id = id
		self.andId = andId
		self.andOption = None
		self.dll = dll
		if self.dll is not None and self.dll <= 0:
			BugUtil.warn("BugOptions - %s has invalid dll value %r, ignoring", id, dll)
			self.dll = None
Beispiel #28
0
	def storeSign (self, pPlot, ePlayer, szCaption):
		""" Stores sign data in the appropraite PlotSigns element. """
		thisKey = self.__getKey(pPlot)
		if not thisKey:
			BugUtil.warn("MapSigns.storeSign() could not determine valid keyname for Plot %s." % (str(pPlot)))
			return False
		if not thisKey in self.plotDict:
			self.plotDict[thisKey] = PlotSigns(pPlot)
		self.plotDict[thisKey].setSign(ePlayer, szCaption)
Beispiel #29
0
	def resolveDll(self, element, dll):
		dll = BugDll.decode(dll)
		inherited = element.getState("dll")
		if dll is None:
			return inherited
		if inherited is None:
			return dll
		if inherited > dll:
			BugUtil.warn("BugConfig - element <%s>.dll attribute %s overrides newer inherited dll attribute %s" % (element.tag, dll, inherited))
		return dll
Beispiel #30
0
    def addEvent(self, eventType):
        """Creates a new event type without any handlers.

        Prints a warning if eventType is already defined.
        """
        if self.hasEvent(eventType):
            BugUtil.warn("BugEventManager - event '%s' already defined", eventType)
        else:
            BugUtil.debug("BugEventManager - adding event '%s'", eventType)
            self.EventHandlerMap[eventType] = []
Beispiel #31
0
def getOption(id):
	global g_options
	if g_options is None:
		import BugOptions
		g_options = BugOptions.g_options
		if g_options is None:
			import BugUtil
			BugUtil.warn("Cannot access BUG options")
			return None
	return g_options.getOption(id)
Beispiel #32
0
def getProposedTradeData(getFunc, addFunc):
	for index in range(MAX_TRADE_DATA):
		data = getFunc(index)
		if data:
			addFunc(data)
		else:
			break
	else:
		BugUtil.warn("DiplomacyUtil.getProposedTradeData - reached %d items, ignoring rest",
				MAX_TRADE_DATA)
Beispiel #33
0
	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 addEvent(self, eventType):
		"""Creates a new event type without any handlers.
		
		Prints a warning if eventType is already defined.
		"""
		if self.hasEvent(eventType):
			BugUtil.warn("BugEventManager - event '%s' already defined", eventType)
		else:
			BugUtil.debug("BugEventManager - adding event '%s'", eventType)
			self.EventHandlerMap[eventType] = []
Beispiel #35
0
	def resolveDll(self, element, dll):
		dll = BugDll.decode(dll)
		inherited = element.getState("dll")
		if dll is None:
			return inherited
		if inherited is None:
			return dll
		if inherited > dll:
			BugUtil.warn("BugConfig - element <%s>.dll attribute %s overrides newer inherited dll attribute %s" % (element.tag, dll, inherited))
		return dll
def _setWidgetHelp(widget, type, func):
	"""
	Registers the hover text <func> for <widget> if it hasn't been already.
	
	Do not call this function as it is used internally by the registration functions above.
	"""
	if widget in g_widgetHelp:
		BugUtil.warn("WidgetTypes %d help already registered", widget)
	else:
		BugUtil.debug("WidgetUtil - registering %s hover help for WidgetTypes %d: %s", type, widget, func)
		g_widgetHelp[widget] = func
def _setWidgetHelp(widget, type, func):
	"""
	Registers the hover text <func> for <widget> if it hasn't been already.
	
	Do not call this function as it is used internally by the registration functions above.
	"""
	if widget in g_widgetHelp:
		BugUtil.warn("WidgetTypes %d help already registered", widget)
	else:
		BugUtil.debug("WidgetUtil - registering %s hover help for WidgetTypes %d: %s", type, widget, func)
		g_widgetHelp[widget] = func
Beispiel #38
0
def format(player, trade):
    """Returns a single string containing all of the trade items separated by commas.
    
    player can be either an ID or CyPlayer and is needed when a city is being traded.
    """
    if isinstance(trade, list) or isinstance(trade, tuple) or isinstance(trade, set):
        return ", ".join([format(player, t) for t in trade])
    elif trade.ItemType in TRADE_FORMATS:
        return TRADE_FORMATS[trade.ItemType].format(player, trade)
    else:
        BugUtil.warn("TradeUtil - unknown item type %d", trade.ItemType)
        return ""
Beispiel #39
0
	def _addMod(self, mod):
		id = mod._getID()
		if self._inited:
			BugUtil.warn("BugCore - cannot add mod %s post-init", id)
		elif id in self._emptyMods:
			if not mod._inited:
				BugUtil.error("BugCore - mod %s not initialized", id)
			del self._emptyMods[id]
		elif id in self._mods:
			BugUtil.error("BugCore - mod %s already exists", id)
		else:
			self._mods[id] = mod
Beispiel #40
0
 def _addMod(self, mod):
     id = mod._getID()
     if self._inited:
         BugUtil.warn("BugCore - cannot add mod %s post-init", id)
     elif id in self._emptyMods:
         if not mod._inited:
             BugUtil.error("BugCore - mod %s not initialized", id)
         del self._emptyMods[id]
     elif id in self._mods:
         BugUtil.error("BugCore - mod %s already exists", id)
     else:
         self._mods[id] = mod
def format(player, trade):
	"""Returns a single string containing all of the trade items separated by commas.
	
	player can be either an ID or CyPlayer and is needed when a city is being traded.
	"""
	if isinstance(trade, list) or isinstance(trade, tuple) or isinstance(trade, set):
		return ", ".join([format(player, t) for t in trade])
	elif trade.ItemType in TRADE_FORMATS:
		return TRADE_FORMATS[trade.ItemType].format(player, trade)
	else:
		BugUtil.warn("TradeUtil - unknown item type %d", trade.ItemType)
		return ""
Beispiel #42
0
	def removePopupHandler(self, eventType):
		"""Removes all previously installed popup handlers for the given
		event type.

		The eventType should be an integer. It is an error to fire this
		eventType after removing its handlers.
		"""
		if eventType in self.Events:
			BugUtil.debug("BugEventManager - removing popup handler for event %d", eventType)
			del self.Events[eventType]
		else:
			BugUtil.warn("BugEventManager - event %d has no popup handler", eventType)
	def removeCity(self, ePlayer, city):
		"""
		Removes the city from the data set and erases its dot and cross.
		"""
		if city:
			BugUtil.debug("DotMap - removing city %s", city)
			del self.getCities(ePlayer)[city.point]
			self.dirty = True
			if ePlayer == PlayerUtil.getActivePlayerID():
				self.redrawCrosses(city.layer)
				self.eraseDot(city, self.DOT_ALPHA)
		else:
			BugUtil.warn("City doesn't exist")
Beispiel #44
0
    def removeCity(self, ePlayer, city):
        """
		Removes the city from the data set and erases its dot and cross.
		"""
        if city:
            BugUtil.debug("DotMap - removing city %s", city)
            del self.getCities(ePlayer)[city.point]
            self.dirty = True
            if ePlayer == PlayerUtil.getActivePlayerID():
                self.redrawCrosses(city.layer)
                self.eraseDot(city, self.DOT_ALPHA)
        else:
            BugUtil.warn("City doesn't exist")
	def removePopupHandler(self, eventType):
		"""Removes all previously installed popup handlers for the given 
		event type.
		
		The eventType should be an integer. It is an error to fire this
		eventType after removing its handlers.

		"""
		if eventType in self.Events:
			BugUtil.debug("BugEventManager - removing popup handler for event %d", eventType)
			del self.Events[eventType]
		else:
			BugUtil.warn("BugEventManager - event %d has no popup handler", eventType)
Beispiel #46
0
	def __init__(self, mod, id, andId=None, dll=None):
		self.mod = mod
		self.id = id
		self.andId = andId
		self.andOption = None
		self.dll = BugDll.decode(dll)
		if self.dll is not None and self.dll <= 0:
			BugUtil.warn("BugOptions - %s has invalid dll value %r, ignoring", id, dll)
			self.dll = None
		self.enabled = True
		if self.dll > 0:
			if not BugDll.isVersion(self.dll):
				self.enabled = False
Beispiel #47
0
def getFilePath(root, name, subdir=None):
    """
	Returns the full path to the named file, or None if it doesn't exist.
	"""
    if not root:
        BugUtil.warn("Invalid root directory looking for '%s'", name)
    if subdir:
        path = join(root, subdir, name)
    else:
        path = join(root, name)
    if isfile(path):
        return path
    safeDebugPath("BugPath - not a file: '%s'", path)
    return None
Beispiel #48
0
def findAssetFile(name, subdir=None):
    """
	Returns the full path to the named asset file by searching the paths above.
	"""
    initSearchPaths()
    for dir in _assetFileSearchPaths:
        path = getFilePath(dir, name, subdir)
        if path:
            return path
    if subdir:
        BugUtil.warn("BugPath - cannot find asset file %s in %s", name, subdir)
    else:
        BugUtil.warn("BugPath - cannot find asset file %s", name)
    return None
def getFilePath(root, name, subdir=None):
    """
	Returns the full path to the named file, or None if it doesn't exist.
	"""
    if not root:
        BugUtil.warn("Invalid root directory looking for '%s'", name)
    if subdir:
        path = join(root, subdir, name)
    else:
        path = join(root, name)
    if isfile(path):
        return path
    safeDebugPath("BugPath - not a file: '%s'", path)
    return None
def findAssetFile(name, subdir=None):
    """
	Returns the full path to the named asset file by searching the paths above.
	"""
    initSearchPaths()
    for dir in _assetFileSearchPaths:
        path = getFilePath(dir, name, subdir)
        if path:
            return path
    if subdir:
        BugUtil.warn("BugPath - cannot find asset file %s in %s", name, subdir)
    else:
        BugUtil.warn("BugPath - cannot find asset file %s", name)
    return None
    def displaySign(self, pPlot, ePlayer):
        """ Displays stored sign for given player at given plot based on revealed status.
		If there's a pre-existing sign, engine.addSign will silently fail, leaving the plot unchanged.
		"""
        if not g_bShowSigns:
            BugUtil.debug(
                "MapSigns.displaySign() called but EventSigns is disabled.")
            return False
        if not pPlot or pPlot.isNone():
            BugUtil.warn(
                "MapSigns.displaySign() was passed an invalid plot: %s" %
                (str(pPlot)))
            return False
        thisKey = self.__getKey(pPlot)
        szCaption = ""
        if self.hasPlotSigns(pPlot):
            szCaption = self.plotDict[thisKey].getSign(ePlayer)
        else:
            #BugUtil.debug("MapSigns.displaySign() could not show sign; we don't have any saved signs on plot %s" % (str(thisKey)))
            return False
        if not szCaption:
            BugUtil.debug(
                "MapSigns.displaySign() could not show sign; no caption found for player %d on plot %s"
                % (ePlayer, str(thisKey)))
            return False
        if ePlayer == -1:
            BugUtil.debug(
                "MapSigns.displaySign() landmark (%s) shown on plot %s" %
                (szCaption, ePlayer, str(thisKey)))
            engine.addLandmark(pPlot, szCaption.encode('latin_1'))
        else:
            pPlayer = gc.getPlayer(ePlayer)
            if not pPlayer or pPlayer.isNone():
                BugUtil.warn(
                    "MapSigns.displaySign() was passed an invalid player id: %s"
                    % (str(ePlayer)))
                return False
            eTeam = pPlayer.getTeam()
            if pPlot.isRevealed(eTeam, False):
                BugUtil.debug(
                    "MapSigns.displaySign() sign (%s) shown for player %d on plot %s"
                    % (szCaption, ePlayer, str(thisKey)))
                engine.addSign(pPlot, ePlayer, szCaption.encode('latin_1'))
                return True
            else:
                BugUtil.debug(
                    "MapSigns.displaySign() could not show sign; player %d cannot see plot %s"
                    % (ePlayer, str(thisKey)))
        return False
Beispiel #52
0
def addSign (pPlot, ePlayer, szCaption):
	""" Wrapper for CyEngine.addSign() which stores sign data. 
	If -1 is passed for ePlayer, the sign is assumed to be a landmark that everyone can see.
	"""
	#BugUtil.debug("EventSigns.addSign(pPlot = %s, ePlayer = %s, szCaption = %s)" % (str(pPlot), str(ePlayer), szCaption))
	if not pPlot or pPlot.isNone():
		BugUtil.warn("EventSigns.addSign() was passed an invalid plot: %s" % (str(pPlot)))
		return False
	if gSavedSigns == None:
		BugUtil.warn("EventSigns.addSign() gSavedSigns is not initialized!")
		return False
	gSavedSigns.storeSign(pPlot, ePlayer, szCaption)
	gSavedSigns.displaySign(pPlot, ePlayer)
	SdToolKit.sdSetGlobal(SD_MOD_ID, SD_VAR_ID, gSavedSigns)
	return True
Beispiel #53
0
def addSign (pPlot, ePlayer, szCaption):
	""" Wrapper for CyEngine.addSign() which stores sign data. 
	If -1 is passed for ePlayer, the sign is assumed to be a landmark that everyone can see.
	"""
	#BugUtil.debug("EventSigns.addSign(pPlot = %s, ePlayer = %s, szCaption = %s)" % (str(pPlot), str(ePlayer), szCaption))
	if not pPlot or pPlot.isNone():
		BugUtil.warn("EventSigns.addSign() was passed an invalid plot: %s" % (str(pPlot)))
		return False
	if gSavedSigns == None:
		BugUtil.warn("EventSigns.addSign() gSavedSigns is not initialized!")
		return False
	gSavedSigns.storeSign(pPlot, ePlayer, szCaption)
	gSavedSigns.displaySign(pPlot, ePlayer)
	SdToolKit.sdSetGlobal(SD_MOD_ID, SD_VAR_ID, gSavedSigns)
	return True
Beispiel #54
0
def load():
    global g_values, g_iTurn
    clear()
    data = BugData.getTable(SD_MOD_ID).data
    BugUtil.debug("SpyUtil - loaded: %s", data)
    if SD_VERSION_ID in data:
        if data[SD_VERSION_ID] == 1:
            g_iTurn = data[SD_TURN_ID]
            if g_iTurn != gc.getGame().getGameTurn() - 1:
                BugUtil.warn("SpyUtil - incorrect previous game turn found, ignoring")
            else:
                g_values = data[SD_VALUES_ID]
        elif data[SD_VERSION_ID] > 1:
            BugUtil.warn("SpyUtil - newer format version detected, ignoring")
    else:
        BugUtil.debug("SpyUtil - no data found")
Beispiel #55
0
	def createColorComparerFunction(self, values):
		if values is None:
			BugUtil.warn("BugOptions - createColorComparerFunction() requires one or more values")
			return None
		else:
			if isinstance(values, (types.TupleType, types.ListType)):
				if len(values) == 1:
					return self.createColorComparerFunction(values[0])
				else:
					def contains(*args):
						return self.getColor(*args) in values
					return contains
			else:
				value = self.asType(values)
				def equals(*args):
					return self.getColor(*args) == value
				return equals
def createWidget(name):
	"""
	Creates and returns the next unique WidgetTypes constant to be used with custom UI widgets.
	
	If <name> already exists, a warning is logged and the widget is returned.
	Otherwise the new widget is assigned to WidgetTypes.<name> and returned.
	"""
	if hasattr(WidgetTypes, name):
		BugUtil.warn("WidgetTypes.%s already exists", name)
		return getattr(WidgetTypes, name)
	else:
		global g_nextWidget
		BugUtil.info("WidgetUtil - WidgetTypes.%s = %d", name, g_nextWidget)
		widget = WidgetTypes(g_nextWidget)
		setattr(WidgetTypes, name, widget)
		g_nextWidget += 1
		return widget
def createWidget(name):
	"""
	Creates and returns the next unique WidgetTypes constant to be used with custom UI widgets.
	
	If <name> already exists, a warning is logged and the widget is returned.
	Otherwise the new widget is assigned to WidgetTypes.<name> and returned.
	"""
	if hasattr(WidgetTypes, name):
		BugUtil.warn("WidgetTypes.%s already exists", name)
		return getattr(WidgetTypes, name)
	else:
		global g_nextWidget
		BugUtil.info("WidgetUtil - WidgetTypes.%s = %d", name, g_nextWidget)
		widget = WidgetTypes(g_nextWidget)
		setattr(WidgetTypes, name, widget)
		g_nextWidget += 1
		return widget
Beispiel #58
0
def addSymbol(key, ordinal, name=None):
	global nextSymbolID
	symbol = FontSymbols(nextSymbolID)
	nextSymbolID += 1
	registerSymbol(key, symbol, ordinal)
	if not name:
		name = key.upper().replace(" ", "_")
	else:
		name = name.upper().replace(" ", "_")
	registerSymbolSynonym(key, symbol, name)
	name += "_CHAR"
	registerSymbolSynonym(key, symbol, name)
	if name in FontSymbols.__dict__:
		BugUtil.warn("FontUtil - ignoring duplicate FontSymbols name %s", name)
	else:
		BugUtil.debug("FontUtil - mapping to FontSymbols.%s", name)
		setattr(FontSymbols, name, symbol)
	return symbol