Messenger.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. """Undocumented Module"""
  2. __all__ = ['Messenger']
  3. from PythonUtil import *
  4. from direct.directnotify import DirectNotifyGlobal
  5. import types
  6. # This one line will replace the cheesy hack below, when we remove the
  7. # hack.
  8. #from direct.stdpy.threading import Lock
  9. class Lock:
  10. """ This is a cheesy delayed implementation of Lock, designed to
  11. support the Toontown ActiveX launch, which must import Messenger
  12. before it has downloaded the rest of Panda. This is a TEMPORARY
  13. HACK, to be removed when the ActiveX launch is retired. """
  14. notify = DirectNotifyGlobal.directNotify.newCategory("Messenger.Lock")
  15. def __init__(self):
  16. self.locked = 0
  17. def acquire(self):
  18. # Before we download Panda, we can't use any threading
  19. # interfaces. So don't, until we observe that we have some
  20. # actual contention on the lock.
  21. if self.locked:
  22. # We have contention.
  23. return self.__getLock()
  24. # This relies on the fact that any individual Python statement
  25. # is atomic.
  26. self.locked += 1
  27. if self.locked > 1:
  28. # Whoops, we have contention.
  29. self.locked -= 1
  30. return self.__getLock()
  31. def release(self):
  32. if self.locked:
  33. # Still using the old, cheesy lock.
  34. self.locked -= 1
  35. return
  36. # The new lock must have been put in place.
  37. self.release = self.lock.release
  38. return self.lock.release()
  39. def __getLock(self):
  40. # Now that we've started Panda, it's safe to import the Mutex
  41. # class, which becomes our actual lock.
  42. # From now on, this lock will be used.
  43. self.notify.info("Acquiring Panda lock for the first time.")
  44. from pandac.PandaModules import Thread, Mutex
  45. self.__dict__.setdefault('lock', Mutex('Messenger'))
  46. self.lock.acquire()
  47. self.acquire = self.lock.acquire
  48. # Wait for the cheesy lock to be released before we return.
  49. self.notify.info("Waiting for cheesy lock to be released.")
  50. while self.locked:
  51. Thread.forceYield()
  52. self.notify.info("Got cheesy lock.")
  53. # We return with the lock acquired.
  54. class Messenger:
  55. notify = DirectNotifyGlobal.directNotify.newCategory("Messenger")
  56. def __init__(self):
  57. """
  58. One is keyed off the event name. It has the following structure:
  59. {event1: {object1: [method, extraArgs, persistent],
  60. object2: [method, extraArgs, persistent]},
  61. event2: {object1: [method, extraArgs, persistent],
  62. object2: [method, extraArgs, persistent]}}
  63. This dictionary allow for efficient callbacks when the messenger
  64. hears an event.
  65. A second dictionary remembers which objects are accepting which
  66. events. This allows for efficient ignoreAll commands.
  67. Or, for an example with more real data:
  68. {'mouseDown': {avatar: [avatar.jump, [2.0], 1]}}
  69. """
  70. # eventName->objMsgrId->callbackInfo
  71. self.__callbacks = {}
  72. # objMsgrId->set(eventName)
  73. self.__objectEvents = {}
  74. self._messengerIdGen = 0
  75. # objMsgrId->listenerObject
  76. self._id2object = {}
  77. # A mapping of taskChain -> eventList, used for sending events
  78. # across task chains (and therefore across threads).
  79. self._eventQueuesByTaskChain = {}
  80. # This protects the data structures within this object from
  81. # multithreaded access.
  82. self.lock = Lock()
  83. if __debug__:
  84. self.__isWatching=0
  85. self.__watching={}
  86. # I'd like this to be in the __debug__, but I fear that someone will
  87. # want this in a release build. If you're sure that that will not be
  88. # then please remove this comment and put the quiet/verbose stuff
  89. # under __debug__.
  90. self.quieting={"NewFrame":1,
  91. "avatarMoving":1,
  92. "event-loop-done":1,
  93. 'collisionLoopFinished':1,
  94. } # see def quiet()
  95. def _getMessengerId(self, object):
  96. # TODO: allocate this id in DirectObject.__init__ and get derived
  97. # classes to call down (speed optimization, assuming objects
  98. # accept/ignore more than once over their lifetime)
  99. # get unique messenger id for this object
  100. # assumes lock is held.
  101. if not hasattr(object, '_MSGRmessengerId'):
  102. object._MSGRmessengerId = (object.__class__.__name__, self._messengerIdGen)
  103. self._messengerIdGen += 1
  104. return object._MSGRmessengerId
  105. def _storeObject(self, object):
  106. # store reference-counted reference to object in case we need to
  107. # retrieve it later. assumes lock is held.
  108. id = self._getMessengerId(object)
  109. if id not in self._id2object:
  110. self._id2object[id] = [1, object]
  111. else:
  112. self._id2object[id][0] += 1
  113. def _getObject(self, id):
  114. return self._id2object[id][1]
  115. def _getObjects(self):
  116. self.lock.acquire()
  117. try:
  118. objs = []
  119. for refCount, obj in self._id2object.itervalues():
  120. objs.append(obj)
  121. return objs
  122. finally:
  123. self.lock.release()
  124. def _getNumListeners(self, event):
  125. return len(self.__callbacks.get(event, {}))
  126. def _getEvents(self):
  127. return self.__callbacks.keys()
  128. def _releaseObject(self, object):
  129. # assumes lock is held.
  130. id = self._getMessengerId(object)
  131. if id in self._id2object:
  132. record = self._id2object[id]
  133. record[0] -= 1
  134. if record[0] <= 0:
  135. del self._id2object[id]
  136. def accept(self, event, object, method, extraArgs=[], persistent=1):
  137. """ accept(self, string, DirectObject, Function, List, Boolean)
  138. Make this object accept this event. When the event is
  139. sent (using Messenger.send or from C++), method will be executed,
  140. optionally passing in extraArgs.
  141. If the persistent flag is set, it will continue to respond
  142. to this event, otherwise it will respond only once.
  143. """
  144. notifyDebug = Messenger.notify.getDebug()
  145. if notifyDebug:
  146. Messenger.notify.debug(
  147. "object: %s (%s)\n accepting: %s\n method: %s\n extraArgs: %s\n persistent: %s" %
  148. (safeRepr(object), self._getMessengerId(object), event, safeRepr(method),
  149. safeRepr(extraArgs), persistent))
  150. # Make sure that the method is callable
  151. assert hasattr(method, '__call__'), (
  152. "method not callable in accept (ignoring): %s %s"%
  153. (safeRepr(method), safeRepr(extraArgs)))
  154. # Make sure extraArgs is a list or tuple
  155. if not (isinstance(extraArgs, list) or isinstance(extraArgs, tuple) or isinstance(extraArgs, set)):
  156. raise TypeError, "A list is required as extraArgs argument"
  157. self.lock.acquire()
  158. try:
  159. acceptorDict = self.__callbacks.setdefault(event, {})
  160. id = self._getMessengerId(object)
  161. # Make sure we are not inadvertently overwriting an existing event
  162. # on this particular object.
  163. if id in acceptorDict:
  164. # TODO: we're replacing the existing callback. should this be an error?
  165. if notifyDebug:
  166. oldMethod = acceptorDict[id][0]
  167. if oldMethod == method:
  168. self.notify.warning(
  169. "object: %s was already accepting: \"%s\" with same callback: %s()" %
  170. (object.__class__.__name__, safeRepr(event), method.__name__))
  171. else:
  172. self.notify.warning(
  173. "object: %s accept: \"%s\" new callback: %s() supplanting old callback: %s()" %
  174. (object.__class__.__name__, safeRepr(event), method.__name__, oldMethod.__name__))
  175. acceptorDict[id] = [method, extraArgs, persistent]
  176. # Remember that this object is listening for this event
  177. eventDict = self.__objectEvents.setdefault(id, {})
  178. if event not in eventDict:
  179. self._storeObject(object)
  180. eventDict[event] = None
  181. finally:
  182. self.lock.release()
  183. def ignore(self, event, object):
  184. """ ignore(self, string, DirectObject)
  185. Make this object no longer respond to this event.
  186. It is safe to call even if it was not already accepting
  187. """
  188. if Messenger.notify.getDebug():
  189. Messenger.notify.debug(
  190. safeRepr(object) + ' (%s)\n now ignoring: ' % (self._getMessengerId(object), ) + safeRepr(event))
  191. self.lock.acquire()
  192. try:
  193. id = self._getMessengerId(object)
  194. # Find the dictionary of all the objects accepting this event
  195. acceptorDict = self.__callbacks.get(event)
  196. # If this object is there, delete it from the dictionary
  197. if acceptorDict and id in acceptorDict:
  198. del acceptorDict[id]
  199. # If this dictionary is now empty, remove the event
  200. # entry from the Messenger alltogether
  201. if (len(acceptorDict) == 0):
  202. del self.__callbacks[event]
  203. # This object is no longer listening for this event
  204. eventDict = self.__objectEvents.get(id)
  205. if eventDict and event in eventDict:
  206. del eventDict[event]
  207. if (len(eventDict) == 0):
  208. del self.__objectEvents[id]
  209. self._releaseObject(object)
  210. finally:
  211. self.lock.release()
  212. def ignoreAll(self, object):
  213. """
  214. Make this object no longer respond to any events it was accepting
  215. Useful for cleanup
  216. """
  217. if Messenger.notify.getDebug():
  218. Messenger.notify.debug(
  219. safeRepr(object) + ' (%s)\n now ignoring all events' % (self._getMessengerId(object), ))
  220. self.lock.acquire()
  221. try:
  222. id = self._getMessengerId(object)
  223. # Get the list of events this object is listening to
  224. eventDict = self.__objectEvents.get(id)
  225. if eventDict:
  226. for event in eventDict.keys():
  227. # Find the dictionary of all the objects accepting this event
  228. acceptorDict = self.__callbacks.get(event)
  229. # If this object is there, delete it from the dictionary
  230. if acceptorDict and id in acceptorDict:
  231. del acceptorDict[id]
  232. # If this dictionary is now empty, remove the event
  233. # entry from the Messenger alltogether
  234. if (len(acceptorDict) == 0):
  235. del self.__callbacks[event]
  236. self._releaseObject(object)
  237. del self.__objectEvents[id]
  238. finally:
  239. self.lock.release()
  240. def getAllAccepting(self, object):
  241. """
  242. Returns the list of all events accepted by the indicated object.
  243. """
  244. self.lock.acquire()
  245. try:
  246. id = self._getMessengerId(object)
  247. # Get the list of events this object is listening to
  248. eventDict = self.__objectEvents.get(id)
  249. if eventDict:
  250. return eventDict.keys()
  251. return []
  252. finally:
  253. self.lock.release()
  254. def isAccepting(self, event, object):
  255. """ isAccepting(self, string, DirectOject)
  256. Is this object accepting this event?
  257. """
  258. self.lock.acquire()
  259. try:
  260. acceptorDict = self.__callbacks.get(event)
  261. id = self._getMessengerId(object)
  262. if acceptorDict and id in acceptorDict:
  263. # Found it, return true
  264. return 1
  265. # If we looked in both dictionaries and made it here
  266. # that object must not be accepting that event.
  267. return 0
  268. finally:
  269. self.lock.release()
  270. def whoAccepts(self, event):
  271. """
  272. Return objects accepting the given event
  273. """
  274. return self.__callbacks.get(event)
  275. def isIgnoring(self, event, object):
  276. """ isIgnorning(self, string, DirectObject)
  277. Is this object ignoring this event?
  278. """
  279. return (not self.isAccepting(event, object))
  280. def send(self, event, sentArgs=[], taskChain = None):
  281. """
  282. Send this event, optionally passing in arguments
  283. event is usually a string.
  284. sentArgs is a list of any data that you want passed along to the
  285. handlers listening to this event.
  286. If taskChain is not None, it is the name of the task chain
  287. which should receive the event. If taskChain is None, the
  288. event is handled immediately. Setting a non-None taskChain
  289. will defer the event (possibly till next frame or even later)
  290. and create a new, temporary task within the named taskChain,
  291. but this is the only way to send an event across threads.
  292. """
  293. if Messenger.notify.getDebug() and not self.quieting.get(event):
  294. assert Messenger.notify.debug(
  295. 'sent event: %s sentArgs = %s, taskChain = %s' % (
  296. event, sentArgs, taskChain))
  297. self.lock.acquire()
  298. try:
  299. foundWatch=0
  300. if __debug__:
  301. if self.__isWatching:
  302. for i in self.__watching.keys():
  303. if str(event).find(i) >= 0:
  304. foundWatch=1
  305. break
  306. acceptorDict = self.__callbacks.get(event)
  307. if not acceptorDict:
  308. if __debug__:
  309. if foundWatch:
  310. print "Messenger: \"%s\" was sent, but no function in Python listened."%(event,)
  311. return
  312. if taskChain:
  313. # Queue the event onto the indicated task chain.
  314. from direct.task.TaskManagerGlobal import taskMgr
  315. queue = self._eventQueuesByTaskChain.setdefault(taskChain, [])
  316. queue.append((acceptorDict, event, sentArgs, foundWatch))
  317. if len(queue) == 1:
  318. # If this is the first (only) item on the queue,
  319. # spawn the task to empty it.
  320. taskMgr.add(self.__taskChainDispatch, name = 'Messenger-%s' % (taskChain),
  321. extraArgs = [taskChain], taskChain = taskChain,
  322. appendTask = True)
  323. else:
  324. # Handle the event immediately.
  325. self.__dispatch(acceptorDict, event, sentArgs, foundWatch)
  326. finally:
  327. self.lock.release()
  328. def __taskChainDispatch(self, taskChain, task):
  329. """ This task is spawned each time an event is sent across
  330. task chains. Its job is to empty the task events on the queue
  331. for this particular task chain. This guarantees that events
  332. are still delivered in the same order they were sent. """
  333. while True:
  334. eventTuple = None
  335. self.lock.acquire()
  336. try:
  337. queue = self._eventQueuesByTaskChain.get(taskChain, None)
  338. if queue:
  339. eventTuple = queue[0]
  340. del queue[0]
  341. if not queue:
  342. # The queue is empty, we're done.
  343. if queue is not None:
  344. del self._eventQueuesByTaskChain[taskChain]
  345. if not eventTuple:
  346. # No event; we're done.
  347. return task.done
  348. self.__dispatch(*eventTuple)
  349. finally:
  350. self.lock.release()
  351. return task.done
  352. def __dispatch(self, acceptorDict, event, sentArgs, foundWatch):
  353. for id in acceptorDict.keys():
  354. # We have to make this apparently redundant check, because
  355. # it is possible that one object removes its own hooks
  356. # in response to a handler called by a previous object.
  357. #
  358. # NOTE: there is no danger of skipping over objects due to
  359. # modifications to acceptorDict, since the for..in above
  360. # iterates over a list of objects that is created once at
  361. # the start
  362. callInfo = acceptorDict.get(id)
  363. if callInfo:
  364. method, extraArgs, persistent = callInfo
  365. # If this object was only accepting this event once,
  366. # remove it from the dictionary
  367. if not persistent:
  368. # This object is no longer listening for this event
  369. eventDict = self.__objectEvents.get(id)
  370. if eventDict and event in eventDict:
  371. del eventDict[event]
  372. if (len(eventDict) == 0):
  373. del self.__objectEvents[id]
  374. self._releaseObject(self._getObject(id))
  375. del acceptorDict[id]
  376. # If the dictionary at this event is now empty, remove
  377. # the event entry from the Messenger altogether
  378. if (event in self.__callbacks \
  379. and (len(self.__callbacks[event]) == 0)):
  380. del self.__callbacks[event]
  381. if __debug__:
  382. if foundWatch:
  383. print "Messenger: \"%s\" --> %s%s"%(
  384. event,
  385. self.__methodRepr(method),
  386. tuple(extraArgs + sentArgs))
  387. #print "Messenger: \"%s\" --> %s%s"%(
  388. # event,
  389. # self.__methodRepr(method),
  390. # tuple(extraArgs + sentArgs))
  391. # It is important to make the actual call here, after
  392. # we have cleaned up the accept hook, because the
  393. # method itself might call accept() or acceptOnce()
  394. # again.
  395. assert hasattr(method, '__call__')
  396. # Release the lock temporarily while we call the method.
  397. self.lock.release()
  398. try:
  399. method (*(extraArgs + sentArgs))
  400. finally:
  401. self.lock.acquire()
  402. def clear(self):
  403. """
  404. Start fresh with a clear dict
  405. """
  406. self.lock.acquire()
  407. try:
  408. self.__callbacks.clear()
  409. self.__objectEvents.clear()
  410. self._id2object.clear()
  411. finally:
  412. self.lock.release()
  413. def isEmpty(self):
  414. return (len(self.__callbacks) == 0)
  415. def getEvents(self):
  416. return self.__callbacks.keys()
  417. def replaceMethod(self, oldMethod, newFunction):
  418. """
  419. This is only used by Finder.py - the module that lets
  420. you redefine functions with Control-c-Control-v
  421. """
  422. import new
  423. retFlag = 0
  424. for entry in self.__callbacks.items():
  425. event, objectDict = entry
  426. for objectEntry in objectDict.items():
  427. object, params = objectEntry
  428. method = params[0]
  429. if (type(method) == types.MethodType):
  430. function = method.im_func
  431. else:
  432. function = method
  433. #print ('function: ' + repr(function) + '\n' +
  434. # 'method: ' + repr(method) + '\n' +
  435. # 'oldMethod: ' + repr(oldMethod) + '\n' +
  436. # 'newFunction: ' + repr(newFunction) + '\n')
  437. if (function == oldMethod):
  438. newMethod = new.instancemethod(
  439. newFunction, method.im_self, method.im_class)
  440. params[0] = newMethod
  441. # Found it retrun true
  442. retFlag += 1
  443. # didn't find that method, return false
  444. return retFlag
  445. def toggleVerbose(self):
  446. isVerbose = 1 - Messenger.notify.getDebug()
  447. Messenger.notify.setDebug(isVerbose)
  448. if isVerbose:
  449. print "Verbose mode true. quiet list = %s"%(
  450. self.quieting.keys(),)
  451. if __debug__:
  452. def watch(self, needle):
  453. """
  454. return a matching event (needle) if found (in haystack).
  455. This is primarily a debugging tool.
  456. This is intended for debugging use only.
  457. This function is not defined if python is ran with -O (optimize).
  458. See Also: unwatch
  459. """
  460. if not self.__watching.get(needle):
  461. self.__isWatching += 1
  462. self.__watching[needle]=1
  463. def unwatch(self, needle):
  464. """
  465. return a matching event (needle) if found (in haystack).
  466. This is primarily a debugging tool.
  467. This is intended for debugging use only.
  468. This function is not defined if python is ran with -O (optimize).
  469. See Also: watch
  470. """
  471. if self.__watching.get(needle):
  472. self.__isWatching -= 1
  473. del self.__watching[needle]
  474. def quiet(self, message):
  475. """
  476. When verbose mode is on, don't spam the output with messages
  477. marked as quiet.
  478. This is primarily a debugging tool.
  479. This is intended for debugging use only.
  480. This function is not defined if python is ran with -O (optimize).
  481. See Also: unquiet
  482. """
  483. if not self.quieting.get(message):
  484. self.quieting[message]=1
  485. def unquiet(self, message):
  486. """
  487. Remove a message from the list of messages that are not reported
  488. in verbose mode.
  489. This is primarily a debugging tool.
  490. This is intended for debugging use only.
  491. This function is not defined if python is ran with -O (optimize).
  492. See Also: quiet
  493. """
  494. if self.quieting.get(message):
  495. del self.quieting[message]
  496. def find(self, needle):
  497. """
  498. return a matching event (needle) if found (in haystack).
  499. This is primarily a debugging tool.
  500. """
  501. keys = self.__callbacks.keys()
  502. keys.sort()
  503. for event in keys:
  504. if repr(event).find(needle) >= 0:
  505. print self.__eventRepr(event),
  506. return {event: self.__callbacks[event]}
  507. def findAll(self, needle, limit=None):
  508. """
  509. return a dict of events (needle) if found (in haystack).
  510. limit may be None or an integer (e.g. 1).
  511. This is primarily a debugging tool.
  512. """
  513. matches = {}
  514. keys = self.__callbacks.keys()
  515. keys.sort()
  516. for event in keys:
  517. if repr(event).find(needle) >= 0:
  518. print self.__eventRepr(event),
  519. matches[event] = self.__callbacks[event]
  520. # if the limit is not None, decrement and
  521. # check for break:
  522. if limit > 0:
  523. limit -= 1
  524. if limit == 0:
  525. break
  526. return matches
  527. def __methodRepr(self, method):
  528. """
  529. return string version of class.method or method.
  530. """
  531. if (type(method) == types.MethodType):
  532. functionName = method.im_class.__name__ + '.' + \
  533. method.im_func.__name__
  534. else:
  535. functionName = method.__name__
  536. return functionName
  537. def __eventRepr(self, event):
  538. """
  539. Compact version of event, acceptor pairs
  540. """
  541. str = event.ljust(32) + '\t'
  542. acceptorDict = self.__callbacks[event]
  543. for key, (method, extraArgs, persistent) in acceptorDict.items():
  544. str = str + self.__methodRepr(method) + ' '
  545. str = str + '\n'
  546. return str
  547. def __repr__(self):
  548. """
  549. Compact version of event, acceptor pairs
  550. """
  551. str = "The messenger is currently handling:\n" + "="*64 + "\n"
  552. keys = self.__callbacks.keys()
  553. keys.sort()
  554. for event in keys:
  555. str += self.__eventRepr(event)
  556. # Print out the object: event dictionary too
  557. str += "="*64 + "\n"
  558. for key, eventDict in self.__objectEvents.items():
  559. object = self._getObject(key)
  560. str += "%s:\n" % repr(object)
  561. for event in eventDict.keys():
  562. str += " %s\n" % repr(event)
  563. str += "="*64 + "\n" + "End of messenger info.\n"
  564. return str
  565. def detailedRepr(self):
  566. """
  567. Print out the table in a detailed readable format
  568. """
  569. import types
  570. str = 'Messenger\n'
  571. str = str + '='*50 + '\n'
  572. keys = self.__callbacks.keys()
  573. keys.sort()
  574. for event in keys:
  575. acceptorDict = self.__callbacks[event]
  576. str = str + 'Event: ' + event + '\n'
  577. for key in acceptorDict.keys():
  578. function, extraArgs, persistent = acceptorDict[key]
  579. object = self._getObject(key)
  580. if (type(object) == types.InstanceType):
  581. className = object.__class__.__name__
  582. else:
  583. className = "Not a class"
  584. functionName = function.__name__
  585. str = (str + '\t' +
  586. 'Acceptor: ' + className + ' instance' + '\n\t' +
  587. 'Function name:' + functionName + '\n\t' +
  588. 'Extra Args: ' + repr(extraArgs) + '\n\t' +
  589. 'Persistent: ' + repr(persistent) + '\n')
  590. # If this is a class method, get its actual function
  591. if (type(function) == types.MethodType):
  592. str = (str + '\t' +
  593. 'Method: ' + repr(function) + '\n\t' +
  594. 'Function: ' + repr(function.im_func) + '\n')
  595. else:
  596. str = (str + '\t' +
  597. 'Function: ' + repr(function) + '\n')
  598. str = str + '='*50 + '\n'
  599. return str