Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate reST/ref docs from python or stub files, move time and cursors docs #3188

Merged
merged 11 commits into from
Dec 31, 2024
2 changes: 1 addition & 1 deletion .github/workflows/build-debian-multiarch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ env:
apt-get install libsdl2-dev libsdl2-image-dev libsdl2-mixer-dev libsdl2-ttf-dev -y
apt-get install libfreetype6-dev libportmidi-dev fontconfig -y
apt-get install python3-dev python3-pip python3-wheel python3-sphinx -y
pip3 install meson-python --break-system-packages
pip3 install meson-python "sphinx-autoapi<=3.3.2" --break-system-packages

jobs:
build-multiarch:
Expand Down
2 changes: 2 additions & 0 deletions buildconfig/stubs/gen_stubs.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ def get_all(mod: Any):
f.write(misc_stubs)

for mod, items in pygame_all_imports.items():
if mod == "pygame":
mod = "."
if len(items) <= 4:
# try to write imports in a single line if it can fit the line limit
import_items = (f"{string} as {string}" for string in items)
Expand Down
2 changes: 1 addition & 1 deletion buildconfig/stubs/pygame/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# A script to auto-generate locals.pyi, constants.pyi and __init__.pyi typestubs
# IMPORTANT NOTE: Do not edit this file by hand!

from pygame import (
from . import (
display as display,
draw as draw,
event as event,
Expand Down
146 changes: 137 additions & 9 deletions buildconfig/stubs/pygame/time.pyi
Original file line number Diff line number Diff line change
@@ -1,15 +1,143 @@
"""Pygame module for monitoring time.

Times in pygame are represented in milliseconds (1/1000 seconds). Most
platforms have a limited time resolution of around 10 milliseconds. This
resolution, in milliseconds, is given in the ``TIMER_RESOLUTION`` constant.
"""

from typing import Union, final

from pygame.event import Event

def get_ticks() -> int: ...
def wait(milliseconds: int, /) -> int: ...
def delay(milliseconds: int, /) -> int: ...
def set_timer(event: Union[int, Event], millis: int, loops: int = 0) -> None: ...
def get_ticks() -> int:
"""Get the time in milliseconds.

Return the number of milliseconds since ``pygame.init()`` was called. Before
pygame is initialized this will always be 0.
"""

def wait(milliseconds: int, /) -> int:
"""Pause the program for an amount of time.

Will pause for a given number of milliseconds. This function sleeps the
process to share the processor with other programs. A program that waits for
even a few milliseconds will consume very little processor time. It is
slightly less accurate than the ``pygame.time.delay()`` function.

This returns the actual number of milliseconds used.
"""

def delay(milliseconds: int, /) -> int:
"""Pause the program for an amount of time.

Will pause for a given number of milliseconds. This function will use the
processor (rather than sleeping) in order to make the delay more accurate
than ``pygame.time.wait()``.

This returns the actual number of milliseconds used.
"""

def set_timer(event: Union[int, Event], millis: int, loops: int = 0) -> None:
"""Repeatedly create an event on the event queue.

Set an event to appear on the event queue every given number of milliseconds.
The first event will not appear until the amount of time has passed.

The ``event`` attribute can be a ``pygame.event.Event`` object or an integer
type that denotes an event.

``loops`` is an integer that denotes the number of events posted. If 0 (default)
then the events will keep getting posted, unless explicitly stopped.

To disable the timer for such an event, call the function again with the same
event argument with ``millis`` argument set to 0.

It is also worth mentioning that a particular event type can only be put on a
timer once. In other words, there cannot be two timers for the same event type.
Setting an event timer for a particular event discards the old one for that
event type.

When this function is called with an ``Event`` object, the event(s) received
on the event queue will be a shallow copy; the dict attribute of the event
object passed as an argument and the dict attributes of the event objects
received on timer will be references to the same dict object in memory.
Modifications on one dict can affect another, use deepcopy operations on the
dict object if you don't want this behaviour.
However, calling this function with an integer event type would place event objects
on the queue that don't have a common dict reference.

``loops`` replaces the ``once`` argument, and this does not break backward
compatibility.

.. versionaddedold:: 2.0.0.dev3 once argument added.
.. versionchangedold:: 2.0.1 event argument supports ``pygame.event.Event`` object
.. versionaddedold:: 2.0.1 added loops argument to replace once argument
"""

@final
class Clock:
def tick(self, framerate: float = 0, /) -> int: ...
def tick_busy_loop(self, framerate: float = 0, /) -> int: ...
def get_time(self) -> int: ...
def get_rawtime(self) -> int: ...
def get_fps(self) -> float: ...
"""Create an object to help track time.

Creates a new Clock object that can be used to track an amount of time. The
clock also provides several functions to help control a game's framerate.

.. versionchanged:: 2.1.4 This class is also available through the ``pygame.Clock``
alias.
"""

def __new__(cls) -> Clock: ...
def tick(self, framerate: float = 0, /) -> int:
"""Update the clock.

This method should be called once per frame. It will compute how many
milliseconds have passed since the previous call.

If you pass the optional framerate argument the function will delay to
keep the game running slower than the given ticks per second. This can be
used to help limit the runtime speed of a game. By calling
``Clock.tick(40)`` once per frame, the program will never run at more
than 40 frames per second.

Note that this function uses SDL_Delay function which is not accurate on
every platform, but does not use much CPU. Use tick_busy_loop if you want
an accurate timer, and don't mind chewing CPU.
"""

def tick_busy_loop(self, framerate: float = 0, /) -> int:
"""Update the clock.

This method should be called once per frame. It will compute how many
milliseconds have passed since the previous call.

If you pass the optional framerate argument the function will delay to
keep the game running slower than the given ticks per second. This can be
used to help limit the runtime speed of a game. By calling
``Clock.tick_busy_loop(40)`` once per frame, the program will never run at
more than 40 frames per second.

Note that this function uses :func:`pygame.time.delay`, which uses lots
of CPU in a busy loop to make sure that timing is more accurate.

.. versionaddedold:: 1.8
"""

def get_time(self) -> int:
"""Time used in the previous tick.

The number of milliseconds that passed between the previous two calls to
``Clock.tick()``.
"""

def get_rawtime(self) -> int:
"""Actual time used in the previous tick.

Similar to ``Clock.get_time()``, but does not include any time used
while ``Clock.tick()`` was delaying to limit the framerate.
"""

def get_fps(self) -> float:
"""Compute the clock framerate.

Compute your game's framerate (in frames per second). It is computed by
averaging the last ten calls to ``Clock.tick()``.
"""
19 changes: 15 additions & 4 deletions docs/reST/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys, os
import sys, os, pathlib

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
Expand All @@ -23,11 +23,22 @@

# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest',
'sphinx.ext.coverage', 'ext.headers', 'ext.boilerplate',
'ext.customversion', 'ext.edit_on_github']
extensions = ['autoapi.extension', 'ext.headers', 'ext.boilerplate',
'ext.customversion', 'ext.edit_on_github', 'ext.documenters']


autoapi_dirs = [
pathlib.Path('.').resolve().parent.parent / 'buildconfig' / 'stubs' / 'pygame',
pathlib.Path('.').resolve().parent.parent / 'src_py',
]

autoapi_options = ['members', 'undoc-members']
autoapi_ignore = ["*controller.py", "*_sdl2/window.py", "*freetype.py", "*ftfont.py", "*__pyinstaller*", "*__init__.py", "*__briefcase*"]
autoapi_generate_api_docs = False
autodoc_typehints = 'none'
suppress_warnings = ['autoapi.python_import_resolution']
autodoc_member_order = 'bysource'

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

Expand Down
136 changes: 136 additions & 0 deletions docs/reST/ext/documenters.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import autoapi
import autoapi.documenters
from autoapi._objects import PythonClass


def build_signatures(object):
name = object.short_name

if isinstance(object, PythonClass):
if object.constructor is not None:
object = object.constructor
object.obj["return_annotation"] = name
object.obj["overloads"] = [
(arg, name) for arg, _ in object.obj["overloads"]
]

else:
for child in object.children:
if child.short_name == "__new__":
object = child
break

if object is None or object.obj.get("args", None) is None:
return

sigs = [(object.obj["args"], object.obj["return_annotation"])]
sigs.extend(object.obj["overloads"])

for args, ret in sigs:
arg_string = ""
for modifier, arg_name, _, default in args:
modifier = modifier or ""
arg_name = arg_name or ""
default = default or ""

if default:
default = "=" + default
arg_string += f", {modifier}{arg_name}{default}"

if arg_string:
arg_string = arg_string[2:]

if ret.count("[") > 2 or ret.count(",") > 3:
ret = ret.split("[")[0]
if ret in ("Optional", "Union"):
ret = "..."

yield f"| :sg:`{name}({arg_string}) -> {ret}`"


def get_doc(env, obj):
if obj.docstring:
return obj.docstring

# If we don't already have docs, check if a python implementation exists of this
# module and return its docstring if it does
python_object = env.autoapi_all_objects.get(
obj.id.replace("pygame", "src_py"), None
)
if python_object is not None:
return python_object.docstring

return ""


class AutopgDocumenter(autoapi.documenters.AutoapiDocumenter):
def format_signature(self, **kwargs):
return ""

def get_doc(self, encoding=None, ignore=1):
return [get_doc(self.env, self.object).splitlines()]

def add_directive_header(self, sig: str) -> None:
super().add_directive_header(sig)
if "module" in self.objtype:
sourcename = self.get_sourcename()
self.add_line(f" :synopsis: {self.get_doc()[0][0]}", sourcename)

def get_object_members(self, want_all):
members_check_module, members = super().get_object_members(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) != ""
)

