PyObject *
_pygi_marshal_to_py_unichar (PyGIInvokeState   *state,
                             PyGICallableCache *callable_cache,
                             PyGIArgCache      *arg_cache,
                             GIArgument        *arg)
{
    PyObject *py_obj = NULL;

    /* Preserve the bidirectional mapping between 0 and "" */
    if (arg->v_uint32 == 0) {
        py_obj = PYGLIB_PyUnicode_FromString ("");
    } else if (g_unichar_validate (arg->v_uint32)) {
        gchar utf8[6];
        gint bytes;

        bytes = g_unichar_to_utf8 (arg->v_uint32, utf8);
        py_obj = PYGLIB_PyUnicode_FromStringAndSize ((char*)utf8, bytes);
    } else {
        /* TODO: Convert the error to an exception. */
        PyErr_Format (PyExc_TypeError,
                      "Invalid unicode codepoint %" G_GUINT32_FORMAT,
                      arg->v_uint32);
    }

    return py_obj;
}
Example #2
0
static PyObject *
_wrap_g_irepository_get_dependencies (PyGIRepository *self,
                                      PyObject       *args,
                                      PyObject       *kwargs)
{
    static char *kwlist[] = { "namespace", NULL };
    const char *namespace_;
    char **namespaces;
    PyObject *py_namespaces;
    gssize i;

    if (!PyArg_ParseTupleAndKeywords (args, kwargs,
                                      "s:Repository.get_dependencies", kwlist, &namespace_)) {
        return NULL;
    }

    py_namespaces = PyList_New (0);
    /* Returns NULL in case of no dependencies */
    namespaces = g_irepository_get_dependencies (self->repository, namespace_);
    if (namespaces == NULL) {
        return py_namespaces;
    }

    for (i = 0; namespaces[i] != NULL; i++) {
        PyObject *py_namespace = PYGLIB_PyUnicode_FromString (namespaces[i]);
        PyList_Append (py_namespaces, py_namespace);
        Py_DECREF(py_namespace);
    }

    g_strfreev (namespaces);

    return py_namespaces;
}
Example #3
0
static PyObject *
_wrap_g_irepository_enumerate_versions (PyGIRepository *self,
                                        PyObject       *args,
                                        PyObject       *kwargs)
{
    static char *kwlist[] = { "namespace", NULL };
    const char *namespace_;
    GList *versions, *item;
    PyObject *ret = NULL;

    if (!PyArg_ParseTupleAndKeywords (args, kwargs, "s:Repository.enumerate_versions",
                                      kwlist, &namespace_)) {
        return NULL;
    }

    versions = g_irepository_enumerate_versions (self->repository, namespace_);
    ret = PyList_New(0);
    for (item = versions; item; item = item->next) {
        char *version = item->data;
        PyObject *py_version = PYGLIB_PyUnicode_FromString (version);
        PyList_Append(ret, py_version);
        Py_DECREF(py_version);
        g_free (version);
    }
    g_list_free(versions);

    return ret;
}
PyObject *
_pygi_marshal_to_py_filename (PyGIInvokeState   *state,
                              PyGICallableCache *callable_cache,
                              PyGIArgCache      *arg_cache,
                              GIArgument        *arg)
{
    gchar *string;
    PyObject *py_obj = NULL;
    GError *error = NULL;

    if (arg->v_string == NULL) {
        py_obj = Py_None;
        Py_INCREF (py_obj);
        return py_obj;
    }

    string = g_filename_to_utf8 (arg->v_string, -1, NULL, NULL, &error);
    if (string == NULL) {
        PyErr_SetString (PyExc_Exception, error->message);
        /* TODO: Convert the error to an exception. */
        return NULL;
    }

    py_obj = PYGLIB_PyUnicode_FromString (string);
    g_free (string);

    return py_obj;
}
Example #5
0
/**
 * Extends __dir__ with the extra attributes accessible through
 * resulttuple_getattro()
 */
