+.mypy_cache
*.bak
*.lo
*.o
CHERE_INVOKING: "yes"
<<: *mingw-defaults
-python2.7:
- variables:
- PYENV_VERSION: "2.7.17-debug"
- <<: *defaults
-
python3.5:
variables:
PYENV_VERSION: "3.5.9"
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:
+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
-------------------
-Metadata-Version: 1.0
+Metadata-Version: 1.2
Name: PyGObject
Version: @VERSION@
Summary: Python bindings for GObject Introspection
Classifier: Programming Language :: C
Classifier: Programming Language :: Python
Classifier: Topic :: Software Development :: Libraries :: Python Modules
+Requires-Python: >=3.5, <4
<https://developer.gnome.org/glib/stable/>`__, `GIO
<https://developer.gnome.org/gio/stable/>`__ 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+**.
----
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
-# -*- coding: utf-8 -*-
-
extensions = [
'sphinx.ext.todo',
'sphinx.ext.intersphinx',
'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),
}
* 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
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
#!/usr/bin/env python
-# coding=utf-8
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
#
# 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__)
from ._gi import Repository
from ._gi import PyGIDeprecationWarning
from ._gi import PyGIWarning
-from ._compat import string_types
_API = _API # pyflakes
PyGIDeprecationWarning = PyGIDeprecationWarning
"""
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():
+++ /dev/null
-# 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 <http://www.gnu.org/licenses/>.
-
-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)
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
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)
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
-# -*- coding: utf-8 -*-
# Copyright 2017 Christoph Reiter
#
# This library is free software; you can redistribute it and/or
from __future__ import print_function
import os
-import sys
import socket
import signal
import threading
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.
"""
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):
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
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, \
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,
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
#include "pygi-property.h"
#include "pygi-util.h"
#include "gimodule.h"
-#include "pygi-python-compat.h"
#include "pygi-basictype.h"
PyObject *PyGIWarning;
}
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;
/* 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,
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;
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;
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;
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);
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);
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);
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);
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;
}
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;
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
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);
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
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-from __future__ import absolute_import
import sys
import warnings
import importlib
install_headers(headers, subdir : 'pygobject-@0@'.format(platform_version))
python_sources = [
- '_compat.py',
'_constants.py',
'docstring.py',
'_error.py',
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,
# 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 \
# 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():
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
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)
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',
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:
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
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)
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)
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:
_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
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
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)
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)
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)
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)
__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):
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)
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)
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:
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')
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"):
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)
}
}
-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 *
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;
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;
}
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;
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;
}
#include <config.h>
-#include "pygi-python-compat.h"
#include "pygi-type.h"
#include "pygi-util.h"
#include "pygi-type.h"
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;
{
static char warning[256];
- if (!PYGLIB_PyLong_Check(other)) {
+ if (!PyLong_Check (other)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
if (module == NULL)
return NULL;
- if (!PYGLIB_PyUnicode_Check (module)) {
+ if (!PyUnicode_Check (module)) {
Py_DECREF (module);
return NULL;
}
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;
sprintf(tmp, "<enum %s of type %s.%s>", value,
namespace, Py_TYPE (self)->tp_name);
else
- sprintf(tmp, "<enum %ld of type %s.%s>", PYGLIB_PyLong_AS_LONG(self),
+ sprintf(tmp, "<enum %ld of type %s.%s>", 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 *
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);
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);
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);
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);
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__"));
}
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;
}
#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;
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)
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;
{
static char warning[256];
- if (!PYGLIB_PyLong_Check(other)) {
+ if (!PyLong_Check (other)) {
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
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;
namespace, Py_TYPE (self)->tp_name);
else
retval = g_strdup_printf("<flags %ld of type %s.%s>",
- 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;
g_type_class_unref(eclass);
- pyint = PYGLIB_PyLong_FromUnsignedLong(value);
+ pyint = PyLong_FromUnsignedLong (value);
ret = PyDict_GetItem(values, pyint);
if (!ret) {
PyErr_Clear();
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);
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();
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);
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);
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)));
}
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);
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);
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);
}
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);
}
(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 */
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;
}
extern GQuark pygflags_class_key;
typedef struct {
- PYGLIB_PyLongObject parent;
+ PyLongObject parent;
int zero_pad; /* must always be 0 */
GType gtype;
} PyGFlags;
#include <pygenum.h>
#include <pygflags.h>
-#include "pygi-python-compat.h"
#include "pygi-argument.h"
#include "pygi-info.h"
#include "pygi-value.h"
/* 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;
}
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;
}
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) {
#include <Python.h>
#include <glib.h>
-#include "pygi-python-compat.h"
#include "pygi-array.h"
#include "pygi-info.h"
#include "pygi-marshal-cleanup.h"
}
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
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) {
*/
#include <Python.h>
-#include "pygi-python-compat.h"
+
#include "pygi-type.h"
#include "pygi-basictype.h"
#include "pygi-argument.h"
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;
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 *
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);
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);
/* 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,
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);
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);
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;
}
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);
if (!bytes)
return FALSE;
- if (PYGLIB_PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) {
+ if (PyBytes_AsStringAndSize (bytes, &buffer, NULL) == -1) {
Py_DECREF (bytes);
return FALSE;
}
Py_TYPE (py_arg)->tp_name);
return FALSE;
}
-#endif
*result = filename;
return TRUE;
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");
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;
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);
PyObject *
pygi_gint_to_py (gint value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
gboolean
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);
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
}
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);
PyObject *
pygi_glong_to_py (glong value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
gboolean
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);
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);
}
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;
}
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);
PyObject *
pygi_gint8_to_py (gint8 value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
gboolean
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;
}
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);
PyObject *
pygi_guint8_to_py (guint8 value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
static gboolean
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);
static PyObject *
pygi_gint16_to_py (gint16 value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
static gboolean
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);
static PyObject *
pygi_guint16_to_py (guint16 value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
static gboolean
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);
static PyObject *
pygi_gint32_to_py (gint32 value)
{
- return PYGLIB_PyLong_FromLong (value);
+ return PyLong_FromLong (value);
}
static gboolean
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);
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
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);
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);
}
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);
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);
}
Py_RETURN_NONE;
}
- return PYGLIB_PyUnicode_FromString (value);
+ return PyUnicode_FromString (value);
}
PyObject *
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;
}
#include "pygboxed.h"
#include "pygi-type.h"
#include "pygi-basictype.h"
-#include "pygi-python-compat.h"
+#include "pygi-util.h"
#include <girepository.h>
return 0;
}
-PYGLIB_DEFINE_TYPE("gi.Boxed", PyGIBoxed_Type, PyGIBoxed);
+PYGI_DEFINE_TYPE("gi.Boxed", PyGIBoxed_Type, PyGIBoxed);
PyObject *
pygi_boxed_new (PyTypeObject *type,
#include <Python.h>
#include <girepository.h>
-#include "pygi-python-compat.h"
#include "pygi-type.h"
#include "pygi-info.h"
#include "pygi-cache.h"
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;
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
-#include "pygi-python-compat.h"
+#include "pygi-util.h"
#include "pygi-ccallback.h"
#include <girepository.h>
return result;
}
-PYGLIB_DEFINE_TYPE("gi.CCallback", PyGICCallback_Type, PyGICCallback);
+PYGI_DEFINE_TYPE("gi.CCallback", PyGICCallback_Type, PyGICCallback);
PyObject *
_pygi_ccallback_new (GCallback callback,
#include <Python.h>
#include <glib.h>
-#include "pygi-python-compat.h"
#include "pygi-enum-marshal.h"
#include "pygi-type.h"
#include "pygenum.h"
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 */
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 */
#include <Python.h>
#include "pygi-error.h"
#include "pygi-type.h"
-#include "pygi-python-compat.h"
#include "pygi-util.h"
#include "pygi-basictype.h"
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;
}
#include <Python.h>
#include <cairo.h>
-
-#if PY_VERSION_HEX < 0x03000000
-#include <pycairo.h>
-static Pycairo_CAPI_t *Pycairo_CAPI;
-#else
#include <py3cairo.h>
-#endif
#include <cairo-gobject.h>
* shared library that interacts with PyGI through a PyCapsule API at runtime.
*/
#include <pygi-foreign-api.h>
-#include "pygi-python-compat.h"
/*
* cairo_t marshaling
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",
cairo_pattern_from_gvalue,
cairo_pattern_to_gvalue);
-}
-PYGLIB_MODULE_END;
+ return module;
+}
\ No newline at end of file
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
-#include "pygi-python-compat.h"
#include "pygi-info.h"
#include "pygi-cache.h"
#include "pygi-invoke.h"
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;
_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 *
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",
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);
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[] = {
/* CallableInfo */
-PYGLIB_DEFINE_TYPE ("gi.CallableInfo", PyGICallableInfo_Type, PyGICallableInfo);
+PYGI_DEFINE_TYPE ("gi.CallableInfo", PyGICallableInfo_Type, PyGICallableInfo);
/* _callable_info_call:
*
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 "
};
/* 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)
};
/* 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)
/* 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)
/* 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)
/* 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)
};
/* 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)
/* 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)
/* 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)
/* 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)
/* 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)
};
/* 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)
};
/* 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)
/* 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,
/* 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)
/* 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)
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) {
#include <Python.h>
#include <glib.h>
-#include "pygi-python-compat.h"
#include "pygi-object.h"
#include "pygobject-object.h"
#include "pygparamspec.h"
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;
}
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);
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)
+++ /dev/null
-/* -*- 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 <http://www.gnu.org/licenses/>.
- */
-
-#ifndef __PYGLIB_PYTHON_COMPAT_H__
-#define __PYGLIB_PYTHON_COMPAT_H__
-
-#ifndef PY_SSIZE_T_CLEAN
-#error "PY_SSIZE_T_CLEAN not defined"
-#endif
-
-#include <Python.h>
-
-#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__ */
#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,
#include <Python.h>
#include <glib.h>
#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";
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.
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;
}
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)
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);
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)
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;
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);
}
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);
* IN THE SOFTWARE.
*/
-#include "pygi-python-compat.h"
#include "pygi-info.h"
#include "pygi-boxed.h"
#include "pygi-type.h"
#include <Python.h>
#include <glib.h>
-#include "pygi-python-compat.h"
#include "pygi-struct-marshal.h"
#include "pygi-struct.h"
#include "pygi-foreign.h"
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)
#include "pygi-type.h"
#include "pygi-type.h"
#include "pygpointer.h"
-#include "pygi-python-compat.h"
+#include "pygi-util.h"
#include <girepository.h>
return 0;
}
-PYGLIB_DEFINE_TYPE("gi.Struct", PyGIStruct_Type, PyGIStruct);
+PYGI_DEFINE_TYPE("gi.Struct", PyGIStruct_Type, PyGIStruct);
PyObject *
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);
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);
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)
g_snprintf(buf, sizeof(buf), "<GType %s (%lu)>",
name?name:"invalid", (unsigned long int) self->type);
- return PYGLIB_PyUnicode_FromString(buf);
+ return PyUnicode_FromString (buf);
}
static void
_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 *
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;
}
/* 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) {
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
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));
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));
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)
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:
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;
#include <girepository.h>
#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);
#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)
{
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)
{
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();
}
#include <Python.h>
#include <glib.h>
-#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; \
} \
} 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
#include <Python.h>
#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"
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);
*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:
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));
* 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);
#include <Python.h>
#include <glib-object.h>
-#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)
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;
}
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)
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);
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);
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);
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)
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);
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)
*/
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);
}
/* 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);
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;
/* -------------- 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)
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 *
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;
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;
}
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) {
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);
}
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;
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;
&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;
&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;
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;
}
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;
}
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;
}
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)
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 */
#include <Python.h>
#include <glib-object.h>
-#include "pygi-python-compat.h"
#include "pygobject-internal.h"
/* Data that belongs to the GObject instance, not the Python wrapper */
#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:
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);
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);
}
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;
}
#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:
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;
}
#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)
}
}
-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 *
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
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);
}
} 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);
}
} 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)) {
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)
}
}
-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 *
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
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;
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;
}
#include <Python.h>
#include <glib.h>
-#include "pygi-python-compat.h"
+#include "pygi-util.h"
#include "pygi-basictype.h"
#include "pygspawn.h"
#include "pygi-error.h"
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)
#ifdef G_OS_WIN32
return (GPid)PyLong_AsVoidPtr (self);
#else
- return (GPid)PYGLIB_PyLong_AsLong (self);
+ return (GPid)PyLong_AsLong (self);
#endif
}
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
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");
Py_XDECREF(tmp);
return NULL;
}
- argv[i] = PYGLIB_PyUnicode_AsString(tmp);
+ argv[i] = PyUnicode_AsUTF8 (tmp);
Py_DECREF(tmp);
}
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");
g_free(argv);
return NULL;
}
- envp[i] = PYGLIB_PyUnicode_AsString(tmp);
+ envp[i] = PyUnicode_AsUTF8 (tmp);
Py_DECREF(tmp);
}
}
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;
}
-from __future__ import absolute_import
import warnings
from gi import PyGIDeprecationWarning
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-from __future__ import absolute_import
-
import sys
from ..importer import DynamicImporter
# 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
# 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:
project('pygobject', 'c',
- version : '3.36.1',
+ version : '3.38.0',
meson_version : '>= 0.46.0',
default_options : [ 'warning_level=1',
'buildtype=debugoptimized'])
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()
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 = []
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')
import sys
import warnings
+from collections import UserList
import gi
from gi.repository import GObject
-from gi import _compat
_patches = []
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):
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
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)
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
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"
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"""
"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",
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()]
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("."))
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
"-Wwrite-strings",
]
- if sys.version_info[0] == 2:
- args += [
- "-Wdeclaration-after-statement",
- ]
-
args += [
"-Wno-incompatible-pointer-types-discards-qualifiers",
"-Wno-missing-field-initializers",
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)
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")
)
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():
"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']),
],
-from __future__ import absolute_import
-
import os
import sys
import unittest
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":
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
-# -*- 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):
finally:
sys.excepthook = orig_excepthook
if exceptions:
- reraise(*exceptions[0])
+ tp, value, tb = exceptions[0]
+ raise tp(value).with_traceback(tb)
-from __future__ import absolute_import
-
import contextlib
import unittest
import inspect
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"])
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']
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)
#!/usr/bin/env python
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import os
import sys
-from __future__ import absolute_import
-
import os
import unittest
# -*- Mode: Python; py-indent-offset: 4 -*-
-# coding=utf-8
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import unittest
import pytest
-from __future__ import absolute_import
-
import unittest
import gi.docstring
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-from __future__ import absolute_import
-
import unittest
import pickle
# -*- 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
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
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
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")
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']
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):
# -*- Mode: Python; py-indent-offset: 4 -*-
-# coding=utf-8
-
-from __future__ import absolute_import
import math
import unittest
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import unittest
from gi.repository import GLib
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
-from __future__ import absolute_import
-
# system
import gc
import sys
# -*- Mode: Python; py-indent-offset: 4 -*-
-# coding=utf-8
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import sys
import unittest
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
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)
(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
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")
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 = [
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):
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"))
@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")
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,
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()
# 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):
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import os
import unittest
import warnings
# -*- Mode: Python -*-
-# encoding: UTF-8
-
-from __future__ import absolute_import
import os
import sys
import pytest
from gi.repository import GLib
from gi import PyGIDeprecationWarning
-from gi._compat import PY3
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
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import sys
import gc
import unittest
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
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))))
-# coding: UTF-8
-
-from __future__ import absolute_import
-
import tempfile
import os
import pytest
</template>
</interface>
"""
+
@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 = """
</template>
</interface>
"""
+
@Gtk.Template(string=testbox)
class TestBox(Gtk.Box):
_testlabel = Gtk.Template.Child()
def __init__(self):
- super(TestBox, self).__init__()
+ super().__init__()
assert isinstance(self._testlabel, TestLabel)
</template>
</interface>
"""
+
@Gtk.Template(string=window)
class MyWindow(Gtk.Window):
_testlabel = Gtk.Template.Child()
def __init__(self):
- super(MyWindow, self).__init__()
+ super().__init__()
assert isinstance(self._testbox, TestBox)
assert isinstance(self._testlabel, TestLabel)
</template>
</interface>
"""
+
@Gtk.Template(string=xml)
class MyBox(Gtk.Box):
_label = Gtk.Template.Child()
def __init__(self):
- super(MyBox, self).__init__()
+ super().__init__()
self._label.props.label = "awesome label"
my_box = MyBox()
-from __future__ import absolute_import
-
import unittest
from gi.repository import GObject
# -*- 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
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
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
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import unittest
from gi.repository import GObject
-# -*- 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
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())
# -*- Mode: Python -*-
-# encoding: UTF-8
-
-from __future__ import absolute_import
import os
import unittest
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import os
import select
import signal
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import unittest
import weakref
import gc
#!/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
-# -*- coding: utf-8 -*-
# Copyright 2017 Christoph Reiter
#
# This library is free software; you can redistribute it and/or
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
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)
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import re
import os
import sys
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()
ev.type = Gdk.EventType.BUTTON_PRESS
self.assertEqual(str(Gdk.ModifierType.META_MASK),
'<flags GDK_META_MASK of type Gdk.ModifierType>')
- self.assertEqual(Gdk.ModifierType.RELEASE_MASK | 0, 0x40000000)
- self.assertEqual(hex(Gdk.ModifierType.RELEASE_MASK), '0x40000000')
- self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK),
- '<flags GDK_RELEASE_MASK of type Gdk.ModifierType>')
+ # 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),
+ '<flags GDK_RELEASE_MASK of type Gdk.ModifierType>')
- self.assertEqual(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK, 0x50000000)
- self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK),
- '<flags GDK_META_MASK | GDK_RELEASE_MASK of type Gdk.ModifierType>')
+ self.assertEqual(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK, 0x50000000)
+ self.assertEqual(str(Gdk.ModifierType.RELEASE_MASK | Gdk.ModifierType.META_MASK),
+ '<flags GDK_META_MASK | GDK_RELEASE_MASK of type Gdk.ModifierType>')
@unittest.skipIf(GDK4, "not in gdk4")
def test_color_parse(self):
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-from __future__ import absolute_import
-
import pytest
from gi import PyGIDeprecationWarning
-from __future__ import absolute_import
-
import random
import platform
import warnings
from gi.repository import Gio, GObject
from gi import PyGIWarning
-from gi._compat import cmp
class Item(GObject.Object):
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
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:
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import os
import gc
import unittest
import gi
from gi.repository import GLib
-from gi._compat import long_, integer_types
from .helper import capture_gi_deprecation_warnings
# 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
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))
-# -*- 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
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"
# -*- 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
import gi.overrides
import gi.types
-from gi._compat import cmp
from gi.repository import GLib, GObject
try:
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
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')
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)
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('''
+<interface>
+ <object class="GtkWindow" id="win">
+ <property name="css-name">amazing</property>
+ </object>
+ <object class="TestWindow" id="testwin">
+ <property name="css-name">amazing-test</property>
+ </object>
+</interface>''')
+ 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)
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()
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()
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):
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()
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)
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)
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')
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()
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import unittest
try:
-# coding=utf-8
-
-from __future__ import absolute_import
-
import os
import gc
import sys
from gi.repository import Regress
from gi import _propertyhelper as propertyhelper
-from gi._compat import long_, PY3, PY2
from .helper import capture_glib_warnings
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):
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):
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:
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'))
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):
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)
-from __future__ import absolute_import
-
-import sys
import unittest
import ctypes
from ctypes import c_void_p, py_object, c_char_p
]
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
# -*- Mode: Python; py-indent-offset: 4 -*-
# vim: tabstop=4 shiftwidth=4 expandtab
-from __future__ import absolute_import
-
import unittest
import base64
# 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
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-from __future__ import absolute_import
-
import unittest
import pickle
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import gc
import unittest
import sys
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
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,)),
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)
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),
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import sys
import gc
import unittest
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import sys
import os
import unittest
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import unittest
from gi.repository import GLib
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
# USA
-from __future__ import absolute_import
-
import unittest
from gi.repository import GObject
# -*- Mode: Python -*-
-from __future__ import absolute_import
-
import unittest
from gi.repository import GObject
#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,
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;
}
};
/* 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)
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)
};
/* 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)
};
/* 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)
return NULL;
result = pyg_constant_strip_prefix (name, strip_prefix);
- return PYGLIB_PyUnicode_FromString (result);
+ return PyUnicode_FromString (result);
}
static PyObject *
return NULL;
}
- return PYGLIB_PyLong_FromLong (nparams);
+ return PyLong_FromLong (nparams);
}
G_GNUC_END_IGNORE_DEPRECATIONS
if (!pyg_pyobj_to_unichar_conv (obj, &result))
return NULL;
- return PYGLIB_PyLong_FromLong (result);
+ return PyLong_FromLong (result);
}
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;
if ((m = PyImport_ImportModule("gi.repository.GObject")) == NULL) {
PyErr_SetString(PyExc_ImportError,
"could not import gobject");
- return PYGLIB_MODULE_ERROR_RETURN;
+ return NULL;
}
/* TestInterface */
&PyTestFloatingAndSunk_Type,
Py_BuildValue("(O)",
&PyGObject_Type));
+
+ return module;
}
-PYGLIB_MODULE_END