return members_check_module, members

def process_doc(self, docstrings):
for docstring in docstrings:
if not docstring:
continue

yield f"| :sl:`{docstring[0]}`"

if "args" in self.object.obj or hasattr(self.object, "constructor"):
yield from build_signatures(self.object)
else:
annotation = self.object.obj.get("annotation", None)
if annotation is not None:
if annotation.count("[") > 2 or annotation.count(",") > 3:
annotation = "..."
yield f"| :sg:`{self.object.short_name} -> {annotation}`"

yield from docstring[1:]

yield ""


def setup(app):
names = [
"function",
"property",
"decorator",
"class",
"method",
"data",
"attribute",
"module",
"exception",
]

for name in names:
capitalized = name.capitalize()
app.add_autodocumenter(
type(
f"Autopg{capitalized}Documenter",
(
AutopgDocumenter,
getattr(autoapi.documenters, f"Autoapi{capitalized}Documenter"),
),
{"objtype": f"pg{name}"},
)
)
2 changes: 1 addition & 1 deletion docs/reST/ext/indexer.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,6 @@ def collect_document_info(app, doctree):


class CollectInfo(Visitor):

"""Records the information for a document"""

desctypes = {
Expand All @@ -74,6 +73,7 @@ class CollectInfo(Visitor):
"exception",
"class",
"attribute",
"property",
"method",
"staticmethod",
"classmethod",
Expand Down
Loading
Loading