This commit is contained in:
Anna Śmigiel 2022-04-01 19:21:56 +02:00
parent 4d5981b238
commit 684d7d9289
2208 changed files with 238 additions and 421141 deletions

238
.gitignore vendored Normal file
View File

@ -0,0 +1,238 @@
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
.Python
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
.venv
pip-selfcheck.json
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
.idea/

8
.idea/.gitignore vendored
View File

@ -1,8 +0,0 @@
# Default ignored files
/shelf/
/workspace.xml
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
# Editor-based HTTP Client requests
/httpRequests/

View File

@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/venv" />
</content>
<orderEntry type="jdk" jdkName="Python 3.9" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>

View File

@ -1,6 +0,0 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>

View File

@ -1,4 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
</project>

View File

@ -1,8 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/AI_wozek_widlowy.iml" filepath="$PROJECT_DIR$/.idea/AI_wozek_widlowy.iml" />
</modules>
</component>
</project>

View File

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -1,26 +0,0 @@
/*
pygame - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _CAMERA_H
#define _CAMERA_H
#include "_pygame.h"
#include "camera.h"
#endif

View File

@ -1,326 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* This will use PYGAMEAPI_EXTERN_SLOTS instead
* of PYGAMEAPI_DEFINE_SLOTS for base modules.
*/
#ifndef _PYGAME_INTERNAL_H
#define _PYGAME_INTERNAL_H
#include "pgplatform.h"
/*
If PY_SSIZE_T_CLEAN is defined before including Python.h, length is a
Py_ssize_t rather than an int for all # variants of formats (s#, y#, etc.)
*/
#define PY_SSIZE_T_CLEAN
#include <Python.h>
/* Ensure PyPy-specific code is not in use when running on GraalPython (PR
* #2580) */
#if defined(GRAALVM_PYTHON) && defined(PYPY_VERSION)
#undef PYPY_VERSION
#endif
#include <SDL.h>
/* SDL 1.2 constants removed from SDL 2 */
typedef enum {
SDL_HWSURFACE = 0,
SDL_RESIZABLE = SDL_WINDOW_RESIZABLE,
SDL_ASYNCBLIT = 0,
SDL_OPENGL = SDL_WINDOW_OPENGL,
SDL_OPENGLBLIT = 0,
SDL_ANYFORMAT = 0,
SDL_HWPALETTE = 0,
SDL_DOUBLEBUF = 0,
SDL_FULLSCREEN = SDL_WINDOW_FULLSCREEN,
SDL_HWACCEL = 0,
SDL_SRCCOLORKEY = 0,
SDL_RLEACCELOK = 0,
SDL_SRCALPHA = 0,
SDL_NOFRAME = SDL_WINDOW_BORDERLESS,
SDL_GL_SWAP_CONTROL = 0,
TIMER_RESOLUTION = 0
} PygameVideoFlags;
/* the wheel button constants were removed from SDL 2 */
typedef enum {
PGM_BUTTON_LEFT = SDL_BUTTON_LEFT,
PGM_BUTTON_RIGHT = SDL_BUTTON_RIGHT,
PGM_BUTTON_MIDDLE = SDL_BUTTON_MIDDLE,
PGM_BUTTON_WHEELUP = 4,
PGM_BUTTON_WHEELDOWN = 5,
PGM_BUTTON_X1 = SDL_BUTTON_X1 + 2,
PGM_BUTTON_X2 = SDL_BUTTON_X2 + 2,
PGM_BUTTON_KEEP = 0x80
} PygameMouseFlags;
typedef enum {
/* Any SDL_* events here are for backward compatibility. */
SDL_NOEVENT = 0,
SDL_ACTIVEEVENT = SDL_USEREVENT,
SDL_VIDEORESIZE,
SDL_VIDEOEXPOSE,
PGE_MIDIIN,
PGE_MIDIOUT,
PGE_KEYREPEAT, /* Special internal pygame event, for managing key-presses
*/
/* DO NOT CHANGE THE ORDER OF EVENTS HERE */
PGE_WINDOWSHOWN,
PGE_WINDOWHIDDEN,
PGE_WINDOWEXPOSED,
PGE_WINDOWMOVED,
PGE_WINDOWRESIZED,
PGE_WINDOWSIZECHANGED,
PGE_WINDOWMINIMIZED,
PGE_WINDOWMAXIMIZED,
PGE_WINDOWRESTORED,
PGE_WINDOWENTER,
PGE_WINDOWLEAVE,
PGE_WINDOWFOCUSGAINED,
PGE_WINDOWFOCUSLOST,
PGE_WINDOWCLOSE,
PGE_WINDOWTAKEFOCUS,
PGE_WINDOWHITTEST,
/* Here we define PGPOST_* events, events that act as a one-to-one
* proxy for SDL events (and some extra events too!), the proxy is used
* internally when pygame users use event.post()
*
* At a first glance, these may look redundant, but they are really
* important, especially with event blocking. If proxy events are
* not there, blocked events dont make it to our event filter, and
* that can break a lot of stuff.
*
* IMPORTANT NOTE: Do not post events directly with these proxy types,
* use the appropriate functions from event.c, that handle these proxy
* events for you.
* Proxy events are for internal use only */
PGPOST_EVENTBEGIN, /* mark start of proxy-events */
PGPOST_ACTIVEEVENT = PGPOST_EVENTBEGIN,
PGPOST_AUDIODEVICEADDED,
PGPOST_AUDIODEVICEREMOVED,
PGPOST_CONTROLLERAXISMOTION,
PGPOST_CONTROLLERBUTTONDOWN,
PGPOST_CONTROLLERBUTTONUP,
PGPOST_CONTROLLERDEVICEADDED,
PGPOST_CONTROLLERDEVICEREMOVED,
PGPOST_CONTROLLERDEVICEREMAPPED,
PGPOST_CONTROLLERTOUCHPADDOWN,
PGPOST_CONTROLLERTOUCHPADMOTION,
PGPOST_CONTROLLERTOUCHPADUP,
PGPOST_DOLLARGESTURE,
PGPOST_DOLLARRECORD,
PGPOST_DROPFILE,
PGPOST_DROPTEXT,
PGPOST_DROPBEGIN,
PGPOST_DROPCOMPLETE,
PGPOST_FINGERMOTION,
PGPOST_FINGERDOWN,
PGPOST_FINGERUP,
PGPOST_KEYDOWN,
PGPOST_KEYUP,
PGPOST_JOYAXISMOTION,
PGPOST_JOYBALLMOTION,
PGPOST_JOYHATMOTION,
PGPOST_JOYBUTTONDOWN,
PGPOST_JOYBUTTONUP,
PGPOST_JOYDEVICEADDED,
PGPOST_JOYDEVICEREMOVED,
PGPOST_MIDIIN,
PGPOST_MIDIOUT,
PGPOST_MOUSEMOTION,
PGPOST_MOUSEBUTTONDOWN,
PGPOST_MOUSEBUTTONUP,
PGPOST_MOUSEWHEEL,
PGPOST_MULTIGESTURE,
PGPOST_NOEVENT,
PGPOST_QUIT,
PGPOST_SYSWMEVENT,
PGPOST_TEXTEDITING,
PGPOST_TEXTINPUT,
PGPOST_VIDEORESIZE,
PGPOST_VIDEOEXPOSE,
PGPOST_WINDOWSHOWN,
PGPOST_WINDOWHIDDEN,
PGPOST_WINDOWEXPOSED,
PGPOST_WINDOWMOVED,
PGPOST_WINDOWRESIZED,
PGPOST_WINDOWSIZECHANGED,
PGPOST_WINDOWMINIMIZED,
PGPOST_WINDOWMAXIMIZED,
PGPOST_WINDOWRESTORED,
PGPOST_WINDOWENTER,
PGPOST_WINDOWLEAVE,
PGPOST_WINDOWFOCUSGAINED,
PGPOST_WINDOWFOCUSLOST,
PGPOST_WINDOWCLOSE,
PGPOST_WINDOWTAKEFOCUS,
PGPOST_WINDOWHITTEST,
PGE_USEREVENT, /* this event must stay in this position only */
PG_NUMEVENTS =
SDL_LASTEVENT /* Not an event. Indicates end of user events. */
} PygameEventCode;
typedef enum {
SDL_APPFOCUSMOUSE,
SDL_APPINPUTFOCUS,
SDL_APPACTIVE
} PygameAppCode;
/* Surface flags: based on SDL 1.2 flags */
typedef enum {
PGS_SWSURFACE = 0x00000000,
PGS_HWSURFACE = 0x00000001,
PGS_ASYNCBLIT = 0x00000004,
PGS_ANYFORMAT = 0x10000000,
PGS_HWPALETTE = 0x20000000,
PGS_DOUBLEBUF = 0x40000000,
PGS_FULLSCREEN = 0x80000000,
PGS_SCALED = 0x00000200,
PGS_OPENGL = 0x00000002,
PGS_OPENGLBLIT = 0x0000000A,
PGS_RESIZABLE = 0x00000010,
PGS_NOFRAME = 0x00000020,
PGS_SHOWN = 0x00000040, /* Added from SDL 2 */
PGS_HIDDEN = 0x00000080, /* Added from SDL 2 */
PGS_HWACCEL = 0x00000100,
PGS_SRCCOLORKEY = 0x00001000,
PGS_RLEACCELOK = 0x00002000,
PGS_RLEACCEL = 0x00004000,
PGS_SRCALPHA = 0x00010000,
PGS_PREALLOC = 0x01000000
} PygameSurfaceFlags;
// TODO Implement check below in a way that does not break CI
/* New buffer protocol (PEP 3118) implemented on all supported Py versions.
#if !defined(Py_TPFLAGS_HAVE_NEWBUFFER)
#error No support for PEP 3118/Py_TPFLAGS_HAVE_NEWBUFFER. Please use a
supported Python version. #endif */
#define RAISE(x, y) (PyErr_SetString((x), (y)), (PyObject *)NULL)
#define DEL_ATTR_NOT_SUPPORTED_CHECK(name, value) \
do { \
if (!value) { \
if (name) { \
PyErr_Format(PyExc_AttributeError, \
"Cannot delete attribute %s", name); \
} \
else { \
PyErr_SetString(PyExc_AttributeError, \
"Cannot delete attribute"); \
} \
return -1; \
} \
} while (0)
/*
* Initialization checks
*/
#define VIDEO_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_VIDEO)) \
return RAISE(pgExc_SDLError, "video system not initialized")
#define CDROM_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_CDROM)) \
return RAISE(pgExc_SDLError, "cdrom system not initialized")
#define JOYSTICK_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_JOYSTICK)) \
return RAISE(pgExc_SDLError, "joystick system not initialized")
/* thread check */
#ifdef WITH_THREAD
#define PG_CHECK_THREADS() (1)
#else /* ~WITH_THREAD */
#define PG_CHECK_THREADS() \
(RAISE(PyExc_NotImplementedError, "Python built without thread support"))
#endif /* ~WITH_THREAD */
#define PyType_Init(x) (((x).ob_type) = &PyType_Type)
/*
* event module internals
*/
struct pgEventObject {
PyObject_HEAD int type;
PyObject *dict;
};
/*
* surflock module internals
*/
typedef struct {
PyObject_HEAD PyObject *surface;
PyObject *lockobj;
PyObject *weakrefs;
} pgLifetimeLockObject;
/*
* surface module internals
*/
struct pgSubSurface_Data {
PyObject *owner;
int pixeloffset;
int offsetx, offsety;
};
/*
* color module internals
*/
struct pgColorObject {
PyObject_HEAD Uint8 data[4];
Uint8 len;
};
/*
* include public API
*/
#include "include/_pygame.h"
/* Slot counts.
* Remember to keep these constants up to date.
*/
#define PYGAMEAPI_RECT_NUMSLOTS 5
#define PYGAMEAPI_JOYSTICK_NUMSLOTS 2
#define PYGAMEAPI_DISPLAY_NUMSLOTS 2
#define PYGAMEAPI_SURFACE_NUMSLOTS 4
#define PYGAMEAPI_SURFLOCK_NUMSLOTS 8
#define PYGAMEAPI_RWOBJECT_NUMSLOTS 7
#define PYGAMEAPI_PIXELARRAY_NUMSLOTS 2
#define PYGAMEAPI_COLOR_NUMSLOTS 5
#define PYGAMEAPI_MATH_NUMSLOTS 2
#define PYGAMEAPI_CDROM_NUMSLOTS 2
#define PYGAMEAPI_BASE_NUMSLOTS 24
#define PYGAMEAPI_EVENT_NUMSLOTS 6
#endif /* _PYGAME_INTERNAL_H */

View File

@ -1,30 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef _SURFACE_H
#define _SURFACE_H
#include "_pygame.h"
#include "surface.h"
#endif

View File

