summaryrefslogtreecommitdiff
path: root/display/modes.py
blob: c43638db32222211c1a8375b2ea39a7d761c08b3 (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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import sys
import importlib
import traceback
# import display.dpy_pygame

KeyPressed  = 2
KeyReleased = 3


class BaseDisplay:
    __taskbkgnd = None
    
    def taskbar(self, s):
        (x, y, w, h) = s
        if self.__taskbkgnd is None:
            pixel = "\x00\x00\x80"
            hole  = "\x01\x01\x01"
            self.__taskbkgnd = self.pixmap(32, 32,
                ((pixel+hole)*16 + (hole+pixel)*16) * 16, 0x010101)
        for j in range(y, y+h, 32):
            for i in range(x, x+w, 32):
                self.putppm(i, j, self.__taskbkgnd,
                            (0, 0, x+w-i, y+h-j))


class Mode:
    low_priority = 0
    
    def __init__(self, name, descr, extraoptsdescr,
                 options={}, url=None):
        self.name = name
        self.descr = descr
        self.extraoptsdescr = extraoptsdescr
        self.options = options.copy()
        self.url = url

    def getmodule(self):
#        import dpy_pygame
        print( f"getmodule __import__ {self.prefix}{self.name.lower()}", file=sys.stderr )
        return importlib.import_module( "display." + self.prefix + self.name.lower() )
        #__import__(self.prefix + self.name.lower(), globals(),
        #                  locals(), ['available'])

    def imperror(self):
        try:
            return self.__imperror
        except AttributeError:
            try:
                print( f"getmodule = {self}" )
                module = self.getmodule()
            except ImportError as e:
                result = 'not installed'
                print("== ImportError traceback:", file=sys.stderr )
                traceback.print_exc(file=sys.stderr)
            else:
                result = hasattr(module, 'imperror') and module.imperror()
            self.__imperror = result
        print( f"imperror result={result}" )
        return result

    def unique_id(self):
        return self.prefix + self.name
    
    def printline(self, f):
        err = self.imperror()
        if err:
            state = ' [%s]' % err
        else:
            state = ''
        print('  %-8s %s%s' % (self.name, self.descr, state), file=f)
        if self.url:
            print('             %s' % self.url, file=f)
        for line in self.extraoptsdescr:
            print('             %s' % line, file=f)

    def getformaloptions(self):
        return '', [c+'=' for c in list(self.options.keys())]

    def setoptions(self, options):
        for key in list(self.options.keys()):
            if '--'+key in options:
                self.options[key] = options['--'+key]

    def currentdriver(self):
        lst = list(self.options.items())
        lst.sort()
        lst = ['--%s=%s' % keyvalue for keyvalue in lst]
        return ' '.join([self.name] + lst)

    def htmloptionstext(self, *args):
        if self.imperror():
            return None
        module = self.getmodule()
        return (hasattr(module, 'htmloptionstext') and
                module.htmloptionstext(*args))


class GraphicMode(Mode):
    prefix = 'dpy_'


class SoundMode(Mode):
    prefix = 'snd_'


def graphicmodeslist():
    return [
        GraphicMode('X', 'XWindow (Linux/Unix)',
                    ['--shm=yes  use the Shared Memory extension (default)',
                     '--shm=no   disable it (for remote connections or old X servers)',
                     ],
                    {'shm': 'yes'}),
        GraphicMode('windows', 'MS Windows', []),
        GraphicMode('pygame', 'PyGame library (all platforms)',
                    ['--fullscreen=yes    go full screen (Esc key to exit)',
                     '--transparency=yes  slightly transparent bubbles (default)',
                     '--transparency=no   disable it (a bit faster)',
                     '--zoom=xxx%         scale image by xxx %',
                     '--smooth            smoothed scaled image',
                     '--smoothfast        semi-smoothed, for 200% scale only'],
                    {'transparency': 'yes', 'fullscreen': 'no',
                     'zoom': '100', 'smooth': 'yes', 'smoothfast': 'no'},
                    url='http://www.pygame.org'),
        GraphicMode('gtk', 'PyGTK (Gnome)',
                    ['--zoom=xxx%         scale image by xxx %'],
                    {'zoom': '100'},
                    url='http://www.pygtk.org/'),
        ]

def soundmodeslist():
    return [
        SoundMode('pygame', 'PyGame library mixer (all platforms)',
                  [], url='http://www.pygame.org'),
        SoundMode('linux', 'audio mixer for Linux',
                  ['--freq=#  mixer frequency (default 44100)',
                   '--fmt=#   data format (default S16_NE, --fmt=list for a list)'],
                  {'freq': '44100', 'fmt': 'S16_NE'}),
        SoundMode('windows', 'audio mixer for Windows',
                  ['--freq=#  mixer frequency (default 44100)',
                   '--bits=#  bits per sample (8 or default 16)'],
                  {'freq': '44100', 'bits': '16'}),
        SoundMode('off', 'no sounds', []),
        ]

def findmode(name, lst):
    if name is None:
        # find the first installed mode
        last_chance = None
        for info in lst:
            err = info.imperror()
            if err:
                continue
            if info.low_priority:
                if last_chance is None:
                    last_chance = info
            else:
                return info
        if last_chance is not None:
            return last_chance
        raise KeyError('no driver available!')
    else:
        # find mode by name
        for info in lst:
            if info.name.upper() == name.upper():
                err = info.imperror()
                if err:
                    raise KeyError('%s: %s' % (info.name, err))
                return info
        raise KeyError('%s: no such driver' % name)

def findmode_err(*args):
    try:
        return findmode(*args)
    except KeyError as e:
        print(str(e), file=sys.stderr)
        sys.exit(1)

def open_dpy(mode, width, height, title):
    driver, sound, extraopts = mode
    ginfo = findmode_err(driver, graphicmodeslist())
    ginfo.setoptions(extraopts)
    dpy = ginfo.getmodule().Display(width, height, title, **ginfo.options)
    print('graphics driver:', ginfo.currentdriver())
    return dpy

def open_snd(mode):
    driver, sound, extraopts = mode
    sinfo = findmode_err(sound, soundmodeslist())
    sinfo.setoptions(extraopts)
    snd = sinfo.getmodule().Sound(**sinfo.options)
    if snd.has_sound:
        sinfo.options['music'] = 'yes'
        sinfo.setoptions(extraopts)
        if (sinfo.options['music'].startswith('n') or
            sinfo.options['music'] == 'off'):
            snd.has_music = 0
        print('sound driver:', sinfo.currentdriver())
        return snd
    else:
        return None


def musichtmloptiontext(nameval):
    return '''<font size=-1>
<%s> Background music</input><%s>
</font>''' % (nameval("checkbox", "music", "yes", default="yes", mangling=0),
              nameval("hidden", "music", "no", mangling=0))