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

wingdbstub.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. #########################################################################
  2. """ wingdbstub.py -- Start debugging Python programs from outside of Wing
  3. Copyright (c) 1999-2018, Archaeopteryx Software, Inc. All rights reserved.
  4. Written by Stephan R.A. Deibel and John P. Ehresman
  5. Usage:
  6. -----
  7. This file is used to initiate debug in Python code without launching
  8. that code from Wing. To use it, edit the configuration values below,
  9. start Wing and configure it to listen for outside debug connections,
  10. and then add the following line to your code:
  11. import wingdbstub
  12. Debugging will start immediately after this import statement is reached.
  13. For details, see Debugging Externally Launched Code in the manual.
  14. """
  15. #########################################################################
  16. import sys
  17. import os
  18. if sys.version_info >= (3, 7):
  19. import importlib
  20. else:
  21. import imp
  22. #------------------------------------------------------------------------
  23. # Required configuration values (some installers set this automatically)
  24. # This should be the full path to your Wing installation. On OS X, use
  25. # the full path of the Wing application bundle, for example
  26. # /Applications/WingIDE.app. When set to None, the environment variable
  27. # WINGHOME is used instead.
  28. WINGHOME = r"C:\Program Files (x86)\Wing IDE 6.1"
  29. #------------------------------------------------------------------------
  30. # Optional configuration values: The named environment variables, if set,
  31. # will override these settings.
  32. # Set this to 1 to disable all debugging; 0 to enable debugging
  33. # (WINGDB_DISABLED environment variable)
  34. kWingDebugDisabled = 0
  35. # Host:port of the IDE within which to debug: As configured in the IDE
  36. # with the Server Port preference
  37. # (WINGDB_HOSTPORT environment variable)
  38. kWingHostPort = 'localhost:50005'
  39. # Port on which to listen for connection requests, so that the
  40. # IDE can attach or reattach to the debug process after it has started.
  41. # Set this to '-1' to disable listening for connection requests.
  42. # This is only used when the debug process is not attached to
  43. # an IDE or the IDE has dropped its connection. The configured
  44. # port can optionally be added to the IDE's Common Attach Hosts
  45. # preference. Note that a random port is used instead if the given
  46. # port is already in use.
  47. # (WINGDB_ATTACHPORT environment variable)
  48. kAttachPort = '50015'
  49. # Set this to a filename to log verbose information about the debugger
  50. # internals to a file. If the file does not exist, it will be created
  51. # as long as its enclosing directory exists and is writeable. Use
  52. # "<stderr>" or "<stdout>" to write to stderr or stdout. Note that
  53. # "<stderr>" may cause problems on Windows if the debug process is not
  54. # running in a console.
  55. # (WINGDB_LOGFILE environment variable)
  56. kLogFile = None
  57. # Produce a tremendous amount of logging from the debugger internals.
  58. # Do not set this unless instructed to do so by Wingware support. It
  59. # will slow the debugger to a crawl.
  60. # (WINGDB_LOGVERYVERBOSE environment variable)
  61. kLogVeryVerbose = 0
  62. # Set this to 1 when debugging embedded scripts in an environment that
  63. # creates and reuses a Python instance across multiple script invocations.
  64. # It turns off automatic detection of program quit so that the debug session
  65. # can span multiple script invocations. When this is turned on, you may
  66. # need to call ProgramQuit() on the debugger object to shut down the
  67. # debugger cleanly when your application exits or discards the Python
  68. # instance. If multiple Python instances are created in the same run,
  69. # only the first one will be able to debug unless it terminates debug
  70. # and the environment variable WINGDB_ACTIVE is unset before importing
  71. # this module in the second or later Python instance. See the Wing
  72. # manual for details.
  73. # (WINGDB_EMBEDDED environment variable)
  74. kEmbedded = 1
  75. # Path to search for the debug password file and the name of the file
  76. # to use. The password file contains a security token for all
  77. # connections to the IDE and must match the wingdebugpw file in the
  78. # User Settngs directory used by the IDE. '$<winguserprofile>'
  79. # is replaced by the User Settings directory for the user that
  80. # is running the process.
  81. # (WINGDB_PWFILEPATH environment variable)
  82. kPWFilePath = [os.path.dirname(__file__), '$<winguserprofile>']
  83. kPWFileName = 'wingdebugpw'
  84. # Whether to exit when the debugger fails to run or to connect with the IDE
  85. # By default, execution continues without debug or without connecting to
  86. # the IDE.
  87. # (WINGDB_EXITONFAILURE environment variable)
  88. kExitOnFailure = 0
  89. #------------------------------------------------------------------------
  90. # Find Wing debugger installation location
  91. if sys.hexversion >= 0x03000000:
  92. def has_key(o, key):
  93. return key in o
  94. else:
  95. def has_key(o, key):
  96. return o.has_key(key)
  97. # Check environment: Must have WINGHOME defined if still == None
  98. if WINGHOME == None:
  99. if has_key(os.environ, 'WINGHOME'):
  100. WINGHOME=os.environ['WINGHOME']
  101. else:
  102. msg = '\n'.join(["*******************************************************************",
  103. "Error: Could not find Wing installation! You must set WINGHOME or edit",
  104. "wingdbstub.py where indicated to point it to the location where",
  105. "Wing is installed.\n"])
  106. sys.stderr.write(msg)
  107. raise ImportError(msg)
  108. WINGHOME = os.path.expanduser(WINGHOME)
  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. if sys.version_info >= (3, 7):
  147. import importlib.machinery
  148. import importlib.util
  149. spec = importlib.machinery.PathFinder.find_spec('wingdb', [path])
  150. if spec is not None:
  151. mod = importlib.util.module_from_spec(spec)
  152. if mod is not None:
  153. spec.loader.exec_module(mod)
  154. return mod
  155. else:
  156. f, p, d = imp.find_module('wingdb', [path])
  157. try:
  158. return imp.load_module('wingdb', f, p, d)
  159. finally:
  160. if f is not None:
  161. f.close()
  162. except ImportError:
  163. pass
  164. return None
  165. #------------------------------------------------------------------------
  166. # Set debugger if it hasn't been set -- this is to handle module reloading
  167. # In the reload case, the debugger variable will be set to something
  168. try:
  169. debugger
  170. except NameError:
  171. debugger = None
  172. # Unset WINGDB_ACTIVE env if it was inherited from another process
  173. # XXX Would be better to be able to call getpid() on dbgtracer but can't access it yet
  174. if 'WINGDB_ACTIVE' in os.environ and os.environ['WINGDB_ACTIVE'] != str(os.getpid()):
  175. del os.environ['WINGDB_ACTIVE']
  176. # Start debugging if not disabled and this module has never been imported
  177. # before
  178. if (not kWingDebugDisabled and debugger is None
  179. and not has_key(os.environ, 'WINGDB_DISABLED') and
  180. not has_key(os.environ, 'WINGDB_ACTIVE')):
  181. exit_on_fail = 0
  182. try:
  183. # Obtain exit if fails value
  184. exit_on_fail = os.environ.get('WINGDB_EXITONFAILURE', kExitOnFailure)
  185. # Obtain configuration for log file to use, if any
  186. logfile = os.environ.get('WINGDB_LOGFILE', kLogFile)
  187. if logfile == '-' or logfile == None or len(logfile.strip()) == 0:
  188. logfile = None
  189. very_verbose_log = os.environ.get('WINGDB_LOGVERYVERBOSE', kLogVeryVerbose)
  190. if type(very_verbose_log) == type('') and very_verbose_log.strip() == '':
  191. very_verbose_log = 0
  192. # Determine remote host/port where the IDE is running
  193. hostport = os.environ.get('WINGDB_HOSTPORT', kWingHostPort)
  194. colonpos = hostport.find(':')
  195. host = hostport[:colonpos]
  196. port = int(hostport[colonpos+1:])
  197. # Determine port to listen on locally for attach requests
  198. attachport = int(os.environ.get('WINGDB_ATTACHPORT', kAttachPort))
  199. # Check if running embedded script
  200. embedded = int(os.environ.get('WINGDB_EMBEDDED', kEmbedded))
  201. # Obtain debug password file search path
  202. if has_key(os.environ, 'WINGDB_PWFILEPATH'):
  203. pwfile_path = os.environ['WINGDB_PWFILEPATH'].split(os.pathsep)
  204. else:
  205. pwfile_path = kPWFilePath
  206. # Obtain debug password file name
  207. if has_key(os.environ, 'WINGDB_PWFILENAME'):
  208. pwfile_name = os.environ['WINGDB_PWFILENAME']
  209. else:
  210. pwfile_name = kPWFileName
  211. # Load wingdb.py
  212. actual_winghome = _FindActualWingHome(WINGHOME)
  213. wingdb = _ImportWingdb(actual_winghome, kUserSettingsDir)
  214. if wingdb == None:
  215. sys.stdout.write("*******************************************************************\n")
  216. sys.stdout.write("Error: Cannot find wingdb.py in $(WINGHOME)/bin or $(WINGHOME)/src\n")
  217. sys.stdout.write("Error: Please check the WINGHOME definition in wingdbstub.py\n")
  218. sys.exit(2)
  219. # Find the netserver module and create an error stream
  220. netserver = wingdb.FindNetServerModule(actual_winghome, kUserSettingsDir)
  221. err = wingdb.CreateErrStream(netserver, logfile, very_verbose_log)
  222. # Start debugging
  223. debugger = netserver.CNetworkServer(host, port, attachport, err,
  224. pwfile_path=pwfile_path,
  225. pwfile_name=pwfile_name,
  226. autoquit=not embedded)
  227. debugger.StartDebug(stophere=0)
  228. os.environ['WINGDB_ACTIVE'] = str(os.getpid())
  229. if debugger.ChannelClosed():
  230. raise ValueError('Not connected')
  231. except:
  232. if exit_on_fail:
  233. raise
  234. else:
  235. pass
  236. def Ensure(require_connection=1, require_debugger=1):
  237. """ Ensure the debugger is started and attempt to connect to the IDE if
  238. not already connected. Will raise a ValueError if:
  239. * the require_connection arg is true and the debugger is unable to connect
  240. * the require_debugger arg is true and the debugger cannot be loaded
  241. If SuspendDebug() has been called through the low-level API, calling
  242. Ensure() resets the suspend count to zero and additional calls to
  243. ResumeDebug() will be ignored until SuspendDebug() is called again.
  244. Note that a change to the host & port to connect to will only
  245. be use if a new connection is made.
  246. """
  247. if debugger is None:
  248. if require_debugger:
  249. raise ValueError("No debugger")
  250. return
  251. hostport = os.environ.get('WINGDB_HOSTPORT', kWingHostPort)
  252. colonpos = hostport.find(':')
  253. host = hostport[:colonpos]
  254. port = int(hostport[colonpos+1:])
  255. resumed = debugger.ResumeDebug()
  256. while resumed > 0:
  257. resumed = debugger.ResumeDebug()
  258. debugger.SetClientAddress((host, port))
  259. if not debugger.DebugActive():
  260. debugger.StartDebug()
  261. elif debugger.ChannelClosed():
  262. debugger.ConnectToClient()
  263. if require_connection and debugger.ChannelClosed():
  264. raise ValueError('Not connected')