From eef837afd8789ac534c285b433315aebf9aa2f91 Mon Sep 17 00:00:00 2001 From: DongHun Kwak Date: Wed, 25 Nov 2020 14:49:25 +0900 Subject: [PATCH] Imported Upstream version 3.38.0 --- .gitignore | 1 + .gitlab-ci.yml | 11 -- NEWS | 22 ++++ PKG-INFO.in | 3 +- README.rst | 6 +- docs/Makefile | 4 +- docs/conf.py | 5 +- docs/packagingguide.rst | 2 +- examples/demo/demos/printing.py | 4 +- examples/demo/demos/rotatedtext.py | 1 - gi/__init__.py | 5 +- gi/_compat.py | 56 --------- gi/_option.py | 5 +- gi/_ossighelper.py | 14 --- gi/_propertyhelper.py | 7 +- gi/gimodule.c | 137 +++++++++++--------- gi/importer.py | 1 - gi/meson.build | 3 +- gi/module.py | 10 +- gi/overrides/GObject.py | 13 +- gi/overrides/Gdk.py | 4 +- gi/overrides/Gio.py | 9 +- gi/overrides/Gtk.py | 71 ++++++----- gi/pygboxed.c | 32 +++-- gi/pygenum.c | 45 ++++--- gi/pygenum.h | 4 +- gi/pygflags.c | 75 ++++++----- gi/pygflags.h | 2 +- gi/pygi-argument.c | 10 +- gi/pygi-array.c | 9 +- gi/pygi-basictype.c | 166 ++++++++----------------- gi/pygi-boxed.c | 4 +- gi/pygi-cache.c | 3 +- gi/pygi-ccallback.c | 4 +- gi/pygi-enum-marshal.c | 9 +- gi/pygi-error.c | 3 +- gi/pygi-foreign-cairo.c | 45 ++++--- gi/pygi-info.c | 68 +++++----- gi/pygi-invoke.c | 6 - gi/pygi-object.c | 7 +- gi/pygi-python-compat.h | 192 ----------------------------- gi/pygi-repository.c | 4 +- gi/pygi-resulttuple.c | 28 ++--- gi/pygi-source.c | 1 - gi/pygi-struct-marshal.c | 3 +- gi/pygi-struct.c | 14 +-- gi/pygi-type.c | 43 ++++--- gi/pygi-type.h | 9 -- gi/pygi-util.c | 61 +-------- gi/pygi-util.h | 30 +---- gi/pygi-value.c | 16 +-- gi/pyginterface.c | 36 ++++-- gi/pygobject-object.c | 68 +++++----- gi/pygobject-object.h | 1 - gi/pygoptioncontext.c | 13 +- gi/pygoptiongroup.c | 10 +- gi/pygparamspec.c | 14 +-- gi/pygpointer.c | 21 +++- gi/pygspawn.c | 27 ++-- gi/pygtkcompat.py | 1 - gi/repository/__init__.py | 2 - gi/types.py | 17 +-- meson.build | 27 ++-- meson_options.txt | 2 +- pygtkcompat/pygtkcompat.py | 15 +-- setup.py | 51 ++------ tests/__init__.py | 13 +- tests/conftest.py | 9 +- tests/helper.py | 4 +- tests/meson.build | 4 +- tests/runtests.py | 2 - tests/test_atoms.py | 2 - tests/test_cairo.py | 3 - tests/test_docstring.py | 2 - tests/test_error.py | 2 - tests/test_everything.py | 19 +-- tests/test_fields.py | 3 - tests/test_gdbus.py | 2 - tests/test_generictreemodel.py | 2 - tests/test_gi.py | 129 ++++++------------- tests/test_gio.py | 2 - tests/test_glib.py | 10 +- tests/test_gobject.py | 10 +- tests/test_gtk_template.py | 16 +-- tests/test_gtype.py | 2 - tests/test_import_machinery.py | 17 +-- tests/test_interface.py | 2 - tests/test_internal_api.py | 13 +- tests/test_iochannel.py | 3 - tests/test_mainloop.py | 2 - tests/test_object_marshaling.py | 2 - tests/test_option.py | 9 -- tests/test_ossig.py | 4 +- tests/test_overrides_gdk.py | 23 ++-- tests/test_overrides_gdkpixbuf.py | 2 - tests/test_overrides_gio.py | 5 +- tests/test_overrides_glib.py | 7 +- tests/test_overrides_gobject.py | 14 +-- tests/test_overrides_gtk.py | 119 +++++++++++++----- tests/test_overrides_pango.py | 2 - tests/test_properties.py | 32 ++--- tests/test_pycapi.py | 17 +-- tests/test_pygtkcompat.py | 2 - tests/test_repository.py | 6 +- tests/test_resulttuple.py | 2 - tests/test_signal.py | 35 ++---- tests/test_source.py | 2 - tests/test_subprocess.py | 2 - tests/test_thread.py | 2 - tests/test_typeclass.py | 2 - tests/test_unknown.py | 2 - tests/testhelpermodule.c | 55 ++++++--- 112 files changed, 835 insertions(+), 1376 deletions(-) delete mode 100644 gi/_compat.py delete mode 100644 gi/pygi-python-compat.h diff --git a/.gitignore b/.gitignore index ea4475d..6b29f6f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ +.mypy_cache *.bak *.lo *.o diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index fb5bfea..5db5b26 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -65,11 +65,6 @@ python3-mingw64: CHERE_INVOKING: "yes" <<: *mingw-defaults -python2.7: - variables: - PYENV_VERSION: "2.7.17-debug" - <<: *defaults - python3.5: variables: PYENV_VERSION: "3.5.9" @@ -90,12 +85,6 @@ python3.8: PYENV_VERSION: "3.8.1-debug" <<: *defaults -pypy2.7: - allow_failure: true - variables: - PYENV_VERSION: "pypy2.7-7.3.0" - <<: *defaults - pypy3.6: allow_failure: true variables: diff --git a/NEWS b/NEWS index 0a5e423..812645f 100644 --- a/NEWS +++ b/NEWS @@ -1,3 +1,25 @@ +3.38.0 - 2020-09-12 +------------------- + +* Python 2 is no longer supported. + + Note for distros/packagers: + In case you want to keep Python 2 support you'll likely split any existing + package into a Python 2 and 3 version. Since these aren't parallel installable + here are some recommendations on how to make it work: + + * Build the devel package from the Python 3 source package + * Drop the headers/.pc files from the Python 2 build/package + * Make sure no Python 2 using package depends on the devel package + (@Arch: gnumeric can be build without Python support for example) + + See :issue:`392` for details + +* meson: Make the `pycairo` option a feature :mr:`146` :mr:`147` +* gdk overrides: Fix wrapping of scroll events :mr:`141` +* Add overrides for Gtk.Button set/get_focus_on_click :mr:`132` + + 3.36.1 - 2020-05-06 ------------------- diff --git a/PKG-INFO.in b/PKG-INFO.in index 34891d7..b48c905 100644 --- a/PKG-INFO.in +++ b/PKG-INFO.in @@ -1,4 +1,4 @@ -Metadata-Version: 1.0 +Metadata-Version: 1.2 Name: PyGObject Version: @VERSION@ Summary: Python bindings for GObject Introspection @@ -18,3 +18,4 @@ Classifier: Operating System :: Microsoft :: Windows Classifier: Programming Language :: C Classifier: Programming Language :: Python Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.5, <4 diff --git a/README.rst b/README.rst index cc88c28..6f9f148 100644 --- a/README.rst +++ b/README.rst @@ -12,9 +12,9 @@ `__, `GIO `__ and many more. -It supports Linux, Windows and macOS and works with **Python 2.7+**, **Python -3.5+**, **PyPy** and **PyPy3**. PyGObject, including this documentation, is -licensed under the **LGPLv2.1+**. +It supports Linux, Windows and macOS and works with **Python 3.5+** and +**PyPy3**. PyGObject, including this documentation, is licensed under the +**LGPLv2.1+**. ---- diff --git a/docs/Makefile b/docs/Makefile index 55525c5..bdba909 100644 --- a/docs/Makefile +++ b/docs/Makefile @@ -7,10 +7,10 @@ images/%.svg: images/%.dia dia $< --export=$@ --filter=dia-svg _build: Makefile *.rst devguide/*.rst guide/*/*.rst guide/*.rst conf.py images/*.png $(DIA_SVGS) ../README.rst ../NEWS - sphinx-build -b html . _build + python3 -m sphinx -b html . _build linkcheck: - sphinx-build -b linkcheck -n . _build + python3 -m sphinx -b linkcheck -n . _build clean: rm -R _build diff --git a/docs/conf.py b/docs/conf.py index 9609974..2263dc5 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - extensions = [ 'sphinx.ext.todo', 'sphinx.ext.intersphinx', @@ -12,8 +10,7 @@ intersphinx_mapping = { 'glib': ('https://lazka.github.io/pgi-docs/GLib-2.0', None), 'gdk': ('https://lazka.github.io/pgi-docs/Gdk-3.0', None), 'gio': ('https://lazka.github.io/pgi-docs/Gio-2.0', None), - 'python2': ('https://docs.python.org/2.7', None), - 'python3': ('https://docs.python.org/3', None), + 'python': ('https://docs.python.org/3', None), 'cairo': ('https://pycairo.readthedocs.io/en/latest', None), } diff --git a/docs/packagingguide.rst b/docs/packagingguide.rst index eae5d75..e1715eb 100644 --- a/docs/packagingguide.rst +++ b/docs/packagingguide.rst @@ -23,7 +23,7 @@ Runtime dependencies: * glib * libgirepository (gobject-introspection) * libffi - * Python 2 or 3 + * Python 3 The overrides directory contains various files which includes various Python imports mentioning gtk, gdk etc. They are only used when the diff --git a/examples/demo/demos/printing.py b/examples/demo/demos/printing.py index 6e68037..a87bd6f 100644 --- a/examples/demo/demos/printing.py +++ b/examples/demo/demos/printing.py @@ -92,8 +92,8 @@ class PrintingApp: file_path = print_data['filename'] if not os.path.isfile(file_path): file_path = os.path.join('demos', file_path) - if not os.path.isfile: - raise Exception("file not found: " % (file_path, )) + if not os.path.isfile(file_path): + raise Exception("file not found: %s" % (file_path, )) # in reality you should most likely not read the entire # file into a buffer diff --git a/examples/demo/demos/rotatedtext.py b/examples/demo/demos/rotatedtext.py index 8e4c2b7..4dac189 100644 --- a/examples/demo/demos/rotatedtext.py +++ b/examples/demo/demos/rotatedtext.py @@ -1,5 +1,4 @@ #!/usr/bin/env python -# coding=utf-8 # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab # diff --git a/gi/__init__.py b/gi/__init__.py index bdfd5a9..3454790 100644 --- a/gi/__init__.py +++ b/gi/__init__.py @@ -18,8 +18,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - # support overrides in different directories than our gi module from pkgutil import extend_path __path__ = extend_path(__path__, __name__) @@ -44,7 +42,6 @@ from ._gi import _API from ._gi import Repository from ._gi import PyGIDeprecationWarning from ._gi import PyGIWarning -from ._compat import string_types _API = _API # pyflakes PyGIDeprecationWarning = PyGIDeprecationWarning @@ -111,7 +108,7 @@ def require_version(namespace, version): """ repository = Repository.get_default() - if not isinstance(version, string_types): + if not isinstance(version, str): raise ValueError('Namespace version needs to be a string.') if namespace in repository.get_loaded_namespaces(): diff --git a/gi/_compat.py b/gi/_compat.py deleted file mode 100644 index 00f5fbb..0000000 --- a/gi/_compat.py +++ /dev/null @@ -1,56 +0,0 @@ -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Lesser General Public -# License as published by the Free Software Foundation; either -# version 2.1 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 -# Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public -# License along with this library; if not, see . - -import sys - -PY2 = PY3 = False -if sys.version_info[0] == 2: - PY2 = True - - from StringIO import StringIO - StringIO - - from UserList import UserList - UserList - - long_ = eval("long") - integer_types = eval("(int, long)") - string_types = eval("(basestring,)") - text_type = eval("unicode") - - reload = eval("reload") - xrange = eval("xrange") - cmp = eval("cmp") - - exec("def reraise(tp, value, tb):\n raise tp, value, tb") -else: - PY3 = True - - from io import StringIO - StringIO - - from collections import UserList - UserList - - long_ = int - integer_types = (int,) - string_types = (str,) - text_type = str - - from importlib import reload - reload - xrange = range - cmp = lambda a, b: (a > b) - (a < b) - - def reraise(tp, value, tb): - raise tp(value).with_traceback(tb) diff --git a/gi/_option.py b/gi/_option.py index 9babb2a..2fa54d8 100644 --- a/gi/_option.py +++ b/gi/_option.py @@ -32,7 +32,6 @@ import optparse from optparse import OptParseError, OptionError, OptionValueError, \ BadOptionError, OptionConflictError from .module import get_introspection_module -from ._compat import string_types from gi import _gi from gi._error import GError @@ -230,7 +229,7 @@ class OptionGroup(optparse.OptionGroup): def set_values_to_defaults(self): for option in self.option_list: default = self.defaults.get(option.dest) - if isinstance(default, string_types): + if isinstance(default, str): opt_str = option.get_opt_string() self.defaults[option.dest] = option.check_value( opt_str, default) @@ -310,7 +309,7 @@ class OptionParser(optparse.OptionParser): return context def add_option_group(self, *args, **kwargs): - if isinstance(args[0], string_types): + if isinstance(args[0], str): optparse.OptionParser.add_option_group(self, OptionGroup(self, *args, **kwargs)) return diff --git a/gi/_ossighelper.py b/gi/_ossighelper.py index 213f096..fba24e6 100644 --- a/gi/_ossighelper.py +++ b/gi/_ossighelper.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright 2017 Christoph Reiter # # This library is free software; you can redistribute it and/or @@ -17,7 +16,6 @@ from __future__ import print_function import os -import sys import socket import signal import threading @@ -63,8 +61,6 @@ def wakeup_on_signal(): shortly so that any registered Python signal handlers registered through signal.signal() can run. - Works on Windows but needs Python 3.5+. - In case the wrapped function is not called from the main thread it will be called as is and it will not wake up the default loop for signals. """ @@ -77,16 +73,6 @@ def wakeup_on_signal(): from gi.repository import GLib - # On Windows only Python 3.5+ supports passing sockets to set_wakeup_fd - set_wakeup_fd_supports_socket = ( - os.name != "nt" or sys.version_info[:2] >= (3, 5)) - # On Windows only Python 3 has an implementation of socketpair() - has_socketpair = hasattr(socket, "socketpair") - - if not has_socketpair or not set_wakeup_fd_supports_socket: - yield - return - read_socket, write_socket = socket.socketpair() with closing(read_socket), closing(write_socket): diff --git a/gi/_propertyhelper.py b/gi/_propertyhelper.py index 6f82ab6..def34b2 100644 --- a/gi/_propertyhelper.py +++ b/gi/_propertyhelper.py @@ -18,7 +18,6 @@ # License along with this library; if not, see . from . import _gi -from ._compat import string_types, long_ from ._constants import \ TYPE_NONE, TYPE_INTERFACE, TYPE_CHAR, TYPE_UCHAR, \ TYPE_BOOLEAN, TYPE_INT, TYPE_UINT, TYPE_LONG, \ @@ -93,8 +92,6 @@ class Property(object): self.value = value """ _type_from_pytype_lookup = { - # Put long_ first in case long_ and int are the same so int clobbers long_ - long_: TYPE_LONG, int: TYPE_INT, bool: TYPE_BOOLEAN, float: TYPE_DOUBLE, @@ -152,11 +149,11 @@ class Property(object): self.default = self._get_default(default) self._check_default() - if not isinstance(nick, string_types): + if not isinstance(nick, str): raise TypeError("nick must be a string") self.nick = nick - if not isinstance(blurb, string_types): + if not isinstance(blurb, str): raise TypeError("blurb must be a string") self.blurb = blurb # Always clobber __doc__ with blurb even if blurb is empty because diff --git a/gi/gimodule.c b/gi/gimodule.c index a63237d..890a6bf 100644 --- a/gi/gimodule.c +++ b/gi/gimodule.c @@ -52,7 +52,6 @@ #include "pygi-property.h" #include "pygi-util.h" #include "gimodule.h" -#include "pygi-python-compat.h" #include "pygi-basictype.h" PyObject *PyGIWarning; @@ -442,7 +441,7 @@ pyg_param_spec_from_object (PyObject *tuple) } item = PyTuple_GetItem(tuple, val_length-1); - if (!PYGLIB_PyLong_Check(item)) { + if (!PyLong_Check (item)) { PyErr_SetString(PyExc_TypeError, "last element in tuple must be an int"); return NULL; @@ -565,13 +564,13 @@ add_properties (GObjectClass *klass, PyObject *properties) /* values are of format (type,nick,blurb, type_specific_args, flags) */ - if (!PYGLIB_PyUnicode_Check(key)) { + if (!PyUnicode_Check(key)) { PyErr_SetString(PyExc_TypeError, "__gproperties__ keys must be strings"); ret = FALSE; break; } - prop_name = PYGLIB_PyUnicode_AsString (key); + prop_name = PyUnicode_AsUTF8 (key); if (!PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, @@ -604,7 +603,7 @@ add_properties (GObjectClass *klass, PyObject *properties) break; } item = PyTuple_GetItem(value, val_length-1); - if (!PYGLIB_PyLong_Check(item)) { + if (!PyLong_Check (item)) { PyErr_SetString(PyExc_TypeError, "last element in __gproperties__ value tuple must be an int"); ret = FALSE; @@ -627,14 +626,14 @@ add_properties (GObjectClass *klass, PyObject *properties) PyObject *type, *pvalue, *traceback; ret = FALSE; PyErr_Fetch(&type, &pvalue, &traceback); - if (PYGLIB_PyUnicode_Check(pvalue)) { + if (PyUnicode_Check(pvalue)) { char msg[256]; g_snprintf(msg, 256, "%s (while registering property '%s' for GType '%s')", - PYGLIB_PyUnicode_AsString(pvalue), + PyUnicode_AsUTF8 (pvalue), prop_name, G_OBJECT_CLASS_NAME(klass)); Py_DECREF(pvalue); - value = PYGLIB_PyUnicode_FromString(msg); + value = PyUnicode_FromString (msg); } PyErr_Restore(type, pvalue, traceback); break; @@ -682,7 +681,7 @@ _pyg_signal_accumulator(GSignalInvocationHint *ihint, state = PyGILState_Ensure(); if (ihint->detail) - py_detail = PYGLIB_PyUnicode_FromString(g_quark_to_string(ihint->detail)); + py_detail = PyUnicode_FromString (g_quark_to_string(ihint->detail)); else { Py_INCREF(Py_None); py_detail = Py_None; @@ -826,17 +825,17 @@ add_signals (GObjectClass *klass, PyObject *signals) const gchar *signal_name; gchar *signal_name_canon, *c; - if (!PYGLIB_PyUnicode_Check(key)) { + if (!PyUnicode_Check(key)) { PyErr_SetString(PyExc_TypeError, "__gsignals__ keys must be strings"); ret = FALSE; break; } - signal_name = PYGLIB_PyUnicode_AsString (key); + signal_name = PyUnicode_AsUTF8 (key); if (value == Py_None || - (PYGLIB_PyUnicode_Check(value) && - !strcmp(PYGLIB_PyUnicode_AsString(value), "override"))) + (PyUnicode_Check(value) && + !strcmp(PyUnicode_AsUTF8 (value), "override"))) { /* canonicalize signal name, replacing '-' with '_' */ signal_name_canon = g_strdup(signal_name); @@ -1220,8 +1219,8 @@ get_type_name_for_class(PyTypeObject *class) g_free(type_name); g_snprintf(name_serial_str, 16, "-v%i", name_serial); module = PyObject_GetAttrString((PyObject *)class, "__module__"); - if (module && PYGLIB_PyUnicode_Check(module)) { - type_name = g_strconcat(PYGLIB_PyUnicode_AsString(module), ".", + if (module && PyUnicode_Check (module)) { + type_name = g_strconcat(PyUnicode_AsUTF8 (module), ".", class->tp_name, name_serial > 1 ? name_serial_str : NULL, NULL); @@ -1937,9 +1936,9 @@ pyg_channel_read(PyObject* self, PyObject *args, PyObject *kwargs) PyErr_SetString(PyExc_TypeError, "first argument is not a GLib.IOChannel"); return NULL; } - + if (max_count == 0) - return PYGLIB_PyBytes_FromString(""); + return PyBytes_FromString (""); iochannel = pyg_boxed_get (py_iochannel, GIOChannel); @@ -1948,26 +1947,26 @@ pyg_channel_read(PyObject* self, PyObject *args, PyObject *kwargs) gsize single_read; char* buf; gsize buf_size; - - if (max_count == -1) + + if (max_count == -1) buf_size = CHUNK_SIZE; else { buf_size = max_count - total_read; if (buf_size > CHUNK_SIZE) buf_size = CHUNK_SIZE; } - + if ( ret_obj == NULL ) { - ret_obj = PYGLIB_PyBytes_FromStringAndSize((char *)NULL, buf_size); + ret_obj = PyBytes_FromStringAndSize ((char *)NULL, buf_size); if (ret_obj == NULL) goto failure; } - else if (buf_size + total_read > (gsize)PYGLIB_PyBytes_Size(ret_obj)) { - if (PYGLIB_PyBytes_Resize(&ret_obj, buf_size + total_read) == -1) + else if (buf_size + total_read > (gsize)PyBytes_Size (ret_obj)) { + if (_PyBytes_Resize (&ret_obj, buf_size + total_read) == -1) goto failure; } - - buf = PYGLIB_PyBytes_AsString(ret_obj) + total_read; + + buf = PyBytes_AsString (ret_obj) + total_read; Py_BEGIN_ALLOW_THREADS; status = g_io_channel_read_chars (iochannel, buf, buf_size, &single_read, &error); @@ -1975,12 +1974,12 @@ pyg_channel_read(PyObject* self, PyObject *args, PyObject *kwargs) if (pygi_error_check (&error)) goto failure; - + total_read += single_read; } - - if ( total_read != (gsize)PYGLIB_PyBytes_Size(ret_obj) ) { - if (PYGLIB_PyBytes_Resize(&ret_obj, total_read) == -1) + + if ( total_read != (gsize)PyBytes_Size (ret_obj) ) { + if (_PyBytes_Resize (&ret_obj, total_read) == -1) goto failure; } @@ -2094,7 +2093,7 @@ pyg_add_emission_hook(PyGObject *self, PyObject *args) if (!g_signal_parse_name(name, gtype, &sigid, &detail, TRUE)) { repr = PyObject_Repr((PyObject*)self); PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s", - PYGLIB_PyUnicode_AsString(repr), + PyUnicode_AsUTF8 (repr), name); Py_DECREF(repr); return NULL; @@ -2497,9 +2496,30 @@ pygi_register_version_tuples(PyObject *d) return 0; } -PYGLIB_MODULE_START(_gi, "_gi") -{ +static struct PyModuleDef __gimodule = { + PyModuleDef_HEAD_INIT, + "_gi", + NULL, + -1, + _gi_functions, + NULL, + NULL, + NULL, + NULL +}; + +#ifdef __GNUC__ +#define PYGI_MODINIT_FUNC __attribute__((visibility("default"))) PyMODINIT_FUNC +#else +#define PYGI_MODINIT_FUNC PyMODINIT_FUNC +#endif + +PYGI_MODINIT_FUNC PyInit__gi(void); + +PYGI_MODINIT_FUNC PyInit__gi(void) { + PyObject *module; PyObject *api; + module = PyModule_Create(&__gimodule); PyObject *module_dict = PyModule_GetDict (module); /* Always enable Python threads since we cannot predict which GI repositories @@ -2512,57 +2532,57 @@ PYGLIB_MODULE_START(_gi, "_gi") PyModule_AddStringConstant(module, "__package__", "gi._gi"); if (pygi_foreign_init () < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_error_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_repository_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_info_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_type_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_pointer_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_struct_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_gboxed_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_boxed_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_ccallback_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_resulttuple_register_types (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_spawn_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_option_context_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_option_group_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_register_api (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_register_constants (module) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_register_version_tuples (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_register_warnings (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pyi_object_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_interface_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_paramspec_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_enum_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; if (pygi_flags_register_types (module_dict) < 0) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; PyGIWarning = PyErr_NewException ("gi.PyGIWarning", PyExc_Warning, NULL); if (PyGIWarning == NULL) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; PyGIDeprecationWarning = PyErr_NewException("gi.PyGIDeprecationWarning", PyExc_DeprecationWarning, NULL); @@ -2580,8 +2600,9 @@ PYGLIB_MODULE_START(_gi, "_gi") api = PyCapsule_New ( (void *) &CAPI, "gi._API", NULL); if (api == NULL) { - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; } PyModule_AddObject (module, "_API", api); + + return module; } -PYGLIB_MODULE_END diff --git a/gi/importer.py b/gi/importer.py index e14d47b..3296797 100644 --- a/gi/importer.py +++ b/gi/importer.py @@ -21,7 +21,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import import sys import warnings import importlib diff --git a/gi/meson.build b/gi/meson.build index c1afd68..8edf832 100644 --- a/gi/meson.build +++ b/gi/meson.build @@ -44,7 +44,6 @@ headers = [ install_headers(headers, subdir : 'pygobject-@0@'.format(platform_version)) python_sources = [ - '_compat.py', '_constants.py', 'docstring.py', '_error.py', @@ -80,7 +79,7 @@ giext = python.extension_module('_gi', sources, c_args: pyext_c_args + main_c_args ) -if with_pycairo +if cairo_dep.found() gicairoext = python.extension_module('_gi_cairo', ['pygi-foreign-cairo.c'], dependencies : [python_ext_dep, glib_dep, gi_dep, ffi_dep, pycairo_dep, cairo_dep, cairo_gobject_dep], install: true, diff --git a/gi/module.py b/gi/module.py index c5b030a..f9e26bc 100644 --- a/gi/module.py +++ b/gi/module.py @@ -20,16 +20,8 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - import importlib -try: - maketrans = ''.maketrans -except AttributeError: - # fallback for Python 2 - from string import maketrans - import gi from ._gi import \ @@ -155,7 +147,7 @@ class IntrospectionModule(object): # Don't use upper() here to avoid locale specific # identifier conversion (e. g. in Turkish 'i'.upper() == 'i') # see https://bugzilla.gnome.org/show_bug.cgi?id=649165 - ascii_upper_trans = maketrans( + ascii_upper_trans = ''.maketrans( 'abcdefgjhijklmnopqrstuvwxyz', 'ABCDEFGJHIJKLMNOPQRSTUVWXYZ') for value_info in info.get_values(): diff --git a/gi/overrides/GObject.py b/gi/overrides/GObject.py index 81f214f..95a3c1f 100644 --- a/gi/overrides/GObject.py +++ b/gi/overrides/GObject.py @@ -29,8 +29,6 @@ import gi.module from gi.overrides import override, deprecated_attr from gi.repository import GLib from gi import PyGIDeprecationWarning -from gi._compat import PY2, text_type - from gi import _propertyhelper as propertyhelper from gi import _signalhelper as signalhelper from gi import _gi @@ -239,15 +237,8 @@ class Value(GObjectModule.Value): self.set_uchar(py_value) elif gtype == TYPE_STRING: if not isinstance(py_value, str) and py_value is not None: - if PY2: - if isinstance(py_value, text_type): - py_value = py_value.encode('UTF-8') - else: - raise TypeError("Expected string or unicode but got %s%s" % - (py_value, type(py_value))) - else: - raise TypeError("Expected string but got %s%s" % - (py_value, type(py_value))) + raise TypeError("Expected string but got %s%s" % + (py_value, type(py_value))) _gi._gvalue_set(self, py_value) elif gtype == TYPE_PARAM: self.set_param(py_value) diff --git a/gi/overrides/Gdk.py b/gi/overrides/Gdk.py index d77748e..a40d3ec 100644 --- a/gi/overrides/Gdk.py +++ b/gi/overrides/Gdk.py @@ -212,6 +212,7 @@ if GDK2 or GDK3: Gdk.EventType.DROP_FINISHED: 'dnd', Gdk.EventType.CLIENT_EVENT: 'client', Gdk.EventType.VISIBILITY_NOTIFY: 'visibility', + Gdk.EventType.SCROLL: 'scroll', Gdk.EventType.EXPOSE: 'expose', Gdk.EventType.MAP: 'any', Gdk.EventType.UNMAP: 'any', @@ -295,9 +296,6 @@ if GDK2 or GDK3: for method_info in Gdk.Event.__info__.get_methods(): name = method_info.get_name() event_method = getattr(Gdk.Event, name) - # python2 we need to use the __func__ attr to avoid internal - # instance checks - event_method = getattr(event_method, '__func__', event_method) # use the _gsuccess_mask decorator if this method is whitelisted if name in gsuccess_mask_funcs: diff --git a/gi/overrides/Gio.py b/gi/overrides/Gio.py index eafbae5..5cc12a6 100644 --- a/gi/overrides/Gio.py +++ b/gi/overrides/Gio.py @@ -23,7 +23,6 @@ import warnings from .._ossighelper import wakeup_on_signal, register_sigint_fallback from ..overrides import override, deprecated_init from ..module import get_introspection_module -from .._compat import xrange from gi._gi import pygobject_new_full from gi import PyGIWarning @@ -427,7 +426,7 @@ class ListModel(Gio.ListModel): def __getitem__(self, key): if isinstance(key, slice): - return [self.get_item(i) for i in xrange(*key.indices(len(self)))] + return [self.get_item(i) for i in range(*key.indices(len(self)))] elif isinstance(key, int): if key < 0: key += len(self) @@ -454,7 +453,7 @@ class ListModel(Gio.ListModel): return self.get_n_items() def __iter__(self): - for i in xrange(len(self)): + for i in range(len(self)): yield self.get_item(i) @@ -504,7 +503,7 @@ class ListStore(Gio.ListStore): elif step == -1: _list_store_splice(self, stop + 1, max(start - stop, 0), []) else: - for i in sorted(xrange(start, stop, step), reverse=True): + for i in sorted(range(start, stop, step), reverse=True): self.remove(i) elif isinstance(key, int): if key < 0: @@ -531,7 +530,7 @@ class ListStore(Gio.ListStore): _list_store_splice( self, start, max(stop - start, 0), valuelist) else: - indices = list(xrange(start, stop, step)) + indices = list(range(start, stop, step)) if len(indices) != len(valuelist): raise ValueError diff --git a/gi/overrides/Gtk.py b/gi/overrides/Gtk.py index 9453805..64a5088 100644 --- a/gi/overrides/Gtk.py +++ b/gi/overrides/Gtk.py @@ -21,18 +21,13 @@ import sys import warnings - -if sys.version_info[0] == 2: - import collections as abc -else: - from collections import abc +from collections import abc from gi.repository import GObject from .._ossighelper import wakeup_on_signal, register_sigint_fallback from .._gtktemplate import Template from ..overrides import override, strip_boolean_result, deprecated_init from ..module import get_introspection_module -from .._compat import string_types from gi import PyGIDeprecationWarning @@ -409,7 +404,7 @@ if Gtk._version in ("2.0", "3.0"): class UIManager(Gtk.UIManager): def add_ui_from_string(self, buffer): - if not isinstance(buffer, string_types): + if not isinstance(buffer, str): raise TypeError('buffer must be a string') length = _get_utf8_length(buffer) @@ -463,7 +458,7 @@ if Gtk._version in ("2.0", "3.0"): def _get_utf8_length(string): - assert isinstance(string, string_types) + assert isinstance(string, str) if not isinstance(string, bytes): string = string.encode("utf-8") return len(string) @@ -485,7 +480,7 @@ class Builder(Gtk.Builder): self.connect_signals_full(_builder_connect_callback, obj_or_map) def add_from_string(self, buffer): - if not isinstance(buffer, string_types): + if not isinstance(buffer, str): raise TypeError('buffer must be a string') length = _get_utf8_length(buffer) @@ -493,7 +488,7 @@ class Builder(Gtk.Builder): return Gtk.Builder.add_from_string(self, buffer, length) def add_objects_from_string(self, buffer, object_ids): - if not isinstance(buffer, string_types): + if not isinstance(buffer, str): raise TypeError('buffer must be a string') length = _get_utf8_length(buffer) @@ -696,14 +691,14 @@ IconView = override(IconView) __all__.append('IconView') -class ToolButton(Gtk.ToolButton): - __init__ = deprecated_init(Gtk.ToolButton.__init__, - arg_names=('stock_id',), - category=PyGTKDeprecationWarning) - +if Gtk._version in ("2.0", "3.0"): + class ToolButton(Gtk.ToolButton): + __init__ = deprecated_init(Gtk.ToolButton.__init__, + arg_names=('stock_id',), + category=PyGTKDeprecationWarning) -ToolButton = override(ToolButton) -__all__.append('ToolButton') + ToolButton = override(ToolButton) + __all__.append('ToolButton') class IMContext(Gtk.IMContext): @@ -759,7 +754,7 @@ class TextBuffer(Gtk.TextBuffer): Gtk.TextBuffer.set_text(self, text, length) def insert(self, iter, text, length=-1): - if not isinstance(text, string_types): + if not isinstance(text, str): raise TypeError('text must be a string, not %s' % type(text)) Gtk.TextBuffer.insert(self, iter, text, length) @@ -788,7 +783,7 @@ class TextBuffer(Gtk.TextBuffer): self.insert_with_tags(iter, text, *tag_objs) def insert_at_cursor(self, text, length=-1): - if not isinstance(text, string_types): + if not isinstance(text, str): raise TypeError('text must be a string, not %s' % type(text)) Gtk.TextBuffer.insert_at_cursor(self, text, length) @@ -1209,7 +1204,7 @@ class TreePath(Gtk.TreePath): def __new__(cls, path=0): if isinstance(path, int): path = str(path) - elif not isinstance(path, string_types): + elif not isinstance(path, str): path = ":".join(str(val) for val in path) if len(path) == 0: @@ -1465,6 +1460,18 @@ class Button(Gtk.Button, Container): else: self._init(*args, **kwargs) + if hasattr(Gtk.Widget, "set_focus_on_click"): + def set_focus_on_click(self, *args, **kwargs): + # Gtk.Widget.set_focus_on_click should be used instead but it's + # no obvious how because of the shadowed method, so override here + return Gtk.Widget.set_focus_on_click(self, *args, **kwargs) + + if hasattr(Gtk.Widget, "get_focus_on_click"): + def get_focus_on_click(self, *args, **kwargs): + # Gtk.Widget.get_focus_on_click should be used instead but it's + # no obvious how because of the shadowed method, so override here + return Gtk.Widget.get_focus_on_click(self, *args, **kwargs) + Button = override(Button) __all__.append('Button') @@ -1626,22 +1633,20 @@ if Gtk._version == '3.0': Menu = override(Menu) __all__.append('Menu') -_Gtk_main_quit = Gtk.main_quit - - -@override(Gtk.main_quit) -def main_quit(*args): - _Gtk_main_quit() - +if Gtk._version in ("2.0", "3.0"): + _Gtk_main_quit = Gtk.main_quit -_Gtk_main = Gtk.main + @override(Gtk.main_quit) + def main_quit(*args): + _Gtk_main_quit() + _Gtk_main = Gtk.main -@override(Gtk.main) -def main(*args, **kwargs): - with register_sigint_fallback(Gtk.main_quit): - with wakeup_on_signal(): - return _Gtk_main(*args, **kwargs) + @override(Gtk.main) + def main(*args, **kwargs): + with register_sigint_fallback(Gtk.main_quit): + with wakeup_on_signal(): + return _Gtk_main(*args, **kwargs) if Gtk._version in ("2.0", "3.0"): diff --git a/gi/pygboxed.c b/gi/pygboxed.c index 1f355be..5659bc1 100644 --- a/gi/pygboxed.c +++ b/gi/pygboxed.c @@ -30,7 +30,7 @@ GQuark pygboxed_type_key; -PYGLIB_DEFINE_TYPE("gobject.GBoxed", PyGBoxed_Type, PyGBoxed); +PYGI_DEFINE_TYPE("gobject.GBoxed", PyGBoxed_Type, PyGBoxed); static void gboxed_dealloc(PyGBoxed *self) @@ -58,10 +58,10 @@ gboxed_richcompare(PyObject *self, PyObject *other, int op) } } -static PYGLIB_Py_hash_t +static Py_hash_t gboxed_hash(PyGBoxed *self) { - return PYGLIB_Py_hash_t_FromVoidPtr (pyg_boxed_get_ptr (self)); + return (Py_hash_t)(gintptr)(pyg_boxed_get_ptr (self)); } static PyObject * @@ -74,12 +74,12 @@ gboxed_repr(PyGBoxed *boxed) if (module == NULL) return NULL; - if (!PYGLIB_PyUnicode_Check (module)) { + if (!PyUnicode_Check (module)) { Py_DECREF (module); return NULL; } - module_str = PYGLIB_PyUnicode_AsString (module); + module_str = PyUnicode_AsUTF8 (module); namespace = g_strrstr (module_str, "."); if (namespace == NULL) { namespace = module_str; @@ -87,10 +87,10 @@ gboxed_repr(PyGBoxed *boxed) namespace += 1; } - repr = PYGLIB_PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>", - namespace, Py_TYPE (self)->tp_name, - self, g_type_name (boxed->gtype), - pyg_boxed_get_ptr (boxed)); + repr = PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>", + namespace, Py_TYPE (self)->tp_name, + self, g_type_name (boxed->gtype), + pyg_boxed_get_ptr (boxed)); Py_DECREF (module); return repr; } @@ -244,6 +244,8 @@ pygi_gboxed_new (GType boxed_type, gpointer boxed, gboolean copy_boxed, int pygi_gboxed_register_types(PyObject *d) { + PyObject *pygtype; + pygboxed_type_key = g_quark_from_static_string("PyGBoxed::class"); PyGBoxed_Type.tp_dealloc = (destructor)gboxed_dealloc; @@ -254,8 +256,16 @@ pygi_gboxed_register_types(PyObject *d) PyGBoxed_Type.tp_init = (initproc)gboxed_init; PyGBoxed_Type.tp_free = (freefunc)gboxed_free; PyGBoxed_Type.tp_hash = (hashfunc)gboxed_hash; - - PYGOBJECT_REGISTER_GTYPE(d, PyGBoxed_Type, "GBoxed", G_TYPE_BOXED); + PyGBoxed_Type.tp_alloc = PyType_GenericAlloc; + PyGBoxed_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&PyGBoxed_Type)) + return -1; + + pygtype = pyg_type_wrapper_new (G_TYPE_POINTER); + PyDict_SetItemString (PyGBoxed_Type.tp_dict, "__gtype__", pygtype); + Py_DECREF (pygtype); + + PyDict_SetItemString(d, "GBoxed", (PyObject *)&PyGBoxed_Type); return 0; } diff --git a/gi/pygenum.c b/gi/pygenum.c index 69f1cd7..37495e8 100644 --- a/gi/pygenum.c +++ b/gi/pygenum.c @@ -21,7 +21,6 @@ #include -#include "pygi-python-compat.h" #include "pygi-type.h" #include "pygi-util.h" #include "pygi-type.h" @@ -31,14 +30,14 @@ GQuark pygenum_class_key; -PYGLIB_DEFINE_TYPE("gobject.GEnum", PyGEnum_Type, PyGEnum); +PYGI_DEFINE_TYPE("gobject.GEnum", PyGEnum_Type, PyGEnum); static PyObject * pyg_enum_val_new(PyObject* subclass, GType gtype, PyObject *intval) { PyObject *args, *item; args = Py_BuildValue("(O)", intval); - item = (&PYGLIB_PyLong_Type)->tp_new((PyTypeObject*)subclass, args, NULL); + item = (&PyLong_Type)->tp_new((PyTypeObject*)subclass, args, NULL); Py_DECREF(args); if (!item) return NULL; @@ -52,7 +51,7 @@ pyg_enum_richcompare(PyGEnum *self, PyObject *other, int op) { static char warning[256]; - if (!PYGLIB_PyLong_Check(other)) { + if (!PyLong_Check (other)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -82,7 +81,7 @@ pyg_enum_repr(PyGEnum *self) if (module == NULL) return NULL; - if (!PYGLIB_PyUnicode_Check (module)) { + if (!PyUnicode_Check (module)) { Py_DECREF (module); return NULL; } @@ -90,12 +89,12 @@ pyg_enum_repr(PyGEnum *self) enum_class = g_type_class_ref(self->gtype); g_assert(G_IS_ENUM_CLASS(enum_class)); - l = PYGLIB_PyLong_AS_LONG(self); + l = PyLong_AS_LONG ((PyObject*)self); for (index = 0; index < enum_class->n_values; index++) if (l == enum_class->values[index].value) break; - module_str = PYGLIB_PyUnicode_AsString (module); + module_str = PyUnicode_AsUTF8 (module); namespace = g_strrstr (module_str, "."); if (namespace == NULL) { namespace = module_str; @@ -108,12 +107,12 @@ pyg_enum_repr(PyGEnum *self) sprintf(tmp, "", value, namespace, Py_TYPE (self)->tp_name); else - sprintf(tmp, "", PYGLIB_PyLong_AS_LONG(self), + sprintf(tmp, "", PyLong_AS_LONG ((PyObject*)self), namespace, Py_TYPE (self)->tp_name); Py_DECREF (module); g_type_class_unref(enum_class); - return PYGLIB_PyUnicode_FromString(tmp); + return PyUnicode_FromString (tmp); } static PyObject * @@ -171,7 +170,7 @@ pyg_enum_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) g_type_class_unref(eclass); - intvalue = PYGLIB_PyLong_FromLong(value); + intvalue = PyLong_FromLong(value); ret = PyDict_GetItem(values, intvalue); Py_DECREF(intvalue); Py_DECREF(values); @@ -201,11 +200,11 @@ pyg_enum_from_gtype (GType gtype, int value) if (!pyclass) pyclass = pyg_enum_add(NULL, g_type_name(gtype), NULL, gtype); if (!pyclass) - return PYGLIB_PyLong_FromLong(value); + return PyLong_FromLong(value); values = PyDict_GetItemString(((PyTypeObject *)pyclass)->tp_dict, "__enum_values__"); - intvalue = PYGLIB_PyLong_FromLong(value); + intvalue = PyLong_FromLong(value); retval = PyDict_GetItem(values, intvalue); if (retval) { Py_INCREF(retval); @@ -262,7 +261,7 @@ pyg_enum_add (PyObject * module, if (module) PyDict_SetItemString(((PyTypeObject *)stub)->tp_dict, "__module__", - PYGLIB_PyUnicode_FromString(PyModule_GetName(module))); + PyUnicode_FromString (PyModule_GetName(module))); g_type_set_qdata(gtype, pygenum_class_key, stub); @@ -283,7 +282,7 @@ pyg_enum_add (PyObject * module, for (i = 0; i < eclass->n_values; i++) { PyObject *item, *intval; - intval = PYGLIB_PyLong_FromLong(eclass->values[i].value); + intval = PyLong_FromLong(eclass->values[i].value); item = pyg_enum_val_new(stub, gtype, intval); PyDict_SetItem(values, intval, item); Py_DECREF(intval); @@ -315,7 +314,7 @@ pyg_enum_reduce(PyObject *self, PyObject *args) if (!PyArg_ParseTuple(args, ":GEnum.__reduce__")) return NULL; - return Py_BuildValue("(O(i)O)", Py_TYPE(self), PYGLIB_PyLong_AsLong(self), + return Py_BuildValue("(O(i)O)", Py_TYPE(self), PyLong_AsLong (self), PyObject_GetAttrString(self, "__dict__")); } @@ -382,18 +381,28 @@ static PyGetSetDef pyg_enum_getsets[] = { int pygi_enum_register_types(PyObject *d) { + PyObject *pygtype; + pygenum_class_key = g_quark_from_static_string("PyGEnum::class"); - PyGEnum_Type.tp_base = &PYGLIB_PyLong_Type; + PyGEnum_Type.tp_base = &PyLong_Type; PyGEnum_Type.tp_new = pyg_enum_new; - PyGEnum_Type.tp_hash = PYGLIB_PyLong_Type.tp_hash; + PyGEnum_Type.tp_hash = PyLong_Type.tp_hash; PyGEnum_Type.tp_repr = (reprfunc)pyg_enum_repr; PyGEnum_Type.tp_str = (reprfunc)pyg_enum_repr; PyGEnum_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; PyGEnum_Type.tp_richcompare = (richcmpfunc)pyg_enum_richcompare; PyGEnum_Type.tp_methods = pyg_enum_methods; PyGEnum_Type.tp_getset = pyg_enum_getsets; - PYGOBJECT_REGISTER_GTYPE(d, PyGEnum_Type, "GEnum", G_TYPE_ENUM); + PyGEnum_Type.tp_alloc = PyType_GenericAlloc; + if (PyType_Ready(&PyGEnum_Type)) + return -1; + + pygtype = pyg_type_wrapper_new (G_TYPE_ENUM); + PyDict_SetItemString (PyGEnum_Type.tp_dict, "__gtype__", pygtype); + Py_DECREF (pygtype); + + PyDict_SetItemString(d, "GEnum", (PyObject *)&PyGEnum_Type); return 0; } diff --git a/gi/pygenum.h b/gi/pygenum.h index 5be979a..5b46d35 100644 --- a/gi/pygenum.h +++ b/gi/pygenum.h @@ -20,14 +20,12 @@ #ifndef __PYGOBJECT_ENUM_H__ #define __PYGOBJECT_ENUM_H__ -#include "pygi-python-compat.h" - extern GQuark pygenum_class_key; #define PyGEnum_Check(x) (PyObject_IsInstance((PyObject *)x, (PyObject *)&PyGEnum_Type) && g_type_is_a(((PyGFlags*)x)->gtype, G_TYPE_ENUM)) typedef struct { - PYGLIB_PyLongObject parent; + PyLongObject parent; int zero_pad; /* must always be 0 */ GType gtype; } PyGEnum; diff --git a/gi/pygflags.c b/gi/pygflags.c index 01e8a55..a9c443b 100644 --- a/gi/pygflags.c +++ b/gi/pygflags.c @@ -29,7 +29,7 @@ GQuark pygflags_class_key; -PYGLIB_DEFINE_TYPE("gobject.GFlags", PyGFlags_Type, PyGFlags); +PYGI_DEFINE_TYPE("gobject.GFlags", PyGFlags_Type, PyGFlags); static PyObject * pyg_flags_val_new(PyObject* subclass, GType gtype, PyObject *intval) @@ -37,7 +37,7 @@ pyg_flags_val_new(PyObject* subclass, GType gtype, PyObject *intval) PyObject *args, *item; args = Py_BuildValue("(O)", intval); g_assert(PyObject_IsSubclass(subclass, (PyObject*) &PyGFlags_Type)); - item = PYGLIB_PyLong_Type.tp_new((PyTypeObject*)subclass, args, NULL); + item = PyLong_Type.tp_new((PyTypeObject*)subclass, args, NULL); Py_DECREF(args); if (!item) return NULL; @@ -51,7 +51,7 @@ pyg_flags_richcompare(PyGFlags *self, PyObject *other, int op) { static char warning[256]; - if (!PYGLIB_PyLong_Check(other)) { + if (!PyLong_Check (other)) { Py_INCREF(Py_NotImplemented); return Py_NotImplemented; } @@ -105,18 +105,18 @@ pyg_flags_repr(PyGFlags *self) char *tmp, *retval, *module_str, *namespace; PyObject *pyretval, *module; - tmp = generate_repr(self->gtype, (guint)PYGLIB_PyLong_AsUnsignedLong(self)); + tmp = generate_repr(self->gtype, (guint)PyLong_AsUnsignedLongMask ((PyObject*)self)); module = PyObject_GetAttrString ((PyObject *)self, "__module__"); if (module == NULL) return NULL; - if (!PYGLIB_PyUnicode_Check (module)) { + if (!PyUnicode_Check (module)) { Py_DECREF (module); return NULL; } - module_str = PYGLIB_PyUnicode_AsString (module); + module_str = PyUnicode_AsUTF8 (module); namespace = g_strrstr (module_str, "."); if (namespace == NULL) { namespace = module_str; @@ -129,12 +129,12 @@ pyg_flags_repr(PyGFlags *self) namespace, Py_TYPE (self)->tp_name); else retval = g_strdup_printf("", - PYGLIB_PyLong_AsUnsignedLong (self), + PyLong_AsUnsignedLongMask ((PyObject*)self), namespace, Py_TYPE (self)->tp_name); g_free(tmp); Py_DECREF (module); - pyretval = PYGLIB_PyUnicode_FromString(retval); + pyretval = PyUnicode_FromString (retval); g_free(retval); return pyretval; @@ -183,7 +183,7 @@ pyg_flags_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) g_type_class_unref(eclass); - pyint = PYGLIB_PyLong_FromUnsignedLong(value); + pyint = PyLong_FromUnsignedLong (value); ret = PyDict_GetItem(values, pyint); if (!ret) { PyErr_Clear(); @@ -206,7 +206,7 @@ pyg_flags_from_gtype (GType gtype, guint value) PyObject *pyclass, *values, *retval, *pyint; if (PyErr_Occurred()) - return PYGLIB_PyLong_FromUnsignedLong(0); + return PyLong_FromUnsignedLong (0); g_return_val_if_fail(gtype != G_TYPE_INVALID, NULL); @@ -221,11 +221,11 @@ pyg_flags_from_gtype (GType gtype, guint value) if (!pyclass) pyclass = pyg_flags_add(NULL, g_type_name(gtype), NULL, gtype); if (!pyclass) - return PYGLIB_PyLong_FromUnsignedLong(value); + return PyLong_FromUnsignedLong (value); values = PyDict_GetItemString(((PyTypeObject *)pyclass)->tp_dict, "__flags_values__"); - pyint = PYGLIB_PyLong_FromUnsignedLong(value); + pyint = PyLong_FromUnsignedLong (value); retval = PyDict_GetItem(values, pyint); if (!retval) { PyErr_Clear(); @@ -283,7 +283,7 @@ pyg_flags_add (PyObject * module, if (module) { PyDict_SetItemString(((PyTypeObject *)stub)->tp_dict, "__module__", - PYGLIB_PyUnicode_FromString(PyModule_GetName(module))); + PyUnicode_FromString (PyModule_GetName(module))); /* Add it to the module name space */ PyModule_AddObject(module, (char*)typename, stub); @@ -302,7 +302,7 @@ pyg_flags_add (PyObject * module, for (i = 0; i < eclass->n_values; i++) { PyObject *item, *intval; - intval = PYGLIB_PyLong_FromUnsignedLong(eclass->values[i].value); + intval = PyLong_FromUnsignedLong (eclass->values[i].value); g_assert(PyErr_Occurred() == NULL); item = pyg_flags_val_new(stub, gtype, intval); PyDict_SetItem(values, intval, item); @@ -334,32 +334,32 @@ static PyObject * pyg_flags_and(PyGFlags *a, PyGFlags *b) { if (!PyGFlags_Check(a) || !PyGFlags_Check(b)) - return PYGLIB_PyLong_Type.tp_as_number->nb_and((PyObject*)a, + return PyLong_Type.tp_as_number->nb_and((PyObject*)a, (PyObject*)b); return pyg_flags_from_gtype(a->gtype, - (guint)(PYGLIB_PyLong_AsUnsignedLong(a) & PYGLIB_PyLong_AsUnsignedLong(b))); + (guint)(PyLong_AsUnsignedLongMask ((PyObject*)a) & PyLong_AsUnsignedLongMask ((PyObject*)b))); } static PyObject * pyg_flags_or(PyGFlags *a, PyGFlags *b) { if (!PyGFlags_Check(a) || !PyGFlags_Check(b)) - return PYGLIB_PyLong_Type.tp_as_number->nb_or((PyObject*)a, + return PyLong_Type.tp_as_number->nb_or((PyObject*)a, (PyObject*)b); - return pyg_flags_from_gtype(a->gtype, (guint)(PYGLIB_PyLong_AsUnsignedLong(a) | PYGLIB_PyLong_AsUnsignedLong(b))); + return pyg_flags_from_gtype(a->gtype, (guint)(PyLong_AsUnsignedLongMask ((PyObject*)a) | PyLong_AsUnsignedLongMask ((PyObject*)b))); } static PyObject * pyg_flags_xor(PyGFlags *a, PyGFlags *b) { if (!PyGFlags_Check(a) || !PyGFlags_Check(b)) - return PYGLIB_PyLong_Type.tp_as_number->nb_xor((PyObject*)a, + return PyLong_Type.tp_as_number->nb_xor((PyObject*)a, (PyObject*)b); return pyg_flags_from_gtype(a->gtype, - (guint)(PYGLIB_PyLong_AsUnsignedLong(a) ^ PYGLIB_PyLong_AsUnsignedLong(b))); + (guint)(PyLong_AsUnsignedLongMask ((PyObject*)a) ^ PyLong_AsUnsignedLongMask ((PyObject*)b))); } @@ -382,9 +382,9 @@ pyg_flags_get_first_value_name(PyGFlags *self, void *closure) flags_class = g_type_class_ref(self->gtype); g_assert(G_IS_FLAGS_CLASS(flags_class)); - flags_value = g_flags_get_first_value(flags_class, (guint)PYGLIB_PyLong_AsUnsignedLong(self)); + flags_value = g_flags_get_first_value(flags_class, (guint)PyLong_AsUnsignedLongMask ((PyObject*)self)); if (flags_value) - retval = PYGLIB_PyUnicode_FromString(flags_value->value_name); + retval = PyUnicode_FromString (flags_value->value_name); else { retval = Py_None; Py_INCREF(Py_None); @@ -404,9 +404,9 @@ pyg_flags_get_first_value_nick(PyGFlags *self, void *closure) flags_class = g_type_class_ref(self->gtype); g_assert(G_IS_FLAGS_CLASS(flags_class)); - flags_value = g_flags_get_first_value(flags_class, (guint)PYGLIB_PyLong_AsUnsignedLong(self)); + flags_value = g_flags_get_first_value(flags_class, (guint)PyLong_AsUnsignedLongMask ((PyObject*)self)); if (flags_value) - retval = PYGLIB_PyUnicode_FromString(flags_value->value_nick); + retval = PyUnicode_FromString (flags_value->value_nick); else { retval = Py_None; Py_INCREF(Py_None); @@ -430,8 +430,8 @@ pyg_flags_get_value_names(PyGFlags *self, void *closure) for (i = 0; i < flags_class->n_values; i++) { PyObject *value_name; - if ((PYGLIB_PyLong_AsUnsignedLong (self) & flags_class->values[i].value) == flags_class->values[i].value) { - value_name = PYGLIB_PyUnicode_FromString (flags_class->values[i].value_name); + if ((PyLong_AsUnsignedLongMask ((PyObject*)self) & flags_class->values[i].value) == flags_class->values[i].value) { + value_name = PyUnicode_FromString (flags_class->values[i].value_name); PyList_Append (retval, value_name); Py_DECREF (value_name); } @@ -454,8 +454,8 @@ pyg_flags_get_value_nicks(PyGFlags *self, void *closure) retval = PyList_New(0); for (i = 0; i < flags_class->n_values; i++) - if ((PYGLIB_PyLong_AsUnsignedLong(self) & flags_class->values[i].value) == flags_class->values[i].value) { - PyObject *py_nick = PYGLIB_PyUnicode_FromString(flags_class->values[i].value_nick); + if ((PyLong_AsUnsignedLongMask ((PyObject*)self) & flags_class->values[i].value) == flags_class->values[i].value) { + PyObject *py_nick = PyUnicode_FromString (flags_class->values[i].value_nick); PyList_Append(retval, py_nick); Py_DECREF (py_nick); } @@ -479,9 +479,6 @@ static PyNumberMethods pyg_flags_as_number = { (binaryfunc)pyg_flags_warn, /* nb_multiply */ (binaryfunc)pyg_flags_warn, /* nb_divide */ (binaryfunc)pyg_flags_warn, /* nb_remainder */ -#if PY_VERSION_HEX < 0x03000000 - (binaryfunc)pyg_flags_warn, /* nb_divmod */ -#endif (ternaryfunc)pyg_flags_warn, /* nb_power */ 0, /* nb_negative */ 0, /* nb_positive */ @@ -501,18 +498,28 @@ static PyNumberMethods pyg_flags_as_number = { int pygi_flags_register_types(PyObject *d) { + PyObject *pygtype; + pygflags_class_key = g_quark_from_static_string("PyGFlags::class"); - PyGFlags_Type.tp_base = &PYGLIB_PyLong_Type; + PyGFlags_Type.tp_base = &PyLong_Type; PyGFlags_Type.tp_new = pyg_flags_new; - PyGFlags_Type.tp_hash = PYGLIB_PyLong_Type.tp_hash; + PyGFlags_Type.tp_hash = PyLong_Type.tp_hash; PyGFlags_Type.tp_repr = (reprfunc)pyg_flags_repr; PyGFlags_Type.tp_as_number = &pyg_flags_as_number; PyGFlags_Type.tp_str = (reprfunc)pyg_flags_repr; PyGFlags_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; PyGFlags_Type.tp_richcompare = (richcmpfunc)pyg_flags_richcompare; PyGFlags_Type.tp_getset = pyg_flags_getsets; - PYGOBJECT_REGISTER_GTYPE(d, PyGFlags_Type, "GFlags", G_TYPE_FLAGS); + PyGFlags_Type.tp_alloc = PyType_GenericAlloc; + if (PyType_Ready(&PyGFlags_Type)) + return -1; + + pygtype = pyg_type_wrapper_new (G_TYPE_FLAGS); + PyDict_SetItemString (PyGFlags_Type.tp_dict, "__gtype__", pygtype); + Py_DECREF (pygtype); + + PyDict_SetItemString(d, "GFlags", (PyObject *)&PyGFlags_Type); return 0; } diff --git a/gi/pygflags.h b/gi/pygflags.h index 7a8b2c7..7cff7f2 100644 --- a/gi/pygflags.h +++ b/gi/pygflags.h @@ -23,7 +23,7 @@ extern GQuark pygflags_class_key; typedef struct { - PYGLIB_PyLongObject parent; + PyLongObject parent; int zero_pad; /* must always be 0 */ GType gtype; } PyGFlags; diff --git a/gi/pygi-argument.c b/gi/pygi-argument.c index 76ce8b4..9b98d9c 100644 --- a/gi/pygi-argument.c +++ b/gi/pygi-argument.c @@ -29,7 +29,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygi-argument.h" #include "pygi-info.h" #include "pygi-value.h" @@ -360,9 +359,6 @@ _pygi_argument_from_object (PyObject *object, /* Note, strings are sequences, but we cannot accept them here */ if (!PySequence_Check (object) || -#if PY_VERSION_HEX < 0x03000000 - PyString_Check (object) || -#endif PyUnicode_Check (object)) { PyErr_SetString (PyExc_TypeError, "expected sequence"); break; @@ -392,9 +388,9 @@ _pygi_argument_from_object (PyObject *object, } if (g_type_info_get_tag (item_type_info) == GI_TYPE_TAG_UINT8 && - PYGLIB_PyBytes_Check(object)) { + PyBytes_Check (object)) { - memcpy(array->data, PYGLIB_PyBytes_AsString(object), length); + memcpy(array->data, PyBytes_AsString (object), length); array->len = length; goto array_success; } @@ -748,7 +744,7 @@ _pygi_argument_to_object (GIArgument *arg, if (item_type_tag == GI_TYPE_TAG_UINT8) { /* Return as a byte array */ - object = PYGLIB_PyBytes_FromStringAndSize (array->data, array->len); + object = PyBytes_FromStringAndSize (array->data, array->len); } else { object = PyList_New (array->len); if (object == NULL) { diff --git a/gi/pygi-array.c b/gi/pygi-array.c index 890e7c5..735bb41 100644 --- a/gi/pygi-array.c +++ b/gi/pygi-array.c @@ -21,7 +21,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygi-array.h" #include "pygi-info.h" #include "pygi-marshal-cleanup.h" @@ -251,8 +250,8 @@ _pygi_marshal_from_py_array (PyGIInvokeState *state, } if (sequence_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8 && - PYGLIB_PyBytes_Check (py_arg)) { - gchar *data = PYGLIB_PyBytes_AsString (py_arg); + PyBytes_Check (py_arg)) { + gchar *data = PyBytes_AsString (py_arg); /* Avoid making a copy if the data * is not transferred to the C function @@ -583,9 +582,9 @@ _pygi_marshal_to_py_array (PyGIInvokeState *state, if (seq_cache->item_cache->type_tag == GI_TYPE_TAG_UINT8) { if (arg->v_pointer == NULL) { - py_obj = PYGLIB_PyBytes_FromString (""); + py_obj = PyBytes_FromString (""); } else { - py_obj = PYGLIB_PyBytes_FromStringAndSize (array_->data, array_->len); + py_obj = PyBytes_FromStringAndSize (array_->data, array_->len); } } else { if (arg->v_pointer == NULL) { diff --git a/gi/pygi-basictype.c b/gi/pygi-basictype.c index c0e5d1d..2864d91 100644 --- a/gi/pygi-basictype.c +++ b/gi/pygi-basictype.c @@ -19,7 +19,7 @@ */ #include -#include "pygi-python-compat.h" + #include "pygi-type.h" #include "pygi-basictype.h" #include "pygi-argument.h" @@ -53,7 +53,7 @@ pygi_gpointer_from_py (PyObject *py_arg, gpointer *result) return FALSE; *result = temp; return TRUE; - } else if (PYGLIB_PyLong_Check(py_arg) || PyLong_Check(py_arg)) { + } else if (PyLong_Check(py_arg)) { temp = PyLong_AsVoidPtr (py_arg); if (PyErr_Occurred ()) return FALSE; @@ -88,13 +88,13 @@ marshal_from_py_void (PyGIInvokeState *state, PyObject * pygi_gsize_to_py (gsize value) { - return PYGLIB_PyLong_FromSize_t (value); + return PyLong_FromSize_t (value); } PyObject * pygi_gssize_to_py (gssize value) { - return PYGLIB_PyLong_FromSsize_t (value); + return PyLong_FromSsize_t (value); } static PyObject * @@ -157,7 +157,7 @@ pygi_gfloat_from_py (PyObject *py_arg, gfloat *result) min = pygi_gfloat_to_py (-G_MAXFLOAT); max = pygi_gfloat_to_py (G_MAXFLOAT); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %S to %S", py_float, min, max); Py_DECREF (min); @@ -197,19 +197,8 @@ pygi_gunichar_from_py (PyObject *py_arg, gunichar *result) if (!py_bytes) return FALSE; - string_ = g_strdup(PYGLIB_PyBytes_AsString (py_bytes)); + string_ = g_strdup(PyBytes_AsString (py_bytes)); Py_DECREF (py_bytes); - -#if PY_VERSION_HEX < 0x03000000 - } else if (PyString_Check (py_arg)) { - PyObject *pyuni = PyUnicode_FromEncodedObject (py_arg, "UTF-8", "strict"); - if (!pyuni) - return FALSE; - - size = PyUnicode_GET_SIZE (pyuni); - string_ = g_strdup (PyString_AsString(py_arg)); - Py_DECREF (pyuni); -#endif } else { PyErr_Format (PyExc_TypeError, "Must be string, not %s", Py_TYPE (py_arg)->tp_name); @@ -236,13 +225,13 @@ pygi_gunichar_to_py (gunichar value) /* Preserve the bidirectional mapping between 0 and "" */ if (value == 0) { - py_obj = PYGLIB_PyUnicode_FromString (""); + py_obj = PyUnicode_FromString (""); } else if (g_unichar_validate (value)) { gchar utf8[6]; gint bytes; bytes = g_unichar_to_utf8 (value, utf8); - py_obj = PYGLIB_PyUnicode_FromStringAndSize ((char*)utf8, bytes); + py_obj = PyUnicode_FromStringAndSize ((char*)utf8, bytes); } else { /* TODO: Convert the error to an exception. */ PyErr_Format (PyExc_TypeError, @@ -288,14 +277,9 @@ pygi_utf8_from_py (PyObject *py_arg, gchar **result) if (!pystr_obj) return FALSE; - string_ = g_strdup (PYGLIB_PyBytes_AsString (pystr_obj)); + string_ = g_strdup (PyBytes_AsString (pystr_obj)); Py_DECREF (pystr_obj); } -#if PY_VERSION_HEX < 0x03000000 - else if (PyString_Check (py_arg)) { - string_ = g_strdup (PyString_AsString (py_arg)); - } -#endif else { PyErr_Format (PyExc_TypeError, "Must be string, not %s", Py_TYPE (py_arg)->tp_name); @@ -317,10 +301,10 @@ filename_from_py_unix (PyObject *py_arg, gchar **result) return TRUE; } - if (PYGLIB_PyBytes_Check (py_arg)) { + if (PyBytes_Check (py_arg)) { char *buffer; - if (PYGLIB_PyBytes_AsStringAndSize (py_arg, &buffer, NULL) == -1) + if (PyBytes_AsStringAndSize (py_arg, &buffer, NULL) == -1) return FALSE; filename = g_strdup (buffer); @@ -328,17 +312,12 @@ filename_from_py_unix (PyObject *py_arg, gchar **result) PyObject *bytes; char *buffer; -#if PY_VERSION_HEX < 0x03000000 - bytes = PyUnicode_AsEncodedString (py_arg, Py_FileSystemDefaultEncoding, - NULL); -#else bytes = PyUnicode_EncodeFSDefault (py_arg); -#endif if (!bytes) return FALSE; - if (PYGLIB_PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) { + if (PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) { Py_DECREF (bytes); return FALSE; } @@ -366,41 +345,12 @@ filename_from_py_win32 (PyObject *py_arg, gchar **result) return TRUE; } -#if PY_VERSION_HEX < 0x03000000 - if (PYGLIB_PyBytes_Check (py_arg)) { - char *buffer; - - if (PYGLIB_PyBytes_AsStringAndSize (py_arg, &buffer, NULL) == -1) - return FALSE; - - filename = g_strdup (buffer); - } else if (PyUnicode_Check (py_arg)) { - PyObject *bytes; - char *buffer; - - bytes = PyUnicode_AsUTF8String (py_arg); - if (!bytes) - return FALSE; - - if (PYGLIB_PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) { - Py_DECREF (bytes); - return FALSE; - } - - filename = g_strdup (buffer); - Py_DECREF (bytes); - } else { - PyErr_Format (PyExc_TypeError, "Must be unicode, not %s", - Py_TYPE (py_arg)->tp_name); - return FALSE; - } -#else - if (PYGLIB_PyBytes_Check (py_arg)) { + if (PyBytes_Check (py_arg)) { PyObject *uni_arg; gboolean temp_result; char *buffer; - if (PYGLIB_PyBytes_AsStringAndSize (py_arg, &buffer, NULL) == -1) + if (PyBytes_AsStringAndSize (py_arg, &buffer, NULL) == -1) return FALSE; uni_arg = PyUnicode_DecodeFSDefault (buffer); @@ -432,7 +382,7 @@ filename_from_py_win32 (PyObject *py_arg, gchar **result) if (!bytes) return FALSE; - if (PYGLIB_PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) { + if (PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) { Py_DECREF (bytes); return FALSE; } @@ -444,7 +394,6 @@ filename_from_py_win32 (PyObject *py_arg, gchar **result) Py_TYPE (py_arg)->tp_name); return FALSE; } -#endif *result = filename; return TRUE; @@ -471,19 +420,7 @@ base_number_checks (PyObject *object) return NULL; } -#if PY_MAJOR_VERSION < 3 - { - PyObject *tmp = PyNumber_Int (object); - if (tmp) { - number = PyNumber_Long (tmp); - Py_DECREF (tmp); - } else { - number = PyNumber_Long (object); - } - } -#else number = PyNumber_Long (object); -#endif if (number == NULL) { PyErr_SetString (PyExc_TypeError, "expected int argument"); @@ -568,7 +505,7 @@ pygi_gint_from_py (PyObject *object, gint *result) if (number == NULL) return FALSE; - long_value = PYGLIB_PyLong_AsLong (number); + long_value = PyLong_AsLong (number); if (PyErr_Occurred ()) { if (PyErr_ExceptionMatches (PyExc_OverflowError)) goto overflow; @@ -584,7 +521,7 @@ pygi_gint_from_py (PyObject *object, gint *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %d to %d", number, (int)G_MININT, (int)G_MAXINT); Py_DECREF (number); @@ -594,7 +531,7 @@ overflow: PyObject * pygi_gint_to_py (gint value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } gboolean @@ -623,7 +560,7 @@ pygi_guint_from_py (PyObject *object, guint *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %lu", number, (long)0, (unsigned long)G_MAXUINT); Py_DECREF (number); @@ -634,10 +571,10 @@ PyObject * pygi_guint_to_py (guint value) { #if (G_MAXUINT <= LONG_MAX) - return PYGLIB_PyLong_FromLong ((long) value); + return PyLong_FromLong ((long) value); #else if (value <= LONG_MAX) - return PYGLIB_PyLong_FromLong ((long) value); + return PyLong_FromLong ((long) value); return PyLong_FromUnsignedLong (value); #endif } @@ -666,7 +603,7 @@ pygi_glong_from_py (PyObject *object, glong *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %ld", number, (long)G_MINLONG, (long)G_MAXLONG); Py_DECREF (number); @@ -676,7 +613,7 @@ overflow: PyObject * pygi_glong_to_py (glong value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } gboolean @@ -703,7 +640,7 @@ pygi_gulong_from_py (PyObject *object, gulong *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %lu", number, (long)0, (unsigned long)G_MAXULONG); Py_DECREF (number); @@ -714,7 +651,7 @@ PyObject * pygi_gulong_to_py (gulong value) { if (value <= LONG_MAX) - return PYGLIB_PyLong_FromLong ((long) value); + return PyLong_FromLong ((long) value); else return PyLong_FromUnsignedLong (value); } @@ -725,13 +662,13 @@ pygi_gint8_from_py (PyObject *object, gint8 *result) long long_value; PyObject *number; - if (PYGLIB_PyBytes_Check (object)) { - if (PYGLIB_PyBytes_Size (object) != 1) { + if (PyBytes_Check (object)) { + if (PyBytes_Size (object) != 1) { PyErr_Format (PyExc_TypeError, "Must be a single character"); return FALSE; } - *result = (gint8)(PYGLIB_PyBytes_AsString (object)[0]); + *result = (gint8)(PyBytes_AsString (object)[0]); return TRUE; } @@ -755,7 +692,7 @@ pygi_gint8_from_py (PyObject *object, gint8 *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %ld", number, (long)G_MININT8, (long)G_MAXINT8); Py_DECREF (number); @@ -765,7 +702,7 @@ overflow: PyObject * pygi_gint8_to_py (gint8 value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } gboolean @@ -774,13 +711,13 @@ pygi_guint8_from_py (PyObject *object, guint8 *result) long long_value; PyObject *number; - if (PYGLIB_PyBytes_Check (object)) { - if (PYGLIB_PyBytes_Size (object) != 1) { + if (PyBytes_Check (object)) { + if (PyBytes_Size (object) != 1) { PyErr_Format (PyExc_TypeError, "Must be a single character"); return FALSE; } - *result = (guint8)(PYGLIB_PyBytes_AsString (object)[0]); + *result = (guint8)(PyBytes_AsString (object)[0]); return TRUE; } @@ -804,7 +741,7 @@ pygi_guint8_from_py (PyObject *object, guint8 *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %ld", number, (long)0, (long)G_MAXUINT8); Py_DECREF (number); @@ -814,7 +751,7 @@ overflow: PyObject * pygi_guint8_to_py (guint8 value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } static gboolean @@ -843,7 +780,7 @@ pygi_gint16_from_py (PyObject *object, gint16 *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %ld", number, (long)G_MININT16, (long)G_MAXINT16); Py_DECREF (number); @@ -853,7 +790,7 @@ overflow: static PyObject * pygi_gint16_to_py (gint16 value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } static gboolean @@ -882,7 +819,7 @@ pygi_guint16_from_py (PyObject *object, guint16 *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %ld", number, (long)0, (long)G_MAXUINT16); Py_DECREF (number); @@ -892,7 +829,7 @@ overflow: static PyObject * pygi_guint16_to_py (guint16 value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } static gboolean @@ -921,7 +858,7 @@ pygi_gint32_from_py (PyObject *object, gint32 *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %ld", number, (long)G_MININT32, (long)G_MAXINT32); Py_DECREF (number); @@ -931,7 +868,7 @@ overflow: static PyObject * pygi_gint32_to_py (gint32 value) { - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); } static gboolean @@ -960,7 +897,7 @@ pygi_guint32_from_py (PyObject *object, guint32 *result) overflow: PyErr_Clear (); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %lu", number, (long)0, (unsigned long)G_MAXUINT32); Py_DECREF (number); @@ -971,10 +908,10 @@ PyObject * pygi_guint32_to_py (guint32 value) { #if (G_MAXUINT <= LONG_MAX) - return PYGLIB_PyLong_FromLong (value); + return PyLong_FromLong (value); #else if (value <= LONG_MAX) - return PYGLIB_PyLong_FromLong((long) value); + return PyLong_FromLong((long) value); else return PyLong_FromLongLong (value); #endif @@ -1008,7 +945,7 @@ overflow: PyErr_Clear (); min = pygi_gint64_to_py (G_MININT64); max = pygi_gint64_to_py (G_MAXINT64); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %S to %S", number, min, max); Py_DECREF (number); @@ -1021,7 +958,7 @@ PyObject * pygi_gint64_to_py (gint64 value) { if (LONG_MIN <= value && value <= LONG_MAX) - return PYGLIB_PyLong_FromLong((long) value); + return PyLong_FromLong((long) value); else return PyLong_FromLongLong (value); } @@ -1053,7 +990,7 @@ pygi_guint64_from_py (PyObject *object, guint64 *result) overflow: PyErr_Clear (); max = pygi_guint64_to_py (G_MAXUINT64); - pygi_pyerr_format ( + PyErr_Format ( PyExc_OverflowError, "%S not in range %ld to %S", number, (long)0, max); Py_DECREF (number); @@ -1065,7 +1002,7 @@ PyObject * pygi_guint64_to_py (guint64 value) { if (value <= LONG_MAX) - return PYGLIB_PyLong_FromLong((long) value); + return PyLong_FromLong((long) value); else return PyLong_FromUnsignedLongLong (value); } @@ -1195,7 +1132,7 @@ pygi_utf8_to_py (gchar *value) Py_RETURN_NONE; } - return PYGLIB_PyUnicode_FromString (value); + return PyUnicode_FromString (value); } PyObject * @@ -1207,16 +1144,11 @@ pygi_filename_to_py (gchar *value) Py_RETURN_NONE; } -#if PY_VERSION_HEX < 0x03000000 - /* On PY2 we return str as is */ - py_obj = PyString_FromString (value); -#else #ifdef G_OS_WIN32 py_obj = PyUnicode_DecodeUTF8 (value, strlen(value), "surrogatepass"); #else py_obj = PyUnicode_DecodeFSDefault (value); -#endif #endif return py_obj; diff --git a/gi/pygi-boxed.c b/gi/pygi-boxed.c index e3b487b..3ab826d 100644 --- a/gi/pygi-boxed.c +++ b/gi/pygi-boxed.c @@ -24,7 +24,7 @@ #include "pygboxed.h" #include "pygi-type.h" #include "pygi-basictype.h" -#include "pygi-python-compat.h" +#include "pygi-util.h" #include @@ -165,7 +165,7 @@ boxed_init (PyObject *self, return 0; } -PYGLIB_DEFINE_TYPE("gi.Boxed", PyGIBoxed_Type, PyGIBoxed); +PYGI_DEFINE_TYPE("gi.Boxed", PyGIBoxed_Type, PyGIBoxed); PyObject * pygi_boxed_new (PyTypeObject *type, diff --git a/gi/pygi-cache.c b/gi/pygi-cache.c index 667ccf6..c6630de 100644 --- a/gi/pygi-cache.c +++ b/gi/pygi-cache.c @@ -21,7 +21,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygi-type.h" #include "pygi-info.h" #include "pygi-cache.h" @@ -662,7 +661,7 @@ _callable_cache_generate_args_cache_real (PyGICallableCache *callable_cache, arg_cache_item = callable_cache->to_py_args; while (arg_cache_item) { const gchar *arg_name = ((PyGIArgCache *)arg_cache_item->data)->arg_name; - PyObject *arg_string = PYGLIB_PyUnicode_FromString (arg_name); + PyObject *arg_string = PyUnicode_FromString (arg_name); PyList_Append (tuple_names, arg_string); Py_DECREF (arg_string); arg_cache_item = arg_cache_item->next; diff --git a/gi/pygi-ccallback.c b/gi/pygi-ccallback.c index cd003e9..897f3c1 100644 --- a/gi/pygi-ccallback.c +++ b/gi/pygi-ccallback.c @@ -19,7 +19,7 @@ * License along with this library; if not, see . */ -#include "pygi-python-compat.h" +#include "pygi-util.h" #include "pygi-ccallback.h" #include @@ -44,7 +44,7 @@ _ccallback_call(PyGICCallback *self, PyObject *args, PyObject *kwargs) return result; } -PYGLIB_DEFINE_TYPE("gi.CCallback", PyGICCallback_Type, PyGICCallback); +PYGI_DEFINE_TYPE("gi.CCallback", PyGICCallback_Type, PyGICCallback); PyObject * _pygi_ccallback_new (GCallback callback, diff --git a/gi/pygi-enum-marshal.c b/gi/pygi-enum-marshal.c index fc33089..15a489d 100644 --- a/gi/pygi-enum-marshal.c +++ b/gi/pygi-enum-marshal.c @@ -21,7 +21,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygi-enum-marshal.h" #include "pygi-type.h" #include "pygenum.h" @@ -132,13 +131,13 @@ _pygi_marshal_from_py_interface_enum (PyGIInvokeState *state, is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type); - py_long = PYGLIB_PyNumber_Long (py_arg); + py_long = PyNumber_Long (py_arg); if (py_long == NULL) { PyErr_Clear(); goto err; } - c_long = PYGLIB_PyLong_AsLong (py_long); + c_long = PyLong_AsLong (py_long); Py_DECREF (py_long); /* Write c_long into arg */ @@ -201,13 +200,13 @@ _pygi_marshal_from_py_interface_flags (PyGIInvokeState *state, is_instance = PyObject_IsInstance (py_arg, iface_cache->py_type); - py_long = PYGLIB_PyNumber_Long (py_arg); + py_long = PyNumber_Long (py_arg); if (py_long == NULL) { PyErr_Clear (); goto err; } - c_ulong = PYGLIB_PyLong_AsUnsignedLong (py_long); + c_ulong = PyLong_AsUnsignedLongMask (py_long); Py_DECREF (py_long); /* only 0 or argument of type Flag is allowed */ diff --git a/gi/pygi-error.c b/gi/pygi-error.c index b0eeccd..de6b7c1 100644 --- a/gi/pygi-error.c +++ b/gi/pygi-error.c @@ -23,7 +23,6 @@ #include #include "pygi-error.h" #include "pygi-type.h" -#include "pygi-python-compat.h" #include "pygi-util.h" #include "pygi-basictype.h" @@ -355,7 +354,7 @@ pygerror_to_gvalue (GValue *value, PyObject *pyerror) int pygi_error_register_types (PyObject *module) { - PyObject *error_module = pygi_import_module ("gi._error"); + PyObject *error_module = PyImport_ImportModule ("gi._error"); if (!error_module) { return -1; } diff --git a/gi/pygi-foreign-cairo.c b/gi/pygi-foreign-cairo.c index 399fe75..aa01157 100644 --- a/gi/pygi-foreign-cairo.c +++ b/gi/pygi-foreign-cairo.c @@ -23,13 +23,7 @@ #include #include - -#if PY_VERSION_HEX < 0x03000000 -#include -static Pycairo_CAPI_t *Pycairo_CAPI; -#else #include -#endif #include @@ -38,7 +32,6 @@ static Pycairo_CAPI_t *Pycairo_CAPI; * shared library that interacts with PyGI through a PyCapsule API at runtime. */ #include -#include "pygi-python-compat.h" /* * cairo_t marshaling @@ -613,23 +606,43 @@ cairo_matrix_from_gvalue (const GValue *value) return PycairoMatrix_FromMatrix (matrix); } +#ifdef __GNUC__ +#define PYGI_MODINIT_FUNC __attribute__((visibility("default"))) PyMODINIT_FUNC +#else +#define PYGI_MODINIT_FUNC PyMODINIT_FUNC +#endif + static PyMethodDef _gi_cairo_functions[] = { {0,} }; -PYGLIB_MODULE_START(_gi_cairo, "_gi_cairo") + +static struct PyModuleDef __gi_cairomodule = { + PyModuleDef_HEAD_INIT, + "_gi_cairo", + NULL, + -1, + _gi_cairo_functions, + NULL, + NULL, + NULL, + NULL +}; + +PYGI_MODINIT_FUNC PyInit__gi_cairo (void); + +PYGI_MODINIT_FUNC PyInit__gi_cairo (void) { + PyObject *module; + module = PyModule_Create (&__gi_cairomodule); + PyObject *gobject_mod; -#if PY_VERSION_HEX < 0x03000000 - Pycairo_IMPORT; -#else import_cairo(); -#endif if (Pycairo_CAPI == NULL) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; gobject_mod = pygobject_init (3, 13, 2); if (gobject_mod == NULL) - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; Py_DECREF (gobject_mod); pygi_register_foreign_struct ("cairo", @@ -698,5 +711,5 @@ PYGLIB_MODULE_START(_gi_cairo, "_gi_cairo") cairo_pattern_from_gvalue, cairo_pattern_to_gvalue); -} -PYGLIB_MODULE_END; + return module; +} \ No newline at end of file diff --git a/gi/pygi-info.c b/gi/pygi-info.c index 0c4824f..cbe8444 100644 --- a/gi/pygi-info.c +++ b/gi/pygi-info.c @@ -20,7 +20,6 @@ * License along with this library; if not, see . */ -#include "pygi-python-compat.h" #include "pygi-info.h" #include "pygi-cache.h" #include "pygi-invoke.h" @@ -40,7 +39,7 @@ _generate_doc_string(PyGIBaseInfo *self) static PyObject *_py_generate_doc_string = NULL; if (_py_generate_doc_string == NULL) { - PyObject *mod = pygi_import_module ("gi.docstring"); + PyObject *mod = PyImport_ImportModule ("gi.docstring"); if (!mod) return NULL; @@ -186,9 +185,9 @@ static PyObject * _base_info_repr (PyGIBaseInfo *self) { - return PYGLIB_PyUnicode_FromFormat ("%s(%s)", - Py_TYPE( (PyObject *) self)->tp_name, - _safe_base_info_get_name (self->info)); + return PyUnicode_FromFormat ("%s(%s)", + Py_TYPE( (PyObject *) self)->tp_name, + _safe_base_info_get_name (self->info)); } static PyObject * @@ -234,21 +233,14 @@ _base_info_richcompare (PyGIBaseInfo *self, PyObject *other, int op) return res; } -PYGLIB_DEFINE_TYPE("gi.BaseInfo", PyGIBaseInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE("gi.BaseInfo", PyGIBaseInfo_Type, PyGIBaseInfo); gboolean _pygi_is_python_keyword (const gchar *name) { /* It may be better to use keyword.iskeyword(); keep in sync with * python -c 'import keyword; print(keyword.kwlist)' */ -#if PY_VERSION_HEX < 0x03000000 - /* Python 2.x */ - static const gchar* keywords[] = {"and", "as", "assert", "break", "class", - "continue", "def", "del", "elif", "else", "except", "exec", "finally", - "for", "from", "global", "if", "import", "in", "is", "lambda", "not", - "or", "pass", "print", "raise", "return", "try", "while", "with", - "yield", NULL}; -#elif PY_VERSION_HEX < 0x04000000 +#if PY_VERSION_HEX < 0x04000000 /* Python 3.x; note that we explicitly keep "print"; it is not a keyword * any more, but we do not want to break API between Python versions */ static const gchar* keywords[] = {"False", "None", "True", "and", "as", @@ -376,13 +368,13 @@ _base_info_getattro(PyGIBaseInfo *self, PyObject *name) static PyObject *docstr; if (docstr == NULL) { - docstr= PYGLIB_PyUnicode_InternFromString("__doc__"); + docstr= PyUnicode_InternFromString ("__doc__"); if (docstr == NULL) return NULL; } Py_INCREF (name); - PYGLIB_PyUnicode_InternInPlace (&name); + PyUnicode_InternInPlace (&name); if (name == docstr) { result = _generate_doc_string (self); @@ -403,8 +395,8 @@ _base_info_attr_name(PyGIBaseInfo *self, void *closure) static PyObject * _base_info_attr_module(PyGIBaseInfo *self, void *closure) { - return PYGLIB_PyUnicode_FromFormat ("gi.repository.%s", - g_base_info_get_namespace (self->info)); + return PyUnicode_FromFormat ("gi.repository.%s", + g_base_info_get_namespace (self->info)); } static PyGetSetDef _base_info_getsets[] = { @@ -522,7 +514,7 @@ out: /* CallableInfo */ -PYGLIB_DEFINE_TYPE ("gi.CallableInfo", PyGICallableInfo_Type, PyGICallableInfo); +PYGI_DEFINE_TYPE ("gi.CallableInfo", PyGICallableInfo_Type, PyGICallableInfo); /* _callable_info_call: * @@ -600,7 +592,7 @@ _function_info_call (PyGICallableInfo *self, PyObject *args, PyObject *kwargs) py_str_name = tmp; } - str_name = PYGLIB_PyBytes_AsString (py_str_name); + str_name = PyBytes_AsString (py_str_name); if (strcmp (str_name, _safe_base_info_get_name (container_info))) { PyErr_Format (PyExc_TypeError, "%s constructor cannot be used to create instances of " @@ -769,21 +761,21 @@ static PyMethodDef _PyGICallableInfo_methods[] = { }; /* CallbackInfo */ -PYGLIB_DEFINE_TYPE ("gi.CallbackInfo", PyGICallbackInfo_Type, PyGICallableInfo); +PYGI_DEFINE_TYPE ("gi.CallbackInfo", PyGICallbackInfo_Type, PyGICallableInfo); static PyMethodDef _PyGICallbackInfo_methods[] = { { NULL, NULL, 0 } }; /* ErrorDomainInfo */ -PYGLIB_DEFINE_TYPE ("gi.ErrorDomainInfo", PyGIErrorDomainInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.ErrorDomainInfo", PyGIErrorDomainInfo_Type, PyGIBaseInfo); static PyMethodDef _PyGIErrorDomainInfo_methods[] = { { NULL, NULL, 0 } }; /* SignalInfo */ -PYGLIB_DEFINE_TYPE ("gi.SignalInfo", PyGISignalInfo_Type, PyGICallableInfo); +PYGI_DEFINE_TYPE ("gi.SignalInfo", PyGISignalInfo_Type, PyGICallableInfo); static PyObject * _wrap_g_signal_info_get_flags (PyGIBaseInfo *self) @@ -813,7 +805,7 @@ static PyMethodDef _PyGISignalInfo_methods[] = { }; /* PropertyInfo */ -PYGLIB_DEFINE_TYPE ("gi.PropertyInfo", PyGIPropertyInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.PropertyInfo", PyGIPropertyInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_property_info_get_flags (PyGIBaseInfo *self) @@ -844,7 +836,7 @@ static PyMethodDef _PyGIPropertyInfo_methods[] = { /* ArgInfo */ -PYGLIB_DEFINE_TYPE ("gi.ArgInfo", PyGIArgInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.ArgInfo", PyGIArgInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_arg_info_get_direction (PyGIBaseInfo *self) @@ -931,7 +923,7 @@ static PyMethodDef _PyGIArgInfo_methods[] = { /* TypeInfo */ -PYGLIB_DEFINE_TYPE ("gi.TypeInfo", PyGITypeInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.TypeInfo", PyGITypeInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_type_info_is_pointer (PyGIBaseInfo *self) @@ -1017,7 +1009,7 @@ static PyMethodDef _PyGITypeInfo_methods[] = { /* FunctionInfo */ -PYGLIB_DEFINE_TYPE ("gi.FunctionInfo", PyGIFunctionInfo_Type, PyGICallableInfo); +PYGI_DEFINE_TYPE ("gi.FunctionInfo", PyGIFunctionInfo_Type, PyGICallableInfo); static PyObject * _wrap_g_function_info_is_constructor (PyGIBaseInfo *self) @@ -1236,7 +1228,7 @@ static PyMethodDef _PyGIFunctionInfo_methods[] = { }; /* RegisteredTypeInfo */ -PYGLIB_DEFINE_TYPE ("gi.RegisteredTypeInfo", PyGIRegisteredTypeInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.RegisteredTypeInfo", PyGIRegisteredTypeInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_registered_type_info_get_type_name (PyGIBaseInfo *self) @@ -1269,7 +1261,7 @@ static PyMethodDef _PyGIRegisteredTypeInfo_methods[] = { /* GIStructInfo */ -PYGLIB_DEFINE_TYPE ("StructInfo", PyGIStructInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("StructInfo", PyGIStructInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_struct_info_get_fields (PyGIBaseInfo *self) @@ -1446,7 +1438,7 @@ pygi_g_struct_info_is_simple (GIStructInfo *struct_info) /* EnumInfo */ -PYGLIB_DEFINE_TYPE ("gi.EnumInfo", PyGIEnumInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.EnumInfo", PyGIEnumInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_enum_info_get_values (PyGIBaseInfo *self) @@ -1490,7 +1482,7 @@ static PyMethodDef _PyGIEnumInfo_methods[] = { /* ObjectInfo */ -PYGLIB_DEFINE_TYPE ("ObjectInfo", PyGIObjectInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("ObjectInfo", PyGIObjectInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_object_info_get_parent (PyGIBaseInfo *self) @@ -1632,7 +1624,7 @@ static PyMethodDef _PyGIObjectInfo_methods[] = { /* GIInterfaceInfo */ -PYGLIB_DEFINE_TYPE ("InterfaceInfo", PyGIInterfaceInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("InterfaceInfo", PyGIInterfaceInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_interface_info_get_methods (PyGIBaseInfo *self) @@ -1709,7 +1701,7 @@ static PyMethodDef _PyGIInterfaceInfo_methods[] = { }; /* GIConstantInfo */ -PYGLIB_DEFINE_TYPE ("gi.ConstantInfo", PyGIConstantInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.ConstantInfo", PyGIConstantInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_constant_info_get_value (PyGIBaseInfo *self) @@ -1749,7 +1741,7 @@ static PyMethodDef _PyGIConstantInfo_methods[] = { }; /* GIValueInfo */ -PYGLIB_DEFINE_TYPE ("gi.ValueInfo", PyGIValueInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.ValueInfo", PyGIValueInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_value_info_get_value (PyGIBaseInfo *self) @@ -1769,7 +1761,7 @@ static PyMethodDef _PyGIValueInfo_methods[] = { /* GIFieldInfo */ -PYGLIB_DEFINE_TYPE ("gi.FieldInfo", PyGIFieldInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.FieldInfo", PyGIFieldInfo_Type, PyGIBaseInfo); static gssize _struct_field_array_length_marshal (gsize length_index, @@ -2165,14 +2157,14 @@ static PyMethodDef _PyGIFieldInfo_methods[] = { /* GIUnresolvedInfo */ -PYGLIB_DEFINE_TYPE ("gi.UnresolvedInfo", PyGIUnresolvedInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.UnresolvedInfo", PyGIUnresolvedInfo_Type, PyGIBaseInfo); static PyMethodDef _PyGIUnresolvedInfo_methods[] = { { NULL, NULL, 0 } }; /* GIVFuncInfo */ -PYGLIB_DEFINE_TYPE ("gi.VFuncInfo", PyGIVFuncInfo_Type, PyGICallableInfo); +PYGI_DEFINE_TYPE ("gi.VFuncInfo", PyGIVFuncInfo_Type, PyGICallableInfo); static PyObject * _wrap_g_vfunc_info_get_flags (PyGIBaseInfo *self) @@ -2208,7 +2200,7 @@ static PyMethodDef _PyGIVFuncInfo_methods[] = { /* GIUnionInfo */ -PYGLIB_DEFINE_TYPE ("gi.UnionInfo", PyGIUnionInfo_Type, PyGIBaseInfo); +PYGI_DEFINE_TYPE ("gi.UnionInfo", PyGIUnionInfo_Type, PyGIBaseInfo); static PyObject * _wrap_g_union_info_get_fields (PyGIBaseInfo *self) diff --git a/gi/pygi-invoke.c b/gi/pygi-invoke.c index d5956c6..7b822e4 100644 --- a/gi/pygi-invoke.c +++ b/gi/pygi-invoke.c @@ -40,12 +40,6 @@ _check_for_unexpected_kwargs (PyGICallableCache *cache, while (PyDict_Next (py_kwargs, &dict_iter_pos, &dict_key, &dict_value)) { PyObject *key; -#if PY_VERSION_HEX < 0x03000000 - if (PyString_Check (dict_key)) { - Py_INCREF (dict_key); - key = dict_key; - } else -#endif { key = PyUnicode_AsUTF8String (dict_key); if (key == NULL) { diff --git a/gi/pygi-object.c b/gi/pygi-object.c index 79170e3..00b36c1 100644 --- a/gi/pygi-object.c +++ b/gi/pygi-object.c @@ -21,7 +21,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygi-object.h" #include "pygobject-object.h" #include "pygparamspec.h" @@ -52,7 +51,7 @@ _pygi_marshal_from_py_gobject (PyObject *py_arg, /*in*/ if (!pygobject_check (py_arg, &PyGObject_Type)) { PyObject *repr = PyObject_Repr (py_arg); PyErr_Format(PyExc_TypeError, "expected GObject but got %s", - PYGLIB_PyUnicode_AsString (repr)); + PyUnicode_AsUTF8 (repr)); Py_DECREF (repr); return FALSE; } @@ -117,7 +116,7 @@ pygi_arg_gobject_out_arg_from_py (PyObject *py_arg, /*in*/ gchar *msg = g_strdup_printf ("Expecting to marshal a borrowed reference for %s, " "but nothing in Python is holding a reference to this object. " "See: https://bugzilla.gnome.org/show_bug.cgi?id=687522", - PYGLIB_PyUnicode_AsString(repr)); + PyUnicode_AsUTF8 (repr)); Py_DECREF (repr); if (PyErr_WarnEx (PyExc_RuntimeWarning, msg, 2)) { g_free (msg); @@ -161,7 +160,7 @@ _pygi_marshal_from_py_interface_object (PyGIInvokeState *state, PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s", arg_cache->arg_name ? arg_cache->arg_name : "self", ( (PyGIInterfaceCache *)arg_cache)->type_name, - module ? PYGLIB_PyUnicode_AsString(module) : "", + module ? PyUnicode_AsUTF8 (module) : "", module ? "." : "", Py_TYPE (py_arg)->tp_name); if (module) diff --git a/gi/pygi-python-compat.h b/gi/pygi-python-compat.h deleted file mode 100644 index 76999db..0000000 --- a/gi/pygi-python-compat.h +++ /dev/null @@ -1,192 +0,0 @@ -/* -*- Mode: C; c-basic-offset: 4 -*- - * pyglib - Python bindings for GLib toolkit. - * Copyright (C) 2008 Johan Dahlin - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 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 - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, see . - */ - -#ifndef __PYGLIB_PYTHON_COMPAT_H__ -#define __PYGLIB_PYTHON_COMPAT_H__ - -#ifndef PY_SSIZE_T_CLEAN -#error "PY_SSIZE_T_CLEAN not defined" -#endif - -#include - -#define PYGLIB_MODULE_ERROR_RETURN NULL - -#ifdef __GNUC__ -#define PYGI_MODINIT_FUNC __attribute__((visibility("default"))) PyMODINIT_FUNC -#else -#define PYGI_MODINIT_FUNC PyMODINIT_FUNC -#endif - -/* Compilation on Python 2.x */ -#if PY_VERSION_HEX < 0x03000000 - -#define PYGLIB_PyUnicode_Check PyString_Check -#define PYGLIB_PyUnicode_AsString PyString_AsString -#define PYGLIB_PyUnicode_AsStringAndSize PyString_AsStringAndSize -#define PYGLIB_PyUnicode_FromString PyString_FromString -#define PYGLIB_PyUnicode_FromStringAndSize PyString_FromStringAndSize -#define PYGLIB_PyUnicode_FromFormat PyString_FromFormat -#define PYGLIB_PyUnicode_Type PyString_Type -#define PYGLIB_PyUnicode_InternFromString PyString_InternFromString -#define PYGLIB_PyUnicode_InternInPlace PyString_InternInPlace -#define PYGLIB_PyUnicode_Format PyString_Format - -#define PYGLIB_PyBytes_FromString PyString_FromString -#define PYGLIB_PyBytes_FromStringAndSize PyString_FromStringAndSize -#define PYGLIB_PyBytes_Resize _PyString_Resize -#define PYGLIB_PyBytes_AsString PyString_AsString -#define PYGLIB_PyBytes_AsStringAndSize PyString_AsStringAndSize -#define PYGLIB_PyBytes_Size PyString_Size -#define PYGLIB_PyBytes_Check PyString_Check - -#define PYGLIB_PyLong_Check PyInt_Check -#define PYGLIB_PyLong_FromLong PyInt_FromLong -#define PYGLIB_PyLong_FromSsize_t PyInt_FromSsize_t -#define PYGLIB_PyLong_FromSize_t PyInt_FromSize_t -#define PYGLIB_PyLong_AsLong PyInt_AsLong -#define PYGLIB_PyLong_AsSsize_t PyInt_AsSsize_t -#define PYGLIB_PyLongObject PyIntObject -#define PYGLIB_PyLong_Type PyInt_Type -#define PYGLIB_PyLong_AS_LONG PyInt_AS_LONG - -#define PYGLIB_Py_hash_t long - -/* Python 2.7 lacks a PyInt_FromUnsignedLong function; use signed longs, and - * rely on PyInt_AsUnsignedLong() to interpret them correctly */ -#define PYGLIB_PyLong_FromUnsignedLong PyInt_FromLong -#define PYGLIB_PyLong_AsUnsignedLong(o) PyInt_AsUnsignedLongMask((PyObject*)(o)) - -#define PYGLIB_PyNumber_Long PyNumber_Int - -#define PYGLIB_MODULE_START(symbol, modname) \ -PyObject * pyglib_##symbol##_module_create(void); \ -PYGI_MODINIT_FUNC init##symbol(void); \ -PYGI_MODINIT_FUNC init##symbol(void) { \ - pyglib_##symbol##_module_create(); \ -}; \ -PyObject * pyglib_##symbol##_module_create(void) \ -{ \ - PyObject *module; \ - module = Py_InitModule(modname, symbol##_functions); - -#define PYGLIB_MODULE_END return module; } - -#define PYGLIB_DEFINE_TYPE(typename, symbol, csymbol) \ -PyTypeObject symbol = { \ - PyObject_HEAD_INIT(NULL) \ - 0, \ - typename, \ - sizeof(csymbol), \ - 0, \ -}; - -#define PYGLIB_REGISTER_TYPE(d, type, name) \ - if (!type.tp_alloc) \ - type.tp_alloc = PyType_GenericAlloc; \ - if (!type.tp_new) \ - type.tp_new = PyType_GenericNew; \ - if (PyType_Ready(&type)) \ - return -1; \ - PyDict_SetItemString(d, name, (PyObject *)&type); - -#else - -#define PYGLIB_MODULE_START(symbol, modname) \ - static struct PyModuleDef _##symbol##module = { \ - PyModuleDef_HEAD_INIT, \ - modname, \ - NULL, \ - -1, \ - symbol##_functions, \ - NULL, \ - NULL, \ - NULL, \ - NULL \ -}; \ -PyObject * pyglib_##symbol##_module_create(void); \ -PYGI_MODINIT_FUNC PyInit_##symbol(void); \ -PYGI_MODINIT_FUNC PyInit_##symbol(void) { \ - return pyglib_##symbol##_module_create(); \ -}; \ -PyObject * pyglib_##symbol##_module_create(void) \ -{ \ - PyObject *module; \ - module = PyModule_Create(&_##symbol##module); - -#define PYGLIB_MODULE_END return module; } - -#define PYGLIB_DEFINE_TYPE(typename, symbol, csymbol) \ -PyTypeObject symbol = { \ - PyVarObject_HEAD_INIT(NULL, 0) \ - typename, \ - sizeof(csymbol) \ -}; - -#define PYGLIB_REGISTER_TYPE(d, type, name) \ - if (!type.tp_alloc) \ - type.tp_alloc = PyType_GenericAlloc; \ - if (!type.tp_new) \ - type.tp_new = PyType_GenericNew; \ - if (PyType_Ready(&type)) \ - return -1; \ - PyDict_SetItemString(d, name, (PyObject *)&type); - -#define PYGLIB_PyUnicode_Check PyUnicode_Check -#define PYGLIB_PyUnicode_AsString _PyUnicode_AsString -#define PYGLIB_PyUnicode_AsStringAndSize(obj, buf, size) \ - (((*(buf) = _PyUnicode_AsStringAndSize(obj, size)) != NULL) ? 0 : -1) -#define PYGLIB_PyUnicode_FromString PyUnicode_FromString -#define PYGLIB_PyUnicode_FromStringAndSize PyUnicode_FromStringAndSize -#define PYGLIB_PyUnicode_FromFormat PyUnicode_FromFormat -#define PYGLIB_PyUnicode_Resize PyUnicode_Resize -#define PYGLIB_PyUnicode_Type PyUnicode_Type -#define PYGLIB_PyUnicode_InternFromString PyUnicode_InternFromString -#define PYGLIB_PyUnicode_InternInPlace PyUnicode_InternInPlace -#define PYGLIB_PyUnicode_Format PyUnicode_Format - -#define PYGLIB_PyLong_Check PyLong_Check -#define PYGLIB_PyLong_FromLong PyLong_FromLong -#define PYGLIB_PyLong_FromSsize_t PyLong_FromSsize_t -#define PYGLIB_PyLong_FromSize_t PyLong_FromSize_t -#define PYGLIB_PyLong_AsLong PyLong_AsLong -#define PYGLIB_PyLong_AsSsize_t PyLong_AsSsize_t -#define PYGLIB_PyLong_AS_LONG(o) PyLong_AS_LONG((PyObject*)(o)) -#define PYGLIB_PyLongObject PyLongObject -#define PYGLIB_PyLong_Type PyLong_Type - -#define PYGLIB_PyLong_FromUnsignedLong PyLong_FromUnsignedLong -#define PYGLIB_PyLong_AsUnsignedLong(o) PyLong_AsUnsignedLongMask((PyObject*)(o)) - -#define PYGLIB_PyBytes_FromString PyBytes_FromString -#define PYGLIB_PyBytes_FromStringAndSize PyBytes_FromStringAndSize -#define PYGLIB_PyBytes_Resize(o, len) _PyBytes_Resize(o, len) -#define PYGLIB_PyBytes_AsString PyBytes_AsString -#define PYGLIB_PyBytes_AsStringAndSize PyBytes_AsStringAndSize -#define PYGLIB_PyBytes_Size PyBytes_Size -#define PYGLIB_PyBytes_Check PyBytes_Check - -#define PYGLIB_PyNumber_Long PyNumber_Long - -#define PYGLIB_Py_hash_t Py_hash_t - -#endif - -#define PYGLIB_Py_hash_t_FromVoidPtr(ptr) ((PYGLIB_Py_hash_t)(gintptr)(ptr)) - -#endif /* __PYGLIB_PYTHON_COMPAT_H__ */ diff --git a/gi/pygi-repository.c b/gi/pygi-repository.c index 133f89c..a39e7b1 100644 --- a/gi/pygi-repository.c +++ b/gi/pygi-repository.c @@ -22,11 +22,11 @@ #include "pygi-repository.h" #include "pygi-info.h" #include "pygi-basictype.h" -#include "pygi-python-compat.h" +#include "pygi-util.h" PyObject *PyGIRepositoryError; -PYGLIB_DEFINE_TYPE("gi.Repository", PyGIRepository_Type, PyGIRepository); +PYGI_DEFINE_TYPE("gi.Repository", PyGIRepository_Type, PyGIRepository); static PyObject * _wrap_g_irepository_enumerate_versions (PyGIRepository *self, diff --git a/gi/pygi-resulttuple.c b/gi/pygi-resulttuple.c index 0d060d0..6cb3cba 100644 --- a/gi/pygi-resulttuple.c +++ b/gi/pygi-resulttuple.c @@ -20,7 +20,7 @@ #include #include #include "pygi-resulttuple.h" -#include "pygi-python-compat.h" +#include "pygi-util.h" static char repr_format_key[] = "__repr_format"; static char tuple_indices_key[] = "__tuple_indices"; @@ -43,7 +43,7 @@ static PyObject *free_list[PyGIResultTuple_MAXSAVESIZE]; static int numfree[PyGIResultTuple_MAXSAVESIZE]; #endif -PYGLIB_DEFINE_TYPE ("gi._gi.ResultTuple", PyGIResultTuple_Type, PyTupleObject) +PYGI_DEFINE_TYPE ("gi._gi.ResultTuple", PyGIResultTuple_Type, PyTupleObject) /** * ResultTuple.__repr__() implementation. @@ -54,12 +54,12 @@ static PyObject* resulttuple_repr(PyObject *self) { PyObject *format, *repr, *format_attr; - format_attr = PYGLIB_PyUnicode_FromString (repr_format_key); + format_attr = PyUnicode_FromString (repr_format_key); format = PyTuple_Type.tp_getattro (self, format_attr); Py_DECREF (format_attr); if (format == NULL) return NULL; - repr = PYGLIB_PyUnicode_Format (format, self); + repr = PyUnicode_Format (format, self); Py_DECREF (format); return repr; } @@ -73,7 +73,7 @@ static PyObject* resulttuple_getattro(PyObject *self, PyObject *name) { PyObject *mapping, *index, *mapping_attr, *item; - mapping_attr = PYGLIB_PyUnicode_FromString (tuple_indices_key); + mapping_attr = PyUnicode_FromString (tuple_indices_key); mapping = PyTuple_Type.tp_getattro (self, mapping_attr); Py_DECREF (mapping_attr); if (mapping == NULL) @@ -82,7 +82,7 @@ resulttuple_getattro(PyObject *self, PyObject *name) { index = PyDict_GetItem (mapping, name); if (index != NULL) { - item = PyTuple_GET_ITEM (self, PYGLIB_PyLong_AsSsize_t (index)); + item = PyTuple_GET_ITEM (self, PyLong_AsSsize_t (index)); Py_INCREF (item); } else { item = PyTuple_Type.tp_getattro (self, name); @@ -120,7 +120,7 @@ resulttuple_dir(PyObject *self) PyObject *mapping_values = NULL; PyObject *result = NULL; - mapping_attr = PYGLIB_PyUnicode_FromString (tuple_indices_key); + mapping_attr = PyUnicode_FromString (tuple_indices_key); mapping = PyTuple_Type.tp_getattro (self, mapping_attr); Py_DECREF (mapping_attr); if (mapping == NULL) @@ -208,8 +208,8 @@ pygi_resulttuple_new_type(PyObject *tuple_names) { format_list = PyList_New (0); index_dict = PyDict_New (); - empty_format = PYGLIB_PyUnicode_FromString ("%r"); - named_format = PYGLIB_PyUnicode_FromString ("%s=%%r"); + empty_format = PyUnicode_FromString ("%r"); + named_format = PyUnicode_FromString ("%s=%%r"); len = PyList_Size (tuple_names); for (i = 0; i < len; i++) { PyObject *item, *named_args, *named_build, *index; @@ -218,11 +218,11 @@ pygi_resulttuple_new_type(PyObject *tuple_names) { PyList_Append (format_list, empty_format); } else { named_args = Py_BuildValue ("(O)", item); - named_build = PYGLIB_PyUnicode_Format (named_format, named_args); + named_build = PyUnicode_Format (named_format, named_args); Py_DECREF (named_args); PyList_Append (format_list, named_build); Py_DECREF (named_build); - index = PYGLIB_PyLong_FromSsize_t (i); + index = PyLong_FromSsize_t (i); PyDict_SetItem (index_dict, item, index); Py_DECREF (index); } @@ -230,12 +230,12 @@ pygi_resulttuple_new_type(PyObject *tuple_names) { Py_DECREF (empty_format); Py_DECREF (named_format); - sep = PYGLIB_PyUnicode_FromString (", "); + sep = PyUnicode_FromString (", "); format_string = PyObject_CallMethod (sep, "join", "O", format_list); Py_DECREF (sep); Py_DECREF (format_list); - paren_format = PYGLIB_PyUnicode_FromString ("(%s)"); - paren_string = PYGLIB_PyUnicode_Format (paren_format, format_string); + paren_format = PyUnicode_FromString ("(%s)"); + paren_string = PyUnicode_Format (paren_format, format_string); Py_DECREF (paren_format); Py_DECREF (format_string); diff --git a/gi/pygi-source.c b/gi/pygi-source.c index c6cdfda..c85386d 100644 --- a/gi/pygi-source.c +++ b/gi/pygi-source.c @@ -23,7 +23,6 @@ * IN THE SOFTWARE. */ -#include "pygi-python-compat.h" #include "pygi-info.h" #include "pygi-boxed.h" #include "pygi-type.h" diff --git a/gi/pygi-struct-marshal.c b/gi/pygi-struct-marshal.c index a7705a5..6daf317 100644 --- a/gi/pygi-struct-marshal.c +++ b/gi/pygi-struct-marshal.c @@ -21,7 +21,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygi-struct-marshal.h" #include "pygi-struct.h" #include "pygi-foreign.h" @@ -312,7 +311,7 @@ type_error: PyErr_Format (PyExc_TypeError, "argument %s: Expected %s, but got %s%s%s", arg_name ? arg_name : "self", type_name, - module ? PYGLIB_PyUnicode_AsString(module) : "", + module ? PyUnicode_AsUTF8(module) : "", module ? "." : "", Py_TYPE (py_arg)->tp_name); if (module) diff --git a/gi/pygi-struct.c b/gi/pygi-struct.c index 4c05b7c..5188485 100644 --- a/gi/pygi-struct.c +++ b/gi/pygi-struct.c @@ -25,7 +25,7 @@ #include "pygi-type.h" #include "pygi-type.h" #include "pygpointer.h" -#include "pygi-python-compat.h" +#include "pygi-util.h" #include @@ -144,7 +144,7 @@ struct_init (PyObject *self, return 0; } -PYGLIB_DEFINE_TYPE("gi.Struct", PyGIStruct_Type, PyGIStruct); +PYGI_DEFINE_TYPE("gi.Struct", PyGIStruct_Type, PyGIStruct); PyObject * @@ -216,11 +216,11 @@ struct_repr(PyGIStruct *self) if (info == NULL) return NULL; - repr = PYGLIB_PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>", - g_base_info_get_namespace (info), - g_base_info_get_name (info), - self, g_type_name (pointer->gtype), - pointer->pointer); + repr = PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>", + g_base_info_get_namespace (info), + g_base_info_get_name (info), + self, g_type_name (pointer->gtype), + pointer->pointer); g_base_info_unref (info); diff --git a/gi/pygi-type.c b/gi/pygi-type.c index 952d307..6f9f7b4 100644 --- a/gi/pygi-type.c +++ b/gi/pygi-type.c @@ -41,7 +41,7 @@ pygi_type_import_by_name (const char *namespace_, module_name = g_strconcat ("gi.repository.", namespace_, NULL); - py_module = pygi_import_module (module_name); + py_module = PyImport_ImportModule (module_name); g_free (module_name); @@ -111,7 +111,7 @@ typedef struct { GType type; } PyGTypeWrapper; -PYGLIB_DEFINE_TYPE("gobject.GType", PyGTypeWrapper_Type, PyGTypeWrapper); +PYGI_DEFINE_TYPE("gobject.GType", PyGTypeWrapper_Type, PyGTypeWrapper); static PyObject* generic_gsize_richcompare(gsize a, gsize b, int op) @@ -187,7 +187,7 @@ pyg_type_wrapper_repr(PyGTypeWrapper *self) g_snprintf(buf, sizeof(buf), "", name?name:"invalid", (unsigned long int) self->type); - return PYGLIB_PyUnicode_FromString(buf); + return PyUnicode_FromString (buf); } static void @@ -260,7 +260,7 @@ static PyObject * _wrap_g_type_wrapper__get_name(PyGTypeWrapper *self, void *closure) { const char *name = g_type_name(self->type); - return PYGLIB_PyUnicode_FromString(name ? name : "invalid"); + return PyUnicode_FromString (name ? name : "invalid"); } static PyObject * @@ -501,15 +501,13 @@ pyg_type_from_object_strict(PyObject *obj, gboolean strict) if (PyType_Check(obj)) { PyTypeObject *tp = (PyTypeObject *)obj; - if (tp == &PYGLIB_PyLong_Type) + if (tp == &PyLong_Type) return G_TYPE_INT; else if (tp == &PyBool_Type) return G_TYPE_BOOLEAN; - else if (tp == &PyLong_Type) - return G_TYPE_LONG; else if (tp == &PyFloat_Type) return G_TYPE_DOUBLE; - else if (tp == &PYGLIB_PyUnicode_Type) + else if (tp == &PyUnicode_Type) return G_TYPE_STRING; else if (tp == &PyBaseObject_Type) return PY_TYPE_OBJECT; @@ -520,8 +518,8 @@ pyg_type_from_object_strict(PyObject *obj, gboolean strict) } /* handle strings */ - if (PYGLIB_PyUnicode_Check(obj)) { - gchar *name = PYGLIB_PyUnicode_AsString(obj); + if (PyUnicode_Check (obj)) { + gchar *name = PyUnicode_AsUTF8(obj); type = g_type_from_name(name); if (type != 0) { @@ -594,7 +592,7 @@ pyg_enum_get_value(GType enum_type, PyObject *obj, gint *val) if (!obj) { *val = 0; res = 0; - } else if (PYGLIB_PyLong_Check(obj)) { + } else if (PyLong_Check (obj)) { if (!pygi_gint_from_py (obj, val)) res = -1; else @@ -617,9 +615,9 @@ pyg_enum_get_value(GType enum_type, PyObject *obj, gint *val) g_type_name(enum_type), g_type_name(((PyGEnum *) obj)->gtype)); } - } else if (PYGLIB_PyUnicode_Check(obj)) { + } else if (PyUnicode_Check (obj)) { GEnumValue *info; - char *str = PYGLIB_PyUnicode_AsString(obj); + char *str = PyUnicode_AsUTF8 (obj); if (enum_type != G_TYPE_NONE) eclass = G_ENUM_CLASS(g_type_class_ref(enum_type)); @@ -671,15 +669,15 @@ pyg_flags_get_value(GType flag_type, PyObject *obj, guint *val) if (!obj) { *val = 0; res = 0; - } else if (PYGLIB_PyLong_Check(obj)) { + } else if (PyLong_Check (obj)) { if (pygi_guint_from_py (obj, val)) res = 0; } else if (PyLong_Check(obj)) { if (pygi_guint_from_py (obj, val)) res = 0; - } else if (PYGLIB_PyUnicode_Check(obj)) { + } else if (PyUnicode_Check (obj)) { GFlagsValue *info; - char *str = PYGLIB_PyUnicode_AsString(obj); + char *str = PyUnicode_AsUTF8 (obj); if (flag_type != G_TYPE_NONE) fclass = G_FLAGS_CLASS(g_type_class_ref(flag_type)); @@ -715,7 +713,7 @@ pyg_flags_get_value(GType flag_type, PyObject *obj, guint *val) for (i = 0; i < len; i++) { PyObject *item = PyTuple_GetItem(obj, i); - char *str = PYGLIB_PyUnicode_AsString(item); + char *str = PyUnicode_AsUTF8 (item); GFlagsValue *info = g_flags_get_value_by_name(fclass, str); if (!info) @@ -1250,12 +1248,12 @@ object_doc_descr_get(PyObject *self, PyObject *obj, PyObject *type) g_array_free(parents, TRUE); } - pystring = PYGLIB_PyUnicode_FromStringAndSize(string->str, string->len); + pystring = PyUnicode_FromStringAndSize (string->str, string->len); g_string_free(string, TRUE); return pystring; } -PYGLIB_DEFINE_TYPE("gobject.GObject.__doc__", PyGObjectDoc_Type, PyObject); +PYGI_DEFINE_TYPE("gobject.GObject.__doc__", PyGObjectDoc_Type, PyObject); /** * pyg_object_descr_doc_get: @@ -1379,7 +1377,12 @@ pygi_type_register_types(PyObject *d) PyGTypeWrapper_Type.tp_methods = _PyGTypeWrapper_methods; PyGTypeWrapper_Type.tp_getset = _PyGTypeWrapper_getsets; PyGTypeWrapper_Type.tp_init = (initproc)pyg_type_wrapper_init; - PYGLIB_REGISTER_TYPE(d, PyGTypeWrapper_Type, "GType"); + PyGTypeWrapper_Type.tp_alloc = PyType_GenericAlloc; + PyGTypeWrapper_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&PyGTypeWrapper_Type)) + return -1; + + PyDict_SetItemString(d, "GType", (PyObject *)&PyGTypeWrapper_Type); /* This type lazily registered in pyg_object_descr_doc_get */ PyGObjectDoc_Type.tp_dealloc = (destructor)object_doc_dealloc; diff --git a/gi/pygi-type.h b/gi/pygi-type.h index 94ddc85..c7e1a45 100644 --- a/gi/pygi-type.h +++ b/gi/pygi-type.h @@ -26,15 +26,6 @@ #include #include "pygobject-internal.h" -#define PYGOBJECT_REGISTER_GTYPE(d, type, name, gtype) \ - { \ - PyObject *o; \ - PYGLIB_REGISTER_TYPE(d, type, name); \ - PyDict_SetItemString(type.tp_dict, "__gtype__", \ - o=pyg_type_wrapper_new(gtype)); \ - Py_DECREF(o); \ -} - extern PyTypeObject PyGTypeWrapper_Type; typedef PyObject *(* fromvaluefunc)(const GValue *value); diff --git a/gi/pygi-util.c b/gi/pygi-util.c index c02a53c..3a297f4 100644 --- a/gi/pygi-util.c +++ b/gi/pygi-util.c @@ -18,38 +18,6 @@ #include "pygi-util.h" -/** - * Like PyErr_Format, but supports the format syntax of - * PyUnicode_FromFormat also under Python 2. - * Note: Python 2 doesn't support %lld and %llo there. - */ -PyObject* -pygi_pyerr_format (PyObject *exception, const char *format, ...) -{ - PyObject *text; - va_list argp; - va_start(argp, format); - text = PyUnicode_FromFormatV (format, argp); - va_end(argp); - - if (text != NULL) { -#if PY_MAJOR_VERSION < 3 - PyObject *str; - str = PyUnicode_AsUTF8String (text); - Py_DECREF (text); - if (str) { - PyErr_SetObject (exception, str); - Py_DECREF (str); - } -#else - PyErr_SetObject (exception, text); - Py_DECREF (text); -#endif - } - - return NULL; -} - gboolean pygi_guint_from_pyssize (Py_ssize_t pyval, guint *result) { @@ -64,23 +32,6 @@ pygi_guint_from_pyssize (Py_ssize_t pyval, guint *result) return TRUE; } -/* Better alternative to PyImport_ImportModule which tries to import from - * sys.modules first */ -PyObject * -pygi_import_module (const char *name) -{ -#if PY_VERSION_HEX < 0x03000000 && !defined(PYPY_VERSION) - /* see PyImport_ImportModuleNoBlock - * https://github.com/python/cpython/blob/2.7/Python/import.c#L2166-L2206 */ - PyObject *result = PyImport_ImportModuleNoBlock(name); - if (result) - return result; - - PyErr_Clear(); -#endif - return PyImport_ImportModule(name); -} - PyObject * pyg_integer_richcompare(PyObject *v, PyObject *w, int op) { @@ -88,12 +39,12 @@ pyg_integer_richcompare(PyObject *v, PyObject *w, int op) gboolean t; switch (op) { - case Py_EQ: t = PYGLIB_PyLong_AS_LONG(v) == PYGLIB_PyLong_AS_LONG(w); break; - case Py_NE: t = PYGLIB_PyLong_AS_LONG(v) != PYGLIB_PyLong_AS_LONG(w); break; - case Py_LE: t = PYGLIB_PyLong_AS_LONG(v) <= PYGLIB_PyLong_AS_LONG(w); break; - case Py_GE: t = PYGLIB_PyLong_AS_LONG(v) >= PYGLIB_PyLong_AS_LONG(w); break; - case Py_LT: t = PYGLIB_PyLong_AS_LONG(v) < PYGLIB_PyLong_AS_LONG(w); break; - case Py_GT: t = PYGLIB_PyLong_AS_LONG(v) > PYGLIB_PyLong_AS_LONG(w); break; + case Py_EQ: t = PyLong_AS_LONG (v) == PyLong_AS_LONG (w); break; + case Py_NE: t = PyLong_AS_LONG (v) != PyLong_AS_LONG (w); break; + case Py_LE: t = PyLong_AS_LONG (v) <= PyLong_AS_LONG (w); break; + case Py_GE: t = PyLong_AS_LONG (v) >= PyLong_AS_LONG (w); break; + case Py_LT: t = PyLong_AS_LONG (v) < PyLong_AS_LONG (w); break; + case Py_GT: t = PyLong_AS_LONG (v) > PyLong_AS_LONG (w); break; default: g_assert_not_reached(); } diff --git a/gi/pygi-util.h b/gi/pygi-util.h index 2f9847e..f67ca8a 100644 --- a/gi/pygi-util.h +++ b/gi/pygi-util.h @@ -3,20 +3,21 @@ #include #include -#include "pygobject-internal.h" -#include "pygi-python-compat.h" G_BEGIN_DECLS PyObject * pyg_integer_richcompare(PyObject *v, PyObject *w, int op); PyObject * pyg_ptr_richcompare(void* a, void *b, int op); const gchar * pyg_constant_strip_prefix(const gchar *name, const gchar *strip_prefix); -PyObject * pygi_import_module (const char *name); -PyObject * pygi_pyerr_format (PyObject *exception, const char *format, ...); gboolean pygi_guint_from_pyssize (Py_ssize_t pyval, guint *result); -#if PY_VERSION_HEX >= 0x03000000 +#define PYGI_DEFINE_TYPE(typename, symbol, csymbol) \ +PyTypeObject symbol = { \ + PyVarObject_HEAD_INIT(NULL, 0) \ + typename, \ + sizeof(csymbol) \ +}; #define _PyGI_ERROR_PREFIX(format, ...) G_STMT_START { \ PyObject *py_error_prefix; \ @@ -37,25 +38,6 @@ gboolean pygi_guint_from_pyssize (Py_ssize_t pyval, guint *result); } \ } G_STMT_END -#else - -#define _PyGI_ERROR_PREFIX(format, ...) G_STMT_START { \ - PyObject *py_error_prefix; \ - py_error_prefix = PyString_FromFormat(format, ## __VA_ARGS__); \ - if (py_error_prefix != NULL) { \ - PyObject *py_error_type, *py_error_value, *py_error_traceback; \ - PyErr_Fetch(&py_error_type, &py_error_value, &py_error_traceback); \ - if (PyString_Check(py_error_value)) { \ - PyString_ConcatAndDel(&py_error_prefix, py_error_value); \ - if (py_error_prefix != NULL) { \ - py_error_value = py_error_prefix; \ - } \ - } \ - PyErr_Restore(py_error_type, py_error_value, py_error_traceback); \ - } \ -} G_STMT_END - -#endif G_END_DECLS diff --git a/gi/pygi-value.c b/gi/pygi-value.c index 0c54c3e..e7ee1e0 100644 --- a/gi/pygi-value.c +++ b/gi/pygi-value.c @@ -19,7 +19,6 @@ #include #include "pygi-value.h" #include "pygi-struct.h" -#include "pygi-python-compat.h" #include "pygi-basictype.h" #include "pygobject-object.h" #include "pygi-type.h" @@ -536,12 +535,13 @@ pyg_value_from_pyobject_with_error(GValue *value, PyObject *obj) else if (PySequence_Check(obj) && G_VALUE_HOLDS(value, G_TYPE_ARRAY)) return pyg_array_from_pyobject(value, obj); - else if (PYGLIB_PyUnicode_Check(obj) && + else if (PyUnicode_Check (obj) && G_VALUE_HOLDS(value, G_TYPE_GSTRING)) { GString *string; char *buffer; Py_ssize_t len; - if (PYGLIB_PyUnicode_AsStringAndSize(obj, &buffer, &len)) + buffer = PyUnicode_AsUTF8AndSize (obj, &len); + if (buffer == NULL) return -1; string = g_string_new_len(buffer, len); g_value_set_boxed(value, string); @@ -655,9 +655,9 @@ pygi_value_to_py_basic_type (const GValue *value, GType fundamental, gboolean *h *handled = TRUE; switch (fundamental) { case G_TYPE_CHAR: - return PYGLIB_PyLong_FromLong (g_value_get_schar (value)); + return PyLong_FromLong (g_value_get_schar (value)); case G_TYPE_UCHAR: - return PYGLIB_PyLong_FromLong (g_value_get_uchar (value)); + return PyLong_FromLong (g_value_get_uchar (value)); case G_TYPE_BOOLEAN: return pygi_gboolean_to_py (g_value_get_boolean (value)); case G_TYPE_INT: @@ -747,7 +747,7 @@ value_to_py_structured_type (const GValue *value, GType fundamental, gboolean co return ret; } else if (G_VALUE_HOLDS(value, G_TYPE_GSTRING)) { GString *string = (GString *) g_value_get_boxed(value); - PyObject *ret = PYGLIB_PyUnicode_FromStringAndSize(string->str, string->len); + PyObject *ret = PyUnicode_FromStringAndSize (string->str, string->len); return ret; } bm = pyg_type_lookup(G_VALUE_TYPE(value)); @@ -816,10 +816,10 @@ pyg_value_as_pyobject (const GValue *value, gboolean copy_boxed) * See: https://bugzilla.gnome.org/show_bug.cgi?id=733893 */ if (fundamental == G_TYPE_CHAR) { gint8 val = g_value_get_schar(value); - return PYGLIB_PyUnicode_FromStringAndSize ((char *)&val, 1); + return PyUnicode_FromStringAndSize ((char *)&val, 1); } else if (fundamental == G_TYPE_UCHAR) { guint8 val = g_value_get_uchar(value); - return PYGLIB_PyBytes_FromStringAndSize ((char *)&val, 1); + return PyBytes_FromStringAndSize ((char *)&val, 1); } pyobj = pygi_value_to_py_basic_type (value, fundamental, &handled); diff --git a/gi/pyginterface.c b/gi/pyginterface.c index a80b40f..b6e5529 100644 --- a/gi/pyginterface.c +++ b/gi/pyginterface.c @@ -23,14 +23,14 @@ #include #include -#include "pygi-python-compat.h" +#include "pygi-util.h" #include "pyginterface.h" #include "pygi-type.h" GQuark pyginterface_type_key; GQuark pyginterface_info_key; -PYGLIB_DEFINE_TYPE("gobject.GInterface", PyGInterface_Type, PyObject) +PYGI_DEFINE_TYPE("gobject.GInterface", PyGInterface_Type, PyObject) static int pyg_interface_init(PyObject *self, PyObject *args, PyObject *kwargs) @@ -108,19 +108,29 @@ pyg_lookup_interface_info(GType gtype) int pygi_interface_register_types(PyObject *d) { - pyginterface_type_key = g_quark_from_static_string("PyGInterface::type"); - pyginterface_info_key = g_quark_from_static_string("PyGInterface::info"); + PyObject *pygtype; - PyGInterface_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; - PyGInterface_Type.tp_init = (initproc)pyg_interface_init; - PyGInterface_Type.tp_free = (freefunc)pyg_interface_free; + pyginterface_type_key = g_quark_from_static_string("PyGInterface::type"); + pyginterface_info_key = g_quark_from_static_string("PyGInterface::info"); - PYGOBJECT_REGISTER_GTYPE(d, PyGInterface_Type, "GInterface", G_TYPE_INTERFACE) + PyGInterface_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; + PyGInterface_Type.tp_init = (initproc)pyg_interface_init; + PyGInterface_Type.tp_free = (freefunc)pyg_interface_free; + PyGInterface_Type.tp_alloc = PyType_GenericAlloc; + PyGInterface_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&PyGInterface_Type)) + return -1; - PyDict_SetItemString(PyGInterface_Type.tp_dict, "__doc__", - pyg_object_descr_doc_get()); - PyDict_SetItemString(PyGInterface_Type.tp_dict, "__gdoc__", - pyg_object_descr_doc_get()); + pygtype = pyg_type_wrapper_new (G_TYPE_INTERFACE); + PyDict_SetItemString (PyGInterface_Type.tp_dict, "__gtype__", pygtype); + Py_DECREF (pygtype); - return 0; + PyDict_SetItemString(PyGInterface_Type.tp_dict, "__doc__", + pyg_object_descr_doc_get()); + PyDict_SetItemString(PyGInterface_Type.tp_dict, "__gdoc__", + pyg_object_descr_doc_get()); + + PyDict_SetItemString(d, "GInterface", (PyObject *)&PyGInterface_Type); + + return 0; } diff --git a/gi/pygobject-object.c b/gi/pygobject-object.c index 76b18cc..c59a2cc 100644 --- a/gi/pygobject-object.c +++ b/gi/pygobject-object.c @@ -207,7 +207,7 @@ typedef struct { guint index; } PyGPropsIter; -PYGLIB_DEFINE_TYPE("gi._gi.GPropsIter", PyGPropsIter_Type, PyGPropsIter); +PYGI_DEFINE_TYPE("gi._gi.GPropsIter", PyGPropsIter_Type, PyGPropsIter); static void pyg_props_iter_dealloc(PyGPropsIter *self) @@ -263,7 +263,7 @@ build_parameter_list(GObjectClass *class) name = g_strdup(g_param_spec_get_name(props[i])); /* hyphens cannot belong in identifiers */ g_strdelimit(name, "-", '_'); - prop_str = PYGLIB_PyUnicode_FromString(name); + prop_str = PyUnicode_FromString (name); PyList_SetItem(props_list, i, prop_str); g_free(name); @@ -282,7 +282,7 @@ PyGProps_getattro(PyGProps *self, PyObject *attr) GObjectClass *class; GParamSpec *pspec; - attr_name = PYGLIB_PyUnicode_AsString(attr); + attr_name = PyUnicode_AsUTF8 (attr); if (!attr_name) { PyErr_Clear(); return PyObject_GenericGetAttr((PyObject *)self, attr); @@ -336,7 +336,7 @@ set_property_from_pspec(GObject *obj, PyObject *pvalue_str = PyObject_Repr(pvalue); PyErr_Format(PyExc_TypeError, "could not convert %s to type '%s' when setting property '%s.%s'", - PYGLIB_PyUnicode_AsString(pvalue_str), + PyUnicode_AsUTF8 (pvalue_str), g_type_name(G_PARAM_SPEC_VALUE_TYPE(pspec)), G_OBJECT_TYPE_NAME(obj), pspec->name); @@ -352,7 +352,7 @@ set_property_from_pspec(GObject *obj, return TRUE; } -PYGLIB_DEFINE_TYPE("gi._gi.GProps", PyGProps_Type, PyGProps); +PYGI_DEFINE_TYPE("gi._gi.GProps", PyGProps_Type, PyGProps); static int PyGProps_setattro(PyGProps *self, PyObject *attr, PyObject *pvalue) @@ -368,7 +368,7 @@ PyGProps_setattro(PyGProps *self, PyObject *attr, PyObject *pvalue) return -1; } - attr_name = PYGLIB_PyUnicode_AsString(attr); + attr_name = PyUnicode_AsUTF8 (attr); if (!attr_name) { PyErr_Clear(); return PyObject_GenericSetAttr((PyObject *)self, attr, pvalue); @@ -478,7 +478,7 @@ static PySequenceMethods _PyGProps_as_sequence = { 0 }; -PYGLIB_DEFINE_TYPE("gi._gi.GPropsDescr", PyGPropsDescr_Type, PyObject); +PYGI_DEFINE_TYPE("gi._gi.GPropsDescr", PyGPropsDescr_Type, PyObject); static PyObject * pyg_props_descr_descr_get(PyObject *self, PyObject *obj, PyObject *type) @@ -579,7 +579,7 @@ pygobject_register_class(PyObject *dict, const gchar *type_name, */ s = strrchr(type->tp_name, '.'); if (s != NULL) { - mod_name = PYGLIB_PyUnicode_FromStringAndSize(type->tp_name, (int)(s - type->tp_name)); + mod_name = PyUnicode_FromStringAndSize (type->tp_name, (int)(s - type->tp_name)); PyDict_SetItemString(type->tp_dict, "__module__", mod_name); Py_DECREF(mod_name); } @@ -795,7 +795,7 @@ pygobject_new_with_interfaces(GType gtype) /* Something special to point out that it's not accessible through * gi.repository */ - o = PYGLIB_PyUnicode_FromString ("__gi__"); + o = PyUnicode_FromString ("__gi__"); PyDict_SetItemString (dict, "__module__", o); Py_DECREF (o); @@ -870,17 +870,11 @@ static void pygobject_inherit_slots(PyTypeObject *type, PyObject *bases, gboolean check_for_present) { static int slot_offsets[] = { offsetof(PyTypeObject, tp_richcompare), -#if PY_VERSION_HEX < 0x03000000 - offsetof(PyTypeObject, tp_compare), -#endif offsetof(PyTypeObject, tp_richcompare), offsetof(PyTypeObject, tp_hash), offsetof(PyTypeObject, tp_iter), offsetof(PyTypeObject, tp_repr), offsetof(PyTypeObject, tp_str), -#if PY_VERSION_HEX < 0x03000000 - offsetof(PyTypeObject, tp_print), -#endif }; gsize i; @@ -1113,7 +1107,7 @@ pygobject_watch_closure(PyObject *self, GClosure *closure) /* -------------- PyGObject behaviour ----------------- */ -PYGLIB_DEFINE_TYPE("gi._gi.GObject", PyGObject_Type, PyGObject); +PYGI_DEFINE_TYPE("gi._gi.GObject", PyGObject_Type, PyGObject); static void pygobject_dealloc(PyGObject *self) @@ -1163,10 +1157,10 @@ pygobject_richcompare(PyObject *self, PyObject *other, int op) op); } -static PYGLIB_Py_hash_t +static Py_hash_t pygobject_hash(PyGObject *self) { - return PYGLIB_Py_hash_t_FromVoidPtr (self->obj); + return (Py_hash_t)(gintptr)(self->obj); } static PyObject * @@ -1179,12 +1173,12 @@ pygobject_repr(PyGObject *self) if (module == NULL) return NULL; - if (!PYGLIB_PyUnicode_Check (module)) { + if (!PyUnicode_Check (module)) { Py_DECREF (module); return NULL; } - module_str = PYGLIB_PyUnicode_AsString (module); + module_str = PyUnicode_AsUTF8 (module); namespace = g_strrstr (module_str, "."); if (namespace == NULL) { namespace = module_str; @@ -1192,10 +1186,10 @@ pygobject_repr(PyGObject *self) namespace += 1; } - repr = PYGLIB_PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>", - namespace, Py_TYPE (self)->tp_name, self, - self->obj ? G_OBJECT_TYPE_NAME (self->obj) : "uninitialized", - self->obj); + repr = PyUnicode_FromFormat ("<%s.%s object at %p (%s at %p)>", + namespace, Py_TYPE (self)->tp_name, self, + self->obj ? G_OBJECT_TYPE_NAME (self->obj) : "uninitialized", + self->obj); Py_DECREF (module); return repr; } @@ -1277,7 +1271,7 @@ pygobject_prepare_construct_properties(GObjectClass *class, PyObject *kwargs, GParamSpec *pspec; GValue *gvalue = &(*values)[*n_properties]; - const gchar *key_str = PYGLIB_PyUnicode_AsString(key); + const gchar *key_str = PyUnicode_AsUTF8 (key); pspec = g_object_class_find_property(class, key_str); if (!pspec) { @@ -1401,13 +1395,13 @@ pygobject_get_properties(PyGObject *self, PyObject *args) gchar *property_name; PyObject *item; - if (!PYGLIB_PyUnicode_Check(py_property)) { + if (!PyUnicode_Check (py_property)) { PyErr_SetString(PyExc_TypeError, "Expected string argument for property."); goto fail; } - property_name = PYGLIB_PyUnicode_AsString(py_property); + property_name = PyUnicode_AsUTF8 (py_property); item = pygi_get_property_value_by_name (self, property_name); PyTuple_SetItem (tuple, i, item); } @@ -1474,7 +1468,7 @@ pygobject_set_properties(PyGObject *self, PyObject *args, PyObject *kwargs) pos = 0; while (kwargs && PyDict_Next (kwargs, &pos, &key, &value)) { - gchar *key_str = PYGLIB_PyUnicode_AsString(key); + gchar *key_str = PyUnicode_AsUTF8 (key); GParamSpec *pspec; int ret = -1; @@ -1658,8 +1652,8 @@ pygobject_bind_property(PyGObject *self, PyObject *args) source_repr = PyObject_Repr((PyObject*)self); target_repr = PyObject_Repr(target); PyErr_Format(PyExc_TypeError, "Cannot create binding from %s.%s to %s.%s", - PYGLIB_PyUnicode_AsString(source_repr), source_name, - PYGLIB_PyUnicode_AsString(target_repr), target_name); + PyUnicode_AsUTF8 (source_repr), source_name, + PyUnicode_AsUTF8 (target_repr), target_name); Py_DECREF(source_repr); Py_DECREF(target_repr); return NULL; @@ -1681,7 +1675,7 @@ connect_helper(PyGObject *self, gchar *name, PyObject *callback, PyObject *extra &sigid, &detail, TRUE)) { PyObject *repr = PyObject_Repr((PyObject*)self); PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s", - PYGLIB_PyUnicode_AsString(repr), + PyUnicode_AsUTF8 (repr), name); Py_DECREF(repr); return NULL; @@ -1889,7 +1883,7 @@ pygobject_emit(PyGObject *self, PyObject *args) &signal_id, &detail, TRUE)) { repr = PyObject_Repr((PyObject*)self); PyErr_Format(PyExc_TypeError, "%s: unknown signal name: %s", - PYGLIB_PyUnicode_AsString(repr), + PyUnicode_AsUTF8 (repr), name); Py_DECREF(repr); return NULL; @@ -2102,7 +2096,7 @@ pygobject_disconnect_by_func(PyGObject *self, PyObject *args) if (!closure) { repr = PyObject_Repr((PyObject*)pyfunc); PyErr_Format(PyExc_TypeError, "nothing connected to %s", - PYGLIB_PyUnicode_AsString(repr)); + PyUnicode_AsUTF8 (repr)); Py_DECREF(repr); return NULL; } @@ -2136,7 +2130,7 @@ pygobject_handler_block_by_func(PyGObject *self, PyObject *args) if (!closure) { repr = PyObject_Repr((PyObject*)pyfunc); PyErr_Format(PyExc_TypeError, "nothing connected to %s", - PYGLIB_PyUnicode_AsString(repr)); + PyUnicode_AsUTF8 (repr)); Py_DECREF(repr); return NULL; } @@ -2170,7 +2164,7 @@ pygobject_handler_unblock_by_func(PyGObject *self, PyObject *args) if (!closure) { repr = PyObject_Repr((PyObject*)pyfunc); PyErr_Format(PyExc_TypeError, "nothing connected to %s", - PYGLIB_PyUnicode_AsString(repr)); + PyUnicode_AsUTF8 (repr)); Py_DECREF(repr); return NULL; } @@ -2264,7 +2258,7 @@ typedef struct { gboolean have_floating_ref; } PyGObjectWeakRef; -PYGLIB_DEFINE_TYPE("gi._gi.GObjectWeakRef", PyGObjectWeakRef_Type, PyGObjectWeakRef); +PYGI_DEFINE_TYPE("gi._gi.GObjectWeakRef", PyGObjectWeakRef_Type, PyGObjectWeakRef); static int pygobject_weak_ref_traverse(PyGObjectWeakRef *self, visitproc visit, void *arg) @@ -2473,7 +2467,7 @@ pyi_object_register_types(PyObject *d) descr = PyObject_New(PyObject, &PyGPropsDescr_Type); PyDict_SetItemString(PyGObject_Type.tp_dict, "props", descr); PyDict_SetItemString(PyGObject_Type.tp_dict, "__module__", - o=PYGLIB_PyUnicode_FromString("gi._gi")); + o=PyUnicode_FromString ("gi._gi")); Py_DECREF(o); /* GPropsIter */ diff --git a/gi/pygobject-object.h b/gi/pygobject-object.h index 580939a..95e95aa 100644 --- a/gi/pygobject-object.h +++ b/gi/pygobject-object.h @@ -3,7 +3,6 @@ #include #include -#include "pygi-python-compat.h" #include "pygobject-internal.h" /* Data that belongs to the GObject instance, not the Python wrapper */ diff --git a/gi/pygoptioncontext.c b/gi/pygoptioncontext.c index 61ecb76..c2f402c 100644 --- a/gi/pygoptioncontext.c +++ b/gi/pygoptioncontext.c @@ -25,7 +25,7 @@ #include "pygi-util.h" #include "pygi-basictype.h" -PYGLIB_DEFINE_TYPE("gi._gi.OptionContext", PyGOptionContext_Type, PyGOptionContext) +PYGI_DEFINE_TYPE("gi._gi.OptionContext", PyGOptionContext_Type, PyGOptionContext) /** * pyg_option_group_transfer_group: @@ -151,7 +151,7 @@ pyg_option_context_parse(PyGOptionContext *self, for (pos = 0; pos < argv_length; pos++) { arg = PyList_GetItem(argv, pos); - argv_content[pos] = g_strdup(PYGLIB_PyUnicode_AsString(arg)); + argv_content[pos] = g_strdup(PyUnicode_AsUTF8 (arg)); if (argv_content[pos] == NULL) { g_strfreev(argv_content); @@ -179,7 +179,7 @@ pyg_option_context_parse(PyGOptionContext *self, new_argv = PyList_New(g_strv_length(argv_content)); for (pos = 0; pos < argv_length; pos++) { - arg = PYGLIB_PyUnicode_FromString(argv_content[pos]); + arg = PyUnicode_FromString (argv_content[pos]); PyList_SetItem(new_argv, pos, arg); } @@ -368,7 +368,12 @@ pygi_option_context_register_types(PyObject *d) PyGOptionContext_Type.tp_flags = Py_TPFLAGS_DEFAULT; PyGOptionContext_Type.tp_methods = pyg_option_context_methods; PyGOptionContext_Type.tp_init = (initproc)pyg_option_context_init; - PYGLIB_REGISTER_TYPE(d, PyGOptionContext_Type, "OptionContext"); + PyGOptionContext_Type.tp_alloc = PyType_GenericAlloc; + PyGOptionContext_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&PyGOptionContext_Type)) + return -1; + + PyDict_SetItemString(d, "OptionContext", (PyObject *)&PyGOptionContext_Type); return 0; } diff --git a/gi/pygoptiongroup.c b/gi/pygoptiongroup.c index f144d81..9d1bdc1 100644 --- a/gi/pygoptiongroup.c +++ b/gi/pygoptiongroup.c @@ -24,7 +24,7 @@ #include "pygi-error.h" #include "pygi-util.h" -PYGLIB_DEFINE_TYPE("gi._gi.OptionGroup", PyGOptionGroup_Type, PyGOptionGroup) +PYGI_DEFINE_TYPE("gi._gi.OptionGroup", PyGOptionGroup_Type, PyGOptionGroup) /** * pyg_option_group_new: @@ -295,7 +295,13 @@ pygi_option_group_register_types(PyObject *d) PyGOptionGroup_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; PyGOptionGroup_Type.tp_methods = pyg_option_group_methods; PyGOptionGroup_Type.tp_init = (initproc)pyg_option_group_init; - PYGLIB_REGISTER_TYPE(d, PyGOptionGroup_Type, "OptionGroup"); + PyGOptionGroup_Type.tp_alloc = PyType_GenericAlloc; + PyGOptionGroup_Type.tp_new = PyType_GenericNew; + + if (PyType_Ready(&PyGOptionGroup_Type)) + return -1; + + PyDict_SetItemString(d, "OptionGroup", (PyObject *)&PyGOptionGroup_Type); return 0; } diff --git a/gi/pygparamspec.c b/gi/pygparamspec.c index 2c59181..bb94cd9 100644 --- a/gi/pygparamspec.c +++ b/gi/pygparamspec.c @@ -31,7 +31,7 @@ #include "pygi-util.h" #include "pygi-basictype.h" -PYGLIB_DEFINE_TYPE("gobject.GParamSpec", PyGParamSpec_Type, PyGParamSpec); +PYGI_DEFINE_TYPE("gobject.GParamSpec", PyGParamSpec_Type, PyGParamSpec); static PyObject* pyg_param_spec_richcompare(PyObject *self, PyObject *other, int op) @@ -46,10 +46,10 @@ pyg_param_spec_richcompare(PyObject *self, PyObject *other, int op) } } -static PYGLIB_Py_hash_t +static Py_hash_t pyg_param_spec_hash(PyGParamSpec *self) { - return PYGLIB_Py_hash_t_FromVoidPtr (pyg_param_spec_get (self)); + return (Py_hash_t)(gintptr)(pyg_param_spec_get (self)); } static PyObject * @@ -60,7 +60,7 @@ pyg_param_spec_repr(PyGParamSpec *self) g_snprintf(buf, sizeof(buf), "<%s '%s'>", G_PARAM_SPEC_TYPE_NAME (pyg_param_spec_get (self)), g_param_spec_get_name (pyg_param_spec_get (self))); - return PYGLIB_PyUnicode_FromString(buf); + return PyUnicode_FromString (buf); } static void @@ -136,7 +136,7 @@ pyg_param_spec_getattr(PyGParamSpec *self, const gchar *attr) if (G_IS_PARAM_SPEC_CHAR(pspec)) { if (!strcmp(attr, "default_value")) { - return PYGLIB_PyUnicode_FromFormat( + return PyUnicode_FromFormat( "%c", G_PARAM_SPEC_CHAR(pspec)->default_value); } else if (!strcmp(attr, "minimum")) { return pygi_gint8_to_py (G_PARAM_SPEC_CHAR(pspec)->minimum); @@ -145,7 +145,7 @@ pyg_param_spec_getattr(PyGParamSpec *self, const gchar *attr) } } else if (G_IS_PARAM_SPEC_UCHAR(pspec)) { if (!strcmp(attr, "default_value")) { - return PYGLIB_PyUnicode_FromFormat( + return PyUnicode_FromFormat( "%c", G_PARAM_SPEC_UCHAR(pspec)->default_value); } else if (!strcmp(attr, "minimum")) { return pygi_guint8_to_py (G_PARAM_SPEC_UCHAR(pspec)->minimum); @@ -206,7 +206,7 @@ pyg_param_spec_getattr(PyGParamSpec *self, const gchar *attr) } } else if (G_IS_PARAM_SPEC_UNICHAR(pspec)) { if (!strcmp(attr, "default_value")) { - return PYGLIB_PyUnicode_FromFormat( + return PyUnicode_FromFormat( "%c", G_PARAM_SPEC_UNICHAR(pspec)->default_value); } } else if (G_IS_PARAM_SPEC_ENUM(pspec)) { diff --git a/gi/pygpointer.c b/gi/pygpointer.c index 8e13374..fc6482d 100644 --- a/gi/pygpointer.c +++ b/gi/pygpointer.c @@ -30,7 +30,7 @@ GQuark pygpointer_class_key; -PYGLIB_DEFINE_TYPE("gobject.GPointer", PyGPointer_Type, PyGPointer); +PYGI_DEFINE_TYPE("gobject.GPointer", PyGPointer_Type, PyGPointer); static void pyg_pointer_dealloc(PyGPointer *self) @@ -51,10 +51,10 @@ pyg_pointer_richcompare(PyObject *self, PyObject *other, int op) } } -static PYGLIB_Py_hash_t +static Py_hash_t pyg_pointer_hash(PyGPointer *self) { - return PYGLIB_Py_hash_t_FromVoidPtr (pyg_pointer_get_ptr (self)); + return (Py_hash_t)(gintptr)(pyg_pointer_get_ptr (self)); } static PyObject * @@ -65,7 +65,7 @@ pyg_pointer_repr(PyGPointer *self) g_snprintf(buf, sizeof(buf), "<%s at 0x%" G_GUINTPTR_FORMAT ">", g_type_name(self->gtype), (guintptr)pyg_pointer_get_ptr (self)); - return PYGLIB_PyUnicode_FromString(buf); + return PyUnicode_FromString (buf); } static int @@ -187,6 +187,8 @@ pyg_pointer_new(GType pointer_type, gpointer pointer) int pygi_pointer_register_types(PyObject *d) { + PyObject *pygtype; + pygpointer_class_key = g_quark_from_static_string("PyGPointer::class"); PyGPointer_Type.tp_dealloc = (destructor)pyg_pointer_dealloc; @@ -196,7 +198,16 @@ pygi_pointer_register_types(PyObject *d) PyGPointer_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; PyGPointer_Type.tp_init = (initproc)pyg_pointer_init; PyGPointer_Type.tp_free = (freefunc)pyg_pointer_free; - PYGOBJECT_REGISTER_GTYPE(d, PyGPointer_Type, "GPointer", G_TYPE_POINTER); + PyGPointer_Type.tp_alloc = PyType_GenericAlloc; + PyGPointer_Type.tp_new = PyType_GenericNew; + if (PyType_Ready(&PyGPointer_Type)) + return -1; + + pygtype = pyg_type_wrapper_new (G_TYPE_POINTER); + PyDict_SetItemString (PyGPointer_Type.tp_dict, "__gtype__", pygtype); + Py_DECREF (pygtype); + + PyDict_SetItemString(d, "GPointer", (PyObject *)&PyGPointer_Type); return 0; } diff --git a/gi/pygspawn.c b/gi/pygspawn.c index 9457c6d..56ecf06 100644 --- a/gi/pygspawn.c +++ b/gi/pygspawn.c @@ -22,7 +22,7 @@ #include #include -#include "pygi-python-compat.h" +#include "pygi-util.h" #include "pygi-basictype.h" #include "pygspawn.h" #include "pygi-error.h" @@ -32,7 +32,7 @@ struct _PyGChildSetupData { PyObject *data; }; -PYGLIB_DEFINE_TYPE("gi._gi.Pid", PyGPid_Type, PYGLIB_PyLongObject) +PYGI_DEFINE_TYPE("gi._gi.Pid", PyGPid_Type, PyLongObject) static GPid pyg_pid_get_pid (PyObject *self) @@ -40,7 +40,7 @@ pyg_pid_get_pid (PyObject *self) #ifdef G_OS_WIN32 return (GPid)PyLong_AsVoidPtr (self); #else - return (GPid)PYGLIB_PyLong_AsLong (self); + return (GPid)PyLong_AsLong (self); #endif } @@ -61,7 +61,7 @@ static void pyg_pid_free(PyObject *gpid) { g_spawn_close_pid(pyg_pid_get_pid (gpid)); - PYGLIB_PyLong_Type.tp_free((void *) gpid); + PyLong_Type.tp_free((void *) gpid); } static int @@ -158,7 +158,7 @@ pyglib_spawn_async(PyObject *object, PyObject *args, PyObject *kwargs) argv = g_new0(char *, len + 1); for (i = 0; i < len; ++i) { PyObject *tmp = PySequence_ITEM(pyargv, i); - if (tmp == NULL || !PYGLIB_PyUnicode_Check(tmp)) { + if (tmp == NULL || !PyUnicode_Check (tmp)) { PyErr_SetString(PyExc_TypeError, "gi._gi.spawn_async: " "first argument must be a sequence of strings"); @@ -166,7 +166,7 @@ pyglib_spawn_async(PyObject *object, PyObject *args, PyObject *kwargs) Py_XDECREF(tmp); return NULL; } - argv[i] = PYGLIB_PyUnicode_AsString(tmp); + argv[i] = PyUnicode_AsUTF8 (tmp); Py_DECREF(tmp); } @@ -183,7 +183,7 @@ pyglib_spawn_async(PyObject *object, PyObject *args, PyObject *kwargs) envp = g_new0(char *, len + 1); for (i = 0; i < len; ++i) { PyObject *tmp = PySequence_ITEM(pyenvp, i); - if (tmp == NULL || !PYGLIB_PyUnicode_Check(tmp)) { + if (tmp == NULL || !PyUnicode_Check (tmp)) { PyErr_SetString(PyExc_TypeError, "gi._gi.spawn_async: " "second argument must be a sequence of strings"); @@ -192,7 +192,7 @@ pyglib_spawn_async(PyObject *object, PyObject *args, PyObject *kwargs) g_free(argv); return NULL; } - envp[i] = PYGLIB_PyUnicode_AsString(tmp); + envp[i] = PyUnicode_AsUTF8 (tmp); Py_DECREF(tmp); } } @@ -266,13 +266,18 @@ pyglib_spawn_async(PyObject *object, PyObject *args, PyObject *kwargs) int pygi_spawn_register_types(PyObject *d) { - PyGPid_Type.tp_base = &PYGLIB_PyLong_Type; + PyGPid_Type.tp_base = &PyLong_Type; PyGPid_Type.tp_flags = Py_TPFLAGS_DEFAULT; PyGPid_Type.tp_methods = pyg_pid_methods; PyGPid_Type.tp_init = pyg_pid_tp_init; PyGPid_Type.tp_free = (freefunc)pyg_pid_free; - PyGPid_Type.tp_new = PYGLIB_PyLong_Type.tp_new; - PYGLIB_REGISTER_TYPE(d, PyGPid_Type, "Pid"); + PyGPid_Type.tp_new = PyLong_Type.tp_new; + PyGPid_Type.tp_alloc = PyType_GenericAlloc; + + if (PyType_Ready(&PyGPid_Type)) + return -1; + + PyDict_SetItemString(d, "Pid", (PyObject *)&PyGPid_Type); return 0; } diff --git a/gi/pygtkcompat.py b/gi/pygtkcompat.py index 4a9c4be..364fb6c 100644 --- a/gi/pygtkcompat.py +++ b/gi/pygtkcompat.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import warnings from gi import PyGIDeprecationWarning diff --git a/gi/repository/__init__.py b/gi/repository/__init__.py index 5c5552a..640fc8e 100644 --- a/gi/repository/__init__.py +++ b/gi/repository/__init__.py @@ -18,8 +18,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - import sys from ..importer import DynamicImporter diff --git a/gi/types.py b/gi/types.py index 47ed18a..9205936 100644 --- a/gi/types.py +++ b/gi/types.py @@ -20,9 +20,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - -import warnings import re from ._constants import TYPE_INVALID @@ -290,19 +287,7 @@ def mro(C): # in __mro__ at each point. Therefore at this point we know that # we already have our base class MRO's available to us, there is # no need for us to (re)calculate them. - if hasattr(base, '__mro__'): - bases_of_subclasses += [list(base.__mro__)] - else: - warnings.warn('Mixin class %s is an old style class, please ' - 'update this to derive from "object".' % base, - RuntimeWarning) - # For old-style classes (Python2 only), the MRO is not - # easily accessible. As we do need it here, we calculate - # it via recursion, according to the C3 algorithm. Using C3 - # for old style classes deviates from Python's own behaviour, - # but visible effects here would be a corner case triggered by - # questionable design. - bases_of_subclasses += [mro(base)] + bases_of_subclasses += [list(base.__mro__)] bases_of_subclasses += [list(C.__bases__)] while bases_of_subclasses: diff --git a/meson.build b/meson.build index 4e59729..4b7b75a 100644 --- a/meson.build +++ b/meson.build @@ -1,5 +1,5 @@ project('pygobject', 'c', - version : '3.36.1', + version : '3.38.0', meson_version : '>= 0.46.0', default_options : [ 'warning_level=1', 'buildtype=debugoptimized']) @@ -15,8 +15,8 @@ platform_version = '@0@.0'.format(pygobject_version_major) pymod = import('python') python = pymod.find_installation(get_option('python')) -if python.language_version().version_compare('< 3.0') and host_machine.system() == 'windows' - error('Python 2 on Windows no longer supported since 3.35. Use Python 3 instead.') +if python.language_version().version_compare('< 3.5') + error('Requires Python >= 3.5') endif python_dep = python.dependency() @@ -43,29 +43,26 @@ with_pycairo = get_option('pycairo') cc = meson.get_compiler('c') -if with_pycairo - cairo_dep = dependency('cairo', required: cc.get_id() != 'msvc') - cairo_gobject_dep = dependency('cairo-gobject', required: cc.get_id() != 'msvc') +if not with_pycairo.disabled() + cairo_dep = dependency('cairo', required: with_pycairo.enabled() and cc.get_id() != 'msvc') + cairo_gobject_dep = dependency('cairo-gobject', required: with_pycairo.enabled() and cc.get_id() != 'msvc') if cc.get_id() == 'msvc' and (not cairo_gobject_dep.found() or not cairo_dep.found()) if cc.has_header('cairo.h') and cc.has_header ('cairo-gobject.h') - cairo_dep = cc.find_library ('cairo') - cairo_gobject_dep = cc.find_library ('cairo-gobject') + cairo_dep = cc.find_library ('cairo', required: with_pycairo) + cairo_gobject_dep = cc.find_library ('cairo-gobject', required: with_pycairo) endif endif - if python.language_version().version_compare('>= 3.0') - pycairo_name = 'py3cairo' - else - pycairo_name = 'pycairo' - endif - pycairo_dep = dependency( - pycairo_name, + 'py3cairo', version: pycairo_version_req, fallback: ['pycairo', 'pycairo_dep'], default_options: ['python=' + get_option('python')], + required: with_pycairo, ) +else + cairo_dep = dependency('', required: false) endif main_c_args = [] diff --git a/meson_options.txt b/meson_options.txt index 5dd4cbc..4fb5304 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -1,3 +1,3 @@ option('python', type : 'string', value : 'python3') -option('pycairo', type : 'boolean', value : true, description : 'build with pycairo integration') +option('pycairo', type : 'feature', value : 'auto', description : 'build with pycairo integration') option('tests', type : 'boolean', value : true, description : 'build unit tests') diff --git a/pygtkcompat/pygtkcompat.py b/pygtkcompat/pygtkcompat.py index c9711c6..966b67b 100644 --- a/pygtkcompat/pygtkcompat.py +++ b/pygtkcompat/pygtkcompat.py @@ -34,10 +34,10 @@ a well behaved PyGTK application mostly unmodified on top of PyGI. import sys import warnings +from collections import UserList import gi from gi.repository import GObject -from gi import _compat _patches = [] @@ -149,10 +149,6 @@ def _disable_all(): sys.modules[name] = old_value del _module_patches[:] - _compat.reload(sys) - if _compat.PY2: - sys.setdefaultencoding('ascii') - def enable_gtk(version='3.0'): if _check_enabled("gtk", version): @@ -161,11 +157,6 @@ def enable_gtk(version='3.0'): if version == "4.0": raise ValueError("version 4.0 not supported") - # set the default encoding like PyGTK - _compat.reload(sys) - if _compat.PY2: - sys.setdefaultencoding('utf-8') - # atk gi.require_version('Atk', '1.0') from gi.repository import Atk @@ -429,11 +420,11 @@ def enable_gtk(version='3.0'): orig_size_request = Gtk.Widget.size_request def size_request(widget): - class SizeRequest(_compat.UserList): + class SizeRequest(UserList): def __init__(self, req): self.height = req.height self.width = req.width - _compat.UserList.__init__(self, [self.width, self.height]) + UserList.__init__(self, [self.width, self.height]) return SizeRequest(orig_size_request(widget)) _patch(Gtk.Widget, "size_request", size_request) _patch(Gtk.Widget, "hide_all", Gtk.Widget.hide) diff --git a/setup.py b/setup.py index 8a35829..bc86f16 100755 --- a/setup.py +++ b/setup.py @@ -28,11 +28,7 @@ import posixpath from email import parser -try: - from setuptools import setup -except ImportError: - from distutils.core import setup - +from setuptools import setup from distutils.core import Extension, Distribution, Command from distutils.errors import DistutilsSetupError, DistutilsOptionError from distutils.ccompiler import new_compiler @@ -41,7 +37,7 @@ from distutils import dir_util, log from distutils.spawn import find_executable -PYGOBJECT_VERSION = "3.36.1" +PYGOBJECT_VERSION = "3.38.0" GLIB_VERSION_REQUIRED = "2.48.0" GI_VERSION_REQUIRED = "1.46.0" PYCAIRO_VERSION_REQUIRED = "1.11.1" @@ -63,10 +59,6 @@ def get_command_class(name): return Distribution({}).get_command_class(name) -def get_pycairo_pkg_config_name(): - return "py3cairo" if sys.version_info[0] == 3 else "pycairo" - - def get_version_requirement(pkg_config_name): """Given a pkg-config module name gets the minimum version required""" @@ -74,7 +66,7 @@ def get_version_requirement(pkg_config_name): "gobject-introspection-1.0": GI_VERSION_REQUIRED, "glib-2.0": GLIB_VERSION_REQUIRED, "gio-2.0": GLIB_VERSION_REQUIRED, - get_pycairo_pkg_config_name(): PYCAIRO_VERSION_REQUIRED, + "py3cairo": PYCAIRO_VERSION_REQUIRED, "libffi": LIBFFI_VERSION_REQUIRED, "cairo": "0", "cairo-gobject": "0", @@ -225,11 +217,7 @@ def pkg_config_version_check(pkg_name, version): def pkg_config_parse(opt, pkg_name): ret = _run_pkg_config_or_exit(pkg_name, [opt, pkg_name]) - - if sys.version_info[0] == 3: - output = ret.decode() - else: - output = ret + output = ret.decode() opt = opt[-2:] return [x.lstrip(opt) for x in output.split()] @@ -837,7 +825,7 @@ def get_pycairo_include_dir(): Raises if pycairo isn't found or it's too old. """ - pkg_config_name = get_pycairo_pkg_config_name() + pkg_config_name = "py3cairo" min_version = get_version_requirement(pkg_config_name) min_version_info = tuple(int(p) for p in min_version.split(".")) @@ -882,23 +870,13 @@ def get_pycairo_include_dir(): location = os.path.dirname(os.path.abspath(cairo.__path__[0])) log.info("pycairo: found %r" % location) - def samefile(src, dst): - # Python 2 on Windows doesn't have os.path.samefile, so we have to - # provide a fallback - if hasattr(os.path, "samefile"): - return os.path.samefile(src, dst) - os.stat(src) - os.stat(dst) - return (os.path.normcase(os.path.abspath(src)) == - os.path.normcase(os.path.abspath(dst))) - def get_sys_path(location, name): # Returns the sysconfig path for a distribution, or None for scheme in sysconfig.get_scheme_names(): for path_type in ["platlib", "purelib"]: path = sysconfig.get_path(path_type, scheme) try: - if samefile(path, location): + if os.path.samefile(path, location): return sysconfig.get_path(name, scheme) except EnvironmentError: pass @@ -1006,11 +984,6 @@ def add_ext_compiler_flags(ext, compiler, _cache={}): "-Wwrite-strings", ] - if sys.version_info[0] == 2: - args += [ - "-Wdeclaration-after-statement", - ] - args += [ "-Wno-incompatible-pointer-types-discards-qualifiers", "-Wno-missing-field-initializers", @@ -1111,9 +1084,6 @@ class build_ext(du_build_ext): add_ext_compiler_flags(gi_cairo_ext, compiler) def run(self): - if os.name == "nt" and sys.version_info[0] == 2: - raise SystemExit("Python 2 on Windows no longer supported since 3.35. Use Python 3 instead.") - self._write_config_h() self._setup_extensions() du_build_ext.run(self) @@ -1197,6 +1167,9 @@ class install(du_install): def main(): + if sys.version_info[0] < 3: + raise Exception("Python 2 no longer supported") + script_dir = get_script_dir() pkginfo = parse_pkg_info(script_dir) gi_dir = os.path.join(script_dir, "gi") @@ -1235,8 +1208,7 @@ def main(): ) ext_modules.append(gi_cairo_ext) install_requires.append( - "pycairo>=%s" % get_version_requirement( - get_pycairo_pkg_config_name())) + "pycairo>=%s" % get_version_requirement("py3cairo")) version = pkginfo["Version"] if is_dev_version(): @@ -1275,8 +1247,7 @@ def main(): "install_pkgconfig": install_pkgconfig, }, install_requires=install_requires, - python_requires=( - '>=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4'), + python_requires=pkginfo["Requires-Python"], data_files=[ ('include/pygobject-3.0', ['gi/pygobject.h']), ], diff --git a/tests/__init__.py b/tests/__init__.py index c5f02c3..44068d2 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import os import sys import unittest @@ -34,12 +32,8 @@ sys.meta_path.insert(0, GIImport()) def init_test_environ(): # this was renamed in Python 3, provide backwards compatible name - if sys.version_info[:2] == (2, 7): - unittest.TestCase.assertRaisesRegex = unittest.TestCase.assertRaisesRegexp - - if sys.version_info[0] == 3: - unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex - unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex + unittest.TestCase.assertRegexpMatches = unittest.TestCase.assertRegex + unittest.TestCase.assertRaisesRegexp = unittest.TestCase.assertRaisesRegex def dbus_launch_session(): if os.name == "nt" or sys.platform == "darwin": @@ -52,8 +46,7 @@ def init_test_environ(): except (subprocess.CalledProcessError, OSError): return (-1, "") else: - if sys.version_info[0] == 3: - out = out.decode("utf-8") + out = out.decode("utf-8") addr, pid = out.splitlines() return int(pid), addr diff --git a/tests/conftest.py b/tests/conftest.py index 820210c..254a721 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,13 +1,7 @@ -# -*- coding: utf-8 -*- - -from __future__ import absolute_import - import sys import pytest -from gi._compat import reraise - @pytest.hookimpl(hookwrapper=True, tryfirst=True) def pytest_runtest_call(item): @@ -28,4 +22,5 @@ def pytest_runtest_call(item): finally: sys.excepthook = orig_excepthook if exceptions: - reraise(*exceptions[0]) + tp, value, tb = exceptions[0] + raise tp(value).with_traceback(tb) diff --git a/tests/helper.py b/tests/helper.py index 1485ec3..bed51e8 100644 --- a/tests/helper.py +++ b/tests/helper.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import contextlib import unittest import inspect @@ -7,11 +5,11 @@ import warnings import functools import sys from collections import namedtuple +from io import StringIO import gi from gi import PyGIDeprecationWarning from gi.repository import GLib -from gi._compat import StringIO ExceptionInfo = namedtuple("ExceptionInfo", ["type", "value", "traceback"]) diff --git a/tests/meson.build b/tests/meson.build index dbb74d1..6a25688 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -68,7 +68,7 @@ regress_headers += ['regressextra.h'] regress_deps = [glib_dep, gobject_dep, gio_dep, gmodule_dep] regress_c_args = [] -if with_pycairo +if cairo_dep.found() regress_deps += [cairo_dep, cairo_gobject_dep] else regress_c_args += ['-D_GI_DISABLE_CAIRO'] @@ -121,7 +121,7 @@ if host_machine.system() == 'windows' endif python_paths = [join_paths(meson.current_build_dir(), '..')] -if with_pycairo and pycairo_dep.type_name() == 'internal' +if pycairo_dep.found() and pycairo_dep.type_name() == 'internal' python_paths += [join_paths(meson.build_root(), 'subprojects', 'pycairo')] endif envdata.append('PYTHONPATH', python_paths) diff --git a/tests/runtests.py b/tests/runtests.py index c05702a..721b5d8 100755 --- a/tests/runtests.py +++ b/tests/runtests.py @@ -1,8 +1,6 @@ #!/usr/bin/env python # -*- Mode: Python -*- -from __future__ import absolute_import - import os import sys diff --git a/tests/test_atoms.py b/tests/test_atoms.py index 26d5c43..a74db38 100644 --- a/tests/test_atoms.py +++ b/tests/test_atoms.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import os import unittest diff --git a/tests/test_cairo.py b/tests/test_cairo.py index 37a6ac3..d73037e 100644 --- a/tests/test_cairo.py +++ b/tests/test_cairo.py @@ -1,9 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- -# coding=utf-8 # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import unittest import pytest diff --git a/tests/test_docstring.py b/tests/test_docstring.py index adee174..29b7e5e 100644 --- a/tests/test_docstring.py +++ b/tests/test_docstring.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import unittest import gi.docstring diff --git a/tests/test_error.py b/tests/test_error.py index a15c7d3..6bcad38 100644 --- a/tests/test_error.py +++ b/tests/test_error.py @@ -22,8 +22,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - import unittest import pickle diff --git a/tests/test_everything.py b/tests/test_everything.py index 68e8765..ba1b062 100644 --- a/tests/test_everything.py +++ b/tests/test_everything.py @@ -1,9 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- -# coding=utf-8 # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import unittest import traceback import ctypes @@ -21,7 +18,6 @@ from gi.repository import Regress as Everything from gi.repository import GObject from gi.repository import GLib from gi.repository import Gio -from gi._compat import PY3, PY2 try: from gi.repository import Gtk @@ -32,9 +28,7 @@ except: from .helper import capture_exceptions -const_str = b'const \xe2\x99\xa5 utf8' -if PY3: - const_str = const_str.decode('UTF-8') +const_str = b'const \xe2\x99\xa5 utf8'.decode('UTF-8') noconst_str = 'non' + const_str @@ -366,11 +360,7 @@ class TestEverything(unittest.TestCase): def test_unichar(self): self.assertEqual("c", Everything.test_unichar("c")) - if PY2: - self.assertEqual(b"\xe2\x99\xa5", Everything.test_unichar(u"♥")) - self.assertEqual(b"\xe2\x99\xa5", Everything.test_unichar(b"\xe2\x99\xa5")) - else: - self.assertEqual(u"♥", Everything.test_unichar(u"♥")) + self.assertEqual(u"♥", Everything.test_unichar(u"♥")) self.assertRaises(TypeError, Everything.test_unichar, "") self.assertRaises(TypeError, Everything.test_unichar, "morethanonechar") @@ -444,7 +434,7 @@ class TestEverything(unittest.TestCase): self.assertEqual(Everything.test_utf8_inout(const_str), noconst_str) def test_filename_return(self): - if PY3 and os.name != "nt": + if os.name != "nt": result = [os.fsdecode(b'\xc3\xa5\xc3\xa4\xc3\xb6'), '/etc/fstab'] else: result = ['åäö', '/etc/fstab'] @@ -596,8 +586,7 @@ class TestEverything(unittest.TestCase): self.assertEqual(Everything.test_array_int_inout([]), []) def test_array_gint8_in(self): - if PY3: - self.assertEqual(Everything.test_array_gint8_in(b'\x01\x03\x05'), 9) + self.assertEqual(Everything.test_array_gint8_in(b'\x01\x03\x05'), 9) self.assertEqual(Everything.test_array_gint8_in([1, 3, 5, -50]), -41) def test_array_gint16_in(self): diff --git a/tests/test_fields.py b/tests/test_fields.py index 0181d28..b9a06e2 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,7 +1,4 @@ # -*- Mode: Python; py-indent-offset: 4 -*- -# coding=utf-8 - -from __future__ import absolute_import import math import unittest diff --git a/tests/test_gdbus.py b/tests/test_gdbus.py index 6e38abe..6c9afb0 100644 --- a/tests/test_gdbus.py +++ b/tests/test_gdbus.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import unittest from gi.repository import GLib diff --git a/tests/test_generictreemodel.py b/tests/test_generictreemodel.py index acb6028..ab31579 100644 --- a/tests/test_generictreemodel.py +++ b/tests/test_generictreemodel.py @@ -17,8 +17,6 @@ # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see . -from __future__ import absolute_import - # system import gc import sys diff --git a/tests/test_gi.py b/tests/test_gi.py index 61ad4f1..2cabe02 100644 --- a/tests/test_gi.py +++ b/tests/test_gi.py @@ -1,9 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- -# coding=utf-8 # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import sys import unittest @@ -22,7 +19,6 @@ from gi import PyGIWarning from gi import PyGIDeprecationWarning from gi.repository import GObject, GLib, Gio from gi.repository import GIMarshallingTests -from gi._compat import PY2, PY3 import pytest from .helper import capture_exceptions, capture_output @@ -681,21 +677,14 @@ class TestUtf8(unittest.TestCase): def test_extra_utf8_full_return_invalid(self): with pytest.raises(UnicodeDecodeError): - value = GIMarshallingTests.extra_utf8_full_return_invalid() - if PY2: - value.decode("utf-8") + GIMarshallingTests.extra_utf8_full_return_invalid() def test_extra_utf8_full_out_invalid(self): with pytest.raises(UnicodeDecodeError): - value = GIMarshallingTests.extra_utf8_full_out_invalid() - if PY2: - value.decode("utf-8") + GIMarshallingTests.extra_utf8_full_out_invalid() def test_utf8_none_in(self): GIMarshallingTests.utf8_none_in(CONSTANT_UTF8) - if PY2: - GIMarshallingTests.utf8_none_in(CONSTANT_UTF8.decode("utf-8")) - self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, 42) self.assertRaises(TypeError, GIMarshallingTests.utf8_none_in, None) @@ -784,22 +773,6 @@ class TestFilename(unittest.TestCase): (ValueError, TypeError), GIMarshallingTests.filename_copy, u"foo\x00") - def test_as_is_py2(self): - if not PY2: - return - - values = [ - b"foo", - b"\xff\xff", - b"\xc3\xb6\xc3\xa4\xc3\xbc", - b"\xed\xa0\xbd", - b"\xf0\x90\x80\x81", - ] - - for v in values: - self.assertEqual(GIMarshallingTests.filename_copy(v), v) - self.assertEqual(GIMarshallingTests.filename_to_glib_repr(v), v) - def test_win32_surrogates(self): if os.name != "nt": return @@ -807,15 +780,10 @@ class TestFilename(unittest.TestCase): copy = GIMarshallingTests.filename_copy glib_repr = GIMarshallingTests.filename_to_glib_repr - if PY3: - self.assertEqual(copy(u"\ud83d"), u"\ud83d") - self.assertEqual(copy(u"\x61\uDC00"), u"\x61\uDC00") - self.assertEqual(copy(u"\uD800\uDC01"), u"\U00010001") - self.assertEqual(copy(u"\uD83D\x20\uDCA9"), u"\uD83D\x20\uDCA9") - else: - self.assertEqual(copy(u"\ud83d"), u"\ud83d".encode("utf-8")) - self.assertEqual(copy(u"\uD800\uDC01").decode("utf-8"), - u"\U00010001") + self.assertEqual(copy(u"\ud83d"), u"\ud83d") + self.assertEqual(copy(u"\x61\uDC00"), u"\x61\uDC00") + self.assertEqual(copy(u"\uD800\uDC01"), u"\U00010001") + self.assertEqual(copy(u"\uD83D\x20\uDCA9"), u"\uD83D\x20\uDCA9") self.assertEqual(glib_repr(u"\ud83d"), b"\xed\xa0\xbd") self.assertEqual(glib_repr(u"\uD800\uDC01"), b"\xf0\x90\x80\x81") @@ -830,7 +798,7 @@ class TestFilename(unittest.TestCase): self.assertEqual(glib_repr(u"\uDC00"), b"\xED\xB0\x80") def test_win32_bytes_py3(self): - if not (os.name == "nt" and PY3): + if not (os.name == "nt"): return values = [ @@ -855,39 +823,27 @@ class TestFilename(unittest.TestCase): copy = GIMarshallingTests.filename_copy glib_repr = GIMarshallingTests.filename_to_glib_repr - if PY3: - try: - os.fsdecode(b"\xff\xfe") - except UnicodeDecodeError: - self.assertRaises(UnicodeDecodeError, copy, b"\xff\xfe") - else: - str_path = copy(b"\xff\xfe") - self.assertTrue(isinstance(str_path, str)) - self.assertEqual(str_path, os.fsdecode(b"\xff\xfe")) - self.assertEqual(copy(str_path), str_path) - self.assertEqual(glib_repr(b"\xff\xfe"), b"\xff\xfe") - self.assertEqual(glib_repr(str_path), b"\xff\xfe") - - # if getfilesystemencoding is ASCII, then we should fail like - # os.fsencode - try: - byte_path = os.fsencode(u"ä") - except UnicodeEncodeError: - self.assertRaises(UnicodeEncodeError, copy, u"ä") - else: - self.assertEqual(copy(u"ä"), u"ä") - self.assertEqual(glib_repr(u"ä"), byte_path) + try: + os.fsdecode(b"\xff\xfe") + except UnicodeDecodeError: + self.assertRaises(UnicodeDecodeError, copy, b"\xff\xfe") else: - self.assertTrue(isinstance(copy(b"\xff\xfe"), bytes)) - self.assertEqual(copy(u"foo"), b"foo") - self.assertTrue(isinstance(copy(u"foo"), bytes)) - try: - byte_path = u"ä".encode(sys.getfilesystemencoding()) - except UnicodeEncodeError: - self.assertRaises(UnicodeEncodeError, copy, u"ä") - else: - self.assertEqual(copy(u"ä"), byte_path) - self.assertEqual(glib_repr(u"ä"), byte_path) + str_path = copy(b"\xff\xfe") + self.assertTrue(isinstance(str_path, str)) + self.assertEqual(str_path, os.fsdecode(b"\xff\xfe")) + self.assertEqual(copy(str_path), str_path) + self.assertEqual(glib_repr(b"\xff\xfe"), b"\xff\xfe") + self.assertEqual(glib_repr(str_path), b"\xff\xfe") + + # if getfilesystemencoding is ASCII, then we should fail like + # os.fsencode + try: + byte_path = os.fsencode(u"ä") + except UnicodeEncodeError: + self.assertRaises(UnicodeEncodeError, copy, u"ä") + else: + self.assertEqual(copy(u"ä"), u"ä") + self.assertEqual(glib_repr(u"ä"), byte_path) @unittest.skip("glib can't handle non-unicode paths") def test_win32_surrogates_exists(self): @@ -902,15 +858,15 @@ class TestFilename(unittest.TestCase): def test_path_exists_various_types(self): wd = self.workdir - wdb = os.fsencode(wd) if PY3 else wd + wdb = os.fsencode(wd) paths = [(wdb, b"foo-1"), (wd, u"foo-2"), (wd, u"öäü-3")] - if PY3: - try: - paths.append((wd, os.fsdecode(b"\xff\xfe-4"))) - except UnicodeDecodeError: - # depends on the code page - pass + + try: + paths.append((wd, os.fsdecode(b"\xff\xfe-4"))) + except UnicodeDecodeError: + # depends on the code page + pass if os.name != "nt": paths.append((wdb, b"\xff\xfe-5")) @@ -961,10 +917,7 @@ class TestArray(unittest.TestCase): @unittest.skipUnless( hasattr(GIMarshallingTests, "array_unichar_out"), "too old gi") def test_array_unichar_out(self): - if PY2: - result = [c.encode("utf-8") for c in list(CONSTANT_UCS4)] - else: - result = list(CONSTANT_UCS4) + result = list(CONSTANT_UCS4) assert GIMarshallingTests.array_unichar_out() == result @unittest.skip("broken") @@ -1627,10 +1580,7 @@ class TestGValue(unittest.TestCase): GLib.MAXINT + 1, GLib.MININT, GLib.MAXINT)): GIMarshallingTests.gvalue_flat_array([GLib.MAXINT + 1, "42", True]) - if PY2: - min_, max_ = GLib.MINLONG, GLib.MAXLONG - else: - min_, max_ = GLib.MININT, GLib.MAXINT + min_, max_ = GLib.MININT, GLib.MAXINT with pytest.raises( OverflowError, @@ -1651,7 +1601,7 @@ class TestGValue(unittest.TestCase): gc.collect() assert obj.__grefcount__ == grefcount - @unittest.skipIf(platform.python_implementation() == "PyPy" and PY3, "fixme") + @unittest.skipIf(platform.python_implementation() == "PyPy", "fixme") def test_gvalue_gobject_ref_counts(self): # Tests a GObject held by a GValue obj = GObject.Object() @@ -2908,10 +2858,7 @@ class TestMRO(unittest.TestCase): # style mixin. type('GIWithOldStyleMixin', (GIMarshallingTests.Object, Mixin), {}) - if PY2: - self.assertTrue(issubclass(warn[0].category, RuntimeWarning)) - else: - self.assertEqual(len(warn), 0) + self.assertEqual(len(warn), 0) class TestInterfaceClash(unittest.TestCase): diff --git a/tests/test_gio.py b/tests/test_gio.py index f3111ea..3b812c4 100644 --- a/tests/test_gio.py +++ b/tests/test_gio.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import os import unittest import warnings diff --git a/tests/test_glib.py b/tests/test_glib.py index 70be98e..0a5cb3d 100644 --- a/tests/test_glib.py +++ b/tests/test_glib.py @@ -1,7 +1,4 @@ # -*- Mode: Python -*- -# encoding: UTF-8 - -from __future__ import absolute_import import os import sys @@ -13,7 +10,6 @@ import subprocess import pytest from gi.repository import GLib from gi import PyGIDeprecationWarning -from gi._compat import PY3 class TestGLib(unittest.TestCase): @@ -83,12 +79,8 @@ class TestGLib(unittest.TestCase): if isinstance(f, bytes): return f if os.name == "nt": - if PY3: - return f.encode("utf-8", "surrogatepass") - else: - return f.encode("utf-8") + return f.encode("utf-8", "surrogatepass") else: - assert PY3 return os.fsencode(f) # this is locale dependent, so we cannot completely verify the result diff --git a/tests/test_gobject.py b/tests/test_gobject.py index bba12cb..77d788a 100644 --- a/tests/test_gobject.py +++ b/tests/test_gobject.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import sys import gc import unittest @@ -804,8 +802,8 @@ class TestGValue(unittest.TestCase): def test_list_properties(): - def find_param(l, name): - for param in l: + def find_param(props, name): + for param in props: if param.name == name: return param return @@ -822,8 +820,8 @@ def test_list_properties(): props = list_props(Gio.SimpleAction) assert find_param(props, "enabled") - def names(l): - return [p.name for p in l] + def names(props): + return [p.name for p in props] assert (set(names(list_props(Gio.Action))) <= set(names(list_props(Gio.SimpleAction)))) diff --git a/tests/test_gtk_template.py b/tests/test_gtk_template.py index db3c8d9..31593f1 100644 --- a/tests/test_gtk_template.py +++ b/tests/test_gtk_template.py @@ -1,7 +1,3 @@ -# coding: UTF-8 - -from __future__ import absolute_import - import tempfile import os import pytest @@ -599,13 +595,14 @@ def test_template_hierarchy(): """ + @Gtk.Template(string=testlabel) class TestLabel(Gtk.Label): __gtype_name__ = "TestLabel" def __init__(self): - super(TestLabel, self).__init__() + super().__init__() self.props.label = "TestLabel" testbox = """ @@ -617,6 +614,7 @@ def test_template_hierarchy(): """ + @Gtk.Template(string=testbox) class TestBox(Gtk.Box): @@ -625,7 +623,7 @@ def test_template_hierarchy(): _testlabel = Gtk.Template.Child() def __init__(self): - super(TestBox, self).__init__() + super().__init__() assert isinstance(self._testlabel, TestLabel) @@ -643,6 +641,7 @@ def test_template_hierarchy(): """ + @Gtk.Template(string=window) class MyWindow(Gtk.Window): @@ -652,7 +651,7 @@ def test_template_hierarchy(): _testlabel = Gtk.Template.Child() def __init__(self): - super(MyWindow, self).__init__() + super().__init__() assert isinstance(self._testbox, TestBox) assert isinstance(self._testlabel, TestLabel) @@ -672,6 +671,7 @@ def test_multiple_init_template_calls(): """ + @Gtk.Template(string=xml) class MyBox(Gtk.Box): @@ -680,7 +680,7 @@ def test_multiple_init_template_calls(): _label = Gtk.Template.Child() def __init__(self): - super(MyBox, self).__init__() + super().__init__() self._label.props.label = "awesome label" my_box = MyBox() diff --git a/tests/test_gtype.py b/tests/test_gtype.py index b9d3349..1d24f9f 100644 --- a/tests/test_gtype.py +++ b/tests/test_gtype.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import unittest from gi.repository import GObject diff --git a/tests/test_import_machinery.py b/tests/test_import_machinery.py index fc1ba7b..a8d5005 100644 --- a/tests/test_import_machinery.py +++ b/tests/test_import_machinery.py @@ -1,15 +1,12 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import sys import unittest import gi.overrides import gi.module import gi.importer -from gi._compat import PY2, PY3 from gi.repository import Regress @@ -122,10 +119,7 @@ class TestImporter(unittest.TestCase): exception_string = str(context.exception) self.assertTrue('InvalidGObjectRepositoryModuleName' in exception_string) - - # The message of the custom exception in gi/importer.py is eaten in Python <3.3 - if sys.version_info >= (3, 3): - self.assertTrue('introspection typelib' in exception_string) + self.assertTrue('introspection typelib' in exception_string) def test_require_version_warning(self): check = gi.importer._check_require_version @@ -146,13 +140,8 @@ class TestImporter(unittest.TestCase): with self.assertRaises(ValueError): gi.require_version('GLib', 2.0) - # Test that unicode strings work in python 2 - if PY2: - gi.require_version('GLib', u'2.0') - - if PY3: - with self.assertRaises(ValueError): - gi.require_version('GLib', b'2.0') + with self.assertRaises(ValueError): + gi.require_version('GLib', b'2.0') def test_require_versions(self): import gi diff --git a/tests/test_interface.py b/tests/test_interface.py index ca1e0f4..ba20cb4 100644 --- a/tests/test_interface.py +++ b/tests/test_interface.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import unittest from gi.repository import GObject diff --git a/tests/test_internal_api.py b/tests/test_internal_api.py index 1ed822c..5136037 100644 --- a/tests/test_internal_api.py +++ b/tests/test_internal_api.py @@ -1,13 +1,9 @@ -# -*- coding: utf-8 -*- # -*- Mode: Python -*- -from __future__ import absolute_import - import unittest import pytest from gi.repository import GLib, GObject -from gi._compat import PY3 import testhelper @@ -103,13 +99,8 @@ def test_to_unichar_conv(): assert testhelper.test_to_unichar_conv(u"A") == 65 assert testhelper.test_to_unichar_conv(u"Ä") == 196 - if PY3: - with pytest.raises(TypeError): - assert testhelper.test_to_unichar_conv(b"\x65") - else: - assert testhelper.test_to_unichar_conv(b"\x65") == 0x65 - with pytest.raises(ValueError): - assert testhelper.test_to_unichar_conv(b"\xff") + with pytest.raises(TypeError): + assert testhelper.test_to_unichar_conv(b"\x65") with pytest.raises(TypeError): testhelper.test_to_unichar_conv(object()) diff --git a/tests/test_iochannel.py b/tests/test_iochannel.py index 56a0aea..c4c6e3d 100644 --- a/tests/test_iochannel.py +++ b/tests/test_iochannel.py @@ -1,7 +1,4 @@ # -*- Mode: Python -*- -# encoding: UTF-8 - -from __future__ import absolute_import import os import unittest diff --git a/tests/test_mainloop.py b/tests/test_mainloop.py index 40a8b97..48399d1 100644 --- a/tests/test_mainloop.py +++ b/tests/test_mainloop.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import os import select import signal diff --git a/tests/test_object_marshaling.py b/tests/test_object_marshaling.py index 3d8ebb8..d52ff54 100644 --- a/tests/test_object_marshaling.py +++ b/tests/test_object_marshaling.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import unittest import weakref import gc diff --git a/tests/test_option.py b/tests/test_option.py index 251eb3a..1dc496a 100644 --- a/tests/test_option.py +++ b/tests/test_option.py @@ -1,16 +1,7 @@ #!/usr/bin/env python -from __future__ import absolute_import - import unittest -# py3k has StringIO in a different module -try: - from StringIO import StringIO - StringIO # pyflakes -except ImportError: - from io import StringIO - from gi.repository import GLib from .helper import capture_exceptions diff --git a/tests/test_ossig.py b/tests/test_ossig.py index b59f2f5..2d03f65 100644 --- a/tests/test_ossig.py +++ b/tests/test_ossig.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # Copyright 2017 Christoph Reiter # # This library is free software; you can redistribute it and/or @@ -24,8 +23,10 @@ from contextlib import contextmanager try: from gi.repository import Gtk + Gtk_version = Gtk._version except ImportError: Gtk = None + Gtk_version = None from gi.repository import Gio, GLib from gi._ossighelper import wakeup_on_signal, register_sigint_fallback @@ -90,6 +91,7 @@ class TestOverridesWakeupOnAlarm(unittest.TestCase): app.run() @unittest.skipIf(Gtk is None or os.name == "nt", "not on Windows") + @unittest.skipIf(Gtk is None or Gtk_version == "4.0", "not in gtk4") def test_gtk_main(self): signal.signal(signal.SIGALRM, lambda *args: Gtk.main_quit()) GLib.idle_add(signal.setitimer, signal.ITIMER_REAL, 0.001) diff --git a/tests/test_overrides_gdk.py b/tests/test_overrides_gdk.py index 0ea9187..1788ef6 100644 --- a/tests/test_overrides_gdk.py +++ b/tests/test_overrides_gdk.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import re import os import sys @@ -125,6 +123,11 @@ class TestGdk(unittest.TestCase): event.type = Gdk.EventType.SCROLL self.assertRaises(AttributeError, lambda: getattr(event, 'foo_bar')) + @unittest.skipIf(GDK4, "not in gdk4") + def test_scroll_event(self): + event = Gdk.Event.new(Gdk.EventType.SCROLL) + assert event.direction == Gdk.ScrollDirection.UP + @unittest.skipIf(GDK4, "not in gdk4") def test_event_strip_boolean(self): ev = Gdk.EventButton() @@ -249,14 +252,16 @@ class TestGdk(unittest.TestCase): self.assertEqual(str(Gdk.ModifierType.META_MASK), '') - self.assertEqual(Gdk.ModifierType.RELEASE_MASK | 0, 0x40000000) - self.assertEqual(hex(Gdk.ModifierType.RELEASE_MASK), '0x40000000') - self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK), - '') + # RELEASE_MASK does not exist in gdk4 + if not GDK4: + self.assertEqual(Gdk.ModifierType.RELEASE_MASK | 0, 0x40000000) + self.assertEqual(hex(Gdk.ModifierType.RELEASE_MASK), '0x40000000') + self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK), + '') - self.assertEqual(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK, 0x50000000) - self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK), - '') + self.assertEqual(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK, 0x50000000) + self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK), + '') @unittest.skipIf(GDK4, "not in gdk4") def test_color_parse(self): diff --git a/tests/test_overrides_gdkpixbuf.py b/tests/test_overrides_gdkpixbuf.py index 5b2d370..4edd9bf 100644 --- a/tests/test_overrides_gdkpixbuf.py +++ b/tests/test_overrides_gdkpixbuf.py @@ -15,8 +15,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - import pytest from gi import PyGIDeprecationWarning diff --git a/tests/test_overrides_gio.py b/tests/test_overrides_gio.py index 8612d51..de0e235 100644 --- a/tests/test_overrides_gio.py +++ b/tests/test_overrides_gio.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - import random import platform import warnings @@ -8,7 +6,6 @@ import pytest from gi.repository import Gio, GObject from gi import PyGIWarning -from gi._compat import cmp class Item(GObject.Object): @@ -42,6 +39,7 @@ def test_list_store_sort(): assert list(args) == user_data assert isinstance(a, NamedItem) assert isinstance(b, NamedItem) + cmp = lambda a, b: (a > b) - (a < b) return cmp(a.props.name, b.props.name) store[:] = items @@ -61,6 +59,7 @@ def test_list_store_insert_sorted(): assert list(args) == user_data assert isinstance(a, NamedItem) assert isinstance(b, NamedItem) + cmp = lambda a, b: (a > b) - (a < b) return cmp(a.props.name, b.props.name) for item in items: diff --git a/tests/test_overrides_glib.py b/tests/test_overrides_glib.py index ac19ccd..d8f1a6c 100644 --- a/tests/test_overrides_glib.py +++ b/tests/test_overrides_glib.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import os import gc import unittest @@ -13,7 +11,6 @@ import pytest import gi from gi.repository import GLib -from gi._compat import long_, integer_types from .helper import capture_gi_deprecation_warnings @@ -183,7 +180,7 @@ class TestGVariant(unittest.TestCase): # nested tuples variant = GLib.Variant('((si)(ub))', (('hello', -1), (42, True))) self.assertEqual(variant.get_type_string(), '((si)(ub))') - self.assertEqual(variant.unpack(), (('hello', -1), (long_(42), True))) + self.assertEqual(variant.unpack(), (('hello', -1), (42, True))) def test_new_tuple_sink(self): # https://bugzilla.gnome.org/show_bug.cgi?id=735166 @@ -724,4 +721,4 @@ class TestConstants(unittest.TestCase): def test_basic_types_limits(self): self.assertTrue(isinstance(GLib.MINFLOAT, float)) - self.assertTrue(isinstance(GLib.MAXLONG, integer_types)) + self.assertTrue(isinstance(GLib.MAXLONG, int)) diff --git a/tests/test_overrides_gobject.py b/tests/test_overrides_gobject.py index 7f20e81..dc26596 100644 --- a/tests/test_overrides_gobject.py +++ b/tests/test_overrides_gobject.py @@ -1,13 +1,8 @@ -# -*- coding: utf-8 -*- - -from __future__ import absolute_import - import pytest from gi import PyGIDeprecationWarning from gi.repository import GObject, GLib, GIMarshallingTests -from gi._compat import PY2 from .helper import ignore_gi_deprecation_warnings @@ -285,15 +280,8 @@ def test_value_string(): assert getter() is None - if PY2: + with pytest.raises(TypeError): setter(b"bar") - assert getter() == b"bar" - - setter(u"öäü") - assert getter().decode("utf-8") == u"öäü" - else: - with pytest.raises(TypeError): - setter(b"bar") setter(u"quux") assert getter() == u"quux" diff --git a/tests/test_overrides_gtk.py b/tests/test_overrides_gtk.py index 88b3f88..ff3acba 100644 --- a/tests/test_overrides_gtk.py +++ b/tests/test_overrides_gtk.py @@ -1,9 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- -# coding: UTF-8 # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import contextlib import unittest import sys @@ -17,7 +14,6 @@ from .helper import ignore_gi_deprecation_warnings, capture_glib_warnings import gi.overrides import gi.types -from gi._compat import cmp from gi.repository import GLib, GObject try: @@ -65,8 +61,14 @@ def realized(widget): window.add(widget) widget.realize() - while Gtk.events_pending(): - Gtk.main_iteration() + if Gtk._version == "4.0": + context = GLib.MainContext() + while context.pending(): + context.iteration(False) + else: + while Gtk.events_pending(): + Gtk.main_iteration() + assert widget.get_realized() yield widget @@ -74,8 +76,13 @@ def realized(widget): window.remove(widget) window.destroy() - while Gtk.events_pending(): - Gtk.main_iteration() + if Gtk._version == "4.0": + context = GLib.MainContext() + while context.pending(): + context.iteration(False) + else: + while Gtk.events_pending(): + Gtk.main_iteration() @unittest.skipUnless(Gtk, 'Gtk not available') @@ -306,7 +313,8 @@ class TestGtk(unittest.TestCase): mi = ui.get_widget("/menubær1") self.assertEqual(type(mi), Gtk.MenuBar) - def test_window(self): + @unittest.skipIf(Gtk_version == "4.0", "not in gtk4") + def test_window_gtk3(self): # standard Window w = Gtk.Window() self.assertEqual(w.get_property('type'), Gtk.WindowType.TOPLEVEL) @@ -338,6 +346,33 @@ class TestGtk(unittest.TestCase): self.assertEqual(builder.get_object('testpop').get_property('type'), Gtk.WindowType.POPUP) + @unittest.skipUnless(Gtk_version == "4.0", "no GtkWindowType in gtk4") + def test_window_gtk4(self): + w = Gtk.Window() + + # check that setting default size works + w.set_default_size(300, 300) + self.assertEqual(w.get_default_size(), (300, 300)) + + class TestWindow(Gtk.Window): + __gtype_name__ = "TestWindow" + + # works from builder + builder = Gtk.Builder() + builder.add_from_string(''' + + + amazing + + + amazing-test + +''') + self.assertEqual(builder.get_object("win").get_property("css-name"), + "amazing") + self.assertEqual(builder.get_object("testwin").get_property("css-name"), + "amazing-test") + def test_dialog_classes(self): self.assertEqual(Gtk.Dialog, gi.overrides.Gtk.Dialog) self.assertEqual(Gtk.FileChooserDialog, gi.overrides.Gtk.FileChooserDialog) @@ -655,6 +690,7 @@ class TestGtk(unittest.TestCase): sb = sw.get_vscrollbar() self.assertEqual(sw.get_vadjustment(), sb.get_adjustment()) + @unittest.skipIf(Gtk_version == "4.0", "not in gtk4") def test_widget_drag_methods(self): widget = Gtk.Button() @@ -672,10 +708,8 @@ class TestGtk(unittest.TestCase): widget.drag_dest_set_track_motion(True) widget.drag_dest_get_target_list() widget.drag_dest_set_target_list(None) - if GTK4: - widget.drag_dest_set_target_list(Gdk.ContentFormats.new([])) - else: - widget.drag_dest_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) + + widget.drag_dest_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) widget.drag_dest_unset() widget.drag_highlight() @@ -687,23 +721,39 @@ class TestGtk(unittest.TestCase): widget.drag_source_add_text_targets() widget.drag_source_add_uri_targets() widget.drag_source_set_icon_name("_About") - if not GTK4: - widget.drag_source_set_icon_pixbuf(GdkPixbuf.Pixbuf()) - widget.drag_source_set_icon_stock(Gtk.STOCK_ABOUT) + widget.drag_source_set_icon_pixbuf(GdkPixbuf.Pixbuf()) + widget.drag_source_set_icon_stock(Gtk.STOCK_ABOUT) widget.drag_source_get_target_list() widget.drag_source_set_target_list(None) - if GTK4: - widget.drag_source_set_target_list(Gdk.ContentFormats.new([])) - else: - widget.drag_source_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) + widget.drag_source_set_target_list(Gtk.TargetList.new([Gtk.TargetEntry.new('test', 0, 0)])) widget.drag_source_unset() # these methods cannot be called because they require a valid drag on # a real GdkWindow. So we only check that they exist and are callable. - if not GTK4: - self.assertTrue(hasattr(widget, 'drag_dest_set_proxy')) + self.assertTrue(hasattr(widget, 'drag_dest_set_proxy')) self.assertTrue(hasattr(widget, 'drag_get_data')) + @unittest.skipIf(Gtk_version != "4.0", "gtk4 only") + def test_widget_drag_methods_gtk4(self): + widget = Gtk.Button() + widget.drag_check_threshold(0, 0, 0, 0) + + # drag source + drag_source = Gtk.DragSource() + content = Gdk.ContentProvider.new_for_value("data") + drag_source.set_content(content) + drag_source.set_actions(Gdk.DragAction.COPY) + image = Gtk.Image.new_from_icon_name("dialog-warning") + drag_source.set_icon(image.get_paintable(), 0, 0) + widget.add_controller(drag_source) + + # drop target + drop_target = Gtk.DropTarget.new(Gdk.ContentFormats.new([]), Gdk.DragAction.COPY) + widget.add_controller(drop_target) + + widget.remove_controller(drag_source) + widget.remove_controller(drop_target) + @unittest.skipIf(sys.platform == "darwin", "crashes") @unittest.skipIf(GTK4, "uses lots of gtk3 only api") def test_drag_target_list_gtk3(self): @@ -778,12 +828,6 @@ class TestGtk(unittest.TestCase): self.assertEqual(button.props.label, 'mylabel') self.assertEqual(button.props.icon_widget, icon) - def test_toolbutton_gtk4(self): - icon = Gtk.Image.new() - button = Gtk.ToolButton(label='mylabel', icon_widget=icon) - self.assertEqual(button.props.label, 'mylabel') - self.assertEqual(button.props.icon_widget, icon) - @unittest.skipIf(Gtk_version == "4.0", "not in gtk4") def test_iconset(self): Gtk.IconSet() @@ -812,6 +856,7 @@ class TestGtk(unittest.TestCase): self.assertEqual(stock_item.stock_id, 'gtk-ok') self.assertEqual(Gtk.stock_lookup('nosuchthing'), None) + @unittest.skipIf(Gtk_version == "4.0", "not in gtk4") def test_gtk_main(self): # with no arguments GLib.idle_add(Gtk.main_quit) @@ -2337,6 +2382,7 @@ class TestTreeModel(unittest.TestCase): def sort_func(store, iter1, iter2, data): assert data is None + cmp = lambda a, b: (a > b) - (a < b) return cmp(store[iter1][0], store[iter2][0]) list_store.set_default_sort_func(sort_func) @@ -2417,8 +2463,13 @@ class TestTreeView(unittest.TestCase): with realized(tree): tree.set_cursor(model[0].path) - while Gtk.events_pending(): - Gtk.main_iteration() + if Gtk._version == "4.0": + context = GLib.MainContext() + while context.pending(): + context.iteration(False) + else: + while Gtk.events_pending(): + Gtk.main_iteration() self.assertEqual(tree.get_column(0).get_title(), 'Head1') self.assertEqual(tree.get_column(1).get_title(), 'Head2') @@ -2742,3 +2793,11 @@ class TestContainer(unittest.TestCase): self.assertEqual(expand, False) self.assertEqual(fill, False) self.assertEqual(padding, 21) + + +def test_button_focus_on_click(): + b = Gtk.Button() + b.set_focus_on_click(True) + assert b.get_focus_on_click() + b.set_focus_on_click(False) + assert not b.get_focus_on_click() diff --git a/tests/test_overrides_pango.py b/tests/test_overrides_pango.py index a08880b..2ec4cb1 100644 --- a/tests/test_overrides_pango.py +++ b/tests/test_overrides_pango.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import unittest try: diff --git a/tests/test_properties.py b/tests/test_properties.py index 35b03b7..ec5df0c 100644 --- a/tests/test_properties.py +++ b/tests/test_properties.py @@ -1,7 +1,3 @@ -# coding=utf-8 - -from __future__ import absolute_import - import os import gc import sys @@ -31,7 +27,6 @@ from gi.repository import GIMarshallingTests from gi.repository import Regress from gi import _propertyhelper as propertyhelper -from gi._compat import long_, PY3, PY2 from .helper import capture_glib_warnings @@ -182,10 +177,7 @@ class TestPropertyObject(unittest.TestCase): def test_utf8_lone_surrogate(self): obj = PropertyObject() - if PY3: - with pytest.raises(TypeError): - obj.set_property('construct', '\ud83d') - else: + with pytest.raises(TypeError): obj.set_property('construct', '\ud83d') def test_int_to_str(self): @@ -207,12 +199,12 @@ class TestPropertyObject(unittest.TestCase): def test_uint64(self): obj = new(PropertyObject) self.assertEqual(obj.props.uint64, 0) - obj.props.uint64 = long_(1) - self.assertEqual(obj.props.uint64, long_(1)) obj.props.uint64 = 1 - self.assertEqual(obj.props.uint64, long_(1)) + self.assertEqual(obj.props.uint64, 1) + obj.props.uint64 = 1 + self.assertEqual(obj.props.uint64, 1) - self.assertRaises((TypeError, OverflowError), obj.set_property, "uint64", long_(-1)) + self.assertRaises((TypeError, OverflowError), obj.set_property, "uint64", -1) self.assertRaises((TypeError, OverflowError), obj.set_property, "uint64", -1) def test_uint64_default_value(self): @@ -220,7 +212,7 @@ class TestPropertyObject(unittest.TestCase): class TimeControl(GObject.GObject): __gproperties__ = { 'time': (TYPE_UINT64, 'Time', 'Time', - long_(0), (1 << 64) - 1, long_(0), + 0, (1 << 64) - 1, 0, ParamFlags.READABLE) } except OverflowError: @@ -512,9 +504,9 @@ class TestProperty(unittest.TestCase): def test_simple(self): class C(GObject.GObject): str = GObject.Property(type=str) - int = GObject.Property(type=int) float = GObject.Property(type=float) - long = GObject.Property(type=long_) + long = GObject.Property(type=int) + int = GObject.Property(type=int) self.assertTrue(hasattr(C.props, 'str')) self.assertTrue(hasattr(C.props, 'int')) @@ -534,9 +526,9 @@ class TestProperty(unittest.TestCase): o.float = 3.14 self.assertEqual(o.float, 3.14) - self.assertEqual(o.long, long_(0)) - o.long = long_(100) - self.assertEqual(o.long, long_(100)) + self.assertEqual(o.long, 0) + o.long = 100 + self.assertEqual(o.long, 100) def test_custom_getter(self): class C(GObject.GObject): @@ -871,8 +863,6 @@ class TestProperty(unittest.TestCase): def test_python_to_glib_type_mapping(self): tester = GObject.Property() self.assertEqual(tester._type_from_python(int), GObject.TYPE_INT) - if PY2: - self.assertEqual(tester._type_from_python(long_), GObject.TYPE_LONG) self.assertEqual(tester._type_from_python(bool), GObject.TYPE_BOOLEAN) self.assertEqual(tester._type_from_python(float), GObject.TYPE_DOUBLE) self.assertEqual(tester._type_from_python(str), GObject.TYPE_STRING) diff --git a/tests/test_pycapi.py b/tests/test_pycapi.py index 969b78e..d049a8d 100644 --- a/tests/test_pycapi.py +++ b/tests/test_pycapi.py @@ -1,6 +1,3 @@ -from __future__ import absolute_import - -import sys import unittest import ctypes from ctypes import c_void_p, py_object, c_char_p @@ -23,16 +20,10 @@ def get_capi(): ] api_obj = gi._gobject._PyGObject_API - if sys.version_info[0] == 2: - func_type = ctypes.PYFUNCTYPE(c_void_p, py_object) - PyCObject_AsVoidPtr = func_type( - ('PyCObject_AsVoidPtr', ctypes.pythonapi)) - ptr = PyCObject_AsVoidPtr(api_obj) - else: - func_type = ctypes.PYFUNCTYPE(c_void_p, py_object, c_char_p) - PyCapsule_GetPointer = func_type( - ('PyCapsule_GetPointer', ctypes.pythonapi)) - ptr = PyCapsule_GetPointer(api_obj, b"gobject._PyGObject_API") + func_type = ctypes.PYFUNCTYPE(c_void_p, py_object, c_char_p) + PyCapsule_GetPointer = func_type( + ('PyCapsule_GetPointer', ctypes.pythonapi)) + ptr = PyCapsule_GetPointer(api_obj, b"gobject._PyGObject_API") ptr = ctypes.cast(ptr, ctypes.POINTER(CAPI)) return ptr.contents diff --git a/tests/test_pygtkcompat.py b/tests/test_pygtkcompat.py index 3e6a69e..c01892a 100644 --- a/tests/test_pygtkcompat.py +++ b/tests/test_pygtkcompat.py @@ -1,8 +1,6 @@ # -*- Mode: Python; py-indent-offset: 4 -*- # vim: tabstop=4 shiftwidth=4 expandtab -from __future__ import absolute_import - import unittest import base64 diff --git a/tests/test_repository.py b/tests/test_repository.py index 2da7f5a..0aa29b6 100644 --- a/tests/test_repository.py +++ b/tests/test_repository.py @@ -20,13 +20,9 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import import unittest -try: - from collections import abc -except ImportError: - import collections as abc +from collections import abc import gi._gi as GIRepository from gi.module import repository as repo diff --git a/tests/test_resulttuple.py b/tests/test_resulttuple.py index 4576495..00daa7b 100644 --- a/tests/test_resulttuple.py +++ b/tests/test_resulttuple.py @@ -18,8 +18,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - import unittest import pickle diff --git a/tests/test_signal.py b/tests/test_signal.py index 68592c5..e327d37 100644 --- a/tests/test_signal.py +++ b/tests/test_signal.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import gc import unittest import sys @@ -12,7 +10,6 @@ import time from gi.repository import GObject, GLib, Regress, Gio from gi import _signalhelper as signalhelper from gi.module import repository as repo -from gi._compat import PY3, long_ import testhelper from .helper import capture_glib_warnings, capture_gi_deprecation_warnings @@ -523,7 +520,7 @@ class CM(GObject.GObject): test2=(GObject.SignalFlags.RUN_LAST, None, (str,)), test3=(GObject.SignalFlags.RUN_LAST, int, (GObject.TYPE_DOUBLE,)), test4=(GObject.SignalFlags.RUN_FIRST, None, - (bool, long_, GObject.TYPE_FLOAT, GObject.TYPE_DOUBLE, int, + (bool, int, GObject.TYPE_FLOAT, GObject.TYPE_DOUBLE, int, GObject.TYPE_UINT, GObject.TYPE_ULONG)), test_float=(GObject.SignalFlags.RUN_LAST, GObject.TYPE_FLOAT, (GObject.TYPE_FLOAT,)), test_double=(GObject.SignalFlags.RUN_LAST, GObject.TYPE_DOUBLE, (GObject.TYPE_DOUBLE,)), @@ -555,7 +552,7 @@ class _TestCMarshaller: self.assertEqual(rv, 20) def test_test4(self): - self.obj.emit("test4", True, long_(10), 3.14, 1.78, 20, long_(30), long_(31)) + self.obj.emit("test4", True, 10, 3.14, 1.78, 20, 30, 31) def test_float(self): rv = self.obj.emit("test-float", 1.234) @@ -1015,28 +1012,16 @@ class TestInstallSignals(unittest.TestCase): self.assertTrue(hasattr(self.Sub2, 'do_sub2test')) -# For this test to work with both python2 and 3 we need to dynamically -# exec the given code due to the new syntax causing an error in python 2. -annotated_class_code = """ -class AnnotatedSignalClass(GObject.GObject): - @GObject.Signal - def sig1(self, a:int, b:float): - pass - - @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) - def sig2_with_return(self, a:int, b:float) -> str: - return "test" -""" - - -@unittest.skipUnless(PY3, 'Argument annotations require Python 3') class TestPython3Signals(unittest.TestCase): - AnnotatedClass = None - def setUp(self): - exec(annotated_class_code, globals(), globals()) - self.assertTrue('AnnotatedSignalClass' in globals()) - self.AnnotatedClass = globals()['AnnotatedSignalClass'] + class AnnotatedClass(GObject.GObject): + @GObject.Signal + def sig1(self, a: int, b: float): + pass + + @GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) + def sig2_with_return(self, a: int, b: float) -> str: + return "test" def test_annotations(self): self.assertEqual(signalhelper.get_signal_annotations(self.AnnotatedClass.sig1.func), diff --git a/tests/test_source.py b/tests/test_source.py index 1a600fd..9249892 100644 --- a/tests/test_source.py +++ b/tests/test_source.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import sys import gc import unittest diff --git a/tests/test_subprocess.py b/tests/test_subprocess.py index bd1056e..274a501 100644 --- a/tests/test_subprocess.py +++ b/tests/test_subprocess.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import sys import os import unittest diff --git a/tests/test_thread.py b/tests/test_thread.py index 45ebd0b..334eff0 100644 --- a/tests/test_thread.py +++ b/tests/test_thread.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import unittest from gi.repository import GLib diff --git a/tests/test_typeclass.py b/tests/test_typeclass.py index b584fdd..1f34a09 100644 --- a/tests/test_typeclass.py +++ b/tests/test_typeclass.py @@ -20,8 +20,6 @@ # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 # USA -from __future__ import absolute_import - import unittest from gi.repository import GObject diff --git a/tests/test_unknown.py b/tests/test_unknown.py index 1ed1fb8..76fa185 100644 --- a/tests/test_unknown.py +++ b/tests/test_unknown.py @@ -1,7 +1,5 @@ # -*- Mode: Python -*- -from __future__ import absolute_import - import unittest from gi.repository import GObject diff --git a/tests/testhelpermodule.c b/tests/testhelpermodule.c index 82b0399..e6f6ffe 100644 --- a/tests/testhelpermodule.c +++ b/tests/testhelpermodule.c @@ -5,7 +5,12 @@ #include "test-unknown.h" #include "test-floating.h" -#include "pygi-python-compat.h" +#define PYGI_DEFINE_TYPE(typename, symbol, csymbol) \ +PyTypeObject symbol = { \ + PyVarObject_HEAD_INIT(NULL, 0) \ + typename, \ + sizeof(csymbol) \ +}; static PyObject * _wrap_TestInterface__do_iface_method(PyObject *cls, PyObject *args, @@ -82,7 +87,7 @@ _wrap_test_g_object_new (PyObject * self) PyObject *rv; obj = g_object_new(g_type_from_name("PyGObject"), NULL); - rv = PYGLIB_PyLong_FromLong(obj->ref_count); /* should be == 2 at this point */ + rv = PyLong_FromLong(obj->ref_count); /* should be == 2 at this point */ g_object_unref(obj); return rv; } @@ -111,7 +116,7 @@ static const PyMethodDef _PyTestInterface_methods[] = { }; /* TestInterface */ -PYGLIB_DEFINE_TYPE("test.Interface", PyTestInterface_Type, PyObject); +PYGI_DEFINE_TYPE("test.Interface", PyTestInterface_Type, PyObject); static PyObject * _wrap_TestInterface__do_iface_method(PyObject *cls, PyObject *args, PyObject *kwargs) @@ -136,7 +141,7 @@ _wrap_TestInterface__do_iface_method(PyObject *cls, PyObject *args, PyObject *kw return Py_None; } -PYGLIB_DEFINE_TYPE("testhelper.Unknown", PyTestUnknown_Type, PyGObject); +PYGI_DEFINE_TYPE("testhelper.Unknown", PyTestUnknown_Type, PyGObject); static void _wrap_TestInterface__proxy_do_iface_method(TestInterface *self) @@ -222,10 +227,10 @@ static const GInterfaceInfo __TestInterface__iinfo = { }; /* TestFloating */ -PYGLIB_DEFINE_TYPE("testhelper.Floating", PyTestFloating_Type, PyGObject); +PYGI_DEFINE_TYPE("testhelper.Floating", PyTestFloating_Type, PyGObject); /* TestOwnedByLibrary */ -PYGLIB_DEFINE_TYPE("testhelper.OwnedByLibrary", PyTestOwnedByLibrary_Type, PyGObject); +PYGI_DEFINE_TYPE("testhelper.OwnedByLibrary", PyTestOwnedByLibrary_Type, PyGObject); static PyObject * _wrap_test_owned_by_library_release (PyGObject *self) @@ -240,7 +245,7 @@ static const PyMethodDef _PyTestOwnedByLibrary_methods[] = { }; /* TestFloatingAndSunk */ -PYGLIB_DEFINE_TYPE("testhelper.FloatingAndSunk", PyTestFloatingAndSunk_Type, PyGObject); +PYGI_DEFINE_TYPE("testhelper.FloatingAndSunk", PyTestFloatingAndSunk_Type, PyGObject); static PyObject * _wrap_test_floating_and_sunk_release (PyGObject *self) @@ -583,7 +588,7 @@ _wrap_constant_strip_prefix(PyObject *self, PyObject *args) return NULL; result = pyg_constant_strip_prefix (name, strip_prefix); - return PYGLIB_PyUnicode_FromString (result); + return PyUnicode_FromString (result); } static PyObject * @@ -676,7 +681,7 @@ _wrap_test_parse_constructor_args (PyObject *self, PyObject *args) return NULL; } - return PYGLIB_PyLong_FromLong (nparams); + return PyLong_FromLong (nparams); } G_GNUC_END_IGNORE_DEPRECATIONS @@ -693,7 +698,7 @@ _wrap_test_to_unichar_conv (PyObject * self, PyObject *args) if (!pyg_pyobj_to_unichar_conv (obj, &result)) return NULL; - return PYGLIB_PyLong_FromLong (result); + return PyLong_FromLong (result); } static PyMethodDef testhelper_functions[] = { @@ -715,11 +720,32 @@ static PyMethodDef testhelper_functions[] = { { NULL, NULL } }; -PYGLIB_MODULE_START(testhelper, "testhelper") -{ +static struct PyModuleDef _testhelpermodule = { + PyModuleDef_HEAD_INIT, + "testhelper", + NULL, + -1, + testhelper_functions, + NULL, + NULL, + NULL, + NULL +}; + +#ifdef __GNUC__ +#define PYGI_MODINIT_FUNC __attribute__((visibility("default"))) PyMODINIT_FUNC +#else +#define PYGI_MODINIT_FUNC PyMODINIT_FUNC +#endif + +PYGI_MODINIT_FUNC PyInit_testhelper(void); + +PYGI_MODINIT_FUNC PyInit_testhelper(void) { + PyObject *module; PyObject *gobject_module; PyObject *m, *d; + module = PyModule_Create(&_testhelpermodule); if ((gobject_module = pygobject_init(-1, -1, -1)) == NULL) return NULL; @@ -730,7 +756,7 @@ PYGLIB_MODULE_START(testhelper, "testhelper") if ((m = PyImport_ImportModule("gi.repository.GObject")) == NULL) { PyErr_SetString(PyExc_ImportError, "could not import gobject"); - return PYGLIB_MODULE_ERROR_RETURN; + return NULL; } /* TestInterface */ @@ -779,6 +805,7 @@ PYGLIB_MODULE_START(testhelper, "testhelper") &PyTestFloatingAndSunk_Type, Py_BuildValue("(O)", &PyGObject_Type)); + + return module; } -PYGLIB_MODULE_END -- 2.34.1