Example #1
0
static PyObject *
pyg_flags_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
    static char *kwlist[] = { "value", NULL };
    long value;
    PyObject *pytc, *values, *ret, *pyint;
    GType gtype;
    GFlagsClass *eclass;

    if (!PyArg_ParseTupleAndKeywords(args, kwargs, "l", kwlist, &value))
	return NULL;

    pytc = PyObject_GetAttrString((PyObject *)type, "__gtype__");
    if (!pytc)
	return NULL;

    if (!PyObject_TypeCheck(pytc, &PyGTypeWrapper_Type)) {
	Py_DECREF(pytc);
	PyErr_SetString(PyExc_TypeError,
			"__gtype__ attribute not a typecode");
	return NULL;
    }

    gtype = pyg_type_from_object(pytc);
    Py_DECREF(pytc);

    eclass = G_FLAGS_CLASS(g_type_class_ref(gtype));

    values = PyObject_GetAttrString((PyObject *)type, "__flags_values__");
    if (!values) {
	g_type_class_unref(eclass);
	return NULL;
    }

    if (!PyDict_Check(values)) {
	PyErr_SetString(PyExc_TypeError, "__flags_values__ badly formed");
	Py_DECREF(values);
	g_type_class_unref(eclass);
	return NULL;
    }

    g_type_class_unref(eclass);

    pyint = PYGLIB_PyLong_FromLong(value);
    ret = PyDict_GetItem(values, pyint);
    if (!ret) {
        PyErr_Clear();

        ret = pyg_flags_val_new((PyObject *)type, gtype, pyint);
        g_assert(ret != NULL);
    } else {
        Py_INCREF(ret);
    }

    Py_DECREF(pyint);
    Py_DECREF(values);

    return ret;
}
Example #2
0
PyObject*
pyg_flags_from_gtype (GType gtype, guint value)
{
    PyObject *pyclass, *values, *retval, *pyint;

    if (PyErr_Occurred())
        return PYGLIB_PyLong_FromUnsignedLong(0);

    g_return_val_if_fail(gtype != G_TYPE_INVALID, NULL);

    /* Get a wrapper class by:
     * 1. check for one attached to the gtype
     * 2. lookup one in a typelib
     * 3. creating a new one
     */
    pyclass = (PyObject*)g_type_get_qdata(gtype, pygflags_class_key);
    if (!pyclass)
        pyclass = pygi_type_import_by_g_type(gtype);
    if (!pyclass)
        pyclass = pyg_flags_add(NULL, g_type_name(gtype), NULL, gtype);
    if (!pyclass)
	return PYGLIB_PyLong_FromUnsignedLong(value);

    values = PyDict_GetItemString(((PyTypeObject *)pyclass)->tp_dict,
				  "__flags_values__");
    pyint = PYGLIB_PyLong_FromUnsignedLong(value);
    retval = PyDict_GetItem(values, pyint);
    if (!retval) {
	PyErr_Clear();

	retval = pyg_flags_val_new(pyclass, gtype, pyint);
	g_assert(retval != NULL);
    } else {
	Py_INCREF(retval);
    }
    Py_DECREF(pyint);
    
    return retval;
}