home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32com_server_register.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  15.4 KB  |  422 lines

  1. """Utilities for registering objects.
  2.  
  3. This module contains utility functions to register Python objects as
  4. valid COM Servers.  The RegisterServer function provides all information
  5. necessary to allow the COM framework to respond to a request for a COM object,
  6. construct the necessary Python object, and dispatch COM events.
  7.  
  8. """
  9. import sys
  10. import win32api
  11. import win32con
  12. import pythoncom
  13. import winerror
  14. import os
  15.  
  16. CATID_PythonCOMServer = "{B3EF80D0-68E2-11D0-A689-00C04FD658FF}"
  17.  
  18. def _set_subkeys(keyName, valueDict, base=win32con.HKEY_CLASSES_ROOT):
  19.   hkey = win32api.RegCreateKey(base, keyName)
  20.   try:
  21.     for key, value in valueDict.items():
  22.       win32api.RegSetValueEx(hkey, key, None, win32con.REG_SZ, value)
  23.   finally:
  24.     win32api.RegCloseKey(hkey)
  25.             
  26. def _set_string(path, value, base=win32con.HKEY_CLASSES_ROOT):
  27.   "Set a string value in the registry."
  28.  
  29.   win32api.RegSetValue(base,
  30.                        path,
  31.                        win32con.REG_SZ,
  32.                        value)
  33.  
  34. def _get_string(path, base=win32con.HKEY_CLASSES_ROOT):
  35.   "Get a string value from the registry."
  36.  
  37.   try:
  38.     return win32api.RegQueryValue(base, path)
  39.   except win32api.error:
  40.     return None
  41.  
  42. def _remove_key(path, base=win32con.HKEY_CLASSES_ROOT):
  43.   "Remove a string from the registry."
  44.  
  45.   try:
  46.     win32api.RegDeleteKey(base, path)
  47.   except win32api.error, (code, fn, msg):
  48.     if code != winerror.ERROR_FILE_NOT_FOUND:
  49.       raise win32api.error, (code, fn, msg)
  50.  
  51. def recurse_delete_key(path, base=win32con.HKEY_CLASSES_ROOT):
  52.   """Recursively delete registry keys.
  53.  
  54.   This is needed since you can't blast a key when subkeys exist.
  55.   """
  56.   try:
  57.     h = win32api.RegOpenKey(base, path)
  58.   except win32api.error, (code, fn, msg):
  59.     if code != winerror.ERROR_FILE_NOT_FOUND:
  60.       raise win32api.error, (code, fn, msg)
  61.   else:
  62.     # parent key found and opened successfully. do some work, making sure
  63.     # to always close the thing (error or no).
  64.     try:
  65.       # remove all of the subkeys
  66.       while 1:
  67.         try:
  68.           subkeyname = win32api.RegEnumKey(h, 0)
  69.         except win32api.error, (code, fn, msg):
  70.           if code != winerror.ERROR_NO_MORE_ITEMS:
  71.             raise win32api.error, (code, fn, msg)
  72.           break
  73.         recurse_delete_key(path + '\\' + subkeyname, base)
  74.  
  75.       # remove the parent key
  76.       _remove_key(path, base)
  77.     finally:
  78.       win32api.RegCloseKey(h)
  79.  
  80. def _cat_registrar():
  81.   return pythoncom.CoCreateInstance(
  82.     pythoncom.CLSID_StdComponentCategoriesMgr,
  83.     None,
  84.     pythoncom.CLSCTX_INPROC_SERVER,
  85.     pythoncom.IID_ICatRegister
  86.     )
  87.     
  88. def _find_localserver_exe(mustfind):
  89.   # First a concession for freeze...
  90.   if pythoncom.frozen: return win32api.GetShortPathName(sys.executable)
  91.   exeBaseName = "pythonw.exe"
  92.   # First see if in the same directory as this .EXE
  93.   exeName = os.path.join( os.path.split(sys.executable)[0], exeBaseName )
  94.   try:
  95.     os.stat(exeName)
  96.   except os.error:
  97.     # See if the registry has some info.
  98.     try:
  99.       key = "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % sys.winver
  100.       path = win32api.RegQueryValue( win32con.HKEY_LOCAL_MACHINE, key )
  101.       exeName = os.path.join( path, exeBaseName )
  102.       os.stat(exeName)
  103.     except (win32api.error, os.error):
  104.       if mustfind:
  105.         raise RuntimeError, "Can not locate the program '%s'" % exeBaseName
  106.       return None
  107.   return exeName
  108.  
  109. def _find_localserver_module():
  110.   import win32com.server
  111.   path = win32com.server.__path__[0]
  112.   baseName = "localserver"
  113.   pyfile = os.path.join(path, baseName + ".py")
  114.   try:
  115.     os.stat(pyfile)
  116.   except os.error:
  117.     # See if we have a compiled extension
  118.     if __debug__:
  119.       ext = ".pyc"
  120.     else:
  121.       ext = ".pyo"
  122.     pyfile = os.path.join(path, baseName + ext)
  123.     try:
  124.       os.stat(pyfile)
  125.     except os.error:
  126.       raise RuntimeError, "Can not locate the Python module 'win32com.server.%s'" % baseName
  127.   return pyfile
  128.  
  129. def RegisterServer(clsid, 
  130.                    pythonInstString=None, 
  131.                    desc=None,
  132.                    progID=None, verProgID=None,
  133.                    defIcon=None,
  134.                    threadingModel="both",
  135.                    policy=None,
  136.                    catids=[], other={},
  137.                    addPyComCat=1,
  138.                    dispatcher = None,
  139.                    clsctx = None,
  140.                    addnPath = None
  141.                   ):
  142.   """Registers a Python object as a COM Server.  This enters almost all necessary
  143.      information in the system registry, allowing COM to use the object.
  144.  
  145.      clsid -- The (unique) CLSID of the server.
  146.      pythonInstString -- A string holding the instance name that will be created
  147.                    whenever COM requests a new object.
  148.      desc -- The description of the COM object.
  149.      progID -- The user name of this object (eg, Word.Document)
  150.      verProgId -- The user name of this version's implementation (eg Word.6.Document)
  151.      defIcon -- The default icon for the object.
  152.      threadingModel -- The threading model this object supports.
  153.      policy -- The policy to use when creating this object.
  154.      catids -- A list of category ID's this object belongs in.
  155.      other -- A dictionary of extra items to be registered.
  156.      addPyComCat -- A flag indicating if the object should be added to the list
  157.               of Python servers installed on the machine.
  158.      dispatcher -- The dispatcher to use when creating this object.
  159.      clsctx -- One of the CLSCTX_* constants.
  160.      addnPath -- An additional path the COM framework will add to sys.path
  161.                  before attempting to create the object.
  162.   """
  163.  
  164.  
  165.   ### backwards-compat check
  166.   ### Certain policies do not require a "class name", just the policy itself.
  167.   if not pythonInstString and not policy:
  168.     raise TypeError, 'You must specify either the Python Class or Python Policy which implement the COM object.'
  169.  
  170.   keyNameRoot = "CLSID\\%s" % str(clsid)
  171.   _set_string(keyNameRoot, desc)
  172.  
  173.   # Also register as an "Application" so DCOM etc all see us.
  174.   _set_string("AppID\\%s" % clsid, progID)
  175.   # Depending on contexts requested, register the specified server type.
  176.   if not clsctx or clsctx & pythoncom.CLSCTX_INPROC_SERVER:
  177.     # get the module loaded
  178.     try:
  179.       # We dont need to put the path.  It will either be in the system directory (in which
  180.       # case it will be found) or maybe in the clients directory, in which case we assume
  181.       # the correct one will be located.
  182.       dllName = os.path.basename(pythoncom.__file__)
  183.     except win32api.error:
  184.       raise ImportError, "Could not locate the PythonCOM extension"
  185.     _set_subkeys(keyNameRoot + "\\InprocServer32",
  186.                  { None : dllName,
  187.                    "ThreadingModel" : threadingModel,
  188.                    })
  189.   if not clsctx or clsctx & pythoncom.CLSCTX_LOCAL_SERVER:
  190.     exeName = _find_localserver_exe(clsctx)
  191.     if exeName:
  192.       exeName = win32api.GetShortPathName(exeName)
  193.       if not pythoncom.frozen:
  194.         pyfile = _find_localserver_module()
  195.         pyfile_insert = ' "%s"' % (pyfile)
  196.       else:
  197.         pyfile_insert = ''
  198.       _set_string(keyNameRoot + '\\LocalServer32', '%s%s %s' % (exeName, pyfile_insert, str(clsid)))
  199.     else:
  200.       sys.stderr.write("Warning:  Can not locate a host .EXE for the COM server\nThe server will not be registered with LocalServer32 support.")
  201.  
  202.   if pythonInstString:
  203.     _set_string(keyNameRoot + '\\PythonCOM', pythonInstString)
  204.   else:
  205.     _remove_key(keyNameRoot + '\\PythonCOM')
  206.   if policy:
  207.     _set_string(keyNameRoot + '\\PythonCOMPolicy', policy)
  208.   else:
  209.     _remove_key(keyNameRoot + '\\PythonCOMPolicy')
  210.  
  211.   if dispatcher:
  212.     _set_string(keyNameRoot + '\\PythonCOMDispatcher', dispatcher)
  213.   else:
  214.     _remove_key(keyNameRoot + '\\PythonCOMDispatcher')
  215.  
  216.   if defIcon:
  217.     _set_string(keyNameRoot + '\\DefaultIcon', defIcon)
  218.  
  219.   if addnPath:
  220.     _set_string(keyNameRoot + "\\PythonCOMPath", addnPath)
  221.   else:
  222.     _remove_key(keyNameRoot + "\\PythonCOMPath")
  223.  
  224.   if addPyComCat:
  225.     catids = catids + [ CATID_PythonCOMServer ]
  226.  
  227.   # Set up the implemented categories
  228.   if catids:
  229.     regCat = _cat_registrar()
  230.     regCat.RegisterClassImplCategories(clsid, catids)
  231.  
  232.   # set up any other reg values they might have
  233.   if other:
  234.     for key, value in other.items():
  235.       _set_string(keyNameRoot + '\\' + key, value)
  236.  
  237.   if progID:
  238.     # set the progID as the most specific that was given to us
  239.     if verProgID:
  240.       _set_string(keyNameRoot + '\\ProgID', verProgID)
  241.     else:
  242.       _set_string(keyNameRoot + '\\ProgID', progID)
  243.  
  244.     # Set up the root entries - version independent.
  245.     if desc:
  246.       _set_string(progID, desc)
  247.     _set_string(progID + '\\CLSID', str(clsid))
  248.  
  249.     # Set up the root entries - version dependent.
  250.     if verProgID:
  251.       # point from independent to the current version
  252.       _set_string(progID + '\\CurVer', verProgID)
  253.  
  254.       # point to the version-independent one
  255.       _set_string(keyNameRoot + '\\VersionIndependentProgID', progID)
  256.  
  257.       # set up the versioned progID
  258.       if desc:
  259.         _set_string(verProgID, desc)
  260.       _set_string(verProgID + '\\CLSID', str(clsid))
  261.  
  262. def GetUnregisterServerKeys(clsid, progID=None, verProgID=None, customKeys = None):
  263.   """Given a server, return a list of of ("key", root), which are keys recursively
  264.   and uncondtionally deleted at unregister or uninstall time.
  265.   """
  266.   # remove the main CLSID registration
  267.   ret = [("CLSID\\%s" % str(clsid), win32con.HKEY_CLASSES_ROOT)]
  268.   # remove the versioned ProgID registration
  269.   if verProgID:
  270.     ret.append((verProgID, win32con.HKEY_CLASSES_ROOT))
  271.   # blow away the independent ProgID. we can't leave it since we just
  272.   # torched the class.
  273.   ### could potentially check the CLSID... ?
  274.   if progID:
  275.     ret.append((progID, win32con.HKEY_CLASSES_ROOT))
  276.   # The DCOM config tool may write settings to the AppID key for our CLSID
  277.   ret.append( ("AppID\\%s" % str(clsid), win32con.HKEY_CLASSES_ROOT) )
  278.   # Any custom keys?
  279.   if customKeys:
  280.     ret = ret + customKeys
  281.    
  282.   return ret
  283.   
  284.  
  285. def UnregisterServer(clsid, progID=None, verProgID=None, customKeys = None):
  286.   """Unregisters a Python COM server."""
  287.  
  288.   for args in GetUnregisterServerKeys(clsid, progID, verProgID, customKeys ):
  289.     apply(recurse_delete_key, args)
  290.  
  291.   ### it might be nice at some point to "roll back" the independent ProgID
  292.   ### to an earlier version if one exists, and just blowing away the
  293.   ### specified version of the ProgID (and its corresponding CLSID)
  294.   ### another time, though...
  295.  
  296.   ### NOTE: ATL simply blows away the above three keys without the
  297.   ### potential checks that I describe.  Assuming that defines the
  298.   ### "standard" then we have no additional changes necessary.
  299.  
  300. def GetRegisteredServerOption(clsid, optionName):
  301.   """Given a CLSID for a server and option name, return the option value
  302.   """
  303.   keyNameRoot = "CLSID\\%s\\%s" % (str(clsid), str(optionName))
  304.   return _get_string(keyNameRoot)
  305.  
  306.  
  307. def _get(ob, attr, default=None):
  308.   try:
  309.     return getattr(ob, attr)
  310.   except AttributeError:
  311.     return default
  312.  
  313. def RegisterClasses(*classes, **flags):
  314.   quiet = flags.has_key('quiet') and flags['quiet']
  315.   debugging = flags.has_key('debug') and flags['debug']
  316.   for cls in classes:
  317.     clsid = cls._reg_clsid_
  318.     progID = _get(cls, '_reg_progid_')
  319.     desc = _get(cls, '_reg_desc_', progID)
  320.     spec = _get(cls, '_reg_class_spec_')
  321.     verProgID = _get(cls, '_reg_verprogid_')
  322.     defIcon = _get(cls, '_reg_icon_')
  323.     threadingModel = _get(cls, '_reg_threading_', 'both')
  324.     catids = _get(cls, '_reg_catids_', [])
  325.     options = _get(cls, '_reg_options_', {})
  326.     policySpec = _get(cls, '_reg_policy_spec_')
  327.     clsctx = _get(cls, '_reg_clsctx_')
  328.     addPyComCat = not _get(cls, '_reg_disable_pycomcat_', 0)
  329.     addnPath = None
  330.     if debugging:
  331.       # If the class has a debugging dispatcher specified, use it, otherwise
  332.       # use our default dispatcher.
  333.       dispatcherSpec = _get(cls, '_reg_debug_dispatcher_spec_')
  334.       if dispatcherSpec is None:
  335.         dispatcherSpec = "win32com.server.dispatcher.DispatcherWin32trace"
  336.       # And remember the debugging flag as servers may wish to use it at runtime.
  337.       debuggingDesc = "(for debugging)"
  338.       options['Debugging'] = "1"
  339.     else:
  340.       dispatcherSpec = _get(cls, '_reg_dispatcher_spec_')
  341.       debuggingDesc = ""
  342.       options['Debugging'] = "0"
  343.  
  344.     if spec is None and policySpec in [None, 'DynamicPolicy', 'DesignatedWrapPolicy', 'DefaultPolicy']: 
  345.       # No class or policy has been specified (or a policy we know requires it!)
  346.       # We assume sys.argv[0] holds the script name
  347.       # so we build the info our-self.
  348.       scriptDir = os.path.split(sys.argv[0])[0]
  349.       if not scriptDir: scriptDir = "."
  350.       # Use the win32api to find the case-sensitive name
  351.       try:
  352.         moduleName = os.path.splitext(win32api.FindFiles(sys.argv[0])[0][8])[0]
  353.       except (IndexError, win32api.error):
  354.         # Can't find the script file - the user must explicitely set the _reg_... attribute.
  355.         raise TypeError, "Can't locate the script hosting the COM object - please set _reg_class_spec_ in your object"
  356.  
  357.       spec = moduleName + "." + cls.__name__
  358.       addnPath = win32api.GetFullPathName(scriptDir)
  359.  
  360.     RegisterServer(clsid, spec, desc, progID, verProgID, defIcon,
  361.                    threadingModel, policySpec, catids, options,
  362.                    addPyComCat, dispatcherSpec, clsctx, addnPath)
  363.     if not quiet:
  364.       print 'Registered:', progID or spec, debuggingDesc
  365.  
  366.  
  367. def UnregisterClasses(*classes, **flags):
  368.   quiet = flags.has_key('quiet') and flags['quiet']
  369.   for cls in classes:
  370.     clsid = cls._reg_clsid_
  371.     progID = _get(cls, '_reg_progid_')
  372.     verProgID = _get(cls, '_reg_verprogid_')
  373.     customKeys = _get(cls, '_reg_remove_keys_')
  374.  
  375.     UnregisterServer(clsid, progID, verProgID, customKeys)
  376.     if not quiet:
  377.       print 'Unregistered:', progID or str(clsid)
  378.  
  379. #
  380. # Unregister info is for installers or external uninstallers.
  381. # The WISE installer, for example firstly registers the COM server,
  382. # then queries for the Unregister info, appending it to its
  383. # install log.  Uninstalling the package will the uninstall the server
  384. def UnregisterInfoClasses(*classes, **flags):
  385.   ret = []
  386.   for cls in classes:
  387.     clsid = cls._reg_clsid_
  388.     progID = _get(cls, '_reg_progid_')
  389.     verProgID = _get(cls, '_reg_verprogid_')
  390.     customKeys = _get(cls, '_reg_remove_keys_')
  391.  
  392.     ret = ret + GetUnregisterServerKeys(clsid, progID, verProgID, customKeys)
  393.   return ret
  394.  
  395. def UseCommandLine(*classes, **flags):
  396.   unregisterInfo = '--unregister_info' in sys.argv
  397.   unregister = '--unregister' in sys.argv
  398.   flags['quiet'] = flags.get('quiet',0) or '--quiet' in sys.argv
  399.   flags['debug'] = flags.get('debug',0) or '--debug' in sys.argv
  400.   if unregisterInfo:
  401.     return apply(UnregisterInfoClasses, classes, flags)
  402.   if unregister:
  403.     apply(UnregisterClasses, classes, flags)
  404.   else:
  405.     apply(RegisterClasses, classes, flags)
  406.  
  407.  
  408. def RegisterPyComCategory():
  409.   """ Register the Python COM Server component category.
  410.   """
  411.   regCat = _cat_registrar()
  412.   regCat.RegisterCategories( [ (CATID_PythonCOMServer,
  413.                                 0x0409,
  414.                                 "Python COM Server") ] )
  415.  
  416. try:
  417.   win32api.RegQueryValue(win32con.HKEY_CLASSES_ROOT,
  418.                          'Component Categories\\%s' % CATID_PythonCOMServer)
  419. except win32api.error:
  420.   RegisterPyComCategory()
  421.  
  422.