static PyObject *
resulttuple_dir(PyObject *self)
{
    PyObject *mapping_attr;
    PyObject *items = NULL;
    PyObject *mapping = NULL;
    PyObject *mapping_values = NULL;
    PyObject *result = NULL;

    mapping_attr = PYGLIB_PyUnicode_FromString (tuple_indices_key);
    mapping = PyTuple_Type.tp_getattro (self, mapping_attr);
    Py_DECREF (mapping_attr);
    if (mapping == NULL)
        goto error;
    items = PyObject_Dir ((PyObject*)self->ob_type);
    if (items == NULL)
        goto error;
    mapping_values = PyDict_Keys (mapping);
    if (mapping_values == NULL)
        goto error;
    result = PySequence_InPlaceConcat (items, mapping_values);

error:
    Py_XDECREF (items);
    Py_XDECREF (mapping);
    Py_XDECREF (mapping_values);

    return result;
}
Example #6
0
static PyObject *
pyg_enum_repr(PyGEnum *self)
{
  GEnumClass *enum_class;
  const char *value;
  guint index;
  static char tmp[256];
  long l;

  enum_class = g_type_class_ref(self->gtype);
  g_assert(G_IS_ENUM_CLASS(enum_class));

  l = PYGLIB_PyLong_AS_LONG(self);
  for (index = 0; index < enum_class->n_values; index++) 
      if (l == enum_class->values[index].value)
          break;

  value = enum_class->values[index].value_name;
  if (value)
      sprintf(tmp, "<enum %s of type %s>", value, g_type_name(self->gtype));
  else
      sprintf(tmp, "<enum %ld of type %s>", PYGLIB_PyLong_AS_LONG(self), g_type_name(self->gtype));

  g_type_class_unref(enum_class);

  return PYGLIB_PyUnicode_FromString(tmp);
}
Example #7
0
static PyObject *
pyg_type_wrapper_repr(PyGTypeWrapper *self)
{
    char buf[80];
    const gchar *name = g_type_name(self->type);

    g_snprintf(buf, sizeof(buf), "<GType %s (%lu)>",
	       name?name:"invalid", (unsigned long int) self->type);
    return PYGLIB_PyUnicode_FromString(buf);
}
Example #8
0
static PyObject *
_pygi_marshal_to_py_utf8 (GIArgument *arg)
{
    PyObject *py_obj = NULL;
    if (arg->v_string == NULL) {
        Py_RETURN_NONE;
     }

    py_obj = PYGLIB_PyUnicode_FromString (arg->v_string);
    return py_obj;
}
Example #9
0
static PyObject *
_wrap_g_base_info_get_name (PyGIBaseInfo *self)
{
    /* 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
    /* 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",
        "assert", "break", "class", "continue", "def", "del", "elif", "else",
        "except", "finally", "for", "from", "global", "if", "import", "in",
        "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return",
        "try", "while", "with", "yield",
        "print", NULL};
#else
    #error Need keyword list for this major Python version
#endif

    const gchar *name, **i;

    name = g_base_info_get_name (self->info);

    /* escape keywords */
    for (i = keywords; *i != NULL; ++i) {
        if (strcmp (name, *i) == 0) {
            gchar *escaped = g_strconcat (name, "_", NULL);
            PyObject *obj = PYGLIB_PyUnicode_FromString (escaped);
            g_free (escaped);
            return obj;
        }
    }

    return PYGLIB_PyUnicode_FromString (name);
}
Example #10
0
static PyObject *
_wrap_constant_strip_prefix(PyObject *self, PyObject *args)
{
    const char *name, *strip_prefix;
    const gchar *result;

    if (!PyArg_ParseTuple (args, "ss", &name, &strip_prefix))
        return NULL;

    result = pyg_constant_strip_prefix (name, strip_prefix);
    return PYGLIB_PyUnicode_FromString (result);
}
Example #11
0
/**
 * ResultTuple.__repr__() implementation.
 * Takes the _ResultTuple.__repr_format format string and applies the tuple
 * values to it.
 */
static PyObject*
resulttuple_repr(PyObject *self) {
    PyObject *format,  *repr, *format_attr;

    format_attr = PYGLIB_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);
    Py_DECREF (format);
    return repr;
}
Example #12
0
PyObject *
_pygi_marshal_to_py_utf8 (PyGIInvokeState   *state,
                          PyGICallableCache *callable_cache,
                          PyGIArgCache      *arg_cache,
                          GIArgument        *arg)
{
    PyObject *py_obj = NULL;
    if (arg->v_string == NULL) {
        py_obj = Py_None;
        Py_INCREF (py_obj);
        return py_obj;
     }

    py_obj = PYGLIB_PyUnicode_FromString (arg->v_string);
    return py_obj;
}
Example #13
0
static PyObject *
pyg_flags_repr(PyGFlags *self)
{
    char *tmp, *retval;
    PyObject *pyretval;

    tmp = generate_repr(self->gtype, PYGLIB_PyLong_AS_LONG(self));

    if (tmp)
        retval = g_strdup_printf("<flags %s of type %s>", tmp,
                                 g_type_name(self->gtype));
    else
        retval = g_strdup_printf("<flags %ld of type %s>", PYGLIB_PyLong_AS_LONG(self),
                                 g_type_name(self->gtype));
    g_free(tmp);

    pyretval = PYGLIB_PyUnicode_FromString(retval);
    g_free(retval);

    return pyretval;
}
Example #14
0
static PyObject *
_wrap_g_irepository_get_loaded_namespaces (PyGIRepository *self)
{
    char **namespaces;
    PyObject *py_namespaces;
    gssize i;

    namespaces = g_irepository_get_loaded_namespaces (self->repository);

    py_namespaces = PyList_New (0);
    for (i = 0; namespaces[i] != NULL; i++) {
        PyObject *py_namespace = PYGLIB_PyUnicode_FromString (namespaces[i]);
        PyList_Append (py_namespaces, py_namespace);
        Py_DECREF(py_namespace);
        g_free (namespaces[i]);
    }

    g_free (namespaces);

    return py_namespaces;
}
Example #15
0
/**
 * PyGIResultTuple_Type.tp_getattro implementation.
 * Looks up the tuple index in _ResultTuple.__tuple_indices and returns the
 * tuple item.
 */
static PyObject*
resulttuple_getattro(PyObject *self, PyObject *name) {
    PyObject *mapping, *index, *mapping_attr, *item;

    mapping_attr = PYGLIB_PyUnicode_FromString (tuple_indices_key);
    mapping = PyTuple_Type.tp_getattro (self, mapping_attr);
    Py_DECREF (mapping_attr);
    if (mapping == NULL)
        return NULL;
    g_assert (PyDict_Check (mapping));
    index = PyDict_GetItem (mapping, name);

    if (index != NULL) {
        item = PyTuple_GET_ITEM (self, PYGLIB_PyLong_AsSsize_t (index));
        Py_INCREF (item);
    } else {
        item = PyTuple_Type.tp_getattro (self, name);
    }
    Py_DECREF (mapping);

    return item;
}
Example #16
0
static PyObject *
_wrap_g_irepository_get_version (PyGIRepository *self,
                                 PyObject       *args,
                                 PyObject       *kwargs)
{
    static char *kwlist[] = { "namespace", NULL };
    const char *namespace_;
    const gchar *version;

    if (!PyArg_ParseTupleAndKeywords (args, kwargs,
                                      "s:Repository.get_version", kwlist, &namespace_)) {
        return NULL;
    }

    version = g_irepository_get_version (self->repository, namespace_);
    if (version == NULL) {
        PyErr_Format (PyExc_RuntimeError, "Namespace '%s' not loaded", namespace_);
        return NULL;
    }

    return PYGLIB_PyUnicode_FromString (version);
}
Example #17
0
static PyObject *
_pygi_marshal_to_py_filename (GIArgument *arg)
{
    gchar *string = NULL;
    PyObject *py_obj = NULL;
    GError *error = NULL;

    if (arg->v_string == NULL) {
        Py_RETURN_NONE;
    }

    string = g_filename_to_utf8 (arg->v_string, -1, NULL, NULL, &error);
    if (string == NULL) {
        PyErr_SetString (PyExc_Exception, error->message);
        /* TODO: Convert the error to an exception. */
        return NULL;
    }

    py_obj = PYGLIB_PyUnicode_FromString (string);
    g_free (string);

    return py_obj;
}
Example #18
0
static PyObject *
_wrap_g_base_info_get_namespace (PyGIBaseInfo *self)
{
    return PYGLIB_PyUnicode_FromString (g_base_info_get_namespace (self->info));
}
Example #19
0
/**
 * pyg_value_as_pyobject:
 * @value: the GValue object.
 * @copy_boxed: true if boxed values should be copied.
 *
 * This function creates/returns a Python wrapper object that
 * represents the GValue passed as an argument.
 *
 * Returns: a PyObject representing the value.
 */
PyObject *
pyg_value_as_pyobject(const GValue *value, gboolean copy_boxed)
{
    gchar buf[128];

    switch (G_TYPE_FUNDAMENTAL(G_VALUE_TYPE(value))) {
    case G_TYPE_INTERFACE:
	if (g_type_is_a(G_VALUE_TYPE(value), G_TYPE_OBJECT))
	    return pygobject_new(g_value_get_object(value));
	else
	    break;
    case G_TYPE_CHAR: {
	gint8 val = g_value_get_char(value);
	return PYGLIB_PyUnicode_FromStringAndSize((char *)&val, 1);
    }
    case G_TYPE_UCHAR: {
	guint8 val = g_value_get_uchar(value);
	return PYGLIB_PyBytes_FromStringAndSize((char *)&val, 1);
    }
    case G_TYPE_BOOLEAN: {
	return PyBool_FromLong(g_value_get_boolean(value));
    }
    case G_TYPE_INT:
	return PYGLIB_PyLong_FromLong(g_value_get_int(value));
    case G_TYPE_UINT:
	{
	    /* in Python, the Int object is backed by a long.  If a
	       long can hold the whole value of an unsigned int, use
	       an Int.  Otherwise, use a Long object to avoid overflow.
	       This matches the ULongArg behavior in codegen/argtypes.h */
#if (G_MAXUINT <= G_MAXLONG)
	    return PYGLIB_PyLong_FromLong((glong) g_value_get_uint(value));
#else
	    return PyLong_FromUnsignedLong((gulong) g_value_get_uint(value));
#endif
	}
    case G_TYPE_LONG:
	return PYGLIB_PyLong_FromLong(g_value_get_long(value));
    case G_TYPE_ULONG:
	{
	    gulong val = g_value_get_ulong(value);

	    if (val <= G_MAXLONG)
		return PYGLIB_PyLong_FromLong((glong) val);
	    else
		return PyLong_FromUnsignedLong(val);
	}
    case G_TYPE_INT64:
	{
	    gint64 val = g_value_get_int64(value);

	    if (G_MINLONG <= val && val <= G_MAXLONG)
		return PYGLIB_PyLong_FromLong((glong) val);
	    else
		return PyLong_FromLongLong(val);
	}
    case G_TYPE_UINT64:
	{
	    guint64 val = g_value_get_uint64(value);

	    if (val <= G_MAXLONG)
		return PYGLIB_PyLong_FromLong((glong) val);
	    else
		return PyLong_FromUnsignedLongLong(val);
	}
    case G_TYPE_ENUM:
	return pyg_enum_from_gtype(G_VALUE_TYPE(value), g_value_get_enum(value));
    case G_TYPE_FLAGS:
	return pyg_flags_from_gtype(G_VALUE_TYPE(value), g_value_get_flags(value));
    case G_TYPE_FLOAT:
	return PyFloat_FromDouble(g_value_get_float(value));
    case G_TYPE_DOUBLE:
	return PyFloat_FromDouble(g_value_get_double(value));
    case G_TYPE_STRING:
	{
	    const gchar *str = g_value_get_string(value);

	    if (str)
		return PYGLIB_PyUnicode_FromString(str);
	    Py_INCREF(Py_None);
	    return Py_None;
	}
    case G_TYPE_POINTER:
	return pyg_pointer_new(G_VALUE_TYPE(value),
			       g_value_get_pointer(value));
    case G_TYPE_BOXED: {
	PyGTypeMarshal *bm;

	if (G_VALUE_HOLDS(value, PY_TYPE_OBJECT)) {
	    PyObject *ret = (PyObject *)g_value_dup_boxed(value);
	    if (ret == NULL) {
		Py_INCREF(Py_None);
		return Py_None;
	    }
	    return ret;
        } else if (G_VALUE_HOLDS(value, G_TYPE_VALUE)) {
            GValue *n_value = g_value_get_boxed (value);
            return pyg_value_as_pyobject(n_value, copy_boxed);
        } else if (G_VALUE_HOLDS(value, G_TYPE_VALUE_ARRAY)) {
	    GValueArray *array = (GValueArray *) g_value_get_boxed(value);
	    PyObject *ret = PyList_New(array->n_values);
	    int i;
	    for (i = 0; i < array->n_values; ++i)
		PyList_SET_ITEM(ret, i, pyg_value_as_pyobject
                                (array->values + i, copy_boxed));
	    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);
	    return ret;
	}
	bm = pyg_type_lookup(G_VALUE_TYPE(value));
	if (bm) {
	    return bm->fromvalue(value);
	} else {
	    if (copy_boxed)
		return pyg_boxed_new(G_VALUE_TYPE(value),
				     g_value_get_boxed(value), TRUE, TRUE);
	    else
		return pyg_boxed_new(G_VALUE_TYPE(value),
				     g_value_get_boxed(value),FALSE,FALSE);
	}
    }
    case G_TYPE_PARAM:
	return pyg_param_spec_new(g_value_get_param(value));
    case G_TYPE_OBJECT:
	return pygobject_new(g_value_get_object(value));
    default:
	{
	    PyGTypeMarshal *bm;
	    if ((bm = pyg_type_lookup(G_VALUE_TYPE(value))))
		return bm->fromvalue(value);
	    break;
	}
    }
    g_snprintf(buf, sizeof(buf), "unknown type %s",
	       g_type_name(G_VALUE_TYPE(value)));
    PyErr_SetString(PyExc_TypeError, buf);
    return NULL;
}
Example #20
0
/**
 * pygi_resulttuple_new_type:
 * @tuple_names: A python list containing str or None items.
 *
 * Similar to namedtuple() creates a new tuple subclass which
 * allows to access items by name and have a pretty __repr__.
 * Each item in the passed name list corresponds to an item with
 * the same index in the tuple class. If the name is None the item/index
 * is unnamed.
 *
 * Returns: A new PyTypeObject which is a subclass of PyGIResultTuple_Type
 *    or %NULL in case of an error.
 */
PyTypeObject*
pygi_resulttuple_new_type(PyObject *tuple_names) {
    PyTypeObject *new_type;
    PyObject *class_dict, *format_string, *empty_format, *named_format,
        *format_list, *sep, *index_dict, *slots, *paren_format, *new_type_args,
        *paren_string;
    Py_ssize_t len, i;

    g_assert (PyList_Check (tuple_names));

    class_dict = PyDict_New ();

    /* To save some memory don't use an instance dict */
    slots = PyTuple_New (0);
    PyDict_SetItemString (class_dict, "__slots__", slots);
    Py_DECREF (slots);

    format_list = PyList_New (0);
    index_dict = PyDict_New ();

    empty_format = PYGLIB_PyUnicode_FromString ("%r");
    named_format = PYGLIB_PyUnicode_FromString ("%s=%%r");
    len = PyList_Size (tuple_names);
    for (i = 0; i < len; i++) {
        PyObject *item, *named_args, *named_build, *index;
        item = PyList_GET_ITEM (tuple_names, i);
        if (item == Py_None) {
            PyList_Append (format_list, empty_format);
        } else {
            named_args = Py_BuildValue ("(O)", item);
            named_build = PYGLIB_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);
            PyDict_SetItem (index_dict, item, index);
            Py_DECREF (index);
        }
    }
    Py_DECREF (empty_format);
    Py_DECREF (named_format);

    sep = PYGLIB_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);
    Py_DECREF (paren_format);
    Py_DECREF (format_string);

    PyDict_SetItemString (class_dict, repr_format_key, paren_string);
    Py_DECREF (paren_string);

    PyDict_SetItemString (class_dict, tuple_indices_key, index_dict);
    Py_DECREF (index_dict);

    new_type_args = Py_BuildValue ("s(O)O", "_ResultTuple",
                                   &PyGIResultTuple_Type, class_dict);
    new_type = (PyTypeObject *)PyType_Type.tp_new (&PyType_Type,
                                                   new_type_args, NULL);
    Py_DECREF (new_type_args);
    Py_DECREF (class_dict);

    if (new_type != NULL) {
        /* disallow subclassing as that would break the free list caching
         * since we assume that all subclasses use PyTupleObject */
        new_type->tp_flags &= ~Py_TPFLAGS_BASETYPE;
    }

    return new_type;
}
Example #21
0
static PyObject *
_wrap_g_type_wrapper__get_name(PyGTypeWrapper *self, void *closure)
{
   const char *name = g_type_name(self->type);
   return PYGLIB_PyUnicode_FromString(name ? name : "invalid");
}