summaryrefslogtreecommitdiff
path: root/gem/aes.py
blob: 7d515985f34b2a97bbddb8e976503c188343cd58 (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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import struct

import _gem

from error import GEMError
from constants import *

def alert(message,type=None,buttons=('Ok',),default=None):
    """Displays a generic GEM alert box with the specified
    message.  The type of box may also be specified as one
    of ('none', 'exclamation', 'question', 'stop', 'info',
    'disk', 'bomb').  The buttons parameter can contain a 
    tuple or list of button texts (up to 3, as limited by
    GEM."""
    
    alert_types = ['none', 'exclamation', 'question',
                   'stop', 'info', 'disk', 'bomb']
    try:
        internal_type = alert_types.index(type.lower())
    except ValueError:
        raise GEMError('Unknown alert box type')
    except AttributeError:
        if type is None:
            internal_type = 0
        else:
            internal_type = type
    
    if default is None:
        default = 0
    elif type(default) is str:
        try:
            default = buttons.index(default)
        except ValueError:
            raise GEMError('Could not locate default button')
    
    bstring = ''
    if len(buttons) > 3:
        buttons = buttons[0:3]
    for button in buttons:
        if len(button) > 10:
            button = button[0:10]
        bstring = bstring + button + '|'
    bstring = bstring[:-1]
    
    astring = "[{0}][{1}][{2}]".format(repr(internal_type),
                                       message, bstring)
    
    return _gem.form_alert(default, astring)
    
def window_update(action):
    """Issues a 'wind_update()' call to the AES with the specified
    argument.  The action argument must be END_UPDATE, BEG_UPDATE,
    END_MCTRL, or BEG_MCTRL."""
    _gem.wind_update(action)
    
class Window:
    """A class wrapping GEM windows and their functionality"""
    
    def __init__(self, type=NAME|FULLER|MOVER|CLOSER|SIZER):
        """Creates (but does not show) a window"""
        self.id = _gem.wind_create(type,(0,0,10,10))
        self.name = None
    
    def open(self,rect):
        """Opens a window using the the specified rectangle (x,y,w,h)"""
        _gem.wind_open(self.id, rect)
        
    def close(self):
        """Closes (but does not destroy) a window"""
        _gem.wind_close(self.id)
        
    def destroy(self):
        """Deletes an existing GEM window"""
        _gem.wind_delete(self.id)
        self.id = None
    
    def resize(self,rect):
        """Resizes/moves a window"""
        _gem.wind_set(self.id,WF_CURRXYWH,rect)
    
    def top(self):
        """Sets the current window to topmost"""
        _gem.wind_set(self.id,WF_TOP,(self.id,0,0,0))
    
    def set_name(self,name):
        """Sets the name of a window"""
        _gem.wind_set_string(self.id,WF_NAME,name)
        self.name = name
        
    def begin_update(self):
        window_update(BEG_UPDATE)
    
    def end_update(self):
        window_update(END_UPDATE)

    def get_size(self):
        """Returns the window position and size"""
        return _gem.wind_get(self.id,WF_CURRXYWH)

    def get_work_rect(self):
        """Returns this window's current work area rectangle"""
        return _gem.wind_get(self.id,WF_WORKXYWH)
        
    def get_invalid_rectangles(self):
        """Returns a list of rectangles requiring redrawing"""
        rects = []
        r = _gem.wind_get(self.id,WF_FIRSTXYWH)
        while r[2] > 0 or r[3] > 0:
            rects.append(r)
            r = _gem.wind_get(self.id,WF_NEXTXYWH)
        
        return rects
        
    def intersect_work_area(self,rect):
        """Returns the intersecting region of a rectangle and the window's workspace"""
        wrect = self.get_work_rect()

        tw = min(wrect[0]+wrect[2], rect[0]+rect[2])
        th = min(wrect[1]+wrect[3], rect[1]+rect[3])
        tx = max(wrect[0], rect[0])
        ty = max(wrect[1], rect[1])
        
        if (tw > tx) and (th > ty):
            return (tx, ty, tw-tx, th-ty)
        else:
            return None
            
    def graphics_handle(self):
        """Returns a VDI handle to the screen"""
        vh,ignore = _gem.graf_handle()
        return vh

class Event:
    def __init__(self):
        pass
        
    def process(self):
        pass
        
class MouseButtonEvent(Event):
    """A base mouse button event class"""
    def __init__(self, clicks=1, mask=MB_LEFT, state=0):
        Event.__init__(self)
        self.clicks = clicks
        self.mask = mask
        self.requested_state = state
        
        self.returned_button = None
        self.returned_state = None
        self.returned_clicks = None
        self.position = None
        
class MouseMovementEvent(Event):
    def __init__(self):
        Event.__init__(self)
        raise RuntimeError("Not yet implemented")
        
class TimerEvent(Event):
    def __init__(self, length=1000):
        Event.__init__(self)
        self.length = length
        
class KeyboardEvent(Event):
    def __init__(self):
        Event.__init__(self)
        
        self.keycode = None

class MessageEvent(Event):
    def __init__(self):
        Event.__init__(self)

        self.message = None
        self.sender_id = None
        self.extended_data = None
        self.raw_message = None
    
    def get_word(self,index):
        """Retrieves a word from the raw message array"""
        if index > 7:
            raise ValueError('Message index must be between 0 and (including) 7.')
        try:
            ret = struct.unpack_from("@h",self.raw_message,offset=index*2)
        except SystemError:
            print 'Warning: SystemError on struct.unpack_from in get_word()'
            return 0
        return ret[0]
        
    def process(self):
        self.message = self.get_word(0)
        self.sender_id = self.get_word(1)
        
        extended_data_length = self.get_word(2)
        #if extended_data_length > 0:
        #    self.extended_data = _gem.appl_read(self.sender_id,extended_data_length)
        #else:
        #    self.extended_data = None

class Application:

    def __init__(self):
        """Initializes the GEM application"""
        self.id = _gem.appl_init()
        if self.id == -1:
            raise GEMError("The application failed to initialize")
        
        self.windows = []
        self.resource = False
        
        self.message_event = None
        self.button_event = None
        self.keyboard_event = None
        self.mouse_event = None
        self.timer_event = None
        
        self.event_processing = False
        
    def destroy(self):
        """Destroys the application"""
        window_update(BEG_UPDATE)
        for w in self.windows:
            try:
                w.close()
                w.destroy()
            except:
                pass
        window_update(END_UPDATE)
        _gem.appl_exit(self.id)
        
    def load_resource(self,file):
        """Loads a resource file into the application."""
        try:
            _gem.rsrc_load(file)
            self.resource = True
        except:
            self.resource = False
            raise GEMError("Could not load the resource file {0}".format(file))
            
    def get_resource_item(self,type,index):
        """Returns a capsule containing a resource item"""
        return _gem.rsrc_gaddr(type,index)
    
    def set_menu(self,item,show=True):
        """Sets the application menu"""
        if type(item) is int:
            capsule = self.get_resource_address(R_OBJECT,item)
        else:
            capsule = item
        
        action = MENU_SHOW
        if type(show) is int:
            action = show
        elif not show:
            action = MENU_HIDE
        
        window_update(BEG_UPDATE)
        _gem.menu_bar(capsule, action)
        window_update(END_UPDATE)
    
    def get_resource_address(self,type,index):
        """Retrieves the address of a resource element in a Python capsule.
        The returned object should never be directly modified."""
        if not self.resource:
            raise GEMError("A resource has not yet be loaded")
            
        return _gem.rsrc_gaddr(type, index)
        
    def new_window(self, rect, name=None):
        """Opens an application-managed window"""
        w = Window()
        w.begin_update()
        if name is not None:
            w.set_name(name)
        w.open(rect)
        w.end_update()
        
        self.windows.append(w)
        return w
        
    def close_window(self,w):
        """Closes an application-managed window"""
        if w in self.windows:
            self.windows.remove(w)
            w.close()
            w.destroy()
            
    def event_loop(self):
        """Executes the GEM event loop, watching for events specified
        by the event attributes of the Application object."""
        
        self.event_processing = True
        while self.event_processing:
            
            events = 0
            kwdict = dict()
            if self.message_event is not None:
                events = events | MU_MESAG
                
            if self.button_event is not None:
                events = events | MU_BUTTON
                kwdict['mouse_buttons'] = (self.button_event.clicks, 
                                           self.button_event.mask, 
                                           self.button_event.state)
                
            if self.timer_event is not None:
                events = events | MU_TIMER
                kwdict['timer'] = self.timer_event.length
                
            if self.keyboard_event is not None:
                events = events | MU_KEYBD
                
            if self.mouse_event is not None:
                self.event_processing = False
                raise RuntimeError("Not yet implemented")
                events = events | MU_M1 | MU_M2 | MU_WHEEL | MU_MX
            
            if events == 0:
                self.event_processing = False
                raise GEMError("No event callbacks have been specified")
        
            ret = _gem.evnt_multi(events,**kwdict)
            
            if ret['events'] & MU_MESAG:
                #if type(ret['message']) is str:
                #    self.message_event.raw_message = bytearray(ret['message'])
                #else:
                self.message_event.raw_message = ret['message']
                self.message_event.process()
                
            if ret['events'] & MU_BUTTON:
                self.button_event.position = ret['mouse_position']
                self.button_event.returned_button = ret['mouse_button'][0]
                self.button_event.returned_state = ret['mouse_button'][1]
                self.button_event.returned_clicks = ret['mouse_button'][2]
                self.button_event.process()
                
            if ret['events'] & MU_TIMER:
                self.timer_event.process()
                
            if ret['events'] & MU_KEYBD:
                self.keyboard_event.keycode = ret['key']
                self.keyboard_event.process()
                
    def graphics_handle(self):
        """Returns a VDI handle to the screen"""
        vh,ignore = _gem.graf_handle()
        return vh
        
    def send_message(self, data, target=None):
        """Send a message to a gem application (self if target is None)"""
        xmsg = data
        if len(data) > 8:
            raise ValueError("Message may only be 8 words long")
        else:
            while len(xmsg) < 8:
                xmsg = xmsg + (0,)
            
        bytemsg = struct.pack("@hhhhhhhh",*xmsg)
        
        if target is None:
            ret = _gem.appl_write(self.id, 16, bytemsg)
        elif type(target) is int:
            ret = _gem.appl_write(target, 16, bytemsg)
        else:
            ret = _gem.appl_write(target.id, 16, bytemsg)
                
        return ret
        
    def draw_object(self,object,depth,position=None,center=True):
        """Draws an AES object (usually from a resource)"""
        xpos = position
        if center:
            position = _gem.form_center(object)
        
        _gem.objc_draw(object,0,depth,position)
    
    def form_do(self,object):
        """Executes a form (dialog)"""
        return _gem.form_do(object,0)