/
event.py
2877 lines (2453 loc) · 84.6 KB
/
event.py
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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""A light-weight implementation of event handling built on calls to SDL.
Many event constants are derived directly from SDL.
For example: ``tcod.event.KeySym.UP`` and ``tcod.event.Scancode.A`` refer to
SDL's ``SDLK_UP`` and ``SDL_SCANCODE_A`` respectfully.
`See this table for all of SDL's keyboard constants.
<https://wiki.libsdl.org/SDL_Keycode>`_
Printing any event will tell you its attributes in a human readable format.
An events type attribute if omitted is just the classes name with all letters upper-case.
As a general guideline, you should use :any:`KeyboardEvent.sym` for command inputs,
and :any:`TextInput.text` for name entry fields.
Example::
import tcod
KEY_COMMANDS = {
tcod.event.KeySym.UP: "move N",
tcod.event.KeySym.DOWN: "move S",
tcod.event.KeySym.LEFT: "move W",
tcod.event.KeySym.RIGHT: "move E",
}
context = tcod.context.new()
while True:
console = context.new_console()
context.present(console, integer_scaling=True)
for event in tcod.event.wait():
context.convert_event(event) # Adds tile coordinates to mouse events.
if isinstance(event, tcod.event.Quit):
print(event)
raise SystemExit()
elif isinstance(event, tcod.event.KeyDown):
print(event) # Prints the Scancode and KeySym enums for this event.
if event.sym in KEY_COMMANDS:
print(f"Command: {KEY_COMMANDS[event.sym]}")
elif isinstance(event, tcod.event.MouseButtonDown):
print(event) # Prints the mouse button constant names for this event.
elif isinstance(event, tcod.event.MouseMotion):
print(event) # Prints the mouse button mask bits in a readable format.
else:
print(event) # Print any unhandled events.
Python 3.10 introduced `match statements <https://docs.python.org/3/tutorial/controlflow.html#match-statements>`_
which can be used to dispatch events more gracefully:
Example::
import tcod
KEY_COMMANDS = {
tcod.event.KeySym.UP: "move N",
tcod.event.KeySym.DOWN: "move S",
tcod.event.KeySym.LEFT: "move W",
tcod.event.KeySym.RIGHT: "move E",
}
context = tcod.context.new()
while True:
console = context.new_console()
context.present(console, integer_scaling=True)
for event in tcod.event.wait():
context.convert_event(event) # Adds tile coordinates to mouse events.
match event:
case tcod.event.Quit():
raise SystemExit()
case tcod.event.KeyDown(sym) if sym in KEY_COMMANDS:
print(f"Command: {KEY_COMMANDS[sym]}")
case tcod.event.KeyDown(sym=sym, scancode=scancode, mod=mod, repeat=repeat):
print(f"KeyDown: {sym=}, {scancode=}, {mod=}, {repeat=}")
case tcod.event.MouseButtonDown(button=button, pixel=pixel, tile=tile):
print(f"MouseButtonDown: {button=}, {pixel=}, {tile=}")
case tcod.event.MouseMotion(pixel=pixel, pixel_motion=pixel_motion, tile=tile, tile_motion=tile_motion):
print(f"MouseMotion: {pixel=}, {pixel_motion=}, {tile=}, {tile_motion=}")
case tcod.event.Event() as event:
print(event) # Show any unhandled events.
.. versionadded:: 8.4
"""
from __future__ import annotations
import enum
import warnings
from typing import Any, Callable, Final, Generic, Iterator, Mapping, NamedTuple, TypeVar
import numpy as np
from numpy.typing import NDArray
from typing_extensions import Literal
import tcod.event_constants
import tcod.sdl.joystick
from tcod.cffi import ffi, lib
from tcod.event_constants import * # noqa: F403
from tcod.event_constants import KMOD_ALT, KMOD_CTRL, KMOD_GUI, KMOD_SHIFT
from tcod.sdl.joystick import _HAT_DIRECTIONS
T = TypeVar("T")
class _ConstantsWithPrefix(Mapping[int, str]):
def __init__(self, constants: Mapping[int, str]) -> None:
self.constants = constants
def __getitem__(self, key: int) -> str:
return "tcod.event." + self.constants[key]
def __len__(self) -> int:
return len(self.constants)
def __iter__(self) -> Iterator[int]:
return iter(self.constants)
def _describe_bitmask(bits: int, table: Mapping[int, str], default: str = "0") -> str:
"""Return a bitmask in human readable form.
This is a private function, used internally.
`bits` is the bitmask to be represented.
`table` is a reverse lookup table.
`default` is returned when no other bits can be represented.
"""
result = []
for bit, name in table.items():
if bit & bits:
result.append(name)
if not result:
return default
return "|".join(result)
def _pixel_to_tile(x: float, y: float) -> tuple[float, float] | None:
"""Convert pixel coordinates to tile coordinates."""
if not lib.TCOD_ctx.engine:
return None
xy = ffi.new("double[2]", (x, y))
lib.TCOD_sys_pixel_to_tile(xy, xy + 1)
return xy[0], xy[1]
class Point(NamedTuple):
"""A 2D position used for events with mouse coordinates.
.. seealso::
:any:`MouseMotion` :any:`MouseButtonDown` :any:`MouseButtonUp`
"""
x: int
"""A pixel or tile coordinate starting with zero as the left-most position."""
y: int
"""A pixel or tile coordinate starting with zero as the top-most position."""
def _verify_tile_coordinates(xy: Point | None) -> Point:
"""Check if an events tile coordinate is initialized and warn if not.
Always returns a valid Point object for backwards compatibility.
"""
if xy is not None:
return xy
warnings.warn(
"This events tile coordinates are uninitialized!"
"\nYou MUST pass this event to `Context.convert_event` before you can"
" read its tile attributes.",
RuntimeWarning,
stacklevel=3, # Called within other functions, never directly.
)
return Point(0, 0)
_is_sdl_video_initialized = False
def _init_sdl_video() -> None:
"""Keyboard layout stuff needs SDL to be initialized first."""
global _is_sdl_video_initialized
if _is_sdl_video_initialized:
return
lib.SDL_InitSubSystem(lib.SDL_INIT_VIDEO)
_is_sdl_video_initialized = True
class Modifier(enum.IntFlag):
"""Keyboard modifier flags, a bit-field of held modifier keys.
Use `bitwise and` to check if a modifier key is held.
The following example shows some common ways of checking modifiers.
All non-zero return values are considered true.
Example::
>>> mod = tcod.event.Modifier(4098)
>>> mod & tcod.event.Modifier.SHIFT # Check if any shift key is held.
<Modifier.RSHIFT: 2>
>>> mod & tcod.event.Modifier.LSHIFT # Check if left shift key is held.
<Modifier.NONE: 0>
>>> not mod & tcod.event.Modifier.LSHIFT # Check if left shift key is NOT held.
True
>>> mod & tcod.event.Modifier.SHIFT and mod & tcod.event.Modifier.CTRL # Check if Shift+Control is held.
<Modifier.NONE: 0>
.. versionadded:: 12.3
"""
NONE = 0
LSHIFT = 1
"""Left shift."""
RSHIFT = 2
"""Right shift."""
SHIFT = LSHIFT | RSHIFT
"""LSHIFT | RSHIFT"""
LCTRL = 64
"""Left control."""
RCTRL = 128
"""Right control."""
CTRL = LCTRL | RCTRL
"""LCTRL | RCTRL"""
LALT = 256
"""Left alt."""
RALT = 512
"""Right alt."""
ALT = LALT | RALT
"""LALT | RALT"""
LGUI = 1024
"""Left meta key."""
RGUI = 2048
"""Right meta key."""
GUI = LGUI | RGUI
"""LGUI | RGUI"""
NUM = 4096
"""Numpad lock."""
CAPS = 8192
"""Caps lock."""
MODE = 16384
"""Alt graph."""
class MouseButton(enum.IntEnum):
"""An enum for mouse buttons.
.. versionadded:: 16.1
"""
LEFT = 1
"""Left mouse button."""
MIDDLE = 2
"""Middle mouse button."""
RIGHT = 3
"""Right mouse button."""
X1 = 4
"""Back mouse button."""
X2 = 5
"""Forward mouse button."""
def __repr__(self) -> str:
return f"{self.__class__.__name__}.{self.name}"
class MouseButtonMask(enum.IntFlag):
"""A mask enum for held mouse buttons.
.. versionadded:: 16.1
"""
LEFT = 0x1
"""Left mouse button is held."""
MIDDLE = 0x2
"""Middle mouse button is held."""
RIGHT = 0x4
"""Right mouse button is held."""
X1 = 0x8
"""Back mouse button is held."""
X2 = 0x10
"""Forward mouse button is held."""
def __repr__(self) -> str:
if self.value == 0:
return f"{self.__class__.__name__}(0)"
return "|".join(f"{self.__class__.__name__}.{self.__class__(bit).name}" for bit in self.__class__ if bit & self)
class Event:
"""The base event class.
Attributes:
type (str): This events type.
sdl_event: When available, this holds a python-cffi 'SDL_Event*'
pointer. All sub-classes have this attribute.
"""
def __init__(self, type: str | None = None) -> None:
if type is None:
type = self.__class__.__name__.upper()
self.type: Final = type
self.sdl_event = None
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> Event:
"""Return a class instance from a python-cffi 'SDL_Event*' pointer."""
raise NotImplementedError()
def __str__(self) -> str:
return f"<type={self.type!r}>"
class Quit(Event):
"""An application quit request event.
For more info on when this event is triggered see:
https://wiki.libsdl.org/SDL_EventType#SDL_QUIT
Attributes:
type (str): Always "QUIT".
"""
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> Quit:
self = cls()
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}()"
class KeyboardEvent(Event):
"""Base keyboard event.
Attributes:
type (str): Will be "KEYDOWN" or "KEYUP", depending on the event.
scancode (Scancode): The keyboard scan-code, this is the physical location
of the key on the keyboard rather than the keys symbol.
sym (KeySym): The keyboard symbol.
mod (Modifier): A bitmask of the currently held modifier keys.
For example, if shift is held then
``event.mod & tcod.event.Modifier.SHIFT`` will evaluate to a true
value.
repeat (bool): True if this event exists because of key repeat.
.. versionchanged:: 12.5
`scancode`, `sym`, and `mod` now use their respective enums.
"""
def __init__(self, scancode: int, sym: int, mod: int, repeat: bool = False) -> None:
super().__init__()
self.scancode = Scancode(scancode)
self.sym = KeySym(sym)
self.mod = Modifier(mod)
self.repeat = repeat
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> Any:
keysym = sdl_event.key.keysym
self = cls(keysym.scancode, keysym.sym, keysym.mod, bool(sdl_event.key.repeat))
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return "tcod.event.{}(scancode={!r}, sym={!r}, mod={!r}{})".format(
self.__class__.__name__,
self.scancode,
self.sym,
self.mod,
", repeat=True" if self.repeat else "",
)
def __str__(self) -> str:
return self.__repr__().replace("tcod.event.", "")
class KeyDown(KeyboardEvent):
pass
class KeyUp(KeyboardEvent):
pass
class MouseState(Event):
"""Mouse state.
Attributes:
type (str): Always "MOUSESTATE".
position (Point): The position coordinates of the mouse.
tile (Point): The integer tile coordinates of the mouse on the screen.
state (int): A bitmask of which mouse buttons are currently held.
Will be a combination of the following names:
* tcod.event.BUTTON_LMASK
* tcod.event.BUTTON_MMASK
* tcod.event.BUTTON_RMASK
* tcod.event.BUTTON_X1MASK
* tcod.event.BUTTON_X2MASK
.. versionadded:: 9.3
.. versionchanged:: 15.0
Renamed `pixel` attribute to `position`.
"""
def __init__(
self,
position: tuple[int, int] = (0, 0),
tile: tuple[int, int] | None = (0, 0),
state: int = 0,
) -> None:
super().__init__()
self.position = Point(*position)
self._tile = Point(*tile) if tile is not None else None
self.state = state
@property
def pixel(self) -> Point:
warnings.warn(
"The mouse.pixel attribute is deprecated. Use mouse.position instead.",
DeprecationWarning,
stacklevel=2,
)
return self.position
@pixel.setter
def pixel(self, value: Point) -> None:
self.position = value
@property
def tile(self) -> Point:
warnings.warn(
"The mouse.tile attribute is deprecated. Use mouse.position of the event returned by context.convert_event instead.",
DeprecationWarning,
stacklevel=2,
)
return _verify_tile_coordinates(self._tile)
@tile.setter
def tile(self, xy: tuple[int, int]) -> None:
self._tile = Point(*xy)
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(position={tuple(self.position)!r}, tile={tuple(self.tile)!r}, state={MouseButtonMask(self.state)})"
def __str__(self) -> str:
return ("<%s, position=(x=%i, y=%i), tile=(x=%i, y=%i), state=%s>") % (
super().__str__().strip("<>"),
*self.position,
*self.tile,
MouseButtonMask(self.state),
)
class MouseMotion(MouseState):
"""Mouse motion event.
Attributes:
type (str): Always "MOUSEMOTION".
position (Point): The pixel coordinates of the mouse.
motion (Point): The pixel delta.
tile (Point): The integer tile coordinates of the mouse on the screen.
tile_motion (Point): The integer tile delta.
state (int): A bitmask of which mouse buttons are currently held.
Will be a combination of the following names:
* tcod.event.BUTTON_LMASK
* tcod.event.BUTTON_MMASK
* tcod.event.BUTTON_RMASK
* tcod.event.BUTTON_X1MASK
* tcod.event.BUTTON_X2MASK
.. versionchanged:: 15.0
Renamed `pixel` attribute to `position`.
Renamed `pixel_motion` attribute to `motion`.
"""
def __init__(
self,
position: tuple[int, int] = (0, 0),
motion: tuple[int, int] = (0, 0),
tile: tuple[int, int] | None = (0, 0),
tile_motion: tuple[int, int] | None = (0, 0),
state: int = 0,
) -> None:
super().__init__(position, tile, state)
self.motion = Point(*motion)
self.__tile_motion = Point(*tile_motion) if tile_motion is not None else None
@property
def pixel_motion(self) -> Point:
warnings.warn(
"The mouse.pixel_motion attribute is deprecated. Use mouse.motion instead.",
DeprecationWarning,
stacklevel=2,
)
return self.motion
@pixel_motion.setter
def pixel_motion(self, value: Point) -> None:
warnings.warn(
"The mouse.pixel_motion attribute is deprecated. Use mouse.motion instead.",
DeprecationWarning,
stacklevel=2,
)
self.motion = value
@property
def tile_motion(self) -> Point:
warnings.warn(
"The mouse.tile_motion attribute is deprecated."
" Use mouse.motion of the event returned by context.convert_event instead.",
DeprecationWarning,
stacklevel=2,
)
return _verify_tile_coordinates(self.__tile_motion)
@tile_motion.setter
def tile_motion(self, xy: tuple[int, int]) -> None:
warnings.warn(
"The mouse.tile_motion attribute is deprecated."
" Use mouse.motion of the event returned by context.convert_event instead.",
DeprecationWarning,
stacklevel=2,
)
self.__tile_motion = Point(*xy)
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> MouseMotion:
motion = sdl_event.motion
pixel = motion.x, motion.y
pixel_motion = motion.xrel, motion.yrel
subtile = _pixel_to_tile(*pixel)
if subtile is None:
self = cls(pixel, pixel_motion, None, None, motion.state)
else:
tile = int(subtile[0]), int(subtile[1])
prev_pixel = pixel[0] - pixel_motion[0], pixel[1] - pixel_motion[1]
prev_subtile = _pixel_to_tile(*prev_pixel) or (0, 0)
prev_tile = int(prev_subtile[0]), int(prev_subtile[1])
tile_motion = tile[0] - prev_tile[0], tile[1] - prev_tile[1]
self = cls(pixel, pixel_motion, tile, tile_motion, motion.state)
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(position={tuple(self.position)!r}, motion={tuple(self.motion)!r}, tile={tuple(self.tile)!r}, tile_motion={tuple(self.tile_motion)!r}, state={MouseButtonMask(self.state)!r})"
def __str__(self) -> str:
return ("<%s, motion=(x=%i, y=%i), tile_motion=(x=%i, y=%i)>") % (
super().__str__().strip("<>"),
*self.motion,
*self.tile_motion,
)
class MouseButtonEvent(MouseState):
"""Mouse button event.
Attributes:
type (str): Will be "MOUSEBUTTONDOWN" or "MOUSEBUTTONUP",
depending on the event.
position (Point): The pixel coordinates of the mouse.
tile (Point): The integer tile coordinates of the mouse on the screen.
button (int): Which mouse button.
This will be one of the following names:
* tcod.event.BUTTON_LEFT
* tcod.event.BUTTON_MIDDLE
* tcod.event.BUTTON_RIGHT
* tcod.event.BUTTON_X1
* tcod.event.BUTTON_X2
"""
def __init__(
self,
pixel: tuple[int, int] = (0, 0),
tile: tuple[int, int] | None = (0, 0),
button: int = 0,
) -> None:
super().__init__(pixel, tile, button)
@property
def button(self) -> int:
return self.state
@button.setter
def button(self, value: int) -> None:
self.state = value
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> Any:
button = sdl_event.button
pixel = button.x, button.y
subtile = _pixel_to_tile(*pixel)
if subtile is None:
tile: tuple[int, int] | None = None
else:
tile = int(subtile[0]), int(subtile[1])
self = cls(pixel, tile, button.button)
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(position={tuple(self.position)!r}, tile={tuple(self.tile)!r}, button={MouseButton(self.button)!r})"
def __str__(self) -> str:
return "<type=%r, position=(x=%i, y=%i), tile=(x=%i, y=%i), button=%r)" % (
self.type,
*self.position,
*self.tile,
MouseButton(self.button),
)
class MouseButtonDown(MouseButtonEvent):
"""Same as MouseButtonEvent but with ``type="MouseButtonDown"``."""
class MouseButtonUp(MouseButtonEvent):
"""Same as MouseButtonEvent but with ``type="MouseButtonUp"``."""
class MouseWheel(Event):
"""Mouse wheel event.
Attributes:
type (str): Always "MOUSEWHEEL".
x (int): Horizontal scrolling. A positive value means scrolling right.
y (int): Vertical scrolling. A positive value means scrolling away from
the user.
flipped (bool): If True then the values of `x` and `y` are the opposite
of their usual values. This depends on the settings of
the Operating System.
"""
def __init__(self, x: int, y: int, flipped: bool = False) -> None:
super().__init__()
self.x = x
self.y = y
self.flipped = flipped
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> MouseWheel:
wheel = sdl_event.wheel
self = cls(wheel.x, wheel.y, bool(wheel.direction))
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return "tcod.event.%s(x=%i, y=%i%s)" % (
self.__class__.__name__,
self.x,
self.y,
", flipped=True" if self.flipped else "",
)
def __str__(self) -> str:
return "<%s, x=%i, y=%i, flipped=%r)" % (
super().__str__().strip("<>"),
self.x,
self.y,
self.flipped,
)
class TextInput(Event):
"""SDL text input event.
Attributes:
type (str): Always "TEXTINPUT".
text (str): A Unicode string with the input.
"""
def __init__(self, text: str) -> None:
super().__init__()
self.text = text
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> TextInput:
self = cls(ffi.string(sdl_event.text.text, 32).decode("utf8"))
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(text={self.text!r})"
def __str__(self) -> str:
return "<{}, text={!r})".format(super().__str__().strip("<>"), self.text)
class WindowEvent(Event):
"""A window event."""
type: Final[ # type: ignore[misc] # Narrowing final type.
Literal[
"WindowShown",
"WindowHidden",
"WindowExposed",
"WindowMoved",
"WindowResized",
"WindowSizeChanged",
"WindowMinimized",
"WindowMaximized",
"WindowRestored",
"WindowEnter",
"WindowLeave",
"WindowFocusGained",
"WindowFocusLost",
"WindowClose",
"WindowTakeFocus",
"WindowHitTest",
]
]
"""The current window event. This can be one of various options."""
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> WindowEvent | Undefined:
if sdl_event.window.event not in cls.__WINDOW_TYPES:
return Undefined.from_sdl_event(sdl_event)
event_type: Final = cls.__WINDOW_TYPES[sdl_event.window.event]
self: WindowEvent
if sdl_event.window.event == lib.SDL_WINDOWEVENT_MOVED:
self = WindowMoved(sdl_event.window.data1, sdl_event.window.data2)
elif sdl_event.window.event in (
lib.SDL_WINDOWEVENT_RESIZED,
lib.SDL_WINDOWEVENT_SIZE_CHANGED,
):
self = WindowResized(event_type, sdl_event.window.data1, sdl_event.window.data2)
else:
self = cls(event_type)
self.sdl_event = sdl_event
return self
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(type={self.type!r})"
__WINDOW_TYPES = {
lib.SDL_WINDOWEVENT_SHOWN: "WindowShown",
lib.SDL_WINDOWEVENT_HIDDEN: "WindowHidden",
lib.SDL_WINDOWEVENT_EXPOSED: "WindowExposed",
lib.SDL_WINDOWEVENT_MOVED: "WindowMoved",
lib.SDL_WINDOWEVENT_RESIZED: "WindowResized",
lib.SDL_WINDOWEVENT_SIZE_CHANGED: "WindowSizeChanged",
lib.SDL_WINDOWEVENT_MINIMIZED: "WindowMinimized",
lib.SDL_WINDOWEVENT_MAXIMIZED: "WindowMaximized",
lib.SDL_WINDOWEVENT_RESTORED: "WindowRestored",
lib.SDL_WINDOWEVENT_ENTER: "WindowEnter",
lib.SDL_WINDOWEVENT_LEAVE: "WindowLeave",
lib.SDL_WINDOWEVENT_FOCUS_GAINED: "WindowFocusGained",
lib.SDL_WINDOWEVENT_FOCUS_LOST: "WindowFocusLost",
lib.SDL_WINDOWEVENT_CLOSE: "WindowClose",
lib.SDL_WINDOWEVENT_TAKE_FOCUS: "WindowTakeFocus",
lib.SDL_WINDOWEVENT_HIT_TEST: "WindowHitTest",
}
class WindowMoved(WindowEvent):
"""Window moved event.
Attributes:
x (int): Movement on the x-axis.
y (int): Movement on the y-axis.
"""
type: Final[Literal["WINDOWMOVED"]] # type: ignore[assignment,misc]
"""Always "WINDOWMOVED"."""
def __init__(self, x: int, y: int) -> None:
super().__init__(None)
self.x = x
self.y = y
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(type={self.type!r}, x={self.x!r}, y={self.y!r})"
def __str__(self) -> str:
return "<{}, x={!r}, y={!r})".format(
super().__str__().strip("<>"),
self.x,
self.y,
)
class WindowResized(WindowEvent):
"""Window resized event.
Attributes:
width (int): The current width of the window.
height (int): The current height of the window.
"""
type: Final[Literal["WindowResized", "WindowSizeChanged"]] # type: ignore[misc]
"""WindowResized" or "WindowSizeChanged"""
def __init__(self, type: str, width: int, height: int) -> None:
super().__init__(type)
self.width = width
self.height = height
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}(type={self.type!r}, width={self.width!r}, height={self.height!r})"
def __str__(self) -> str:
return "<{}, width={!r}, height={!r})".format(
super().__str__().strip("<>"),
self.width,
self.height,
)
class JoystickEvent(Event):
"""A base class for joystick events.
.. versionadded:: 13.8
"""
def __init__(self, type: str, which: int) -> None:
super().__init__(type)
self.which = which
"""The ID of the joystick this event is for."""
@property
def joystick(self) -> tcod.sdl.joystick.Joystick:
if self.type == "JOYDEVICEADDED":
return tcod.sdl.joystick.Joystick._open(self.which)
return tcod.sdl.joystick.Joystick._from_instance_id(self.which)
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}" f"(type={self.type!r}, which={self.which})"
def __str__(self) -> str:
prefix = super().__str__().strip("<>")
return f"<{prefix}, which={self.which}>"
class JoystickAxis(JoystickEvent):
"""When a joystick axis changes in value.
.. versionadded:: 13.8
.. seealso::
:any:`tcod.sdl.joystick`
"""
which: int
"""The ID of the joystick this event is for."""
def __init__(self, type: str, which: int, axis: int, value: int) -> None:
super().__init__(type, which)
self.axis = axis
"""The index of the changed axis."""
self.value = value
"""The raw value of the axis in the range -32768 to 32767."""
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> JoystickAxis:
return cls("JOYAXISMOTION", sdl_event.jaxis.which, sdl_event.jaxis.axis, sdl_event.jaxis.value)
def __repr__(self) -> str:
return (
f"tcod.event.{self.__class__.__name__}"
f"(type={self.type!r}, which={self.which}, axis={self.axis}, value={self.value})"
)
def __str__(self) -> str:
prefix = super().__str__().strip("<>")
return f"<{prefix}, axis={self.axis}, value={self.value}>"
class JoystickBall(JoystickEvent):
"""When a joystick ball is moved.
.. versionadded:: 13.8
.. seealso::
:any:`tcod.sdl.joystick`
"""
which: int
"""The ID of the joystick this event is for."""
def __init__(self, type: str, which: int, ball: int, dx: int, dy: int) -> None:
super().__init__(type, which)
self.ball = ball
"""The index of the moved ball."""
self.dx = dx
"""The X motion of the ball."""
self.dy = dy
"""The Y motion of the ball."""
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> JoystickBall:
return cls(
"JOYBALLMOTION", sdl_event.jball.which, sdl_event.jball.ball, sdl_event.jball.xrel, sdl_event.jball.yrel
)
def __repr__(self) -> str:
return (
f"tcod.event.{self.__class__.__name__}"
f"(type={self.type!r}, which={self.which}, ball={self.ball}, dx={self.dx}, dy={self.dy})"
)
def __str__(self) -> str:
prefix = super().__str__().strip("<>")
return f"<{prefix}, ball={self.ball}, dx={self.dx}, dy={self.dy}>"
class JoystickHat(JoystickEvent):
"""When a joystick hat changes direction.
.. versionadded:: 13.8
.. seealso::
:any:`tcod.sdl.joystick`
"""
which: int
"""The ID of the joystick this event is for."""
def __init__(self, type: str, which: int, x: Literal[-1, 0, 1], y: Literal[-1, 0, 1]) -> None:
super().__init__(type, which)
self.x = x
"""The new X direction of the hat."""
self.y = y
"""The new Y direction of the hat."""
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> JoystickHat:
return cls("JOYHATMOTION", sdl_event.jhat.which, *_HAT_DIRECTIONS[sdl_event.jhat.hat])
def __repr__(self) -> str:
return (
f"tcod.event.{self.__class__.__name__}" f"(type={self.type!r}, which={self.which}, x={self.x}, y={self.y})"
)
def __str__(self) -> str:
prefix = super().__str__().strip("<>")
return f"<{prefix}, x={self.x}, y={self.y}>"
class JoystickButton(JoystickEvent):
"""When a joystick button is pressed or released.
.. versionadded:: 13.8
Example::
for event in tcod.event.get():
match event:
case JoystickButton(which=which, button=button, pressed=True):
print(f"Pressed {button=} on controller {which}.")
case JoystickButton(which=which, button=button, pressed=False):
print(f"Released {button=} on controller {which}.")
"""
which: int
"""The ID of the joystick this event is for."""
def __init__(self, type: str, which: int, button: int) -> None:
super().__init__(type, which)
self.button = button
"""The index of the button this event is for."""
@property
def pressed(self) -> bool:
"""True if the joystick button has been pressed, False when the button was released."""
return self.type == "JOYBUTTONDOWN"
@classmethod
def from_sdl_event(cls, sdl_event: Any) -> JoystickButton:
type = {lib.SDL_JOYBUTTONDOWN: "JOYBUTTONDOWN", lib.SDL_JOYBUTTONUP: "JOYBUTTONUP"}[sdl_event.type]
return cls(type, sdl_event.jbutton.which, sdl_event.jbutton.button)
def __repr__(self) -> str:
return f"tcod.event.{self.__class__.__name__}" f"(type={self.type!r}, which={self.which}, button={self.button})"
def __str__(self) -> str:
prefix = super().__str__().strip("<>")
return f"<{prefix}, button={self.button}>"
class JoystickDevice(JoystickEvent):
"""An event for when a joystick is added or removed.
.. versionadded:: 13.8
Example::
joysticks: set[tcod.sdl.joystick.Joystick] = {}
for event in tcod.event.get():
match event: