iādZddlZddlZddlZddlZddlZddlZddlZddlmZm Z m Z m Z m Z m Z mZmZmZddlmZdZdZejejZejejZdZdZd Zd Zd ZGd d ZGddeZ Gdde Z!Gdde!Z"GddeZ#e!Z$dZ%dZ&dZ'dS)a Policies Note that Dispatchers are now implemented in "dispatcher.py", but are still documented here. Policies A policy is an object which manages the interaction between a public Python object, and COM . In simple terms, the policy object is the object which is actually called by COM, and it invokes the requested method, fetches/sets the requested property, etc. See the @win32com.server.policy.CreateInstance@ method for a description of how a policy is specified or created. Exactly how a policy determines which underlying object method/property is obtained is up to the policy. A few policies are provided, but you can build your own. See each policy class for a description of how it implements its policy. There is a policy that allows the object to specify exactly which methods and properties will be exposed. There is also a policy that will dynamically expose all Python methods and properties - even those added after the object has been instantiated. Dispatchers A Dispatcher is a level in front of a Policy. A dispatcher is the thing which actually receives the COM calls, and passes them to the policy object (which in turn somehow does something with the wrapped object). It is important to note that a policy does not need to have a dispatcher. A dispatcher has the same interface as a policy, and simply steps in its place, delegating to the real policy. The primary use for a Dispatcher is to support debugging when necessary, but without imposing overheads when not (ie, by not using a dispatcher at all). There are a few dispatchers provided - "tracing" dispatchers which simply prints calls and args (including a variation which uses win32api.OutputDebugString), and a "debugger" dispatcher, which can invoke the debugger when necessary. Error Handling It is important to realise that the caller of these interfaces may not be Python. Therefore, general Python exceptions and tracebacks aren't much use. In general, there is an COMException class that should be raised, to allow the framework to extract rich COM type error information. The general rule is that the **only** exception returned from Python COM Server code should be an COMException instance. Any other Python exception should be considered an implementation bug in the server (if not, it should be handled, and an appropriate COMException instance raised). Any other exception is considered "unexpected", and a dispatcher may take special action (see Dispatchers above) Occasionally, the implementation will raise the policy.error error. This usually means there is a problem in the implementation that the Python programmer should fix. For example, if policy is asked to wrap an object which it can not support (because, eg, it does not provide _public_methods_ or _dynamic_) then policy.error will be raised, indicating it is a Python programmers problem, rather than a COM error. N) DISPATCH_METHODDISPATCH_PROPERTYGETDISPATCH_PROPERTYPUTDISPATCH_PROPERTYPUTREFDISPID_EVALUATEDISPID_NEWENUMDISPID_PROPERTYPUTDISPID_STARTENUM DISPID_VALUE) COMExceptionzGreg Stein and Mark HammondzCLSID\%s\PythonCOMzCLSID\%s\PythonCOMPolicyzCLSID\%s\PythonCOMDispatcherzCLSID\%s\PythonCOMPathc tjtjt|zd}|D]0}|t jvr t jd|1n#tj $rYnwxYw tjtjt|z}t|}n#tj $r t}YnwxYw tjtjt|z}|rt|}n#tj $rd}YnwxYw|r ||d}n |d}|||S)aCreate a new instance of the specified IID The COM framework **always** calls this function to create a new instance for the specified CLSID. This function looks up the registry for the name of a policy, creates the policy, and asks the policy to create the specified object by calling the _CreateInstance_ method. Exactly how the policy creates the instance is up to the policy. See the specific policy documentation for more details. ;rN)win32api RegQueryValuewin32conHKEY_CLASSES_ROOT regAddnPathsplitsyspathinserterror regPolicy resolve_func DefaultPolicy regDispatcher_CreateInstance_)clsidreqIID addnPathsnewPathpolicy dispatcherretObjs DC:\PYTHON\_runtimes\venv\Lib\site-packages\win32com/server/policy.pyCreateInstancer'ls *  & e(;  %** ! , ,Gch&&7+++ , >     '(BIPUDUVVf%% >+  & (=    2%j11J > FD))  " "5& 1 11s6A-A00BB6B==CC8DD'&D'ceZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZdZdZdZdZdZdZdS)BasicWrapPolicyaThe base class of policies. Normally not used directly (use a child class, instead) This policy assumes we are wrapping another object as the COM server. This supports the delegation of the core COM entry points to either the wrapped object, or to a child class. This policy supports the following special attributes on the wrapped object _query_interface_ -- A handler which can respond to the COM 'QueryInterface' call. _com_interfaces_ -- An optional list of IIDs which the interface will assume are valid for the object. _invoke_ -- A handler which can respond to the COM 'Invoke' call. If this attribute is not provided, then the default policy implementation is used. If this attribute does exist, it is responsible for providing all required functionality - ie, the policy _invoke_ method is not invoked at all (and nor are you able to call it!) _getidsofnames_ -- A handler which can respond to the COM 'GetIDsOfNames' call. If this attribute is not provided, then the default policy implementation is used. If this attribute does exist, it is responsible for providing all required functionality - ie, the policy _getidsofnames_ method is not invoked at all (and nor are you able to call it!) IDispatchEx functionality: _invokeex_ -- Very similar to _invoke_, except slightly different arguments are used. And the result is just the _real_ result (rather than the (hresult, argErr, realResult) tuple that _invoke_ uses. This is the new, prefered handler (the default _invoke_ handler simply called _invokeex_) _getdispid_ -- Very similar to _getidsofnames_, except slightly different arguments are used, and only 1 property at a time can be fetched (which is all we support in getidsofnames anyway!) This is the new, prefered handler (the default _invoke_ handler simply called _invokeex_) _getnextdispid_- uses self._name_to_dispid_ to enumerate the DISPIDs c8|||dSdS)zInitialise the policy object Params: object -- The object to wrap. May be None *iff* @BasicWrapPolicy._CreateInstance_@ will be called immediately after this to setup a brand new object N)_wrap_selfobjects r&__init__zBasicWrapPolicy.__init__s*   KK       c  tjtjt|z}n.#tj$rt dt|zdwxYwt|}|| tj ||S#tj $rE}|j \}}}} ddl m} d|d| |d|d|}tj |||| d }~wwxYw) zCreates a new instance of a **wrapped** object This method looks up a "@win32com.server.policy.regSpec@" % clsid entry in the registry (using @DefaultPolicy@) z)The object is not correctly registered - z key can not be readr)IIDToInterfaceNamez The object 'z3' was created, but does not support the interface 'z'(z): N)rrrrregSpecr ValueError call_funcr+ pythoncom WrapObject com_errorargs win32com.utilr2) r-rr classSpecmyobxxx_todo_changemehrdescexcargr2s r&rz BasicWrapPolicy._CreateInstance_sR   .*GeOII~   aGeOaaa  ## D :'f55 5" : : :#4#9 RsC 8 8 8 8 8 8NtNN0088NN   ""8?Q }}VT64888 7&Ac Ftd|||||ddfSNS_OKrErds r&rDzBasicWrapPolicy._invoke_,s'RvtT4PPPPr0ct|dkrttjd|||S)zThe main COM entry-point for GetIDsOfNames. This checks the validity of the arguments, and calls the _getidsofnames_ helper. r z$Cannot support member argument namesr])lenr rbDISP_E_INVALIDrFr-namesrfs r&_GetIDsOfNames_zBasicWrapPolicy._GetIDsOfNames_2sK u::>>-; ##E4000r0c<||ddfSNrrGrrs r&rFzBasicWrapPolicy._getidsofnames_>s  q1--//r0c.|||SNrwr-namefdexs r& _GetDispID_zBasicWrapPolicy._GetDispID_Fsd+++r0c |j|S#t$rttjwxYwNr^)rJr`rar rbDISP_E_UNKNOWNNAMErzs r&rGzBasicWrapPolicy._getdispid_IsQ B(6 6 B B BX%@AAA A Bs !%Act|trJ |j|}n)#t$rt t jdwxYw|||||||S)zZThe main COM entry-point for InvokeEx. This calls the _invokeex_ helper. r\r]) rMr_rJr`rar rbrcrEr-rerfrgr9kwargsserviceProviders r& _InvokeEx_zBasicWrapPolicy._InvokeEx_Qs fc " "  .v||~~>   ""8?Q vtVT6?SSSric td)z]A stub for _invokeex_ - should never be called. Simply raises an exception. z0This class does not provide _invokeex_ semantics)NotImplementedErrorrs r&rEzBasicWrapPolicy._invokeex_`s ""TUUUr0c.|||Sry)_deletememberbyname_rzs r&_DeleteMemberByName_z$BasicWrapPolicy._DeleteMemberByName_hs((t444r0c6ttjrr rb E_NOTIMPLrzs r&rz$BasicWrapPolicy._deletememberbyname_k!34444r0c,||Sry)_deletememberbydispidr-ids r&_DeleteMemberByDispID_z&BasicWrapPolicy._DeleteMemberByDispID_ns))"---r0c6ttjrrrs r&_deletememberbydispid_z&BasicWrapPolicy._deletememberbydispid_qrr0c.|||Sry)_getmemberproperties_r-rr|s r&_GetMemberProperties_z%BasicWrapPolicy._GetMemberProperties_ts))"d333r0c6ttjrrrs r&rz%BasicWrapPolicy._getmemberproperties_wrr0c,||Sry)_getmembername_r-res r&_GetMemberName_zBasicWrapPolicy._GetMemberName_zs##F+++r0c6ttjrrrs r&rzBasicWrapPolicy._getmembername_}rr0c.|||Sry)_getnextdispid_)r-r|res r&_GetNextDispID_zBasicWrapPolicy._GetNextDispID_s##D&111r0cjd|jD}||tkr|dS |||dzS#t $rt tjt$rt tj wxYw)Nc(g|]}|tk |SrZ)r ).0rs r& z3BasicWrapPolicy._getnextdispid_..s#UUUbbDT>T>Tr>T>T>Tr0rr r) rJvaluessortr indexr4r rb E_UNEXPECTED IndexErrorS_FALSE)r-r|reidss r&rzBasicWrapPolicy._getnextdispid_sUUD188::UUU  % % %q6M ;399V,,q011 @ @ @")>???? ; ; ;")9:::: ;s A**AB2c*|Sry)_getnamespaceparentr-s r&_GetNameSpaceParent_z$BasicWrapPolicy._GetNameSpaceParent_s'')))r0c6ttjrrrs r&_getnamespaceparent_z$BasicWrapPolicy._getnamespaceparent_rr0N)__name__ __module__ __qualname____doc__r/rr+rXrCrhrDrtrFr}rGrrErrrrrrrrrrrrrZr0r&r)r)s  D    :::8&'&'&'R+++ 9 9 9QQQ 1 1 1000,,,BBB T T TVVV555555...555444555,,,555222 ; ; ;***55555r0r)ceZdZdZdZdZdS)MappedWrapPolicyaKWraps an object using maps to do its magic This policy wraps up a Python object, using a number of maps which translate from a Dispatch ID and flags, into an object to call/getattr, etc. It is the responsibility of derived classes to determine exactly how the maps are filled (ie, the derived classes determine the map filling policy. This policy supports the following special attributes on the wrapped object _dispid_to_func_/_dispid_to_get_/_dispid_to_put_ -- These are dictionaries (keyed by integer dispid, values are string attribute names) which the COM implementation uses when it is processing COM requests. Note that the implementation uses this dictionary for its own purposes - not a copy - which means the contents of these dictionaries will change as the object is used. c$t|||j}t|dr |j|_ni|_t|dr |j|_ni|_t|dr|j|_dSi|_dS)N_dispid_to_func__dispid_to_get__dispid_to_put_)r)r+rKrLrrr)r-r.rSs r&r+zMappedWrapPolicy._wrap_stV,,, Z 2) * * '$&$7D ! !$&D ! 2( ) ) &#%#5D #%D 2( ) ) &#%#5D #%D r0c||jvr |j|S||jvr |j|S||jvr |j|Sttjr)rrrr rbrcrs r&rz MappedWrapPolicy._getmembername_sj T* * *(0 0 t+ + +'/ / t+ + +'/ /X%CDDD Dr0N)rrrrr+rrZr0r&rrsA$&&& EEEEEr0rc6eZdZdZdZdZdZdZdZdZ dS) DesignatedWrapPolicyaPA policy which uses a mapping to link functions and dispid A MappedWrappedPolicy which allows the wrapped object to specify, via certain special named attributes, exactly which methods and properties are exposed. All a wrapped object need do is provide the special attributes, and the policy will handle everything else. Attributes: _public_methods_ -- Required, unless a typelib GUID is given -- A list of strings, which must be the names of methods the object provides. These methods will be exposed and callable from other COM hosts. _public_attrs_ A list of strings, which must be the names of attributes on the object. These attributes will be exposed and readable and possibly writeable from other COM hosts. _readonly_attrs_ -- A list of strings, which must also appear in _public_attrs. These attributes will be readable, but not writable, by other COM hosts. _value_ -- A method that will be called if the COM host requests the "default" method (ie, calls Invoke with dispid==DISPID_VALUE) _NewEnum -- A method that will be called if the COM host requests an enumerator on the object (ie, calls Invoke with dispid==DISPID_NEWENUM.) It is the responsibility of the method to ensure the returned object conforms to the required Enum interface. _typelib_guid_ -- The GUID of the typelibrary with interface definitions we use. _typelib_version_ -- A tuple of (major, minor) with a default of 1,1 _typelib_lcid_ -- The LCID of the typelib, default = LOCALE_USER_DEFAULT _Evaluate -- Dunno what this means, except the host has called Invoke with dispid==DISPID_EVALUATE! See the COM documentation for details. ct|dd}|`t|dd\}}t|dd}ddlm}dt|dgD}||||||}ng}t||t |d st |dstd |j D]!\} } | |j | <"|j D]!\} } | |j | <"|j D]!\} } | |j | <"|D]|\} } } | |j | <| tkr | |j| <8| tt fvr | |j | <S| t"kr | |j | <itd | | fzt |d rd |j t$<d |j t&<t |d rt(|j d<d |jt(<t |drt*|j d<d|jt*<|d} t |drt |dr|j} ng} |jD]{} |j | } | 3| } | |j | <|| } | |j | <| | vr | |j | <|t|d gD]m} |j | } | 3| } | |j | <|| } | |j| <nd|_dS)N_typelib_guid__typelib_version_r r_typelib_lcid_r) universalcpg|]3}t|tj|d1|4S)rI)rMrNrO startswith)rrTs r&rz/DesignatedWrapPolicy._wrap_..sS!!Z%788BCcARARr0rH_public_methods_zwObject does not support DesignatedWrapPolicy, as it does not have either _public_methods_ or _typelib_guid_ attributes.zunexpected invkind: %d (%s)_value__NewEnum_newenum _Evaluate _evaluatei_public_attrs__readonly_attrs_)getattrwin32comrRegisterInterfacesrr+rLr4ritemsrJr`rrrrrrr r rr_allocnextdispidrrget _typeinfos_)r-rStlb_guid tlb_major tlb_minortlb_lcidr interfacesuniversal_datarer{invkind next_dispidreadonlys r&r+zDesignatedWrapPolicy._wrap_s12/66  #*2/BF#K#K Iyr#3Q77H * * * * * *  %7<<J '99(Iy*NN Nb)))r-.. wrCS7T7T ^  !17799 9 9LFD28D !$**,, / / 06688 9 9LFD28D !$**,, / / 06688 9 9LFD28D !$**,, / /&4 R R !FGT28D !$**,, //))04%f--13JKKK/3$V,,000/3$V,, !>'4!PQQQ 2y ! ! A1:D  .7@D !3 4 2z " " ?0>D !* -4>D !. 1 2{ # # A1@D !+ .5@D !/ 2++C00 2' ( ( 8r-.. .) 8 8.224::<<@@>(F:@D)$**,,7"&"7"7 "D"DK/3$V,x''37D(0B 2B77 1 1D*..tzz||<>  I&tz3FOO 9&xIFF??$$Z0  E '/'8'8'?'?$ 9(%;&&&)&     s-B  BBcj|j||_t|jSry)rrrprs r&_GetTypeInfoCount_z'DesignatedWrapPolicy._GetTypeInfoCount_Ns0   ##5577D 4#$$$r0c|j||_|dks|t|jkrttjd|j|fS)Nrr)rrrpr rbDISP_E_BADINDEX)r-rrfs r& _GetTypeInfo_z"DesignatedWrapPolicy._GetTypeInfo_Ssd   ##5577D  199T%5!6!666X%=>>> >$"5)))r0cJ |dz }||jvr||jvr ||jvr|S#Nr )rrr)r- last_dispids r&rz%DesignatedWrapPolicy._allocnextdispidZsF # 1 K4#888t';;;t';;;"" #r0c |tzr |j|} t|j|}n(#t$rt t jwxYw ||S#t$rE} t|  ddkrtd| d|d|dd} ~ wwxYw#t$r'|tzst t jYnwxYw|tzrm |j|} n(#t$rt t jwxYwt|j| } t| t jr| |} | S|t$t&zzr |j|} n(#t$rt t jwxYwt|jd| zd} t| t jr4tt|j| dt jr| |nt+|j| |ddSt t jd ) Nr argumentsrz ** TypeError z calling function ()Setzinvalid wFlagsr])rrrrKAttributeErrorr rbrc TypeErrorr_findprintrarrrMtypes MethodTyperrrsetattr E_INVALIDARG) r-rerfrgr9kwArgsrfuncnamefuncvr{retobfns r&rEzDesignatedWrapPolicy._invokeex_ds O #  08M"4:x88DD%MMM&X-KLLLLM4;& 1vv{{;//144UaUU4UUDUUUVVV     44&&< * ( (  I+F3 I I I")GHHHH IDJ--E%!122 %t L ),CC D  I+F3 I I I")GHHHH IUT\488B"e.// 3J D$//1A55 3D  D$q'222 F!6=MNNNNsK B00%AA B-(AB((B-0.C! C!/ C==%D". E<<%F!N) rrrrr+rrrrrErZr0r&rrsBR R R h&%%% ***###6O6O6O6O6Or0rceZdZdZdZdZdS)EventHandlerPolicya&The default policy used by event handlers in the win32com.client package. In addition to the base policy, this provides argument conversion semantics for params: dispatch params are converted to dispatch objects NOTE: Later, we may allow the object to override this process?? cg}|D]}t|trddl} | j|}ngt|t rR ddl} | j|tj}n#tj $rYnwxYw| |t||fSrv) rM IDispatchTypewin32com.clientclientDispatch IUnknownTypeQueryInterfacer6 IID_IDispatchrrRtuple) r-r9rrerfrgrretrArs r&_transform_args_z#EventHandlerPolicy._transform_args_s  C#}-- &&&&o..s33C.. ****"/22**9+BCCCC!D JJsOOOOSzz6!!s;B  BBc ||||||||\}}t|||||||Sry)rrrE)r-rerfrgr9rrs r&rEzEventHandlerPolicy._invokeex_sQ,, &&$  f$.. &$fo   r0N)rrrrrrErZr0r&rrs<"""&     r0rc*eZdZdZdZdZdZdZdS) DynamicPolicya*A policy which dynamically (ie, at run-time) determines public interfaces. A dynamic policy is used to dynamically dispatch methods and properties to the wrapped object. The list of objects and properties does not need to be known in advance, and methods or properties added to the wrapped object after construction are also handled. The wrapped object must provide the following attributes: _dynamic_ -- A method that will be called whenever an invoke on the object is called. The method is called with the name of the underlying method/property (ie, the mapping of dispid to/from name has been resolved.) This name property may also be '_value_' to indicate the default, and '_NewEnum' to indicate a new enumerator is requested. ct||t|jdst ddx|_|_tdtdi|_ dS)N _dynamic_z*Object does not support Dynamic COM Policyirr) r)r+rLrKr4_next_dynamic_ _min_dynamic_r r_dyn_dispid_to_name_r,s r&r+zDynamicPolicy._wrap_sftV,,,tz;// KIJJ J377d0 ) J% !!!r0c|} |j|S#t$r*|jdzx}|_||j|<||j|<|cYSwxYwr)r`rJrarr)r-r{r|lnameres r&rGzDynamicPolicy._getdispid_su  (/ /   +/+>+B BFT(+1D !% (04D %f -MMM  s #1AAc Ftd|||||ddfSrkrmrds r&rDzDynamicPolicy._invoke_s%RvtT4PPPPr0c |j|}n)#t$rttjdwxYw|j||||S)Nr\r])rrar rbrcrKr)r-rerfrgr9rrr{s r&rEzDynamicPolicy._invokeex_so  ,V4DD   4;M  z##D$===s &6N)rrrrr+rGrDrErZr0r&rrs]"      QQQ > > > > >r0rc |d}|d|}||dzd}t|}t||S#t$rt |cYSwxYw)zResolve a function by name Given a function specified by 'module.function', return a callable object (ie, the function itself) .Nr )rindex_import_modulerr4globals)specidxmnamefnamemodules r&rrs kk#TcT S1WYY &&vu%%% yysA A A.-A.c&t||S)zrCall a function specified by name. Call a function specified by 'module.function' and return the result. )r)r%r9s r&r5r5s <  t $$r0cDt|tj|S)zImport a module just like the 'import' statement. Having this function is much nicer for importing arbitrary modules than using the 'exec' keyword. It is more efficient and obvious to the reader. ) __import__rmodules)r's r&r#r#s! u ;u r0)(rrrr6rNrrrbrrrrrrr r r exceptionr __author__rnTypeIIDsrr  IID_IUnknownrr3rrrr'r)rrrrrrr5r#rZr0r&r2sbBBH                       $##### * "9#:; !)"89  ! ( 0 ( (2(2(2V}5}5}5}5}5}5}5}5@+E+E+E+E+E+E+E+E\UOUOUOUOUO+UOUOUOp# # # # # -# # # L5>5>5>5>5>O5>5>5>p% &%%%     r0