summaryrefslogtreecommitdiffstats
path: root/python/pykde/examples/pykde-sampler/lib.py
blob: 875ae1ab8bb67fa9598871a41201fd58ec6ed7ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#!/usr/bin/env python
"""

"""
import os
import sys

from os import listdir, walk
from os.path import dirname, isdir, abspath, split, join, exists


samplerpath = dirname(abspath(__file__))
packagepath, packagename = split(samplerpath)

samplerpath += os.path.sep
packagepath += os.path.sep


def namedimport(name):
    """ import a module given a dotted package name

    Taken directly from the Python library docs for __import __
    """
    mod = __import__(name)
    components = name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod


def ispackage(path):
    return isdir(path) and exists(join(path, '__init__.py'))


def ismodule(path):
    head, tail = os.path.split(path)
    if tail in ('__init__.py', '__init__.pyc', '__init__.pyo'):
        return False
    head, tail = os.path.splitext(path)
    return tail in ('.py', ) # don't use these, which filters them out dupes ( '.pyc', '.pyo')


def listimports(top):
    top = abspath(top)
    yield top
    for path in listdir(top):
        path = join(top, path)
        if ispackage(path):
            yield path
            for subpath in listimports(path):
                yield subpath
        elif ismodule(path):
            yield path


def listmodules():
    if samplerpath not in sys.path:
        sys.path.append(samplerpath)

    dirs = [join(samplerpath, d) for d in listdir(samplerpath)]
    dirs = [d for d in dirs if exists(join(d, '__init__.py'))]

    modules = []    
    for dirname in dirs:
        dirpath = join(samplerpath, dirname)
        for path in listimports(dirpath):
            path = path.replace('.py', '')
            path = path.replace(samplerpath, '').replace(os.path.sep, '.')
            try:
                module = namedimport(path)
            except (ValueError, ImportError, ), exc:
                print 'Exception %s importing %s' % (exc, path, )
            else:
                modules.append((path, module))
    modules.sort()
    return [(path, SamplerModule(module)) for path, module in modules]


class SamplerModule(object):
    defaultIcon = 'filenew'


    def __init__(self, module):
        self.module = module


    def name(self):
        return self.module.__name__.split('.')[-1]


    def labelText(self):
        return getattr(self.module, 'labelText', self.name())


    def icon(self):
        return getattr(self.module, 'iconName', self.defaultIcon)


    def builder(self):
        for name in ('buildWidget', 'buildDialog', 'buildApp', 'MainFrame'):
            try:
                return getattr(self.module, name)
            except (AttributeError, ):
                pass
        raise AttributeError('No builder found')