home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2010 November / maximum-cd-2010-11.iso / DiscContents / calibre-0.7.13.msi / file_2569 < prev    next >
Encoding:
Text File  |  2005-10-23  |  18.0 KB  |  511 lines

  1. # A tool to setup the Python registry.
  2.  
  3. error = "Registry Setup Error"
  4.  
  5. import sys # at least we can count on this!
  6.  
  7. def FileExists(fname):
  8.     """Check if a file exists.  Returns true or false.
  9.     """
  10.     import os
  11.     try:
  12.         os.stat(fname)
  13.         return 1
  14.     except os.error, details:
  15.         return 0
  16.  
  17. def IsPackageDir(path, packageName, knownFileName):
  18.     """Given a path, a ni package name, and possibly a known file name in
  19.            the root of the package, see if this path is good.
  20.       """
  21.     import os
  22.     if knownFileName is None:
  23.         knownFileName = "."
  24.     return FileExists(os.path.join(os.path.join(path, packageName),knownFileName))
  25.  
  26. def IsDebug():
  27.     """Return "_d" if we're running a debug version.
  28.     
  29.     This is to be used within DLL names when locating them.
  30.     """
  31.     import imp
  32.     for suffix_item in imp.get_suffixes():
  33.         if suffix_item[0]=='_d.pyd':
  34.             return '_d'
  35.     return ''
  36.  
  37. def FindPackagePath(packageName, knownFileName, searchPaths):
  38.     """Find a package.
  39.  
  40.            Given a ni style package name, check the package is registered.
  41.  
  42.            First place looked is the registry for an existing entry.  Then
  43.            the searchPaths are searched.
  44.       """
  45.     import regutil, os
  46.     pathLook = regutil.GetRegisteredNamedPath(packageName)
  47.     if pathLook and IsPackageDir(pathLook, packageName, knownFileName):
  48.         return pathLook, None # The currently registered one is good.
  49.     # Search down the search paths.
  50.     for pathLook in searchPaths:
  51.         if IsPackageDir(pathLook, packageName, knownFileName):
  52.             # Found it
  53.             ret = os.path.abspath(pathLook)
  54.             return ret, ret
  55.     raise error, "The package %s can not be located" % packageName
  56.  
  57. def FindHelpPath(helpFile, helpDesc, searchPaths):
  58.     # See if the current registry entry is OK
  59.     import os, win32api, win32con
  60.     try:
  61.         key = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\Help", 0, win32con.KEY_ALL_ACCESS)
  62.         try:
  63.             try:
  64.                 path = win32api.RegQueryValueEx(key, helpDesc)[0]
  65.                 if FileExists(os.path.join(path, helpFile)):
  66.                     return os.path.abspath(path)
  67.             except win32api.error:
  68.                 pass # no registry entry.
  69.         finally:
  70.             key.Close()
  71.     except win32api.error:
  72.         pass
  73.     for pathLook in searchPaths:
  74.         if FileExists(os.path.join(pathLook, helpFile)):
  75.             return os.path.abspath(pathLook)
  76.         pathLook = os.path.join(pathLook, "Help")
  77.         if FileExists(os.path.join( pathLook, helpFile)):
  78.             return os.path.abspath(pathLook)
  79.     raise error, "The help file %s can not be located" % helpFile
  80.  
  81. def FindAppPath(appName, knownFileName, searchPaths):
  82.     """Find an application.
  83.  
  84.          First place looked is the registry for an existing entry.  Then
  85.          the searchPaths are searched.
  86.       """
  87.     # Look in the first path.
  88.     import regutil, string, os
  89.     regPath = regutil.GetRegisteredNamedPath(appName)
  90.     if regPath:
  91.         pathLook = string.split(regPath,";")[0]
  92.     if regPath and FileExists(os.path.join(pathLook, knownFileName)):
  93.         return None # The currently registered one is good.
  94.     # Search down the search paths.
  95.     for pathLook in searchPaths:
  96.         if FileExists(os.path.join(pathLook, knownFileName)):
  97.             # Found it
  98.             return os.path.abspath(pathLook)
  99.     raise error, "The file %s can not be located for application %s" % (knownFileName, appName)
  100.  
  101. def FindPythonExe(exeAlias, possibleRealNames, searchPaths):
  102.     """Find an exe.
  103.  
  104.        Returns the full path to the .exe, and a boolean indicating if the current 
  105.        registered entry is OK.  We don't trust the already registered version even
  106.        if it exists - it may be wrong (ie, for a different Python version)
  107.     """
  108.     import win32api, regutil, string, os, sys
  109.     if possibleRealNames is None:
  110.         possibleRealNames = exeAlias
  111.     # Look first in Python's home.
  112.     found = os.path.join(sys.prefix,  possibleRealNames)
  113.     if not FileExists(found): # for developers
  114.         found = os.path.join(sys.prefix,  "PCBuild", possibleRealNames)
  115.     if not FileExists(found):
  116.         found = LocateFileName(possibleRealNames, searchPaths)
  117.  
  118.     registered_ok = 0
  119.     try:
  120.         registered = win32api.RegQueryValue(regutil.GetRootKey(), regutil.GetAppPathsKey() + "\\" + exeAlias)
  121.         registered_ok = found==registered
  122.     except win32api.error:
  123.         pass
  124.     return found, registered_ok
  125.  
  126. def QuotedFileName(fname):
  127.     """Given a filename, return a quoted version if necessary
  128.       """
  129.     import regutil, string
  130.     try:
  131.         string.index(fname, " ") # Other chars forcing quote?
  132.         return '"%s"' % fname
  133.     except ValueError:
  134.         # No space in name.
  135.         return fname
  136.  
  137. def LocateFileName(fileNamesString, searchPaths):
  138.     """Locate a file name, anywhere on the search path.
  139.  
  140.        If the file can not be located, prompt the user to find it for us
  141.        (using a common OpenFile dialog)
  142.  
  143.        Raises KeyboardInterrupt if the user cancels.
  144.     """
  145.     import regutil, string, os
  146.     fileNames = string.split(fileNamesString,";")
  147.     for path in searchPaths:
  148.         for fileName in fileNames:
  149.             try:
  150.                 retPath = os.path.join(path, fileName)
  151.                 os.stat(retPath)
  152.                 break
  153.             except os.error:
  154.                 retPath = None
  155.         if retPath:
  156.             break
  157.     else:
  158.         fileName = fileNames[0]
  159.         try:
  160.             import win32ui, win32con
  161.         except ImportError:
  162.             raise error, "Need to locate the file %s, but the win32ui module is not available\nPlease run the program again, passing as a parameter the path to this file." % fileName
  163.         # Display a common dialog to locate the file.
  164.         flags=win32con.OFN_FILEMUSTEXIST
  165.         ext = os.path.splitext(fileName)[1]
  166.         filter = "Files of requested type (*%s)|*%s||" % (ext,ext)
  167.         dlg = win32ui.CreateFileDialog(1,None,fileName,flags,filter,None)
  168.         dlg.SetOFNTitle("Locate " + fileName)
  169.         if dlg.DoModal() <> win32con.IDOK:
  170.             raise KeyboardInterrupt, "User cancelled the process"
  171.         retPath = dlg.GetPathName()
  172.     return os.path.abspath(retPath)
  173.  
  174. def LocatePath(fileName, searchPaths):
  175.     """Like LocateFileName, but returns a directory only.
  176.     """
  177.     import os
  178.     return os.path.abspath(os.path.split(LocateFileName(fileName, searchPaths))[0])
  179.  
  180. def LocateOptionalPath(fileName, searchPaths):
  181.     """Like LocatePath, but returns None if the user cancels.
  182.     """
  183.     try:
  184.         return LocatePath(fileName, searchPaths)
  185.     except KeyboardInterrupt:
  186.         return None
  187.  
  188.  
  189. def LocateOptionalFileName(fileName, searchPaths = None):
  190.     """Like LocateFileName, but returns None if the user cancels.
  191.     """
  192.     try:
  193.         return LocateFileName(fileName, searchPaths)
  194.     except KeyboardInterrupt:
  195.         return None
  196.  
  197. def LocatePythonCore(searchPaths):
  198.     """Locate and validate the core Python directories.  Returns a list
  199.          of paths that should be used as the core (ie, un-named) portion of
  200.          the Python path.
  201.     """
  202.     import string, os, regutil
  203.     currentPath = regutil.GetRegisteredNamedPath(None)
  204.     if currentPath:
  205.         presearchPaths = string.split(currentPath, ";")
  206.     else:
  207.         presearchPaths = [os.path.abspath(".")]
  208.     libPath = None
  209.     for path in presearchPaths:
  210.         if FileExists(os.path.join(path, "os.py")):
  211.             libPath = path
  212.             break
  213.     if libPath is None and searchPaths is not None:
  214.         libPath = LocatePath("os.py", searchPaths)
  215.     if libPath is None:
  216.         raise error, "The core Python library could not be located."
  217.  
  218.     corePath = None
  219.     suffix = IsDebug()
  220.     for path in presearchPaths:
  221.         if FileExists(os.path.join(path, "unicodedata%s.pyd" % suffix)):
  222.             corePath = path
  223.             break
  224.     if corePath is None and searchPaths is not None:
  225.         corePath = LocatePath("unicodedata%s.pyd" % suffix, searchPaths)
  226.     if corePath is None:
  227.         raise error, "The core Python path could not be located."
  228.  
  229.     installPath = os.path.abspath(os.path.join(libPath, ".."))
  230.     return installPath, [libPath, corePath]
  231.  
  232. def FindRegisterPackage(packageName, knownFile, searchPaths, registryAppName = None):
  233.     """Find and Register a package.
  234.  
  235.        Assumes the core registry setup correctly.
  236.  
  237.        In addition, if the location located by the package is already
  238.            in the **core** path, then an entry is registered, but no path.
  239.        (no other paths are checked, as the application whose path was used
  240.        may later be uninstalled.  This should not happen with the core)
  241.     """
  242.     import regutil, string
  243.     if not packageName: raise error, "A package name must be supplied"
  244.     corePaths = string.split(regutil.GetRegisteredNamedPath(None),";")
  245.     if not searchPaths: searchPaths = corePaths
  246.     registryAppName = registryAppName or packageName
  247.     try:
  248.         pathLook, pathAdd = FindPackagePath(packageName, knownFile, searchPaths)
  249.         if pathAdd is not None:
  250.             if pathAdd in corePaths:
  251.                 pathAdd = ""
  252.             regutil.RegisterNamedPath(registryAppName, pathAdd)
  253.         return pathLook
  254.     except error, details:
  255.         print "*** The %s package could not be registered - %s" % (packageName, details)
  256.         print "*** Please ensure you have passed the correct paths on the command line."
  257.         print "*** - For packages, you should pass a path to the packages parent directory,"
  258.         print "*** - and not the package directory itself..."
  259.  
  260.  
  261. def FindRegisterApp(appName, knownFiles, searchPaths):
  262.     """Find and Register a package.
  263.  
  264.        Assumes the core registry setup correctly.
  265.  
  266.     """
  267.     import regutil, string
  268.     if type(knownFiles)==type(''):
  269.         knownFiles = [knownFiles]
  270.     paths=[]
  271.     try:
  272.         for knownFile in knownFiles:
  273.             pathLook = FindAppPath(appName, knownFile, searchPaths)
  274.             if pathLook:
  275.                 paths.append(pathLook)
  276.     except error, details:
  277.         print "*** ", details
  278.         return
  279.  
  280.     regutil.RegisterNamedPath(appName, string.join(paths,";"))
  281.  
  282. def FindRegisterPythonExe(exeAlias, searchPaths, actualFileNames = None):
  283.     """Find and Register a Python exe (not necessarily *the* python.exe)
  284.  
  285.        Assumes the core registry setup correctly.
  286.     """
  287.     import regutil, string
  288.     fname, ok = FindPythonExe(exeAlias, actualFileNames, searchPaths)
  289.     if not ok:
  290.         regutil.RegisterPythonExe(fname, exeAlias)
  291.     return fname
  292.  
  293.  
  294. def FindRegisterHelpFile(helpFile, searchPaths, helpDesc = None ):
  295.     import regutil
  296.     
  297.     try:
  298.         pathLook = FindHelpPath(helpFile, helpDesc, searchPaths)
  299.     except error, details:
  300.         print "*** ", details
  301.         return
  302. #    print "%s found at %s" % (helpFile, pathLook)
  303.     regutil.RegisterHelpFile(helpFile, pathLook, helpDesc)
  304.     
  305. def SetupCore(searchPaths):
  306.     """Setup the core Python information in the registry.
  307.  
  308.        This function makes no assumptions about the current state of sys.path.
  309.  
  310.        After this function has completed, you should have access to the standard
  311.        Python library, and the standard Win32 extensions
  312.     """
  313.  
  314.     import sys    
  315.     for path in searchPaths:
  316.         sys.path.append(path)
  317.  
  318.     import string, os
  319.     import regutil, win32api,win32con
  320.     
  321.     installPath, corePaths = LocatePythonCore(searchPaths)
  322.     # Register the core Pythonpath.
  323.     print corePaths
  324.     regutil.RegisterNamedPath(None, string.join(corePaths,";"))
  325.  
  326.     # Register the install path.
  327.     hKey = win32api.RegCreateKey(regutil.GetRootKey() , regutil.BuildDefaultPythonKey())
  328.     try:
  329.         # Core Paths.
  330.         win32api.RegSetValue(hKey, "InstallPath", win32con.REG_SZ, installPath)
  331.     finally:
  332.         win32api.RegCloseKey(hKey)
  333.  
  334.     # Register the win32 core paths.
  335.     win32paths = os.path.abspath( os.path.split(win32api.__file__)[0]) + ";" + \
  336.                  os.path.abspath( os.path.split(LocateFileName("win32con.py;win32con.pyc", sys.path ) )[0] )
  337.  
  338.     # Python has builtin support for finding a "DLLs" directory, but
  339.     # not a PCBuild.  Having it in the core paths means it is ignored when
  340.     # an EXE not in the Python dir is hosting us - so we add it as a named
  341.     # value
  342.     check = os.path.join(sys.prefix, "PCBuild")
  343.     if os.path.isdir(check):
  344.         regutil.RegisterNamedPath("PCBuild",check)
  345.  
  346. def RegisterShellInfo(searchPaths):
  347.     """Registers key parts of the Python installation with the Windows Shell.
  348.  
  349.        Assumes a valid, minimal Python installation exists
  350.        (ie, SetupCore() has been previously successfully run)
  351.     """
  352.     import regutil, win32con
  353.     suffix = IsDebug()
  354.     # Set up a pointer to the .exe's
  355.     exePath = FindRegisterPythonExe("Python%s.exe" % suffix, searchPaths)
  356.     regutil.SetRegistryDefaultValue(".py", "Python.File", win32con.HKEY_CLASSES_ROOT)
  357.     regutil.RegisterShellCommand("Open", QuotedFileName(exePath)+" \"%1\" %*", "&Run")
  358.     regutil.SetRegistryDefaultValue("Python.File\\DefaultIcon", "%s,0" % exePath, win32con.HKEY_CLASSES_ROOT)
  359.     
  360.     FindRegisterHelpFile("Python.hlp", searchPaths, "Main Python Documentation")
  361.     FindRegisterHelpFile("ActivePython.chm", searchPaths, "Main Python Documentation")
  362.  
  363.     # We consider the win32 core, as it contains all the win32 api type
  364.     # stuff we need.
  365. #    FindRegisterApp("win32", ["win32con.pyc", "win32api%s.pyd" % suffix], searchPaths)
  366.  
  367. usage = """\
  368. regsetup.py - Setup/maintain the registry for Python apps.
  369.  
  370. Run without options, (but possibly search paths) to repair a totally broken
  371. python registry setup.  This should allow other options to work.
  372.  
  373. Usage:   %s [options ...] paths ...
  374. -p packageName  -- Find and register a package.  Looks in the paths for
  375.                    a sub-directory with the name of the package, and
  376.                    adds a path entry for the package.
  377. -a appName      -- Unconditionally add an application name to the path.
  378.                    A new path entry is create with the app name, and the
  379.                    paths specified are added to the registry.
  380. -c              -- Add the specified paths to the core Pythonpath.
  381.                    If a path appears on the core path, and a package also 
  382.                    needs that same path, the package will not bother 
  383.                    registering it.  Therefore, By adding paths to the 
  384.                    core path, you can avoid packages re-registering the same path.  
  385. -m filename     -- Find and register the specific file name as a module.
  386.                    Do not include a path on the filename!
  387. --shell         -- Register everything with the Win95/NT shell.
  388. --upackage name -- Unregister the package
  389. --uapp name     -- Unregister the app (identical to --upackage)
  390. --umodule name  -- Unregister the module
  391.  
  392. --description   -- Print a description of the usage.
  393. --examples      -- Print examples of usage.
  394. """ % sys.argv[0]
  395.  
  396. description="""\
  397. If no options are processed, the program attempts to validate and set 
  398. the standard Python path to the point where the standard library is
  399. available.  This can be handy if you move Python to a new drive/sub-directory,
  400. in which case most of the options would fail (as they need at least string.py,
  401. os.py etc to function.)
  402. Running without options should repair Python well enough to run with 
  403. the other options.
  404.  
  405. paths are search paths that the program will use to seek out a file.
  406. For example, when registering the core Python, you may wish to
  407. provide paths to non-standard places to look for the Python help files,
  408. library files, etc.
  409.  
  410. See also the "regcheck.py" utility which will check and dump the contents
  411. of the registry.
  412. """
  413.  
  414. examples="""\
  415. Examples:
  416. "regsetup c:\\wierd\\spot\\1 c:\\wierd\\spot\\2"
  417. Attempts to setup the core Python.  Looks in some standard places,
  418. as well as the 2 wierd spots to locate the core Python files (eg, Python.exe,
  419. python14.dll, the standard library and Win32 Extensions.
  420.  
  421. "regsetup -a myappname . .\subdir"
  422. Registers a new Pythonpath entry named myappname, with "C:\\I\\AM\\HERE" and
  423. "C:\\I\\AM\\HERE\subdir" added to the path (ie, all args are converted to
  424. absolute paths)
  425.  
  426. "regsetup -c c:\\my\\python\\files"
  427. Unconditionally add "c:\\my\\python\\files" to the 'core' Python path.
  428.  
  429. "regsetup -m some.pyd \\windows\\system"
  430. Register the module some.pyd in \\windows\\system as a registered
  431. module.  This will allow some.pyd to be imported, even though the
  432. windows system directory is not (usually!) on the Python Path.
  433.  
  434. "regsetup --umodule some"
  435. Unregister the module "some".  This means normal import rules then apply
  436. for that module.
  437. """
  438.  
  439. if __name__=='__main__':
  440.     if len(sys.argv)>1 and sys.argv[1] in ['/?','-?','-help','-h']:
  441.         print usage
  442.     elif len(sys.argv)==1 or not sys.argv[1][0] in ['/','-']:
  443.         # No args, or useful args.
  444.         searchPath = sys.path[:]
  445.         for arg in sys.argv[1:]:
  446.             searchPath.append(arg)
  447.         # Good chance we are being run from the "regsetup.py" directory.
  448.         # Typically this will be "\somewhere\win32\Scripts" and the 
  449.         # "somewhere" and "..\Lib" should also be searched.
  450.         searchPath.append("..\\Build")
  451.         searchPath.append("..\\Lib")
  452.         searchPath.append("..")
  453.         searchPath.append("..\\..")
  454.  
  455.                 # for developers:
  456.                 # also search somewhere\lib, ..\build, and ..\..\build
  457.         searchPath.append("..\\..\\lib")
  458.         searchPath.append("..\\build")
  459.         searchPath.append("..\\..\\pcbuild")
  460.  
  461.         print "Attempting to setup/repair the Python core"
  462.  
  463.         SetupCore(searchPath)
  464.         RegisterShellInfo(searchPath)
  465.         FindRegisterHelpFile("PyWin32.chm", searchPath, "Pythonwin Reference")
  466.         # Check the registry.
  467.         print "Registration complete - checking the registry..."
  468.         import regcheck
  469.         regcheck.CheckRegistry()
  470.     else:
  471.         searchPaths = []
  472.         import getopt, string
  473.         opts, args = getopt.getopt(sys.argv[1:], 'p:a:m:c', 
  474.             ['shell','upackage=','uapp=','umodule=','description','examples'])
  475.         for arg in args:
  476.             searchPaths.append(arg)
  477.         for o,a in opts:
  478.             if o=='--description':
  479.                 print description
  480.             if o=='--examples':
  481.                 print examples
  482.             if o=='--shell':
  483.                 print "Registering the Python core."
  484.                 RegisterShellInfo(searchPaths)
  485.             if o=='-p':
  486.                 print "Registering package", a
  487.                 FindRegisterPackage(a,None,searchPaths)
  488.             if o in ['--upackage', '--uapp']:
  489.                 import regutil
  490.                 print "Unregistering application/package", a
  491.                 regutil.UnregisterNamedPath(a)
  492.             if o=='-a':
  493.                 import regutil
  494.                 path = string.join(searchPaths,";")
  495.                 print "Registering application", a,"to path",path
  496.                 regutil.RegisterNamedPath(a,path)
  497.             if o=='-c':
  498.                 if not len(searchPaths):
  499.                     raise error, "-c option must provide at least one additional path"
  500.                 import win32api, regutil
  501.                 currentPaths = string.split(regutil.GetRegisteredNamedPath(None),";")
  502.                 oldLen = len(currentPaths)
  503.                 for newPath in searchPaths:
  504.                     if newPath not in currentPaths:
  505.                         currentPaths.append(newPath)
  506.                 if len(currentPaths)<>oldLen:
  507.                     print "Registering %d new core paths" % (len(currentPaths)-oldLen)
  508.                     regutil.RegisterNamedPath(None,string.join(currentPaths,";"))
  509.                 else:
  510.                     print "All specified paths are already registered."
  511.