diff --git a/buildconfig/stubs/pygame/display.pyi b/buildconfig/stubs/pygame/display.pyi index 43e1ec8c05..5d77738cb3 100644 --- a/buildconfig/stubs/pygame/display.pyi +++ b/buildconfig/stubs/pygame/display.pyi @@ -1,6 +1,59 @@ +"""Pygame module to control the display window and screen. + +This module offers control over the pygame display. Pygame has a single display +Surface that is either contained in a window or runs full screen. Once you +create the display you treat it as a regular Surface. Changes are not +immediately visible onscreen; you must choose one of the two flipping functions +to update the actual display. + +The origin of the display, where x = 0 and y = 0, is the top left of the +screen. Both axes increase positively towards the bottom right of the screen. + +The pygame display can actually be initialized in one of several modes. By +default, the display is a basic software driven framebuffer. You can request +special modules like automatic scaling or OpenGL support. These are +controlled by flags passed to ``pygame.display.set_mode()``. + +Pygame can only have a single display active at any time. Creating a new one +with ``pygame.display.set_mode()`` will close the previous display. To detect +the number and size of attached screens, you can use +``pygame.display.get_desktop_sizes`` and then select appropriate window size +and display index to pass to ``pygame.display.set_mode()``. + +For backward compatibility ``pygame.display`` allows precise control over +the pixel format or display resolutions. This used to be necessary with old +graphics cards and CRT screens, but is usually not needed any more. Use the +functions ``pygame.display.mode_ok()``, ``pygame.display.list_modes()``, and +``pygame.display.Info()`` to query detailed information about the display. + +Once the display Surface is created, the functions from this module affect the +single existing display. The Surface becomes invalid if the module is +uninitialized. If a new display mode is set, the existing Surface will +automatically switch to operate on the new display. + +When the display mode is set, several events are placed on the pygame event +queue. ``pygame.QUIT`` is sent when the user has requested the program to +shut down. The window will receive ``pygame.ACTIVEEVENT`` events as the display +gains and loses input focus. If the display is set with the +``pygame.RESIZABLE`` flag, ``pygame.VIDEORESIZE`` events will be sent when the +user adjusts the window dimensions. Hardware displays that draw direct to the +screen will get ``pygame.VIDEOEXPOSE`` events when portions of the window must +be redrawn. + +A new windowevent API was introduced in pygame 2.0.1. Check event module docs +for more information on that + +Some display environments have an option for automatically stretching all +windows. When this option is enabled, this automatic stretching distorts the +appearance of the pygame window. In the pygame examples directory, there is +example code (prevent_display_stretching.py) which shows how to disable this +automatic stretching of the pygame display on Microsoft Windows (Vista or newer +required). +""" + from collections.abc import Iterable from typing import Optional, Union, overload, Literal -from typing_extensions import deprecated # added in 3.13 +from typing_extensions import deprecated # added in 3.13 from pygame.constants import FULLSCREEN from pygame.surface import Surface @@ -34,18 +87,205 @@ class _VidInfo: current_w: int pixel_format: str -def init() -> None: ... -def quit() -> None: ... -def get_init() -> bool: ... +def init() -> None: + """Initialize the display module. + + Initializes the pygame display module. The display module cannot do anything + until it is initialized. This is usually handled for you automatically when + you call the higher level ``pygame.init()``. + + Pygame will select from one of several internal display backends when it is + initialized. The display mode will be chosen depending on the platform and + permissions of current user. Before the display module is initialized the + environment variable ``SDL_VIDEODRIVER`` can be set to control which backend + is used. The systems with multiple choices are listed here. + + :: + + Windows : windib, directx + Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib, wayland + + :note: On wayland desktops, pygame-ce may choose to use the X11 video driver to run on Xwayland. + This behaviour is determined by the SDL library and might change in the future, so it's suggested + to account for this and not rely on the default behavior. The Wayland video driver can be forced + by setting the ``SDL_VIDEODRIVER`` environment variable to ``"wayland"`` + + On some platforms it is possible to embed the pygame display into an already + existing window. To do this, the environment variable ``SDL_WINDOWID`` must + be set to a string containing the window id or handle. The environment + variable is checked when the pygame display is initialized. Be aware that + there can be many strange side effects when running in an embedded display. + + It is harmless to call this more than once, repeated calls have no effect. + + .. versionchanged:: 2.5.0 the manylinux wheels distributed by us now support the ``wayland`` videodriver + + """ + +def quit() -> None: + """Uninitialize the display module. + + This will shut down the entire display module. This means any active + displays will be closed. This will also be handled automatically when the + program exits. + + It is harmless to call this more than once, repeated calls have no effect. + """ + +def get_init() -> bool: + """Returns True if the display module has been initialized. + + Returns True if the :mod:`pygame.display` module is currently initialized. + """ + def set_mode( size: Point = (0, 0), flags: int = 0, depth: int = 0, display: int = 0, vsync: int = 0, -) -> Surface: ... -def get_surface() -> Optional[Surface]: ... -def flip() -> None: ... +) -> Surface: + """Initialize a window or screen for display. + + This will create a window or display output and return a display Surface. + The arguments passed in are requests for a display type. The actual created + display will be the best possible match supported by the system. + + Note that calling this function implicitly initializes ``pygame.display``, if + it was not initialized before. + + The size argument is a pair of numbers representing the width and + height. The flags argument is a collection of additional options. The depth + argument represents the number of bits to use for color. + + The Surface that gets returned can be drawn to like a regular Surface but + changes will eventually be seen on the monitor. + + If no size is passed or is set to ``(0, 0)``, the created Surface will have + the same size as the current screen resolution. If only the width or height + are set to ``0``, the Surface will have the same width or height as the + screen resolution. + + Since pygame 2, the depth argument is ignored, in favour of the best + and fastest one. It also raises a deprecation warning since pygame-ce + 2.4.0 if the passed in depth is not 0 or the one pygame selects. + + When requesting fullscreen display modes, sometimes an exact match for the + requested size cannot be made. In these situations pygame will select + the closest compatible match. The returned surface will still always match + the requested size. + + On high resolution displays(4k, 1080p) and tiny graphics games (640x480) + show up very small so that they are unplayable. SCALED scales up the window + for you. The game thinks it's a 640x480 window, but really it can be bigger. + Mouse events are scaled for you, so your game doesn't need to do it. Note + that SCALED is considered an experimental API and may change in future + releases. + + The flags argument controls which type of display you want. There are + several to choose from, and you can even combine multiple types using the + bitwise or operator, (the pipe "|" character). Here are the display + flags you will want to choose from: + + :: + + pygame.FULLSCREEN create a fullscreen display + pygame.DOUBLEBUF only applicable with OPENGL + pygame.HWSURFACE (obsolete in pygame 2) hardware accelerated, only in FULLSCREEN + pygame.OPENGL create an OpenGL-renderable display + pygame.RESIZABLE display window should be sizeable + pygame.NOFRAME display window will have no border or controls + pygame.SCALED resolution depends on desktop size and scale graphics + pygame.SHOWN window is opened in visible mode (default) + pygame.HIDDEN window is opened in hidden mode + + + .. versionaddedold:: 2.0.0 ``SCALED``, ``SHOWN`` and ``HIDDEN`` + + .. versionaddedold:: 2.0.0 ``vsync`` parameter + + By setting the ``vsync`` parameter to ``1``, it is possible to get a display + with vertical sync at a constant frame rate determined by the monitor and + graphics drivers. Subsequent calls to :func:`pygame.display.flip()` or + :func:`pygame.display.update()` will block (i.e. *wait*) until the screen + has refreshed, in order to prevent "screen tearing" + . + + Be careful when using this feature together with ``pygame.time.Clock`` or + :func:`pygame.time.delay()`, as multiple forms of waiting and frame rate + limiting may interact to cause skipped frames. + + The request only works when graphics acceleration is available on the + system. The exact behaviour depends on the hardware and driver + configuration. When ``vsync`` is requested, but unavailable, + ``set_mode()`` may raise an exception. + + Setting the ``vsync`` parameter to ``-1`` in conjunction with ``OPENGL`` + will request the OpenGL-specific feature "adaptive vsync" . + + Here is an example usage of a call + to ``set_mode()`` that may give you a display with vsync: + + :: + + flags = pygame.OPENGL | pygame.FULLSCREEN + try: + window_surface = pygame.display.set_mode((1920, 1080), flags, vsync=1) + vsync_success=True + except pygame.error: + window_surface = pygame.display.set_mode((1920, 1080), flags) + vsync_success=False + + .. versionaddedold:: 2.0.0 ``vsync`` parameter + + .. versionchanged:: 2.2.0 passing ``vsync`` can raise an exception + + .. versionchanged:: 2.2.0 explicit request for "adaptive vsync" + + .. versionchanged:: 2.2.0 ``vsync=1`` does not require ``SCALED`` or ``OPENGL`` + + .. deprecated:: 2.4.0 The depth argument is ignored, and will be set to the optimal value + + .. versionchanged:: 2.5.0 No longer emits warning when running on xwayland, see :func:`pygame.display.init` for details on running on wayland directly + + Basic example: + + :: + + # Open a window on the screen + screen_width=700 + screen_height=400 + screen=pygame.display.set_mode([screen_width, screen_height]) + + The display index ``0`` means the default display is used. If no display + index argument is provided, the default display can be overridden with an + environment variable. + + + .. versionchangedold:: 1.9.5 ``display`` argument added + + .. versionchanged:: 2.1.3 + pygame now ensures that subsequent calls to this function clears the + window to black. On older versions, this was an implementation detail + on the major platforms this function was tested with. + """ + +def get_surface() -> Optional[Surface]: + """Get a reference to the currently set display surface. + + Return a reference to the currently set display Surface. If no display mode + has been set this will return None. + """ + +def flip() -> None: + """Update the full display Surface to the screen. + + This will update the contents of the entire display. + + When using an ``pygame.OPENGL`` display mode this will perform a gl buffer + swap. + """ + @overload def update() -> None: ... @overload @@ -55,47 +295,522 @@ def update( @overload def update(x: float, y: float, w: float, h: float, /) -> None: ... @overload -def update(xy: Point, wh: Point, /) -> None: ... -def get_driver() -> str: ... -def Info() -> _VidInfo: ... -def get_wm_info() -> dict[str, int]: ... +def update(xy: Point, wh: Point, /) -> None: + """Update all, or a portion, of the display. For non-OpenGL displays. + + For non OpenGL display Surfaces, this function is very similar to + ``pygame.display.flip()`` with an optional parameter that allows only + portions of the display surface to be updated, instead of the entire area. + If no argument is passed it updates the entire Surface area like + ``pygame.display.flip()``. + + .. note:: calling ``display.update(None)`` means no part of the window is + updated. Whereas ``display.update()`` means the whole window is + updated. + + You can pass the function a single rectangle, or an iterable of rectangles. + Generally you do not want to pass an iterable of rectangles as there is a + performance cost per rectangle passed to the function. On modern hardware, + after a very small number of rectangles passed in, the per-rectangle cost + will exceed the saving of updating less pixels. In most applications it is + simply more efficient to update the entire display surface at once, it also + means you do not need to keep track of a list of rectangles for each call + to update. + + If passing an iterable of rectangles it is safe to include None + values in the list, which will be skipped. + + This call cannot be used on ``pygame.OPENGL`` displays and will generate an + exception. + + .. versionchanged:: 2.5.1 Added support for passing an iterable, previously only sequence was allowed + """ + +def get_driver() -> str: + """Get the name of the pygame display backend. + + Pygame chooses one of many available display backends when it is + initialized. This returns the internal name used for the display backend. + This can be used to provide limited information about what display + capabilities might be accelerated. See the ``SDL_VIDEODRIVER`` flags in + ``pygame.display.set_mode()`` to see some of the common options. + """ + +def Info() -> _VidInfo: + """Create a video display information object. + + Creates a simple object containing several attributes to describe the + current graphics environment. If this is called before + ``pygame.display.set_mode()`` some platforms can provide information about + the default display mode. This can also be called after setting the display + mode to verify specific display options were satisfied. The VidInfo object + has several attributes: + + .. code-block:: text + + hw: 1 if the display is hardware accelerated + wm: 1 if windowed display modes can be used + video_mem: The megabytes of video memory on the display. + This is 0 if unknown + bitsize: Number of bits used to store each pixel + bytesize: Number of bytes used to store each pixel + masks: Four values used to pack RGBA values into pixels + shifts: Four values used to pack RGBA values into pixels + losses: Four values used to pack RGBA values into pixels + blit_hw: 1 if hardware Surface blitting is accelerated + blit_hw_CC: 1 if hardware Surface colorkey blitting is accelerated + blit_hw_A: 1 if hardware Surface pixel alpha blitting is + accelerated + blit_sw: 1 if software Surface blitting is accelerated + blit_sw_CC: 1 if software Surface colorkey blitting is + accelerated + blit_sw_A: 1 if software Surface pixel alpha blitting is + accelerated + current_h, current_w: Height and width of the current video + mode, or of the desktop mode if called before + the display.set_mode is called. They are -1 on error. + pixel_format: The pixel format of the display Surface as a string. + E.g PIXELFORMAT_RGB888. + + .. versionchanged:: 2.4.0 ``pixel_format`` attribute added. + """ + +def get_wm_info() -> dict[str, int]: + """Get information about the current windowing system. + + Creates a dictionary filled with string keys. The strings and values are + arbitrarily created by the system. Some systems may have no information and + an empty dictionary will be returned. Most platforms will return a "window" + key with the value set to the system id for the current display. + + .. versionaddedold:: 1.7.1 + """ + +def get_desktop_sizes() -> list[tuple[int, int]]: + """Get sizes of active desktops. + + This function returns the sizes of the currently configured + virtual desktops as a list of (x, y) tuples of integers. + + The length of the list is not the same as the number of attached monitors, + as a desktop can be mirrored across multiple monitors. The desktop sizes + do not indicate the maximum monitor resolutions supported by the hardware, + but the desktop size configured in the operating system. + + In order to fit windows into the desktop as it is currently configured, and + to respect the resolution configured by the operating system in fullscreen + mode, this function *should* be used to replace many use cases of + ``pygame.display.list_modes()`` whenever applicable. + + .. versionaddedold:: 2.0.0 + """ + def list_modes( depth: int = 0, flags: int = FULLSCREEN, display: int = 0, -) -> list[tuple[int, int]]: ... +) -> list[tuple[int, int]]: + """Get list of available fullscreen modes. + + This function returns a list of possible sizes for a specified color + depth. The return value will be an empty list if no display modes are + available with the given arguments. A return value of ``-1`` means that + any requested size should work (this is likely the case for windowed + modes). Mode sizes are sorted from biggest to smallest. + + If depth is ``0``, the current/best color depth for the display is used. + The flags defaults to ``pygame.FULLSCREEN``, but you may need to add + additional flags for specific fullscreen modes. + + The display index ``0`` means the default display is used. + + Since pygame 2.0, ``pygame.display.get_desktop_sizes()`` has taken over + some use cases from ``pygame.display.list_modes()``: + + To find a suitable size for non-fullscreen windows, it is preferable to + use ``pygame.display.get_desktop_sizes()`` to get the size of the *current* + desktop, and to then choose a smaller window size. This way, the window is + guaranteed to fit, even when the monitor is configured to a lower resolution + than the maximum supported by the hardware. + + To avoid changing the physical monitor resolution, it is also preferable to + use ``pygame.display.get_desktop_sizes()`` to determine the fullscreen + resolution. Developers are strongly advised to default to the current + physical monitor resolution unless the user explicitly requests a different + one (e.g. in an options menu or configuration file). + + .. versionchangedold:: 1.9.5 ``display`` argument added + """ + def mode_ok( size: IntPoint, flags: int = 0, depth: int = 0, display: int = 0, -) -> int: ... -def gl_get_attribute(flag: int, /) -> int: ... -def gl_set_attribute(flag: int, value: int, /) -> None: ... -def get_active() -> bool: ... -def iconify() -> bool: ... -def toggle_fullscreen() -> int: ... +) -> int: + """Pick the best color depth for a display mode. + + This function uses the same arguments as ``pygame.display.set_mode()``. It + is used to determine if a requested display mode is available. It will + return ``0`` if the display mode cannot be set. Otherwise it will return a + pixel depth that best matches the display asked for. + + Usually the depth argument is not passed, but some platforms can support + multiple display depths. If passed it will hint to which depth is a better + match. + + The function will return ``0`` if the passed display flags cannot be set. + + The display index ``0`` means the default display is used. + + .. versionchangedold:: 1.9.5 ``display`` argument added + """ + +def gl_get_attribute(flag: int, /) -> int: + """Get the value for an OpenGL flag for the current display. + + After calling ``pygame.display.set_mode()`` with the ``pygame.OPENGL`` flag, + it is a good idea to check the value of any requested OpenGL attributes. See + ``pygame.display.gl_set_attribute()`` for a list of valid flags. + """ + +def gl_set_attribute(flag: int, value: int, /) -> None: + """Request an OpenGL display attribute for the display mode. + + When calling ``pygame.display.set_mode()`` with the ``pygame.OPENGL`` flag, + Pygame automatically handles setting the OpenGL attributes like color and + double-buffering. OpenGL offers several other attributes you may want control + over. Pass one of these attributes as the flag, and its appropriate value. + This must be called before ``pygame.display.set_mode()``. + + Many settings are the requested minimum. Creating a window with an OpenGL context + will fail if OpenGL cannot provide the requested attribute, but it may for example + give you a stencil buffer even if you request none, or it may give you a larger + one than requested. + + The ``OPENGL`` flags are + + :: + + GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, + GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, + GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO + + :const:`GL_MULTISAMPLEBUFFERS` + + Whether to enable multisampling anti-aliasing. + Defaults to 0 (disabled). + Set ``GL_MULTISAMPLESAMPLES`` to a value + above 0 to control the amount of anti-aliasing. + A typical value is 2 or 3. + + :const:`GL_STENCIL_SIZE` + + Minimum bit size of the stencil buffer. Defaults to 0. + + :const:`GL_DEPTH_SIZE` + + Minimum bit size of the depth buffer. Defaults to 16. + + :const:`GL_STEREO` + + 1 enables stereo 3D. Defaults to 0. + + :const:`GL_BUFFER_SIZE` + + Minimum bit size of the frame buffer. Defaults to 0. + + .. versionaddedold:: 2.0.0 Additional attributes: + + :: + + GL_ACCELERATED_VISUAL, + GL_CONTEXT_MAJOR_VERSION, GL_CONTEXT_MINOR_VERSION, + GL_CONTEXT_FLAGS, GL_CONTEXT_PROFILE_MASK, + GL_SHARE_WITH_CURRENT_CONTEXT, + GL_CONTEXT_RELEASE_BEHAVIOR, + GL_FRAMEBUFFER_SRGB_CAPABLE + + :const:`GL_CONTEXT_PROFILE_MASK` + + Sets the OpenGL profile to one of these values: + + :: + + GL_CONTEXT_PROFILE_CORE disable deprecated features + GL_CONTEXT_PROFILE_COMPATIBILITY allow deprecated features + GL_CONTEXT_PROFILE_ES allow only the ES feature + subset of OpenGL + + :const:`GL_ACCELERATED_VISUAL` + + Set to 1 to require hardware acceleration, or 0 to force software render. + By default, both are allowed. + """ + +def get_active() -> bool: + """Returns True when the display is active on the screen. + + Returns True when the display Surface is considered actively + renderable on the screen and may be visible to the user. This is + the default state immediately after ``pygame.display.set_mode()``. + This method may return True even if the application is fully hidden + behind another application window. + + This will return False if the display Surface has been iconified or + minimized (either via ``pygame.display.iconify()`` or via an OS + specific method such as the minimize-icon available on most + desktops). + + The method can also return False for other reasons without the + application being explicitly iconified or minimized by the user. A + notable example being if the user has multiple virtual desktops and + the display Surface is not on the active virtual desktop. + + .. note:: This function returning True is unrelated to whether the + application has input focus. Please see + ``pygame.key.get_focused()`` and ``pygame.mouse.get_focused()`` + for APIs related to input focus. + """ + +def iconify() -> bool: + """Iconify the display surface. + + Request the window for the display surface be iconified or hidden. Not all + systems and displays support an iconified display. The function will return + True if successful. + + When the display is iconified ``pygame.display.get_active()`` will return + ``False``. The event queue should receive an ``ACTIVEEVENT`` event when the + window has been iconified. Additionally, the event queue also receives a + ``WINDOWEVENT_MINIMIZED`` event when the window has been iconified on pygame 2. + """ + +def toggle_fullscreen() -> int: + """Switch between fullscreen and windowed displays. + + Switches the display window between windowed and fullscreen modes. + Display driver support is not great when using pygame 1, but with + pygame 2 it is the most reliable method to switch to and from fullscreen. + + Supported display drivers in pygame 1: + + * x11 (Linux/Unix) + * wayland (Linux/Unix) + + Supported display drivers in pygame 2: + + * windows (Windows) + * x11 (Linux/Unix) + * wayland (Linux/Unix) + * cocoa (OSX/Mac) + + .. note:: :func:`toggle_fullscreen` doesn't work on Windows + unless the window size is in :func:`pygame.display.list_modes()` or + the window is created with the flag ``pygame.SCALED``. + See `issue #1221 `_. + """ + @deprecated("since 2.1.4. Removed in SDL3") -def set_gamma(red: float, green: float = ..., blue: float = ..., /) -> int: ... +def set_gamma(red: float, green: float = ..., blue: float = ..., /) -> int: + """Change the hardware gamma ramps. + + DEPRECATED: This functionality will go away in SDL3. + + Set the red, green, and blue gamma values on the display hardware. If the + green and blue arguments are not passed, they will both be the same as red. + Not all systems and hardware support gamma ramps, if the function succeeds + it will return ``True``. + + A gamma value of ``1.0`` creates a linear color table. Lower values will + darken the display and higher values will brighten. + + .. deprecated:: 2.1.4 + """ + @deprecated("since 2.1.4. Removed in SDL3") def set_gamma_ramp( red: SequenceLike[int], green: SequenceLike[int], blue: SequenceLike[int], / -) -> int: ... -def set_icon(surface: Surface, /) -> None: ... -def set_caption(title: str, icontitle: Optional[str] = None, /) -> None: ... -def get_caption() -> tuple[str, str]: ... -def set_palette(palette: SequenceLike[ColorLike], /) -> None: ... -def get_num_displays() -> int: ... -def get_window_size() -> tuple[int, int]: ... -def get_window_position() -> tuple[int, int]:... -def set_window_position(position: Point) -> None:... -def get_allow_screensaver() -> bool: ... -def set_allow_screensaver(value: bool = True) -> None: ... -def get_desktop_sizes() -> list[tuple[int, int]]: ... -def is_fullscreen() -> bool: ... -def is_vsync() -> bool: ... -def get_current_refresh_rate() -> int: ... -def get_desktop_refresh_rates() -> list[int]: ... +) -> int: + """Change the hardware gamma ramps with a custom lookup. + + DEPRECATED: This functionality will go away in SDL3. + + Set the red, green, and blue gamma ramps with an explicit lookup table. Each + argument should be sequence of 256 integers. The integers should range + between ``0`` and ``0xffff``. Not all systems and hardware support gamma + ramps, if the function succeeds it will return ``True``. + + .. deprecated:: 2.1.4 + """ + +def set_icon(surface: Surface, /) -> None: + """Change the system image for the display window. + + Sets the runtime icon the system will use to represent the display window. + All windows default to a simple pygame logo for the window icon. + + Note that calling this function implicitly initializes ``pygame.display``, if + it was not initialized before. + + You can pass any surface, but most systems want a smaller image around + 32x32. The image can have colorkey transparency which will be passed to the + system. + + Some systems do not allow the window icon to change after it has been shown. + This function can be called before ``pygame.display.set_mode()`` to create + the icon before the display mode is set. + """ + +def set_caption(title: str, icontitle: Optional[str] = None, /) -> None: + """Set the current window caption. + + If the display has a window title, this function will change the name on the + window. In pygame 1.x, some systems supported an alternate shorter title to + be used for minimized displays, but in pygame 2 ``icontitle`` does nothing. + """ + +def get_caption() -> tuple[str, str]: + """Get the current window caption. + + Returns the title and icontitle of the display window. In pygame 2.x + these will always be the same value. + """ + +def set_palette(palette: SequenceLike[ColorLike], /) -> None: + """Set the display color palette for indexed displays. + + This will change the video display color palette for 8-bit displays. This + does not change the palette for the actual display Surface, only the palette + that is used to display the Surface. If no palette argument is passed, the + system default palette will be restored. The palette is a sequence of + ``RGB`` triplets. + """ + +def get_num_displays() -> int: + """Return the number of displays. + + Returns the number of available displays. This is always 1 if + :func:`pygame.get_sdl_version()` returns a major version number below 2. + + .. versionaddedold:: 1.9.5 + """ + +def get_window_size() -> tuple[int, int]: + """Return the size of the window or screen. + + Returns the size of the window initialized with :func:`pygame.display.set_mode()`. + This may differ from the size of the display surface if ``SCALED`` is used. + + .. versionaddedold:: 2.0.0 + """ + +def get_window_position() -> tuple[int, int]: + """Return the position of the window or screen. + + Returns the position of the window initialized with :func:`pygame.display.set_mode()`. + The position will change when the user moves the window or when the + position is set manually with :func:`pygame.display.set_window_position()`. + Coordinates could be negative or outside the desktop size bounds. The + position is relative to the topleft of the primary monitor and the y coordinate + ignores the window frame. + """ + +def set_window_position(position: Point) -> None: + """Set the current window position. + + Sets the position of the window initialized with :func:`pygame.display.set_mode()`. + This differs from updating environment variables as this function can be + called after the display has been initialised. The position is expected to + be relative to the topleft of the primary monitor. The y coordinate will + ignore the window frame (y = 0 means the frame is hidden). The user will + still be able to move the window after this call. See also + :func:`pygame.display.get_window_position()`. + """ + +def get_allow_screensaver() -> bool: + """Return whether the screensaver is allowed to run. + + Return whether screensaver is allowed to run whilst the app is running. Default + is ``False``. By default pygame does not allow the screensaver during game + play. + + .. note:: Some platforms do not have a screensaver or support + disabling the screensaver. Please see + :func:`pygame.display.set_allow_screensaver()` for + caveats with screensaver support. + + .. versionaddedold:: 2.0.0 + """ + +def set_allow_screensaver(value: bool = True) -> None: + """Set whether the screensaver may run. + + Change whether screensavers should be allowed whilst the app is running. + The default value of the argument to the function is True. + By default pygame does not allow the screensaver during game play. + + If the screensaver has been disallowed due to this function, it will automatically + be allowed to run when :func:`pygame.quit()` is called. + + It is possible to influence the default value via the environment variable + ``SDL_HINT_VIDEO_ALLOW_SCREENSAVER``, which can be set to either ``0`` (disable) + or ``1`` (enable). + + .. note:: Disabling screensaver is subject to platform support. + When platform support is absent, this function will + silently appear to work even though the screensaver state + is unchanged. The lack of feedback is due to SDL not + providing any supported method for determining whether + it supports changing the screensaver state. + + .. versionaddedold:: 2.0.0 + """ + +def is_fullscreen() -> bool: + """Returns True if the pygame window created by pygame.display.set_mode() is in full-screen mode. + + Edge cases: + If the window is in windowed mode, but maximized, this will return `False`. + If the window is in "borderless fullscreen" mode, this will return `True`. + + .. versionadded:: 2.2.0 + """ + +def is_vsync() -> bool: + """Returns True if vertical synchronisation for pygame.display.flip() and pygame.display.update() is enabled. + + .. versionadded:: 2.2.0 + """ + +def get_current_refresh_rate() -> int: + """Returns the screen refresh rate or 0 if unknown. + + The screen refresh rate for the current window. In windowed mode, this + should be equal to the refresh rate of the desktop the window is on. + + If no window is open, an exception is raised. + + When a constant refresh rate cannot be determined, 0 is returned. + + .. versionadded:: 2.2.0 + """ + +def get_desktop_refresh_rates() -> list[int]: + """Returns the screen refresh rates for all displays (in windowed mode). + + If the current window is in full-screen mode, the actual refresh rate for + that window can differ. + + This is safe to call when no window is open (i.e. before any calls to + :func:`pygame.display.set_mode()` + + When a constant refresh rate cannot be determined, 0 is returned for that + desktop. + + .. versionadded:: 2.2.0 + """ + def message_box( title: str, message: Optional[str] = None, @@ -104,4 +819,27 @@ def message_box( buttons: SequenceLike[str] = ("OK",), return_button: int = 0, escape_button: Optional[int] = None, -) -> int: ... +) -> int: + """Create a native GUI message box. + + :param str title: A title string. + :param str message: A message string. If this parameter is set to ``None``, the message will be the title. + :param str message_type: Set the type of message_box, could be ``"info"``, ``"warn"`` or ``"error"``. + :param Window parent_window: The parent window of the message box. + :param tuple buttons: An optional sequence of button name strings to show to the user. + :param int return_button: Button index to use if the return key is hit, ``0`` by default. + :param int escape_button: Button index to use if the escape key is hit, ``None`` for no button linked by default. + + :return: The index of the button that was pushed. + + This function should be called on the thread that ``set_mode()`` is called. + It will block execution of that thread until the user clicks a button or + closes the message_box. + + This function may be called at any time, even before ``pygame.init()``. + + Negative values of ``return_button`` and ``escape_button`` are allowed + just like standard Python list indexing. + + .. versionadded:: 2.4.0 + """ diff --git a/buildconfig/stubs/pygame/system.pyi b/buildconfig/stubs/pygame/system.pyi index 514af9a134..d86c1950f1 100644 --- a/buildconfig/stubs/pygame/system.pyi +++ b/buildconfig/stubs/pygame/system.pyi @@ -1,3 +1,8 @@ +"""Pygame module to provide additional context about the system. + +.. versionadded:: 2.2.0 +""" + from typing import Optional, TypedDict from pygame._data_classes import PowerState @@ -23,8 +28,180 @@ class _Locale(TypedDict): language: str country: Optional[str] -def get_cpu_instruction_sets() -> _InstructionSets: ... -def get_total_ram() -> int: ... -def get_pref_path(org: str, app: str) -> str: ... -def get_pref_locales() -> list[_Locale]: ... -def get_power_state() -> Optional[PowerState]: ... +def get_cpu_instruction_sets() -> _InstructionSets: + """Get the information of CPU instruction sets. + + Returns a dict of the information of CPU instruction sets. The keys of + the dict are the names of instruction sets and the values determine + whether the instruction set is available. + + Some of functions like ``Surface.blit`` can be accelerated by SIMD + instruction sets like SSE2 or AVX2. By checking the availability of + instruction sets, you can check if these accelerations are available. + + Here is an example of the returned dict + :: + + { + 'ALTIVEC': False, + 'MMX': True, + 'SSE': True, + 'SSE2': True, + 'SSE3': True, + 'SSE41': True, + 'SSE42': True, + 'AVX': True, + 'AVX2': True, + 'AVX512F': False, + 'NEON': False, + 'ARMSIMD': False, + 'LSX': False, + 'LASX': False + } + + .. note:: The values of ``LSX`` and ``LASX`` will be always False if + SDL version < 2.24.0. + + .. versionadded:: 2.3.1 + + .. versionchanged:: 2.4.0 removed ``RDTSC`` key, + as it has been removed in pre-release SDL3 + """ + +def get_total_ram() -> int: + """Get the amount of RAM configured in the system. + + Returns the amount of RAM configured in the system in MiB. + + .. versionadded:: 2.3.1 + """ + +def get_pref_path(org: str, app: str) -> str: + """Get a writeable folder for your app. + + When distributing apps, it's helpful to have a way to get a writeable path, + because it's what apps are expected to do, and because sometimes the local + space around the app isn't writeable to the app. + + This function returns a platform specific path for your app to store + savegames, settings, and the like. This path is unique per user and + per app name. + + It takes two strings, ``org`` and ``app``, referring to the "organization" + and "application name." For example, the organization could be "Valve," + and the application name could be "Half Life 2." It then will figure out the + preferred path, **creating the folders referenced by the path if necessary**, + and return a string containing the absolute path. + + For example:: + + On Windows, it would resemble + C:\\Users\\bob\\AppData\\Roaming\\My Company\\My Program Name\\ + + On macOS, it would resemble + /Users/bob/Library/Application Support/My Company/My Program Name/ + + And on Linux it would resemble + /home/bob/.local/share/My Company/My Program Name/ + + .. note:: + Since the organization and app names can potentially be used as + a folder name, it is highly encouraged to avoid punctuation. + Instead stick to letters, numbers, and spaces. + + .. note:: + The ``appdirs`` library has similar functionality for this use case, + but has more "folder types" to choose from. + + .. versionadded:: 2.2.0 + """ + +def get_pref_locales() -> list[_Locale]: + """Get preferred locales set on the system. + + Returns a list of "locale" dicts, sorted in descending order of preference + set on the host OS (the most preferred locale is the first element). May + also be an empty list if pygame could not find this information. + + Each "locale" dict contains the language code which can be accessed by the + key ``"language"``. This language code is an ISO-639 language specifier + (such as "en" for English, "de" for German, etc). + A "locale" dict may also optionally contain a ``"country"`` field, whose + value is an ISO-3166 country code (such as "US" for the United States, + "CA" for Canada, etc). If this field is not set or undetermined, it is + ``None``. + A "locale" dict which looks like ``{'language': 'en', 'country': 'US'}`` + indicates the user prefers American English, while + ``{'language': 'en', 'country': None}`` indicates that the user prefers + English, generically. + + This might be a bit of an expensive call because it has to query the OS. So + this function must not be called in a game loop, instead it's best to ask + for this once and save the results. However, this list can change when the + user changes a system preference outside of your program. pygame will send + a ``LOCALECHANGED`` event in this case, if possible, and you can call this + function again to get an updated copy of preferred locales. + + .. versionadded:: 2.2.0 + """ + +def get_power_state() -> Optional[PowerState]: + """Get the current power supply state. + + **Experimental:** feature available for testing and feedback. + We don't anticipate it changing, but it might if something important + is brought up. `Please leave get_power_state feedback with + authors `_ + + Returns a ``PowerState`` object representing the power supply state. + + Returns ``None`` if the power state is unknown. + + The PowerState object has several attributes: + + .. code-block:: text + + battery_percent: + An integer between 0 and 100, representing the percentage of + battery life left. + + battery_seconds: + An integer, representing the seconds of battery life left. + Could be None if the value is unknown. + + on_battery: + True if the device is running on the battery (not plugged in). + + no_battery: + True if the device has no battery available (plugged in). + + charging: + True if the device is charging battery (plugged in). + + charged: + True if the battery of the device is fully charged (plugged in). + + plugged_in: + True if the device is plugged in. + Equivalent to `not on_battery`. + + has_battery: + True if the device has battery. + Equivalent to `on_battery or not no_battery`. + + + You should never take a battery status as absolute truth. Batteries + (especially failing batteries) are delicate hardware, and the values + reported here are best estimates based on what that hardware reports. It's + not uncommon for older batteries to lose stored power much faster than it + reports, or completely drain when reporting it has 20 percent left, etc. + + Battery status can change at any time; if you are concerned with power + state, you should call this function frequently, and perhaps ignore changes + until they seem to be stable for a few seconds. + + It's possible a platform can only report battery percentage or time left + but not both. + + .. versionadded:: 2.4.0 + """ diff --git a/buildconfig/stubs/pygame/window.pyi b/buildconfig/stubs/pygame/window.pyi index ac948b4931..cdb57e6c96 100644 --- a/buildconfig/stubs/pygame/window.pyi +++ b/buildconfig/stubs/pygame/window.pyi @@ -1,5 +1,5 @@ from typing import Optional, Union -from typing_extensions import deprecated # added in 3.13 +from typing_extensions import deprecated # added in 3.13 from pygame.typing import Point, RectLike from pygame.locals import WINDOWPOS_UNDEFINED @@ -9,69 +9,461 @@ from pygame.surface import Surface def get_grabbed_window() -> Optional[Window]: ... class Window: + """Pygame object that represents a window. + + The Window class (formerly known as _sdl2.video.Window), is a newly + published feature of pygame-ce 2.5.2. This class allows for programs + to drive multiple windows on-screen at once, something not possible with + the :func:`pygame.display.set_mode` API. Not everything possible with + :mod:`pygame.display` is possible yet in the Window API, but the new + window class will continue to be developed, and we're excited to share + the new functionality this class offers. + + :param str title: The title of the window. + :param (int, int) size: The size of the window, in screen coordinates. + :param (int, int) or int position: A tuple specifying the window position, or + ``WINDOWPOS_CENTERED``, or ``WINDOWPOS_UNDEFINED``. + :param bool fullscreen: Create a fullscreen window using the window size as + the resolution (videomode change). + :param bool fullscreen_desktop: Create a fullscreen window using the current + desktop resolution. + :param bool opengl: Create a window with support for an OpenGL context. + :param bool vulkan: Create a window with support for a Vulkan instance. + :param bool hidden: Create a hidden window. + :param bool borderless: Create a window without borders. + :param bool resizable: Create a resizable window. + :param bool minimized: Create a mimized window. + :param bool maximized: Create a maximized window. + :param bool mouse_grabbed: Create a window with grabbed mouse input. + :param bool keyboard_grabbed: Create a window with grabbed keyboard input. + :param bool input_focus: Create a window with input focus. + :param bool mouse_focus: Create a window with mouse focus. + :param bool allow_high_dpi: Create a window in high-DPI mode if supported. + :param bool mouse_capture: Create a window that has the mouse captured + (unrelated to INPUT_GRABBED). + :param bool always_on_top: Create a window that is always presented above + others. + :param bool utility: Create a window that doesn't appear in the task bar. + + Event behavior if one Window is created: When the close button is pressed, + the ``QUIT`` event will be sent to the event queue. + + .. code-block:: python + + import pygame + + window = pygame.Window() + + while True: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + raise SystemExit + + Event behavior if multiple ``Window``\ s are created: When the close button is + pressed, a ``WINDOWCLOSE`` event is sent. You need to explicitly destroy + the window. Note that the event ``QUIT`` will only be sent if all + ``Window``\ s have been destroyed. + + .. code-block:: python + + import pygame + + window1 = pygame.Window(position=(0,100)) + window2 = pygame.Window(position=(700,100)) + + while True: + for event in pygame.event.get(): + if event.type == pygame.WINDOWCLOSE: + id = event.window.id + print(f"WINDOWCLOSE event sent to Window #{id}.") + event.window.destroy() + + if event.type == pygame.QUIT: + print(f"Last window is destroyed. QUIT event was sent.") + pygame.quit() + raise SystemExit + + .. versionadded:: 2.4.0 + .. versionchanged:: 2.5.0 when ``opengl`` is ``True``, the ``Window`` has an OpenGL context created by pygame + .. versionchanged:: 2.5.1 Window is now a base class, allowing subclassing + """ + def __init__( self, title: str = "pygame window", size: Point = (640, 480), position: Union[int, Point] = WINDOWPOS_UNDEFINED, - **flags: bool + **flags: bool, ) -> None: ... - def destroy(self) -> None: ... - def set_windowed(self) -> None: ... - def set_fullscreen(self, desktop: bool = False) -> None: ... - def focus(self, input_only: bool = False) -> None: ... - def hide(self) -> None: ... - def show(self) -> None: ... - def restore(self) -> None: ... - def maximize(self) -> None: ... - def minimize(self) -> None: ... - def set_modal_for(self, parent: Window, /) -> None: ... - def set_icon(self, icon: Surface, /) -> None: ... - def get_surface(self) -> Surface: ... - def flip(self) -> None: ... - def flash(self, operation: int, /) -> None: ... grab_mouse: bool + """Get or set the window's mouse grab mode. + + When this attribute is set to ``True``, the window will try to confine the mouse + cursor to itself. + + Note this only set the "mode" of grab. The mouse may be confined to another window + depending on the window focus. To get if the mouse is currently restricted to this + window, please use :attr:`mouse_grabbed`. + + .. seealso:: :attr:`mouse_grabbed` + + .. versionadded:: 2.4.0 + """ + grab_keyboard: bool + """Get or set the window's keyboard grab mode. + + When this attribute is set to ``True``, the window will try to capture system + keyboard shortcuts like ``Alt+Tab`` or the ``Meta/Super`` key. + + This attribute only set the "mode" of grab. The keyboard may be captured by + another window depending on the window focus. To get if keyboard is currently + captured by this window, please use :attr:`keyboard_grabbed`. + + Note that not all system keyboard shortcuts can be captured by applications + (one example is ``Ctrl+Alt+Del`` on Windows). + + When keyboard grab is enabled, pygame will continue to handle ``Alt+Tab`` when + the window is full-screen to ensure the user is not trapped in your application. + If you have a custom keyboard shortcut to exit fullscreen mode, you may suppress + this behavior with an environment variable, e.g. + ``os.environ["SDL_ALLOW_ALT_TAB_WHILE_GRABBED"] = "0"``. + + This attribute requires SDL 2.0.16+. + + .. seealso:: :attr:`keyboard_grabbed` + + .. versionadded:: 2.4.0 + """ + + @property + def mouse_grabbed(self) -> bool: + """Get if the mouse cursor is confined to the window (**read-only**). + + Get if the mouse cursor is currently grabbed and confined to the window. + + Roughly equivalent to this expression: + + :: + + win.grab_mouse and (win is get_grabbed_window()) + + .. seealso:: :attr:`grab_mouse` + + .. versionadded:: 2.4.0 + """ + + @property + def keyboard_grabbed(self) -> bool: + """Get if the keyboard shortcuts are captured by the window (**read-only**). + + Get if the keyboard shortcuts are currently grabbed and captured by the window. + + Roughly equivalent to this expression: + + :: + + win.grab_keyboard and (win is get_grabbed_window()) + + This attribute requires SDL 2.0.16+. + + .. seealso:: :attr:`grab_keyboard` + + .. versionadded:: 2.4.0 + """ + + @property + def focused(self) -> bool: + """Get if the window is focused (**read-only**). + + Get if the window is currently focused. The same result can be achieved using + the ``WINDOWFOCUSGAINED`` and ``WINDOWFOCUSLOST`` events. + + Use :meth:`focus` to focus and raise the window. + + .. versionadded:: 2.5.2 + """ title: str + """Get or set the window title. + + An empty string means that no title is set. + """ + resizable: bool + """Get or set whether the window is resizable.""" + borderless: bool + """Gets or sets whether the window is borderless. + + .. note:: You can't change the border state of a fullscreen window. + """ + always_on_top: bool - relative_mouse: bool - opacity: float + """Get or set whether the window is always on top. + + Setting the always-on-top mode requires SDL 2.0.16+. + + .. versionadded:: 2.3.1 + """ @property - def mouse_grabbed(self) -> bool: ... - @property - def keyboard_grabbed(self) -> bool: ... - @property - def focused(self) -> bool: ... - @property - def id(self) -> int: ... + def id(self) -> int: + """Get the unique window ID (**read-only**).""" + @property - def mouse_rect(self) -> Optional[Rect]: ... + def mouse_rect(self) -> Optional[Rect]: + """Get or set the mouse confinement rectangle of the window. + + Setting this attribute to a rect-like object confines the + cursor to the specified area of this window. + + This attribute can be None, meaning that there is no mouse rect. + + Note that this does NOT grab the cursor, it only defines the area a + cursor is restricted to when the window has mouse focus. + + .. versionadded:: 2.4.0 + """ + @mouse_rect.setter def mouse_rect(self, value: Optional[RectLike]) -> None: ... @property - def size(self) -> tuple[int, int]: ... + def size(self) -> tuple[int, int]: + """Get or set the window size in pixels.""" + @size.setter def size(self, value: Point) -> None: ... @property - def minimum_size(self) -> tuple[int, int]: ... + def minimum_size(self) -> tuple[int, int]: + """Get or set the minimum size of the window's client area. + + Initial value in most cases is ``(0, 0)``. If :func:`from_display_module` + was used to create the window and :func:`pygame.display.set_mode` was + called with the ``SCALED`` flag, the initial value is the size used in + that call. + + Raises a ``ValueError`` if negative values are provided or + if the width or height provided are greater than set + maximum width or height respectively. Unless maximum size + is ``(0, 0)`` (initial value). + + .. seealso:: :attr:`maximum_size`. + + .. versionadded:: 2.4.0 + """ + @minimum_size.setter def minimum_size(self, value: Point) -> None: ... @property - def maximum_size(self) -> tuple[int, int]: ... + def maximum_size(self) -> tuple[int, int]: + """Get or set the maximum size of the window's client area. + + Initial value is ``(0, 0)``. + + Raises a ``ValueError`` if negative values are provided or + if the width or height provided are less than set minimum + width or height respectively. + + .. seealso:: :attr:`minimum_size`. + + .. versionadded:: 2.4.0 + """ + @maximum_size.setter def maximum_size(self, value: Point) -> None: ... @property - def position(self) -> tuple[int, int]: ... + def position(self) -> tuple[int, int]: + """Get or set the window position in screen coordinates.""" + @position.setter def position(self, value: Union[int, Point]) -> None: ... + opacity: float + """Get or set the window opacity, between 0.0 (fully transparent) and 1.0 (fully opaque).""" + @property - def opengl(self) -> bool: ... + def opengl(self) -> bool: + """Get if the window supports OpenGL. + + ``True`` if the ``Window`` has an OpenGL context associated with it, ``False`` otherwise + + .. versionadded:: 2.5.0 + """ + @property - def utility(self) -> bool: ... + def utility(self) -> bool: + """Get if the window is an utility window (**read-only**). + + ``True`` if the window doesn't appear in the task bar, ``False`` otherwise. + This only works for X11 and Windows, for other platforms, creating ``Window(utility=True)`` won't change anything. + + .. versionadded:: 2.5.3 + """ + @classmethod - @deprecated("since 2.4.0. Use either the display module or the Window class with get_surface and flip. Try not to mix display and Window") - def from_display_module(cls) -> Window: ... + @deprecated( + "since 2.4.0. Use either the display module or the Window class with get_surface and flip. Try not to mix display and Window" + ) + def from_display_module(cls) -> Window: + """Create a Window object using window data from display module. + + **DON'T USE THIS!** If you want to draw to a surface and use the window + API, use :func:`Window.get_surface` and :func:`Window.flip`. + + Create a Window object that uses the same window data from the :mod:`pygame.display` module, created upon calling + :func:`pygame.display.set_mode`. + + .. deprecated:: 2.4.0 + """ + + def get_surface(self) -> Surface: + """Get the window surface. + + Returns a "display surface" for this Window. The surface returned is + analogous to the surface returned by :func:`pygame.display.set_mode`. + + This method allows software rendering (classic pygame rendering) on top + of the Window API. This method should not be called when using hardware + rendering (coming soon). + + Similarly to the "display surface" returned by :mod:`pygame.display`, + this surface will change size with the Window, and will become invalid + after the Window's destruction. + + .. seealso:: :func:`flip` + + .. versionadded:: 2.4.0 + """ + + def flip(self) -> None: + """Update the display surface to the window. + + Update pixel data from memory to be displayed in the window. This is the Window + class equivalent of :func:`pygame.display.flip`. + + With ``get_surface()`` this method allows software rendering (classic pygame rendering) flipping pixel data + from an associated surface in memory to be displayed in the window. Alternatively, when this window has an + associated OpenGL context, this method will instead perform a GL buffer swap to the window. + + Here is a runnable example of using ``get_surface`` and ``flip``: + + .. code-block:: python + + import pygame + + win = pygame.Window() + surf = win.get_surface() # get the window surface + + while True: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + pygame.quit() + raise SystemExit + + # draw something on the surface + surf.fill("red") + + win.flip() # update the surface to the window + + + .. versionadded:: 2.4.0 + """ + + def set_windowed(self) -> None: + """Enable windowed mode (exit fullscreen). + + .. seealso:: :func:`set_fullscreen` + """ + + def set_fullscreen(self, desktop: bool = False) -> None: + """Enter fullscreen. + + :param bool desktop: If ``True``, use the current desktop resolution. + If ``False``, change the fullscreen resolution to the window size. + + .. seealso:: :meth:`set_windowed`. + """ + + def destroy(self) -> None: + """Destroy the window. + + Destroys the internal window data of this Window object. This method is + called automatically when this Window object is garbage collected, so + there usually aren't any reasons to call it manually. + + Other methods that try to manipulate that window data will raise an error. + """ + + def hide(self) -> None: + """Hide the window.""" + + def show(self) -> None: + """Show the window.""" + + def focus(self, input_only: bool = False) -> None: + """Set the window to be focused. + + Raises the window above other windows and sets the input focus. + + :param input_only: if ``True``, the window will be given input focus + but may be completely obscured by other windows. + Only supported on X11. This has been deprecated and + may be removed in a future version. + + .. deprecated:: 2.5.3 ``input_only`` argument + """ + + def restore(self) -> None: + """Restore the size and position of a minimized or maximized window.""" + + def maximize(self) -> None: + """Maximize the window.""" + + def minimize(self) -> None: + """Minimize the window.""" + + def set_icon(self, icon: Surface, /) -> None: + """Set the window icon. + + :param Surface surface: A Surface to use as the icon. + """ + + def set_modal_for(self, parent: Window, /) -> None: + """Set the window as a modal for a parent window. + + :param Window parent: The parent window. + + .. note:: This function is only supported on X11. + """ + + def flash(self, operation: int, /) -> None: + """Flash a window to demand attention from the user. + + :param int operation: The flash operation. + + Supported flash operations are: + * ``pygame.FLASH_CANCEL``: Cancel the current flash state if present + * ``pygame.FLASH_BRIEFLY``: Flash for a short amount of time to get attention + * ``pygame.FLASH_UNTIL_FOCUSED``: Keep flashing until the window is focused + + Window flashing requires SDL 2.0.16+. A :mod:`pygame.error` exception will be raised + otherwise. + + .. note:: This function is only supported on Windows, X11, Wayland and Cocoa (MacOS). + A :mod:`pygame.error` exception will be raised if it's not supported therefore it's + advised to wrap it in a try block. + + .. code-block:: python + + import pygame + window = pygame.Window() + + try: + window.flash(pygame.FLASH_BRIEFLY) + except pygame.error: + print("Window flashing not supported") + + .. versionadded:: 2.5.2 + """ + relative_mouse: bool diff --git a/docs/reST/ext/documenters.py b/docs/reST/ext/documenters.py index 0775a1f843..b02a9739f4 100644 --- a/docs/reST/ext/documenters.py +++ b/docs/reST/ext/documenters.py @@ -1,6 +1,7 @@ import autoapi import autoapi.documenters from autoapi._objects import PythonClass +import re def build_signatures(object): @@ -45,6 +46,9 @@ def build_signatures(object): if ret in ("Optional", "Union"): ret = "..." + # Shorten "pygame.module.X" types to "X" + ret = re.sub(r"pygame(.[a-zA-Z0-9_]+)+", lambda x: x.group(1)[1:], ret) + yield f"| :sg:`{name}({arg_string}) -> {ret}`" @@ -81,9 +85,7 @@ def get_object_members(self, want_all): members = ( member for member in members - if not member.object.obj.get("hide", False) - and not member.object.imported - and get_doc(self.env, member.object) != "" + if not member.object.imported and get_doc(self.env, member.object) != "" ) return members_check_module, members diff --git a/docs/reST/ref/display.rst b/docs/reST/ref/display.rst index 223a3744de..21aa8355f3 100644 --- a/docs/reST/ref/display.rst +++ b/docs/reST/ref/display.rst @@ -3,876 +3,5 @@ :mod:`pygame.display` ===================== -.. module:: pygame.display - :synopsis: pygame module to control the display window and screen - -| :sl:`pygame module to control the display window and screen` - -This module offers control over the pygame display. Pygame has a single display -Surface that is either contained in a window or runs full screen. Once you -create the display you treat it as a regular Surface. Changes are not -immediately visible onscreen; you must choose one of the two flipping functions -to update the actual display. - -The origin of the display, where x = 0 and y = 0, is the top left of the -screen. Both axes increase positively towards the bottom right of the screen. - -The pygame display can actually be initialized in one of several modes. By -default, the display is a basic software driven framebuffer. You can request -special modules like automatic scaling or OpenGL support. These are -controlled by flags passed to ``pygame.display.set_mode()``. - -Pygame can only have a single display active at any time. Creating a new one -with ``pygame.display.set_mode()`` will close the previous display. To detect -the number and size of attached screens, you can use -``pygame.display.get_desktop_sizes`` and then select appropriate window size -and display index to pass to ``pygame.display.set_mode()``. - -For backward compatibility ``pygame.display`` allows precise control over -the pixel format or display resolutions. This used to be necessary with old -graphics cards and CRT screens, but is usually not needed any more. Use the -functions ``pygame.display.mode_ok()``, ``pygame.display.list_modes()``, and -``pygame.display.Info()`` to query detailed information about the display. - -Once the display Surface is created, the functions from this module affect the -single existing display. The Surface becomes invalid if the module is -uninitialized. If a new display mode is set, the existing Surface will -automatically switch to operate on the new display. - -When the display mode is set, several events are placed on the pygame event -queue. ``pygame.QUIT`` is sent when the user has requested the program to -shut down. The window will receive ``pygame.ACTIVEEVENT`` events as the display -gains and loses input focus. If the display is set with the -``pygame.RESIZABLE`` flag, ``pygame.VIDEORESIZE`` events will be sent when the -user adjusts the window dimensions. Hardware displays that draw direct to the -screen will get ``pygame.VIDEOEXPOSE`` events when portions of the window must -be redrawn. - -A new windowevent API was introduced in pygame 2.0.1. Check event module docs -for more information on that - -Some display environments have an option for automatically stretching all -windows. When this option is enabled, this automatic stretching distorts the -appearance of the pygame window. In the pygame examples directory, there is -example code (prevent_display_stretching.py) which shows how to disable this -automatic stretching of the pygame display on Microsoft Windows (Vista or newer -required). - -.. function:: init - - | :sl:`Initialize the display module` - | :sg:`init() -> None` - - Initializes the pygame display module. The display module cannot do anything - until it is initialized. This is usually handled for you automatically when - you call the higher level ``pygame.init()``. - - Pygame will select from one of several internal display backends when it is - initialized. The display mode will be chosen depending on the platform and - permissions of current user. Before the display module is initialized the - environment variable ``SDL_VIDEODRIVER`` can be set to control which backend - is used. The systems with multiple choices are listed here. - - :: - - Windows : windib, directx - Unix : x11, dga, fbcon, directfb, ggi, vgl, svgalib, aalib, wayland - - :note: On wayland desktops, pygame-ce may choose to use the X11 video driver to run on Xwayland. - This behaviour is determined by the SDL library and might change in the future, so it's suggested - to account for this and not rely on the default behavior. The Wayland video driver can be forced - by setting the ``SDL_VIDEODRIVER`` environment variable to ``"wayland"`` - - On some platforms it is possible to embed the pygame display into an already - existing window. To do this, the environment variable ``SDL_WINDOWID`` must - be set to a string containing the window id or handle. The environment - variable is checked when the pygame display is initialized. Be aware that - there can be many strange side effects when running in an embedded display. - - It is harmless to call this more than once, repeated calls have no effect. - - .. versionchanged:: 2.5.0 the manylinux wheels distributed by us now support the ``wayland`` videodriver - - .. ## pygame.display.init ## - -.. function:: quit - - | :sl:`Uninitialize the display module` - | :sg:`quit() -> None` - - This will shut down the entire display module. This means any active - displays will be closed. This will also be handled automatically when the - program exits. - - It is harmless to call this more than once, repeated calls have no effect. - - .. ## pygame.display.quit ## - -.. function:: get_init - - | :sl:`Returns True if the display module has been initialized` - | :sg:`get_init() -> bool` - - Returns True if the :mod:`pygame.display` module is currently initialized. - - .. ## pygame.display.get_init ## - -.. function:: set_mode - - | :sl:`Initialize a window or screen for display` - | :sg:`set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface` - - This will create a window or display output and return a display Surface. - The arguments passed in are requests for a display type. The actual created - display will be the best possible match supported by the system. - - Note that calling this function implicitly initializes ``pygame.display``, if - it was not initialized before. - - The size argument is a pair of numbers representing the width and - height. The flags argument is a collection of additional options. The depth - argument represents the number of bits to use for color. - - The Surface that gets returned can be drawn to like a regular Surface but - changes will eventually be seen on the monitor. - - If no size is passed or is set to ``(0, 0)``, the created Surface will have - the same size as the current screen resolution. If only the width or height - are set to ``0``, the Surface will have the same width or height as the - screen resolution. - - Since pygame 2, the depth argument is ignored, in favour of the best - and fastest one. It also raises a deprecation warning since pygame-ce - 2.4.0 if the passed in depth is not 0 or the one pygame selects. - - When requesting fullscreen display modes, sometimes an exact match for the - requested size cannot be made. In these situations pygame will select - the closest compatible match. The returned surface will still always match - the requested size. - - On high resolution displays(4k, 1080p) and tiny graphics games (640x480) - show up very small so that they are unplayable. SCALED scales up the window - for you. The game thinks it's a 640x480 window, but really it can be bigger. - Mouse events are scaled for you, so your game doesn't need to do it. Note - that SCALED is considered an experimental API and may change in future - releases. - - The flags argument controls which type of display you want. There are - several to choose from, and you can even combine multiple types using the - bitwise or operator, (the pipe "|" character). Here are the display - flags you will want to choose from: - - :: - - pygame.FULLSCREEN create a fullscreen display - pygame.DOUBLEBUF only applicable with OPENGL - pygame.HWSURFACE (obsolete in pygame 2) hardware accelerated, only in FULLSCREEN - pygame.OPENGL create an OpenGL-renderable display - pygame.RESIZABLE display window should be sizeable - pygame.NOFRAME display window will have no border or controls - pygame.SCALED resolution depends on desktop size and scale graphics - pygame.SHOWN window is opened in visible mode (default) - pygame.HIDDEN window is opened in hidden mode - - - .. versionaddedold:: 2.0.0 ``SCALED``, ``SHOWN`` and ``HIDDEN`` - - .. versionaddedold:: 2.0.0 ``vsync`` parameter - - By setting the ``vsync`` parameter to ``1``, it is possible to get a display - with vertical sync at a constant frame rate determined by the monitor and - graphics drivers. Subsequent calls to :func:`pygame.display.flip()` or - :func:`pygame.display.update()` will block (i.e. *wait*) until the screen - has refreshed, in order to prevent "screen tearing" - . - - Be careful when using this feature together with ``pygame.time.Clock`` or - :func:`pygame.time.delay()`, as multiple forms of waiting and frame rate - limiting may interact to cause skipped frames. - - The request only works when graphics acceleration is available on the - system. The exact behaviour depends on the hardware and driver - configuration. When ``vsync`` is requested, but unavailable, - ``set_mode()`` may raise an exception. - - Setting the ``vsync`` parameter to ``-1`` in conjunction with ``OPENGL`` - will request the OpenGL-specific feature "adaptive vsync" . - - Here is an example usage of a call - to ``set_mode()`` that may give you a display with vsync: - - :: - - flags = pygame.OPENGL | pygame.FULLSCREEN - try: - window_surface = pygame.display.set_mode((1920, 1080), flags, vsync=1) - vsync_success=True - except pygame.error: - window_surface = pygame.display.set_mode((1920, 1080), flags) - vsync_success=False - - .. versionaddedold:: 2.0.0 ``vsync`` parameter - - .. versionchanged:: 2.2.0 passing ``vsync`` can raise an exception - - .. versionchanged:: 2.2.0 explicit request for "adaptive vsync" - - .. versionchanged:: 2.2.0 ``vsync=1`` does not require ``SCALED`` or ``OPENGL`` - - .. deprecated:: 2.4.0 The depth argument is ignored, and will be set to the optimal value - - .. versionchanged:: 2.5.0 No longer emits warning when running on xwayland, see :func:`pygame.display.init` for details on running on wayland directly - - - Basic example: - - :: - - # Open a window on the screen - screen_width=700 - screen_height=400 - screen=pygame.display.set_mode([screen_width, screen_height]) - - The display index ``0`` means the default display is used. If no display - index argument is provided, the default display can be overridden with an - environment variable. - - - .. versionchangedold:: 1.9.5 ``display`` argument added - - .. versionchanged:: 2.1.3 - pygame now ensures that subsequent calls to this function clears the - window to black. On older versions, this was an implementation detail - on the major platforms this function was tested with. - - .. ## pygame.display.set_mode ## - -.. function:: get_surface - - | :sl:`Get a reference to the currently set display surface` - | :sg:`get_surface() -> Surface` - | :sg:`get_surface() -> None` - - Return a reference to the currently set display Surface. If no display mode - has been set this will return None. - - .. ## pygame.display.get_surface ## - -.. function:: flip - - | :sl:`Update the full display Surface to the screen` - | :sg:`flip() -> None` - - This will update the contents of the entire display. - - When using an ``pygame.OPENGL`` display mode this will perform a gl buffer - swap. - - .. ## pygame.display.flip ## - -.. function:: update - - | :sl:`Update all, or a portion, of the display. For non-OpenGL displays.` - | :sg:`update() -> None` - | :sg:`update(rectangle, /) -> None` - | :sg:`update(x, y, w, h, /) -> None` - | :sg:`update((x, y), (w, h), /) -> None` - | :sg:`update(rectangle_iterable, /) -> None` - - For non OpenGL display Surfaces, this function is very similar to - ``pygame.display.flip()`` with an optional parameter that allows only - portions of the display surface to be updated, instead of the entire area. - If no argument is passed it updates the entire Surface area like - ``pygame.display.flip()``. - - .. note:: calling ``display.update(None)`` means no part of the window is - updated. Whereas ``display.update()`` means the whole window is - updated. - - You can pass the function a single rectangle, or an iterable of rectangles. - Generally you do not want to pass an iterable of rectangles as there is a - performance cost per rectangle passed to the function. On modern hardware, - after a very small number of rectangles passed in, the per-rectangle cost - will exceed the saving of updating less pixels. In most applications it is - simply more efficient to update the entire display surface at once, it also - means you do not need to keep track of a list of rectangles for each call - to update. - - If passing an iterable of rectangles it is safe to include None - values in the list, which will be skipped. - - This call cannot be used on ``pygame.OPENGL`` displays and will generate an - exception. - - .. versionchanged:: 2.5.1 Added support for passing an iterable, previously only sequence was allowed - - .. ## pygame.display.update ## - -.. function:: get_driver - - | :sl:`Get the name of the pygame display backend` - | :sg:`get_driver() -> name` - - Pygame chooses one of many available display backends when it is - initialized. This returns the internal name used for the display backend. - This can be used to provide limited information about what display - capabilities might be accelerated. See the ``SDL_VIDEODRIVER`` flags in - ``pygame.display.set_mode()`` to see some of the common options. - - .. ## pygame.display.get_driver ## - -.. function:: Info - - | :sl:`Create a video display information object` - | :sg:`Info() -> VideoInfo` - - Creates a simple object containing several attributes to describe the - current graphics environment. If this is called before - ``pygame.display.set_mode()`` some platforms can provide information about - the default display mode. This can also be called after setting the display - mode to verify specific display options were satisfied. The VidInfo object - has several attributes: - - .. code-block:: text - - hw: 1 if the display is hardware accelerated - wm: 1 if windowed display modes can be used - video_mem: The megabytes of video memory on the display. - This is 0 if unknown - bitsize: Number of bits used to store each pixel - bytesize: Number of bytes used to store each pixel - masks: Four values used to pack RGBA values into pixels - shifts: Four values used to pack RGBA values into pixels - losses: Four values used to pack RGBA values into pixels - blit_hw: 1 if hardware Surface blitting is accelerated - blit_hw_CC: 1 if hardware Surface colorkey blitting is accelerated - blit_hw_A: 1 if hardware Surface pixel alpha blitting is - accelerated - blit_sw: 1 if software Surface blitting is accelerated - blit_sw_CC: 1 if software Surface colorkey blitting is - accelerated - blit_sw_A: 1 if software Surface pixel alpha blitting is - accelerated - current_h, current_w: Height and width of the current video - mode, or of the desktop mode if called before - the display.set_mode is called. They are -1 on error. - pixel_format: The pixel format of the display Surface as a string. - E.g PIXELFORMAT_RGB888. - - .. versionchanged:: 2.4.0 ``pixel_format`` attribute added. - - .. ## pygame.display.Info ## - -.. function:: get_wm_info - - | :sl:`Get information about the current windowing system` - | :sg:`get_wm_info() -> dict` - - Creates a dictionary filled with string keys. The strings and values are - arbitrarily created by the system. Some systems may have no information and - an empty dictionary will be returned. Most platforms will return a "window" - key with the value set to the system id for the current display. - - .. versionaddedold:: 1.7.1 - - .. ## pygame.display.get_wm_info ## - -.. function:: get_desktop_sizes - - | :sl:`Get sizes of active desktops` - | :sg:`get_desktop_sizes() -> list` - - This function returns the sizes of the currently configured - virtual desktops as a list of (x, y) tuples of integers. - - The length of the list is not the same as the number of attached monitors, - as a desktop can be mirrored across multiple monitors. The desktop sizes - do not indicate the maximum monitor resolutions supported by the hardware, - but the desktop size configured in the operating system. - - In order to fit windows into the desktop as it is currently configured, and - to respect the resolution configured by the operating system in fullscreen - mode, this function *should* be used to replace many use cases of - ``pygame.display.list_modes()`` whenever applicable. - - .. versionaddedold:: 2.0.0 - -.. function:: list_modes - - | :sl:`Get list of available fullscreen modes` - | :sg:`list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list` - - This function returns a list of possible sizes for a specified color - depth. The return value will be an empty list if no display modes are - available with the given arguments. A return value of ``-1`` means that - any requested size should work (this is likely the case for windowed - modes). Mode sizes are sorted from biggest to smallest. - - If depth is ``0``, the current/best color depth for the display is used. - The flags defaults to ``pygame.FULLSCREEN``, but you may need to add - additional flags for specific fullscreen modes. - - The display index ``0`` means the default display is used. - - Since pygame 2.0, ``pygame.display.get_desktop_sizes()`` has taken over - some use cases from ``pygame.display.list_modes()``: - - To find a suitable size for non-fullscreen windows, it is preferable to - use ``pygame.display.get_desktop_sizes()`` to get the size of the *current* - desktop, and to then choose a smaller window size. This way, the window is - guaranteed to fit, even when the monitor is configured to a lower resolution - than the maximum supported by the hardware. - - To avoid changing the physical monitor resolution, it is also preferable to - use ``pygame.display.get_desktop_sizes()`` to determine the fullscreen - resolution. Developers are strongly advised to default to the current - physical monitor resolution unless the user explicitly requests a different - one (e.g. in an options menu or configuration file). - - .. versionchangedold:: 1.9.5 ``display`` argument added - - .. ## pygame.display.list_modes ## - -.. function:: mode_ok - - | :sl:`Pick the best color depth for a display mode` - | :sg:`mode_ok(size, flags=0, depth=0, display=0) -> depth` - - This function uses the same arguments as ``pygame.display.set_mode()``. It - is used to determine if a requested display mode is available. It will - return ``0`` if the display mode cannot be set. Otherwise it will return a - pixel depth that best matches the display asked for. - - Usually the depth argument is not passed, but some platforms can support - multiple display depths. If passed it will hint to which depth is a better - match. - - The function will return ``0`` if the passed display flags cannot be set. - - The display index ``0`` means the default display is used. - - .. versionchangedold:: 1.9.5 ``display`` argument added - - .. ## pygame.display.mode_ok ## - -.. function:: gl_get_attribute - - | :sl:`Get the value for an OpenGL flag for the current display` - | :sg:`gl_get_attribute(flag, /) -> value` - - After calling ``pygame.display.set_mode()`` with the ``pygame.OPENGL`` flag, - it is a good idea to check the value of any requested OpenGL attributes. See - ``pygame.display.gl_set_attribute()`` for a list of valid flags. - - .. ## pygame.display.gl_get_attribute ## - -.. function:: gl_set_attribute - - | :sl:`Request an OpenGL display attribute for the display mode` - | :sg:`gl_set_attribute(flag, value, /) -> None` - - When calling ``pygame.display.set_mode()`` with the ``pygame.OPENGL`` flag, - Pygame automatically handles setting the OpenGL attributes like color and - double-buffering. OpenGL offers several other attributes you may want control - over. Pass one of these attributes as the flag, and its appropriate value. - This must be called before ``pygame.display.set_mode()``. - - Many settings are the requested minimum. Creating a window with an OpenGL context - will fail if OpenGL cannot provide the requested attribute, but it may for example - give you a stencil buffer even if you request none, or it may give you a larger - one than requested. - - The ``OPENGL`` flags are: - - :: - - GL_ALPHA_SIZE, GL_DEPTH_SIZE, GL_STENCIL_SIZE, GL_ACCUM_RED_SIZE, - GL_ACCUM_GREEN_SIZE, GL_ACCUM_BLUE_SIZE, GL_ACCUM_ALPHA_SIZE, - GL_MULTISAMPLEBUFFERS, GL_MULTISAMPLESAMPLES, GL_STEREO - - :const:`GL_MULTISAMPLEBUFFERS` - - Whether to enable multisampling anti-aliasing. - Defaults to 0 (disabled). - - Set ``GL_MULTISAMPLESAMPLES`` to a value - above 0 to control the amount of anti-aliasing. - A typical value is 2 or 3. - - :const:`GL_STENCIL_SIZE` - - Minimum bit size of the stencil buffer. Defaults to 0. - - :const:`GL_DEPTH_SIZE` - - Minimum bit size of the depth buffer. Defaults to 16. - - :const:`GL_STEREO` - - 1 enables stereo 3D. Defaults to 0. - - :const:`GL_BUFFER_SIZE` - - Minimum bit size of the frame buffer. Defaults to 0. - - .. versionaddedold:: 2.0.0 Additional attributes: - - :: - - GL_ACCELERATED_VISUAL, - GL_CONTEXT_MAJOR_VERSION, GL_CONTEXT_MINOR_VERSION, - GL_CONTEXT_FLAGS, GL_CONTEXT_PROFILE_MASK, - GL_SHARE_WITH_CURRENT_CONTEXT, - GL_CONTEXT_RELEASE_BEHAVIOR, - GL_FRAMEBUFFER_SRGB_CAPABLE - - :const:`GL_CONTEXT_PROFILE_MASK` - - Sets the OpenGL profile to one of these values: - - :: - - GL_CONTEXT_PROFILE_CORE disable deprecated features - GL_CONTEXT_PROFILE_COMPATIBILITY allow deprecated features - GL_CONTEXT_PROFILE_ES allow only the ES feature - subset of OpenGL - - :const:`GL_ACCELERATED_VISUAL` - - Set to 1 to require hardware acceleration, or 0 to force software render. - By default, both are allowed. - - .. ## pygame.display.gl_set_attribute ## - -.. function:: get_active - - | :sl:`Returns True when the display is active on the screen` - | :sg:`get_active() -> bool` - - Returns True when the display Surface is considered actively - renderable on the screen and may be visible to the user. This is - the default state immediately after ``pygame.display.set_mode()``. - This method may return True even if the application is fully hidden - behind another application window. - - This will return False if the display Surface has been iconified or - minimized (either via ``pygame.display.iconify()`` or via an OS - specific method such as the minimize-icon available on most - desktops). - - The method can also return False for other reasons without the - application being explicitly iconified or minimized by the user. A - notable example being if the user has multiple virtual desktops and - the display Surface is not on the active virtual desktop. - - .. note:: This function returning True is unrelated to whether the - application has input focus. Please see - ``pygame.key.get_focused()`` and ``pygame.mouse.get_focused()`` - for APIs related to input focus. - - .. ## pygame.display.get_active ## - -.. function:: iconify - - | :sl:`Iconify the display surface` - | :sg:`iconify() -> bool` - - Request the window for the display surface be iconified or hidden. Not all - systems and displays support an iconified display. The function will return - True if successful. - - When the display is iconified ``pygame.display.get_active()`` will return - ``False``. The event queue should receive an ``ACTIVEEVENT`` event when the - window has been iconified. Additionally, the event queue also receives a - ``WINDOWEVENT_MINIMIZED`` event when the window has been iconified on pygame 2. - - .. ## pygame.display.iconify ## - -.. function:: toggle_fullscreen - - | :sl:`Switch between fullscreen and windowed displays` - | :sg:`toggle_fullscreen() -> int` - - Switches the display window between windowed and fullscreen modes. - Display driver support is not great when using pygame 1, but with - pygame 2 it is the most reliable method to switch to and from fullscreen. - - Supported display drivers in pygame 1: - - * x11 (Linux/Unix) - * wayland (Linux/Unix) - - Supported display drivers in pygame 2: - - * windows (Windows) - * x11 (Linux/Unix) - * wayland (Linux/Unix) - * cocoa (OSX/Mac) - - .. Note:: :func:`toggle_fullscreen` doesn't work on Windows - unless the window size is in :func:`pygame.display.list_modes()` or - the window is created with the flag ``pygame.SCALED``. - See `issue #1221 `_. - - .. ## pygame.display.toggle_fullscreen ## - -.. function:: set_gamma - - | :sl:`Change the hardware gamma ramps` - | :sg:`set_gamma(red, green=None, blue=None, /) -> bool` - - DEPRECATED: This functionality will go away in SDL3. - - Set the red, green, and blue gamma values on the display hardware. If the - green and blue arguments are not passed, they will both be the same as red. - Not all systems and hardware support gamma ramps, if the function succeeds - it will return ``True``. - - A gamma value of ``1.0`` creates a linear color table. Lower values will - darken the display and higher values will brighten. - - .. deprecated:: 2.1.4 - - .. ## pygame.display.set_gamma ## - -.. function:: set_gamma_ramp - - | :sl:`Change the hardware gamma ramps with a custom lookup` - | :sg:`set_gamma_ramp(red, green, blue, /) -> bool` - - DEPRECATED: This functionality will go away in SDL3. - - Set the red, green, and blue gamma ramps with an explicit lookup table. Each - argument should be sequence of 256 integers. The integers should range - between ``0`` and ``0xffff``. Not all systems and hardware support gamma - ramps, if the function succeeds it will return ``True``. - - .. deprecated:: 2.1.4 - - .. ## pygame.display.set_gamma_ramp ## - -.. function:: set_icon - - | :sl:`Change the system image for the display window` - | :sg:`set_icon(surface, /) -> None` - - Sets the runtime icon the system will use to represent the display window. - All windows default to a simple pygame logo for the window icon. - - Note that calling this function implicitly initializes ``pygame.display``, if - it was not initialized before. - - You can pass any surface, but most systems want a smaller image around - 32x32. The image can have colorkey transparency which will be passed to the - system. - - Some systems do not allow the window icon to change after it has been shown. - This function can be called before ``pygame.display.set_mode()`` to create - the icon before the display mode is set. - - .. ## pygame.display.set_icon ## - -.. function:: set_caption - - | :sl:`Set the current window caption` - | :sg:`set_caption(title, icontitle=None, /) -> None` - - If the display has a window title, this function will change the name on the - window. In pygame 1.x, some systems supported an alternate shorter title to - be used for minimized displays, but in pygame 2 ``icontitle`` does nothing. - - .. ## pygame.display.set_caption ## - -.. function:: get_caption - - | :sl:`Get the current window caption` - | :sg:`get_caption() -> (title, icontitle)` - - Returns the title and icontitle of the display window. In pygame 2.x - these will always be the same value. - - .. ## pygame.display.get_caption ## - -.. function:: set_palette - - | :sl:`Set the display color palette for indexed displays` - | :sg:`set_palette(palette=None, /) -> None` - - This will change the video display color palette for 8-bit displays. This - does not change the palette for the actual display Surface, only the palette - that is used to display the Surface. If no palette argument is passed, the - system default palette will be restored. The palette is a sequence of - ``RGB`` triplets. - - .. ## pygame.display.set_palette ## - -.. function:: get_num_displays - - | :sl:`Return the number of displays` - | :sg:`get_num_displays() -> int` - - Returns the number of available displays. This is always 1 if - :func:`pygame.get_sdl_version()` returns a major version number below 2. - - .. versionaddedold:: 1.9.5 - - .. ## pygame.display.get_num_displays ## - -.. function:: get_window_size - - | :sl:`Return the size of the window or screen` - | :sg:`get_window_size() -> tuple` - - Returns the size of the window initialized with :func:`pygame.display.set_mode()`. - This may differ from the size of the display surface if ``SCALED`` is used. - - .. versionaddedold:: 2.0.0 - - .. ## pygame.display.get_window_size ## - -.. function:: get_window_position - - | :sl:`Return the position of the window or screen` - | :sg:`get_window_position() -> tuple` - - Returns the position of the window initialized with :func:`pygame.display.set_mode()`. - The position will change when the user moves the window or when the position is set manually with :func:`pygame.display.set_window_position()`. - Coordinates could be negative or outside the desktop size bounds. - The position is relative to the topleft of the primary monitor and the y coordinate ignores the window frame. - - .. ## pygame.display.get_window_position ## - -.. function:: set_window_position - - | :sl:`Set the current window position` - | :sg:`set_window_position((x, y)) -> None` - - Sets the position of the window initialized with :func:`pygame.display.set_mode()`. - This differs from updating environment variables as this function can be called after the display has been initialised. - The position is expected to be relative to the topleft of the primary monitor. - The y coordinate will ignore the window frame (y = 0 means the frame is hidden). - The user will still be able to move the window after this call. See also :func:`pygame.display.get_window_position()`. - - .. ## pygame.display.set_window_position ## - -.. function:: get_allow_screensaver - - | :sl:`Return whether the screensaver is allowed to run.` - | :sg:`get_allow_screensaver() -> bool` - - Return whether screensaver is allowed to run whilst the app is running. - Default is ``False``. - By default pygame does not allow the screensaver during game play. - - .. note:: Some platforms do not have a screensaver or support - disabling the screensaver. Please see - :func:`pygame.display.set_allow_screensaver()` for - caveats with screensaver support. - - .. versionaddedold:: 2.0.0 - - .. ## pygame.display.get_allow_screensaver ## - -.. function:: set_allow_screensaver - - | :sl:`Set whether the screensaver may run` - | :sg:`set_allow_screensaver(bool) -> None` - - Change whether screensavers should be allowed whilst the app is running. - The default value of the argument to the function is True. - By default pygame does not allow the screensaver during game play. - - If the screensaver has been disallowed due to this function, it will automatically - be allowed to run when :func:`pygame.quit()` is called. - - It is possible to influence the default value via the environment variable - ``SDL_HINT_VIDEO_ALLOW_SCREENSAVER``, which can be set to either ``0`` (disable) - or ``1`` (enable). - - .. note:: Disabling screensaver is subject to platform support. - When platform support is absent, this function will - silently appear to work even though the screensaver state - is unchanged. The lack of feedback is due to SDL not - providing any supported method for determining whether - it supports changing the screensaver state. - - .. versionaddedold:: 2.0.0 - -.. function:: is_fullscreen - - | :sl:`Returns True if the pygame window created by pygame.display.set_mode() is in full-screen mode` - | :sg:`is_fullscreen() -> bool` - - Edge cases: - If the window is in windowed mode, but maximized, this will return `False`. - If the window is in "borderless fullscreen" mode, this will return `True`. - - .. versionadded:: 2.2.0 - -.. function:: is_vsync - - | :sl:`Returns True if vertical synchronisation for pygame.display.flip() and pygame.display.update() is enabled` - | :sg:`is_vsync() -> bool` - - .. versionadded:: 2.2.0 - -.. function:: get_current_refresh_rate() -> int - - | :sl:`Returns the screen refresh rate or 0 if unknown` - | :sg:`get_current_refresh_rate() -> int` - - The screen refresh rate for the current window. In windowed mode, this - should be equal to the refresh rate of the desktop the window is on. - - If no window is open, an exception is raised. - - When a constant refresh rate cannot be determined, 0 is returned. - - .. versionadded:: 2.2.0 - -.. function:: get_desktop_refresh_rates() -> list - - | :sl:`Returns the screen refresh rates for all displays (in windowed mode).` - | :sg:`get_desktop_refresh_rates() -> list` - - If the current window is in full-screen mode, the actual refresh rate for - that window can differ. - - This is safe to call when no window is open (i.e. before any calls to - :func:`pygame.display.set_mode()` - - When a constant refresh rate cannot be determined, 0 is returned for that - desktop. - - - .. versionadded:: 2.2.0 - .. ## pygame.display.set_allow_screensaver ## - -.. function:: message_box - - | :sl:`Create a native GUI message box` - | :sg:`message_box(title, message=None, message_type='info', parent_window=None, buttons=('OK',), return_button=0, escape_button=None) -> int` - - :param str title: A title string. - :param str message: A message string. If this parameter is set to ``None``, the message will be the title. - :param str message_type: Set the type of message_box, could be ``"info"``, ``"warn"`` or ``"error"``. - :param Window parent_window: The parent window of the message box. - :param tuple buttons: An optional sequence of button name strings to show to the user. - :param int return_button: Button index to use if the return key is hit, ``0`` by default. - :param int escape_button: Button index to use if the escape key is hit, ``None`` for no button linked by default. - - :return: The index of the button that was pushed. - - This function should be called on the thread that ``set_mode()`` is called. - It will block execution of that thread until the user clicks a button or - closes the message_box. - - This function may be called at any time, even before ``pygame.init()``. - - Negative values of ``return_button`` and ``escape_button`` are allowed - just like standard Python list indexing. - - .. versionadded:: 2.4.0 - - -.. ## pygame.display ## +.. autopgmodule:: pygame.display + :members: diff --git a/docs/reST/ref/system.rst b/docs/reST/ref/system.rst index de5cb55daf..d2b74addd8 100644 --- a/docs/reST/ref/system.rst +++ b/docs/reST/ref/system.rst @@ -1,194 +1,7 @@ .. include:: common.txt :mod:`pygame.system` -====================== +==================== -.. module:: pygame.system - :synopsis: pygame module to provide additional context about the system - -| :sl:`pygame module to provide additional context about the system` - -.. versionadded:: 2.2.0 - -.. function:: get_cpu_instruction_sets - - | :sl:`get the information of CPU instruction sets` - | :sg:`get_cpu_instruction_sets() -> instruction_sets` - - Returns a dict of the information of CPU instruction sets. The keys of - the dict are the names of instruction sets and the values determine - whether the instruction set is available. - - Some of functions like ``Surface.blit`` can be accelerated by SIMD - instruction sets like SSE2 or AVX2. By checking the availability of - instruction sets, you can check if these accelerations are available. - - Here is an example of the returned dict - :: - - { - 'ALTIVEC': False, - 'MMX': True, - 'SSE': True, - 'SSE2': True, - 'SSE3': True, - 'SSE41': True, - 'SSE42': True, - 'AVX': True, - 'AVX2': True, - 'AVX512F': False, - 'NEON': False, - 'ARMSIMD': False, - 'LSX': False, - 'LASX': False - } - - .. Note:: The values of ``LSX`` and ``LASX`` will be always False if - SDL version < 2.24.0. - - .. versionadded:: 2.3.1 - - .. versionchanged:: 2.4.0 removed ``RDTSC`` key, - as it has been removed in pre-release SDL3 - -.. function:: get_total_ram - - | :sl:`get the amount of RAM configured in the system` - | :sg:`get_total_ram() -> ram_size` - - Returns the amount of RAM configured in the system in MiB. - - .. versionadded:: 2.3.1 - -.. function:: get_pref_path - - | :sl:`get a writeable folder for your app` - | :sg:`get_pref_path(org, app) -> path` - - When distributing apps, it's helpful to have a way to get a writeable path, - because it's what apps are expected to do, and because sometimes the local - space around the app isn't writeable to the app. - - This function returns a platform specific path for your app to store - savegames, settings, and the like. This path is unique per user and - per app name. - - It takes two strings, ``org`` and ``app``, referring to the "organization" - and "application name." For example, the organization could be "Valve," - and the application name could be "Half Life 2." It then will figure out the - preferred path, **creating the folders referenced by the path if necessary**, - and return a string containing the absolute path. - - For example:: - - On Windows, it would resemble - C:\\Users\\bob\\AppData\\Roaming\\My Company\\My Program Name\\ - - On macOS, it would resemble - /Users/bob/Library/Application Support/My Company/My Program Name/ - - And on Linux it would resemble - /home/bob/.local/share/My Company/My Program Name/ - - .. note:: - Since the organization and app names can potentially be used as - a folder name, it is highly encouraged to avoid punctuation. - Instead stick to letters, numbers, and spaces. - - .. note:: - The ``appdirs`` library has similar functionality for this use case, - but has more "folder types" to choose from. - - .. versionadded:: 2.2.0 - -.. function:: get_pref_locales - - | :sl:`get preferred locales set on the system` - | :sg:`get_pref_locales() -> list[locale]` - - Returns a list of "locale" dicts, sorted in descending order of preference - set on the host OS (the most preferred locale is the first element). May - also be an empty list if pygame could not find this information. - - Each "locale" dict contains the language code which can be accessed by the - key ``"language"``. This language code is an ISO-639 language specifier - (such as "en" for English, "de" for German, etc). - A "locale" dict may also optionally contain a ``"country"`` field, whose - value is an ISO-3166 country code (such as "US" for the United States, - "CA" for Canada, etc). If this field is not set or undetermined, it is - ``None``. - A "locale" dict which looks like ``{'language': 'en', 'country': 'US'}`` - indicates the user prefers American English, while - ``{'language': 'en', 'country': None}`` indicates that the user prefers - English, generically. - - This might be a bit of an expensive call because it has to query the OS. So - this function must not be called in a game loop, instead it's best to ask - for this once and save the results. However, this list can change when the - user changes a system preference outside of your program. pygame will send - a ``LOCALECHANGED`` event in this case, if possible, and you can call this - function again to get an updated copy of preferred locales. - - .. versionadded:: 2.2.0 - -.. function:: get_power_state - - | :sl:`get the current power supply state` - | :sg:`get_pref_power_state() -> PowerState` - - **Experimental:** feature available for testing and feedback. - We don't anticipate it changing, but it might if something important - is brought up. `Please leave get_power_state feedback with - authors `_ - - Returns a ``PowerState`` object representing the power supply state. - - Returns ``None`` if the power state is unknown. - - The PowerState object has several attributes: - - .. code-block:: text - - battery_percent: - An integer between 0 and 100, representing the percentage of - battery life left. - - battery_seconds: - An integer, representing the seconds of battery life left. - Could be None if the value is unknown. - - on_battery: - True if the device is running on the battery (not plugged in). - - no_battery: - True if the device has no battery available (plugged in). - - charging: - True if the device is charging battery (plugged in). - - charged: - True if the battery of the device is fully charged (plugged in). - - plugged_in: - True if the device is plugged in. - Equivalent to `not on_battery`. - - has_battery: - True if the device has battery. - Equivalent to `on_battery or not no_battery`. - - - You should never take a battery status as absolute truth. Batteries - (especially failing batteries) are delicate hardware, and the values - reported here are best estimates based on what that hardware reports. It's - not uncommon for older batteries to lose stored power much faster than it - reports, or completely drain when reporting it has 20 percent left, etc. - - Battery status can change at any time; if you are concerned with power - state, you should call this function frequently, and perhaps ignore changes - until they seem to be stable for a few seconds. - - It's possible a platform can only report battery percentage or time left - but not both. - - .. versionadded:: 2.4.0 +.. autopgmodule:: pygame.system + :members: diff --git a/docs/reST/ref/window.rst b/docs/reST/ref/window.rst index b460047bd7..7d751ff871 100644 --- a/docs/reST/ref/window.rst +++ b/docs/reST/ref/window.rst @@ -5,482 +5,5 @@ .. currentmodule:: pygame -.. class:: Window - - | :sl:`pygame object that represents a window` - | :sg:`Window(title='pygame window', size=(640, 480), position=None, fullscreen=False, fullscreen_desktop=False, **kwargs) -> Window` - - The Window class (formerly known as _sdl2.video.Window), is a newly - published feature of pygame-ce 2.5.2. This class allows for programs - to drive multiple windows on-screen at once, something not possible with - the :func:`pygame.display.set_mode` API. Not everything possible with - :mod:`pygame.display` is possible yet in the Window API, but the new - window class will continue to be developed, and we're excited to share - the new functionality this class offers. - - :param str title: The title of the window. - :param (int, int) size: The size of the window, in screen coordinates. - :param (int, int) or int position: A tuple specifying the window position, or - ``WINDOWPOS_CENTERED``, or ``WINDOWPOS_UNDEFINED``. - :param bool fullscreen: Create a fullscreen window using the window size as - the resolution (videomode change). - :param bool fullscreen_desktop: Create a fullscreen window using the current - desktop resolution. - :param bool opengl: Create a window with support for an OpenGL context. - :param bool vulkan: Create a window with support for a Vulkan instance. - :param bool hidden: Create a hidden window. - :param bool borderless: Create a window without borders. - :param bool resizable: Create a resizable window. - :param bool minimized: Create a mimized window. - :param bool maximized: Create a maximized window. - :param bool mouse_grabbed: Create a window with grabbed mouse input. - :param bool keyboard_grabbed: Create a window with grabbed keyboard input. - :param bool input_focus: Create a window with input focus. - :param bool mouse_focus: Create a window with mouse focus. - :param bool allow_high_dpi: Create a window in high-DPI mode if supported. - :param bool mouse_capture: Create a window that has the mouse captured - (unrelated to INPUT_GRABBED). - :param bool always_on_top: Create a window that is always presented above - others. - :param bool utility: Create a window that doesn't appear in the task bar. - - Event behavior if one Window is created: When the close button is pressed, - the ``QUIT`` event will be sent to the event queue. - - .. code-block:: python - - import pygame - - window = pygame.Window() - - while True: - for event in pygame.event.get(): - if event.type == pygame.QUIT: - pygame.quit() - raise SystemExit - - Event behavior if multiple ``Window``\ s are created: When the close button is - pressed, a ``WINDOWCLOSE`` event is sent. You need to explicitly destroy - the window. Note that the event ``QUIT`` will only be sent if all - ``Window``\ s have been destroyed. - - .. code-block:: python - - import pygame - - window1 = pygame.Window(position=(0,100)) - window2 = pygame.Window(position=(700,100)) - - while True: - for event in pygame.event.get(): - if event.type == pygame.WINDOWCLOSE: - id = event.window.id - print(f"WINDOWCLOSE event sent to Window #{id}.") - event.window.destroy() - - if event.type == pygame.QUIT: - print(f"Last window is destroyed. QUIT event was sent.") - pygame.quit() - raise SystemExit - - .. versionadded:: 2.4.0 - .. versionchanged:: 2.5.0 when ``opengl`` is ``True``, the ``Window`` has an OpenGL context created by pygame - .. versionchanged:: 2.5.1 Window is now a base class, allowing subclassing - - - .. attribute:: grab_mouse - - | :sl:`Get or set the window's mouse grab mode` - | :sg:`grab_mouse -> bool` - - When this attribute is set to ``True``, the window will try to confine the mouse - cursor to itself. - - Note this only set the "mode" of grab. The mouse may be confined to another window - depending on the window focus. To get if the mouse is currently restricted to this - window, please use :attr:`mouse_grabbed`. - - .. seealso:: :attr:`mouse_grabbed` - - .. versionadded:: 2.4.0 - - .. attribute:: grab_keyboard - - | :sl:`Get or set the window's keyboard grab mode` - | :sg:`grab_keyboard -> bool` - - When this attribute is set to ``True``, the window will try to capture system - keyboard shortcuts like ``Alt+Tab`` or the ``Meta/Super`` key. - - This attribute only set the "mode" of grab. The keyboard may be captured by - another window depending on the window focus. To get if keyboard is currently - captured by this window, please use :attr:`keyboard_grabbed`. - - Note that not all system keyboard shortcuts can be captured by applications - (one example is ``Ctrl+Alt+Del`` on Windows). - - When keyboard grab is enabled, pygame will continue to handle ``Alt+Tab`` when - the window is full-screen to ensure the user is not trapped in your application. - If you have a custom keyboard shortcut to exit fullscreen mode, you may suppress - this behavior with an environment variable, e.g. - ``os.environ["SDL_ALLOW_ALT_TAB_WHILE_GRABBED"] = "0"``. - - This attribute requires SDL 2.0.16+. - - .. seealso:: :attr:`keyboard_grabbed` - - .. versionadded:: 2.4.0 - - .. attribute:: mouse_grabbed - - | :sl:`Get if the mouse cursor is confined to the window (**read-only**)` - | :sg:`mouse_grabbed -> bool` - - Get if the mouse cursor is currently grabbed and confined to the window. - - Roughly equivalent to this expression: - - :: - - win.grab_mouse and (win is get_grabbed_window()) - - .. seealso:: :attr:`grab_mouse` - - .. versionadded:: 2.4.0 - - .. attribute:: keyboard_grabbed - - | :sl:`Get if the keyboard shortcuts are captured by the window (**read-only**)` - | :sg:`keyboard_grabbed -> bool` - - Get if the keyboard shortcuts are currently grabbed and captured by the window. - - Roughly equivalent to this expression: - - :: - - win.grab_keyboard and (win is get_grabbed_window()) - - This attribute requires SDL 2.0.16+. - - .. seealso:: :attr:`grab_keyboard` - - .. versionadded:: 2.4.0 - - .. attribute:: focused - - | :sl:`Get if the window is focused (**read-only**)` - | :sg:`focused -> bool` - - Get if the window is currently focused. The same result can be achieved using - the ``WINDOWFOCUSGAINED`` and ``WINDOWFOCUSLOST`` events. - - Use :meth:`focus` to focus and raise the window. - - .. versionadded:: 2.5.2 - - .. attribute:: title - - | :sl:`Get or set the window title` - | :sg:`title -> str` - - Gets or sets the window title. An empty string means that no title is set. - - .. attribute:: resizable - - | :sl:`Get or set whether the window is resizable` - | :sg:`resizable -> bool` - - .. attribute:: borderless - - | :sl:`Get or set whether the window is borderless` - | :sg:`borderless -> bool` - - Gets or sets whether the window is borderless. - - .. note:: You can't change the border state of a fullscreen window. - - .. attribute:: always_on_top - - | :sl:`Get or set whether the window is always on top` - | :sg:`always_on_top -> bool` - - Get or set whether the window is always on top. - - Setting the always-on-top mode requires SDL 2.0.16+. - - .. versionadded:: 2.3.1 - - .. attribute:: id - - | :sl:`Get the unique window ID (**read-only**)` - | :sg:`id -> int` - - .. attribute:: mouse_rect - - | :sl:`Get or set the mouse confinement rectangle of the window` - | :sg:`mouse_rect -> Rect|None` - - Setting this attribute to a rect-like object confines the - cursor to the specified area of this window. - - This attribute can be None, meaning that there is no mouse rect. - - Note that this does NOT grab the cursor, it only defines the area a - cursor is restricted to when the window has mouse focus. - - .. versionadded:: 2.4.0 - - .. attribute:: size - - | :sl:`Get or set the window size in pixels` - | :sg:`size -> (int, int)` - - .. attribute:: minimum_size - - | :sl:`Get or set the minimum size of the window's client area` - | :sg:`minimum_size -> (int, int)` - - Initial value in most cases is ``(0, 0)``. If :func:`from_display_module` - was used to create the window and :func:`pygame.display.set_mode` was - called with the ``SCALED`` flag, the initial value is the size used in - that call. - - Raises a ``ValueError`` if negative values are provided or - if the width or height provided are greater than set - maximum width or height respectively. Unless maximum size - is ``(0, 0)`` (initial value). - - .. seealso:: :attr:`maximum_size`. - - .. versionadded:: 2.4.0 - - .. attribute:: maximum_size - - | :sl:`Get or set the maximum size of the window's client area` - | :sg:`maximum_size -> (int, int)` - - Initial value is ``(0, 0)``. - - Raises a ``ValueError`` if negative values are provided or - if the width or height provided are less than set minimum - width or height respectively. - - .. seealso:: :attr:`minimum_size`. - - .. versionadded:: 2.4.0 - - .. attribute:: position - - | :sl:`Get or set the window position in screen coordinates` - | :sg:`position -> (int, int) or WINDOWPOS_CENTERED or WINDOWPOS_UNDEFINED` - - .. attribute:: opacity - - | :sl:`Get or set the window opacity, between 0.0 (fully transparent) and 1.0 (fully opaque)` - | :sg:`opacity -> float` - - .. attribute:: opengl - - | :sl:`Get if the window supports OpenGL` - | :sg:`opengl -> bool` - - ``True`` if the ``Window`` has an OpenGL context associated with it, ``False`` otherwise - - .. versionadded:: 2.5.0 - - .. attribute:: utility - - | :sl:`Get if the window is an utility window (**read-only**)` - | :sg:`utility -> bool` - - ``True`` if the window doesn't appear in the task bar, ``False`` otherwise. - This only works for X11 and Windows, for other platforms, creating ``Window(utility=True)`` won't change anything. - - .. versionadded:: 2.5.3 - - .. classmethod:: from_display_module - - | :sl:`Create a Window object using window data from display module` - | :sg:`from_display_module() -> Window` - - **DON'T USE THIS!** If you want to draw to a surface and use the window - API, use :func:`Window.get_surface` and :func:`Window.flip`. - - Create a Window object that uses the same window data from the :mod:`pygame.display` module, created upon calling - :func:`pygame.display.set_mode`. - - .. deprecated:: 2.4.0 - - .. method:: get_surface - - | :sl:`Get the window surface` - | :sg:`get_surface() -> Surface` - - Returns a "display surface" for this Window. The surface returned is - analogous to the surface returned by :func:`pygame.display.set_mode`. - - This method allows software rendering (classic pygame rendering) on top - of the Window API. This method should not be called when using hardware - rendering (coming soon). - - Similarly to the "display surface" returned by :mod:`pygame.display`, - this surface will change size with the Window, and will become invalid - after the Window's destruction. - - .. seealso:: :func:`flip` - - .. versionadded:: 2.4.0 - - .. method:: flip - - | :sl:`Update the display surface to the window.` - | :sg:`flip() -> None` - - Update pixel data from memory to be displayed in the window. This is the Window - class equivalent of :func:`pygame.display.flip`. - - With ``get_surface()`` this method allows software rendering (classic pygame rendering) flipping pixel data - from an associated surface in memory to be displayed in the window. Alternatively, when this window has an - associated OpenGL context, this method will instead perform a GL buffer swap to the window. - - Here is a runnable example of using ``get_surface`` and ``flip``: - - .. code-block:: python - - import pygame - - win = pygame.Window() - surf = win.get_surface() # get the window surface - - while True: - for event in pygame.event.get(): - if event.type == pygame.QUIT: - pygame.quit() - raise SystemExit - - # draw something on the surface - surf.fill("red") - - win.flip() # update the surface to the window - - - .. versionadded:: 2.4.0 - - .. method:: set_windowed - - | :sl:`Enable windowed mode (exit fullscreen)` - | :sg:`set_windowed() -> None` - - .. seealso:: :func:`set_fullscreen` - - .. method:: set_fullscreen - - | :sl:`Enter fullscreen` - | :sg:`set_fullscreen(desktop=False) -> None` - - :param bool desktop: If ``True``, use the current desktop resolution. - If ``False``, change the fullscreen resolution to the window size. - - .. seealso:: :meth:`set_windowed`. - - .. method:: destroy - - | :sl:`Destroy the window` - | :sg:`destroy() -> None` - - Destroys the internal window data of this Window object. This method is - called automatically when this Window object is garbage collected, so - there usually aren't any reasons to call it manually. - - Other methods that try to manipulate that window data will raise an error. - - .. method:: hide - - | :sl:`Hide the window` - | :sg:`hide() -> None` - - .. method:: show - - | :sl:`Show the window` - | :sg:`show() -> None` - - .. method:: focus - - | :sl:`Set the window to be focused` - | :sg:`focus(input_only=False) -> None` - - Raises the window above other windows and sets the input focus. - - :param bool input_only: if ``True``, the window will be given input focus - but may be completely obscured by other windows. - Only supported on X11. This has been deprecated and - may be removed in a future version. - - .. deprecated:: 2.5.3 ``input_only`` argument - - .. method:: restore - - | :sl:`Restore the size and position of a minimized or maximized window` - | :sg:`restore() -> None` - - .. method:: maximize - - | :sl:`Maximize the window` - | :sg:`maximize() -> None` - - .. method:: minimize - - | :sl:`Minimize the window` - | :sg:`maximize() -> None` - - .. method:: set_icon - - | :sl:`Set the window icon` - | :sg:`set_icon(surface, /) -> None` - - Sets the window icon. - - :param Surface surface: A Surface to use as the icon. - - .. method:: set_modal_for - - | :sl:`Set the window as a modal for a parent window` - | :sg:`set_modal_for(parent, /) -> None` - - :param Window parent: The parent window. - - .. note:: This function is only supported on X11. - - .. method:: flash - - | :sl:`Flash a window to demand attention from the user` - | :sg:`flash(operation, /) -> None` - - :param int operation: The flash operation. - - Supported flash operations are: - * ``pygame.FLASH_CANCEL``: Cancel the current flash state if present - * ``pygame.FLASH_BRIEFLY``: Flash for a short amount of time to get attention - * ``pygame.FLASH_UNTIL_FOCUSED``: Keep flashing until the window is focused - - Window flashing requires SDL 2.0.16+. A :mod:`pygame.error` exception will be raised - otherwise. - - .. note:: This function is only supported on Windows, X11, Wayland and Cocoa (MacOS). - A :mod:`pygame.error` exception will be raised if it's not supported therefore it's - advised to wrap it in a try block. - - .. code-block:: python - - import pygame - window = pygame.Window() - - try: - window.flash(pygame.FLASH_BRIEFLY) - except pygame.error: - print("Window flashing not supported") - - .. versionadded:: 2.5.2 - - .. ## pygame.Window ## +.. autopgclass:: pygame.Window + :members: diff --git a/src_c/doc/display_doc.h b/src_c/doc/display_doc.h index 8e03e368fe..b46a9d30af 100644 --- a/src_c/doc/display_doc.h +++ b/src_c/doc/display_doc.h @@ -1,37 +1,37 @@ /* Auto generated file: with make_docs.py . Docs go in docs/reST/ref/ . */ -#define DOC_DISPLAY "pygame module to control the display window and screen" -#define DOC_DISPLAY_INIT "init() -> None\nInitialize the display module" -#define DOC_DISPLAY_QUIT "quit() -> None\nUninitialize the display module" -#define DOC_DISPLAY_GETINIT "get_init() -> bool\nReturns True if the display module has been initialized" -#define DOC_DISPLAY_SETMODE "set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface\nInitialize a window or screen for display" -#define DOC_DISPLAY_GETSURFACE "get_surface() -> Surface\nget_surface() -> None\nGet a reference to the currently set display surface" -#define DOC_DISPLAY_FLIP "flip() -> None\nUpdate the full display Surface to the screen" -#define DOC_DISPLAY_UPDATE "update() -> None\nupdate(rectangle, /) -> None\nupdate(x, y, w, h, /) -> None\nupdate((x, y), (w, h), /) -> None\nupdate(rectangle_iterable, /) -> None\nUpdate all, or a portion, of the display. For non-OpenGL displays." -#define DOC_DISPLAY_GETDRIVER "get_driver() -> name\nGet the name of the pygame display backend" -#define DOC_DISPLAY_INFO "Info() -> VideoInfo\nCreate a video display information object" -#define DOC_DISPLAY_GETWMINFO "get_wm_info() -> dict\nGet information about the current windowing system" -#define DOC_DISPLAY_GETDESKTOPSIZES "get_desktop_sizes() -> list\nGet sizes of active desktops" -#define DOC_DISPLAY_LISTMODES "list_modes(depth=0, flags=pygame.FULLSCREEN, display=0) -> list\nGet list of available fullscreen modes" -#define DOC_DISPLAY_MODEOK "mode_ok(size, flags=0, depth=0, display=0) -> depth\nPick the best color depth for a display mode" -#define DOC_DISPLAY_GLGETATTRIBUTE "gl_get_attribute(flag, /) -> value\nGet the value for an OpenGL flag for the current display" -#define DOC_DISPLAY_GLSETATTRIBUTE "gl_set_attribute(flag, value, /) -> None\nRequest an OpenGL display attribute for the display mode" -#define DOC_DISPLAY_GETACTIVE "get_active() -> bool\nReturns True when the display is active on the screen" -#define DOC_DISPLAY_ICONIFY "iconify() -> bool\nIconify the display surface" -#define DOC_DISPLAY_TOGGLEFULLSCREEN "toggle_fullscreen() -> int\nSwitch between fullscreen and windowed displays" -#define DOC_DISPLAY_SETGAMMA "set_gamma(red, green=None, blue=None, /) -> bool\nChange the hardware gamma ramps" -#define DOC_DISPLAY_SETGAMMARAMP "set_gamma_ramp(red, green, blue, /) -> bool\nChange the hardware gamma ramps with a custom lookup" -#define DOC_DISPLAY_SETICON "set_icon(surface, /) -> None\nChange the system image for the display window" -#define DOC_DISPLAY_SETCAPTION "set_caption(title, icontitle=None, /) -> None\nSet the current window caption" -#define DOC_DISPLAY_GETCAPTION "get_caption() -> (title, icontitle)\nGet the current window caption" -#define DOC_DISPLAY_SETPALETTE "set_palette(palette=None, /) -> None\nSet the display color palette for indexed displays" -#define DOC_DISPLAY_GETNUMDISPLAYS "get_num_displays() -> int\nReturn the number of displays" -#define DOC_DISPLAY_GETWINDOWSIZE "get_window_size() -> tuple\nReturn the size of the window or screen" -#define DOC_DISPLAY_GETWINDOWPOSITION "get_window_position() -> tuple\nReturn the position of the window or screen" -#define DOC_DISPLAY_SETWINDOWPOSITION "set_window_position((x, y)) -> None\nSet the current window position" +#define DOC_DISPLAY "Pygame module to control the display window and screen." +#define DOC_DISPLAY_INIT "init() -> None\nInitialize the display module." +#define DOC_DISPLAY_QUIT "quit() -> None\nUninitialize the display module." +#define DOC_DISPLAY_GETINIT "get_init() -> bool\nReturns True if the display module has been initialized." +#define DOC_DISPLAY_SETMODE "set_mode(size=(0, 0), flags=0, depth=0, display=0, vsync=0) -> Surface\nInitialize a window or screen for display." +#define DOC_DISPLAY_GETSURFACE "get_surface() -> Optional[Surface]\nGet a reference to the currently set display surface." +#define DOC_DISPLAY_FLIP "flip() -> None\nUpdate the full display Surface to the screen." +#define DOC_DISPLAY_UPDATE "update() -> None\nupdate(rectangle, /) -> None\nupdate(x, y, w, h, /) -> None\nupdate(xy, wh, /) -> None\nUpdate all, or a portion, of the display. For non-OpenGL displays." +#define DOC_DISPLAY_GETDRIVER "get_driver() -> str\nGet the name of the pygame display backend." +#define DOC_DISPLAY_INFO "Info() -> _VidInfo\nCreate a video display information object." +#define DOC_DISPLAY_GETWMINFO "get_wm_info() -> dict[str, int]\nGet information about the current windowing system." +#define DOC_DISPLAY_GETDESKTOPSIZES "get_desktop_sizes() -> list[tuple[int, int]]\nGet sizes of active desktops." +#define DOC_DISPLAY_LISTMODES "list_modes(depth=0, flags=FULLSCREEN, display=0) -> list[tuple[int, int]]\nGet list of available fullscreen modes." +#define DOC_DISPLAY_MODEOK "mode_ok(size, flags=0, depth=0, display=0) -> int\nPick the best color depth for a display mode." +#define DOC_DISPLAY_GLGETATTRIBUTE "gl_get_attribute(flag, /) -> int\nGet the value for an OpenGL flag for the current display." +#define DOC_DISPLAY_GLSETATTRIBUTE "gl_set_attribute(flag, value, /) -> None\nRequest an OpenGL display attribute for the display mode." +#define DOC_DISPLAY_GETACTIVE "get_active() -> bool\nReturns True when the display is active on the screen." +#define DOC_DISPLAY_ICONIFY "iconify() -> bool\nIconify the display surface." +#define DOC_DISPLAY_TOGGLEFULLSCREEN "toggle_fullscreen() -> int\nSwitch between fullscreen and windowed displays." +#define DOC_DISPLAY_SETGAMMA "set_gamma(red, green=..., blue=..., /) -> int\nChange the hardware gamma ramps." +#define DOC_DISPLAY_SETGAMMARAMP "set_gamma_ramp(red, green, blue, /) -> int\nChange the hardware gamma ramps with a custom lookup." +#define DOC_DISPLAY_SETICON "set_icon(surface, /) -> None\nChange the system image for the display window." +#define DOC_DISPLAY_SETCAPTION "set_caption(title, icontitle=None, /) -> None\nSet the current window caption." +#define DOC_DISPLAY_GETCAPTION "get_caption() -> tuple[str, str]\nGet the current window caption." +#define DOC_DISPLAY_SETPALETTE "set_palette(palette, /) -> None\nSet the display color palette for indexed displays." +#define DOC_DISPLAY_GETNUMDISPLAYS "get_num_displays() -> int\nReturn the number of displays." +#define DOC_DISPLAY_GETWINDOWSIZE "get_window_size() -> tuple[int, int]\nReturn the size of the window or screen." +#define DOC_DISPLAY_GETWINDOWPOSITION "get_window_position() -> tuple[int, int]\nReturn the position of the window or screen." +#define DOC_DISPLAY_SETWINDOWPOSITION "set_window_position(position) -> None\nSet the current window position." #define DOC_DISPLAY_GETALLOWSCREENSAVER "get_allow_screensaver() -> bool\nReturn whether the screensaver is allowed to run." -#define DOC_DISPLAY_SETALLOWSCREENSAVER "set_allow_screensaver(bool) -> None\nSet whether the screensaver may run" -#define DOC_DISPLAY_ISFULLSCREEN "is_fullscreen() -> bool\nReturns True if the pygame window created by pygame.display.set_mode() is in full-screen mode" -#define DOC_DISPLAY_ISVSYNC "is_vsync() -> bool\nReturns True if vertical synchronisation for pygame.display.flip() and pygame.display.update() is enabled" -#define DOC_DISPLAY_GETCURRENTREFRESHRATE "get_current_refresh_rate() -> int\nReturns the screen refresh rate or 0 if unknown" -#define DOC_DISPLAY_GETDESKTOPREFRESHRATES "get_desktop_refresh_rates() -> list\nReturns the screen refresh rates for all displays (in windowed mode)." -#define DOC_DISPLAY_MESSAGEBOX "message_box(title, message=None, message_type='info', parent_window=None, buttons=('OK',), return_button=0, escape_button=None) -> int\nCreate a native GUI message box" +#define DOC_DISPLAY_SETALLOWSCREENSAVER "set_allow_screensaver(value=True) -> None\nSet whether the screensaver may run." +#define DOC_DISPLAY_ISFULLSCREEN "is_fullscreen() -> bool\nReturns True if the pygame window created by pygame.display.set_mode() is in full-screen mode." +#define DOC_DISPLAY_ISVSYNC "is_vsync() -> bool\nReturns True if vertical synchronisation for pygame.display.flip() and pygame.display.update() is enabled." +#define DOC_DISPLAY_GETCURRENTREFRESHRATE "get_current_refresh_rate() -> int\nReturns the screen refresh rate or 0 if unknown." +#define DOC_DISPLAY_GETDESKTOPREFRESHRATES "get_desktop_refresh_rates() -> list[int]\nReturns the screen refresh rates for all displays (in windowed mode)." +#define DOC_DISPLAY_MESSAGEBOX "message_box(title, message=None, message_type='info', parent_window=None, buttons=('OK', ), return_button=0, escape_button=None) -> int\nCreate a native GUI message box." diff --git a/src_c/doc/system_doc.h b/src_c/doc/system_doc.h index 37f7775509..449f7defbe 100644 --- a/src_c/doc/system_doc.h +++ b/src_c/doc/system_doc.h @@ -1,7 +1,7 @@ /* Auto generated file: with make_docs.py . Docs go in docs/reST/ref/ . */ -#define DOC_SYSTEM "pygame module to provide additional context about the system" -#define DOC_SYSTEM_GETCPUINSTRUCTIONSETS "get_cpu_instruction_sets() -> instruction_sets\nget the information of CPU instruction sets" -#define DOC_SYSTEM_GETTOTALRAM "get_total_ram() -> ram_size\nget the amount of RAM configured in the system" -#define DOC_SYSTEM_GETPREFPATH "get_pref_path(org, app) -> path\nget a writeable folder for your app" -#define DOC_SYSTEM_GETPREFLOCALES "get_pref_locales() -> list[locale]\nget preferred locales set on the system" -#define DOC_SYSTEM_GETPOWERSTATE "get_pref_power_state() -> PowerState\nget the current power supply state" +#define DOC_SYSTEM "Pygame module to provide additional context about the system." +#define DOC_SYSTEM_GETCPUINSTRUCTIONSETS "get_cpu_instruction_sets() -> _InstructionSets\nGet the information of CPU instruction sets." +#define DOC_SYSTEM_GETTOTALRAM "get_total_ram() -> int\nGet the amount of RAM configured in the system." +#define DOC_SYSTEM_GETPREFPATH "get_pref_path(org, app) -> str\nGet a writeable folder for your app." +#define DOC_SYSTEM_GETPREFLOCALES "get_pref_locales() -> list[_Locale]\nGet preferred locales set on the system." +#define DOC_SYSTEM_GETPOWERSTATE "get_power_state() -> Optional[PowerState]\nGet the current power supply state." diff --git a/src_c/doc/window_doc.h b/src_c/doc/window_doc.h index 8a1063a54b..665780a618 100644 --- a/src_c/doc/window_doc.h +++ b/src_c/doc/window_doc.h @@ -1,35 +1,35 @@ /* Auto generated file: with make_docs.py . Docs go in docs/reST/ref/ . */ -#define DOC_WINDOW "Window(title='pygame window', size=(640, 480), position=None, fullscreen=False, fullscreen_desktop=False, **kwargs) -> Window\npygame object that represents a window" -#define DOC_WINDOW_GRABMOUSE "grab_mouse -> bool\nGet or set the window's mouse grab mode" -#define DOC_WINDOW_GRABKEYBOARD "grab_keyboard -> bool\nGet or set the window's keyboard grab mode" -#define DOC_WINDOW_MOUSEGRABBED "mouse_grabbed -> bool\nGet if the mouse cursor is confined to the window (**read-only**)" -#define DOC_WINDOW_KEYBOARDGRABBED "keyboard_grabbed -> bool\nGet if the keyboard shortcuts are captured by the window (**read-only**)" -#define DOC_WINDOW_FOCUSED "focused -> bool\nGet if the window is focused (**read-only**)" -#define DOC_WINDOW_TITLE "title -> str\nGet or set the window title" -#define DOC_WINDOW_RESIZABLE "resizable -> bool\nGet or set whether the window is resizable" -#define DOC_WINDOW_BORDERLESS "borderless -> bool\nGet or set whether the window is borderless" -#define DOC_WINDOW_ALWAYSONTOP "always_on_top -> bool\nGet or set whether the window is always on top" -#define DOC_WINDOW_ID "id -> int\nGet the unique window ID (**read-only**)" -#define DOC_WINDOW_MOUSERECT "mouse_rect -> Rect|None\nGet or set the mouse confinement rectangle of the window" -#define DOC_WINDOW_SIZE "size -> (int, int)\nGet or set the window size in pixels" -#define DOC_WINDOW_MINIMUMSIZE "minimum_size -> (int, int)\nGet or set the minimum size of the window's client area" -#define DOC_WINDOW_MAXIMUMSIZE "maximum_size -> (int, int)\nGet or set the maximum size of the window's client area" -#define DOC_WINDOW_POSITION "position -> (int, int) or WINDOWPOS_CENTERED or WINDOWPOS_UNDEFINED\nGet or set the window position in screen coordinates" -#define DOC_WINDOW_OPACITY "opacity -> float\nGet or set the window opacity, between 0.0 (fully transparent) and 1.0 (fully opaque)" -#define DOC_WINDOW_OPENGL "opengl -> bool\nGet if the window supports OpenGL" -#define DOC_WINDOW_UTILITY "utility -> bool\nGet if the window is an utility window (**read-only**)" -#define DOC_WINDOW_FROMDISPLAYMODULE "from_display_module() -> Window\nCreate a Window object using window data from display module" -#define DOC_WINDOW_GETSURFACE "get_surface() -> Surface\nGet the window surface" +#define DOC_WINDOW "Window(title='pygame window', size=(640, 480), position=WINDOWPOS_UNDEFINED, **flags) -> Window\nPygame object that represents a window." +#define DOC_WINDOW_GRABMOUSE "grab_mouse -> bool\nGet or set the window's mouse grab mode." +#define DOC_WINDOW_GRABKEYBOARD "grab_keyboard -> bool\nGet or set the window's keyboard grab mode." +#define DOC_WINDOW_MOUSEGRABBED "mouse_grabbed() -> bool\nGet if the mouse cursor is confined to the window (**read-only**)." +#define DOC_WINDOW_KEYBOARDGRABBED "keyboard_grabbed() -> bool\nGet if the keyboard shortcuts are captured by the window (**read-only**)." +#define DOC_WINDOW_FOCUSED "focused() -> bool\nGet if the window is focused (**read-only**)." +#define DOC_WINDOW_TITLE "title -> str\nGet or set the window title." +#define DOC_WINDOW_RESIZABLE "resizable -> bool\nGet or set whether the window is resizable." +#define DOC_WINDOW_BORDERLESS "borderless -> bool\nGets or sets whether the window is borderless." +#define DOC_WINDOW_ALWAYSONTOP "always_on_top -> bool\nGet or set whether the window is always on top." +#define DOC_WINDOW_ID "id() -> int\nGet the unique window ID (**read-only**)." +#define DOC_WINDOW_MOUSERECT "mouse_rect() -> Optional[Rect]\nGet or set the mouse confinement rectangle of the window." +#define DOC_WINDOW_SIZE "size() -> tuple[int, int]\nGet or set the window size in pixels." +#define DOC_WINDOW_MINIMUMSIZE "minimum_size() -> tuple[int, int]\nGet or set the minimum size of the window's client area." +#define DOC_WINDOW_MAXIMUMSIZE "maximum_size() -> tuple[int, int]\nGet or set the maximum size of the window's client area." +#define DOC_WINDOW_POSITION "position() -> tuple[int, int]\nGet or set the window position in screen coordinates." +#define DOC_WINDOW_OPACITY "opacity -> float\nGet or set the window opacity, between 0.0 (fully transparent) and 1.0 (fully opaque)." +#define DOC_WINDOW_OPENGL "opengl() -> bool\nGet if the window supports OpenGL." +#define DOC_WINDOW_UTILITY "utility() -> bool\nGet if the window is an utility window (**read-only**)." +#define DOC_WINDOW_FROMDISPLAYMODULE "from_display_module() -> Window\nCreate a Window object using window data from display module." +#define DOC_WINDOW_GETSURFACE "get_surface() -> Surface\nGet the window surface." #define DOC_WINDOW_FLIP "flip() -> None\nUpdate the display surface to the window." -#define DOC_WINDOW_SETWINDOWED "set_windowed() -> None\nEnable windowed mode (exit fullscreen)" -#define DOC_WINDOW_SETFULLSCREEN "set_fullscreen(desktop=False) -> None\nEnter fullscreen" -#define DOC_WINDOW_DESTROY "destroy() -> None\nDestroy the window" -#define DOC_WINDOW_HIDE "hide() -> None\nHide the window" -#define DOC_WINDOW_SHOW "show() -> None\nShow the window" -#define DOC_WINDOW_FOCUS "focus(input_only=False) -> None\nSet the window to be focused" -#define DOC_WINDOW_RESTORE "restore() -> None\nRestore the size and position of a minimized or maximized window" -#define DOC_WINDOW_MAXIMIZE "maximize() -> None\nMaximize the window" -#define DOC_WINDOW_MINIMIZE "maximize() -> None\nMinimize the window" -#define DOC_WINDOW_SETICON "set_icon(surface, /) -> None\nSet the window icon" -#define DOC_WINDOW_SETMODALFOR "set_modal_for(parent, /) -> None\nSet the window as a modal for a parent window" -#define DOC_WINDOW_FLASH "flash(operation, /) -> None\nFlash a window to demand attention from the user" +#define DOC_WINDOW_SETWINDOWED "set_windowed() -> None\nEnable windowed mode (exit fullscreen)." +#define DOC_WINDOW_SETFULLSCREEN "set_fullscreen(desktop=False) -> None\nEnter fullscreen." +#define DOC_WINDOW_DESTROY "destroy() -> None\nDestroy the window." +#define DOC_WINDOW_HIDE "hide() -> None\nHide the window." +#define DOC_WINDOW_SHOW "show() -> None\nShow the window." +#define DOC_WINDOW_FOCUS "focus(input_only=False) -> None\nSet the window to be focused." +#define DOC_WINDOW_RESTORE "restore() -> None\nRestore the size and position of a minimized or maximized window." +#define DOC_WINDOW_MAXIMIZE "maximize() -> None\nMaximize the window." +#define DOC_WINDOW_MINIMIZE "minimize() -> None\nMinimize the window." +#define DOC_WINDOW_SETICON "set_icon(icon, /) -> None\nSet the window icon." +#define DOC_WINDOW_SETMODALFOR "set_modal_for(parent, /) -> None\nSet the window as a modal for a parent window." +#define DOC_WINDOW_FLASH "flash(operation, /) -> None\nFlash a window to demand attention from the user."