Imported Upstream version 3.21.91
[platform/upstream/python-gobject.git] / gi / pygi-type.c
1 /* -*- Mode: C; c-basic-offset: 4 -*-
2  * vim: tabstop=4 shiftwidth=4 expandtab
3  *
4  * Copyright (C) 2009 Simon van der Linden <svdlinden@src.gnome.org>
5  *
6  *   pygi-type.c: helpers to lookup Python wrappers from GType and GIBaseInfo.
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include "pygtype.h"
23 #include "pygi-type.h"
24
25 #include <pyglib-python-compat.h>
26
27
28 PyObject *
29 _pygi_type_import_by_name (const char *namespace_,
30                            const char *name)
31 {
32     gchar *module_name;
33     PyObject *py_module;
34     PyObject *py_object;
35
36     module_name = g_strconcat ("gi.repository.", namespace_, NULL);
37
38     py_module = PyImport_ImportModule (module_name);
39
40     g_free (module_name);
41
42     if (py_module == NULL) {
43         return NULL;
44     }
45
46     py_object = PyObject_GetAttrString (py_module, name);
47
48     Py_DECREF (py_module);
49
50     return py_object;
51 }
52
53 PyObject *
54 pygi_type_import_by_g_type (GType g_type)
55 {
56     GIRepository *repository;
57     GIBaseInfo *info;
58     PyObject *type;
59
60     repository = g_irepository_get_default();
61
62     info = g_irepository_find_by_gtype (repository, g_type);
63     if (info == NULL) {
64         return NULL;
65     }
66
67     type = _pygi_type_import_by_gi_info (info);
68     g_base_info_unref (info);
69
70     return type;
71 }
72
73 PyObject *
74 _pygi_type_import_by_gi_info (GIBaseInfo *info)
75 {
76     return _pygi_type_import_by_name (g_base_info_get_namespace (info),
77                                       g_base_info_get_name (info));
78 }
79
80 PyObject *
81 _pygi_type_get_from_g_type (GType g_type)
82 {
83     PyObject *py_g_type;
84     PyObject *py_type;
85
86     py_g_type = pyg_type_wrapper_new (g_type);
87     if (py_g_type == NULL) {
88         return NULL;
89     }
90
91     py_type = PyObject_GetAttrString (py_g_type, "pytype");
92     if (py_type == Py_None) {
93         py_type = pygi_type_import_by_g_type (g_type);
94     }
95
96     Py_DECREF (py_g_type);
97
98     return py_type;
99 }
100