Difficult-Rocket/libs/pyglet/window/mouse.py

101 lines
2.3 KiB
Python
Raw Permalink Normal View History

2021-04-16 23:21:06 +08:00
"""Mouse constants and utilities for pyglet.window.
"""
2021-12-26 23:06:03 +08:00
class MouseStateHandler:
2021-04-16 23:21:06 +08:00
"""Simple handler that tracks the state of buttons from the mouse. If a
button is pressed then this handler holds a True value for it.
2022-10-11 21:53:55 +08:00
If the window loses focus, all buttons will be reset to False in order
to avoid a "sticky" button state.
2021-04-16 23:21:06 +08:00
For example::
>>> win = window.Window()
>>> mousebuttons = mouse.MouseStateHandler()
>>> win.push_handlers(mousebuttons)
# Hold down the "left" button...
>>> mousebuttons[mouse.LEFT]
True
>>> mousebuttons[mouse.RIGHT]
False
"""
def __init__(self):
2021-12-26 23:06:03 +08:00
self.data = {
"x": 0,
"y": 0,
}
2021-04-16 23:21:06 +08:00
def on_mouse_press(self, x, y, button, modifiers):
2021-12-26 23:06:03 +08:00
self.data[button] = True
2021-04-16 23:21:06 +08:00
def on_mouse_release(self, x, y, button, modifiers):
2021-12-26 23:06:03 +08:00
self.data[button] = False
2022-10-11 21:53:55 +08:00
def on_deactivate(self):
self.data.clear()
def on_mouse_motion(self, x, y, dx, dy):
2021-12-26 23:06:03 +08:00
self.data["x"] = x
self.data["y"] = y
def on_mouse_drag(self, x, y, dx, dy, buttons, modifiers):
2021-12-26 23:06:03 +08:00
self.data["x"] = x
self.data["y"] = y
2021-04-16 23:21:06 +08:00
def __getitem__(self, key):
2021-12-26 23:06:03 +08:00
return self.data.get(key, False)
2021-04-16 23:21:06 +08:00
def buttons_string(buttons):
"""Return a string describing a set of active mouse buttons.
Example::
>>> buttons_string(LEFT | RIGHT)
'LEFT|RIGHT'
:Parameters:
`buttons` : int
Bitwise combination of mouse button constants.
:rtype: str
"""
button_names = []
if buttons & LEFT:
2022-10-11 21:53:55 +08:00
button_names.append("LEFT")
2021-04-16 23:21:06 +08:00
if buttons & MIDDLE:
2022-10-11 21:53:55 +08:00
button_names.append("MIDDLE")
2021-04-16 23:21:06 +08:00
if buttons & RIGHT:
2022-10-11 21:53:55 +08:00
button_names.append("RIGHT")
if buttons & MOUSE4:
button_names.append("MOUSE4")
if buttons & MOUSE5:
button_names.append("MOUSE5")
return "|".join(button_names)
2021-04-16 23:21:06 +08:00
#: Constant for the left mouse button.
#:
#: :meta hide-value:
2021-04-16 23:21:06 +08:00
LEFT = 1 << 0
#: Constant for the middle mouse button.
#:
#: :meta hide-value:
2021-04-16 23:21:06 +08:00
MIDDLE = 1 << 1
#: Constant for the right mouse button.
#:
#: :meta hide-value:
2021-04-16 23:21:06 +08:00
RIGHT = 1 << 2
#: Constant for the mouse4 button.
#:
#: :meta hide-value:
2022-10-11 21:53:55 +08:00
MOUSE4 = 1 << 3
#: Constant for the mouse5 button.
#:
#: :meta hide-value:
2022-10-11 21:53:55 +08:00
MOUSE5 = 1 << 4