Play images and video from Synology PhotoStation server

wingdbstub.py 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. orig_sys_modules = list(sys.modules.keys())
  18. orig_sys_path = list(sys.path)
  19. orig_meta_path = list(sys.meta_path)
  20. import os
  21. if sys.version_info >= (3, 7):
  22. import importlib
  23. else:
  24. import imp
  25. #------------------------------------------------------------------------
  26. # Required configuration values (some installers set this automatically)
  27. # This should be the full path to your Wing installation. On OS X, use
  28. # the full path of the Wing application bundle, for example
  29. # /Applications/WingPro.app. When set to None, the environment variable
  30. # WINGHOME is used instead.
  31. WINGHOME = r"C:\Program Files (x86)\Wing Pro 7.0"
  32. #------------------------------------------------------------------------
  33. # Optional configuration values: The named environment variables, if set,
  34. # will override these settings.
  35. # Set this to 1 to disable all debugging; 0 to enable debugging
  36. # (WINGDB_DISABLED environment variable)
  37. kWingDebugDisabled = 0
  38. # Host:port of the IDE within which to debug: As configured in the IDE
  39. # with the Server Port preference
  40. # (WINGDB_HOSTPORT environment variable)
  41. kWingHostPort = 'localhost:50005'
  42. # Port on which to listen for connection requests, so that the
  43. # IDE can attach or reattach to the debug process after it has started.
  44. # Set this to '-1' to disable listening for connection requests.
  45. # This is only used when the debug process is not attached to
  46. # an IDE or the IDE has dropped its connection. The configured
  47. # port can optionally be added to the IDE's Common Attach Hosts
  48. # preference. Note that a random port is used instead if the given
  49. # port is already in use.
  50. # (WINGDB_ATTACHPORT environment variable)
  51. kAttachPort = '50015'
  52. # Set this to a filename to log verbose information about the debugger
  53. # internals to a file. If the file does not exist, it will be created
  54. # as long as its enclosing directory exists and is writeable. Use
  55. # "<stderr>" or "<stdout>" to write to stderr or stdout. Note that
  56. # "<stderr>" may cause problems on Windows if the debug process is not
  57. # running in a console.
  58. # (WINGDB_LOGFILE environment variable)
  59. kLogFile = None
  60. # Produce a tremendous amount of logging from the debugger internals.
  61. # Do not set this unless instructed to do so by Wingware support. It
  62. # will slow the debugger to a crawl.
  63. # (WINGDB_LOGVERYVERBOSE environment variable)
  64. kLogVeryVerbose = 0
  65. # Set this to 1 when debugging embedded scripts in an environment that
  66. # creates and reuses a Python instance across multiple script invocations.
  67. # It turns off automatic detection of program quit so that the debug session
  68. # can span multiple script invocations. When this is turned on, you may
  69. # need to call ProgramQuit() on the debugger object to shut down the
  70. # debugger cleanly when your application exits or discards the Python
  71. # instance. If multiple Python instances are created in the same run,
  72. # only the first one will be able to debug unless it terminates debug
  73. # and the environment variable WINGDB_ACTIVE is unset before importing
  74. # this module in the second or later Python instance. See the Wing
  75. # manual for details.
  76. # (WINGDB_EMBEDDED environment variable)
  77. kEmbedded = 0
  78. # Path to search for the debug password file and the name of the file
  79. # to use. The password file contains a security token for all
  80. # connections to the IDE and must match the wingdebugpw file in the
  81. # User Settngs directory used by the IDE. '$<winguserprofile>'
  82. # is replaced by the User Settings directory for the user that
  83. # is running the process.
  84. # (WINGDB_PWFILEPATH environment variable)
  85. kPWFilePath = [os.path.dirname(__file__), '$<winguserprofile>']
  86. kPWFileName = 'wingdebugpw'
  87. # Whether to exit when the debugger fails to run or to connect with the IDE
  88. # By default, execution continues without debug or without connecting to
  89. # the IDE.
  90. # (WINGDB_EXITONFAILURE environment variable)
  91. kExitOnFailure = 0
  92. #------------------------------------------------------------------------
  93. # Find Wing debugger installation location
  94. # Check environment: Must have WINGHOME defined if still == None
  95. if WINGHOME == None:
  96. if 'WINGHOME' in os.environ:
  97. WINGHOME=os.environ['WINGHOME']
  98. else:
  99. msg = '\n'.join(["*******************************************************************",
  100. "Error: Could not find Wing installation! You must set WINGHOME or edit",
  101. "wingdbstub.py where indicated to point it to the location where",
  102. "Wing is installed.\n"])
  103. sys.stderr.write(msg)
  104. raise ImportError(msg)
  105. WINGHOME = os.path.expanduser(WINGHOME)
  106. def NP_FindActualWingHome(winghome):
  107. """ Find the actual directory to use for winghome. Needed on OS X
  108. where the .app directory is the preferred dir to use for WINGHOME and
  109. .app/Contents/MacOS is accepted for backward compatibility. """
  110. if sys.platform != 'darwin':
  111. return winghome
  112. app_dir = None
  113. if os.path.isdir(winghome):
  114. if winghome.endswith('/'):
  115. wo_slash = winghome[:-1]
  116. else:
  117. wo_slash = winghome
  118. if wo_slash.endswith('.app'):
  119. app_dir = wo_slash
  120. elif wo_slash.endswith('.app/Contents/MacOS'):
  121. app_dir = wo_slash[:-len('/Contents/MacOS')]
  122. if app_dir and os.path.isdir(os.path.join(app_dir, 'Contents', 'Resources')):
  123. return os.path.join(app_dir, 'Contents', 'Resources')
  124. return winghome
  125. WINGHOME = NP_FindActualWingHome(WINGHOME)
  126. os.environ['WINGHOME'] = WINGHOME
  127. # Path used to find the wingdebugpw file
  128. kPWFilePath.append(WINGHOME)
  129. #-----------------------------------------------------------------------
  130. def NP_LoadModuleFromBootstrap(winghome, modname):
  131. """Load a module from the installation bootstrap directory. Assumes that
  132. imports don't change sys.path. The modules are unloaded from sys.modules
  133. so they can be loaded again later from an update."""
  134. # Limited to simple module loads
  135. assert '.' not in modname
  136. orig_sys_path = sys.path[:]
  137. orig_modules = set(sys.modules)
  138. dirname = winghome + '/bootstrap'
  139. sys.path.insert(0, dirname)
  140. code = 'import %s' % modname
  141. exec(code)
  142. new_modules = set(sys.modules)
  143. new_modules.difference_update(orig_modules)
  144. for mod in new_modules:
  145. del sys.modules[mod]
  146. sys.path = orig_sys_path
  147. return locals()[modname]
  148. #------------------------------------------------------------------------
  149. # Set debugger if it hasn't been set -- this is to handle module reloading
  150. # In the reload case, the debugger variable will be set to something
  151. try:
  152. debugger
  153. except NameError:
  154. debugger = None
  155. #-----------------------------------------------------------------------
  156. # Unset WINGDB_ACTIVE env if it was inherited from another process
  157. # XXX Would be better to be able to call getpid() on dbgtracer but can't access it yet
  158. if 'WINGDB_ACTIVE' in os.environ and os.environ['WINGDB_ACTIVE'] != str(os.getpid()):
  159. del os.environ['WINGDB_ACTIVE']
  160. #-----------------------------------------------------------------------
  161. # Start debugging if not disabled and this module has never been imported
  162. # before
  163. if (not kWingDebugDisabled and debugger is None and
  164. 'WINGDB_DISABLED' not in os.environ and
  165. 'WINGDB_ACTIVE' not in os.environ):
  166. exit_on_fail = 0
  167. try:
  168. # Obtain exit if fails value
  169. exit_on_fail = os.environ.get('WINGDB_EXITONFAILURE', kExitOnFailure)
  170. # Obtain configuration for log file to use, if any
  171. logfile = os.environ.get('WINGDB_LOGFILE', kLogFile)
  172. if logfile == '-' or logfile == None or len(logfile.strip()) == 0:
  173. logfile = None
  174. very_verbose_log = os.environ.get('WINGDB_LOGVERYVERBOSE', kLogVeryVerbose)
  175. if type(very_verbose_log) == type('') and very_verbose_log.strip() == '':
  176. very_verbose_log = 0
  177. # Determine remote host/port where the IDE is running
  178. hostport = os.environ.get('WINGDB_HOSTPORT', kWingHostPort)
  179. colonpos = hostport.find(':')
  180. host = hostport[:colonpos]
  181. port = int(hostport[colonpos+1:])
  182. # Determine port to listen on locally for attach requests
  183. attachport = int(os.environ.get('WINGDB_ATTACHPORT', kAttachPort))
  184. # Check if running embedded script
  185. embedded = int(os.environ.get('WINGDB_EMBEDDED', kEmbedded))
  186. # Obtain debug password file search path
  187. if 'WINGDB_PWFILEPATH' in os.environ:
  188. pwfile_path = os.environ['WINGDB_PWFILEPATH'].split(os.pathsep)
  189. else:
  190. pwfile_path = kPWFilePath
  191. # Obtain debug password file name
  192. if 'WINGDB_PWFILENAME' in os.environ:
  193. pwfile_name = os.environ['WINGDB_PWFILENAME']
  194. else:
  195. pwfile_name = kPWFileName
  196. # Set up temporary log for errors from merge importer Setup
  197. class CTmpLog:
  198. def __init__(self):
  199. self.fErrors = []
  200. def write(self, s):
  201. self.fErrors.append(s)
  202. tmp_log = CTmpLog()
  203. # Set up the meta importer; everything after this point can be update
  204. bootstrap_utils = NP_LoadModuleFromBootstrap(WINGHOME, 'bootstrap_utils')
  205. winghome, user_settings = bootstrap_utils.NP_SetupWingHomeModule(WINGHOME)
  206. meta = bootstrap_utils.NP_CreateMetaImporter(WINGHOME, user_settings, 'dbg',
  207. tmp_log)
  208. import _winghome
  209. _winghome.kWingHome = winghome
  210. _winghome.kUserSettings = user_settings
  211. # Find the netserver module and create an error stream
  212. from debug.tserver import startdebug
  213. netserver = startdebug.FindNetServerModule(WINGHOME, user_settings)
  214. err = startdebug.CreateErrStream(netserver, logfile, very_verbose_log)
  215. # Write any temporary log entries
  216. for s in tmp_log.fErrors:
  217. err.write(s)
  218. # Create debug server
  219. debugger = netserver.CNetworkServer(host, port, attachport, err,
  220. pwfile_path=pwfile_path,
  221. pwfile_name=pwfile_name,
  222. autoquit=not embedded)
  223. # Restore module and path environment
  224. from debug.tserver import startdebug
  225. startdebug.RestoreEnvironment(orig_sys_modules, orig_sys_path, orig_meta_path)
  226. # Start debugging
  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. #-----------------------------------------------------------------------
  237. def Ensure(require_connection=1, require_debugger=1):
  238. """ Ensure the debugger is started and attempt to connect to the IDE if
  239. not already connected. Will raise a ValueError if:
  240. * the require_connection arg is true and the debugger is unable to connect
  241. * the require_debugger arg is true and the debugger cannot be loaded
  242. If SuspendDebug() has been called through the low-level API, calling
  243. Ensure() resets the suspend count to zero and additional calls to
  244. ResumeDebug() will be ignored until SuspendDebug() is called again.
  245. Note that a change to the host & port to connect to will only
  246. be use if a new connection is made.
  247. """
  248. if debugger is None:
  249. if require_debugger:
  250. raise ValueError("No debugger")
  251. return
  252. hostport = os.environ.get('WINGDB_HOSTPORT', kWingHostPort)
  253. colonpos = hostport.find(':')
  254. host = hostport[:colonpos]
  255. port = int(hostport[colonpos+1:])
  256. resumed = debugger.ResumeDebug()
  257. while resumed > 0:
  258. resumed = debugger.ResumeDebug()
  259. debugger.SetClientAddress((host, port))
  260. if not debugger.DebugActive():
  261. debugger.StartDebug()
  262. elif debugger.ChannelClosed():
  263. debugger.ConnectToClient()
  264. if require_connection and debugger.ChannelClosed():
  265. raise ValueError('Not connected')