Debian Codegraph @

src/pygame_sdl2/event.pyx

raw
1 # Copyright 2014 Patrick Dawson <[email protected]>
2 # Copyright 2014 Tom Rothamel <[email protected]>
3 #
4 # This software is provided 'as-is', without any express or implied
5 # warranty. In no event will the authors be held liable for any damages
6 # arising from the use of this software.
7 #
8 # Permission is granted to anyone to use this software for any purpose,
9 # including commercial applications, and to alter it and redistribute it
10 # freely, subject to the following restrictions:
11 #
12 # 1. The origin of this software must not be misrepresented; you must not
13 # claim that you wrote the original software. If you use this software
14 # in a product, an acknowledgment in the product documentation would be
15 # appreciated but is not required.
16 # 2. Altered source versions must be plainly marked as such, and must not be
17 # misrepresented as being the original software.
18 # 3. This notice may not be removed or altered from any source distribution.
19
20 from cpython.ref cimport Py_INCREF, Py_DECREF
21
22 from sdl2 cimport *
23 from pygame_sdl2.display cimport Window, main_window
24 import threading
25 import pygame_sdl2
26 import sys
27
28 if sys.version_info[0] >= 3:
29 unichr = chr
30
31 include "event_names.pxi"
32
33 # Add events to emulate SDL 1.2. These also need to be added in locals.
34 ACTIVEEVENT = SDL_LASTEVENT - 1
35 VIDEORESIZE = SDL_LASTEVENT - 2
36 VIDEOEXPOSE = SDL_LASTEVENT - 3
37 WINDOWMOVED = SDL_LASTEVENT - 4
38 # (Do not add events here.)
39
40 event_names[ACTIVEEVENT] = "ACTIVEEVENT"
41 event_names[VIDEORESIZE] = "VIDEORESIZE"
42 event_names[VIDEOEXPOSE] = "VIDEOEXPOSE"
43 event_names[WINDOWMOVED] = "WINDOWMOVED"
44
45 # This is used for events posted to the event queue. This won't be returned
46 # to the user - it's just used internally, with the event object itself
47 # giving the type.
48 cdef unsigned int POSTEDEVENT
49 POSTEDEVENT = SDL_LASTEVENT - 5
50
51 # The maximum number of a user-defined event.
52 USEREVENT_MAX = SDL_LASTEVENT - 6
53
54 # If true, the mousewheel is mapped to buttons 4 and 5. Otherwise, a
55 # MOUSEWHEEL event is created.
56 cdef bint mousewheel_buttons = 1
57
58 cdef unsigned int SDL_TOUCH_MOUSEID
59 SDL_TOUCH_MOUSEID = <unsigned int> -1
60
61 class EventType(object):
62
63 def __init__(self, type, dict=None, **kwargs):
64 self._type = type
65
66 if dict:
67 self.__dict__.update(dict)
68
69 self.__dict__.update(kwargs)
70
71 def __repr__(self):
72 if SDL_USEREVENT <= self.type < WINDOWMOVED:
73 ename = "UserEvent%d" % (self.type - SDL_USEREVENT)
74 else:
75 try:
76 ename = event_names[self.type]
77 except KeyError:
78 ename = "UNKNOWN"
79
80 rest = [ ]
81
82 for k, v in sorted(self.__dict__.items()):
83 if k == "_type" or k == "timestamp":
84 continue
85
86 rest.append("%s=%r" % (k, v))
87
88 return '<Event(%d-%s %s)>' % (self.type, ename, ", ".join(rest))
89
90 @property
91 def dict(self):
92 return self.__dict__
93
94 @property
95 def type(self):
96 return self._type
97
98 def __eq__(self, other):
99 return self.__dict__ == other.__dict__
100
101 def __ne__(self, other):
102 return not (self == other)
103
104 def __nonzero__(self):
105 return self.type != 0
106
107 Event = EventType
108
109 cdef get_textinput():
110 cdef SDL_Event evt
111
112 SDL_PumpEvents()
113
114 if SDL_PeepEvents(&evt, 1, SDL_GETEVENT, SDL_TEXTINPUT, SDL_TEXTINPUT) > 0:
115 return evt.text.text.decode('utf-8')
116 return u''
117
118 cdef make_keyboard_event(SDL_KeyboardEvent *e):
119 dargs = { 'scancode' : e.keysym.scancode,
120 'key' : e.keysym.sym,
121 'mod' : e.keysym.mod,
122 'unicode' : '',
123 'repeat' : e.repeat,
124 }
125
126 if not pygame_sdl2.key.text_input:
127
128 if e.type == SDL_KEYDOWN:
129 # Be careful to only check for a TEXTINPUT event when you know that
130 # there will be one associated with this KEYDOWN event.
131 if e.keysym.sym < 0x20:
132 dargs['unicode'] = unichr(e.keysym.sym)
133 elif e.keysym.sym <= 0xFFFF:
134 dargs['unicode'] = get_textinput()
135
136 else:
137 if e.type == SDL_KEYDOWN and not(e.keysym.mod & KMOD_NUM):
138 if SDLK_KP_1 <= e.keysym.sym <= SDLK_KP_0:
139 get_textinput()
140 dargs['unicode'] = ''
141
142 return EventType(e.type, dict=dargs, repeat=e.repeat)
143
144 cdef make_mousemotion_event(SDL_MouseMotionEvent *e):
145 buttons = (1 if e.state & SDL_BUTTON_LMASK else 0,
146 1 if e.state & SDL_BUTTON_MMASK else 0,
147 1 if e.state & SDL_BUTTON_RMASK else 0)
148 return EventType(e.type, pos=(e.x, e.y), rel=(e.xrel, e.yrel), which=e.which, buttons=buttons, touch=(SDL_TOUCH_MOUSEID == e.which))
149
150 cdef make_mousebtn_event(SDL_MouseButtonEvent *e):
151 btn = e.button
152
153 # SDL 1.x maps wheel to buttons 4/5
154 if mousewheel_buttons and btn >= 4:
155 btn += 2
156
157 return EventType(e.type, button=btn, pos=(e.x, e.y), which=e.which, touch=(SDL_TOUCH_MOUSEID == e.which))
158
159 cdef make_mousewheel_event(SDL_MouseWheelEvent *e):
160
161 cdef int x, y
162
163 # SDL2-style, if the user has opted-in.
164 if not mousewheel_buttons:
165 return EventType(e.type, which=e.which, x=e.x, y=e.y, touch=(SDL_TOUCH_MOUSEID == e.which))
166
167 # Otherwise, follow the SDL1 approach.
168
169 y = e.y
170
171 # TODO: Implement when 2.0.4 becomes widespread.
172 # if e.direction == SDL_MOUSEWHEEL_FLIPPED:
173 # y = -y
174
175 if y > 0:
176 btn = 4
177 elif y < 0:
178 btn = 5
179 else:
180 return EventType(0) # x axis scrolling produces no event in pygame
181
182 # This is not the mouse position at the time of the event
183 SDL_GetMouseState(&x, &y)
184
185 # MOUSEBUTTONUP event should follow immediately after
186 event_queue.insert(0, EventType(SDL_MOUSEBUTTONUP, which=e.which, button=btn, pos=(x,y), touch=(SDL_TOUCH_MOUSEID == e.which)))
187 return EventType(SDL_MOUSEBUTTONDOWN, which=e.which, button=btn, pos=(x,y), touch=(SDL_TOUCH_MOUSEID == e.which))
188
189
190 cdef make_joyaxis_event(SDL_JoyAxisEvent *e):
191 return EventType(e.type, joy=e.which, instance_id=e.which, axis=e.axis, value=e.value/32768.0)
192
193 cdef make_joyball_event(SDL_JoyBallEvent *e):
194 return EventType(e.type, joy=e.which, instance_id=e.which, ball=e.ball, rel=(e.xrel, e.yrel))
195
196 cdef make_joyhat_event(SDL_JoyHatEvent *e):
197 return EventType(e.type, joy=e.which, instance_id=e.which, hat=e.hat, value=e.value)
198
199 cdef make_joybtn_event(SDL_JoyButtonEvent *e):
200 return EventType(e.type, joy=e.which, instance_id=e.which, button=e.button)
201
202 cdef make_textinput_event(SDL_TextInputEvent *e):
203 try:
204 return EventType(e.type, text=e.text.decode("utf-8"))
205 except UnicodeDecodeError:
206 return EventType(e.type, text='')
207
208 cdef make_textediting_event(SDL_TextEditingEvent *e):
209 try:
210 return EventType(e.type, text=e.text.decode("utf-8"), start=e.start, length=e.length)
211 except UnicodeDecodeError:
212 return EventType(e.type, text='', start=e.start, length=e.length)
213
214 cdef make_drop_event(SDL_DropEvent *e):
215 if e.file:
216 file = e.file.decode("utf-8")
217 SDL_free(e.file)
218 else:
219 file = None
220
221 return EventType(e.type, file=file, window_id=e.windowID)
222
223 cdef make_window_event(SDL_WindowEvent *e):
224 # SDL_APPMOUSEFOCUS
225 if e.event == SDL_WINDOWEVENT_ENTER:
226 return EventType(ACTIVEEVENT, state=1, gain=1)
227 elif e.event == SDL_WINDOWEVENT_LEAVE:
228 return EventType(ACTIVEEVENT, state=1, gain=0)
229
230 # SDL_APPINPUTFOCUS
231 elif e.event == SDL_WINDOWEVENT_FOCUS_GAINED:
232 return EventType(ACTIVEEVENT, state=2, gain=1)
233 elif e.event == SDL_WINDOWEVENT_FOCUS_LOST:
234 return EventType(ACTIVEEVENT, state=2, gain=0)
235
236 # SDL_APPACTIVE
237 elif e.event == SDL_WINDOWEVENT_RESTORED:
238 return EventType(ACTIVEEVENT, state=4, gain=1)
239 elif e.event == SDL_WINDOWEVENT_MINIMIZED:
240 return EventType(ACTIVEEVENT, state=4, gain=0)
241
242 elif e.event == SDL_WINDOWEVENT_RESIZED:
243 return EventType(VIDEORESIZE, size=(e.data1, e.data2), w=e.data1, h=e.data2)
244
245 elif e.event == SDL_WINDOWEVENT_EXPOSED:
246 return EventType(VIDEOEXPOSE)
247
248 elif e.event == SDL_WINDOWEVENT_MOVED:
249 return EventType(WINDOWMOVED, pos=(e.data1, e.data2), x=e.data1, y=e.data2)
250
251 return EventType(SDL_WINDOWEVENT, event=e.event, data1=e.data1, data2=e.data2)
252
253 cdef make_event(SDL_Event *e):
254 cdef object o
255
256 if e.type == SDL_MOUSEMOTION:
257 return make_mousemotion_event(<SDL_MouseMotionEvent*>e)
258 elif e.type in (SDL_MOUSEBUTTONDOWN, SDL_MOUSEBUTTONUP):
259 return make_mousebtn_event(<SDL_MouseButtonEvent*>e)
260
261 elif e.type == SDL_MOUSEWHEEL:
262 return make_mousewheel_event(<SDL_MouseWheelEvent*>e)
263 elif e.type in (SDL_KEYDOWN, SDL_KEYUP):
264 return make_keyboard_event(<SDL_KeyboardEvent*>e)
265 elif e.type == SDL_JOYAXISMOTION:
266 return make_joyaxis_event(<SDL_JoyAxisEvent*>e)
267 elif e.type == SDL_JOYBALLMOTION:
268 return make_joyball_event(<SDL_JoyBallEvent*>e)
269 elif e.type == SDL_JOYHATMOTION:
270 return make_joyhat_event(<SDL_JoyHatEvent*>e)
271 elif e.type in (SDL_JOYBUTTONDOWN, SDL_JOYBUTTONUP):
272 return make_joybtn_event(<SDL_JoyButtonEvent*>e)
273 elif e.type in (SDL_JOYDEVICEADDED, SDL_JOYDEVICEREMOVED):
274 return EventType(e.type, which=e.jdevice.which)
275 elif e.type == SDL_WINDOWEVENT:
276 return make_window_event(<SDL_WindowEvent*>e)
277 elif e.type == SDL_TEXTINPUT:
278 return make_textinput_event(<SDL_TextInputEvent *> e)
279 elif e.type == SDL_TEXTEDITING:
280 return make_textediting_event(<SDL_TextEditingEvent *> e)
281 elif e.type == SDL_CONTROLLERAXISMOTION:
282 return EventType(e.type, which=e.caxis.which, axis=e.caxis.axis, value=e.caxis.value)
283 elif e.type in (SDL_CONTROLLERBUTTONDOWN, SDL_CONTROLLERBUTTONUP):
284 return EventType(e.type, which=e.cbutton.which, button=e.cbutton.button, state=e.cbutton.state)
285 elif e.type in (SDL_CONTROLLERDEVICEADDED, SDL_CONTROLLERDEVICEREMOVED, SDL_CONTROLLERDEVICEREMAPPED):
286 return EventType(e.type, which=e.cdevice.which)
287 elif e.type in (SDL_FINGERMOTION, SDL_FINGERDOWN, SDL_FINGERUP):
288 return EventType(e.type, touchId=e.tfinger.touchId, fingerId=e.tfinger.fingerId, touch_id=e.tfinger.touchId, finger_id=e.tfinger.fingerId, x=e.tfinger.x, y=e.tfinger.y, dx=e.tfinger.dx, dy=e.tfinger.dy, pressure=e.tfinger.pressure)
289 elif e.type == SDL_MULTIGESTURE:
290 return EventType(e.type, touchId=e.mgesture.touchId, dTheta=e.mgesture.dTheta, dDist=e.mgesture.dDist, x=e.mgesture.x, y=e.mgesture.y, numFingers=e.mgesture.numFingers, touch_id=e.mgesture.touchId, rotated=e.mgesture.dTheta, pinched=e.mgesture.dDist, num_fingers=e.mgesture.numFingers)
291 elif e.type in (SDL_DROPFILE, SDL_DROPTEXT, SDL_DROPBEGIN, SDL_DROPCOMPLETE):
292 return make_drop_event(<SDL_DropEvent*> e)
293 elif e.type == POSTEDEVENT:
294 o = <object> e.user.data1
295 Py_DECREF(o)
296 return o
297 elif e.type >= SDL_USEREVENT:
298 # Can't do anything useful with data1 and data2 here.
299 return EventType(e.type, code=e.user.code)
300
301 return EventType(e.type)
302
303
304 # The event queue - a list of pending events from oldest to newest.
305 cdef public event_queue = list()
306
307 # The lock that protects the event queue.
308 lock = threading.RLock()
309
310 # This is the object that is returned when no event exists.
311 NOEVENT_EVENT = EventType(0)
312
313
314 cdef bint has_event(kinds):
315 """
316 Returns true if at least one event in the queue has a type in `kinds`,
317 which must support the in operator.
318
319 The lock must be held when calling this function
320 """
321
322 for i in event_queue:
323 if i._type in kinds:
324 return True
325
326
327 cdef object get_events(kinds):
328 """
329 Returns a list containing all events in the event queue with type `kinds`.
330 Removes those events from the event queue.
331
332 The lock must be held when calling this function.
333 """
334
335 if isinstance(kinds, int):
336 kinds = [ kinds ]
337
338 global event_queue
339
340 cdef list rv = [ ]
341 cdef list new_queue = [ ]
342
343 for i in event_queue:
344 if i._type in kinds:
345 rv.append(i)
346 else:
347 new_queue.append(i)
348
349 event_queue = new_queue
350
351 return rv
352
353
354 cdef int poll_sdl() except 1:
355 """
356 Polls SDL for pending events, and places those events onto the event q
357 queue.
358 """
359
360 cdef SDL_Event evt
361
362 with lock:
363 while SDL_PollEvent(&evt):
364 e = make_event(&evt)
365 e.timestamp = evt.common.timestamp
366 event_queue.append(e)
367
368 return 0
369
370
371 def pump():
372 with lock:
373 poll_sdl()
374
375
376 def get(t=None):
377
378 global event_queue
379
380 with lock:
381 poll_sdl()
382
383 if t is None:
384 rv = event_queue
385 event_queue = [ ]
386
387 elif isinstance(t, int):
388 rv = get_events(( t, ))
389
390 else:
391 rv = get_events(t)
392
393 return rv
394
395
396 def poll():
397
398 with lock:
399 poll_sdl()
400
401 if event_queue:
402 return event_queue.pop(0)
403
404 return NOEVENT_EVENT
405
406
407 def wait():
408
409 cdef SDL_Event evt
410 cdef int result
411
412 with lock:
413 poll_sdl()
414
415 if event_queue:
416 return event_queue.pop(0)
417
418 with nogil:
419 result = SDL_WaitEvent(&evt)
420
421 if result:
422 return make_event(&evt)
423 else:
424 return NOEVENT_EVENT
425
426
427 def peek(t=None):
428
429 with lock:
430 poll_sdl()
431
432 if t is None:
433 return len(event_queue) != 0
434 elif isinstance(t, int):
435 return has_event(( t, ))
436 else:
437 return has_event(t)
438
439
440 def clear(t=None):
441
442 # Clear is implemented in terms of get.
443 get(t)
444
445 def get_standard_events():
446 """
447 Returns a list of standard events that pygame_sdl2 knows about.
448 """
449
450 return [ i for i in event_names.keys() if (i < SDL_USEREVENT) or (i > USEREVENT_MAX) ]
451
452 def event_name(t):
453 try:
454 return event_names[t]
455 except KeyError:
456 return "UNKNOWN"
457
458 def set_blocked(t=None):
459 if t == None:
460 for et in event_names.keys():
461 SDL_EventState(et, SDL_ENABLE)
462 elif isinstance(t, int):
463 SDL_EventState(t, SDL_IGNORE)
464 else:
465 for et in t:
466 SDL_EventState(et, SDL_IGNORE)
467
468 def set_allowed(t=None):
469 if t == None:
470 for et in event_names.keys():
471 SDL_EventState(et, SDL_IGNORE)
472 elif isinstance(t, int):
473 SDL_EventState(t, SDL_ENABLE)
474 else:
475 for et in t:
476 SDL_EventState(et, SDL_ENABLE)
477
478 def get_blocked(t):
479 return SDL_EventState(t, SDL_QUERY) == SDL_IGNORE
480
481 def set_grab(on):
482 SDL_SetWindowGrab(main_window.window, on)
483
484 if SDL_ShowCursor(SDL_QUERY) == SDL_DISABLE:
485 SDL_SetRelativeMouseMode(on)
486
487 def get_grab():
488 return SDL_GetWindowGrab(main_window.window)
489
490 def set_mousewheel_buttons(flag):
491 """
492 If true (the default), the mousewheel will generate events involving
493 mouse buttons 4 and 5, and mousebuttons 4 and higher will be mapped to 6 and higher.
494
495 If false, MOUSEWHEEL events are generated, and the mousebuttons are
496 not remapped.
497 """
498
499 global mousewheel_buttons
500 mousewheel_buttons = flag
501
502 def get_mousewheel_buttons():
503 """
504 Returns the value set by mousehweel buttons,.
505 """
506
507 return mousewheel_buttons
508
509 def post(e):
510 """
511 Posts event object `e` to the event queue.
512 """
513
514 cdef SDL_Event event;
515
516 if not isinstance(e, EventType):
517 raise pygame_sdl2.error("event.post must be called with an Event.")
518
519 if get_blocked(e.type):
520 return
521
522 Py_INCREF(e)
523
524 event.type = POSTEDEVENT
525 event.user.data1 = <void *> e
526
527 SDL_PushEvent(&event)
528
529 def register(name):
530 """
531 Registers a unique event number and returns that number.
532
533 `name`
534 A string name for the event. This is used when calling `repr` on
535 the event.
536 """
537
538 rv = SDL_RegisterEvents(1)
539
540 event_names[rv] = name
541 return rv
542
543 def copy_event_queue():
544 """
545 Returns a copy of the event queue. The copy cannot be used for modifying
546 the event queue.
547 """
548
549 return event_queue[:]
550
551 # Usually called by display.init.
552 def init():
553 if not SDL_WasInit(SDL_INIT_EVENTS):
554
555 pygame_sdl2.display.sdl_main_init()
556
557 if SDL_InitSubSystem(SDL_INIT_EVENTS):
558 raise pygame_sdl2.error.error()
559
560 _types = """
561 Event = EventType
562 """