@ -1,252 +0,0 @@
#ifndef CAMERA_H
#define CAMERA_H
/*
pygame - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "pygame.h"
#include "pgcompat.h"
#include "doc/camera_doc.h"
#if defined(__unix__)
#include <structmember.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <fcntl.h> /* low-level i/o */
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
/* on freebsd there is no asm/types */
#ifdef linux
#include <asm/types.h> /* for videodev2.h */
#endif
#include <linux/videodev2.h>
#endif
#if defined(__WIN32__)
#define PYGAME_WINDOWS_CAMERA 1
#include <mfapi.h>
#include <mfobjects.h>
#include <mfidl.h>
#include <mfreadwrite.h>
#include <combaseapi.h>
#include <mftransform.h>
#endif
/* some constants used which are not defined on non-v4l machines. */
#ifndef V4L2_PIX_FMT_RGB24
#define V4L2_PIX_FMT_RGB24 'RGB3'
#endif
#ifndef V4L2_PIX_FMT_RGB444
#define V4L2_PIX_FMT_RGB444 'R444'
#endif
#ifndef V4L2_PIX_FMT_YUYV
#define V4L2_PIX_FMT_YUYV 'YUYV'
#endif
#ifndef V4L2_PIX_FMT_XBGR32
#define V4L2_PIX_FMT_XBGR32 'XR24'
#endif
#define CLEAR(x) memset(&(x), 0, sizeof(x))
#define SAT(c) \
if (c & (~255)) { \
if (c < 0) \
c = 0; \
else \
c = 255; \
}
#define SAT2(c) ((c) & (~255) ? ((c) < 0 ? 0 : 255) : (c))
#define DEFAULT_WIDTH 640
#define DEFAULT_HEIGHT 480
#define RGB_OUT 1
#define YUV_OUT 2
#define HSV_OUT 4
#define CAM_V4L \
1 /* deprecated. the incomplete support in pygame was removed */
#define CAM_V4L2 2
struct buffer {
void *start;
size_t length;
};
#if defined(__unix__)
typedef struct pgCameraObject {
PyObject_HEAD char *device_name;
int camera_type;
unsigned long pixelformat;
unsigned int color_out;
struct buffer *buffers;
unsigned int n_buffers;
int width;
int height;
int size;
int hflip;
int vflip;
int brightness;
int fd;
} pgCameraObject;
#elif defined(PYGAME_WINDOWS_CAMERA)
typedef struct pgCameraObject {
PyObject_HEAD WCHAR *device_name;
IMFSourceReader *reader;
IMFTransform *transform;
IMFVideoProcessorControl *control;
IMFMediaBuffer *buf;
IMFMediaBuffer *raw_buf;
int buffer_ready;
short open; /* used to signal the update_function to exit */
HANDLE t_handle;
HRESULT t_error;
int t_error_line;
int width;
int height;
int hflip;
int vflip;
int last_vflip;
int color_out;
unsigned long pixelformat;
} pgCameraObject;
#else
/* generic definition.
*/
typedef struct pgCameraObject {
PyObject_HEAD char *device_name;
int camera_type;
unsigned long pixelformat;
unsigned int color_out;
struct buffer *buffers;
unsigned int n_buffers;
int width;
int height;
int size;
int hflip;
int vflip;
int brightness;
int fd;
} pgCameraObject;
#endif
/* internal functions for colorspace conversion */
void
colorspace(SDL_Surface *src, SDL_Surface *dst, int cspace);
void
rgb24_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
bgr32_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
rgb444_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
rgb_to_yuv(const void *src, void *dst, int length, unsigned long source,
SDL_PixelFormat *format);
void
rgb_to_hsv(const void *src, void *dst, int length, unsigned long source,
SDL_PixelFormat *format);
void
yuyv_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
yuyv_to_yuv(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
uyvy_to_rgb(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
uyvy_to_yuv(const void *src, void *dst, int length, SDL_PixelFormat *format);
void
sbggr8_to_rgb(const void *src, void *dst, int width, int height,
SDL_PixelFormat *format);
void
yuv420_to_rgb(const void *src, void *dst, int width, int height,
SDL_PixelFormat *format);
void
yuv420_to_yuv(const void *src, void *dst, int width, int height,
SDL_PixelFormat *format);
#if defined(__unix__)
/* internal functions specific to v4l2 */
char **
v4l2_list_cameras(int *num_devices);
int
v4l2_get_control(int fd, int id, int *value);
int
v4l2_set_control(int fd, int id, int value);
PyObject *
v4l2_read_raw(pgCameraObject *self);
int
v4l2_xioctl(int fd, int request, void *arg);
int
v4l2_process_image(pgCameraObject *self, const void *image,
unsigned int buffer_size, SDL_Surface *surf);
int
v4l2_query_buffer(pgCameraObject *self);
int
v4l2_read_frame(pgCameraObject *self, SDL_Surface *surf);
int
v4l2_stop_capturing(pgCameraObject *self);
int
v4l2_start_capturing(pgCameraObject *self);
int
v4l2_uninit_device(pgCameraObject *self);
int
v4l2_init_mmap(pgCameraObject *self);
int
v4l2_init_device(pgCameraObject *self);
int
v4l2_close_device(pgCameraObject *self);
int
v4l2_open_device(pgCameraObject *self);
#elif defined(PYGAME_WINDOWS_CAMERA)
/* internal functions specific to WINDOWS */
WCHAR **
windows_list_cameras(int *num_devices);
int
windows_init_device(pgCameraObject *self);
int
windows_open_device(pgCameraObject *self);
IMFActivate *
windows_device_from_name(WCHAR *device_name);
int
windows_close_device(pgCameraObject *self);
int
windows_read_frame(pgCameraObject *self, SDL_Surface *surf);
int
windows_frame_ready(pgCameraObject *self, int *result);
PyObject *
windows_read_raw(pgCameraObject *self);
int
windows_process_image(pgCameraObject *self, BYTE *data, DWORD buffer_size,
SDL_Surface *surf);
void
windows_dealloc_device(pgCameraObject *self);
int
windows_init_device(pgCameraObject *self);
#endif
#endif /* !CAMERA_H */

View File

@ -1,15 +0,0 @@
#ifndef PGFONT_INTERNAL_H
#define PGFONT_INTERNAL_H
#include <SDL_ttf.h>
/* test font initialization */
#define FONT_INIT_CHECK() \
if (!(*(int *)PyFONT_C_API[2])) \
return RAISE(pgExc_SDLError, "font system not initialized")
#include "include/pygame_font.h"
#define PYGAMEAPI_FONT_NUMSLOTS 3
#endif /* ~PGFONT_INTERNAL_H */

View File

@ -1,114 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2009 Vicent Marti
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _PYGAME_FREETYPE_INTERNAL_H_
#define _PYGAME_FREETYPE_INTERNAL_H_
#include "pgcompat.h"
#include "pgplatform.h"
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_CACHE_H
#include FT_XFREE86_H
#include FT_TRIGONOMETRY_H
/**********************************************************
* Global module constants
**********************************************************/
/* Render styles */
#define FT_STYLE_NORMAL 0x00
#define FT_STYLE_STRONG 0x01
#define FT_STYLE_OBLIQUE 0x02
#define FT_STYLE_UNDERLINE 0x04
#define FT_STYLE_WIDE 0x08
#define FT_STYLE_DEFAULT 0xFF
/* Bounding box modes */
#define FT_BBOX_EXACT FT_GLYPH_BBOX_SUBPIXELS
#define FT_BBOX_EXACT_GRIDFIT FT_GLYPH_BBOX_GRIDFIT
#define FT_BBOX_PIXEL FT_GLYPH_BBOX_TRUNCATE
#define FT_BBOX_PIXEL_GRIDFIT FT_GLYPH_BBOX_PIXELS
/* Rendering flags */
#define FT_RFLAG_NONE (0)
#define FT_RFLAG_ANTIALIAS (1 << 0)
#define FT_RFLAG_AUTOHINT (1 << 1)
#define FT_RFLAG_VERTICAL (1 << 2)
#define FT_RFLAG_HINTED (1 << 3)
#define FT_RFLAG_KERNING (1 << 4)
#define FT_RFLAG_TRANSFORM (1 << 5)
#define FT_RFLAG_PAD (1 << 6)
#define FT_RFLAG_ORIGIN (1 << 7)
#define FT_RFLAG_UCS4 (1 << 8)
#define FT_RFLAG_USE_BITMAP_STRIKES (1 << 9)
#define FT_RFLAG_DEFAULTS \
(FT_RFLAG_HINTED | FT_RFLAG_USE_BITMAP_STRIKES | FT_RFLAG_ANTIALIAS)
#define FT_RENDER_NEWBYTEARRAY 0x0
#define FT_RENDER_NEWSURFACE 0x1
#define FT_RENDER_EXISTINGSURFACE 0x2
/**********************************************************
* Global module types
**********************************************************/
typedef struct _scale_s {
FT_UInt x, y;
} Scale_t;
typedef FT_Angle Angle_t;
struct fontinternals_;
struct freetypeinstance_;
typedef struct {
FT_Long font_index;
FT_Open_Args open_args;
} pgFontId;
typedef struct {
PyObject_HEAD pgFontId id;
PyObject *path;
int is_scalable;
int is_bg_col_set;
Scale_t face_size;
FT_Int16 style;
FT_Int16 render_flags;
double strength;
double underline_adjustment;
FT_UInt resolution;
Angle_t rotation;
FT_Matrix transform;
FT_Byte fgcolor[4];
FT_Byte bgcolor[4];
struct freetypeinstance_ *freetype; /* Personal reference */
struct fontinternals_ *_internals;
} pgFontObject;
#define pgFont_IS_ALIVE(o) (((pgFontObject *)(o))->_internals != 0)
/* import public API */
#include "include/pygame_freetype.h"
#define PYGAMEAPI_FREETYPE_NUMSLOTS 2
#endif /* ~_PYGAME_FREETYPE_INTERNAL_H_ */

View File

@ -1,497 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef _PYGAME_H
#define _PYGAME_H
/** This header file includes all the definitions for the
** base pygame extensions. This header only requires
** Python includes (and SDL.h for functions that use SDL types).
** The reason for functions prototyped with #define's is
** to allow for maximum Python portability. It also uses
** Python as the runtime linker, which allows for late binding.
'' For more information on this style of development, read
** the Python docs on this subject.
** http://www.python.org/doc/current/ext/using-cobjects.html
**
** If using this to build your own derived extensions,
** you'll see that the functions available here are mainly
** used to help convert between python objects and SDL objects.
** Since this library doesn't add a lot of functionality to
** the SDL library, it doesn't need to offer a lot either.
**
** When initializing your extension module, you must manually
** import the modules you want to use. (this is the part about
** using python as the runtime linker). Each module has its
** own import_xxx() routine. You need to perform this import
** after you have initialized your own module, and before
** you call any routines from that module. Since every module
** in pygame does this, there are plenty of examples.
**
** The base module does include some useful conversion routines
** that you are free to use in your own extension.
**/
#include "pgplatform.h"
#include <Python.h>
/* version macros (defined since version 1.9.5) */
#define PG_MAJOR_VERSION 2
#define PG_MINOR_VERSION 1
#define PG_PATCH_VERSION 2
#define PG_VERSIONNUM(MAJOR, MINOR, PATCH) \
(1000 * (MAJOR) + 100 * (MINOR) + (PATCH))
#define PG_VERSION_ATLEAST(MAJOR, MINOR, PATCH) \
(PG_VERSIONNUM(PG_MAJOR_VERSION, PG_MINOR_VERSION, PG_PATCH_VERSION) >= \
PG_VERSIONNUM(MAJOR, MINOR, PATCH))
#include "pgcompat.h"
/* Flag indicating a pg_buffer; used for assertions within callbacks */
#ifndef NDEBUG
#define PyBUF_PYGAME 0x4000
#endif
#define PyBUF_HAS_FLAG(f, F) (((f) & (F)) == (F))
/* Array information exchange struct C type; inherits from Py_buffer
*
* Pygame uses its own Py_buffer derived C struct as an internal representation
* of an imported array buffer. The extended Py_buffer allows for a
* per-instance release callback,
*/
typedef void (*pybuffer_releaseproc)(Py_buffer *);
typedef struct pg_bufferinfo_s {
Py_buffer view;
PyObject *consumer; /* Input: Borrowed reference */
pybuffer_releaseproc release_buffer;
} pg_buffer;
#include "pgimport.h"
/*
* BASE module
*/
#ifndef PYGAMEAPI_BASE_INTERNAL
#define pgExc_SDLError ((PyObject *)PYGAMEAPI_GET_SLOT(base, 0))
#define pg_RegisterQuit \
(*(void (*)(void (*)(void)))PYGAMEAPI_GET_SLOT(base, 1))
#define pg_IntFromObj \
(*(int (*)(PyObject *, int *))PYGAMEAPI_GET_SLOT(base, 2))
#define pg_IntFromObjIndex \
(*(int (*)(PyObject *, int, int *))PYGAMEAPI_GET_SLOT(base, 3))
#define pg_TwoIntsFromObj \
(*(int (*)(PyObject *, int *, int *))PYGAMEAPI_GET_SLOT(base, 4))
#define pg_FloatFromObj \
(*(int (*)(PyObject *, float *))PYGAMEAPI_GET_SLOT(base, 5))
#define pg_FloatFromObjIndex \
(*(int (*)(PyObject *, int, float *))PYGAMEAPI_GET_SLOT(base, 6))
#define pg_TwoFloatsFromObj \
(*(int (*)(PyObject *, float *, float *))PYGAMEAPI_GET_SLOT(base, 7))
#define pg_UintFromObj \
(*(int (*)(PyObject *, Uint32 *))PYGAMEAPI_GET_SLOT(base, 8))
#define pg_UintFromObjIndex \
(*(int (*)(PyObject *, int, Uint32 *))PYGAMEAPI_GET_SLOT(base, 9))
#define pg_mod_autoinit (*(int (*)(const char *))PYGAMEAPI_GET_SLOT(base, 10))
#define pg_mod_autoquit (*(void (*)(const char *))PYGAMEAPI_GET_SLOT(base, 11))
#define pg_RGBAFromObj \
(*(int (*)(PyObject *, Uint8 *))PYGAMEAPI_GET_SLOT(base, 12))
#define pgBuffer_AsArrayInterface \
(*(PyObject * (*)(Py_buffer *)) PYGAMEAPI_GET_SLOT(base, 13))
#define pgBuffer_AsArrayStruct \
(*(PyObject * (*)(Py_buffer *)) PYGAMEAPI_GET_SLOT(base, 14))
#define pgObject_GetBuffer \
(*(int (*)(PyObject *, pg_buffer *, int))PYGAMEAPI_GET_SLOT(base, 15))
#define pgBuffer_Release (*(void (*)(pg_buffer *))PYGAMEAPI_GET_SLOT(base, 16))
#define pgDict_AsBuffer \
(*(int (*)(pg_buffer *, PyObject *, int))PYGAMEAPI_GET_SLOT(base, 17))
#define pgExc_BufferError ((PyObject *)PYGAMEAPI_GET_SLOT(base, 18))
#define pg_GetDefaultWindow \
(*(SDL_Window * (*)(void)) PYGAMEAPI_GET_SLOT(base, 19))
#define pg_SetDefaultWindow \
(*(void (*)(SDL_Window *))PYGAMEAPI_GET_SLOT(base, 20))
#define pg_GetDefaultWindowSurface \
(*(pgSurfaceObject * (*)(void)) PYGAMEAPI_GET_SLOT(base, 21))
#define pg_SetDefaultWindowSurface \
(*(void (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(base, 22))
#define pg_EnvShouldBlendAlphaSDL2 \
(*(char *(*)(void))PYGAMEAPI_GET_SLOT(base, 23))
#define import_pygame_base() IMPORT_PYGAME_MODULE(base)
#endif /* ~PYGAMEAPI_BASE_INTERNAL */
typedef struct {
PyObject_HEAD SDL_Rect r;
PyObject *weakreflist;
} pgRectObject;
#define pgRect_AsRect(x) (((pgRectObject *)x)->r)
#ifndef PYGAMEAPI_RECT_INTERNAL
#define pgRect_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(rect, 0))
#define pgRect_Check(x) ((x)->ob_type == &pgRect_Type)
#define pgRect_New (*(PyObject * (*)(SDL_Rect *)) PYGAMEAPI_GET_SLOT(rect, 1))
#define pgRect_New4 \
(*(PyObject * (*)(int, int, int, int)) PYGAMEAPI_GET_SLOT(rect, 2))
#define pgRect_FromObject \
(*(SDL_Rect * (*)(PyObject *, SDL_Rect *)) PYGAMEAPI_GET_SLOT(rect, 3))
#define pgRect_Normalize (*(void (*)(SDL_Rect *))PYGAMEAPI_GET_SLOT(rect, 4))
#define import_pygame_rect() IMPORT_PYGAME_MODULE(rect)
#endif /* ~PYGAMEAPI_RECT_INTERNAL */
/*
* CDROM module
*/
typedef struct {
PyObject_HEAD int id;
} pgCDObject;
#define pgCD_AsID(x) (((pgCDObject *)x)->id)
#ifndef PYGAMEAPI_CDROM_INTERNAL
#define pgCD_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(cdrom, 0))
#define pgCD_Check(x) ((x)->ob_type == &pgCD_Type)
#define pgCD_New (*(PyObject * (*)(int)) PYGAMEAPI_GET_SLOT(cdrom, 1))
#define import_pygame_cd() IMPORT_PYGAME_MODULE(cdrom)
#endif
/*
* JOYSTICK module
*/
typedef struct pgJoystickObject {
PyObject_HEAD int id;
SDL_Joystick *joy;
/* Joysticks form an intrusive linked list.
*
* Note that we don't maintain refcounts for these so they are weakrefs
* from the Python side.
*/
struct pgJoystickObject *next;
struct pgJoystickObject *prev;
} pgJoystickObject;
#define pgJoystick_AsID(x) (((pgJoystickObject *)x)->id)
#define pgJoystick_AsSDL(x) (((pgJoystickObject *)x)->joy)
#ifndef PYGAMEAPI_JOYSTICK_INTERNAL
#define pgJoystick_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(joystick, 0))
#define pgJoystick_Check(x) ((x)->ob_type == &pgJoystick_Type)
#define pgJoystick_New (*(PyObject * (*)(int)) PYGAMEAPI_GET_SLOT(joystick, 1))
#define import_pygame_joystick() IMPORT_PYGAME_MODULE(joystick)
#endif
/*
* DISPLAY module
*/
typedef struct {
Uint32 hw_available : 1;
Uint32 wm_available : 1;
Uint32 blit_hw : 1;
Uint32 blit_hw_CC : 1;
Uint32 blit_hw_A : 1;
Uint32 blit_sw : 1;
Uint32 blit_sw_CC : 1;
Uint32 blit_sw_A : 1;
Uint32 blit_fill : 1;
Uint32 video_mem;
SDL_PixelFormat *vfmt;
SDL_PixelFormat vfmt_data;
int current_w;
int current_h;
} pg_VideoInfo;
typedef struct {
PyObject_HEAD pg_VideoInfo info;
} pgVidInfoObject;
#define pgVidInfo_AsVidInfo(x) (((pgVidInfoObject *)x)->info)
#ifndef PYGAMEAPI_DISPLAY_INTERNAL
#define pgVidInfo_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(display, 0))
#define pgVidInfo_Check(x) ((x)->ob_type == &pgVidInfo_Type)
#define pgVidInfo_New \
(*(PyObject * (*)(pg_VideoInfo *)) PYGAMEAPI_GET_SLOT(display, 1))
#define import_pygame_display() IMPORT_PYGAME_MODULE(display)
#endif /* ~PYGAMEAPI_DISPLAY_INTERNAL */
/*
* SURFACE module
*/
struct pgSubSurface_Data;
struct SDL_Surface;
typedef struct {
PyObject_HEAD struct SDL_Surface *surf;
int owner;
struct pgSubSurface_Data *subsurface; /* ptr to subsurface data (if a
* subsurface)*/
PyObject *weakreflist;
PyObject *locklist;
PyObject *dependency;
} pgSurfaceObject;
#define pgSurface_AsSurface(x) (((pgSurfaceObject *)x)->surf)
#ifndef PYGAMEAPI_SURFACE_INTERNAL
#define pgSurface_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(surface, 0))
#define pgSurface_Check(x) \
(PyObject_IsInstance((x), (PyObject *)&pgSurface_Type))
#define pgSurface_New2 \
(*(pgSurfaceObject * (*)(SDL_Surface *, int)) \
PYGAMEAPI_GET_SLOT(surface, 1))
#define pgSurface_SetSurface \
(*(int (*)(pgSurfaceObject *, SDL_Surface *, int))PYGAMEAPI_GET_SLOT( \
surface, 3))
#define pgSurface_Blit \
(*(int (*)(pgSurfaceObject *, pgSurfaceObject *, SDL_Rect *, SDL_Rect *, \
int))PYGAMEAPI_GET_SLOT(surface, 2))
#define import_pygame_surface() \
do { \
IMPORT_PYGAME_MODULE(surface); \
if (PyErr_Occurred() != NULL) \
break; \
IMPORT_PYGAME_MODULE(surflock); \
} while (0)
#define pgSurface_New(surface) pgSurface_New2((surface), 1)
#define pgSurface_NewNoOwn(surface) pgSurface_New2((surface), 0)
#endif /* ~PYGAMEAPI_SURFACE_INTERNAL */
/*
* SURFLOCK module
* auto imported/initialized by surface
*/
#ifndef PYGAMEAPI_SURFLOCK_INTERNAL
#define pgLifetimeLock_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(surflock, 0))
#define pgLifetimeLock_Check(x) ((x)->ob_type == &pgLifetimeLock_Type)
#define pgSurface_Prep(x) \
if ((x)->subsurface) \
(*(*(void (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 1)))(x)
#define pgSurface_Unprep(x) \
if ((x)->subsurface) \
(*(*(void (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 2)))(x)
#define pgSurface_Lock \
(*(int (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 3))
#define pgSurface_Unlock \
(*(int (*)(pgSurfaceObject *))PYGAMEAPI_GET_SLOT(surflock, 4))
#define pgSurface_LockBy \
(*(int (*)(pgSurfaceObject *, PyObject *))PYGAMEAPI_GET_SLOT(surflock, 5))
#define pgSurface_UnlockBy \
(*(int (*)(pgSurfaceObject *, PyObject *))PYGAMEAPI_GET_SLOT(surflock, 6))
#define pgSurface_LockLifetime \
(*(PyObject * (*)(PyObject *, PyObject *)) PYGAMEAPI_GET_SLOT(surflock, 7))
#endif
/*
* EVENT module
*/
typedef struct pgEventObject pgEventObject;
#ifndef PYGAMEAPI_EVENT_INTERNAL
#define pgEvent_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(event, 0))
#define pgEvent_Check(x) ((x)->ob_type == &pgEvent_Type)
#define pgEvent_New \
(*(PyObject * (*)(SDL_Event *)) PYGAMEAPI_GET_SLOT(event, 1))
#define pgEvent_New2 \
(*(PyObject * (*)(int, PyObject *)) PYGAMEAPI_GET_SLOT(event, 2))
#define pgEvent_FillUserEvent \
(*(int (*)(pgEventObject *, SDL_Event *))PYGAMEAPI_GET_SLOT(event, 3))
#define pg_EnableKeyRepeat (*(int (*)(int, int))PYGAMEAPI_GET_SLOT(event, 4))
#define pg_GetKeyRepeat (*(void (*)(int *, int *))PYGAMEAPI_GET_SLOT(event, 5))
#define import_pygame_event() IMPORT_PYGAME_MODULE(event)
#endif
/*
* RWOBJECT module
* the rwobject are only needed for C side work, not accessable from python.
*/
#ifndef PYGAMEAPI_RWOBJECT_INTERNAL
#define pgRWops_FromObject \
(*(SDL_RWops * (*)(PyObject *)) PYGAMEAPI_GET_SLOT(rwobject, 0))
#define pgRWops_IsFileObject \
(*(int (*)(SDL_RWops *))PYGAMEAPI_GET_SLOT(rwobject, 1))
#define pg_EncodeFilePath \
(*(PyObject * (*)(PyObject *, PyObject *)) PYGAMEAPI_GET_SLOT(rwobject, 2))
#define pg_EncodeString \
(*(PyObject * (*)(PyObject *, const char *, const char *, PyObject *)) \
PYGAMEAPI_GET_SLOT(rwobject, 3))
#define pgRWops_FromFileObject \
(*(SDL_RWops * (*)(PyObject *)) PYGAMEAPI_GET_SLOT(rwobject, 4))
#define pgRWops_ReleaseObject \
(*(int (*)(SDL_RWops *))PYGAMEAPI_GET_SLOT(rwobject, 5))
#define pgRWops_GetFileExtension \
(*(char *(*)(SDL_RWops *))PYGAMEAPI_GET_SLOT(rwobject, 6))
#define import_pygame_rwobject() IMPORT_PYGAME_MODULE(rwobject)
#endif
/*
* PixelArray module
*/
#ifndef PYGAMEAPI_PIXELARRAY_INTERNAL
#define PyPixelArray_Type ((PyTypeObject *)PYGAMEAPI_GET_SLOT(pixelarray, 0))
#define PyPixelArray_Check(x) ((x)->ob_type == &PyPixelArray_Type)
#define PyPixelArray_New (*(PyObject * (*)) PYGAMEAPI_GET_SLOT(pixelarray, 1))
#define import_pygame_pixelarray() IMPORT_PYGAME_MODULE(pixelarray)
#endif /* PYGAMEAPI_PIXELARRAY_INTERNAL */
/*
* Color module
*/
typedef struct pgColorObject pgColorObject;
#ifndef PYGAMEAPI_COLOR_INTERNAL
#define pgColor_Type (*(PyObject *)PYGAMEAPI_GET_SLOT(color, 0))
#define pgColor_Check(x) ((x)->ob_type == &pgColor_Type)
#define pgColor_New (*(PyObject * (*)(Uint8 *)) PYGAMEAPI_GET_SLOT(color, 1))
#define pgColor_NewLength \
(*(PyObject * (*)(Uint8 *, Uint8)) PYGAMEAPI_GET_SLOT(color, 3))
#define pg_RGBAFromColorObj \
(*(int (*)(PyObject *, Uint8 *))PYGAMEAPI_GET_SLOT(color, 2))
#define pg_RGBAFromFuzzyColorObj \
(*(int (*)(PyObject *, Uint8 *))PYGAMEAPI_GET_SLOT(color, 4))
#define pgColor_AsArray(x) (((pgColorObject *)x)->data)
#define pgColor_NumComponents(x) (((pgColorObject *)x)->len)
#define import_pygame_color() IMPORT_PYGAME_MODULE(color)
#endif /* PYGAMEAPI_COLOR_INTERNAL */
/*
* Math module
*/
#ifndef PYGAMEAPI_MATH_INTERNAL
#define pgVector2_Check(x) \
((x)->ob_type == (PyTypeObject *)PYGAMEAPI_GET_SLOT(math, 0))
#define pgVector3_Check(x) \
((x)->ob_type == (PyTypeObject *)PYGAMEAPI_GET_SLOT(math, 1))
/*
#define pgVector2_New \
(*(PyObject*(*)) \
PYGAMEAPI_GET_SLOT(PyGAME_C_API, 1))
*/
#define import_pygame_math() IMPORT_PYGAME_MODULE(math)
#endif /* PYGAMEAPI_MATH_INTERNAL */
#define IMPORT_PYGAME_MODULE _IMPORT_PYGAME_MODULE
/*
* base pygame API slots
* disable slots with NO_PYGAME_C_API
*/
#ifdef PYGAME_H
PYGAMEAPI_DEFINE_SLOTS(base);
PYGAMEAPI_DEFINE_SLOTS(rect);
PYGAMEAPI_DEFINE_SLOTS(cdrom);
PYGAMEAPI_DEFINE_SLOTS(joystick);
PYGAMEAPI_DEFINE_SLOTS(display);
PYGAMEAPI_DEFINE_SLOTS(surface);
PYGAMEAPI_DEFINE_SLOTS(surflock);
PYGAMEAPI_DEFINE_SLOTS(event);
PYGAMEAPI_DEFINE_SLOTS(rwobject);
PYGAMEAPI_DEFINE_SLOTS(pixelarray);
PYGAMEAPI_DEFINE_SLOTS(color);
PYGAMEAPI_DEFINE_SLOTS(math);
#else /* ~PYGAME_H */
PYGAMEAPI_EXTERN_SLOTS(base);
PYGAMEAPI_EXTERN_SLOTS(rect);
PYGAMEAPI_EXTERN_SLOTS(cdrom);
PYGAMEAPI_EXTERN_SLOTS(joystick);
PYGAMEAPI_EXTERN_SLOTS(display);
PYGAMEAPI_EXTERN_SLOTS(surface);
PYGAMEAPI_EXTERN_SLOTS(surflock);
PYGAMEAPI_EXTERN_SLOTS(event);
PYGAMEAPI_EXTERN_SLOTS(rwobject);
PYGAMEAPI_EXTERN_SLOTS(pixelarray);
PYGAMEAPI_EXTERN_SLOTS(color);
PYGAMEAPI_EXTERN_SLOTS(math);
#endif /* ~PYGAME_H */
#endif /* PYGAME_H */

View File

@ -1,171 +0,0 @@
/*
Bitmask 1.7 - A pixel-perfect collision detection library.
Copyright (C) 2002-2005 Ulf Ekstrom except for the bitcount
function which is copyright (C) Donald W. Gillies, 1992.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef BITMASK_H
#define BITMASK_H
#ifdef __cplusplus
extern "C" {
#endif
#include <limits.h>
/* Define INLINE for different compilers. If your compiler does not
support inlining then there might be a performance hit in
bitmask_overlap_area().
*/
#ifndef INLINE
#ifdef __GNUC__
#define INLINE inline
#else
#ifdef _MSC_VER
#define INLINE __inline
#else
#define INLINE
#endif
#endif
#endif
#define BITMASK_W unsigned long int
#define BITMASK_W_LEN (sizeof(BITMASK_W) * CHAR_BIT)
#define BITMASK_W_MASK (BITMASK_W_LEN - 1)
#define BITMASK_N(n) ((BITMASK_W)1 << (n))
typedef struct bitmask {
int w, h;
BITMASK_W bits[1];
} bitmask_t;
/* Creates a bitmask of width w and height h, where
w and h must both be greater than or equal to 0.
The mask is automatically cleared when created.
*/
bitmask_t *
bitmask_create(int w, int h);
/* Frees all the memory allocated by bitmask_create for m. */
void
bitmask_free(bitmask_t *m);
/* Create a copy of the given bitmask. */
bitmask_t *
bitmask_copy(bitmask_t *m);
/* Clears all bits in the mask */
void
bitmask_clear(bitmask_t *m);
/* Sets all bits in the mask */
void
bitmask_fill(bitmask_t *m);
/* Flips all bits in the mask */
void
bitmask_invert(bitmask_t *m);
/* Counts the bits in the mask */
unsigned int
bitmask_count(bitmask_t *m);
/* Returns nonzero if the bit at (x,y) is set. Coordinates start at
(0,0) */
static INLINE int
bitmask_getbit(const bitmask_t *m, int x, int y)
{
return (m->bits[x / BITMASK_W_LEN * m->h + y] &
BITMASK_N(x & BITMASK_W_MASK)) != 0;
}
/* Sets the bit at (x,y) */
static INLINE void
bitmask_setbit(bitmask_t *m, int x, int y)
{
m->bits[x / BITMASK_W_LEN * m->h + y] |= BITMASK_N(x & BITMASK_W_MASK);
}
/* Clears the bit at (x,y) */
static INLINE void
bitmask_clearbit(bitmask_t *m, int x, int y)
{
m->bits[x / BITMASK_W_LEN * m->h + y] &= ~BITMASK_N(x & BITMASK_W_MASK);
}
/* Returns nonzero if the masks overlap with the given offset.
The overlap tests uses the following offsets (which may be negative):
+----+----------..
|A | yoffset
| +-+----------..
+--|B
|xoffset
| |
: :
*/
int
bitmask_overlap(const bitmask_t *a, const bitmask_t *b, int xoffset,
int yoffset);
/* Like bitmask_overlap(), but will also give a point of intersection.
x and y are given in the coordinates of mask a, and are untouched
if there is no overlap. */
int
bitmask_overlap_pos(const bitmask_t *a, const bitmask_t *b, int xoffset,
int yoffset, int *x, int *y);
/* Returns the number of overlapping 'pixels' */
int
bitmask_overlap_area(const bitmask_t *a, const bitmask_t *b, int xoffset,
int yoffset);
/* Fills a mask with the overlap of two other masks. A bitwise AND. */
void
bitmask_overlap_mask(const bitmask_t *a, const bitmask_t *b, bitmask_t *c,
int xoffset, int yoffset);
/* Draws mask b onto mask a (bitwise OR). Can be used to compose large
(game background?) mask from several submasks, which may speed up
the testing. */
void
bitmask_draw(bitmask_t *a, const bitmask_t *b, int xoffset, int yoffset);
void
bitmask_erase(bitmask_t *a, const bitmask_t *b, int xoffset, int yoffset);
/* Return a new scaled bitmask, with dimensions w*h. The quality of the
scaling may not be perfect for all circumstances, but it should
be reasonable. If either w or h is 0 a clear 1x1 mask is returned. */
bitmask_t *
bitmask_scale(const bitmask_t *m, int w, int h);
/* Convolve b into a, drawing the output into o, shifted by offset. If offset
* is 0, then the (x,y) bit will be set if and only if
* bitmask_overlap(a, b, x - b->w - 1, y - b->h - 1) returns true.
*
* Modifies bits o[xoffset ... xoffset + a->w + b->w - 1)
* [yoffset ... yoffset + a->h + b->h - 1). */
void
bitmask_convolve(const bitmask_t *a, const bitmask_t *b, bitmask_t *o,
int xoffset, int yoffset);
#ifdef __cplusplus
} /* End of extern "C" { */
#endif
#endif

View File

@ -1,108 +0,0 @@
/* Python 2.x/3.x and SDL compatibility tools
*/
#if !defined(PGCOMPAT_H)
#define PGCOMPAT_H
#include <Python.h>
/* define common types where SDL is not included */
#ifndef SDL_VERSION_ATLEAST
#ifdef _MSC_VER
typedef unsigned __int8 uint8_t;
typedef unsigned __int32 uint32_t;
#else
#include <stdint.h>
#endif
typedef uint32_t Uint32;
typedef uint8_t Uint8;
#endif /* no SDL */
#if defined(SDL_VERSION_ATLEAST)
#ifndef SDL_WINDOW_VULKAN
#define SDL_WINDOW_VULKAN 0
#endif
#ifndef SDL_WINDOW_ALWAYS_ON_TOP
#define SDL_WINDOW_ALWAYS_ON_TOP 0
#endif
#ifndef SDL_WINDOW_SKIP_TASKBAR
#define SDL_WINDOW_SKIP_TASKBAR 0
#endif
#ifndef SDL_WINDOW_UTILITY
#define SDL_WINDOW_UTILITY 0
#endif
#ifndef SDL_WINDOW_TOOLTIP
#define SDL_WINDOW_TOOLTIP 0
#endif
#ifndef SDL_WINDOW_POPUP_MENU
#define SDL_WINDOW_POPUP_MENU 0
#endif
#ifndef SDL_WINDOW_INPUT_GRABBED
#define SDL_WINDOW_INPUT_GRABBED 0
#endif
#ifndef SDL_WINDOW_INPUT_FOCUS
#define SDL_WINDOW_INPUT_FOCUS 0
#endif
#ifndef SDL_WINDOW_MOUSE_FOCUS
#define SDL_WINDOW_MOUSE_FOCUS 0
#endif
#ifndef SDL_WINDOW_FOREIGN
#define SDL_WINDOW_FOREIGN 0
#endif
#ifndef SDL_WINDOW_ALLOW_HIGHDPI
#define SDL_WINDOW_ALLOW_HIGHDPI 0
#endif
#ifndef SDL_WINDOW_MOUSE_CAPTURE
#define SDL_WINDOW_MOUSE_CAPTURE 0
#endif
#ifndef SDL_WINDOW_ALWAYS_ON_TOP
#define SDL_WINDOW_ALWAYS_ON_TOP 0
#endif
#ifndef SDL_WINDOW_SKIP_TASKBAR
#define SDL_WINDOW_SKIP_TASKBAR 0
#endif
#ifndef SDL_WINDOW_UTILITY
#define SDL_WINDOW_UTILITY 0
#endif
#ifndef SDL_WINDOW_TOOLTIP
#define SDL_WINDOW_TOOLTIP 0
#endif
#ifndef SDL_WINDOW_POPUP_MENU
#define SDL_WINDOW_POPUP_MENU 0
#endif
#if SDL_VERSION_ATLEAST(2, 0, 4)
/* To control the use of:
* SDL_AUDIODEVICEADDED
* SDL_AUDIODEVICEREMOVED
*
* Ref: https://wiki.libsdl.org/SDL_EventType
* Ref: https://wiki.libsdl.org/SDL_AudioDeviceEvent
*/
#define SDL2_AUDIODEVICE_SUPPORTED
#endif
#ifndef SDL_MOUSEWHEEL_FLIPPED
#define NO_SDL_MOUSEWHEEL_FLIPPED
#endif
#endif /* defined(SDL_VERSION_ATLEAST) */
#endif /* ~defined(PGCOMPAT_H) */

View File

@ -1,80 +0,0 @@
#ifndef PGIMPORT_H
#define PGIMPORT_H
/* Prefix when initializing module */
#define MODPREFIX ""
/* Prefix when importing module */
#define IMPPREFIX "pygame."
#ifdef __SYMBIAN32__
/* On Symbian there is no pygame package. The extensions are built-in or in
* sys\bin. */
#undef MODPREFIX
#undef IMPPREFIX
#define MODPREFIX "pygame_"
#define IMPPREFIX "pygame_"
#endif /* __SYMBIAN32__ */
#include "pgcompat.h"
#define PYGAMEAPI_LOCAL_ENTRY "_PYGAME_C_API"
#define PG_CAPSULE_NAME(m) (IMPPREFIX m "." PYGAMEAPI_LOCAL_ENTRY)
/*
* fill API slots defined by PYGAMEAPI_DEFINE_SLOTS/PYGAMEAPI_EXTERN_SLOTS
*/
#define _IMPORT_PYGAME_MODULE(module) \
{ \
PyObject *_mod_##module = PyImport_ImportModule(IMPPREFIX #module); \
\
if (_mod_##module != NULL) { \
PyObject *_c_api = \
PyObject_GetAttrString(_mod_##module, PYGAMEAPI_LOCAL_ENTRY); \
\
Py_DECREF(_mod_##module); \
if (_c_api != NULL && PyCapsule_CheckExact(_c_api)) { \
void **localptr = (void **)PyCapsule_GetPointer( \
_c_api, PG_CAPSULE_NAME(#module)); \
_PGSLOTS_##module = localptr; \
} \
Py_XDECREF(_c_api); \
} \
}
#define PYGAMEAPI_IS_IMPORTED(module) (_PGSLOTS_##module != NULL)
/*
* source file must include one of these in order to use _IMPORT_PYGAME_MODULE.
* this is set by import_pygame_*() functions.
* disable with NO_PYGAME_C_API
*/
#define PYGAMEAPI_DEFINE_SLOTS(module) void **_PGSLOTS_##module = NULL
#define PYGAMEAPI_EXTERN_SLOTS(module) extern void **_PGSLOTS_##module
#define PYGAMEAPI_GET_SLOT(module, index) _PGSLOTS_##module[(index)]
/*
* disabled API with NO_PYGAME_C_API; do nothing instead
*/
#ifdef NO_PYGAME_C_API
#undef PYGAMEAPI_DEFINE_SLOTS
#undef PYGAMEAPI_EXTERN_SLOTS
#define PYGAMEAPI_DEFINE_SLOTS(module)
#define PYGAMEAPI_EXTERN_SLOTS(module)
/* intentionally leave this defined to cause a compiler error *
#define PYGAMEAPI_GET_SLOT(api_root, index)
#undef PYGAMEAPI_GET_SLOT*/
#undef _IMPORT_PYGAME_MODULE
#define _IMPORT_PYGAME_MODULE(module)
#endif /* NO_PYGAME_C_API */
#define encapsulate_api(ptr, module) \
PyCapsule_New(ptr, PG_CAPSULE_NAME(module), NULL)
#endif /* ~PGIMPORT_H */

View File

@ -1,92 +0,0 @@
/* platform/compiler adjustments */
#ifndef PG_PLATFORM_H
#define PG_PLATFORM_H
#if defined(HAVE_SNPRINTF) /* defined in python.h (pyerrors.h) and SDL.h \
(SDL_config.h) */
#undef HAVE_SNPRINTF /* remove GCC redefine warning */
#endif /* HAVE_SNPRINTF */
#ifndef PG_INLINE
#if defined(__clang__)
#define PG_INLINE __inline__ __attribute__((__unused__))
#elif defined(__GNUC__)
#define PG_INLINE __inline__
#elif defined(_MSC_VER)
#define PG_INLINE __inline
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define PG_INLINE inline
#else
#define PG_INLINE
#endif
#endif /* ~PG_INLINE */
// Worth trying this on MSVC/win32 builds to see if provides any speed up
#ifndef PG_FORCEINLINE
#if defined(__clang__)
#define PG_FORCEINLINE __inline__ __attribute__((__unused__))
#elif defined(__GNUC__)
#define PG_FORCEINLINE __inline__
#elif defined(_MSC_VER)
#define PG_FORCEINLINE __forceinline
#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define PG_FORCEINLINE inline
#else
#define PG_FORCEINLINE
#endif
#endif /* ~PG_FORCEINLINE */
/* This is unconditionally defined in Python.h */
#if defined(_POSIX_C_SOURCE)
#undef _POSIX_C_SOURCE
#endif
/* No signal() */
#if defined(__SYMBIAN32__) && defined(HAVE_SIGNAL_H)
#undef HAVE_SIGNAL_H
#endif
#if defined(HAVE_SNPRINTF)
#undef HAVE_SNPRINTF
#endif
/* SDL needs WIN32 */
#if !defined(WIN32) && \
(defined(MS_WIN32) || defined(_WIN32) || defined(__WIN32) || \
defined(__WIN32__) || defined(_WINDOWS))
#define WIN32
#endif
/* Commenting out SSE4_2 stuff because it does not do runtime detection.
#ifndef PG_TARGET_SSE4_2
#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ == 4 &&
__GNUC_MINOR__ >= 9) || __GNUC__ >= 5 ))
//The old gcc 4.8 on centos used by manylinux1 does not seem to get sse4.2
intrinsics #define PG_FUNCTION_TARGET_SSE4_2 __attribute__((target("sse4.2")))
// No else; we define the fallback later
#endif
#endif
*/
/* ~PG_TARGET_SSE4_2 */
/*
#ifdef PG_FUNCTION_TARGET_SSE4_2
#if !defined(__SSE4_2__) && !defined(PG_COMPILE_SSE4_2)
#if defined(__x86_64__) || defined(__i386__)
#define PG_COMPILE_SSE4_2 1
#endif
#endif
#endif
*/
/* ~PG_TARGET_SSE4_2 */
/* Fallback definition of target attribute */
#ifndef PG_FUNCTION_TARGET_SSE4_2
#define PG_FUNCTION_TARGET_SSE4_2
#endif
#ifndef PG_COMPILE_SSE4_2
#define PG_COMPILE_SSE4_2 0
#endif
#endif /* ~PG_PLATFORM_H */

View File

@ -1,34 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* To allow the Pygame C api to be globally shared by all code within an
* extension module built from multiple C files, only include the pygame.h
* header within the top level C file, the one which calls the
* 'import_pygame_*' macros. All other C source files of the module should
* include _pygame.h instead.
*/
#ifndef PYGAME_H
#define PYGAME_H
#include "_pygame.h"
#endif

View File

@ -1,56 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Rene Dudfield, Richard Goedeken
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* Bufferproxy module C api. */
#if !defined(PG_BUFPROXY_HEADER)
#define PG_BUFPROXY_HEADER
#include <Python.h>
typedef PyObject *(*_pgbufproxy_new_t)(PyObject *, getbufferproc);
typedef PyObject *(*_pgbufproxy_get_obj_t)(PyObject *);
typedef int (*_pgbufproxy_trip_t)(PyObject *);
#ifndef PYGAMEAPI_BUFPROXY_INTERNAL
#include "pgimport.h"
PYGAMEAPI_DEFINE_SLOTS(bufferproxy);
#define pgBufproxy_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(bufferproxy, 0))
#define pgBufproxy_Check(x) ((x)->ob_type == &pgBufproxy_Type)
#define pgBufproxy_New (*(_pgbufproxy_new_t)PYGAMEAPI_GET_SLOT(bufferproxy, 1))
#define pgBufproxy_GetParent \
(*(_pgbufproxy_get_obj_t)PYGAMEAPI_GET_SLOT(bufferproxy, 2))
#define pgBufproxy_Trip \
(*(_pgbufproxy_trip_t)PYGAMEAPI_GET_SLOT(bufferproxy, 3))
#define import_pygame_bufferproxy() _IMPORT_PYGAME_MODULE(bufferproxy)
#endif /* ~PYGAMEAPI_BUFPROXY_INTERNAL */
#endif /* ~defined(PG_BUFPROXY_HEADER) */

View File

@ -1,50 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#include <Python.h>
#include "pgplatform.h"
struct TTF_Font;
typedef struct {
PyObject_HEAD TTF_Font *font;
PyObject *weakreflist;
unsigned int ttf_init_generation;
} PyFontObject;
#define PyFont_AsFont(x) (((PyFontObject *)x)->font)
#ifndef PYGAMEAPI_FONT_INTERNAL
#include "pgimport.h"
PYGAMEAPI_DEFINE_SLOTS(font);
#define PyFont_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(font, 0))
#define PyFont_Check(x) ((x)->ob_type == &PyFont_Type)
#define PyFont_New (*(PyObject * (*)(TTF_Font *)) PYGAMEAPI_GET_SLOT(font, 1))
/*slot 2 taken by FONT_INIT_CHECK*/
#define import_pygame_font() _IMPORT_PYGAME_MODULE(font)
#endif

View File

@ -1,42 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2009 Vicent Marti
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PYGAME_FREETYPE_H_
#define PYGAME_FREETYPE_H_
#include "pgplatform.h"
#include "pgimport.h"
#include "pgcompat.h"
#ifndef PYGAME_FREETYPE_INTERNAL
PYGAMEAPI_DEFINE_SLOTS(_freetype);
#define pgFont_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(_freetype, 0))
#define pgFont_Check(x) ((x)->ob_type == &pgFont_Type)
#define pgFont_New \
(*(PyObject * (*)(const char *, long)) PYGAMEAPI_GET_SLOT(_freetype, 1))
#define import_pygame_freetype() _IMPORT_PYGAME_MODULE(_freetype)
#endif /* PYGAME_FREETYPE_INTERNAL */
#endif /* PYGAME_FREETYPE_H_ */

View File

@ -1,45 +0,0 @@
/*
pygame - Python Game Library
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef PGMASK_H
#define PGMASK_H
#include <Python.h>
#include "bitmask.h"
typedef struct {
PyObject_HEAD bitmask_t *mask;
void *bufdata;
} pgMaskObject;
#define pgMask_AsBitmap(x) (((pgMaskObject *)x)->mask)
#ifndef PYGAMEAPI_MASK_INTERNAL
#include "pgimport.h"
PYGAMEAPI_DEFINE_SLOTS(mask);
#define pgMask_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(mask, 0))
#define pgMask_Check(x) ((x)->ob_type == &pgMask_Type)
#define import_pygame_mask() _IMPORT_PYGAME_MODULE(mask)
#endif /* ~PYGAMEAPI_MASK_INTERNAL */
#endif /* ~PGMASK_H */

View File

@ -1,71 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef PGMIXER_H
#define PGMIXER_H
#include <Python.h>
#include <structmember.h>
#include "pgcompat.h"
struct Mix_Chunk;
typedef struct {
PyObject_HEAD Mix_Chunk *chunk;
Uint8 *mem;
PyObject *weakreflist;
} pgSoundObject;
typedef struct {
PyObject_HEAD int chan;
} pgChannelObject;
#define pgSound_AsChunk(x) (((pgSoundObject *)x)->chunk)
#define pgChannel_AsInt(x) (((pgChannelObject *)x)->chan)
#include "pgimport.h"
#ifndef PYGAMEAPI_MIXER_INTERNAL
PYGAMEAPI_DEFINE_SLOTS(mixer);
#define pgSound_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(mixer, 0))
#define pgSound_Check(x) ((x)->ob_type == &pgSound_Type)
#define pgSound_New \
(*(PyObject * (*)(Mix_Chunk *)) PYGAMEAPI_GET_SLOT(mixer, 1))
#define pgSound_Play \
(*(PyObject * (*)(PyObject *, PyObject *)) PYGAMEAPI_GET_SLOT(mixer, 2))
#define pgChannel_Type (*(PyTypeObject *)PYGAMEAPI_GET_SLOT(mixer, 3))
#define pgChannel_Check(x) ((x)->ob_type == &pgChannel_Type)
#define pgChannel_New (*(PyObject * (*)(int)) PYGAMEAPI_GET_SLOT(mixer, 4))
#define import_pygame_mixer() _IMPORT_PYGAME_MODULE(mixer)
#endif /* PYGAMEAPI_MIXER_INTERNAL */
#endif /* ~PGMIXER_H */

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +0,0 @@
#ifndef PGMASK_INTERNAL_H
#define PGMASK_INTERNAL_H
#include "include/pygame_mask.h"
#define PYGAMEAPI_MASK_NUMSLOTS 1
#endif /* ~PGMASK_INTERNAL_H */

View File

@ -1,14 +0,0 @@
#ifndef MIXER_INTERNAL_H
#define MIXER_INTERNAL_H
#include <SDL_mixer.h>
/* test mixer initializations */
#define MIXER_INIT_CHECK() \
if (!SDL_WasInit(SDL_INIT_AUDIO)) \
return RAISE(pgExc_SDLError, "mixer not initialized")
#define PYGAMEAPI_MIXER_NUMSLOTS 5
#include "include/pygame_mixer.h"
#endif /* ~MIXER_INTERNAL_H */

View File

@ -1,123 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef PALETTE_H
#define PALETTE_H
#include <SDL.h>
/* SDL 2 does not assign a default palette color scheme to a new 8 bit
* surface. Instead, the palette is set all white. This defines the SDL 1.2
* default palette.
*/
static const SDL_Color default_palette_colors[] = {
{0, 0, 0, 255}, {0, 0, 85, 255}, {0, 0, 170, 255},
{0, 0, 255, 255}, {0, 36, 0, 255}, {0, 36, 85, 255},
{0, 36, 170, 255}, {0, 36, 255, 255}, {0, 73, 0, 255},
{0, 73, 85, 255}, {0, 73, 170, 255}, {0, 73, 255, 255},
{0, 109, 0, 255}, {0, 109, 85, 255}, {0, 109, 170, 255},
{0, 109, 255, 255}, {0, 146, 0, 255}, {0, 146, 85, 255},
{0, 146, 170, 255}, {0, 146, 255, 255}, {0, 182, 0, 255},
{0, 182, 85, 255}, {0, 182, 170, 255}, {0, 182, 255, 255},
{0, 219, 0, 255}, {0, 219, 85, 255}, {0, 219, 170, 255},
{0, 219, 255, 255}, {0, 255, 0, 255}, {0, 255, 85, 255},
{0, 255, 170, 255}, {0, 255, 255, 255}, {85, 0, 0, 255},
{85, 0, 85, 255}, {85, 0, 170, 255}, {85, 0, 255, 255},
{85, 36, 0, 255}, {85, 36, 85, 255}, {85, 36, 170, 255},
{85, 36, 255, 255}, {85, 73, 0, 255}, {85, 73, 85, 255},
{85, 73, 170, 255}, {85, 73, 255, 255}, {85, 109, 0, 255},
{85, 109, 85, 255}, {85, 109, 170, 255}, {85, 109, 255, 255},
{85, 146, 0, 255}, {85, 146, 85, 255}, {85, 146, 170, 255},
{85, 146, 255, 255}, {85, 182, 0, 255}, {85, 182, 85, 255},
{85, 182, 170, 255}, {85, 182, 255, 255}, {85, 219, 0, 255},
{85, 219, 85, 255}, {85, 219, 170, 255}, {85, 219, 255, 255},
{85, 255, 0, 255}, {85, 255, 85, 255}, {85, 255, 170, 255},
{85, 255, 255, 255}, {170, 0, 0, 255}, {170, 0, 85, 255},
{170, 0, 170, 255}, {170, 0, 255, 255}, {170, 36, 0, 255},
{170, 36, 85, 255}, {170, 36, 170, 255}, {170, 36, 255, 255},
{170, 73, 0, 255}, {170, 73, 85, 255}, {170, 73, 170, 255},
{170, 73, 255, 255}, {170, 109, 0, 255}, {170, 109, 85, 255},
{170, 109, 170, 255}, {170, 109, 255, 255}, {170, 146, 0, 255},
{170, 146, 85, 255}, {170, 146, 170, 255}, {170, 146, 255, 255},
{170, 182, 0, 255}, {170, 182, 85, 255}, {170, 182, 170, 255},
{170, 182, 255, 255}, {170, 219, 0, 255}, {170, 219, 85, 255},
{170, 219, 170, 255}, {170, 219, 255, 255}, {170, 255, 0, 255},
{170, 255, 85, 255}, {170, 255, 170, 255}, {170, 255, 255, 255},
{255, 0, 0, 255}, {255, 0, 85, 255}, {255, 0, 170, 255},
{255, 0, 255, 255}, {255, 36, 0, 255}, {255, 36, 85, 255},
{255, 36, 170, 255}, {255, 36, 255, 255}, {255, 73, 0, 255},
{255, 73, 85, 255}, {255, 73, 170, 255}, {255, 73, 255, 255},
{255, 109, 0, 255}, {255, 109, 85, 255}, {255, 109, 170, 255},
{255, 109, 255, 255}, {255, 146, 0, 255}, {255, 146, 85, 255},
{255, 146, 170, 255}, {255, 146, 255, 255}, {255, 182, 0, 255},
{255, 182, 85, 255}, {255, 182, 170, 255}, {255, 182, 255, 255},
{255, 219, 0, 255}, {255, 219, 85, 255}, {255, 219, 170, 255},
{255, 219, 255, 255}, {255, 255, 0, 255}, {255, 255, 85, 255},
{255, 255, 170, 255}, {255, 255, 255, 255}, {0, 0, 0, 255},
{0, 0, 85, 255}, {0, 0, 170, 255}, {0, 0, 255, 255},
{0, 36, 0, 255}, {0, 36, 85, 255}, {0, 36, 170, 255},
{0, 36, 255, 255}, {0, 73, 0, 255}, {0, 73, 85, 255},
{0, 73, 170, 255}, {0, 73, 255, 255}, {0, 109, 0, 255},
{0, 109, 85, 255}, {0, 109, 170, 255}, {0, 109, 255, 255},
{0, 146, 0, 255}, {0, 146, 85, 255}, {0, 146, 170, 255},
{0, 146, 255, 255}, {0, 182, 0, 255}, {0, 182, 85, 255},
{0, 182, 170, 255}, {0, 182, 255, 255}, {0, 219, 0, 255},
{0, 219, 85, 255}, {0, 219, 170, 255}, {0, 219, 255, 255},
{0, 255, 0, 255}, {0, 255, 85, 255}, {0, 255, 170, 255},
{0, 255, 255, 255}, {85, 0, 0, 255}, {85, 0, 85, 255},
{85, 0, 170, 255}, {85, 0, 255, 255}, {85, 36, 0, 255},
{85, 36, 85, 255}, {85, 36, 170, 255}, {85, 36, 255, 255},
{85, 73, 0, 255}, {85, 73, 85, 255}, {85, 73, 170, 255},
{85, 73, 255, 255}, {85, 109, 0, 255}, {85, 109, 85, 255},
{85, 109, 170, 255}, {85, 109, 255, 255}, {85, 146, 0, 255},
{85, 146, 85, 255}, {85, 146, 170, 255}, {85, 146, 255, 255},
{85, 182, 0, 255}, {85, 182, 85, 255}, {85, 182, 170, 255},
{85, 182, 255, 255}, {85, 219, 0, 255}, {85, 219, 85, 255},
{85, 219, 170, 255}, {85, 219, 255, 255}, {85, 255, 0, 255},
{85, 255, 85, 255}, {85, 255, 170, 255}, {85, 255, 255, 255},
{170, 0, 0, 255}, {170, 0, 85, 255}, {170, 0, 170, 255},
{170, 0, 255, 255}, {170, 36, 0, 255}, {170, 36, 85, 255},
{170, 36, 170, 255}, {170, 36, 255, 255}, {170, 73, 0, 255},
{170, 73, 85, 255}, {170, 73, 170, 255}, {170, 73, 255, 255},
{170, 109, 0, 255}, {170, 109, 85, 255}, {170, 109, 170, 255},
{170, 109, 255, 255}, {170, 146, 0, 255}, {170, 146, 85, 255},
{170, 146, 170, 255}, {170, 146, 255, 255}, {170, 182, 0, 255},
{170, 182, 85, 255}, {170, 182, 170, 255}, {170, 182, 255, 255},
{170, 219, 0, 255}, {170, 219, 85, 255}, {170, 219, 170, 255},
{170, 219, 255, 255}, {170, 255, 0, 255}, {170, 255, 85, 255},
{170, 255, 170, 255}, {170, 255, 255, 255}, {255, 0, 0, 255},
{255, 0, 85, 255}, {255, 0, 170, 255}, {255, 0, 255, 255},
{255, 36, 0, 255}, {255, 36, 85, 255}, {255, 36, 170, 255},
{255, 36, 255, 255}, {255, 73, 0, 255}, {255, 73, 85, 255},
{255, 73, 170, 255}, {255, 73, 255, 255}, {255, 109, 0, 255},
{255, 109, 85, 255}, {255, 109, 170, 255}, {255, 109, 255, 255},
{255, 146, 0, 255}, {255, 146, 85, 255}, {255, 146, 170, 255},
{255, 146, 255, 255}, {255, 182, 0, 255}, {255, 182, 85, 255},
{255, 182, 170, 255}, {255, 182, 255, 255}, {255, 219, 0, 255},
{255, 219, 85, 255}, {255, 219, 170, 255}, {255, 219, 255, 255},
{255, 255, 0, 255}, {255, 255, 85, 255}, {255, 255, 170, 255},
{255, 255, 255, 255}};
static const int default_palette_size =
(int)(sizeof(default_palette_colors) / sizeof(SDL_Color));
#endif

View File

@ -1,26 +0,0 @@
/* array structure interface version 3 declarations */
#if !defined(PG_ARRAYINTER_HEADER)
#define PG_ARRAYINTER_HEADER
static const int PAI_CONTIGUOUS = 0x01;
static const int PAI_FORTRAN = 0x02;
static const int PAI_ALIGNED = 0x100;
static const int PAI_NOTSWAPPED = 0x200;
static const int PAI_WRITEABLE = 0x400;
static const int PAI_ARR_HAS_DESCR = 0x800;
typedef struct {
int two; /* contains the integer 2 -- simple sanity check */
int nd; /* number of dimensions */
char typekind; /* kind in array -- character code of typestr */
int itemsize; /* size of each element */
int flags; /* flags indicating how the data should be */
/* interpreted */
Py_intptr_t *shape; /* A length-nd array of shape information */
Py_intptr_t *strides; /* A length-nd array of stride information */
void *data; /* A pointer to the first element of the array */
PyObject *descr; /* NULL or a data-description */
} PyArrayInterface;
#endif

View File

@ -1,7 +0,0 @@
#ifndef PG_BUFPROXY_INTERNAL_H
#define PG_BUFPROXY_INTERNAL_H
#include "include/pygame_bufferproxy.h"
#define PYGAMEAPI_BUFPROXY_NUMSLOTS 4
#endif /* ~PG_BUFPROXY_INTERNAL_H */

View File

@ -1,57 +0,0 @@
/* Python 2.x/3.x compatibility tools (internal)
*/
#ifndef PGCOMPAT_INTERNAL_H
#define PGCOMPAT_INTERNAL_H
#include "include/pgcompat.h"
/* Module init function returns new module instance. */
#define MODINIT_DEFINE(mod_name) PyMODINIT_FUNC PyInit_##mod_name(void)
/* Defaults for unicode file path encoding */
#if defined(MS_WIN32)
#define UNICODE_DEF_FS_ERROR "replace"
#else
#define UNICODE_DEF_FS_ERROR "surrogateescape"
#endif
#define RELATIVE_MODULE(m) ("." m)
#ifndef Py_TPFLAGS_HAVE_NEWBUFFER
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#ifndef Py_TPFLAGS_HAVE_CLASS
#define Py_TPFLAGS_HAVE_CLASS 0
#endif
#ifndef Py_TPFLAGS_CHECKTYPES
#define Py_TPFLAGS_CHECKTYPES 0
#endif
#define Slice_GET_INDICES_EX(slice, length, start, stop, step, slicelength) \
PySlice_GetIndicesEx(slice, length, start, stop, step, slicelength)
#if defined(SDL_VERSION_ATLEAST)
#if !(SDL_VERSION_ATLEAST(2, 0, 5))
/* These functions require SDL 2.0.5 or greater.
https://wiki.libsdl.org/SDL_SetWindowResizable
*/
void
SDL_SetWindowResizable(SDL_Window *window, SDL_bool resizable);
int
SDL_GetWindowOpacity(SDL_Window *window, float *opacity);
int
SDL_SetWindowOpacity(SDL_Window *window, float opacity);
int
SDL_SetWindowModalFor(SDL_Window *modal_window, SDL_Window *parent_window);
int
SDL_SetWindowInputFocus(SDL_Window *window);
SDL_Surface *
SDL_CreateRGBSurfaceWithFormat(Uint32 flags, int width, int height, int depth,
Uint32 format);
#endif /* !(SDL_VERSION_ATLEAST(2, 0, 5)) */
#endif /* defined(SDL_VERSION_ATLEAST) */
#endif /* ~PGCOMPAT_INTERNAL_H */

View File

@ -1,20 +0,0 @@
#if !defined(PGOPENGL_H)
#define PGOPENGL_H
/** This header includes definitions of Opengl functions as pointer types for
** use with the SDL function SDL_GL_GetProcAddress.
**/
#if defined(_WIN32)
#define GL_APIENTRY __stdcall
#else
#define GL_APIENTRY
#endif
typedef void(GL_APIENTRY *GL_glReadPixels_Func)(int, int, int, int,
unsigned int, unsigned int,
void *);
typedef void(GL_APIENTRY *GL_glViewport_Func)(int, int, unsigned int,
unsigned int);
#endif

View File

@ -1,39 +0,0 @@
/* platform/compiler adjustments (internal) */
#ifndef PG_PLATFORM_INTERNAL_H
#define PG_PLATFORM_INTERNAL_H
/* This must be before all else */
#if defined(__SYMBIAN32__) && defined(OPENC)
#include <sys/types.h>
#if defined(__WINS__)
void *
_alloca(size_t size);
#define alloca _alloca
#endif /* __WINS__ */
#endif /* defined(__SYMBIAN32__) && defined(OPENC) */
#include "include/pgplatform.h"
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef ABS
#define ABS(a) (((a) < 0) ? -(a) : (a))
#endif
#if defined(macintosh) && defined(__MWERKS__) || defined(__SYMBIAN32__)
#define PYGAME_EXPORT __declspec(export)
#else
#define PYGAME_EXPORT
#endif
/* warnings */
#define PG_STRINGIZE_HELPER(x) #x
#define PG_STRINGIZE(x) PG_STRINGIZE_HELPER(x)
#define PG_WARN(desc) \
message(__FILE__ "(" PG_STRINGIZE(__LINE__) "): WARNING: " #desc)
#endif /* ~PG_PLATFORM_INTERNAL_H */

View File

@ -1,32 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
/* This will use PYGAMEAPI_DEFINE_SLOTS instead
* of PYGAMEAPI_EXTERN_SLOTS for base modules.
*/
#ifndef PYGAME_INTERNAL_H
#define PYGAME_INTERNAL_H
#define PYGAME_H
#include "_pygame.h"
#endif /* ~PYGAME_INTERNAL_H */

View File

@ -1,147 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2006, 2007 Rene Dudfield, Marcus von Appen
Originally put in the public domain by Sam Lantinga.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef SCRAP_H
#define SCRAP_H
/* This is unconditionally defined in Python.h */
#if defined(_POSIX_C_SOURCE)
#undef _POSIX_C_SOURCE
#endif
#include <Python.h>
/* Handle clipboard text and data in arbitrary formats */
/**
* Predefined supported pygame scrap types.
*/
#define PYGAME_SCRAP_TEXT "text/plain"
#define PYGAME_SCRAP_BMP "image/bmp"
#define PYGAME_SCRAP_PPM "image/ppm"
#define PYGAME_SCRAP_PBM "image/pbm"
/**
* The supported scrap clipboard types.
*
* This is only relevant in a X11 environment, which supports mouse
* selections as well. For Win32 and MacOS environments the default
* clipboard is used, no matter what value is passed.
*/
typedef enum {
SCRAP_CLIPBOARD,
SCRAP_SELECTION /* only supported in X11 environments. */
} ScrapClipType;
/**
* Macro for initialization checks.
*/
#define PYGAME_SCRAP_INIT_CHECK() \
if (!pygame_scrap_initialized()) \
return (PyErr_SetString(pgExc_SDLError, "scrap system not initialized."), \
NULL)
/**
* \brief Checks, whether the pygame scrap module was initialized.
*
* \return 1 if the modules was initialized, 0 otherwise.
*/
extern int
pygame_scrap_initialized(void);
/**
* \brief Initializes the pygame scrap module internals. Call this before any
* other method.
*
* \return 1 on successful initialization, 0 otherwise.
*/
extern int
pygame_scrap_init(void);
/**
* \brief Checks, whether the pygame window lost the clipboard focus or not.
*
* \return 1 if the window lost the focus, 0 otherwise.
*/
extern int
pygame_scrap_lost(void);
/**
* \brief Places content of a specific type into the clipboard.
*
* \note For X11 the following notes are important: The following types
* are reserved for internal usage and thus will throw an error on
* setting them: "TIMESTAMP", "TARGETS", "SDL_SELECTION".
* Setting PYGAME_SCRAP_TEXT ("text/plain") will also automatically
* set the X11 types "STRING" (XA_STRING), "TEXT" and "UTF8_STRING".
*
* For Win32 the following notes are important: Setting
* PYGAME_SCRAP_TEXT ("text/plain") will also automatically set
* the Win32 type "TEXT" (CF_TEXT).
*
* For QNX the following notes are important: Setting
* PYGAME_SCRAP_TEXT ("text/plain") will also automatically set
* the QNX type "TEXT" (Ph_CL_TEXT).
*
* \param type The type of the content.
* \param srclen The length of the content.
* \param src The NULL terminated content.
* \return 1, if the content could be successfully pasted into the clipboard,
* 0 otherwise.
*/
extern int
pygame_scrap_put(char *type, int srclen, char *src);
/**
* \brief Gets the current content from the clipboard.
*
* \note The received content does not need to be the content previously
* placed in the clipboard using pygame_put_scrap(). See the
* pygame_put_scrap() notes for more details.
*
* \param type The type of the content to receive.
* \param count The size of the returned content.
* \return The content or NULL in case of an error or if no content of the
* specified type was available.
*/
extern char *
pygame_scrap_get(char *type, unsigned long *count);
/**
* \brief Gets the currently available content types from the clipboard.
*
* \return The different available content types or NULL in case of an
* error or if no content type is available.
*/
extern char **
pygame_scrap_get_types(void);
/**
* \brief Checks whether content for the specified scrap type is currently
* available in the clipboard.
*
* \param type The type to check for.
* \return 1, if there is content and 0 otherwise.
*/
extern int
pygame_scrap_contains(char *type);
#endif /* SCRAP_H */

View File

@ -1,355 +0,0 @@
/*
pygame - Python Game Library
Copyright (C) 2000-2001 Pete Shinners
Copyright (C) 2007 Marcus von Appen
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Pete Shinners
pete@shinners.org
*/
#ifndef SURFACE_H
#define SURFACE_H
/* This is defined in SDL.h */
#if defined(_POSIX_C_SOURCE)
#undef _POSIX_C_SOURCE
#endif
#include <SDL.h>
#include "pygame.h"
/* Blend modes */
#define PYGAME_BLEND_ADD 0x1
#define PYGAME_BLEND_SUB 0x2
#define PYGAME_BLEND_MULT 0x3
#define PYGAME_BLEND_MIN 0x4
#define PYGAME_BLEND_MAX 0x5
#define PYGAME_BLEND_RGB_ADD 0x1
#define PYGAME_BLEND_RGB_SUB 0x2
#define PYGAME_BLEND_RGB_MULT 0x3
#define PYGAME_BLEND_RGB_MIN 0x4
#define PYGAME_BLEND_RGB_MAX 0x5
#define PYGAME_BLEND_RGBA_ADD 0x6
#define PYGAME_BLEND_RGBA_SUB 0x7
#define PYGAME_BLEND_RGBA_MULT 0x8
#define PYGAME_BLEND_RGBA_MIN 0x9
#define PYGAME_BLEND_RGBA_MAX 0x10
#define PYGAME_BLEND_PREMULTIPLIED 0x11
#define PYGAME_BLEND_ALPHA_SDL2 0x12
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define GET_PIXEL_24(b) (b[0] + (b[1] << 8) + (b[2] << 16))
#else
#define GET_PIXEL_24(b) (b[2] + (b[1] << 8) + (b[0] << 16))
#endif
#define GET_PIXEL(pxl, bpp, source) \
switch (bpp) { \
case 2: \
pxl = *((Uint16 *)(source)); \
break; \
case 4: \
pxl = *((Uint32 *)(source)); \
break; \
default: { \
Uint8 *b = (Uint8 *)source; \
pxl = GET_PIXEL_24(b); \
} break; \
}
#define GET_PIXELVALS(_sR, _sG, _sB, _sA, px, fmt, ppa) \
SDL_GetRGBA(px, fmt, &(_sR), &(_sG), &(_sB), &(_sA)); \
if (!ppa) { \
_sA = 255; \
}
#define GET_PIXELVALS_1(sr, sg, sb, sa, _src, _fmt) \
sr = _fmt->palette->colors[*((Uint8 *)(_src))].r; \
sg = _fmt->palette->colors[*((Uint8 *)(_src))].g; \
sb = _fmt->palette->colors[*((Uint8 *)(_src))].b; \
sa = 255;
/* For 1 byte palette pixels */
#define SET_PIXELVAL(px, fmt, _dR, _dG, _dB, _dA) \
*(px) = (Uint8)SDL_MapRGBA(fmt, _dR, _dG, _dB, _dA)
#if SDL_BYTEORDER == SDL_LIL_ENDIAN
#define SET_OFFSETS_24(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 0 : fmt->Rshift == 8 ? 1 : 2); \
og = (fmt->Gshift == 0 ? 0 : fmt->Gshift == 8 ? 1 : 2); \
ob = (fmt->Bshift == 0 ? 0 : fmt->Bshift == 8 ? 1 : 2); \
}
#define SET_OFFSETS_32(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 0 \
: fmt->Rshift == 8 ? 1 \
: fmt->Rshift == 16 ? 2 \
: 3); \
og = (fmt->Gshift == 0 ? 0 \
: fmt->Gshift == 8 ? 1 \
: fmt->Gshift == 16 ? 2 \
: 3); \
ob = (fmt->Bshift == 0 ? 0 \
: fmt->Bshift == 8 ? 1 \
: fmt->Bshift == 16 ? 2 \
: 3); \
}
#else
#define SET_OFFSETS_24(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 2 : fmt->Rshift == 8 ? 1 : 0); \
og = (fmt->Gshift == 0 ? 2 : fmt->Gshift == 8 ? 1 : 0); \
ob = (fmt->Bshift == 0 ? 2 : fmt->Bshift == 8 ? 1 : 0); \
}
#define SET_OFFSETS_32(or, og, ob, fmt) \
{ \
or = (fmt->Rshift == 0 ? 3 \
: fmt->Rshift == 8 ? 2 \
: fmt->Rshift == 16 ? 1 \
: 0); \
og = (fmt->Gshift == 0 ? 3 \
: fmt->Gshift == 8 ? 2 \
: fmt->Gshift == 16 ? 1 \
: 0); \
ob = (fmt->Bshift == 0 ? 3 \
: fmt->Bshift == 8 ? 2 \
: fmt->Bshift == 16 ? 1 \
: 0); \
}
#endif
#define CREATE_PIXEL(buf, r, g, b, a, bp, ft) \
switch (bp) { \
case 2: \
*((Uint16 *)(buf)) = ((r >> ft->Rloss) << ft->Rshift) | \
((g >> ft->Gloss) << ft->Gshift) | \
((b >> ft->Bloss) << ft->Bshift) | \
((a >> ft->Aloss) << ft->Ashift); \
break; \
case 4: \
*((Uint32 *)(buf)) = ((r >> ft->Rloss) << ft->Rshift) | \
((g >> ft->Gloss) << ft->Gshift) | \
((b >> ft->Bloss) << ft->Bshift) | \
((a >> ft->Aloss) << ft->Ashift); \
break; \
}
/* Pretty good idea from Tom Duff :-). */
#define LOOP_UNROLLED4(code, n, width) \
n = (width + 3) / 4; \
switch (width & 3) { \
case 0: \
do { \
code; \
case 3: \
code; \
case 2: \
code; \
case 1: \
code; \
} while (--n > 0); \
}
/* Used in the srcbpp == dstbpp == 1 blend functions */
#define REPEAT_3(code) \
code; \
code; \
code;
#define REPEAT_4(code) \
code; \
code; \
code; \
code;
#define BLEND_ADD(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR + sR; \
dR = (tmp <= 255 ? tmp : 255); \
tmp = dG + sG; \
dG = (tmp <= 255 ? tmp : 255); \
tmp = dB + sB; \
dB = (tmp <= 255 ? tmp : 255);
#define BLEND_SUB(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR - sR; \
dR = (tmp >= 0 ? tmp : 0); \
tmp = dG - sG; \
dG = (tmp >= 0 ? tmp : 0); \
tmp = dB - sB; \
dB = (tmp >= 0 ? tmp : 0);
#define BLEND_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \
dR = (dR && sR) ? (dR * sR) >> 8 : 0; \
dG = (dG && sG) ? (dG * sG) >> 8 : 0; \
dB = (dB && sB) ? (dB * sB) >> 8 : 0;
#define BLEND_MIN(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR < dR) { \
dR = sR; \
} \
if (sG < dG) { \
dG = sG; \
} \
if (sB < dB) { \
dB = sB; \
}
#define BLEND_MAX(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR > dR) { \
dR = sR; \
} \
if (sG > dG) { \
dG = sG; \
} \
if (sB > dB) { \
dB = sB; \
}
#define BLEND_RGBA_ADD(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR + sR; \
dR = (tmp <= 255 ? tmp : 255); \
tmp = dG + sG; \
dG = (tmp <= 255 ? tmp : 255); \
tmp = dB + sB; \
dB = (tmp <= 255 ? tmp : 255); \
tmp = dA + sA; \
dA = (tmp <= 255 ? tmp : 255);
#define BLEND_RGBA_SUB(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
tmp = dR - sR; \
dR = (tmp >= 0 ? tmp : 0); \
tmp = dG - sG; \
dG = (tmp >= 0 ? tmp : 0); \
tmp = dB - sB; \
dB = (tmp >= 0 ? tmp : 0); \
tmp = dA - sA; \
dA = (tmp >= 0 ? tmp : 0);
#define BLEND_RGBA_MULT(sR, sG, sB, sA, dR, dG, dB, dA) \
dR = (dR && sR) ? (dR * sR) >> 8 : 0; \
dG = (dG && sG) ? (dG * sG) >> 8 : 0; \
dB = (dB && sB) ? (dB * sB) >> 8 : 0; \
dA = (dA && sA) ? (dA * sA) >> 8 : 0;
#define BLEND_RGBA_MIN(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR < dR) { \
dR = sR; \
} \
if (sG < dG) { \
dG = sG; \
} \
if (sB < dB) { \
dB = sB; \
} \
if (sA < dA) { \
dA = sA; \
}
#define BLEND_RGBA_MAX(sR, sG, sB, sA, dR, dG, dB, dA) \
if (sR > dR) { \
dR = sR; \
} \
if (sG > dG) { \
dG = sG; \
} \
if (sB > dB) { \
dB = sB; \
} \
if (sA > dA) { \
dA = sA; \
}
#if 1
/* Choose an alpha blend equation. If the sign is preserved on a right shift
* then use a specialized, faster, equation. Otherwise a more general form,
* where all additions are done before the shift, is needed.
*/
#if (-1 >> 1) < 0
#define ALPHA_BLEND_COMP(sC, dC, sA) ((((sC - dC) * sA + sC) >> 8) + dC)
#else
#define ALPHA_BLEND_COMP(sC, dC, sA) (((dC << 8) + (sC - dC) * sA + sC) >> 8)
#endif
#define ALPHA_BLEND(sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
if (dA) { \
dR = ALPHA_BLEND_COMP(sR, dR, sA); \
dG = ALPHA_BLEND_COMP(sG, dG, sA); \
dB = ALPHA_BLEND_COMP(sB, dB, sA); \
dA = sA + dA - ((sA * dA) / 255); \
} \
else { \
dR = sR; \
dG = sG; \
dB = sB; \
dA = sA; \
} \
} while (0)
#define ALPHA_BLEND_PREMULTIPLIED_COMP(sC, dC, sA) \
(sC + dC - ((dC + 1) * sA >> 8))
#define ALPHA_BLEND_PREMULTIPLIED(tmp, sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
dR = ALPHA_BLEND_PREMULTIPLIED_COMP(sR, dR, sA); \
dG = ALPHA_BLEND_PREMULTIPLIED_COMP(sG, dG, sA); \
dB = ALPHA_BLEND_PREMULTIPLIED_COMP(sB, dB, sA); \
dA = ALPHA_BLEND_PREMULTIPLIED_COMP(sA, dA, sA); \
} while (0)
#elif 0
#define ALPHA_BLEND(sR, sG, sB, sA, dR, dG, dB, dA) \
do { \
if (sA) { \
if (dA && sA < 255) { \
int dContrib = dA * (255 - sA) / 255; \
dA = sA + dA - ((sA * dA) / 255); \
dR = (dR * dContrib + sR * sA) / dA; \
dG = (dG * dContrib + sG * sA) / dA; \
dB = (dB * dContrib + sB * sA) / dA; \
} \
else { \
dR = sR; \
dG = sG; \
dB = sB; \
dA = sA; \
} \
} \
} while (0)
#endif
int
surface_fill_blend(SDL_Surface *surface, SDL_Rect *rect, Uint32 color,
int blendargs);
void
surface_respect_clip_rect(SDL_Surface *surface, SDL_Rect *rect);
int
pygame_AlphaBlit(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst,
SDL_Rect *dstrect, int the_args);
int
pygame_Blit(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst,
SDL_Rect *dstrect, int the_args);
#endif /* SURFACE_H */

View File

@ -1,187 +0,0 @@
# don't import any costly modules
import sys
import os
is_pypy = '__pypy__' in sys.builtin_module_names
def warn_distutils_present():
if 'distutils' not in sys.modules:
return
if is_pypy and sys.version_info < (3, 7):
# PyPy for 3.6 unconditionally imports distutils, so bypass the warning
# https://foss.heptapod.net/pypy/pypy/-/blob/be829135bc0d758997b3566062999ee8b23872b4/lib-python/3/site.py#L250
return
import warnings
warnings.warn(
"Distutils was imported before Setuptools, but importing Setuptools "
"also replaces the `distutils` module in `sys.modules`. This may lead "
"to undesirable behaviors or errors. To avoid these issues, avoid "
"using distutils directly, ensure that setuptools is installed in the "
"traditional way (e.g. not an editable install), and/or make sure "
"that setuptools is always imported before distutils.")
def clear_distutils():
if 'distutils' not in sys.modules:
return
import warnings
warnings.warn("Setuptools is replacing distutils.")
mods = [
name for name in sys.modules
if name == "distutils" or name.startswith("distutils.")
]
for name in mods:
del sys.modules[name]
def enabled():
"""
Allow selection of distutils by environment variable.
"""
which = os.environ.get('SETUPTOOLS_USE_DISTUTILS', 'local')
return which == 'local'
def ensure_local_distutils():
import importlib
clear_distutils()
# With the DistutilsMetaFinder in place,
# perform an import to cause distutils to be
# loaded from setuptools._distutils. Ref #2906.
with shim():
importlib.import_module('distutils')
# check that submodules load as expected
core = importlib.import_module('distutils.core')
assert '_distutils' in core.__file__, core.__file__
assert 'setuptools._distutils.log' not in sys.modules
def do_override():
"""
Ensure that the local copy of distutils is preferred over stdlib.
See https://github.com/pypa/setuptools/issues/417#issuecomment-392298401
for more motivation.
"""
if enabled():
warn_distutils_present()
ensure_local_distutils()
class _TrivialRe:
def __init__(self, *patterns):
self._patterns = patterns
def match(self, string):
return all(pat in string for pat in self._patterns)
class DistutilsMetaFinder:
def find_spec(self, fullname, path, target=None):
if path is not None:
return
method_name = 'spec_for_{fullname}'.format(**locals())
method = getattr(self, method_name, lambda: None)
return method()
def spec_for_distutils(self):
if self.is_cpython():
return
import importlib
import importlib.abc
import importlib.util
try:
mod = importlib.import_module('setuptools._distutils')
except Exception:
# There are a couple of cases where setuptools._distutils
# may not be present:
# - An older Setuptools without a local distutils is
# taking precedence. Ref #2957.
# - Path manipulation during sitecustomize removes
# setuptools from the path but only after the hook
# has been loaded. Ref #2980.
# In either case, fall back to stdlib behavior.
return
class DistutilsLoader(importlib.abc.Loader):
def create_module(self, spec):
mod.__name__ = 'distutils'
return mod
def exec_module(self, module):
pass
return importlib.util.spec_from_loader(
'distutils', DistutilsLoader(), origin=mod.__file__
)
@staticmethod
def is_cpython():
"""
Suppress supplying distutils for CPython (build and tests).
Ref #2965 and #3007.
"""
return os.path.isfile('pybuilddir.txt')
def spec_for_pip(self):
"""
Ensure stdlib distutils when running under pip.
See pypa/pip#8761 for rationale.
"""
if self.pip_imported_during_build():
return
clear_distutils()
self.spec_for_distutils = lambda: None
@classmethod
def pip_imported_during_build(cls):
"""
Detect if pip is being imported in a build script. Ref #2355.
"""
import traceback
return any(
cls.frame_file_is_setup(frame)
for frame, line in traceback.walk_stack(None)
)
@staticmethod
def frame_file_is_setup(frame):
"""
Return True if the indicated frame suggests a setup.py file.
"""
# some frames may not have __file__ (#2940)
return frame.f_globals.get('__file__', '').endswith('setup.py')
DISTUTILS_FINDER = DistutilsMetaFinder()
def add_shim():
DISTUTILS_FINDER in sys.meta_path or insert_shim()
class shim:
def __enter__(self):
insert_shim()
def __exit__(self, exc, value, tb):
remove_shim()
def insert_shim():
sys.meta_path.insert(0, DISTUTILS_FINDER)
def remove_shim():
try:
sys.meta_path.remove(DISTUTILS_FINDER)
except ValueError:
pass

View File

@ -1 +0,0 @@
__import__('_distutils_hack').do_override()

View File

@ -1 +0,0 @@
import os; var = 'SETUPTOOLS_USE_DISTUTILS'; enabled = os.environ.get(var, 'local') == 'local'; enabled and __import__('_distutils_hack').add_shim();

View File

@ -1,20 +0,0 @@
Copyright (c) 2008-present The pip developers (see AUTHORS.txt file)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,92 +0,0 @@
Metadata-Version: 2.1
Name: pip
Version: 22.0.4
Summary: The PyPA recommended tool for installing Python packages.
Home-page: https://pip.pypa.io/
Author: The pip developers
Author-email: distutils-sig@python.org
License: MIT
Project-URL: Documentation, https://pip.pypa.io
Project-URL: Source, https://github.com/pypa/pip
Project-URL: Changelog, https://pip.pypa.io/en/stable/news/
Platform: UNKNOWN
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Topic :: Software Development :: Build Tools
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: Implementation :: CPython
Classifier: Programming Language :: Python :: Implementation :: PyPy
Requires-Python: >=3.7
License-File: LICENSE.txt
pip - The Python Package Installer
==================================
.. image:: https://img.shields.io/pypi/v/pip.svg
:target: https://pypi.org/project/pip/
.. image:: https://readthedocs.org/projects/pip/badge/?version=latest
:target: https://pip.pypa.io/en/latest
pip is the `package installer`_ for Python. You can use pip to install packages from the `Python Package Index`_ and other indexes.
Please take a look at our documentation for how to install and use pip:
* `Installation`_
* `Usage`_
We release updates regularly, with a new version every 3 months. Find more details in our documentation:
* `Release notes`_
* `Release process`_
In pip 20.3, we've `made a big improvement to the heart of pip`_; `learn more`_. We want your input, so `sign up for our user experience research studies`_ to help us do it right.
**Note**: pip 21.0, in January 2021, removed Python 2 support, per pip's `Python 2 support policy`_. Please migrate to Python 3.
If you find bugs, need help, or want to talk to the developers, please use our mailing lists or chat rooms:
* `Issue tracking`_
* `Discourse channel`_
* `User IRC`_
If you want to get involved head over to GitHub to get the source code, look at our development documentation and feel free to jump on the developer mailing lists and chat rooms:
* `GitHub page`_
* `Development documentation`_
* `Development mailing list`_
* `Development IRC`_
Code of Conduct
---------------
Everyone interacting in the pip project's codebases, issue trackers, chat
rooms, and mailing lists is expected to follow the `PSF Code of Conduct`_.
.. _package installer: https://packaging.python.org/guides/tool-recommendations/
.. _Python Package Index: https://pypi.org
.. _Installation: https://pip.pypa.io/en/stable/installation/
.. _Usage: https://pip.pypa.io/en/stable/
.. _Release notes: https://pip.pypa.io/en/stable/news.html
.. _Release process: https://pip.pypa.io/en/latest/development/release-process/
.. _GitHub page: https://github.com/pypa/pip
.. _Development documentation: https://pip.pypa.io/en/latest/development
.. _made a big improvement to the heart of pip: https://pyfound.blogspot.com/2020/11/pip-20-3-new-resolver.html
.. _learn more: https://pip.pypa.io/en/latest/user_guide/#changes-to-the-pip-dependency-resolver-in-20-3-2020
.. _sign up for our user experience research studies: https://pyfound.blogspot.com/2020/03/new-pip-resolver-to-roll-out-this-year.html
.. _Python 2 support policy: https://pip.pypa.io/en/latest/development/release-process/#python-2-support
.. _Issue tracking: https://github.com/pypa/pip/issues
.. _Discourse channel: https://discuss.python.org/c/packaging
.. _Development mailing list: https://mail.python.org/mailman3/lists/distutils-sig.python.org/
.. _User IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa
.. _Development IRC: https://kiwiirc.com/nextclient/#ircs://irc.libera.chat:+6697/pypa-dev
.. _PSF Code of Conduct: https://github.com/pypa/.github/blob/main/CODE_OF_CONDUCT.md

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +0,0 @@
Wheel-Version: 1.0
Generator: bdist_wheel (0.37.1)
Root-Is-Purelib: true
Tag: py3-none-any

View File

@ -1,5 +0,0 @@
[console_scripts]
pip = pip._internal.cli.main:main
pip3 = pip._internal.cli.main:main
pip3.9 = pip._internal.cli.main:main

View File

@ -1,13 +0,0 @@
from typing import List, Optional
__version__ = "22.0.4"
def main(args: Optional[List[str]] = None) -> int:
"""This is an internal API only meant for use by pip's own console scripts.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)

View File

@ -1,31 +0,0 @@
import os
import sys
import warnings
# Remove '' and current working directory from the first entry
# of sys.path, if present to avoid using current directory
# in pip commands check, freeze, install, list and show,
# when invoked as python -m pip <command>
if sys.path[0] in ("", os.getcwd()):
sys.path.pop(0)
# If we are running from a wheel, add the wheel to sys.path
# This allows the usage python pip-*.whl/pip install pip-*.whl
if __package__ == "":
# __file__ is pip-*.whl/pip/__main__.py
# first dirname call strips of '/__main__.py', second strips off '/pip'
# Resulting path is the name of the wheel itself
# Add that to sys.path so we can import pip
path = os.path.dirname(os.path.dirname(__file__))
sys.path.insert(0, path)
if __name__ == "__main__":
# Work around the error reported in #9540, pending a proper fix.
# Note: It is essential the warning filter is set *before* importing
# pip, as the deprecation happens at import time, not runtime.
warnings.filterwarnings(
"ignore", category=DeprecationWarning, module=".*packaging\\.version"
)
from pip._internal.cli.main import main as _main
sys.exit(_main())

View File

@ -1,19 +0,0 @@
from typing import List, Optional
import pip._internal.utils.inject_securetransport # noqa
from pip._internal.utils import _log
# init_logging() must be called before any call to logging.getLogger()
# which happens at import of most modules.
_log.init_logging()
def main(args: (Optional[List[str]]) = None) -> int:
"""This is preserved for old console scripts that may still be referencing
it.
For additional details, see https://github.com/pypa/pip/issues/7498.
"""
from pip._internal.utils.entrypoints import _wrapper
return _wrapper(args)

View File

@ -1,296 +0,0 @@
"""Build Environment used for isolation during sdist building
"""
import contextlib
import logging
import os
import pathlib
import sys
import textwrap
import zipfile
from collections import OrderedDict
from sysconfig import get_paths
from types import TracebackType
from typing import TYPE_CHECKING, Iterable, Iterator, List, Optional, Set, Tuple, Type
from pip._vendor.certifi import where
from pip._vendor.packaging.requirements import Requirement
from pip._vendor.packaging.version import Version
from pip import __file__ as pip_location
from pip._internal.cli.spinners import open_spinner
from pip._internal.locations import get_platlib, get_prefixed_libs, get_purelib
from pip._internal.metadata import get_environment
from pip._internal.utils.subprocess import call_subprocess
from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
if TYPE_CHECKING:
from pip._internal.index.package_finder import PackageFinder
logger = logging.getLogger(__name__)
class _Prefix:
def __init__(self, path: str) -> None:
self.path = path
self.setup = False
self.bin_dir = get_paths(
"nt" if os.name == "nt" else "posix_prefix",
vars={"base": path, "platbase": path},
)["scripts"]
self.lib_dirs = get_prefixed_libs(path)
@contextlib.contextmanager
def _create_standalone_pip() -> Iterator[str]:
"""Create a "standalone pip" zip file.
The zip file's content is identical to the currently-running pip.
It will be used to install requirements into the build environment.
"""
source = pathlib.Path(pip_location).resolve().parent
# Return the current instance if `source` is not a directory. We can't build
# a zip from this, and it likely means the instance is already standalone.
if not source.is_dir():
yield str(source)
return
with TempDirectory(kind="standalone-pip") as tmp_dir:
pip_zip = os.path.join(tmp_dir.path, "__env_pip__.zip")
kwargs = {}
if sys.version_info >= (3, 8):
kwargs["strict_timestamps"] = False
with zipfile.ZipFile(pip_zip, "w", **kwargs) as zf:
for child in source.rglob("*"):
zf.write(child, child.relative_to(source.parent).as_posix())
yield os.path.join(pip_zip, "pip")
class BuildEnvironment:
"""Creates and manages an isolated environment to install build deps"""
def __init__(self) -> None:
temp_dir = TempDirectory(kind=tempdir_kinds.BUILD_ENV, globally_managed=True)
self._prefixes = OrderedDict(
(name, _Prefix(os.path.join(temp_dir.path, name)))
for name in ("normal", "overlay")
)
self._bin_dirs: List[str] = []
self._lib_dirs: List[str] = []
for prefix in reversed(list(self._prefixes.values())):
self._bin_dirs.append(prefix.bin_dir)
self._lib_dirs.extend(prefix.lib_dirs)
# Customize site to:
# - ensure .pth files are honored
# - prevent access to system site packages
system_sites = {
os.path.normcase(site) for site in (get_purelib(), get_platlib())
}
self._site_dir = os.path.join(temp_dir.path, "site")
if not os.path.exists(self._site_dir):
os.mkdir(self._site_dir)
with open(
os.path.join(self._site_dir, "sitecustomize.py"), "w", encoding="utf-8"
) as fp:
fp.write(
textwrap.dedent(
"""
import os, site, sys
# First, drop system-sites related paths.
original_sys_path = sys.path[:]
known_paths = set()
for path in {system_sites!r}:
site.addsitedir(path, known_paths=known_paths)
system_paths = set(
os.path.normcase(path)
for path in sys.path[len(original_sys_path):]
)
original_sys_path = [
path for path in original_sys_path
if os.path.normcase(path) not in system_paths
]
sys.path = original_sys_path
# Second, add lib directories.
# ensuring .pth file are processed.
for path in {lib_dirs!r}:
assert not path in sys.path
site.addsitedir(path)
"""
).format(system_sites=system_sites, lib_dirs=self._lib_dirs)
)
def __enter__(self) -> None:
self._save_env = {
name: os.environ.get(name, None)
for name in ("PATH", "PYTHONNOUSERSITE", "PYTHONPATH")
}
path = self._bin_dirs[:]
old_path = self._save_env["PATH"]
if old_path:
path.extend(old_path.split(os.pathsep))
pythonpath = [self._site_dir]
os.environ.update(
{
"PATH": os.pathsep.join(path),
"PYTHONNOUSERSITE": "1",
"PYTHONPATH": os.pathsep.join(pythonpath),
}
)
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
for varname, old_value in self._save_env.items():
if old_value is None:
os.environ.pop(varname, None)
else:
os.environ[varname] = old_value
def check_requirements(
self, reqs: Iterable[str]
) -> Tuple[Set[Tuple[str, str]], Set[str]]:
"""Return 2 sets:
- conflicting requirements: set of (installed, wanted) reqs tuples
- missing requirements: set of reqs
"""
missing = set()
conflicting = set()
if reqs:
env = get_environment(self._lib_dirs)
for req_str in reqs:
req = Requirement(req_str)
dist = env.get_distribution(req.name)
if not dist:
missing.add(req_str)
continue
if isinstance(dist.version, Version):
installed_req_str = f"{req.name}=={dist.version}"
else:
installed_req_str = f"{req.name}==={dist.version}"
if dist.version not in req.specifier:
conflicting.add((installed_req_str, req_str))
# FIXME: Consider direct URL?
return conflicting, missing
def install_requirements(
self,
finder: "PackageFinder",
requirements: Iterable[str],
prefix_as_string: str,
*,
kind: str,
) -> None:
prefix = self._prefixes[prefix_as_string]
assert not prefix.setup
prefix.setup = True
if not requirements:
return
with contextlib.ExitStack() as ctx:
pip_runnable = ctx.enter_context(_create_standalone_pip())
self._install_requirements(
pip_runnable,
finder,
requirements,
prefix,
kind=kind,
)
@staticmethod
def _install_requirements(
pip_runnable: str,
finder: "PackageFinder",
requirements: Iterable[str],
prefix: _Prefix,
*,
kind: str,
) -> None:
args: List[str] = [
sys.executable,
pip_runnable,
"install",
"--ignore-installed",
"--no-user",
"--prefix",
prefix.path,
"--no-warn-script-location",
]
if logger.getEffectiveLevel() <= logging.DEBUG:
args.append("-v")
for format_control in ("no_binary", "only_binary"):
formats = getattr(finder.format_control, format_control)
args.extend(
(
"--" + format_control.replace("_", "-"),
",".join(sorted(formats or {":none:"})),
)
)
index_urls = finder.index_urls
if index_urls:
args.extend(["-i", index_urls[0]])
for extra_index in index_urls[1:]:
args.extend(["--extra-index-url", extra_index])
else:
args.append("--no-index")
for link in finder.find_links:
args.extend(["--find-links", link])
for host in finder.trusted_hosts:
args.extend(["--trusted-host", host])
if finder.allow_all_prereleases:
args.append("--pre")
if finder.prefer_binary:
args.append("--prefer-binary")
args.append("--")
args.extend(requirements)
extra_environ = {"_PIP_STANDALONE_CERT": where()}
with open_spinner(f"Installing {kind}") as spinner:
call_subprocess(
args,
command_desc=f"pip subprocess to install {kind}",
spinner=spinner,
extra_environ=extra_environ,
)
class NoOpBuildEnvironment(BuildEnvironment):
"""A no-op drop-in replacement for BuildEnvironment"""
def __init__(self) -> None:
pass
def __enter__(self) -> None:
pass
def __exit__(
self,
exc_type: Optional[Type[BaseException]],
exc_val: Optional[BaseException],
exc_tb: Optional[TracebackType],
) -> None:
pass
def cleanup(self) -> None:
pass
def install_requirements(
self,
finder: "PackageFinder",
requirements: Iterable[str],
prefix_as_string: str,
*,
kind: str,
) -> None:
raise NotImplementedError()

View File

@ -1,264 +0,0 @@
"""Cache Management
"""
import hashlib
import json
import logging
import os
from typing import Any, Dict, List, Optional, Set
from pip._vendor.packaging.tags import Tag, interpreter_name, interpreter_version
from pip._vendor.packaging.utils import canonicalize_name
from pip._internal.exceptions import InvalidWheelFilename
from pip._internal.models.format_control import FormatControl
from pip._internal.models.link import Link
from pip._internal.models.wheel import Wheel
from pip._internal.utils.temp_dir import TempDirectory, tempdir_kinds
from pip._internal.utils.urls import path_to_url
logger = logging.getLogger(__name__)
def _hash_dict(d: Dict[str, str]) -> str:
"""Return a stable sha224 of a dictionary."""
s = json.dumps(d, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
return hashlib.sha224(s.encode("ascii")).hexdigest()
class Cache:
"""An abstract class - provides cache directories for data from links
:param cache_dir: The root of the cache.
:param format_control: An object of FormatControl class to limit
binaries being read from the cache.
:param allowed_formats: which formats of files the cache should store.
('binary' and 'source' are the only allowed values)
"""
def __init__(
self, cache_dir: str, format_control: FormatControl, allowed_formats: Set[str]
) -> None:
super().__init__()
assert not cache_dir or os.path.isabs(cache_dir)
self.cache_dir = cache_dir or None
self.format_control = format_control
self.allowed_formats = allowed_formats
_valid_formats = {"source", "binary"}
assert self.allowed_formats.union(_valid_formats) == _valid_formats
def _get_cache_path_parts(self, link: Link) -> List[str]:
"""Get parts of part that must be os.path.joined with cache_dir"""
# We want to generate an url to use as our cache key, we don't want to
# just re-use the URL because it might have other items in the fragment
# and we don't care about those.
key_parts = {"url": link.url_without_fragment}
if link.hash_name is not None and link.hash is not None:
key_parts[link.hash_name] = link.hash
if link.subdirectory_fragment:
key_parts["subdirectory"] = link.subdirectory_fragment
# Include interpreter name, major and minor version in cache key
# to cope with ill-behaved sdists that build a different wheel
# depending on the python version their setup.py is being run on,
# and don't encode the difference in compatibility tags.
# https://github.com/pypa/pip/issues/7296
key_parts["interpreter_name"] = interpreter_name()
key_parts["interpreter_version"] = interpreter_version()
# Encode our key url with sha224, we'll use this because it has similar
# security properties to sha256, but with a shorter total output (and
# thus less secure). However the differences don't make a lot of
# difference for our use case here.
hashed = _hash_dict(key_parts)
# We want to nest the directories some to prevent having a ton of top
# level directories where we might run out of sub directories on some
# FS.
parts = [hashed[:2], hashed[2:4], hashed[4:6], hashed[6:]]
return parts
def _get_candidates(self, link: Link, canonical_package_name: str) -> List[Any]:
can_not_cache = not self.cache_dir or not canonical_package_name or not link
if can_not_cache:
return []
formats = self.format_control.get_allowed_formats(canonical_package_name)
if not self.allowed_formats.intersection(formats):
return []
candidates = []
path = self.get_path_for_link(link)
if os.path.isdir(path):
for candidate in os.listdir(path):
candidates.append((candidate, path))
return candidates
def get_path_for_link(self, link: Link) -> str:
"""Return a directory to store cached items in for link."""
raise NotImplementedError()
def get(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Link:
"""Returns a link to a cached item if it exists, otherwise returns the
passed link.
"""
raise NotImplementedError()
class SimpleWheelCache(Cache):
"""A cache of wheels for future installs."""
def __init__(self, cache_dir: str, format_control: FormatControl) -> None:
super().__init__(cache_dir, format_control, {"binary"})
def get_path_for_link(self, link: Link) -> str:
"""Return a directory to store cached wheels for link
Because there are M wheels for any one sdist, we provide a directory
to cache them in, and then consult that directory when looking up
cache hits.
We only insert things into the cache if they have plausible version
numbers, so that we don't contaminate the cache with things that were
not unique. E.g. ./package might have dozens of installs done for it
and build a version of 0.0...and if we built and cached a wheel, we'd
end up using the same wheel even if the source has been edited.
:param link: The link of the sdist for which this will cache wheels.
"""
parts = self._get_cache_path_parts(link)
assert self.cache_dir
# Store wheels within the root cache_dir
return os.path.join(self.cache_dir, "wheels", *parts)
def get(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Link:
candidates = []
if not package_name:
return link
canonical_package_name = canonicalize_name(package_name)
for wheel_name, wheel_dir in self._get_candidates(link, canonical_package_name):
try:
wheel = Wheel(wheel_name)
except InvalidWheelFilename:
continue
if canonicalize_name(wheel.name) != canonical_package_name:
logger.debug(
"Ignoring cached wheel %s for %s as it "
"does not match the expected distribution name %s.",
wheel_name,
link,
package_name,
)
continue
if not wheel.supported(supported_tags):
# Built for a different python/arch/etc
continue
candidates.append(
(
wheel.support_index_min(supported_tags),
wheel_name,
wheel_dir,
)
)
if not candidates:
return link
_, wheel_name, wheel_dir = min(candidates)
return Link(path_to_url(os.path.join(wheel_dir, wheel_name)))
class EphemWheelCache(SimpleWheelCache):
"""A SimpleWheelCache that creates it's own temporary cache directory"""
def __init__(self, format_control: FormatControl) -> None:
self._temp_dir = TempDirectory(
kind=tempdir_kinds.EPHEM_WHEEL_CACHE,
globally_managed=True,
)
super().__init__(self._temp_dir.path, format_control)
class CacheEntry:
def __init__(
self,
link: Link,
persistent: bool,
):
self.link = link
self.persistent = persistent
class WheelCache(Cache):
"""Wraps EphemWheelCache and SimpleWheelCache into a single Cache
This Cache allows for gracefully degradation, using the ephem wheel cache
when a certain link is not found in the simple wheel cache first.
"""
def __init__(self, cache_dir: str, format_control: FormatControl) -> None:
super().__init__(cache_dir, format_control, {"binary"})
self._wheel_cache = SimpleWheelCache(cache_dir, format_control)
self._ephem_cache = EphemWheelCache(format_control)
def get_path_for_link(self, link: Link) -> str:
return self._wheel_cache.get_path_for_link(link)
def get_ephem_path_for_link(self, link: Link) -> str:
return self._ephem_cache.get_path_for_link(link)
def get(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Link:
cache_entry = self.get_cache_entry(link, package_name, supported_tags)
if cache_entry is None:
return link
return cache_entry.link
def get_cache_entry(
self,
link: Link,
package_name: Optional[str],
supported_tags: List[Tag],
) -> Optional[CacheEntry]:
"""Returns a CacheEntry with a link to a cached item if it exists or
None. The cache entry indicates if the item was found in the persistent
or ephemeral cache.
"""
retval = self._wheel_cache.get(
link=link,
package_name=package_name,
supported_tags=supported_tags,
)
if retval is not link:
return CacheEntry(retval, persistent=True)
retval = self._ephem_cache.get(
link=link,
package_name=package_name,
supported_tags=supported_tags,
)
if retval is not link:
return CacheEntry(retval, persistent=False)
return None

View File

@ -1,4 +0,0 @@
"""Subpackage containing all of pip's command line interface related code
"""
# This file intentionally does not import submodules

View File

@ -1,171 +0,0 @@
"""Logic that powers autocompletion installed by ``pip completion``.
"""
import optparse
import os
import sys
from itertools import chain
from typing import Any, Iterable, List, Optional
from pip._internal.cli.main_parser import create_main_parser
from pip._internal.commands import commands_dict, create_command
from pip._internal.metadata import get_default_environment
def autocomplete() -> None:
"""Entry Point for completion of main and subcommand options."""
# Don't complete if user hasn't sourced bash_completion file.
if "PIP_AUTO_COMPLETE" not in os.environ:
return
cwords = os.environ["COMP_WORDS"].split()[1:]
cword = int(os.environ["COMP_CWORD"])
try:
current = cwords[cword - 1]
except IndexError:
current = ""
parser = create_main_parser()
subcommands = list(commands_dict)
options = []
# subcommand
subcommand_name: Optional[str] = None
for word in cwords:
if word in subcommands:
subcommand_name = word
break
# subcommand options
if subcommand_name is not None:
# special case: 'help' subcommand has no options
if subcommand_name == "help":
sys.exit(1)
# special case: list locally installed dists for show and uninstall
should_list_installed = not current.startswith("-") and subcommand_name in [
"show",
"uninstall",
]
if should_list_installed:
env = get_default_environment()
lc = current.lower()
installed = [
dist.canonical_name
for dist in env.iter_installed_distributions(local_only=True)
if dist.canonical_name.startswith(lc)
and dist.canonical_name not in cwords[1:]
]
# if there are no dists installed, fall back to option completion
if installed:
for dist in installed:
print(dist)
sys.exit(1)
should_list_installables = (
not current.startswith("-") and subcommand_name == "install"
)
if should_list_installables:
for path in auto_complete_paths(current, "path"):
print(path)
sys.exit(1)
subcommand = create_command(subcommand_name)
for opt in subcommand.parser.option_list_all:
if opt.help != optparse.SUPPRESS_HELP:
for opt_str in opt._long_opts + opt._short_opts:
options.append((opt_str, opt.nargs))
# filter out previously specified options from available options
prev_opts = [x.split("=")[0] for x in cwords[1 : cword - 1]]
options = [(x, v) for (x, v) in options if x not in prev_opts]
# filter options by current input
options = [(k, v) for k, v in options if k.startswith(current)]
# get completion type given cwords and available subcommand options
completion_type = get_path_completion_type(
cwords,
cword,
subcommand.parser.option_list_all,
)
# get completion files and directories if ``completion_type`` is
# ``<file>``, ``<dir>`` or ``<path>``
if completion_type:
paths = auto_complete_paths(current, completion_type)
options = [(path, 0) for path in paths]
for option in options:
opt_label = option[0]
# append '=' to options which require args
if option[1] and option[0][:2] == "--":
opt_label += "="
print(opt_label)
else:
# show main parser options only when necessary
opts = [i.option_list for i in parser.option_groups]
opts.append(parser.option_list)
flattened_opts = chain.from_iterable(opts)
if current.startswith("-"):
for opt in flattened_opts:
if opt.help != optparse.SUPPRESS_HELP:
subcommands += opt._long_opts + opt._short_opts
else:
# get completion type given cwords and all available options
completion_type = get_path_completion_type(cwords, cword, flattened_opts)
if completion_type:
subcommands = list(auto_complete_paths(current, completion_type))
print(" ".join([x for x in subcommands if x.startswith(current)]))
sys.exit(1)
def get_path_completion_type(
cwords: List[str], cword: int, opts: Iterable[Any]
) -> Optional[str]:
"""Get the type of path completion (``file``, ``dir``, ``path`` or None)
:param cwords: same as the environmental variable ``COMP_WORDS``
:param cword: same as the environmental variable ``COMP_CWORD``
:param opts: The available options to check
:return: path completion type (``file``, ``dir``, ``path`` or None)
"""
if cword < 2 or not cwords[cword - 2].startswith("-"):
return None
for opt in opts:
if opt.help == optparse.SUPPRESS_HELP:
continue
for o in str(opt).split("/"):
if cwords[cword - 2].split("=")[0] == o:
if not opt.metavar or any(
x in ("path", "file", "dir") for x in opt.metavar.split("/")
):
return opt.metavar
return None
def auto_complete_paths(current: str, completion_type: str) -> Iterable[str]:
"""If ``completion_type`` is ``file`` or ``path``, list all regular files
and directories starting with ``current``; otherwise only list directories
starting with ``current``.
:param current: The word to be completed
:param completion_type: path completion type(``file``, ``path`` or ``dir``)
:return: A generator of regular files and/or directories
"""
directory, filename = os.path.split(current)
current_path = os.path.abspath(directory)
# Don't complete paths if they can't be accessed
if not os.access(current_path, os.R_OK):
return
filename = os.path.normcase(filename)
# list all files that start with ``filename``
file_list = (
x for x in os.listdir(current_path) if os.path.normcase(x).startswith(filename)
)
for f in file_list:
opt = os.path.join(current_path, f)
comp_file = os.path.normcase(os.path.join(directory, f))
# complete regular files when there is not ``<dir>`` after option
# complete directories when there is ``<file>``, ``<path>`` or
# ``<dir>``after option
if completion_type != "dir" and os.path.isfile(opt):
yield comp_file
elif os.path.isdir(opt):
yield os.path.join(comp_file, "")

View File

@ -1,223 +0,0 @@
"""Base Command class, and related routines"""
import functools
import logging
import logging.config
import optparse
import os
import sys
import traceback
from optparse import Values
from typing import Any, Callable, List, Optional, Tuple
from pip._vendor.rich import traceback as rich_traceback
from pip._internal.cli import cmdoptions
from pip._internal.cli.command_context import CommandContextMixIn
from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip._internal.cli.status_codes import (
ERROR,
PREVIOUS_BUILD_DIR_ERROR,
UNKNOWN_ERROR,
VIRTUALENV_NOT_FOUND,
)
from pip._internal.exceptions import (
BadCommand,
CommandError,
DiagnosticPipError,
InstallationError,
NetworkConnectionError,
PreviousBuildDirError,
UninstallationError,
)
from pip._internal.utils.filesystem import check_path_owner
from pip._internal.utils.logging import BrokenStdoutLoggingError, setup_logging
from pip._internal.utils.misc import get_prog, normalize_path
from pip._internal.utils.temp_dir import TempDirectoryTypeRegistry as TempDirRegistry
from pip._internal.utils.temp_dir import global_tempdir_manager, tempdir_registry
from pip._internal.utils.virtualenv import running_under_virtualenv
__all__ = ["Command"]
logger = logging.getLogger(__name__)
class Command(CommandContextMixIn):
usage: str = ""
ignore_require_venv: bool = False
def __init__(self, name: str, summary: str, isolated: bool = False) -> None:
super().__init__()
self.name = name
self.summary = summary
self.parser = ConfigOptionParser(
usage=self.usage,
prog=f"{get_prog()} {name}",
formatter=UpdatingDefaultsHelpFormatter(),
add_help_option=False,
name=name,
description=self.__doc__,
isolated=isolated,
)
self.tempdir_registry: Optional[TempDirRegistry] = None
# Commands should add options to this option group
optgroup_name = f"{self.name.capitalize()} Options"
self.cmd_opts = optparse.OptionGroup(self.parser, optgroup_name)
# Add the general options
gen_opts = cmdoptions.make_option_group(
cmdoptions.general_group,
self.parser,
)
self.parser.add_option_group(gen_opts)
self.add_options()
def add_options(self) -> None:
pass
def handle_pip_version_check(self, options: Values) -> None:
"""
This is a no-op so that commands by default do not do the pip version
check.
"""
# Make sure we do the pip version check if the index_group options
# are present.
assert not hasattr(options, "no_index")
def run(self, options: Values, args: List[str]) -> int:
raise NotImplementedError
def parse_args(self, args: List[str]) -> Tuple[Values, List[str]]:
# factored out for testability
return self.parser.parse_args(args)
def main(self, args: List[str]) -> int:
try:
with self.main_context():
return self._main(args)
finally:
logging.shutdown()
def _main(self, args: List[str]) -> int:
# We must initialize this before the tempdir manager, otherwise the
# configuration would not be accessible by the time we clean up the
# tempdir manager.
self.tempdir_registry = self.enter_context(tempdir_registry())
# Intentionally set as early as possible so globally-managed temporary
# directories are available to the rest of the code.
self.enter_context(global_tempdir_manager())
options, args = self.parse_args(args)
# Set verbosity so that it can be used elsewhere.
self.verbosity = options.verbose - options.quiet
level_number = setup_logging(
verbosity=self.verbosity,
no_color=options.no_color,
user_log_file=options.log,
)
# TODO: Try to get these passing down from the command?
# without resorting to os.environ to hold these.
# This also affects isolated builds and it should.
if options.no_input:
os.environ["PIP_NO_INPUT"] = "1"
if options.exists_action:
os.environ["PIP_EXISTS_ACTION"] = " ".join(options.exists_action)
if options.require_venv and not self.ignore_require_venv:
# If a venv is required check if it can really be found
if not running_under_virtualenv():
logger.critical("Could not find an activated virtualenv (required).")
sys.exit(VIRTUALENV_NOT_FOUND)
if options.cache_dir:
options.cache_dir = normalize_path(options.cache_dir)
if not check_path_owner(options.cache_dir):
logger.warning(
"The directory '%s' or its parent directory is not owned "
"or is not writable by the current user. The cache "
"has been disabled. Check the permissions and owner of "
"that directory. If executing pip with sudo, you should "
"use sudo's -H flag.",
options.cache_dir,
)
options.cache_dir = None
if "2020-resolver" in options.features_enabled:
logger.warning(
"--use-feature=2020-resolver no longer has any effect, "
"since it is now the default dependency resolver in pip. "
"This will become an error in pip 21.0."
)
def intercepts_unhandled_exc(
run_func: Callable[..., int]
) -> Callable[..., int]:
@functools.wraps(run_func)
def exc_logging_wrapper(*args: Any) -> int:
try:
status = run_func(*args)
assert isinstance(status, int)
return status
except DiagnosticPipError as exc:
logger.error("[present-diagnostic] %s", exc)
logger.debug("Exception information:", exc_info=True)
return ERROR
except PreviousBuildDirError as exc:
logger.critical(str(exc))
logger.debug("Exception information:", exc_info=True)
return PREVIOUS_BUILD_DIR_ERROR
except (
InstallationError,
UninstallationError,
BadCommand,
NetworkConnectionError,
) as exc:
logger.critical(str(exc))
logger.debug("Exception information:", exc_info=True)
return ERROR
except CommandError as exc:
logger.critical("%s", exc)
logger.debug("Exception information:", exc_info=True)
return ERROR
except BrokenStdoutLoggingError:
# Bypass our logger and write any remaining messages to
# stderr because stdout no longer works.
print("ERROR: Pipe to stdout was broken", file=sys.stderr)
if level_number <= logging.DEBUG:
traceback.print_exc(file=sys.stderr)
return ERROR
except KeyboardInterrupt:
logger.critical("Operation cancelled by user")
logger.debug("Exception information:", exc_info=True)
return ERROR
except BaseException:
logger.critical("Exception:", exc_info=True)
return UNKNOWN_ERROR
return exc_logging_wrapper
try:
if not options.debug_mode:
run = intercepts_unhandled_exc(self.run)
else:
run = self.run
rich_traceback.install(show_locals=True)
return run(options, args)
finally:
self.handle_pip_version_check(options)

File diff suppressed because it is too large Load Diff

View File

@ -1,27 +0,0 @@
from contextlib import ExitStack, contextmanager
from typing import ContextManager, Iterator, TypeVar
_T = TypeVar("_T", covariant=True)
class CommandContextMixIn:
def __init__(self) -> None:
super().__init__()
self._in_main_context = False
self._main_context = ExitStack()
@contextmanager
def main_context(self) -> Iterator[None]:
assert not self._in_main_context
self._in_main_context = True
try:
with self._main_context:
yield
finally:
self._in_main_context = False
def enter_context(self, context_provider: ContextManager[_T]) -> _T:
assert self._in_main_context
return self._main_context.enter_context(context_provider)

View File

@ -1,70 +0,0 @@
"""Primary application entrypoint.
"""
import locale
import logging
import os
import sys
from typing import List, Optional
from pip._internal.cli.autocompletion import autocomplete
from pip._internal.cli.main_parser import parse_command
from pip._internal.commands import create_command
from pip._internal.exceptions import PipError
from pip._internal.utils import deprecation
logger = logging.getLogger(__name__)
# Do not import and use main() directly! Using it directly is actively
# discouraged by pip's maintainers. The name, location and behavior of
# this function is subject to change, so calling it directly is not
# portable across different pip versions.
# In addition, running pip in-process is unsupported and unsafe. This is
# elaborated in detail at
# https://pip.pypa.io/en/stable/user_guide/#using-pip-from-your-program.
# That document also provides suggestions that should work for nearly
# all users that are considering importing and using main() directly.
# However, we know that certain users will still want to invoke pip
# in-process. If you understand and accept the implications of using pip
# in an unsupported manner, the best approach is to use runpy to avoid
# depending on the exact location of this entry point.
# The following example shows how to use runpy to invoke pip in that
# case:
#
# sys.argv = ["pip", your, args, here]
# runpy.run_module("pip", run_name="__main__")
#
# Note that this will exit the process after running, unlike a direct
# call to main. As it is not safe to do any processing after calling
# main, this should not be an issue in practice.
def main(args: Optional[List[str]] = None) -> int:
if args is None:
args = sys.argv[1:]
# Configure our deprecation warnings to be sent through loggers
deprecation.install_warning_logger()
autocomplete()
try:
cmd_name, cmd_args = parse_command(args)
except PipError as exc:
sys.stderr.write(f"ERROR: {exc}")
sys.stderr.write(os.linesep)
sys.exit(1)
# Needed for locale.getpreferredencoding(False) to work
# in pip._internal.utils.encoding.auto_decode
try:
locale.setlocale(locale.LC_ALL, "")
except locale.Error as e:
# setlocale can apparently crash if locale are uninitialized
logger.debug("Ignoring error %s when setting locale", e)
command = create_command(cmd_name, isolated=("--isolated" in cmd_args))
return command.main(cmd_args)

View File

@ -1,87 +0,0 @@
"""A single place for constructing and exposing the main parser
"""
import os
import sys
from typing import List, Tuple
from pip._internal.cli import cmdoptions
from pip._internal.cli.parser import ConfigOptionParser, UpdatingDefaultsHelpFormatter
from pip._internal.commands import commands_dict, get_similar_commands
from pip._internal.exceptions import CommandError
from pip._internal.utils.misc import get_pip_version, get_prog
__all__ = ["create_main_parser", "parse_command"]
def create_main_parser() -> ConfigOptionParser:
"""Creates and returns the main parser for pip's CLI"""
parser = ConfigOptionParser(
usage="\n%prog <command> [options]",
add_help_option=False,
formatter=UpdatingDefaultsHelpFormatter(),
name="global",
prog=get_prog(),
)
parser.disable_interspersed_args()
parser.version = get_pip_version()
# add the general options
gen_opts = cmdoptions.make_option_group(cmdoptions.general_group, parser)
parser.add_option_group(gen_opts)
# so the help formatter knows
parser.main = True # type: ignore
# create command listing for description
description = [""] + [
f"{name:27} {command_info.summary}"
for name, command_info in commands_dict.items()
]
parser.description = "\n".join(description)
return parser
def parse_command(args: List[str]) -> Tuple[str, List[str]]:
parser = create_main_parser()
# Note: parser calls disable_interspersed_args(), so the result of this
# call is to split the initial args into the general options before the
# subcommand and everything else.
# For example:
# args: ['--timeout=5', 'install', '--user', 'INITools']
# general_options: ['--timeout==5']
# args_else: ['install', '--user', 'INITools']
general_options, args_else = parser.parse_args(args)
# --version
if general_options.version:
sys.stdout.write(parser.version)
sys.stdout.write(os.linesep)
sys.exit()
# pip || pip help -> print_help()
if not args_else or (args_else[0] == "help" and len(args_else) == 1):
parser.print_help()
sys.exit()
# the subcommand name
cmd_name = args_else[0]
if cmd_name not in commands_dict:
guess = get_similar_commands(cmd_name)
msg = [f'unknown command "{cmd_name}"']
if guess:
msg.append(f'maybe you meant "{guess}"')
raise CommandError(" - ".join(msg))
# all the args without the subcommand
cmd_args = args[:]
cmd_args.remove(cmd_name)
return cmd_name, cmd_args

View File

@ -1,292 +0,0 @@
"""Base option parser setup"""
import logging
import optparse
import shutil
import sys
import textwrap
from contextlib import suppress
from typing import Any, Dict, Iterator, List, Tuple
from pip._internal.cli.status_codes import UNKNOWN_ERROR
from pip._internal.configuration import Configuration, ConfigurationError
from pip._internal.utils.misc import redact_auth_from_url, strtobool
logger = logging.getLogger(__name__)
class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
"""A prettier/less verbose help formatter for optparse."""
def __init__(self, *args: Any, **kwargs: Any) -> None:
# help position must be aligned with __init__.parseopts.description
kwargs["max_help_position"] = 30
kwargs["indent_increment"] = 1
kwargs["width"] = shutil.get_terminal_size()[0] - 2
super().__init__(*args, **kwargs)
def format_option_strings(self, option: optparse.Option) -> str:
return self._format_option_strings(option)
def _format_option_strings(
self, option: optparse.Option, mvarfmt: str = " <{}>", optsep: str = ", "
) -> str:
"""
Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
:param mvarfmt: metavar format string
:param optsep: separator
"""
opts = []
if option._short_opts:
opts.append(option._short_opts[0])
if option._long_opts:
opts.append(option._long_opts[0])
if len(opts) > 1:
opts.insert(1, optsep)
if option.takes_value():
assert option.dest is not None
metavar = option.metavar or option.dest.lower()
opts.append(mvarfmt.format(metavar.lower()))
return "".join(opts)
def format_heading(self, heading: str) -> str:
if heading == "Options":
return ""
return heading + ":\n"
def format_usage(self, usage: str) -> str:
"""
Ensure there is only one newline between usage and the first heading
if there is no description.
"""
msg = "\nUsage: {}\n".format(self.indent_lines(textwrap.dedent(usage), " "))
return msg
def format_description(self, description: str) -> str:
# leave full control over description to us
if description:
if hasattr(self.parser, "main"):
label = "Commands"
else:
label = "Description"
# some doc strings have initial newlines, some don't
description = description.lstrip("\n")
# some doc strings have final newlines and spaces, some don't
description = description.rstrip()
# dedent, then reindent
description = self.indent_lines(textwrap.dedent(description), " ")
description = f"{label}:\n{description}\n"
return description
else:
return ""
def format_epilog(self, epilog: str) -> str:
# leave full control over epilog to us
if epilog:
return epilog
else:
return ""
def indent_lines(self, text: str, indent: str) -> str:
new_lines = [indent + line for line in text.split("\n")]
return "\n".join(new_lines)
class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
"""Custom help formatter for use in ConfigOptionParser.
This is updates the defaults before expanding them, allowing
them to show up correctly in the help listing.
Also redact auth from url type options
"""
def expand_default(self, option: optparse.Option) -> str:
default_values = None
if self.parser is not None:
assert isinstance(self.parser, ConfigOptionParser)
self.parser._update_defaults(self.parser.defaults)
assert option.dest is not None
default_values = self.parser.defaults.get(option.dest)
help_text = super().expand_default(option)
if default_values and option.metavar == "URL":
if isinstance(default_values, str):
default_values = [default_values]
# If its not a list, we should abort and just return the help text
if not isinstance(default_values, list):
default_values = []
for val in default_values:
help_text = help_text.replace(val, redact_auth_from_url(val))
return help_text
class CustomOptionParser(optparse.OptionParser):
def insert_option_group(
self, idx: int, *args: Any, **kwargs: Any
) -> optparse.OptionGroup:
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group
@property
def option_list_all(self) -> List[optparse.Option]:
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res
class ConfigOptionParser(CustomOptionParser):
"""Custom option parser which updates its defaults by checking the
configuration files and environmental variables"""
def __init__(
self,
*args: Any,
name: str,
isolated: bool = False,
**kwargs: Any,
) -> None:
self.name = name
self.config = Configuration(isolated)
assert self.name
super().__init__(*args, **kwargs)
def check_default(self, option: optparse.Option, key: str, val: Any) -> Any:
try:
return option.check_value(key, val)
except optparse.OptionValueError as exc:
print(f"An error occurred during configuration: {exc}")
sys.exit(3)
def _get_ordered_configuration_items(self) -> Iterator[Tuple[str, Any]]:
# Configuration gives keys in an unordered manner. Order them.
override_order = ["global", self.name, ":env:"]
# Pool the options into different groups
section_items: Dict[str, List[Tuple[str, Any]]] = {
name: [] for name in override_order
}
for section_key, val in self.config.items():
# ignore empty values
if not val:
logger.debug(
"Ignoring configuration key '%s' as it's value is empty.",
section_key,
)
continue
section, key = section_key.split(".", 1)
if section in override_order:
section_items[section].append((key, val))
# Yield each group in their override order
for section in override_order:
for key, val in section_items[section]:
yield key, val
def _update_defaults(self, defaults: Dict[str, Any]) -> Dict[str, Any]:
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Accumulate complex default state.
self.values = optparse.Values(self.defaults)
late_eval = set()
# Then set the options with those values
for key, val in self._get_ordered_configuration_items():
# '--' because configuration supports only long names
option = self.get_option("--" + key)
# Ignore options not present in this parser. E.g. non-globals put
# in [global] by users that want them to apply to all applicable
# commands.
if option is None:
continue
assert option.dest is not None
if option.action in ("store_true", "store_false"):
try:
val = strtobool(val)
except ValueError:
self.error(
"{} is not a valid value for {} option, " # noqa
"please specify a boolean value like yes/no, "
"true/false or 1/0 instead.".format(val, key)
)
elif option.action == "count":
with suppress(ValueError):
val = strtobool(val)
with suppress(ValueError):
val = int(val)
if not isinstance(val, int) or val < 0:
self.error(
"{} is not a valid value for {} option, " # noqa
"please instead specify either a non-negative integer "
"or a boolean value like yes/no or false/true "
"which is equivalent to 1/0.".format(val, key)
)
elif option.action == "append":
val = val.split()
val = [self.check_default(option, key, v) for v in val]
elif option.action == "callback":
assert option.callback is not None
late_eval.add(option.dest)
opt_str = option.get_opt_string()
val = option.convert_value(opt_str, val)
# From take_action
args = option.callback_args or ()
kwargs = option.callback_kwargs or {}
option.callback(option, opt_str, val, self, *args, **kwargs)
else:
val = self.check_default(option, key, val)
defaults[option.dest] = val
for key in late_eval:
defaults[key] = getattr(self.values, key)
self.values = None
return defaults
def get_default_values(self) -> optparse.Values:
"""Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work."""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Values(self.defaults)
# Load the configuration, or error out in case of an error
try:
self.config.load()
except ConfigurationError as err:
self.exit(UNKNOWN_ERROR, str(err))
defaults = self._update_defaults(self.defaults.copy()) # ours
for option in self._get_all_options():
assert option.dest is not None
default = defaults.get(option.dest)
if isinstance(default, str):
opt_str = option.get_opt_string()
defaults[option.dest] = option.check_value(opt_str, default)
return optparse.Values(defaults)
def error(self, msg: str) -> None:
self.print_usage(sys.stderr)
self.exit(UNKNOWN_ERROR, f"{msg}\n")

View File

@ -1,321 +0,0 @@
import functools
import itertools
import sys
from signal import SIGINT, default_int_handler, signal
from typing import Any, Callable, Iterator, Optional, Tuple
from pip._vendor.progress.bar import Bar, FillingCirclesBar, IncrementalBar
from pip._vendor.progress.spinner import Spinner
from pip._vendor.rich.progress import (
BarColumn,
DownloadColumn,
FileSizeColumn,
Progress,
ProgressColumn,
SpinnerColumn,
TextColumn,
TimeElapsedColumn,
TimeRemainingColumn,
TransferSpeedColumn,
)
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.logging import get_indentation
from pip._internal.utils.misc import format_size
try:
from pip._vendor import colorama
# Lots of different errors can come from this, including SystemError and
# ImportError.
except Exception:
colorama = None
DownloadProgressRenderer = Callable[[Iterator[bytes]], Iterator[bytes]]
def _select_progress_class(preferred: Bar, fallback: Bar) -> Bar:
encoding = getattr(preferred.file, "encoding", None)
# If we don't know what encoding this file is in, then we'll just assume
# that it doesn't support unicode and use the ASCII bar.
if not encoding:
return fallback
# Collect all of the possible characters we want to use with the preferred
# bar.
characters = [
getattr(preferred, "empty_fill", ""),
getattr(preferred, "fill", ""),
]
characters += list(getattr(preferred, "phases", []))
# Try to decode the characters we're using for the bar using the encoding
# of the given file, if this works then we'll assume that we can use the
# fancier bar and if not we'll fall back to the plaintext bar.
try:
"".join(characters).encode(encoding)
except UnicodeEncodeError:
return fallback
else:
return preferred
_BaseBar: Any = _select_progress_class(IncrementalBar, Bar)
class InterruptibleMixin:
"""
Helper to ensure that self.finish() gets called on keyboard interrupt.
This allows downloads to be interrupted without leaving temporary state
(like hidden cursors) behind.
This class is similar to the progress library's existing SigIntMixin
helper, but as of version 1.2, that helper has the following problems:
1. It calls sys.exit().
2. It discards the existing SIGINT handler completely.
3. It leaves its own handler in place even after an uninterrupted finish,
which will have unexpected delayed effects if the user triggers an
unrelated keyboard interrupt some time after a progress-displaying
download has already completed, for example.
"""
def __init__(self, *args: Any, **kwargs: Any) -> None:
"""
Save the original SIGINT handler for later.
"""
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
self.original_handler = signal(SIGINT, self.handle_sigint)
# If signal() returns None, the previous handler was not installed from
# Python, and we cannot restore it. This probably should not happen,
# but if it does, we must restore something sensible instead, at least.
# The least bad option should be Python's default SIGINT handler, which
# just raises KeyboardInterrupt.
if self.original_handler is None:
self.original_handler = default_int_handler
def finish(self) -> None:
"""
Restore the original SIGINT handler after finishing.
This should happen regardless of whether the progress display finishes
normally, or gets interrupted.
"""
super().finish() # type: ignore
signal(SIGINT, self.original_handler)
def handle_sigint(self, signum, frame): # type: ignore
"""
Call self.finish() before delegating to the original SIGINT handler.
This handler should only be in place while the progress display is
active.
"""
self.finish()
self.original_handler(signum, frame)
class SilentBar(Bar):
def update(self) -> None:
pass
class BlueEmojiBar(IncrementalBar):
suffix = "%(percent)d%%"
bar_prefix = " "
bar_suffix = " "
phases = ("\U0001F539", "\U0001F537", "\U0001F535")
class DownloadProgressMixin:
def __init__(self, *args: Any, **kwargs: Any) -> None:
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
self.message: str = (" " * (get_indentation() + 2)) + self.message
@property
def downloaded(self) -> str:
return format_size(self.index) # type: ignore
@property
def download_speed(self) -> str:
# Avoid zero division errors...
if self.avg == 0.0: # type: ignore
return "..."
return format_size(1 / self.avg) + "/s" # type: ignore
@property
def pretty_eta(self) -> str:
if self.eta: # type: ignore
return f"eta {self.eta_td}" # type: ignore
return ""
def iter(self, it): # type: ignore
for x in it:
yield x
# B305 is incorrectly raised here
# https://github.com/PyCQA/flake8-bugbear/issues/59
self.next(len(x)) # noqa: B305
self.finish()
class WindowsMixin:
def __init__(self, *args: Any, **kwargs: Any) -> None:
# The Windows terminal does not support the hide/show cursor ANSI codes
# even with colorama. So we'll ensure that hide_cursor is False on
# Windows.
# This call needs to go before the super() call, so that hide_cursor
# is set in time. The base progress bar class writes the "hide cursor"
# code to the terminal in its init, so if we don't set this soon
# enough, we get a "hide" with no corresponding "show"...
if WINDOWS and self.hide_cursor: # type: ignore
self.hide_cursor = False
# https://github.com/python/mypy/issues/5887
super().__init__(*args, **kwargs) # type: ignore
# Check if we are running on Windows and we have the colorama module,
# if we do then wrap our file with it.
if WINDOWS and colorama:
self.file = colorama.AnsiToWin32(self.file) # type: ignore
# The progress code expects to be able to call self.file.isatty()
# but the colorama.AnsiToWin32() object doesn't have that, so we'll
# add it.
self.file.isatty = lambda: self.file.wrapped.isatty()
# The progress code expects to be able to call self.file.flush()
# but the colorama.AnsiToWin32() object doesn't have that, so we'll
# add it.
self.file.flush = lambda: self.file.wrapped.flush()
class BaseDownloadProgressBar(WindowsMixin, InterruptibleMixin, DownloadProgressMixin):
file = sys.stdout
message = "%(percent)d%%"
suffix = "%(downloaded)s %(download_speed)s %(pretty_eta)s"
class DefaultDownloadProgressBar(BaseDownloadProgressBar, _BaseBar):
pass
class DownloadSilentBar(BaseDownloadProgressBar, SilentBar):
pass
class DownloadBar(BaseDownloadProgressBar, Bar):
pass
class DownloadFillingCirclesBar(BaseDownloadProgressBar, FillingCirclesBar):
pass
class DownloadBlueEmojiProgressBar(BaseDownloadProgressBar, BlueEmojiBar):
pass
class DownloadProgressSpinner(
WindowsMixin, InterruptibleMixin, DownloadProgressMixin, Spinner
):
file = sys.stdout
suffix = "%(downloaded)s %(download_speed)s"
def next_phase(self) -> str:
if not hasattr(self, "_phaser"):
self._phaser = itertools.cycle(self.phases)
return next(self._phaser)
def update(self) -> None:
message = self.message % self
phase = self.next_phase()
suffix = self.suffix % self
line = "".join(
[
message,
" " if message else "",
phase,
" " if suffix else "",
suffix,
]
)
self.writeln(line)
BAR_TYPES = {
"off": (DownloadSilentBar, DownloadSilentBar),
"on": (DefaultDownloadProgressBar, DownloadProgressSpinner),
"ascii": (DownloadBar, DownloadProgressSpinner),
"pretty": (DownloadFillingCirclesBar, DownloadProgressSpinner),
"emoji": (DownloadBlueEmojiProgressBar, DownloadProgressSpinner),
}
def _legacy_progress_bar(
progress_bar: str, max: Optional[int]
) -> DownloadProgressRenderer:
if max is None or max == 0:
return BAR_TYPES[progress_bar][1]().iter # type: ignore
else:
return BAR_TYPES[progress_bar][0](max=max).iter
#
# Modern replacement, for our legacy progress bars.
#
def _rich_progress_bar(
iterable: Iterator[bytes],
*,
bar_type: str,
size: int,
) -> Iterator[bytes]:
assert bar_type == "on", "This should only be used in the default mode."
if not size:
total = float("inf")
columns: Tuple[ProgressColumn, ...] = (
TextColumn("[progress.description]{task.description}"),
SpinnerColumn("line", speed=1.5),
FileSizeColumn(),
TransferSpeedColumn(),
TimeElapsedColumn(),
)
else:
total = size
columns = (
TextColumn("[progress.description]{task.description}"),
BarColumn(),
DownloadColumn(),
TransferSpeedColumn(),
TextColumn("eta"),
TimeRemainingColumn(),
)
progress = Progress(*columns, refresh_per_second=30)
task_id = progress.add_task(" " * (get_indentation() + 2), total=total)
with progress:
for chunk in iterable:
yield chunk
progress.update(task_id, advance=len(chunk))
def get_download_progress_renderer(
*, bar_type: str, size: Optional[int] = None
) -> DownloadProgressRenderer:
"""Get an object that can be used to render the download progress.
Returns a callable, that takes an iterable to "wrap".
"""
if bar_type == "on":
return functools.partial(_rich_progress_bar, bar_type=bar_type, size=size)
elif bar_type == "off":
return iter # no-op, when passed an iterator
else:
return _legacy_progress_bar(bar_type, size)

View File

@ -1,506 +0,0 @@
"""Contains the Command base classes that depend on PipSession.
The classes in this module are in a separate module so the commands not
needing download / PackageFinder capability don't unnecessarily import the
PackageFinder machinery and all its vendored dependencies, etc.
"""
import logging
import os
import sys
from functools import partial
from optparse import Values
from typing import Any, List, Optional, Tuple
from pip._internal.cache import WheelCache
from pip._internal.cli import cmdoptions
from pip._internal.cli.base_command import Command
from pip._internal.cli.command_context import CommandContextMixIn
from pip._internal.exceptions import CommandError, PreviousBuildDirError
from pip._internal.index.collector import LinkCollector
from pip._internal.index.package_finder import PackageFinder
from pip._internal.models.selection_prefs import SelectionPreferences
from pip._internal.models.target_python import TargetPython
from pip._internal.network.session import PipSession
from pip._internal.operations.prepare import RequirementPreparer
from pip._internal.req.constructors import (
install_req_from_editable,
install_req_from_line,
install_req_from_parsed_requirement,
install_req_from_req_string,
)
from pip._internal.req.req_file import parse_requirements
from pip._internal.req.req_install import InstallRequirement
from pip._internal.req.req_tracker import RequirementTracker
from pip._internal.resolution.base import BaseResolver
from pip._internal.self_outdated_check import pip_self_version_check
from pip._internal.utils.deprecation import deprecated
from pip._internal.utils.temp_dir import (
TempDirectory,
TempDirectoryTypeRegistry,
tempdir_kinds,
)
from pip._internal.utils.virtualenv import running_under_virtualenv
logger = logging.getLogger(__name__)
class SessionCommandMixin(CommandContextMixIn):
"""
A class mixin for command classes needing _build_session().
"""
def __init__(self) -> None:
super().__init__()
self._session: Optional[PipSession] = None
@classmethod
def _get_index_urls(cls, options: Values) -> Optional[List[str]]:
"""Return a list of index urls from user-provided options."""
index_urls = []
if not getattr(options, "no_index", False):
url = getattr(options, "index_url", None)
if url:
index_urls.append(url)
urls = getattr(options, "extra_index_urls", None)
if urls:
index_urls.extend(urls)
# Return None rather than an empty list
return index_urls or None
def get_default_session(self, options: Values) -> PipSession:
"""Get a default-managed session."""
if self._session is None:
self._session = self.enter_context(self._build_session(options))
# there's no type annotation on requests.Session, so it's
# automatically ContextManager[Any] and self._session becomes Any,
# then https://github.com/python/mypy/issues/7696 kicks in
assert self._session is not None
return self._session
def _build_session(
self,
options: Values,
retries: Optional[int] = None,
timeout: Optional[int] = None,
) -> PipSession:
assert not options.cache_dir or os.path.isabs(options.cache_dir)
session = PipSession(
cache=(
os.path.join(options.cache_dir, "http") if options.cache_dir else None
),
retries=retries if retries is not None else options.retries,
trusted_hosts=options.trusted_hosts,
index_urls=self._get_index_urls(options),
)
# Handle custom ca-bundles from the user
if options.cert:
session.verify = options.cert
# Handle SSL client certificate
if options.client_cert:
session.cert = options.client_cert
# Handle timeouts
if options.timeout or timeout:
session.timeout = timeout if timeout is not None else options.timeout
# Handle configured proxies
if options.proxy:
session.proxies = {
"http": options.proxy,
"https": options.proxy,
}
# Determine if we can prompt the user for authentication or not
session.auth.prompting = not options.no_input
return session
class IndexGroupCommand(Command, SessionCommandMixin):
"""
Abstract base class for commands with the index_group options.
This also corresponds to the commands that permit the pip version check.
"""
def handle_pip_version_check(self, options: Values) -> None:
"""
Do the pip version check if not disabled.
This overrides the default behavior of not doing the check.
"""
# Make sure the index_group options are present.
assert hasattr(options, "no_index")
if options.disable_pip_version_check or options.no_index:
return
# Otherwise, check if we're using the latest version of pip available.
session = self._build_session(
options, retries=0, timeout=min(5, options.timeout)
)
with session:
pip_self_version_check(session, options)
KEEPABLE_TEMPDIR_TYPES = [
tempdir_kinds.BUILD_ENV,
tempdir_kinds.EPHEM_WHEEL_CACHE,
tempdir_kinds.REQ_BUILD,
]
def warn_if_run_as_root() -> None:
"""Output a warning for sudo users on Unix.
In a virtual environment, sudo pip still writes to virtualenv.
On Windows, users may run pip as Administrator without issues.
This warning only applies to Unix root users outside of virtualenv.
"""
if running_under_virtualenv():
return
if not hasattr(os, "getuid"):
return
# On Windows, there are no "system managed" Python packages. Installing as
# Administrator via pip is the correct way of updating system environments.
#
# We choose sys.platform over utils.compat.WINDOWS here to enable Mypy platform
# checks: https://mypy.readthedocs.io/en/stable/common_issues.html
if sys.platform == "win32" or sys.platform == "cygwin":
return
if os.getuid() != 0:
return
logger.warning(
"Running pip as the 'root' user can result in broken permissions and "
"conflicting behaviour with the system package manager. "
"It is recommended to use a virtual environment instead: "
"https://pip.pypa.io/warnings/venv"
)
def with_cleanup(func: Any) -> Any:
"""Decorator for common logic related to managing temporary
directories.
"""
def configure_tempdir_registry(registry: TempDirectoryTypeRegistry) -> None:
for t in KEEPABLE_TEMPDIR_TYPES:
registry.set_delete(t, False)
def wrapper(
self: RequirementCommand, options: Values, args: List[Any]
) -> Optional[int]:
assert self.tempdir_registry is not None
if options.no_clean:
configure_tempdir_registry(self.tempdir_registry)
try:
return func(self, options, args)
except PreviousBuildDirError:
# This kind of conflict can occur when the user passes an explicit
# build directory with a pre-existing folder. In that case we do
# not want to accidentally remove it.
configure_tempdir_registry(self.tempdir_registry)
raise
return wrapper
class RequirementCommand(IndexGroupCommand):
def __init__(self, *args: Any, **kw: Any) -> None:
super().__init__(*args, **kw)
self.cmd_opts.add_option(cmdoptions.no_clean())
@staticmethod
def determine_resolver_variant(options: Values) -> str:
"""Determines which resolver should be used, based on the given options."""
if "legacy-resolver" in options.deprecated_features_enabled:
return "legacy"
return "2020-resolver"
@staticmethod
def determine_build_failure_suppression(options: Values) -> bool:
"""Determines whether build failures should be suppressed and backtracked on."""
if "backtrack-on-build-failures" not in options.deprecated_features_enabled:
return False
if "legacy-resolver" in options.deprecated_features_enabled:
raise CommandError("Cannot backtrack with legacy resolver.")
deprecated(
reason=(
"Backtracking on build failures can mask issues related to how "
"a package generates metadata or builds a wheel. This flag will "
"be removed in pip 22.2."
),
gone_in=None,
replacement=(
"avoiding known-bad versions by explicitly telling pip to ignore them "
"(either directly as requirements, or via a constraints file)"
),
feature_flag=None,
issue=10655,
)
return True
@classmethod
def make_requirement_preparer(
cls,
temp_build_dir: TempDirectory,
options: Values,
req_tracker: RequirementTracker,
session: PipSession,
finder: PackageFinder,
use_user_site: bool,
download_dir: Optional[str] = None,
verbosity: int = 0,
) -> RequirementPreparer:
"""
Create a RequirementPreparer instance for the given parameters.
"""
temp_build_dir_path = temp_build_dir.path
assert temp_build_dir_path is not None
resolver_variant = cls.determine_resolver_variant(options)
if resolver_variant == "2020-resolver":
lazy_wheel = "fast-deps" in options.features_enabled
if lazy_wheel:
logger.warning(
"pip is using lazily downloaded wheels using HTTP "
"range requests to obtain dependency information. "
"This experimental feature is enabled through "
"--use-feature=fast-deps and it is not ready for "
"production."
)
else:
lazy_wheel = False
if "fast-deps" in options.features_enabled:
logger.warning(
"fast-deps has no effect when used with the legacy resolver."
)
in_tree_build = "out-of-tree-build" not in options.deprecated_features_enabled
if "in-tree-build" in options.features_enabled:
deprecated(
reason="In-tree builds are now the default.",
replacement="to remove the --use-feature=in-tree-build flag",
gone_in="22.1",
)
if "out-of-tree-build" in options.deprecated_features_enabled:
deprecated(
reason="Out-of-tree builds are deprecated.",
replacement=None,
gone_in="22.1",
)
if options.progress_bar not in {"on", "off"}:
deprecated(
reason="Custom progress bar styles are deprecated",
replacement="to use the default progress bar style.",
gone_in="22.1",
)
return RequirementPreparer(
build_dir=temp_build_dir_path,
src_dir=options.src_dir,
download_dir=download_dir,
build_isolation=options.build_isolation,
req_tracker=req_tracker,
session=session,
progress_bar=options.progress_bar,
finder=finder,
require_hashes=options.require_hashes,
use_user_site=use_user_site,
lazy_wheel=lazy_wheel,
verbosity=verbosity,
in_tree_build=in_tree_build,
)
@classmethod
def make_resolver(
cls,
preparer: RequirementPreparer,
finder: PackageFinder,
options: Values,
wheel_cache: Optional[WheelCache] = None,
use_user_site: bool = False,
ignore_installed: bool = True,
ignore_requires_python: bool = False,
force_reinstall: bool = False,
upgrade_strategy: str = "to-satisfy-only",
use_pep517: Optional[bool] = None,
py_version_info: Optional[Tuple[int, ...]] = None,
) -> BaseResolver:
"""
Create a Resolver instance for the given parameters.
"""
make_install_req = partial(
install_req_from_req_string,
isolated=options.isolated_mode,
use_pep517=use_pep517,
)
suppress_build_failures = cls.determine_build_failure_suppression(options)
resolver_variant = cls.determine_resolver_variant(options)
# The long import name and duplicated invocation is needed to convince
# Mypy into correctly typechecking. Otherwise it would complain the
# "Resolver" class being redefined.
if resolver_variant == "2020-resolver":
import pip._internal.resolution.resolvelib.resolver
return pip._internal.resolution.resolvelib.resolver.Resolver(
preparer=preparer,
finder=finder,
wheel_cache=wheel_cache,
make_install_req=make_install_req,
use_user_site=use_user_site,
ignore_dependencies=options.ignore_dependencies,
ignore_installed=ignore_installed,
ignore_requires_python=ignore_requires_python,
force_reinstall=force_reinstall,
upgrade_strategy=upgrade_strategy,
py_version_info=py_version_info,
suppress_build_failures=suppress_build_failures,
)
import pip._internal.resolution.legacy.resolver
return pip._internal.resolution.legacy.resolver.Resolver(
preparer=preparer,
finder=finder,
wheel_cache=wheel_cache,
make_install_req=make_install_req,
use_user_site=use_user_site,
ignore_dependencies=options.ignore_dependencies,
ignore_installed=ignore_installed,
ignore_requires_python=ignore_requires_python,
force_reinstall=force_reinstall,
upgrade_strategy=upgrade_strategy,
py_version_info=py_version_info,
)
def get_requirements(
self,
args: List[str],
options: Values,
finder: PackageFinder,
session: PipSession,
) -> List[InstallRequirement]:
"""
Parse command-line arguments into the corresponding requirements.
"""
requirements: List[InstallRequirement] = []
for filename in options.constraints:
for parsed_req in parse_requirements(
filename,
constraint=True,
finder=finder,
options=options,
session=session,
):
req_to_add = install_req_from_parsed_requirement(
parsed_req,
isolated=options.isolated_mode,
user_supplied=False,
)
requirements.append(req_to_add)
for req in args:
req_to_add = install_req_from_line(
req,
None,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
user_supplied=True,
)
requirements.append(req_to_add)
for req in options.editables:
req_to_add = install_req_from_editable(
req,
user_supplied=True,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
)
requirements.append(req_to_add)
# NOTE: options.require_hashes may be set if --require-hashes is True
for filename in options.requirements:
for parsed_req in parse_requirements(
filename, finder=finder, options=options, session=session
):
req_to_add = install_req_from_parsed_requirement(
parsed_req,
isolated=options.isolated_mode,
use_pep517=options.use_pep517,
user_supplied=True,
)
requirements.append(req_to_add)
# If any requirement has hash options, enable hash checking.
if any(req.has_hash_options for req in requirements):
options.require_hashes = True
if not (args or options.editables or options.requirements):
opts = {"name": self.name}
if options.find_links:
raise CommandError(
"You must give at least one requirement to {name} "
'(maybe you meant "pip {name} {links}"?)'.format(
**dict(opts, links=" ".join(options.find_links))
)
)
else:
raise CommandError(
"You must give at least one requirement to {name} "
'(see "pip help {name}")'.format(**opts)
)
return requirements
@staticmethod
def trace_basic_info(finder: PackageFinder) -> None:
"""
Trace basic information about the provided objects.
"""
# Display where finder is looking for packages
search_scope = finder.search_scope
locations = search_scope.get_formatted_locations()
if locations:
logger.info(locations)
def _build_package_finder(
self,
options: Values,
session: PipSession,
target_python: Optional[TargetPython] = None,
ignore_requires_python: Optional[bool] = None,
) -> PackageFinder:
"""
Create a package finder appropriate to this requirement command.
:param ignore_requires_python: Whether to ignore incompatible
"Requires-Python" values in links. Defaults to False.
"""
link_collector = LinkCollector.create(session, options=options)
selection_prefs = SelectionPreferences(
allow_yanked=True,
format_control=options.format_control,
allow_all_prereleases=options.pre,
prefer_binary=options.prefer_binary,
ignore_requires_python=ignore_requires_python,
)
return PackageFinder.create(
link_collector=link_collector,
selection_prefs=selection_prefs,
target_python=target_python,
use_deprecated_html5lib="html5lib" in options.deprecated_features_enabled,
)

View File

@ -1,157 +0,0 @@
import contextlib
import itertools
import logging
import sys
import time
from typing import IO, Iterator
from pip._vendor.progress import HIDE_CURSOR, SHOW_CURSOR
from pip._internal.utils.compat import WINDOWS
from pip._internal.utils.logging import get_indentation
logger = logging.getLogger(__name__)
class SpinnerInterface:
def spin(self) -> None:
raise NotImplementedError()
def finish(self, final_status: str) -> None:
raise NotImplementedError()
class InteractiveSpinner(SpinnerInterface):
def __init__(
self,
message: str,
file: IO[str] = None,
spin_chars: str = "-\\|/",
# Empirically, 8 updates/second looks nice
min_update_interval_seconds: float = 0.125,
):
self._message = message
if file is None:
file = sys.stdout
self._file = file
self._rate_limiter = RateLimiter(min_update_interval_seconds)
self._finished = False
self._spin_cycle = itertools.cycle(spin_chars)
self._file.write(" " * get_indentation() + self._message + " ... ")
self._width = 0
def _write(self, status: str) -> None:
assert not self._finished
# Erase what we wrote before by backspacing to the beginning, writing
# spaces to overwrite the old text, and then backspacing again
backup = "\b" * self._width
self._file.write(backup + " " * self._width + backup)
# Now we have a blank slate to add our status
self._file.write(status)
self._width = len(status)
self._file.flush()
self._rate_limiter.reset()
def spin(self) -> None:
if self._finished:
return
if not self._rate_limiter.ready():
return
self._write(next(self._spin_cycle))
def finish(self, final_status: str) -> None:
if self._finished:
return
self._write(final_status)
self._file.write("\n")
self._file.flush()
self._finished = True
# Used for dumb terminals, non-interactive installs (no tty), etc.
# We still print updates occasionally (once every 60 seconds by default) to
# act as a keep-alive for systems like Travis-CI that take lack-of-output as
# an indication that a task has frozen.
class NonInteractiveSpinner(SpinnerInterface):
def __init__(self, message: str, min_update_interval_seconds: float = 60.0) -> None:
self._message = message
self._finished = False
self._rate_limiter = RateLimiter(min_update_interval_seconds)
self._update("started")
def _update(self, status: str) -> None:
assert not self._finished
self._rate_limiter.reset()
logger.info("%s: %s", self._message, status)
def spin(self) -> None:
if self._finished:
return
if not self._rate_limiter.ready():
return
self._update("still running...")
def finish(self, final_status: str) -> None:
if self._finished:
return
self._update(f"finished with status '{final_status}'")
self._finished = True
class RateLimiter:
def __init__(self, min_update_interval_seconds: float) -> None:
self._min_update_interval_seconds = min_update_interval_seconds
self._last_update: float = 0
def ready(self) -> bool:
now = time.time()
delta = now - self._last_update
return delta >= self._min_update_interval_seconds
def reset(self) -> None:
self._last_update = time.time()
@contextlib.contextmanager
def open_spinner(message: str) -> Iterator[SpinnerInterface]:
# Interactive spinner goes directly to sys.stdout rather than being routed
# through the logging system, but it acts like it has level INFO,
# i.e. it's only displayed if we're at level INFO or better.
# Non-interactive spinner goes through the logging system, so it is always
# in sync with logging configuration.
if sys.stdout.isatty() and logger.getEffectiveLevel() <= logging.INFO:
spinner: SpinnerInterface = InteractiveSpinner(message)
else:
spinner = NonInteractiveSpinner(message)
try:
with hidden_cursor(sys.stdout):
yield spinner
except KeyboardInterrupt:
spinner.finish("canceled")
raise
except Exception:
spinner.finish("error")
raise
else:
spinner.finish("done")
@contextlib.contextmanager
def hidden_cursor(file: IO[str]) -> Iterator[None]:
# The Windows terminal does not support the hide/show cursor ANSI codes,
# even via colorama. So don't even try.
if WINDOWS:
yield
# We don't want to clutter the output with control characters if we're
# writing to a file, or if the user is running with --quiet.
# See https://github.com/pypa/pip/issues/3418
elif not file.isatty() or logger.getEffectiveLevel() > logging.INFO:
yield
else:
file.write(HIDE_CURSOR)
try:
yield
finally:
file.write(SHOW_CURSOR)

View File

@ -1,6 +0,0 @@
SUCCESS = 0
ERROR = 1
UNKNOWN_ERROR = 2
VIRTUALENV_NOT_FOUND = 3
PREVIOUS_BUILD_DIR_ERROR = 4
NO_MATCHES_FOUND = 23

View File

@ -1,127 +0,0 @@
"""
Package containing all pip commands
"""
import importlib
from collections import namedtuple
from typing import Any, Dict, Optional
from pip._internal.cli.base_command import Command
CommandInfo = namedtuple("CommandInfo", "module_path, class_name, summary")
# This dictionary does a bunch of heavy lifting for help output:
# - Enables avoiding additional (costly) imports for presenting `--help`.
# - The ordering matters for help display.
#
# Even though the module path starts with the same "pip._internal.commands"
# prefix, the full path makes testing easier (specifically when modifying
# `commands_dict` in test setup / teardown).
commands_dict: Dict[str, CommandInfo] = {
"install": CommandInfo(
"pip._internal.commands.install",
"InstallCommand",
"Install packages.",
),
"download": CommandInfo(
"pip._internal.commands.download",
"DownloadCommand",
"Download packages.",
),
"uninstall": CommandInfo(
"pip._internal.commands.uninstall",
"UninstallCommand",
"Uninstall packages.",
),
"freeze": CommandInfo(
"pip._internal.commands.freeze",
"FreezeCommand",
"Output installed packages in requirements format.",
),
"list": CommandInfo(
"pip._internal.commands.list",
"ListCommand",
"List installed packages.",
),
"show": CommandInfo(
"pip._internal.commands.show",
"ShowCommand",
"Show information about installed packages.",
),
"check": CommandInfo(
"pip._internal.commands.check",
"CheckCommand",
"Verify installed packages have compatible dependencies.",
),
"config": CommandInfo(
"pip._internal.commands.configuration",
"ConfigurationCommand",
"Manage local and global configuration.",
),
"search": CommandInfo(
"pip._internal.commands.search",
"SearchCommand",
"Search PyPI for packages.",
),
"cache": CommandInfo(
"pip._internal.commands.cache",
"CacheCommand",
"Inspect and manage pip's wheel cache.",
),
"index": CommandInfo(
"pip._internal.commands.index",
"IndexCommand",
"Inspect information available from package indexes.",
),
"wheel": CommandInfo(
"pip._internal.commands.wheel",
"WheelCommand",
"Build wheels from your requirements.",
),
"hash": CommandInfo(
"pip._internal.commands.hash",
"HashCommand",
"Compute hashes of package archives.",
),
"completion": CommandInfo(
"pip._internal.commands.completion",
"CompletionCommand",
"A helper command used for command completion.",
),
"debug": CommandInfo(
"pip._internal.commands.debug",
"DebugCommand",
"Show information useful for debugging.",
),
"help": CommandInfo(
"pip._internal.commands.help",
"HelpCommand",
"Show help for commands.",
),
}
def create_command(name: str, **kwargs: Any) -> Command:
"""
Create an instance of the Command class with the given name.
"""
module_path, class_name, summary = commands_dict[name]
module = importlib.import_module(module_path)
command_class = getattr(module, class_name)
command = command_class(name=name, summary=summary, **kwargs)
return command
def get_similar_commands(name: str) -> Optional[str]:
"""Command name auto-correct."""
from difflib import get_close_matches
name = name.lower()
close_commands = get_close_matches(name, commands_dict.keys())
if close_commands:
return close_commands[0]
else:
return None

Some files were not shown because too many files have changed in this diff Show More