Skip to content

Commit 911bf8c

Browse files
add in-app mouse cursor
1 parent 403047b commit 911bf8c

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

examples/_uix/inapp_mouse_cursor.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
'''
2+
In-app mouse cursor.
3+
'''
4+
5+
__all__ = ('inapp_mouse_cursor', )
6+
7+
from functools import partial
8+
from typing import Unpack
9+
10+
import pygame
11+
from pygame.math import Vector2
12+
from pygame import Color
13+
import pygame.constants as C
14+
import asyncpygame as apg
15+
16+
17+
def generate_cursor_image(size: int, color) -> pygame.Surface:
18+
cursor_img = pygame.Surface((size, size))
19+
bgcolor = Color("black")
20+
color = Color(color)
21+
if color == bgcolor:
22+
bgcolor = Color("white")
23+
cursor_img.fill(bgcolor)
24+
hs = size // 2
25+
v = size // 10
26+
points = (
27+
(0, 0),
28+
(hs, size),
29+
(hs + v, hs + v),
30+
(size, hs),
31+
)
32+
pygame.draw.polygon(cursor_img, color, points)
33+
cursor_img = cursor_img.convert()
34+
cursor_img.set_colorkey(bgcolor)
35+
return cursor_img
36+
37+
38+
async def inapp_mouse_cursor(*, color="white", size=60, initial_pos=(-0xFFFF, -0xFFFF), priority, **kwargs: Unpack[apg.CommonParams]):
39+
img = generate_cursor_image(size, color)
40+
pos = Vector2(initial_pos)
41+
42+
with (
43+
kwargs["executor"].register(partial(kwargs["draw_target"].blit, img, pos), priority),
44+
kwargs["sdlevent"].subscribe((C.MOUSEMOTION, ), lambda e, update=pos.update: update(e.pos), priority),
45+
):
46+
await apg.sleep_forever()

examples/_uix_inapp_mouse_cursor.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
from typing import Unpack
2+
from functools import partial
3+
4+
import pygame
5+
from pygame.colordict import THECOLORS
6+
import asyncpygame as apg
7+
from _uix.inapp_mouse_cursor import inapp_mouse_cursor
8+
9+
10+
async def main(**kwargs: Unpack[apg.CommonParams]):
11+
pygame.init()
12+
pygame.mouse.set_visible(False)
13+
pygame.display.set_caption("In-app mouse cursor")
14+
kwargs["draw_target"] = screen = pygame.display.set_mode((600, 600))
15+
16+
r = kwargs["executor"].register
17+
r(partial(screen.fill, THECOLORS["black"]), priority=0)
18+
r(pygame.display.flip, priority=0xFFFFFF00)
19+
20+
await inapp_mouse_cursor(priority=0x100, **kwargs)
21+
22+
23+
if __name__ == "__main__":
24+
apg.run(main)

0 commit comments

Comments
 (0)