#dumpassoc.py
# Copyright (c) 2007 Vincent Povirk
# Prints out a list of extensions and corresponding mime types, and the verbs available for each mime type.
# This is mostly intended as a proof of concept.

import _winreg

#get all subkeys of an existing key
#this works by getting the Nth subkey for all nonzero integers until one fails
#I assume bad things will happen if keys are added/removed while this is working
def get_subkeys(key):
    i = 0
    while True:
        try:
            yield _winreg.EnumKey(key, i)
        except EnvironmentError:
            return
        i = i + 1

for extension in get_subkeys(_winreg.HKEY_CLASSES_ROOT):
    if extension.startswith('.'): #should we exclude .exe and .dll ?
        extension = extension.lower()
        ext_key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, extension)
        objectname = _winreg.QueryValue(ext_key, None)
        if not objectname:
            continue
        #Don't try to read the mime type from the registry (it'd be 
        #ext_key\Content Type) because we can't trust it; python registers .py
        #files as text/plain. I'm told DE's can generally cope with types like
        #application/x-extension-html, even when text/html already exists.
        mimetype = 'application/x-extension-%s' % extension[1:]
        print "extension %s %s" % (extension, mimetype)
        
        obj_key = _winreg.OpenKey(_winreg.HKEY_CLASSES_ROOT, objectname)
        try:
            objname_verbs = get_subkeys(_winreg.OpenKey(obj_key, 'shell'))
        except WindowsError:
            objname_verbs = []
        for verb in objname_verbs:
            print "verb %s %s" % (mimetype, verb.lower())
        #Technically, we should also look for HKCR\Classes\{clsid}\Shell\* (and
        #not print duplicates twice), but I haven't seen anything use it.

