class Notifier: serverDelta = 0 # If this object is set to something, it is used to print output # messages instead of writing them to the console. This is # particularly useful for integrating the Python notify system # with the C++ notify system. streamWriter = None if ConfigVariableBool('notify-integrate', True): streamWriter = StreamWriter(Notify.out(), False) showTime = ConfigVariableBool('notify-timestamp', False) def __init__(self, name, logger=None): """ name is a string logger is a Logger Create a new instance of the Notifier class with a given name and an optional Logger class for piping output to. If no logger specified, use the global default """ self.__name = name if (logger==None): self.__logger = defaultLogger else: self.__logger = logger # Global default levels are initialized here self.__info = 1 self.__warning = 1 self.__debug = 0 self.__logging = 0 def setServerDelta(self, delta, timezone): """ Call this method on any Notify object to globally change the timestamp printed for each line of all Notify objects. This synchronizes the timestamp with the server's known time of day, and also switches into the server's timezone. """ delta = int(round(delta)) Notifier.serverDelta = delta + time.timezone - timezone # The following call is necessary to make the output from C++ # notify messages show the same timestamp as those generated # from Python-level notify messages. NotifyCategory.setServerDelta(self.serverDelta) self.info("Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server." % (PythonUtil.formatElapsedSeconds(delta), (time.timezone - timezone) / 3600)) def getTime(self): """ Return the time as a string suitable for printing at the head of any notify message """ # for some strange reason, time.time() updates only once/minute if # the task is out of focus on win32. time.clock doesn't have this problem. return time.strftime(":%m-%d-%Y %H:%M:%S ", time.localtime(time.time() + self.serverDelta)) def getOnlyTime(self): """ Return the time as a string. The Only in the name is referring to not showing the date. """ return time.strftime("%H:%M:%S", time.localtime(time.time() + self.serverDelta)) def __str__(self): """ Print handling routine """ return "%s: info = %d, warning = %d, debug = %d, logging = %d" % \ (self.__name, self.__info, self.__warning, self.__debug, self.__logging) # Severity funcs def setSeverity(self, severity): from panda3d.core import NSDebug, NSInfo, NSWarning, NSError if severity >= NSError: self.setWarning(0) self.setInfo(0) self.setDebug(0) elif severity == NSWarning: self.setWarning(1) self.setInfo(0) self.setDebug(0) elif severity == NSInfo: self.setWarning(1) self.setInfo(1) self.setDebug(0) elif severity <= NSDebug: self.setWarning(1) self.setInfo(1) self.setDebug(1) def getSeverity(self): from panda3d.core import NSDebug, NSInfo, NSWarning, NSError if self.getDebug(): return NSDebug elif self.getInfo(): return NSInfo elif self.getWarning(): return NSWarning else: return NSError # error funcs def error(self, errorString, exception=StandardError): """ Raise an exception with given string and optional type: Exception: error """ message = str(errorString) if Notifier.showTime.getValue(): string = (self.getTime() + str(exception) + ": " + self.__name + "(error): " + message) else: string = (str(exception) + ": " + self.__name + "(error): " + message) self.__log(string) raise exception(errorString) # warning funcs def warning(self, warningString): """ Issue the warning message if warn flag is on """ if self.__warning: message = str(warningString) if Notifier.showTime.getValue(): string = (self.getTime() + self.__name + '(warning): ' + message) else: string = (":" + self.__name + '(warning): ' + message) self.__log(string) self.__print(string) return 1 # to allow assert myNotify.warning("blah") def setWarning(self, bool): """ Enable/Disable the printing of warning messages """ self.__warning = bool def getWarning(self): """ Return whether the printing of warning messages is on or off """ return(self.__warning) # debug funcs def debug(self, debugString): """ Issue the debug message if debug flag is on """ if self.__debug: message = str(debugString) if Notifier.showTime.getValue(): string = (self.getTime() + self.__name + '(debug): ' + message) else: string = (':' + self.__name + '(debug): ' + message) self.__log(string) self.__print(string) return 1 # to allow assert myNotify.debug("blah") def setDebug(self, bool): """ Enable/Disable the printing of debug messages """ self.__debug = bool def getDebug(self): """ Return whether the printing of debug messages is on or off """ return self.__debug # info funcs def info(self, infoString): """ Print the given informational string, if info flag is on """ if self.__info: message = str(infoString) if Notifier.showTime.getValue(): string = (self.getTime() + self.__name + ': ' + message) else: string = (':' + self.__name + ': ' + message) self.__log(string) self.__print(string) return 1 # to allow assert myNotify.info("blah") def getInfo(self): """ Return whether the printing of info messages is on or off """ return self.__info def setInfo(self, bool): """ Enable/Disable informational message printing """ self.__info = bool # log funcs def __log(self, logEntry): """ Determine whether to send informational message to the logger """ if self.__logging: self.__logger.log(logEntry) def getLogging(self): """ Return 1 if logging enabled, 0 otherwise """ return (self.__logging) def setLogging(self, bool): """ Set the logging flag to int (1=on, 0=off) """ self.__logging = bool def __print(self, string): """ Prints the string to output followed by a newline. """ if self.streamWriter: self.streamWriter.appendData(string + '\n') else: print >> sys.stderr, string def debugStateCall(self, obj=None, fsmMemberName='fsm', secondaryFsm='secondaryFSM'): """ If this notify is in debug mode, print the time of the call followed by the [fsm state] notifier category and the function call (with parameters). """ #f.f_locals['self'].__init__.im_class.__name__ if self.__debug: state = '' doId = '' if obj is not None: fsm=obj.__dict__.get(fsmMemberName) if fsm is not None: stateObj = fsm.getCurrentState() if stateObj is not None: #state = "%s=%s"%(fsmMemberName, stateObj.getName()) state = stateObj.getName() fsm=obj.__dict__.get(secondaryFsm) if fsm is not None: stateObj = fsm.getCurrentState() if stateObj is not None: #state = "%s=%s"%(fsmMemberName, stateObj.getName()) state = "%s, %s"%(state, stateObj.getName()) if hasattr(obj, 'doId'): doId = " doId:%s"%(obj.doId,) #if type(obj) == types.ClassType: # name = "%s."%(obj.__class__.__name__,) string = ":%s:%s [%-7s] id(%s)%s %s"%( self.getOnlyTime(), self.__name, state, id(obj), doId, PythonUtil.traceParentCall()) self.__log(string) self.__print(string) return 1 # to allow assert self.notify.debugStateCall(self) def debugCall(self, debugString=''): """ If this notify is in debug mode, print the time of the call followed by the notifier category and the function call (with parameters). """ if self.__debug: message = str(debugString) string = ":%s:%s \"%s\" %s"%( self.getOnlyTime(), self.__name, message, PythonUtil.traceParentCall()) self.__log(string) self.__print(string) return 1 # to allow assert self.notify.debugCall("blah")
value = cls._defaults[data_id] copier = cls._copiers.get(data_id) data[data_id] = copier(value) if copier else value # Global data - accessible from both the Core and the GUI - can be set and # retrieved through the following class. class GlobalData(metaclass=GlobalMeta): showbase = ShowBase( ) # instancing ShowBase here ensures that setting up Panda3D's # notify system afterwards will work as expected # make sure that Panda3D's notify system redirects its output to the designated log file Notifier.streamWriter = StreamWriter(Notify.out(), False) # Panda3D's notifiers are made accessible through the following class class Notifiers: @classmethod def create(cls, name): notifier = directNotify.newCategory(name) notifier.setSeverity(2) # "debug" level return notifier # Create Panda3D notifiers for different categories Notifiers.imprt = Notifiers.create("Import")
def __init__(self): DirectObject.__init__(self) # We direct both our stdout and stderr objects onto Panda's # Notify stream. This ensures that unadorned print statements # made within Python will get routed into the log properly. stream = StreamWriter(Notify.out(), False) sys.stdout = stream sys.stderr = stream # This is set true by dummyAppRunner(), below. self.dummy = False # These will be set from the application flags when # setP3DFilename() is called. self.allowPythonDev = False self.guiApp = False self.interactiveConsole = False self.initialAppImport = False self.trueFileIO = False self.respectPerPlatform = None self.verifyContents = self.P3DVCNone self.sessionId = 0 self.packedAppEnvironmentInitialized = False self.gotWindow = False self.gotP3DFilename = False self.p3dFilename = None self.p3dUrl = None self.started = False self.windowOpened = False self.windowPrc = None self.http = None if hasattr(core, 'HTTPClient'): self.http = core.HTTPClient.getGlobalPtr() self.Undefined = Undefined self.ConcreteStruct = ConcreteStruct # This is per session. self.nextScriptId = 0 # TODO: we need one of these per instance, not per session. self.instanceId = None # The root Panda3D install directory. This is filled in when # the instance starts up. self.rootDir = None # The log directory. Also filled in when the instance starts. self.logDirectory = None # self.superMirrorUrl, if nonempty, is the "super mirror" URL # that should be contacted first before trying the actual # host. This is primarily used for "downloading" from a # locally-stored Panda3D installation. This is also filled in # when the instance starts up. self.superMirrorUrl = None # A list of the Panda3D packages that have been loaded. self.installedPackages = [] # A list of the Panda3D packages that in the queue to be # downloaded. self.downloadingPackages = [] # A dictionary of HostInfo objects for the various download # hosts we have imported packages from. self.hosts = {} # The altHost string that is in effect from the HTML tokens, # if any, and the dictionary of URL remapping: orig host url # -> alt host url. self.altHost = None self.altHostMap = {} # The URL from which Panda itself should be downloaded. self.pandaHostUrl = PandaSystem.getPackageHostUrl() # Application code can assign a callable object here; if so, # it will be invoked when an uncaught exception propagates to # the top of the TaskMgr.run() loop. self.exceptionHandler = None # Managing packages for runtime download. self.downloadingPackages = [] self.downloadTask = None # The mount point for the multifile. For now, this is always # the current working directory, for convenience; but when we # move to multiple-instance sessions, it may have to be # different for each instance. self.multifileRoot = str(ExecutionEnvironment.getCwd()) # The "main" object will be exposed to the DOM as a property # of the plugin object; that is, document.pluginobject.main in # JavaScript will be appRunner.main here. This may be # replaced with a direct reference to the JavaScript object # later, in setInstanceInfo(). self.main = ScriptAttributes() # By default, we publish a stop() method so the browser can # easy stop the plugin. A particular application can remove # this if it chooses. self.main.stop = self.stop # This will be the browser's toplevel window DOM object; # e.g. self.dom.document will be the document. self.dom = None # This is the list of expressions we will evaluate when # self.dom gets assigned. self.deferredEvals = [] # This is the default requestFunc that is installed if we # never call setRequestFunc(). def defaultRequestFunc(*args): if args[1] == 'notify': # Quietly ignore notifies. return self.notify.info("Ignoring request: %s" % (args, )) self.requestFunc = defaultRequestFunc # This will be filled in with the default WindowProperties for # this instance, e.g. the WindowProperties necessary to # re-embed a window in the browser frame. self.windowProperties = None # Store our pointer so DirectStart-based apps can find us. if AppRunnerGlobal.appRunner is None: AppRunnerGlobal.appRunner = self # We use this messenger hook to dispatch this __startIfReady() # call back to the main thread. self.accept('AppRunner_startIfReady', self.__startIfReady)
class Notifier: serverDelta = 0 streamWriter = None if ConfigVariableBool('notify-integrate', True): streamWriter = StreamWriter(Notify.out(), False) showTime = ConfigVariableBool('notify-timestamp', False) def __init__(self, name, logger=None): self.__name = name if logger == None: self.__logger = defaultLogger else: self.__logger = logger self.__info = 1 self.__warning = 1 self.__debug = 0 self.__logging = 0 return def setServerDelta(self, delta, timezone): delta = int(round(delta)) Notifier.serverDelta = delta + time.timezone - timezone NotifyCategory.setServerDelta(self.serverDelta) self.info( 'Notify clock adjusted by %s (and timezone adjusted by %s hours) to synchronize with server.' % (PythonUtil.formatElapsedSeconds(delta), (time.timezone - timezone) / 3600)) def getTime(self): return time.strftime(':%m-%d-%Y %H:%M:%S ', time.localtime(time.time() + self.serverDelta)) def getOnlyTime(self): return time.strftime('%H:%M:%S', time.localtime(time.time() + self.serverDelta)) def __str__(self): return '%s: info = %d, warning = %d, debug = %d, logging = %d' % ( self.__name, self.__info, self.__warning, self.__debug, self.__logging) def setSeverity(self, severity): from panda3d.core import NSDebug, NSInfo, NSWarning, NSError if severity >= NSError: self.setWarning(0) self.setInfo(0) self.setDebug(0) else: if severity == NSWarning: self.setWarning(1) self.setInfo(0) self.setDebug(0) else: if severity == NSInfo: self.setWarning(1) self.setInfo(1) self.setDebug(0) else: if severity <= NSDebug: self.setWarning(1) self.setInfo(1) self.setDebug(1) def getSeverity(self): from panda3d.core import NSDebug, NSInfo, NSWarning, NSError if self.getDebug(): return NSDebug if self.getInfo(): return NSInfo if self.getWarning(): return NSWarning return NSError def error(self, errorString, exception=StandardError): message = str(errorString) if Notifier.showTime.getValue(): string = self.getTime() + str( exception) + ': ' + self.__name + '(error): ' + message else: string = str( exception) + ': ' + self.__name + '(error): ' + message self.__log(string) raise exception(errorString) def warning(self, warningString): if self.__warning: message = str(warningString) if Notifier.showTime.getValue(): string = self.getTime() + self.__name + '(warning): ' + message else: string = ':' + self.__name + '(warning): ' + message self.__log(string) self.__print(string) return 1 def setWarning(self, bool): self.__warning = bool def getWarning(self): return self.__warning def debug(self, debugString): if self.__debug: message = str(debugString) if Notifier.showTime.getValue(): string = self.getTime() + self.__name + '(debug): ' + message else: string = ':' + self.__name + '(debug): ' + message self.__log(string) self.__print(string) return 1 def setDebug(self, bool): self.__debug = bool def getDebug(self): return self.__debug def info(self, infoString): if self.__info: message = str(infoString) if Notifier.showTime.getValue(): string = self.getTime() + self.__name + ': ' + message else: string = ':' + self.__name + ': ' + message self.__log(string) self.__print(string) return 1 def getInfo(self): return self.__info def setInfo(self, bool): self.__info = bool def __log(self, logEntry): if self.__logging: self.__logger.log(logEntry) def getLogging(self): return self.__logging def setLogging(self, bool): self.__logging = bool def __print(self, string): if self.streamWriter: self.streamWriter.write(string + '\n') else: print >> sys.stderr, string def debugStateCall(self, obj=None, fsmMemberName='fsm', secondaryFsm='secondaryFSM'): if self.__debug: state = '' doId = '' if obj is not None: fsm = obj.__dict__.get(fsmMemberName) if fsm is not None: stateObj = fsm.getCurrentState() if stateObj is not None: state = stateObj.getName() fsm = obj.__dict__.get(secondaryFsm) if fsm is not None: stateObj = fsm.getCurrentState() if stateObj is not None: state = '%s, %s' % (state, stateObj.getName()) if hasattr(obj, 'doId'): doId = ' doId:%s' % (obj.doId, ) string = ':%s:%s [%-7s] id(%s)%s %s' % ( self.getOnlyTime(), self.__name, state, id(obj), doId, PythonUtil.traceParentCall()) self.__log(string) self.__print(string) return 1 def debugCall(self, debugString=''): if self.__debug: message = str(debugString) string = ':%s:%s "%s" %s' % (self.getOnlyTime(), self.__name, message, PythonUtil.traceParentCall()) self.__log(string) self.__print(string) return 1