Kodi plugin to to play various online streams (mostly Latvian)

wingdbstub.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #########################################################################
  2. """ wingdbstub.py -- Debug stub for debuggifying Python programs
  3. Copyright (c) 1999-2001, Archaeopteryx Software, Inc. All rights reserved.
  4. Written by Stephan R.A. Deibel and John P. Ehresman
  5. Usage:
  6. -----
  7. This is the file that Wing DB users copy into their python project
  8. directory if they want to be able to debug programs that are launched
  9. outside of the IDE (e.g., CGI scripts, in response to a browser page
  10. load).
  11. To use this, edit the configuration values below to match your
  12. Wing installation and requirements of your project.
  13. Then, add the following line to your code:
  14. import wingdbstub
  15. Debugging will start immediately after this import statements.
  16. Next make sure that your IDE is running and that it's configured to accept
  17. connections from the host the debug program will be running on.
  18. Now, invoking your python file should run the code within the debugger.
  19. Note, however, that Wing will not stop in the code unless a breakpoint
  20. is set.
  21. If the debug process is started before the IDE, or is not listening
  22. at the time this module is imported then the program will run with
  23. debugging until an attach request is seen. Attaching only works
  24. if the .wingdebugpw file is present; see the manual for details.
  25. On win32, you either need to edit WINGHOME in this script or
  26. pass in an environment variable called WINGHOME that points to
  27. the Wing installation directory.
  28. """
  29. #########################################################################
  30. import sys
  31. import os
  32. import imp
  33. #------------------------------------------------------------------------
  34. # Default configuration values: Note that the named environment
  35. # variables, if set, will override these settings.
  36. # Set this to 1 to disable all debugging; 0 to enable debugging
  37. # (WINGDB_DISABLED environment variable)
  38. kWingDebugDisabled = 0
  39. # Host:port of the IDE within which to debug: As configured in the IDE
  40. # with the Server Port preference
  41. # (WINGDB_HOSTPORT environment variable)
  42. kWingHostPort = 'localhost:50005'
  43. # Port on which to listen for connection requests, so that the
  44. # IDE can (re)attach to the debug process after it has started.
  45. # Set this to '-1' to disable listening for connection requests.
  46. # This is only used when the debug process is not attached to
  47. # an IDE or the IDE has dropped its connection. The configured
  48. # port can optionally be added to the IDE's Common Attach Hosts
  49. # preference. Note that a random port is used instead if this
  50. # port is already in use!
  51. # (WINGDB_ATTACHPORT environment variable)
  52. kAttachPort = '50015'
  53. # Set this to a filename to log verbose information about the debugger
  54. # internals to a file. If the file does not exist, it will be created
  55. # as long as its enclosing directory exists and is writeable. Use
  56. # "<stderr>" or "<stdout>". Note that "<stderr>" may cause problems
  57. # on win32 if the debug process is not running in a console.
  58. # (WINGDB_LOGFILE environment variable)
  59. kLogFile = None
  60. # Set to get a tremendous amount of logging from the debugger internals
  61. # (WINGDB_LOGVERYVERBOSE)
  62. kLogVeryVerbose = 0
  63. # Set this to 1 when debugging embedded scripts in an environment that
  64. # creates and reuses a Python instance across multiple script invocations:
  65. # It turns off automatic detection of program quit so that the debug session
  66. # can span multiple script invocations. When this is turned on, you may
  67. # need to call ProgramQuit() on the debugger object to shut down the
  68. # debugger cleanly when your application exits or discards the Python
  69. # instance. If multiple Python instances are created in the same run,
  70. # only the first one will be able to debug unless it terminates debug
  71. # and the environment variable WINGDB_ACTIVE is unset before importing
  72. # this module in the second or later Python instance. See the Wing
  73. # IDE manual for details.
  74. kEmbedded = 0
  75. # Path to search for the debug password file and the name of the file
  76. # to use. The password file contains the encryption type and connect
  77. # password for all connections to the IDE and must match the wingdebugpw
  78. # file in the profile dir used by the IDE. Any entry of '$<winguserprofile>'
  79. # is replaced by the wing user profile directory for the user that the
  80. # current process is running as
  81. # (WINGDB_PWFILEPATH environment variable)
  82. kPWFilePath = [os.path.dirname(__file__), '$<winguserprofile>']
  83. kPWFileName = 'wingdebugpw'
  84. # Whether to exit if the debugger fails to run or to connect with an IDE
  85. # for whatever reason
  86. kExitOnFailure = 0
  87. #------------------------------------------------------------------------
  88. # Find Wing debugger installation location
  89. # Edit this to point to your Wing installation or set to None to use env WINGHOME
  90. # On OS X this must be set to name of the Wing application bundle
  91. # (for example, /Applications/WingIDE.app)
  92. WINGHOME = None
  93. if sys.hexversion >= 0x03000000:
  94. def has_key(o, key):
  95. return key in o
  96. else:
  97. def has_key(o, key):
  98. return o.has_key(key)
  99. # Check environment: Must have WINGHOME defined if still == None
  100. if WINGHOME == None:
  101. if has_key(os.environ, 'WINGHOME'):
  102. WINGHOME=os.environ['WINGHOME']
  103. else:
  104. sys.stdout.write("*******************************************************************\n")
  105. sys.stdout.write("Error: Could not find Wing installation! You must set WINGHOME or edit\n")
  106. sys.stdout.write("wingdbstub.py where indicated to point it to the location where\n")
  107. sys.stdout.write("Wing is installed.\n")
  108. sys.exit(1)
  109. kPWFilePath.append(WINGHOME)
  110. # The user settings dir where per-user settings & patches are located. Will be
  111. # set from environment if left as None
  112. kUserSettingsDir = None
  113. if kUserSettingsDir is None:
  114. kUserSettingsDir = os.environ.get('WINGDB_USERSETTINGS')
  115. def _FindActualWingHome(winghome):
  116. """ Find the actual directory to use for winghome. Needed on OS X
  117. where the .app directory is the preferred dir to use for WINGHOME and
  118. .app/Contents/MacOS is accepted for backward compatibility. """
  119. if sys.platform != 'darwin':
  120. return winghome
  121. app_dir = None
  122. if os.path.isdir(winghome):
  123. if winghome.endswith('/'):
  124. wo_slash = winghome[:-1]
  125. else:
  126. wo_slash = winghome
  127. if wo_slash.endswith('.app'):
  128. app_dir = wo_slash
  129. elif wo_slash.endswith('.app/Contents/MacOS'):
  130. app_dir = wo_slash[:-len('/Contents/MacOS')]
  131. if app_dir and os.path.isdir(os.path.join(app_dir, 'Contents', 'Resources')):
  132. return os.path.join(app_dir, 'Contents', 'Resources')
  133. return winghome
  134. def _ImportWingdb(winghome, user_settings=None):
  135. """ Find & import wingdb module. """
  136. try:
  137. exec_dict = {}
  138. execfile(os.path.join(winghome, 'bin', '_patchsupport.py'), exec_dict)
  139. find_matching = exec_dict['FindMatching']
  140. dir_list = find_matching('bin', winghome, user_settings)
  141. except Exception:
  142. dir_list = []
  143. dir_list.extend([os.path.join(winghome, 'bin'), os.path.join(winghome, 'src')])
  144. for path in dir_list:
  145. try:
  146. f, p, d = imp.find_module('wingdb', [path])
  147. try:
  148. return imp.load_module('wingdb', f, p, d)
  149. finally:
  150. if f is not None:
  151. f.close()
  152. break
  153. except ImportError:
  154. pass
  155. #------------------------------------------------------------------------
  156. # Set debugger if it hasn't been set -- this is to handle module reloading
  157. # In the reload case, the debugger variable will be set to something
  158. try:
  159. debugger
  160. except NameError:
  161. debugger = None
  162. # Unset WINGDB_ACTIVE env if it was inherited from another process
  163. # XXX Would be better to be able to call getpid() on dbgtracer but can't access it yet
  164. if 'WINGDB_ACTIVE' in os.environ and os.environ['WINGDB_ACTIVE'] != str(os.getpid()):
  165. del os.environ['WINGDB_ACTIVE']
  166. # Start debugging if not disabled and this module has never been imported
  167. # before
  168. if (not kWingDebugDisabled and debugger is None
  169. and not has_key(os.environ, 'WINGDB_DISABLED') and
  170. not has_key(os.environ, 'WINGDB_ACTIVE')):
  171. exit_on_fail = 0
  172. try:
  173. # Obtain exit if fails value
  174. exit_on_fail = os.environ.get('WINGDB_EXITONFAILURE', kExitOnFailure)
  175. # Obtain configuration for log file to use, if any
  176. logfile = os.environ.get('WINGDB_LOGFILE', kLogFile)
  177. if logfile == '-' or logfile == None or len(logfile.strip()) == 0:
  178. logfile = None
  179. very_verbose_log = os.environ.get('WINGDB_LOGVERYVERBOSE', kLogVeryVerbose)
  180. if type(very_verbose_log) == type('') and very_verbose_log.strip() == '':
  181. very_verbose_log = 0
  182. # Determine remote host/port where the IDE is running
  183. hostport = os.environ.get('WINGDB_HOSTPORT', kWingHostPort)
  184. colonpos = hostport.find(':')
  185. host = hostport[:colonpos]
  186. port = int(hostport[colonpos+1:])
  187. # Determine port to listen on locally for attach requests
  188. attachport = int(os.environ.get('WINGDB_ATTACHPORT', kAttachPort))
  189. # Check if running embedded script
  190. embedded = int(os.environ.get('WINGDB_EMBEDDED', kEmbedded))
  191. # Obtain debug password file search path
  192. if has_key(os.environ, 'WINGDB_PWFILEPATH'):
  193. pwfile_path = os.environ['WINGDB_PWFILEPATH'].split(os.pathsep)
  194. else:
  195. pwfile_path = kPWFilePath
  196. # Obtain debug password file name
  197. if has_key(os.environ, 'WINGDB_PWFILENAME'):
  198. pwfile_name = os.environ['WINGDB_PWFILENAME']
  199. else:
  200. pwfile_name = kPWFileName
  201. # Load wingdb.py
  202. actual_winghome = _FindActualWingHome(WINGHOME)
  203. wingdb = _ImportWingdb(actual_winghome, kUserSettingsDir)
  204. if wingdb == None:
  205. sys.stdout.write("*******************************************************************\n")
  206. sys.stdout.write("Error: Cannot find wingdb.py in $(WINGHOME)/bin or $(WINGHOME)/src\n")
  207. sys.stdout.write("Error: Please check the WINGHOME definition in wingdbstub.py\n")
  208. sys.exit(2)
  209. # Find the netserver module and create an error stream
  210. netserver = wingdb.FindNetServerModule(actual_winghome, kUserSettingsDir)
  211. err = wingdb.CreateErrStream(netserver, logfile, very_verbose_log)
  212. # Start debugging
  213. debugger = netserver.CNetworkServer(host, port, attachport, err,
  214. pwfile_path=pwfile_path,
  215. pwfile_name=pwfile_name,
  216. autoquit=not embedded)
  217. debugger.StartDebug(stophere=0)
  218. os.environ['WINGDB_ACTIVE'] = str(os.getpid())
  219. if debugger.ChannelClosed():
  220. raise ValueError('Not connected')
  221. except:
  222. if exit_on_fail:
  223. raise
  224. else:
  225. pass
  226. def Ensure(require_connection=1, require_debugger=1):
  227. """ Ensure the debugger is started and attempt to connect to the IDE if
  228. not already connected. Will raise a ValueError if:
  229. * the require_connection arg is true and the debugger is unable to connect
  230. * the require_debugger arg is true and the debugger cannot be loaded
  231. If SuspendDebug() has been called through the low-level API, calling
  232. Ensure() resets the suspend count to zero and additional calls to
  233. ResumeDebug() will be ignored until SuspendDebug() is called again.
  234. Note that a change to the host & port to connect to will only
  235. be use if a new connection is made.
  236. """
  237. if debugger is None:
  238. if require_debugger:
  239. raise ValueError("No debugger")
  240. return
  241. hostport = os.environ.get('WINGDB_HOSTPORT', kWingHostPort)
  242. colonpos = hostport.find(':')
  243. host = hostport[:colonpos]
  244. port = int(hostport[colonpos+1:])
  245. resumed = debugger.ResumeDebug()
  246. while resumed > 0:
  247. resumed = debugger.ResumeDebug()
  248. debugger.SetClientAddress((host, port))
  249. if not debugger.DebugActive():
  250. debugger.StartDebug()
  251. elif debugger.ChannelClosed():
  252. debugger.ConnectToClient()
  253. if require_connection and debugger.ChannelClosed():
  254. raise ValueError('Not connected')