framework.py 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  1. """AXScript Client Framework
  2. This module provides a core framework for an ActiveX Scripting client.
  3. Derived classes actually implement the AX Client itself, including the
  4. scoping rules, etc.
  5. There are classes defined for the engine itself, and for ScriptItems
  6. """
  7. import sys
  8. from win32com.axscript import axscript
  9. import win32com.server.util
  10. import win32com.client.connect # Need simple connection point support
  11. import win32api, winerror
  12. import pythoncom
  13. import types
  14. import re
  15. def RemoveCR(text):
  16. # No longer just "RemoveCR" - should be renamed to
  17. # FixNewlines, or something. Idea is to fix arbitary newlines into
  18. # something Python can compile...
  19. return re.sub('(\r\n)|\r|(\n\r)','\n',text)
  20. SCRIPTTEXT_FORCEEXECUTION = -2147483648 # 0x80000000
  21. SCRIPTTEXT_ISEXPRESSION = 0x00000020
  22. SCRIPTTEXT_ISPERSISTENT = 0x00000040
  23. from win32com.server.exception import Exception, IsCOMServerException
  24. from . import error # ax.client.error
  25. state_map = {
  26. axscript.SCRIPTSTATE_UNINITIALIZED: "SCRIPTSTATE_UNINITIALIZED",
  27. axscript.SCRIPTSTATE_INITIALIZED: "SCRIPTSTATE_INITIALIZED",
  28. axscript.SCRIPTSTATE_STARTED: "SCRIPTSTATE_STARTED",
  29. axscript.SCRIPTSTATE_CONNECTED: "SCRIPTSTATE_CONNECTED",
  30. axscript.SCRIPTSTATE_DISCONNECTED: "SCRIPTSTATE_DISCONNECTED",
  31. axscript.SCRIPTSTATE_CLOSED: "SCRIPTSTATE_CLOSED",
  32. }
  33. def profile(fn, *args):
  34. import profile
  35. prof = profile.Profile()
  36. try:
  37. # roll on 1.6 :-)
  38. # return prof.runcall(fn, *args)
  39. return prof.runcall(*(fn,) + args)
  40. finally:
  41. import pstats
  42. # Damn - really want to send this to Excel!
  43. # width, list = pstats.Stats(prof).strip_dirs().get_print_list([])
  44. pstats.Stats(prof).strip_dirs().sort_stats("time").print_stats()
  45. class SafeOutput:
  46. softspace=1
  47. def __init__(self, redir=None):
  48. if redir is None: redir = sys.stdout
  49. self.redir=redir
  50. def write(self,message):
  51. try:
  52. self.redir.write(message)
  53. except:
  54. win32api.OutputDebugString(message)
  55. def flush(self):
  56. pass
  57. def close(self):
  58. pass
  59. # Make sure we have a valid sys.stdout/stderr, otherwise out
  60. # print and trace statements may raise an exception
  61. def MakeValidSysOuts():
  62. if not isinstance(sys.stdout, SafeOutput):
  63. sys.stdout = sys.stderr = SafeOutput()
  64. # and for the sake of working around something I can't understand...
  65. # prevent keyboard interrupts from killing IIS
  66. import signal
  67. def noOp(a,b):
  68. # it would be nice to get to the bottom of this, so a warning to
  69. # the debug console can't hurt.
  70. print("WARNING: Ignoring keyboard interrupt from ActiveScripting engine")
  71. # If someone else has already redirected, then assume they know what they are doing!
  72. if signal.getsignal(signal.SIGINT) == signal.default_int_handler:
  73. try:
  74. signal.signal(signal.SIGINT, noOp)
  75. except ValueError:
  76. # Not the main thread - can't do much.
  77. pass
  78. def trace(*args):
  79. """A function used instead of "print" for debugging output.
  80. """
  81. for arg in args:
  82. print(arg, end=' ')
  83. print()
  84. def RaiseAssert(scode, desc):
  85. """A debugging function that raises an exception considered an "Assertion".
  86. """
  87. print("**************** ASSERTION FAILED *******************")
  88. print(desc)
  89. raise Exception(desc, scode)
  90. class AXScriptCodeBlock:
  91. """An object which represents a chunk of code in an AX Script
  92. """
  93. def __init__(self, name, codeText, sourceContextCookie, startLineNumber, flags):
  94. self.name = name
  95. self.codeText = codeText
  96. self.codeObject = None
  97. self.sourceContextCookie = sourceContextCookie
  98. self.startLineNumber = startLineNumber
  99. self.flags = flags
  100. self.beenExecuted = 0
  101. def GetFileName(self):
  102. # Gets the "file name" for Python - uses <...> so Python doesnt think
  103. # it is a real file.
  104. return "<%s>" % self.name
  105. def GetDisplayName(self):
  106. return self.name
  107. def GetLineNo(self, no):
  108. pos = -1
  109. for i in range(no-1):
  110. pos = self.codeText.find('\n', pos+1)
  111. if pos==-1: pos=len(self.codeText)
  112. epos = self.codeText.find('\n', pos+1)
  113. if epos==-1:
  114. epos=len(self.codeText)
  115. return self.codeText[pos+1:epos].strip()
  116. class Event:
  117. """A single event for a ActiveX named object.
  118. """
  119. def __init__(self):
  120. self.name = "<None>"
  121. def __repr__(self):
  122. return "<%s at %d: %s>" % (self.__class__.__name__, id(self), self.name)
  123. def Reset(self):
  124. pass
  125. def Close(self):
  126. pass
  127. def Build(self, typeinfo, funcdesc):
  128. self.dispid = funcdesc[0]
  129. self.name = typeinfo.GetNames(self.dispid)[0]
  130. # print "Event.Build() - Event Name is ", self.name
  131. class EventSink:
  132. """A set of events against an item. Note this is a COM client for connection points.
  133. """
  134. _public_methods_ = []
  135. def __init__(self, myItem, coDispatch):
  136. self.events = {}
  137. self.connection = None
  138. self.coDispatch = coDispatch
  139. self.myScriptItem = myItem
  140. self.myInvokeMethod = myItem.GetEngine().ProcessScriptItemEvent
  141. self.iid = None
  142. def Reset(self):
  143. self.Disconnect()
  144. def Close(self):
  145. self.iid = None
  146. self.myScriptItem = None
  147. self.myInvokeMethod = None
  148. self.coDispatch = None
  149. for event in self.events.values():
  150. event.Reset()
  151. self.events = {}
  152. self.Disconnect()
  153. # COM Connection point methods.
  154. def _query_interface_(self, iid):
  155. if iid==self.iid:
  156. return win32com.server.util.wrap(self)
  157. def _invoke_(self, dispid, lcid, wFlags, args):
  158. try:
  159. event = self.events[dispid]
  160. except:
  161. raise Exception(scode=winerror.DISP_E_MEMBERNOTFOUND)
  162. #print "Invoke for ", event, "on", self.myScriptItem, " - calling", self.myInvokeMethod
  163. return self.myInvokeMethod(self.myScriptItem, event, lcid, wFlags, args)
  164. def GetSourceTypeInfo(self, typeinfo):
  165. """Gets the typeinfo for the Source Events for the passed typeinfo"""
  166. attr = typeinfo.GetTypeAttr()
  167. cFuncs = attr[6]
  168. typeKind = attr[5]
  169. if typeKind not in [pythoncom.TKIND_COCLASS, pythoncom.TKIND_INTERFACE]:
  170. RaiseAssert(winerror.E_UNEXPECTED, "The typeKind of the object is unexpected")
  171. cImplType = attr[8]
  172. for i in range(cImplType):
  173. # Look for the [source, default] interface on the coclass
  174. # that isn't marked as restricted.
  175. flags = typeinfo.GetImplTypeFlags(i)
  176. flagsNeeded = pythoncom.IMPLTYPEFLAG_FDEFAULT | pythoncom.IMPLTYPEFLAG_FSOURCE
  177. if (flags & ( flagsNeeded | pythoncom.IMPLTYPEFLAG_FRESTRICTED))==(flagsNeeded):
  178. # Get the handle to the implemented interface.
  179. href = typeinfo.GetRefTypeOfImplType(i)
  180. return typeinfo.GetRefTypeInfo(href)
  181. def BuildEvents(self):
  182. # See if it is an extender object.
  183. try:
  184. mainTypeInfo = self.coDispatch.QueryInterface(axscript.IID_IProvideMultipleClassInfo)
  185. isMulti = 1
  186. numTypeInfos = mainTypeInfo.GetMultiTypeInfoCount()
  187. except pythoncom.com_error:
  188. isMulti = 0
  189. numTypeInfos = 1
  190. try:
  191. mainTypeInfo = self.coDispatch.QueryInterface(pythoncom.IID_IProvideClassInfo)
  192. except pythoncom.com_error:
  193. numTypeInfos = 0
  194. # Create an event handler for the item.
  195. for item in range(numTypeInfos):
  196. if isMulti:
  197. typeinfo, flags = mainTypeInfo.GetInfoOfIndex(item, axscript.MULTICLASSINFO_GETTYPEINFO)
  198. else:
  199. typeinfo = mainTypeInfo.GetClassInfo()
  200. sourceType = self.GetSourceTypeInfo(typeinfo)
  201. cFuncs = 0
  202. if sourceType:
  203. attr = sourceType.GetTypeAttr()
  204. self.iid = attr[0]
  205. cFuncs = attr[6]
  206. for i in range(cFuncs):
  207. funcdesc = sourceType.GetFuncDesc(i)
  208. event = Event()
  209. event.Build(sourceType, funcdesc)
  210. self.events[event.dispid] = event
  211. def Connect(self):
  212. if self.connection is not None or self.iid is None: return
  213. # trace("Connect for sink item", self.myScriptItem.name, "with IID",str(self.iid))
  214. self.connection = win32com.client.connect.SimpleConnection(self.coDispatch, self, self.iid)
  215. def Disconnect(self):
  216. if self.connection:
  217. try:
  218. self.connection.Disconnect()
  219. except pythoncom.com_error:
  220. pass # Ignore disconnection errors.
  221. self.connection = None
  222. class ScriptItem:
  223. """An item (or subitem) that is exposed to the ActiveX script
  224. """
  225. def __init__(self, parentItem, name, dispatch, flags):
  226. self.parentItem = parentItem
  227. self.dispatch = dispatch
  228. self.name = name
  229. self.flags = flags
  230. self.eventSink = None
  231. self.subItems = {}
  232. self.createdConnections = 0
  233. self.isRegistered = 0
  234. # trace("Creating ScriptItem", name, "of parent", parentItem,"with dispatch", dispatch)
  235. def __repr__(self):
  236. flagsDesc=""
  237. if self.flags is not None and self.flags & axscript.SCRIPTITEM_GLOBALMEMBERS:
  238. flagsDesc = "/Global"
  239. return "<%s at %d: %s%s>" % (self.__class__.__name__, id(self), self.name,flagsDesc)
  240. def _dump_(self, level):
  241. flagDescs = []
  242. if self.flags is not None and self.flags & axscript.SCRIPTITEM_GLOBALMEMBERS:
  243. flagDescs.append("GLOBAL!")
  244. if self.flags is None or self.flags & axscript.SCRIPTITEM_ISVISIBLE == 0:
  245. flagDescs.append("NOT VISIBLE")
  246. if self.flags is not None and self.flags & axscript.SCRIPTITEM_ISSOURCE:
  247. flagDescs.append("EVENT SINK")
  248. if self.flags is not None and self.flags & axscript.SCRIPTITEM_CODEONLY:
  249. flagDescs.append("CODE ONLY")
  250. print(" " * level, "Name=", self.name, ", flags=", "/".join(flagDescs), self)
  251. for subItem in self.subItems.values():
  252. subItem._dump_(level+1)
  253. def Reset(self):
  254. self.Disconnect()
  255. if self.eventSink:
  256. self.eventSink.Reset()
  257. self.isRegistered = 0
  258. for subItem in self.subItems.values():
  259. subItem.Reset()
  260. def Close(self):
  261. self.Reset()
  262. self.dispatch = None
  263. self.parentItem = None
  264. if self.eventSink:
  265. self.eventSink.Close()
  266. self.eventSink = None
  267. for subItem in self.subItems.values():
  268. subItem.Close()
  269. self.subItems = []
  270. self.createdConnections = 0
  271. def Register(self):
  272. if self.isRegistered: return
  273. # Get the type info to use to build this item.
  274. # if not self.dispatch:
  275. # id = self.parentItem.dispatch.GetIDsOfNames(self.name)
  276. # print "DispID of me is", id
  277. # result = self.parentItem.dispatch.Invoke(id, 0, pythoncom.DISPATCH_PROPERTYGET,1)
  278. # if type(result)==pythoncom.TypeIIDs[pythoncom.IID_IDispatch]:
  279. # self.dispatch = result
  280. # else:
  281. # print "*** No dispatch"
  282. # return
  283. # print "**** Made dispatch"
  284. self.isRegistered = 1
  285. # Register the sub-items.
  286. for item in self.subItems.values():
  287. if not item.isRegistered:
  288. item.Register()
  289. def IsGlobal(self):
  290. return self.flags & axscript.SCRIPTITEM_GLOBALMEMBERS
  291. def IsVisible(self):
  292. return (self.flags & (axscript.SCRIPTITEM_ISVISIBLE | axscript.SCRIPTITEM_ISSOURCE)) != 0
  293. def GetEngine(self):
  294. item = self
  295. while item.parentItem.__class__==self.__class__:
  296. item = item.parentItem
  297. return item.parentItem
  298. def _GetFullItemName(self):
  299. ret = self.name
  300. if self.parentItem:
  301. try:
  302. ret = self.parentItem._GetFullItemName() + "." + ret
  303. except AttributeError:
  304. pass
  305. return ret
  306. def GetSubItemClass(self):
  307. return self.__class__
  308. def GetSubItem(self, name):
  309. return self.subItems[name.lower()]
  310. def GetCreateSubItem(self, parentItem, name, dispatch, flags):
  311. keyName = name.lower()
  312. try:
  313. rc = self.subItems[keyName]
  314. # No changes allowed to existing flags.
  315. if not rc.flags is None and not flags is None and rc.flags != flags:
  316. raise Exception(scode=winerror.E_INVALIDARG)
  317. # Existing item must not have a dispatch.
  318. if not rc.dispatch is None and not dispatch is None:
  319. raise Exception(scode=winerror.E_INVALIDARG)
  320. rc.flags = flags # Setup the real flags.
  321. rc.dispatch = dispatch
  322. except KeyError:
  323. rc = self.subItems[keyName] = self.GetSubItemClass()(parentItem, name, dispatch, flags)
  324. return rc
  325. # if self.dispatch is None:
  326. # RaiseAssert(winerror.E_UNEXPECTED, "??")
  327. def CreateConnections(self):
  328. # Create (but do not connect to) the connection points.
  329. if self.createdConnections: return
  330. self.createdConnections = 1
  331. # Nothing to do unless this is an event source
  332. # This flags means self, _and_ children, are connectable.
  333. if self.flags & axscript.SCRIPTITEM_ISSOURCE:
  334. self.BuildEvents()
  335. self.FindBuildSubItemEvents()
  336. def Connect(self):
  337. # Connect to the already created connection points.
  338. if self.eventSink:
  339. self.eventSink.Connect()
  340. for subItem in self.subItems.values():
  341. subItem.Connect()
  342. def Disconnect(self):
  343. # Disconnect from the connection points.
  344. if self.eventSink:
  345. self.eventSink.Disconnect()
  346. for subItem in self.subItems.values():
  347. subItem.Disconnect()
  348. def BuildEvents(self):
  349. if self.eventSink is not None or self.dispatch is None:
  350. RaiseAssert(winerror.E_UNEXPECTED, "Item already has built events, or no dispatch available?")
  351. # trace("BuildEvents for named item", self._GetFullItemName())
  352. self.eventSink = EventSink(self, self.dispatch)
  353. self.eventSink.BuildEvents()
  354. def FindBuildSubItemEvents(self):
  355. # Called during connection to event source. Seeks out and connects to
  356. # all children. As per the AX spec, this is not recursive
  357. # (ie, children sub-items are not seeked)
  358. try:
  359. multiTypeInfo = self.dispatch.QueryInterface(axscript.IID_IProvideMultipleClassInfo)
  360. numTypeInfos = multiTypeInfo.GetMultiTypeInfoCount()
  361. except pythoncom.com_error:
  362. return
  363. for item in range(numTypeInfos):
  364. typeinfo, flags = multiTypeInfo.GetInfoOfIndex(item, axscript.MULTICLASSINFO_GETTYPEINFO)
  365. defaultType = self.GetDefaultSourceTypeInfo(typeinfo)
  366. index = 0
  367. while 1:
  368. try:
  369. fdesc = defaultType.GetFuncDesc(index)
  370. except pythoncom.com_error:
  371. break # No more funcs
  372. index = index + 1
  373. dispid = fdesc[0]
  374. funckind = fdesc[3]
  375. invkind = fdesc[4]
  376. elemdesc = fdesc[8]
  377. funcflags = fdesc[9]
  378. try:
  379. isSubObject = not (funcflags & pythoncom.FUNCFLAG_FRESTRICTED) and \
  380. funckind == pythoncom.FUNC_DISPATCH and \
  381. invkind == pythoncom.INVOKE_PROPERTYGET and \
  382. elemdesc[0][0] == pythoncom.VT_PTR and \
  383. elemdesc[0][1][0] == pythoncom.VT_USERDEFINED
  384. except:
  385. isSubObject = 0
  386. if isSubObject:
  387. try:
  388. # We found a sub-object.
  389. names = typeinfo.GetNames(dispid);
  390. result = self.dispatch.Invoke(dispid, 0x0, pythoncom.DISPATCH_PROPERTYGET, 1)
  391. # IE has an interesting problem - there are lots of synonyms for the same object. Eg
  392. # in a simple form, "window.top", "window.window", "window.parent", "window.self"
  393. # all refer to the same object. Our event implementation code does not differentiate
  394. # eg, "window_onload" will fire for *all* objects named "window". Thus,
  395. # "window" and "window.window" will fire the same event handler :(
  396. # One option would be to check if the sub-object is indeed the
  397. # parent object - however, this would stop "top_onload" from firing,
  398. # as no event handler for "top" would work.
  399. # I think we simply need to connect to a *single* event handler.
  400. # As use in IE is deprecated, I am not solving this now.
  401. if type(result)==pythoncom.TypeIIDs[pythoncom.IID_IDispatch]:
  402. name = names[0]
  403. subObj = self.GetCreateSubItem(self, name, result, axscript.SCRIPTITEM_ISVISIBLE)
  404. #print "subobj", name, "flags are", subObj.flags, "mydisp=", self.dispatch, "result disp=", result, "compare=", self.dispatch==result
  405. subObj.BuildEvents()
  406. subObj.Register()
  407. except pythoncom.com_error:
  408. pass
  409. def GetDefaultSourceTypeInfo(self, typeinfo):
  410. """Gets the typeinfo for the Default Dispatch for the passed typeinfo"""
  411. attr = typeinfo.GetTypeAttr()
  412. cFuncs = attr[6]
  413. typeKind = attr[5]
  414. if typeKind not in [pythoncom.TKIND_COCLASS, pythoncom.TKIND_INTERFACE]:
  415. RaiseAssert(winerror.E_UNEXPECTED, "The typeKind of the object is unexpected")
  416. cImplType = attr[8]
  417. for i in range(cImplType):
  418. # Look for the [source, default] interface on the coclass
  419. # that isn't marked as restricted.
  420. flags = typeinfo.GetImplTypeFlags(i)
  421. if (flags & ( pythoncom.IMPLTYPEFLAG_FDEFAULT | pythoncom.IMPLTYPEFLAG_FSOURCE | pythoncom.IMPLTYPEFLAG_FRESTRICTED))==pythoncom.IMPLTYPEFLAG_FDEFAULT:
  422. # Get the handle to the implemented interface.
  423. href = typeinfo.GetRefTypeOfImplType(i)
  424. defTypeInfo = typeinfo.GetRefTypeInfo(href)
  425. attr = defTypeInfo.GetTypeAttr()
  426. typeKind = attr[5]
  427. typeFlags = attr[11]
  428. if typeKind == pythoncom.TKIND_INTERFACE and typeFlags & pythoncom.TYPEFLAG_FDUAL:
  429. # Get corresponding Disp interface
  430. # -1 is a special value which does this for us.
  431. href = typeinfo.GetRefTypeOfImplType(-1)
  432. return defTypeInfo.GetRefTypeInfo(href)
  433. else:
  434. return defTypeInfo
  435. IActiveScriptMethods = [
  436. "SetScriptSite", "GetScriptSite", "SetScriptState", "GetScriptState",
  437. "Close", "AddNamedItem", "AddTypeLib", "GetScriptDispatch",
  438. "GetCurrentScriptThreadID", "GetScriptThreadID", "GetScriptThreadState",
  439. "InterruptScriptThread", "Clone" ]
  440. IActiveScriptParseMethods = [
  441. "InitNew", "AddScriptlet", "ParseScriptText" ]
  442. IObjectSafetyMethods = [
  443. "GetInterfaceSafetyOptions", "SetInterfaceSafetyOptions"]
  444. # ActiveScriptParseProcedure is a new interface with IIS4/IE4.
  445. IActiveScriptParseProcedureMethods = ['ParseProcedureText']
  446. class COMScript:
  447. """An ActiveX Scripting engine base class.
  448. This class implements the required COM interfaces for ActiveX scripting.
  449. """
  450. _public_methods_ = IActiveScriptMethods + IActiveScriptParseMethods + IObjectSafetyMethods + IActiveScriptParseProcedureMethods
  451. _com_interfaces_ = [axscript.IID_IActiveScript, axscript.IID_IActiveScriptParse, axscript.IID_IObjectSafety] #, axscript.IID_IActiveScriptParseProcedure]
  452. def __init__(self):
  453. # Make sure we can print/trace wihout an exception!
  454. MakeValidSysOuts()
  455. # trace("AXScriptEngine object created", self)
  456. self.baseThreadId = -1
  457. self.debugManager = None
  458. self.threadState = axscript.SCRIPTTHREADSTATE_NOTINSCRIPT
  459. self.scriptState = axscript.SCRIPTSTATE_UNINITIALIZED
  460. self.scriptSite = None
  461. self.safetyOptions = 0
  462. self.lcid = 0
  463. self.subItems = {}
  464. self.scriptCodeBlocks = {}
  465. def _query_interface_(self, iid):
  466. if self.debugManager:
  467. return self.debugManager._query_interface_for_debugger_(iid)
  468. # trace("ScriptEngine QI - unknown IID", iid)
  469. return 0
  470. # IActiveScriptParse
  471. def InitNew(self):
  472. if self.scriptSite is not None:
  473. self.SetScriptState(axscript.SCRIPTSTATE_INITIALIZED)
  474. def AddScriptlet(self, defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber):
  475. # trace ("AddScriptlet", defaultName, code, itemName, subItemName, eventName, delimiter, sourceContextCookie, startLineNumber)
  476. self.DoAddScriptlet(defaultName, code, itemName, subItemName, eventName, delimiter,sourceContextCookie, startLineNumber)
  477. def ParseScriptText(self, code, itemName, context, delimiter, sourceContextCookie, startLineNumber, flags, bWantResult):
  478. # trace ("ParseScriptText", code[:20],"...", itemName, context, delimiter, sourceContextCookie, startLineNumber, flags, bWantResult)
  479. if bWantResult or self.scriptState == axscript.SCRIPTSTATE_STARTED \
  480. or self.scriptState == axscript.SCRIPTSTATE_CONNECTED \
  481. or self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED :
  482. flags = flags | SCRIPTTEXT_FORCEEXECUTION
  483. else:
  484. flags = flags & (~SCRIPTTEXT_FORCEEXECUTION)
  485. if flags & SCRIPTTEXT_FORCEEXECUTION:
  486. # About to execute the code.
  487. self.RegisterNewNamedItems()
  488. return self.DoParseScriptText(code, sourceContextCookie, startLineNumber, bWantResult, flags)
  489. #
  490. # IActiveScriptParseProcedure
  491. def ParseProcedureText( self, code, formalParams, procName, itemName, unkContext, delimiter, contextCookie, startingLineNumber, flags):
  492. trace("ParseProcedureText", code, formalParams, procName, itemName, unkContext, delimiter, contextCookie, startingLineNumber, flags)
  493. # NOTE - this is never called, as we have disabled this interface.
  494. # Problem is, once enabled all even code comes via here, rather than AddScriptlet.
  495. # However, the "procName" is always an empty string - ie, itemName is the object whose event we are handling,
  496. # but no idea what the specific event is!?
  497. # Problem is disabling this block is that AddScriptlet is _not_ passed
  498. # <SCRIPT for="whatever" event="onClick" language="Python">
  499. # (but even for those blocks, the "onClick" information is still missing!?!?!?)
  500. # self.DoAddScriptlet(None, code, itemName, subItemName, eventName, delimiter,sourceContextCookie, startLineNumber)
  501. return None
  502. #
  503. # IActiveScript
  504. def SetScriptSite(self, site):
  505. # We should still work with an existing site (or so MSXML believes :)
  506. self.scriptSite = site
  507. if self.debugManager is not None:
  508. self.debugManager.Close()
  509. import traceback
  510. try:
  511. import win32com.axdebug.axdebug # see if the core exists.
  512. from . import debug
  513. self.debugManager = debug.DebugManager(self)
  514. except pythoncom.com_error:
  515. # COM errors will occur if the debugger interface has never been
  516. # seen on the target system
  517. trace("Debugging interfaces not available - debugging is disabled..")
  518. self.debugManager = None
  519. except ImportError:
  520. trace("Debugging extensions (axdebug) module does not exist - debugging is disabled..")
  521. self.debugManager = None
  522. except:
  523. traceback.print_exc()
  524. trace("*** Debugger Manager could not initialize - %s: %s" % (sys.exc_info()[0],sys.exc_info()[1]))
  525. self.debugManager = None
  526. try:
  527. self.lcid = site.GetLCID()
  528. except pythoncom.com_error:
  529. self.lcid = win32api.GetUserDefaultLCID()
  530. self.Reset()
  531. def GetScriptSite(self, iid):
  532. if self.scriptSite is None: raise Exception(scode=winerror.S_FALSE)
  533. return self.scriptSite.QueryInterface(iid)
  534. def SetScriptState(self, state):
  535. #print "SetScriptState with %s - currentstate = %s" % (state_map.get(state),state_map.get(self.scriptState))
  536. if state == self.scriptState: return
  537. # If closed, allow no other state transitions
  538. if self.scriptState==axscript.SCRIPTSTATE_CLOSED:
  539. raise Exception(scode=winerror.E_INVALIDARG)
  540. if state==axscript.SCRIPTSTATE_INITIALIZED:
  541. # Re-initialize - shutdown then reset.
  542. if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_STARTED]:
  543. self.Stop()
  544. elif state==axscript.SCRIPTSTATE_STARTED:
  545. if self.scriptState == axscript.SCRIPTSTATE_CONNECTED:
  546. self.Disconnect()
  547. if self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED:
  548. self.Reset()
  549. self.Run()
  550. self.ChangeScriptState(axscript.SCRIPTSTATE_STARTED)
  551. elif state==axscript.SCRIPTSTATE_CONNECTED:
  552. if self.scriptState in [axscript.SCRIPTSTATE_UNINITIALIZED,axscript.SCRIPTSTATE_INITIALIZED]:
  553. self.ChangeScriptState(axscript.SCRIPTSTATE_STARTED) # report transition through started
  554. self.Run()
  555. if self.scriptState == axscript.SCRIPTSTATE_STARTED:
  556. self.Connect()
  557. self.ChangeScriptState(state)
  558. elif state==axscript.SCRIPTSTATE_DISCONNECTED:
  559. if self.scriptState == axscript.SCRIPTSTATE_CONNECTED:
  560. self.Disconnect()
  561. elif state==axscript.SCRIPTSTATE_CLOSED:
  562. self.Close()
  563. elif state==axscript.SCRIPTSTATE_UNINITIALIZED:
  564. if self.scriptState == axscript.SCRIPTSTATE_STARTED:
  565. self.Stop()
  566. if self.scriptState == axscript.SCRIPTSTATE_CONNECTED:
  567. self.Disconnect()
  568. if self.scriptState == axscript.SCRIPTSTATE_DISCONNECTED:
  569. self.Reset()
  570. self.ChangeScriptState(state)
  571. else:
  572. raise Exception(scode=winerror.E_INVALIDARG)
  573. def GetScriptState(self):
  574. return self.scriptState
  575. def Close(self):
  576. # trace("Close")
  577. if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED]:
  578. self.Stop()
  579. if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED, axscript.SCRIPTSTATE_INITIALIZED, axscript.SCRIPTSTATE_STARTED]:
  580. pass # engine.close??
  581. if self.scriptState in [axscript.SCRIPTSTATE_UNINITIALIZED, axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED, axscript.SCRIPTSTATE_INITIALIZED, axscript.SCRIPTSTATE_STARTED]:
  582. self.ChangeScriptState(axscript.SCRIPTSTATE_CLOSED)
  583. # Completely reset all named items (including persistent)
  584. for item in self.subItems.values():
  585. item.Close()
  586. self.subItems = {}
  587. self.baseThreadId = -1
  588. if self.debugManager:
  589. self.debugManager.Close()
  590. self.debugManager = None
  591. self.scriptSite = None
  592. self.scriptCodeBlocks = {}
  593. self.persistLoaded = 0
  594. def AddNamedItem(self, name, flags):
  595. if self.scriptSite is None: raise Exception(scode=winerror.E_INVALIDARG)
  596. try:
  597. unknown = self.scriptSite.GetItemInfo(name, axscript.SCRIPTINFO_IUNKNOWN)[0]
  598. dispatch = unknown.QueryInterface(pythoncom.IID_IDispatch)
  599. except pythoncom.com_error:
  600. raise Exception(scode=winerror.E_NOINTERFACE, desc="Object has no dispatch interface available.")
  601. newItem = self.subItems[name] = self.GetNamedItemClass()(self, name, dispatch, flags)
  602. if newItem.IsGlobal():
  603. newItem.CreateConnections()
  604. def GetScriptDispatch(self, name):
  605. # Base classes should override.
  606. raise Exception(scode=winerror.E_NOTIMPL)
  607. def GetCurrentScriptThreadID(self):
  608. return self.baseThreadId
  609. def GetScriptThreadID(self, win32ThreadId):
  610. if self.baseThreadId == -1:
  611. raise Exception(scode=winerror.E_UNEXPECTED)
  612. if self.baseThreadId != win32ThreadId:
  613. raise Exception(scode=winerror.E_INVALIDARG)
  614. return self.baseThreadId
  615. def GetScriptThreadState(self, scriptThreadId):
  616. if self.baseThreadId == -1:
  617. raise Exception(scode=winerror.E_UNEXPECTED)
  618. if scriptThreadId != self.baseThreadId:
  619. raise Exception(scode=winerror.E_INVALIDARG)
  620. return self.threadState
  621. def AddTypeLib(self, uuid, major, minor, flags):
  622. # Get the win32com gencache to register this library.
  623. from win32com.client import gencache
  624. gencache.EnsureModule(uuid, self.lcid, major, minor, bForDemand = 1)
  625. # This is never called by the C++ framework - it does magic.
  626. # See PyGActiveScript.cpp
  627. #def InterruptScriptThread(self, stidThread, exc_info, flags):
  628. # raise Exception("Not Implemented", scode=winerror.E_NOTIMPL)
  629. def Clone(self):
  630. raise Exception("Not Implemented", scode=winerror.E_NOTIMPL)
  631. #
  632. # IObjectSafety
  633. # Note that IE seems to insist we say we support all the flags, even tho
  634. # we dont accept them all. If unknown flags come in, they are ignored, and never
  635. # reflected in GetInterfaceSafetyOptions and the QIs obviously fail, but still IE
  636. # allows our engine to initialize.
  637. def SetInterfaceSafetyOptions(self, iid, optionsMask, enabledOptions):
  638. # trace ("SetInterfaceSafetyOptions", iid, optionsMask, enabledOptions)
  639. if optionsMask & enabledOptions == 0:
  640. return
  641. # See comments above.
  642. # if (optionsMask & enabledOptions & \
  643. # ~(axscript.INTERFACESAFE_FOR_UNTRUSTED_DATA | axscript.INTERFACESAFE_FOR_UNTRUSTED_CALLER)):
  644. # # request for options we don't understand
  645. # RaiseAssert(scode=winerror.E_FAIL, desc="Unknown safety options")
  646. if iid in [pythoncom.IID_IPersist, pythoncom.IID_IPersistStream, pythoncom.IID_IPersistStreamInit,
  647. axscript.IID_IActiveScript, axscript.IID_IActiveScriptParse]:
  648. supported = self._GetSupportedInterfaceSafetyOptions()
  649. self.safetyOptions = supported & optionsMask & enabledOptions
  650. else:
  651. raise Exception(scode=winerror.E_NOINTERFACE)
  652. def _GetSupportedInterfaceSafetyOptions(self):
  653. return 0
  654. def GetInterfaceSafetyOptions(self, iid):
  655. if iid in [pythoncom.IID_IPersist, pythoncom.IID_IPersistStream, pythoncom.IID_IPersistStreamInit,
  656. axscript.IID_IActiveScript, axscript.IID_IActiveScriptParse]:
  657. supported = self._GetSupportedInterfaceSafetyOptions()
  658. return supported, self.safetyOptions
  659. else:
  660. raise Exception(scode=winerror.E_NOINTERFACE)
  661. #
  662. # Other helpers.
  663. def ExecutePendingScripts(self):
  664. self.RegisterNewNamedItems()
  665. self.DoExecutePendingScripts()
  666. def ProcessScriptItemEvent(self, item, event, lcid, wFlags, args):
  667. # trace("ProcessScriptItemEvent", item, event, lcid, wFlags, args)
  668. self.RegisterNewNamedItems()
  669. return self.DoProcessScriptItemEvent(item, event, lcid, wFlags, args)
  670. def _DumpNamedItems_(self):
  671. for item in self.subItems.values():
  672. item._dump_(0)
  673. def ResetNamedItems(self):
  674. # Due to the way we work, we re-create persistent ones.
  675. existing = self.subItems
  676. self.subItems = {}
  677. for name, item in existing.items():
  678. item.Close()
  679. if item.flags & axscript.SCRIPTITEM_ISPERSISTENT:
  680. self.AddNamedItem(item.name, item.flags)
  681. def GetCurrentSafetyOptions(self):
  682. return self.safetyOptions
  683. def ProcessNewNamedItemsConnections(self):
  684. # Process all sub-items.
  685. for item in self.subItems.values():
  686. if not item.createdConnections: # Fast-track!
  687. item.CreateConnections()
  688. def RegisterNewNamedItems(self):
  689. # Register all sub-items.
  690. for item in self.subItems.values():
  691. if not item.isRegistered: # Fast-track!
  692. self.RegisterNamedItem(item)
  693. def RegisterNamedItem(self, item):
  694. item.Register()
  695. def CheckConnectedOrDisconnected(self):
  696. if self.scriptState in [axscript.SCRIPTSTATE_CONNECTED, axscript.SCRIPTSTATE_DISCONNECTED]:
  697. return
  698. RaiseAssert(winerror.E_UNEXPECTED, "Not connected or disconnected - %d" % self.scriptState)
  699. def Connect(self):
  700. self.ProcessNewNamedItemsConnections()
  701. self.RegisterNewNamedItems()
  702. self.ConnectEventHandlers()
  703. def Run(self):
  704. # trace("AXScript running...")
  705. if self.scriptState != axscript.SCRIPTSTATE_INITIALIZED and self.scriptState != axscript.SCRIPTSTATE_STARTED:
  706. raise Exception(scode=winerror.E_UNEXPECTED)
  707. # self._DumpNamedItems_()
  708. self.ExecutePendingScripts()
  709. self.DoRun()
  710. def Stop(self):
  711. # Stop all executing scripts, and disconnect.
  712. if self.scriptState == axscript.SCRIPTSTATE_CONNECTED:
  713. self.Disconnect()
  714. # Reset back to initialized.
  715. self.Reset()
  716. def Disconnect(self):
  717. self.CheckConnectedOrDisconnected()
  718. try:
  719. self.DisconnectEventHandlers()
  720. except pythoncom.com_error:
  721. # Ignore errors when disconnecting.
  722. pass
  723. self.ChangeScriptState(axscript.SCRIPTSTATE_DISCONNECTED)
  724. def ConnectEventHandlers(self):
  725. # trace ("Connecting to event handlers")
  726. for item in self.subItems.values():
  727. item.Connect()
  728. self.ChangeScriptState(axscript.SCRIPTSTATE_CONNECTED);
  729. def DisconnectEventHandlers(self):
  730. # trace ("Disconnecting from event handlers")
  731. for item in self.subItems.values():
  732. item.Disconnect()
  733. def Reset(self):
  734. # Keeping persistent engine state, reset back an initialized state
  735. self.ResetNamedItems()
  736. self.ChangeScriptState(axscript.SCRIPTSTATE_INITIALIZED)
  737. def ChangeScriptState(self, state):
  738. #print " ChangeScriptState with %s - currentstate = %s" % (state_map.get(state),state_map.get(self.scriptState))
  739. self.DisableInterrupts()
  740. try:
  741. self.scriptState = state
  742. try:
  743. if self.scriptSite: self.scriptSite.OnStateChange(state)
  744. except pythoncom.com_error as xxx_todo_changeme:
  745. (hr, desc, exc, arg) = xxx_todo_changeme.args
  746. pass # Ignore all errors here - E_NOTIMPL likely from scriptlets.
  747. finally:
  748. self.EnableInterrupts()
  749. # This stack frame is debugged - therefore we do as little as possible in it.
  750. def _ApplyInScriptedSection(self, fn, args):
  751. if self.debugManager:
  752. self.debugManager.OnEnterScript()
  753. if self.debugManager.adb.appDebugger:
  754. return self.debugManager.adb.runcall(fn, *args)
  755. else:
  756. return fn(*args)
  757. else:
  758. return fn(*args)
  759. def ApplyInScriptedSection(self, codeBlock, fn, args):
  760. self.BeginScriptedSection()
  761. try:
  762. try:
  763. # print "ApplyInSS", codeBlock, fn, args
  764. return self._ApplyInScriptedSection(fn, args)
  765. finally:
  766. if self.debugManager: self.debugManager.OnLeaveScript()
  767. self.EndScriptedSection()
  768. except:
  769. self.HandleException(codeBlock)
  770. # This stack frame is debugged - therefore we do as little as possible in it.
  771. def _CompileInScriptedSection(self, code, name, type):
  772. if self.debugManager: self.debugManager.OnEnterScript()
  773. return compile(code, name, type)
  774. def CompileInScriptedSection(self, codeBlock, type, realCode = None):
  775. if codeBlock.codeObject is not None: # already compiled
  776. return 1
  777. if realCode is None:
  778. code = codeBlock.codeText
  779. else:
  780. code = realCode
  781. name = codeBlock.GetFileName()
  782. self.BeginScriptedSection()
  783. try:
  784. try:
  785. codeObject = self._CompileInScriptedSection(RemoveCR(code), name, type)
  786. codeBlock.codeObject = codeObject
  787. return 1
  788. finally:
  789. if self.debugManager: self.debugManager.OnLeaveScript()
  790. self.EndScriptedSection()
  791. except:
  792. self.HandleException(codeBlock)
  793. # This stack frame is debugged - therefore we do as little as possible in it.
  794. def _ExecInScriptedSection(self, codeObject, globals, locals = None):
  795. if self.debugManager:
  796. self.debugManager.OnEnterScript()
  797. if self.debugManager.adb.appDebugger:
  798. return self.debugManager.adb.run(codeObject, globals, locals)
  799. else:
  800. exec(codeObject, globals, locals)
  801. else:
  802. exec(codeObject, globals, locals)
  803. def ExecInScriptedSection(self, codeBlock, globals, locals = None):
  804. if locals is None: locals = globals
  805. assert not codeBlock.beenExecuted, "This code block should not have been executed"
  806. codeBlock.beenExecuted = 1
  807. self.BeginScriptedSection()
  808. try:
  809. try:
  810. self._ExecInScriptedSection(codeBlock.codeObject, globals, locals)
  811. finally:
  812. if self.debugManager: self.debugManager.OnLeaveScript()
  813. self.EndScriptedSection()
  814. except:
  815. self.HandleException(codeBlock)
  816. def _EvalInScriptedSection(self, codeBlock, globals, locals = None):
  817. if self.debugManager:
  818. self.debugManager.OnEnterScript()
  819. if self.debugManager.adb.appDebugger:
  820. return self.debugManager.adb.runeval(codeBlock, globals, locals)
  821. else:
  822. return eval(codeBlock, globals, locals)
  823. else:
  824. return eval(codeBlock, globals, locals)
  825. def EvalInScriptedSection(self, codeBlock, globals, locals = None):
  826. if locals is None: locals = globals
  827. assert not codeBlock.beenExecuted, "This code block should not have been executed"
  828. codeBlock.beenExecuted = 1
  829. self.BeginScriptedSection()
  830. try:
  831. try:
  832. return self._EvalInScriptedSection(codeBlock.codeObject, globals, locals)
  833. finally:
  834. if self.debugManager: self.debugManager.OnLeaveScript()
  835. self.EndScriptedSection()
  836. except:
  837. self.HandleException(codeBlock)
  838. def HandleException(self, codeBlock):
  839. # NOTE - Never returns - raises a ComException
  840. exc_type, exc_value, exc_traceback = sys.exc_info()
  841. # If a SERVER exception, re-raise it. If a client side COM error, it is
  842. # likely to have originated from the script code itself, and therefore
  843. # needs to be reported like any other exception.
  844. if IsCOMServerException(exc_type):
  845. # Ensure the traceback doesnt cause a cycle.
  846. exc_traceback = None
  847. raise
  848. # It could be an error by another script.
  849. if issubclass(pythoncom.com_error, exc_type) and exc_value.hresult==axscript.SCRIPT_E_REPORTED:
  850. # Ensure the traceback doesnt cause a cycle.
  851. exc_traceback = None
  852. raise Exception(scode=exc_value.hresult)
  853. exception = error.AXScriptException(self, \
  854. codeBlock, exc_type, exc_value, exc_traceback)
  855. # Ensure the traceback doesnt cause a cycle.
  856. exc_traceback = None
  857. result_exception = error.ProcessAXScriptException(self.scriptSite, self.debugManager, exception)
  858. if result_exception is not None:
  859. try:
  860. self.scriptSite.OnScriptTerminate(None, result_exception)
  861. except pythoncom.com_error:
  862. pass # Ignore errors telling engine we stopped.
  863. # reset ourselves to 'connected' so further events continue to fire.
  864. self.SetScriptState(axscript.SCRIPTSTATE_CONNECTED)
  865. raise result_exception
  866. # I think that in some cases this should just return - but the code
  867. # that could return None above is disabled, so it never happens.
  868. RaiseAssert(winerror.E_UNEXPECTED, "Don't have an exception to raise to the caller!")
  869. def BeginScriptedSection(self):
  870. if self.scriptSite is None:
  871. raise Exception(scode=winerror.E_UNEXPECTED)
  872. self.scriptSite.OnEnterScript()
  873. def EndScriptedSection(self):
  874. if self.scriptSite is None:
  875. raise Exception(scode=winerror.E_UNEXPECTED)
  876. self.scriptSite.OnLeaveScript()
  877. def DisableInterrupts(self):
  878. pass
  879. def EnableInterrupts(self):
  880. pass
  881. def GetNamedItem(self, name):
  882. try:
  883. return self.subItems[name]
  884. except KeyError:
  885. raise Exception(scode=winerror.E_INVALIDARG)
  886. def GetNamedItemClass(self):
  887. return ScriptItem
  888. def _AddScriptCodeBlock(self, codeBlock):
  889. self.scriptCodeBlocks[codeBlock.GetFileName()] = codeBlock
  890. if self.debugManager:
  891. self.debugManager.AddScriptBlock(codeBlock)
  892. if __name__=='__main__':
  893. print("This is a framework class - please use pyscript.py etc")
  894. def dumptypeinfo(typeinfo):
  895. return
  896. attr = typeinfo.GetTypeAttr()
  897. # Loop over all methods
  898. print("Methods")
  899. for j in range(attr[6]):
  900. fdesc = list(typeinfo.GetFuncDesc(j))
  901. id = fdesc[0]
  902. try:
  903. names = typeinfo.GetNames(id)
  904. except pythoncom.ole_error:
  905. names = None
  906. doc = typeinfo.GetDocumentation(id)
  907. print(" ", names, "has attr", fdesc)
  908. # Loop over all variables (ie, properties)
  909. print("Variables")
  910. for j in range(attr[7]):
  911. fdesc = list(typeinfo.GetVarDesc(j))
  912. names = typeinfo.GetNames(id)
  913. print(" ", names, "has attr", fdesc)