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_client_gencache.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  18.2 KB  |  552 lines

  1. """Manages the cache of generated Python code.
  2.  
  3. Description
  4.   This file manages the cache of generated Python code.  When run from the 
  5.   command line, it also provides a number of options for managing that cache.
  6.   
  7. Implementation
  8.   Each typelib is generated into a filename of format "{guid}x{lcid}x{major}x{minor}.py"
  9.   
  10.   An external persistant dictionary maps from all known IIDs in all known type libraries
  11.   to the type library itself.
  12.   
  13.   Thus, whenever Python code knows the IID of an object, it can find the IID, LCID and version of
  14.   the type library which supports it.  Given this information, it can find the Python module
  15.   with the support.
  16.   
  17.   If necessary, this support can be generated on the fly.
  18.   
  19. Hacks, to do, etc
  20.   Currently just uses a pickled dictionary, but should used some sort of indexed file.
  21.   Maybe an OLE2 compound file, or a bsddb file?
  22. """
  23. import pywintypes, os, string, sys
  24. import pythoncom
  25. import win32com, win32com.client
  26. import glob
  27. import traceback
  28. import CLSIDToClass
  29.  
  30. # The global dictionary
  31. clsidToTypelib = {}
  32.  
  33. # A dictionary of ITypeLibrary objects for demand generation explicitly handed to us
  34. # Keyed by usual clsid, lcid, major, minor
  35. demandGeneratedTypeLibraries = {}
  36.  
  37. def __init__():
  38.     # Initialize the module.  Called once automatically
  39.     try:
  40.         _LoadDicts()
  41.     except IOError:
  42.         Rebuild()
  43.  
  44. pickleVersion = 1
  45. def _SaveDicts():
  46.     import cPickle
  47.     f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
  48.     try:
  49.         p = cPickle.Pickler(f)
  50.         p.dump(pickleVersion)
  51.         p.dump(clsidToTypelib)
  52.     finally:
  53.         f.close()
  54.  
  55. def _LoadDicts():
  56.     import cPickle
  57.     try:
  58.         # NOTE: IOError on file open must be caught by caller.
  59.         f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
  60.     except AttributeError: # no __gen_path__
  61.         return
  62.     try:
  63.         p = cPickle.Unpickler(f)
  64.         version = p.load()
  65.         global clsidToTypelib
  66.         clsidToTypelib = p.load()
  67.     finally:
  68.         f.close()
  69.  
  70. def GetGeneratedFileName(clsid, lcid, major, minor):
  71.     """Given the clsid, lcid, major and  minor for a type lib, return
  72.     the file name (no extension) providing this support.
  73.     """
  74.     return string.upper(str(clsid))[1:-1] + "x%sx%sx%s" % (lcid, major, minor)
  75.  
  76. def SplitGeneratedFileName(fname):
  77.     """Reverse of GetGeneratedFileName()
  78.     """
  79.     return tuple(string.split(fname,'x',4))
  80.     
  81. def GetGeneratePath():
  82.     """Returns the name of the path to generate to.
  83.     Checks the directory is OK.
  84.     """
  85.     try:
  86.         os.mkdir(win32com.__gen_path__)
  87.     except os.error:
  88.         pass
  89.     try:
  90.         fname = os.path.join(win32com.__gen_path__, "__init__.py")
  91.         os.stat(fname)
  92.     except os.error:
  93.         f = open(fname,"w")
  94.         f.write('# Generated file - this directory may be deleted to reset the COM cache...\n')
  95.         f.write('import win32com\n')
  96.         f.write('if __path__[:-1] != win32com.__gen_path__: __path__.append(win32com.__gen_path__)\n')
  97.         f.close()
  98.     
  99.     return win32com.__gen_path__
  100.  
  101. #
  102. # The helpers for win32com.client.Dispatch and OCX clients.
  103. #
  104. def GetClassForProgID(progid):
  105.     """Get a Python class for a Program ID
  106.     
  107.     Given a Program ID, return a Python class which wraps the COM object
  108.     
  109.     Returns the Python class, or None if no module is available.
  110.     
  111.     Params
  112.     progid -- A COM ProgramID or IID (eg, "Word.Application")
  113.     """
  114.     clsid = pywintypes.IID(progid) # This auto-converts named to IDs.
  115.     return GetClassForCLSID(clsid)
  116.  
  117. def GetClassForCLSID(clsid):
  118.     """Get a Python class for a CLSID
  119.     
  120.     Given a CLSID, return a Python class which wraps the COM object
  121.     
  122.     Returns the Python class, or None if no module is available.
  123.     
  124.     Params
  125.     clsid -- A COM CLSID (or string repr of one)
  126.     """
  127.     # first, take a short-cut - we may already have generated support ready-to-roll.
  128.     clsid = str(clsid)
  129.     if CLSIDToClass.HasClass(clsid):
  130.         return CLSIDToClass.GetClass(clsid)
  131.     mod = GetModuleForCLSID(clsid)
  132.     if mod is None:
  133.         return None
  134.     try:
  135.         return CLSIDToClass.GetClass(clsid)
  136.     except KeyError:
  137.         return None
  138.  
  139. def GetModuleForProgID(progid):
  140.     """Get a Python module for a Program ID
  141.     
  142.     Given a Program ID, return a Python module which contains the
  143.     class which wraps the COM object.
  144.     
  145.     Returns the Python module, or None if no module is available.
  146.     
  147.     Params
  148.     progid -- A COM ProgramID or IID (eg, "Word.Application")
  149.     """
  150.     try:
  151.         iid = pywintypes.IID(progid)
  152.     except pywintypes.com_error:
  153.         return None
  154.     return GetModuleForCLSID(iid)
  155.     
  156. def GetModuleForCLSID(clsid):
  157.     """Get a Python module for a CLSID
  158.     
  159.     Given a CLSID, return a Python module which contains the
  160.     class which wraps the COM object.
  161.     
  162.     Returns the Python module, or None if no module is available.
  163.     
  164.     Params
  165.     progid -- A COM CLSID (ie, not the description)
  166.     """
  167.     clsid_str = str(clsid)
  168.     try:
  169.         typelibCLSID, lcid, major, minor = clsidToTypelib[clsid_str]
  170.     except KeyError:
  171.         return None
  172.  
  173.     mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  174.     if mod is not None:
  175.         sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
  176.         if sub_mod is None:
  177.             sub_mod = mod.VTablesToPackageMap.get(clsid_str)
  178.         if sub_mod is not None:
  179.             sub_mod_name = mod.__name__ + "." + sub_mod
  180.             try:
  181.                 __import__(sub_mod_name)
  182.             except ImportError:
  183.                 info = typelibCLSID, lcid, major, minor
  184.                 # Force the generation.  If this typelibrary has explicitly been added,
  185.                 # use it (it may not be registered, causing a lookup by clsid to fail)
  186.                 if demandGeneratedTypeLibraries.has_key(info):
  187.                     info = demandGeneratedTypeLibraries[info]
  188.                 import makepy
  189.                 makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
  190.                 # Generate does an import...
  191.             mod = sys.modules[sub_mod_name]
  192.     return mod
  193.  
  194. def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
  195.     """Get a Python module for a type library ID
  196.     
  197.     Given the CLSID of a typelibrary, return an imported Python module, 
  198.     else None
  199.     
  200.     Params
  201.     typelibCLSID -- IID of the type library.
  202.     major -- Integer major version.
  203.     minor -- Integer minor version
  204.     lcid -- Integer LCID for the library.
  205.     """
  206.     modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
  207.     return _GetModule(modName)
  208.  
  209.  
  210. def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bGUIProgress = None, bForDemand = 0, bBuildHidden = 1):
  211.     """Generate support for a type library.
  212.     
  213.     Given the IID, LCID and version information for a type library, generate
  214.     and import the necessary support files.
  215.     
  216.     Returns the Python module.  No exceptions are caught.
  217.  
  218.     Params
  219.     typelibCLSID -- IID of the type library.
  220.     major -- Integer major version.
  221.     minor -- Integer minor version.
  222.     lcid -- Integer LCID for the library.
  223.     progressInstance -- Instance to use as progress indicator, or None to
  224.                         use the GUI progress bar.
  225.     """
  226.     if bGUIProgress is not None:
  227.         print "The 'bGuiProgress' param to 'MakeModuleForTypelib' is obsolete."
  228.  
  229.     import makepy
  230.     try:
  231.         makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  232.     except pywintypes.com_error:
  233.         return None
  234.     return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  235.  
  236. def MakeModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = 0, bBuildHidden = 1):
  237.     """Generate support for a type library.
  238.     
  239.     Given a PyITypeLib interface generate and import the necessary support files.  This is useful
  240.     for getting makepy support for a typelibrary that is not registered - the caller can locate
  241.     and load the type library itself, rather than relying on COM to find it.
  242.     
  243.     Returns the Python module.
  244.  
  245.     Params
  246.     typelib_ob -- The type library itself
  247.     progressInstance -- Instance to use as progress indicator, or None to
  248.                         use the GUI progress bar.
  249.     """
  250.     import makepy
  251.     try:
  252.         makepy.GenerateFromTypeLibSpec( typelib_ob, progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  253.     except pywintypes.com_error:
  254.         return None
  255.     tla = typelib_ob.GetLibAttr()
  256.     guid = tla[0]
  257.     lcid = tla[1]
  258.     major = tla[3]
  259.     minor = tla[4]
  260.     return GetModuleForTypelib(guid, lcid, major, minor)
  261.  
  262. def EnsureModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = 0, bBuildHidden = 1):
  263.     """Check we have support for a type library, generating if not.
  264.     
  265.     Given a PyITypeLib interface generate and import the necessary
  266.     support files if necessary. This is useful for getting makepy support
  267.     for a typelibrary that is not registered - the caller can locate and
  268.     load the type library itself, rather than relying on COM to find it.
  269.     
  270.     Returns the Python module.
  271.  
  272.     Params
  273.     typelib_ob -- The type library itself
  274.     progressInstance -- Instance to use as progress indicator, or None to
  275.                         use the GUI progress bar.
  276.     """
  277.     tla = typelib_ob.GetLibAttr()
  278.     guid = tla[0]
  279.     lcid = tla[1]
  280.     major = tla[3]
  281.     minor = tla[4]
  282.  
  283.     #If demand generated, save the typelib interface away for later use
  284.     if bForDemand:
  285.         demandGeneratedTypeLibraries[(str(guid), lcid, major, minor)] = typelib_ob
  286.  
  287.     try:
  288.         return GetModuleForTypelib(guid, lcid, major, minor)
  289.     except ImportError:
  290.         pass
  291.     # Generate it.
  292.     return MakeModuleForTypelibInterface(typelib_ob, progressInstance, bForDemand, bBuildHidden)
  293.  
  294. def ForgetAboutTypelibInterface(typelib_ob):
  295.     """Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand"""
  296.     tla = typelib_ob.GetLibAttr()
  297.     guid = tla[0]
  298.     lcid = tla[1]
  299.     major = tla[3]
  300.     minor = tla[4]
  301.     info = str(guid), lcid, major, minor
  302.     try:
  303.         del demandGeneratedTypeLibraries[info]
  304.     except KeyError:
  305.         # Not worth raising an exception - maybe they dont know we only remember for demand generated, etc.
  306.         print "ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!" % (info,)
  307.  
  308.  
  309.  
  310. def EnsureModule(typelibCLSID, lcid, major, minor, progressInstance = None, bValidateFile=1, bForDemand = 0, bBuildHidden = 1):
  311.     """Ensure Python support is loaded for a type library, generating if necessary.
  312.     
  313.     Given the IID, LCID and version information for a type library, check and if
  314.     necessary (re)generate, then import the necessary support files. If we regenerate the file, there
  315.     is no way to totally snuff out all instances of the old module in Python, and thus we will regenerate the file more than necessary,
  316.     unless makepy/genpy is modified accordingly.
  317.     
  318.     
  319.     Returns the Python module.  No exceptions are caught during the generate process.
  320.  
  321.     Params
  322.     typelibCLSID -- IID of the type library.
  323.     major -- Integer major version.
  324.     minor -- Integer minor version
  325.     lcid -- Integer LCID for the library.
  326.     progressInstance -- Instance to use as progress indicator, or None to
  327.                         use the GUI progress bar.
  328.     bValidateFile -- Whether or not to perform cache validation or not
  329.     bForDemand -- Should a complete generation happen now, or on demand?
  330.     bBuildHidden -- Should hidden members/attributes etc be generated?
  331.     """
  332.     bReloadNeeded = 0
  333.     try:
  334.         try:
  335.             #print "Try specified typelib"
  336.             module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  337.             #print module
  338.         except ImportError:
  339.             # If we get an ImportError
  340.             # We may still find a valid cache file under a different MinorVersion #
  341.             #print "Loading reg typelib"
  342.             tlbAttr = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  343.             # if the above line doesn't throw a pythoncom.com_error
  344.             # Let's suck it in
  345.             #print "Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4]
  346.             try:
  347.                 module = GetModuleForTypelib(typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4])
  348.             except ImportError:
  349.                 module = None
  350.                 minor = tlbAttr[4]
  351.         if bValidateFile:
  352.             filePathPrefix  = "%s\\%s" % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  353.             filePath = filePathPrefix + ".py"
  354.             filePathPyc = filePathPrefix + ".py"
  355.             if __debug__:
  356.                 filePathPyc = filePathPyc + "c"
  357.             else:
  358.                 filePathPyc = filePathPyc + "o"
  359.             # Verify that type library is up to date.
  360.             #print "Grabbing typelib"
  361.             # If the following doesn't throw an exception, then we have a valid type library
  362.             typLibPath = pythoncom.QueryPathOfRegTypeLib(typelibCLSID, major, minor, lcid)
  363.             tlbAttributes = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  364.             #print "Grabbed typelib: ", tlbAttributes[3], tlbAttributes[4]
  365.             ##print module.MinorVersion
  366.             # If we have a differing MinorVersion or genpy has bumped versions, update the file
  367.             import genpy
  368.             if module is not None and (module.MinorVersion != tlbAttributes[4] or genpy.makepy_version != module.makepy_version):
  369.                 #print "Version skew: %d, %d" % (module.MinorVersion, tlbAttributes[4])
  370.                 # try to erase the bad file from the cache
  371.                 try:
  372.                     os.unlink(filePath)
  373.                 except os.error:
  374.                     pass
  375.                 try:
  376.                     os.unlink(filePathPyc)
  377.                 except os.error:
  378.                     pass
  379.                 if os.path.isdir(filePathPrefix):
  380.                     import shutil
  381.                     shutil.rmtree(filePathPrefix)
  382.                 minor = tlbAttributes[4]
  383.                 module = None
  384.                 bReloadNeeded = 1
  385.             else:
  386.                 if module is not None:
  387.                     minor = module.MinorVersion
  388.                     filePathPrefix  = "%s\\%s" % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  389.                     filePath = filePathPrefix + ".py"
  390.                     filePathPyc = filePathPrefix + ".pyc"
  391.                     #print "Trying py stat: ", filePath
  392.                     fModTimeSet = 0
  393.                     try:
  394.                         pyModTime = os.stat(filePath)[8]
  395.                         fModTimeSet = 1
  396.                     except os.error, e:
  397.                         # If .py file fails, try .pyc file
  398.                         #print "Trying pyc stat", filePathPyc
  399.                         try:
  400.                             pyModTime = os.stat(filePathPyc)[8]
  401.                             fModtimeSet = 1
  402.                         except os.error, e:
  403.                             pass
  404.                     #print "Trying stat typelib", pyModTime
  405.                     #print str(typLibPath)
  406.                     typLibModTime = os.stat(str(typLibPath[:-1]))[8]
  407.                     if fModTimeSet and (typLibModTime > pyModTime):
  408.                         bReloadNeeded = 1
  409.                         module = None
  410.     except (ImportError, os.error):    
  411.         module = None
  412.     if module is None:
  413.         #print "Rebuilding: ", major, minor
  414.         module = MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  415.         # If we replaced something, reload it
  416.         if bReloadNeeded:
  417.             module = reload(module)
  418.             AddModuleToCache(typelibCLSID, lcid, major, minor)
  419.     return module
  420.  
  421. def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on!
  422.     """Given a COM prog_id, return an object that is using makepy support, building if necessary"""
  423.     disp = win32com.client.Dispatch(prog_id)
  424.     if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
  425.         try:
  426.             ti = disp._oleobj_.GetTypeInfo()
  427.             disp_clsid = ti.GetTypeAttr()[0]
  428.             tlb, index = ti.GetContainingTypeLib()
  429.             tla = tlb.GetLibAttr()
  430.             mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
  431.             GetModuleForCLSID(disp_clsid)
  432.             # Get the class from the module.
  433.             import CLSIDToClass
  434.             disp_class = CLSIDToClass.GetClass(str(disp_clsid))
  435.             disp = disp_class(disp._oleobj_)
  436.         except pythoncom.com_error:
  437.             raise TypeError, "This COM object can not automate the makepy process - please run makepy manually for this object"
  438.     return disp
  439.  
  440. def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, bFlushNow = 1):
  441.     """Add a newly generated file to the cache dictionary.
  442.     """
  443.     fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
  444.     mod = _GetModule(fname)
  445.     dict = mod.CLSIDToClassMap
  446.     for clsid, cls in dict.items():
  447.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  448.  
  449.     dict = mod.CLSIDToPackageMap
  450.     for clsid, name in dict.items():
  451.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  452.  
  453.     dict = mod.VTablesToClassMap
  454.     for clsid, cls in dict.items():
  455.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  456.  
  457.     dict = mod.VTablesToPackageMap
  458.     for clsid, cls in dict.items():
  459.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  460.  
  461.  
  462.     if bFlushNow:
  463.         _SaveDicts()
  464.  
  465. def _GetModule(fname):
  466.     """Given the name of a module in the gen_py directory, import and return it.
  467.     """
  468.     mod = __import__("win32com.gen_py.%s" % fname)
  469.     return getattr( getattr(mod, "gen_py"), fname)
  470.     
  471. def Rebuild(verbose = 1):
  472.     """Rebuild the cache indexes from the file system.
  473.     """
  474.     clsidToTypelib.clear()
  475.     files = glob.glob(win32com.__gen_path__+ "\\*.py")
  476.     if verbose and len(files): # Dont bother reporting this when directory is empty!
  477.         print "Rebuilding cache of generated files for COM support..."
  478.     for file in files:
  479.         name = os.path.splitext(os.path.split(file)[1])[0]
  480.         try:
  481.             iid, lcid, major, minor = string.split(name, "x")
  482.             ok = 1
  483.         except ValueError:
  484.             ok = 0
  485.         if ok:
  486.             try:
  487.                 iid = pywintypes.IID("{" + iid + "}")
  488.             except pywintypes.com_error:
  489.                 ok = 0
  490.         if ok:
  491.             if verbose:
  492.                 print "Checking", name
  493.             try:
  494.                 AddModuleToCache(iid, lcid, major, minor, verbose, 0)
  495.             except:
  496.                 print "Could not add module %s - %s: %s" % (name, sys.exc_info()[0],sys.exc_info()[1])
  497.         else:
  498.             if verbose and name[0] != '_':
  499.                 print "Skipping module", name
  500.     if verbose and len(files): # Dont bother reporting this when directory is empty!
  501.         print "Done."
  502.     _SaveDicts()
  503.  
  504. def _Dump():
  505.     print "Cache is in directory", win32com.__gen_path__
  506.     files = glob.glob(win32com.__gen_path__+ "\*.py")
  507.     for file in files:
  508.         name = os.path.splitext(os.path.split(file)[1])[0]
  509.         if name[0] != '_':
  510.             mod = _GetModule(name)
  511.             info = SplitGeneratedFileName(name)
  512.             print "%s - %s" % (mod.__doc__, name)
  513.  
  514.     
  515. __init__()
  516.  
  517. usageString = """\
  518.   Usage: gencache [-q] [-d] [-r]
  519.   
  520.          -q         - Quiet
  521.          -d         - Dump the cache (typelibrary description and filename).
  522.          -r         - Rebuild the cache dictionary from the existing .py files
  523. """
  524.  
  525. def usage():
  526.     print usageString
  527.     sys.exit(1)
  528.  
  529. if __name__=='__main__':
  530.     import getopt
  531.     try:
  532.         opts, args = getopt.getopt(sys.argv[1:], "qrd")
  533.     except getopt.error, message:
  534.         print message
  535.         usage()
  536.  
  537.     # we only have options - complain about real args, or none at all!
  538.     if len(sys.argv)==1 or args:
  539.         print usage()
  540.         
  541.     verbose = 1
  542.     for opt, val in opts:
  543.         if opt=='-d': # Dump
  544.             _Dump()
  545.         if opt=='-r':
  546.             Rebuild(verbose)
  547.         if opt=='-q':
  548.             verbose = 0
  549.  
  550. #if __name__=='__main__':
  551. #    print "Rebuilding cache..."
  552. #    Rebuild(1)