##// END OF EJS Templates
fixed comparision of QObjects...
florianlink -
r104:65ef4ea92470
parent child
Show More
@@ -1,207 +1,204
1 1 #ifndef _PYTHONQTCONVERSION_H
2 2 #define _PYTHONQTCONVERSION_H
3 3
4 4 /*
5 5 *
6 6 * Copyright (C) 2006 MeVis Research GmbH All Rights Reserved.
7 7 *
8 8 * This library is free software; you can redistribute it and/or
9 9 * modify it under the terms of the GNU Lesser General Public
10 10 * License as published by the Free Software Foundation; either
11 11 * version 2.1 of the License, or (at your option) any later version.
12 12 *
13 13 * This library is distributed in the hope that it will be useful,
14 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 16 * Lesser General Public License for more details.
17 17 *
18 18 * Further, this software is distributed without any warranty that it is
19 19 * free of the rightful claim of any third person regarding infringement
20 20 * or the like. Any license provided herein, whether implied or
21 21 * otherwise, applies only to this software file. Patent licenses, if
22 22 * any, provided herein do not apply to combinations of this program with
23 23 * other software, or any other product whatsoever.
24 24 *
25 25 * You should have received a copy of the GNU Lesser General Public
26 26 * License along with this library; if not, write to the Free Software
27 27 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 28 *
29 29 * Contact information: MeVis Research GmbH, Universitaetsallee 29,
30 30 * 28359 Bremen, Germany or:
31 31 *
32 32 * http://www.mevis.de
33 33 *
34 34 */
35 35
36 36 //----------------------------------------------------------------------------------
37 37 /*!
38 38 // \file PythonQtConversion.h
39 39 // \author Florian Link
40 40 // \author Last changed by $Author: florian $
41 41 // \date 2006-05
42 42 */
43 43 //----------------------------------------------------------------------------------
44 44
45 45 #include "PythonQt.h"
46 46 #include "PythonQtMisc.h"
47 47 #include "PythonQtClassInfo.h"
48 48 #include "PythonQtMethodInfo.h"
49 49
50 50 #include <QWidget>
51 51 #include <QList>
52 52 #include <vector>
53 53
54 54 typedef PyObject* PythonQtConvertMetaTypeToPythonCB(const void* inObject, int metaTypeId);
55 55 typedef bool PythonQtConvertPythonToMetaTypeCB(PyObject* inObject, void* outObject, int metaTypeId, bool strict);
56 56
57 57 #define PythonQtRegisterListTemplateConverter(type, innertype) \
58 58 { int typeId = qRegisterMetaType<type<innertype> >(#type"<"#innertype">"); \
59 59 PythonQtConv::registerPythonToMetaTypeConverter(typeId, PythonQtConvertPythonListToListOfValueType<type<innertype>, innertype>); \
60 60 PythonQtConv::registerMetaTypeToPythonConverter(typeId, PythonQtConvertListOfValueTypeToPythonList<type<innertype>, innertype>); \
61 61 }
62 62
63 63 #define PythonQtRegisterToolClassesTemplateConverter(innertype) \
64 64 PythonQtRegisterListTemplateConverter(QList, innertype); \
65 65 PythonQtRegisterListTemplateConverter(QVector, innertype); \
66 66 PythonQtRegisterListTemplateConverter(std::vector, innertype);
67 67 // TODO: add QHash etc. here!
68 68
69 69 //! a static class that offers methods for type conversion
70 70 class PYTHONQT_EXPORT PythonQtConv {
71 71
72 72 public:
73 73
74 74 //! get a ref counted True or False Python object
75 75 static PyObject* GetPyBool(bool val);
76 76
77 77 //! converts the Qt parameter given in \c data, interpreting it as a \c info parameter, into a Python object,
78 78 static PyObject* ConvertQtValueToPython(const PythonQtMethodInfo::ParameterInfo& info, const void* data);
79 79
80 80 //! convert python object to Qt (according to the given parameter) and if the conversion should be strict (classInfo is currently not used anymore)
81 81 static void* ConvertPythonToQt(const PythonQtMethodInfo::ParameterInfo& info, PyObject* obj, bool strict, PythonQtClassInfo* classInfo, void* alreadyAllocatedCPPObject = NULL);
82 82
83 83 //! creates a data storage for the passed parameter type and returns a void pointer to be set as arg[0] of qt_metacall
84 84 static void* CreateQtReturnValue(const PythonQtMethodInfo::ParameterInfo& info);
85 85
86 86 //! converts QString to Python string (unicode!)
87 87 static PyObject* QStringToPyObject(const QString& str);
88 88
89 89 //! converts QStringList to Python tuple
90 90 static PyObject* QStringListToPyObject(const QStringList& list);
91 91
92 92 //! converts QStringList to Python list
93 93 static PyObject* QStringListToPyList(const QStringList& list);
94 94
95 95 //! get string representation of py object
96 96 static QString PyObjGetRepresentation(PyObject* val);
97 97
98 98 //! get string value from py object
99 99 static QString PyObjGetString(PyObject* val) { bool ok; QString s = PyObjGetString(val, false, ok); return s; }
100 100 //! get string value from py object
101 101 static QString PyObjGetString(PyObject* val, bool strict, bool &ok);
102 102 //! get bytes from py object
103 103 static QByteArray PyObjGetBytes(PyObject* val, bool strict, bool &ok);
104 104 //! get int from py object
105 105 static int PyObjGetInt(PyObject* val, bool strict, bool &ok);
106 106 //! get int64 from py object
107 107 static qint64 PyObjGetLongLong(PyObject* val, bool strict, bool &ok);
108 108 //! get int64 from py object
109 109 static quint64 PyObjGetULongLong(PyObject* val, bool strict, bool &ok);
110 110 //! get double from py object
111 111 static double PyObjGetDouble(PyObject* val, bool strict, bool &ok);
112 112 //! get bool from py object
113 113 static bool PyObjGetBool(PyObject* val, bool strict, bool &ok);
114 114
115 115 //! create a string list from python sequence
116 116 static QStringList PyObjToStringList(PyObject* val, bool strict, bool& ok);
117 117
118 118 //! convert python object to qvariant, if type is given it will try to create a qvariant of that type, otherwise
119 119 //! it will guess from the python type
120 120 static QVariant PyObjToQVariant(PyObject* val, int type = -1);
121 121
122 122 //! convert QVariant from PyObject
123 123 static PyObject* QVariantToPyObject(const QVariant& v);
124 124
125 125 static PyObject* QVariantMapToPyObject(const QVariantMap& m);
126 126 static PyObject* QVariantListToPyObject(const QVariantList& l);
127 127
128 //! get human readable string from qvariant
129 static QString qVariantToString(const QVariant& v);
130
131 128 //! get human readable string from CPP object (when the metatype is known)
132 129 static QString CPPObjectToString(int type, const void* data);
133 130
134 131 //! register a converter callback from python to cpp for given metatype
135 132 static void registerPythonToMetaTypeConverter(int metaTypeId, PythonQtConvertPythonToMetaTypeCB* cb) { _pythonToMetaTypeConverters.insert(metaTypeId, cb); }
136 133
137 134 //! register a converter callback from cpp to python for given metatype
138 135 static void registerMetaTypeToPythonConverter(int metaTypeId, PythonQtConvertMetaTypeToPythonCB* cb) { _metaTypeToPythonConverters.insert(metaTypeId, cb); }
139 136
140 137 //! returns the inner type id of a simple template of the form SomeObject<InnerType>
141 138 static int getInnerTemplateMetaType(const QByteArray& typeName);
142 139
143 140 //! converts the Qt parameter given in \c data, interpreting it as a \c type registered qvariant/meta type, into a Python object,
144 141 static PyObject* ConvertQtValueToPythonInternal(int type, const void* data);
145 142
146 143 public:
147 144
148 145 static PythonQtValueStorage<qint64, 128> global_valueStorage;
149 146 static PythonQtValueStorage<void*, 128> global_ptrStorage;
150 147 static PythonQtValueStorage<QVariant, 32> global_variantStorage;
151 148
152 149 protected:
153 150 static QHash<int, PythonQtConvertMetaTypeToPythonCB*> _metaTypeToPythonConverters;
154 151 static QHash<int, PythonQtConvertPythonToMetaTypeCB*> _pythonToMetaTypeConverters;
155 152
156 153 //! handle automatic conversion of some special types (QColor, QBrush, ...)
157 154 static void* handlePythonToQtAutoConversion(int typeId, PyObject* obj, void* alreadyAllocatedCPPObject);
158 155
159 156 //! converts the list of pointers of given type to Python
160 157 static PyObject* ConvertQListOfPointerTypeToPythonList(QList<void*>* list, const QByteArray& type);
161 158 //! tries to convert the python object to a QList of pointers to \c type objects, returns true on success
162 159 static bool ConvertPythonListToQListOfPointerType(PyObject* obj, QList<void*>* list, const QByteArray& type, bool strict);
163 160
164 161 //! cast wrapper to given className if possible
165 162 static void* castWrapperTo(PythonQtInstanceWrapper* wrapper, const QByteArray& className, bool& ok);
166 163 };
167 164
168 165 template<class ListType, class T>
169 166 PyObject* PythonQtConvertListOfValueTypeToPythonList(const void* /*QList<T>* */ inList, int metaTypeId)
170 167 {
171 168 ListType* list = (ListType*)inList;
172 169 static const int innerType = PythonQtConv::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId)));
173 170 PyObject* result = PyTuple_New(list->size());
174 171 int i = 0;
175 172 foreach (const T& value, *list) {
176 173 PyTuple_SET_ITEM(result, i, PythonQtConv::ConvertQtValueToPythonInternal(innerType, &value));
177 174 i++;
178 175 }
179 176 return result;
180 177 }
181 178
182 179 template<class ListType, class T>
183 180 bool PythonQtConvertPythonListToListOfValueType(PyObject* obj, void* /*QList<T>* */ outList, int metaTypeId, bool /*strict*/)
184 181 {
185 182 ListType* list = (ListType*)outList;
186 183 static const int innerType = PythonQtConv::getInnerTemplateMetaType(QByteArray(QMetaType::typeName(metaTypeId)));
187 184 bool result = false;
188 185 if (PySequence_Check(obj)) {
189 186 result = true;
190 187 int count = PySequence_Size(obj);
191 188 PyObject* value;
192 189 for (int i = 0;i<count;i++) {
193 190 value = PySequence_GetItem(obj,i);
194 191 // this is quite some overhead, but it avoids having another large switch...
195 192 QVariant v = PythonQtConv::PyObjToQVariant(value, innerType);
196 193 if (v.isValid()) {
197 194 list->push_back(qVariantValue<T>(v));
198 195 } else {
199 196 result = false;
200 197 break;
201 198 }
202 199 }
203 200 }
204 201 return result;
205 202 }
206 203
207 204 #endif
@@ -1,620 +1,620
1 1 /*
2 2 *
3 3 * Copyright (C) 2006 MeVis Research GmbH All Rights Reserved.
4 4 *
5 5 * This library is free software; you can redistribute it and/or
6 6 * modify it under the terms of the GNU Lesser General Public
7 7 * License as published by the Free Software Foundation; either
8 8 * version 2.1 of the License, or (at your option) any later version.
9 9 *
10 10 * This library is distributed in the hope that it will be useful,
11 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 13 * Lesser General Public License for more details.
14 14 *
15 15 * Further, this software is distributed without any warranty that it is
16 16 * free of the rightful claim of any third person regarding infringement
17 17 * or the like. Any license provided herein, whether implied or
18 18 * otherwise, applies only to this software file. Patent licenses, if
19 19 * any, provided herein do not apply to combinations of this program with
20 20 * other software, or any other product whatsoever.
21 21 *
22 22 * You should have received a copy of the GNU Lesser General Public
23 23 * License along with this library; if not, write to the Free Software
24 24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 25 *
26 26 * Contact information: MeVis Research GmbH, Universitaetsallee 29,
27 27 * 28359 Bremen, Germany or:
28 28 *
29 29 * http://www.mevis.de
30 30 *
31 31 */
32 32
33 33 //----------------------------------------------------------------------------------
34 34 /*!
35 35 // \file PythonQtInstanceWrapper.cpp
36 36 // \author Florian Link
37 37 // \author Last changed by $Author: florian $
38 38 // \date 2006-05
39 39 */
40 40 //----------------------------------------------------------------------------------
41 41
42 42 #include "PythonQtInstanceWrapper.h"
43 43 #include <QObject>
44 44 #include "PythonQt.h"
45 45 #include "PythonQtSlot.h"
46 46 #include "PythonQtClassInfo.h"
47 47 #include "PythonQtConversion.h"
48 48 #include "PythonQtClassWrapper.h"
49 49
50 50 PythonQtClassInfo* PythonQtInstanceWrapperStruct::classInfo()
51 51 {
52 52 // take the class info from our type object
53 53 return ((PythonQtClassWrapper*)ob_type)->_classInfo;
54 54 }
55 55
56 56 static void PythonQtInstanceWrapper_deleteObject(PythonQtInstanceWrapper* self, bool force = false) {
57 57
58 58 // is this a C++ wrapper?
59 59 if (self->_wrappedPtr) {
60 60 //mlabDebugConst("Python","c++ wrapper removed " << self->_wrappedPtr << " " << self->_obj->className() << " " << self->classInfo()->wrappedClassName().latin1());
61 61
62 62 PythonQt::priv()->removeWrapperPointer(self->_wrappedPtr);
63 63 // we own our qobject, so we delete it now:
64 64 delete self->_obj;
65 65 self->_obj = NULL;
66 66 if (force || self->classInfo()->hasOwnerMethodButNoOwner(self->_wrappedPtr) || self->_ownedByPythonQt) {
67 67 int type = self->classInfo()->metaTypeId();
68 68 if (self->_useQMetaTypeDestroy && type>=0) {
69 69 // use QMetaType to destroy the object
70 70 QMetaType::destroy(type, self->_wrappedPtr);
71 71 } else {
72 72 PythonQtSlotInfo* slot = self->classInfo()->destructor();
73 73 if (slot) {
74 74 void* args[2];
75 75 args[0] = NULL;
76 76 args[1] = &self->_wrappedPtr;
77 77 slot->decorator()->qt_metacall(QMetaObject::InvokeMetaMethod, slot->slotIndex(), args);
78 78 self->_wrappedPtr = NULL;
79 79 } else {
80 80 if (type>=0) {
81 81 // use QMetaType to destroy the object
82 82 QMetaType::destroy(type, self->_wrappedPtr);
83 83 } else {
84 84 // TODO: warn about not being able to destroy the object?
85 85 }
86 86 }
87 87 }
88 88 }
89 89 } else {
90 90 //mlabDebugConst("Python","qobject wrapper removed " << self->_obj->className() << " " << self->classInfo()->wrappedClassName().latin1());
91 91 if (self->_objPointerCopy) {
92 92 PythonQt::priv()->removeWrapperPointer(self->_objPointerCopy);
93 93 }
94 94 if (self->_obj) {
95 95 if (force || self->_ownedByPythonQt) {
96 96 if (force || !self->_obj->parent()) {
97 97 delete self->_obj;
98 98 }
99 99 } else {
100 100 if (self->_obj->parent()==NULL) {
101 101 // tell someone who is interested that the qobject is no longer wrapped, if it has no parent
102 102 PythonQt::qObjectNoLongerWrappedCB(self->_obj);
103 103 }
104 104 }
105 105 }
106 106 }
107 107 self->_obj = NULL;
108 108 }
109 109
110 110 static void PythonQtInstanceWrapper_dealloc(PythonQtInstanceWrapper* self)
111 111 {
112 112 PythonQtInstanceWrapper_deleteObject(self);
113 113 self->_obj.~QPointer<QObject>();
114 114 self->ob_type->tp_free((PyObject*)self);
115 115 }
116 116
117 117 static PyObject* PythonQtInstanceWrapper_new(PyTypeObject *type, PyObject * /*args*/, PyObject * /*kwds*/)
118 118 {
119 119 //PythonQtClassWrapper *classType = (PythonQtClassWrapper*)type;
120 120 PythonQtInstanceWrapper *self;
121 121 static PyObject* emptyTuple = NULL;
122 122 if (emptyTuple==NULL) {
123 123 emptyTuple = PyTuple_New(0);
124 124 }
125 125
126 126 self = (PythonQtInstanceWrapper*)PyBaseObject_Type.tp_new(type, emptyTuple, NULL);
127 127
128 128 if (self != NULL) {
129 129 new (&self->_obj) QPointer<QObject>();
130 130 self->_wrappedPtr = NULL;
131 131 self->_ownedByPythonQt = false;
132 132 self->_useQMetaTypeDestroy = false;
133 133 self->_isShellInstance = false;
134 134 }
135 135 return (PyObject *)self;
136 136 }
137 137
138 138 int PythonQtInstanceWrapper_init(PythonQtInstanceWrapper * self, PyObject * args, PyObject * kwds)
139 139 {
140 140 if (args == PythonQtPrivate::dummyTuple()) {
141 141 // we are called from the internal PythonQt API, so our data will be filled later on...
142 142 return 0;
143 143 }
144 144
145 145 // we are called from python, try to construct our object
146 146 if (self->classInfo()->constructors()) {
147 147 void* directCPPPointer = NULL;
148 148 PythonQtSlotFunction_CallImpl(self->classInfo(), NULL, self->classInfo()->constructors(), args, kwds, NULL, &directCPPPointer);
149 149 if (PyErr_Occurred()) {
150 150 return -1;
151 151 }
152 152 if (directCPPPointer) {
153 153 // change ownershipflag to be owned by PythonQt
154 154 self->_ownedByPythonQt = true;
155 155 self->_useQMetaTypeDestroy = false;
156 156 if (self->classInfo()->isCPPWrapper()) {
157 157 self->_wrappedPtr = directCPPPointer;
158 158 // TODO xxx: if there is a wrapper factory, we might want to generate a wrapper for our class?!
159 159 } else {
160 160 self->setQObject((QObject*)directCPPPointer);
161 161 }
162 162 // register with PythonQt
163 163 PythonQt::priv()->addWrapperPointer(directCPPPointer, self);
164 164
165 165 PythonQtShellSetInstanceWrapperCB* cb = self->classInfo()->shellSetInstanceWrapperCB();
166 166 if (cb) {
167 167 // if we are a derived python class, we set the wrapper
168 168 // to activate the shell class, otherwise we just ignore that it is a shell...
169 169 // we detect it be checking if the type does not have PythonQtInstanceWrapper_Type as direct base class,
170 170 // which is the case for all non-python derived types
171 171 if (((PyObject*)self)->ob_type->tp_base != &PythonQtInstanceWrapper_Type) {
172 172 // set the wrapper and remember that we have a shell instance!
173 173 (*cb)(directCPPPointer, self);
174 174 self->_isShellInstance = true;
175 175 }
176 176 }
177 177 }
178 178 } else {
179 179 QString error = QString("No constructors available for ") + self->classInfo()->className();
180 180 PyErr_SetString(PyExc_ValueError, error.toLatin1().data());
181 181 return -1;
182 182 }
183 183 return 0;
184 184 }
185 185
186 186 static PyObject *PythonQtInstanceWrapper_classname(PythonQtInstanceWrapper* obj)
187 187 {
188 188 return PyString_FromString(obj->ob_type->tp_name);
189 189 }
190 190
191 191 static PyObject *PythonQtInstanceWrapper_help(PythonQtInstanceWrapper* obj)
192 192 {
193 193 return PythonQt::self()->helpCalled(obj->classInfo());
194 194 }
195 195
196 196 static PyObject *PythonQtInstanceWrapper_delete(PythonQtInstanceWrapper * self)
197 197 {
198 198 PythonQtInstanceWrapper_deleteObject(self, true);
199 199 Py_INCREF(Py_None);
200 200 return Py_None;
201 201 }
202 202
203 203
204 204 static PyMethodDef PythonQtInstanceWrapper_methods[] = {
205 205 {"className", (PyCFunction)PythonQtInstanceWrapper_classname, METH_NOARGS,
206 206 "Return the classname of the object"
207 207 },
208 208 {"help", (PyCFunction)PythonQtInstanceWrapper_help, METH_NOARGS,
209 209 "Shows the help of available methods for this class"
210 210 },
211 211 {"delete", (PyCFunction)PythonQtInstanceWrapper_delete, METH_NOARGS,
212 212 "Deletes the C++ object (at your own risk, my friend!)"
213 213 },
214 214 {NULL, NULL, 0, NULL} /* Sentinel */
215 215 };
216 216
217 217
218 218 static PyObject *PythonQtInstanceWrapper_getattro(PyObject *obj,PyObject *name)
219 219 {
220 220 const char *attributeName;
221 221 PythonQtInstanceWrapper *wrapper = (PythonQtInstanceWrapper *)obj;
222 222
223 223 if ((attributeName = PyString_AsString(name)) == NULL) {
224 224 return NULL;
225 225 }
226 226
227 227 if (qstrcmp(attributeName, "__dict__")==0) {
228 228 PyObject* dict = PyBaseObject_Type.tp_getattro(obj, name);
229 229 dict = PyDict_Copy(dict);
230 230
231 231 if (wrapper->_obj) {
232 232 // only the properties are missing, the rest is already available from
233 233 // PythonQtClassWrapper...
234 234 QStringList l = wrapper->classInfo()->propertyList();
235 235 foreach (QString name, l) {
236 236 PyObject* o = PyObject_GetAttrString(obj, name.toLatin1().data());
237 237 if (o) {
238 238 PyDict_SetItemString(dict, name.toLatin1().data(), o);
239 239 Py_DECREF(o);
240 240 } else {
241 241 std::cerr << "PythonQtInstanceWrapper: something is wrong, could not get attribute " << name.toLatin1().data();
242 242 }
243 243 }
244 244
245 245 QList<QByteArray> dynamicProps = wrapper->_obj->dynamicPropertyNames();
246 246 foreach (QByteArray name, dynamicProps) {
247 247 PyObject* o = PyObject_GetAttrString(obj, name.data());
248 248 if (o) {
249 249 PyDict_SetItemString(dict, name.data(), o);
250 250 Py_DECREF(o);
251 251 } else {
252 252 std::cerr << "PythonQtInstanceWrapper: dynamic property could not be read " << name.data();
253 253 }
254 254 }
255 255 }
256 256 // Note: we do not put children into the dict, is would look confusing?!
257 257 return dict;
258 258 }
259 259
260 260 // first look in super, to return derived methods from base object first
261 261 PyObject* superAttr = PyBaseObject_Type.tp_getattro(obj, name);
262 262 if (superAttr) {
263 263 return superAttr;
264 264 }
265 265 PyErr_Clear();
266 266
267 267 // mlabDebugConst("Python","get " << attributeName);
268 268
269 269 PythonQtMemberInfo member = wrapper->classInfo()->member(attributeName);
270 270 switch (member._type) {
271 271 case PythonQtMemberInfo::Property:
272 272 if (wrapper->_obj) {
273 273 if (member._property.userType() != QVariant::Invalid) {
274 274 return PythonQtConv::QVariantToPyObject(member._property.read(wrapper->_obj));
275 275 } else {
276 276 Py_INCREF(Py_None);
277 277 return Py_None;
278 278 }
279 279 } else {
280 280 QString error = QString("Trying to read property '") + attributeName + "' from a destroyed " + wrapper->classInfo()->className() + " object";
281 281 PyErr_SetString(PyExc_ValueError, error.toLatin1().data());
282 282 return NULL;
283 283 }
284 284 break;
285 285 case PythonQtMemberInfo::Slot:
286 286 return PythonQtSlotFunction_New(member._slot, obj, NULL);
287 287 break;
288 288 case PythonQtMemberInfo::EnumValue:
289 289 {
290 290 PyObject* enumValue = member._enumValue;
291 291 Py_INCREF(enumValue);
292 292 return enumValue;
293 293 }
294 294 break;
295 295 case PythonQtMemberInfo::EnumWrapper:
296 296 {
297 297 PyObject* enumWrapper = member._enumWrapper;
298 298 Py_INCREF(enumWrapper);
299 299 return enumWrapper;
300 300 }
301 301 break;
302 302 case PythonQtMemberInfo::NotFound:
303 303 // handle dynamic properties
304 304 if (wrapper->_obj) {
305 305 QVariant v = wrapper->_obj->property(attributeName);
306 306 if (v.isValid()) {
307 307 return PythonQtConv::QVariantToPyObject(v);
308 308 }
309 309 }
310 310 break;
311 311 default:
312 312 // is an invalid type, go on
313 313 break;
314 314 }
315 315
316 316 // look for the internal methods (className(), help())
317 317 PyObject* internalMethod = Py_FindMethod( PythonQtInstanceWrapper_methods, obj, (char*)attributeName);
318 318 if (internalMethod) {
319 319 return internalMethod;
320 320 }
321 321 PyErr_Clear();
322 322
323 323 if (wrapper->_obj) {
324 324 // look for a child
325 325 QObjectList children = wrapper->_obj->children();
326 326 for (int i = 0; i < children.count(); i++) {
327 327 QObject *child = children.at(i);
328 328 if (child->objectName() == attributeName) {
329 329 return PythonQt::priv()->wrapQObject(child);
330 330 }
331 331 }
332 332 }
333 333
334 334 QString error = QString(wrapper->classInfo()->className()) + " has no attribute named '" + QString(attributeName) + "'";
335 335 PyErr_SetString(PyExc_AttributeError, error.toLatin1().data());
336 336 return NULL;
337 337 }
338 338
339 339 static int PythonQtInstanceWrapper_setattro(PyObject *obj,PyObject *name,PyObject *value)
340 340 {
341 341 QString error;
342 342 char *attributeName;
343 343 PythonQtInstanceWrapper *wrapper = (PythonQtInstanceWrapper *)obj;
344 344
345 345 if ((attributeName = PyString_AsString(name)) == NULL)
346 346 return -1;
347 347
348 348 PythonQtMemberInfo member = wrapper->classInfo()->member(attributeName);
349 349 if (member._type == PythonQtMemberInfo::Property) {
350 350
351 351 if (!wrapper->_obj) {
352 352 error = QString("Trying to set property '") + attributeName + "' on a destroyed " + wrapper->classInfo()->className() + " object";
353 353 PyErr_SetString(PyExc_AttributeError, error.toLatin1().data());
354 354 return -1;
355 355 }
356 356
357 357 QMetaProperty prop = member._property;
358 358 if (prop.isWritable()) {
359 359 QVariant v;
360 360 if (prop.isEnumType()) {
361 361 // this will give us either a string or an int, everything else will probably be an error
362 362 v = PythonQtConv::PyObjToQVariant(value);
363 363 } else {
364 364 int t = prop.userType();
365 365 v = PythonQtConv::PyObjToQVariant(value, t);
366 366 }
367 367 bool success = false;
368 368 if (v.isValid()) {
369 369 success = prop.write(wrapper->_obj, v);
370 370 }
371 371 if (success) {
372 372 return 0;
373 373 } else {
374 374 error = QString("Property '") + attributeName + "' of type '" +
375 375 prop.typeName() + "' does not accept an object of type "
376 376 + QString(value->ob_type->tp_name) + " (" + PythonQtConv::PyObjGetRepresentation(value) + ")";
377 377 }
378 378 } else {
379 379 error = QString("Property '") + attributeName + "' of " + obj->ob_type->tp_name + " object is not writable";
380 380 }
381 381 } else if (member._type == PythonQtMemberInfo::Slot) {
382 382 error = QString("Slot '") + attributeName + "' can not be overwritten on " + obj->ob_type->tp_name + " object";
383 383 } else if (member._type == PythonQtMemberInfo::EnumValue) {
384 384 error = QString("EnumValue '") + attributeName + "' can not be overwritten on " + obj->ob_type->tp_name + " object";
385 385 } else if (member._type == PythonQtMemberInfo::EnumWrapper) {
386 386 error = QString("Enum '") + attributeName + "' can not be overwritten on " + obj->ob_type->tp_name + " object";
387 387 } else if (member._type == PythonQtMemberInfo::NotFound) {
388 388 // handle dynamic properties
389 389 if (wrapper->_obj) {
390 390 QVariant prop = wrapper->_obj->property(attributeName);
391 391 if (prop.isValid()) {
392 392 QVariant v = PythonQtConv::PyObjToQVariant(value);
393 393 if (v.isValid()) {
394 394 wrapper->_obj->setProperty(attributeName, v);
395 395 return 0;
396 396 } else {
397 397 error = QString("Dynamic property '") + attributeName + "' does not accept an object of type "
398 398 + QString(value->ob_type->tp_name) + " (" + PythonQtConv::PyObjGetRepresentation(value) + ")";
399 399 PyErr_SetString(PyExc_AttributeError, error.toLatin1().data());
400 400 return -1;
401 401 }
402 402 }
403 403 }
404 404
405 405 // if we are a derived python class, we allow setting attributes.
406 406 // if we are a direct CPP wrapper, we do NOT allow it, since
407 407 // it would be confusing to allow it because a wrapper will go away when it is not seen by python anymore
408 408 // and when it is recreated from a CPP pointer the attributes are gone...
409 409 if (obj->ob_type->tp_base != &PythonQtInstanceWrapper_Type) {
410 410 return PyBaseObject_Type.tp_setattro(obj,name,value);
411 411 } else {
412 412 error = QString("'") + attributeName + "' does not exist on " + obj->ob_type->tp_name + " and creating new attributes on C++ objects is not allowed";
413 413 }
414 414 }
415 415
416 416 PyErr_SetString(PyExc_AttributeError, error.toLatin1().data());
417 417 return -1;
418 418 }
419 419
420 420 static PyObject * PythonQtInstanceWrapper_str(PyObject * obj)
421 421 {
422 422 PythonQtInstanceWrapper* wrapper = (PythonQtInstanceWrapper*)obj;
423 423 const char* typeName = obj->ob_type->tp_name;
424 424 QObject *qobj = wrapper->_obj;
425 425 if (wrapper->_wrappedPtr) {
426 426 QString str = PythonQtConv::CPPObjectToString(wrapper->classInfo()->metaTypeId(), wrapper->_wrappedPtr);
427 427 if (!str.isEmpty()) {
428 428 return PyString_FromFormat("%s", str.toLatin1().constData());
429 429 } else
430 430 if (wrapper->_obj) {
431 431 return PyString_FromFormat("%s (C++ Object %p wrapped by %s %p))", typeName, wrapper->_wrappedPtr, wrapper->_obj->metaObject()->className(), qobj);
432 432 } else {
433 433 return PyString_FromFormat("%s (C++ Object %p)", typeName, wrapper->_wrappedPtr);
434 434 }
435 435 } else {
436 436 return PyString_FromFormat("%s (QObject %p)", typeName, qobj);
437 437 }
438 438 }
439 439
440 440 static PyObject * PythonQtInstanceWrapper_repr(PyObject * obj)
441 441 {
442 442 PythonQtInstanceWrapper* wrapper = (PythonQtInstanceWrapper*)obj;
443 443 const char* typeName = obj->ob_type->tp_name;
444 444
445 445 QObject *qobj = wrapper->_obj;
446 446 if (wrapper->_wrappedPtr) {
447 447 QString str = PythonQtConv::CPPObjectToString(wrapper->classInfo()->metaTypeId(), wrapper->_wrappedPtr);
448 448 if (!str.isEmpty()) {
449 449 return PyString_FromFormat("%s(%s, %p)", typeName, str.toLatin1().constData(), wrapper->_wrappedPtr);
450 450 } else
451 451 if (wrapper->_obj) {
452 452 return PyString_FromFormat("%s (C++ Object %p wrapped by %s %p))", typeName, wrapper->_wrappedPtr, wrapper->_obj->metaObject()->className(), qobj);
453 453 } else {
454 454 return PyString_FromFormat("%s (C++ Object %p)", typeName, wrapper->_wrappedPtr);
455 455 }
456 456 } else {
457 457 return PyString_FromFormat("%s (%s %p)", typeName, wrapper->classInfo()->className(), qobj);
458 458 }
459 459 }
460 460
461 461 static int PythonQtInstanceWrapper_compare(PyObject * obj1, PyObject * obj2)
462 462 {
463 463 if (PyObject_TypeCheck(obj1, &PythonQtInstanceWrapper_Type) &&
464 464 PyObject_TypeCheck(obj2, &PythonQtInstanceWrapper_Type)) {
465 465
466 466 PythonQtInstanceWrapper* w1 = (PythonQtInstanceWrapper*)obj1;
467 467 PythonQtInstanceWrapper* w2 = (PythonQtInstanceWrapper*)obj2;
468 468 // check pointers directly first:
469 469 if (w1->_wrappedPtr != NULL) {
470 470 if (w1->_wrappedPtr == w2->_wrappedPtr) {
471 471 return 0;
472 472 }
473 473 } else if (w1->_obj == w2->_obj) {
474 474 return 0;
475 475 }
476 476 const char* class1 = w1->classInfo()->className();
477 477 const char* class2 = w2->classInfo()->className();
478 478 if (strcmp(class1, class2) == 0) {
479 479 // same class names, so we can try the operator_equal
480 480 PythonQtMemberInfo info = w1->classInfo()->member("operator_equal");
481 481 if (info._type == PythonQtMemberInfo::Slot) {
482 482 bool result = false;
483 483 void* obj1 = w1->_wrappedPtr;
484 484 if (!obj1) {
485 485 obj1 = w1->_obj;
486 486 }
487 487 if (!obj1) { return -1; }
488 488 void* obj2 = w2->_wrappedPtr;
489 489 if (!obj2) {
490 490 obj2 = w2->_obj;
491 491 }
492 492 if (!obj2) { return -1; }
493 493 if (info._slot->isInstanceDecorator()) {
494 494 // call on decorator QObject
495 495 void* args[3];
496 496 args[0] = &result;
497 497 args[1] = &obj1; // this is a pointer, so it needs a pointer to a pointer
498 498 args[2] = obj2; // this is a reference, so it needs the direct pointer
499 499 info._slot->decorator()->qt_metacall(QMetaObject::InvokeMetaMethod, info._slot->slotIndex(), args);
500 500 return result?0:-1;
501 501 } else {
502 502 // call directly on QObject
503 503 if (w1->_obj && w2->_obj) {
504 504 void* args[2];
505 505 args[0] = &result;
506 args[2] = obj2; // this is a reference, so it needs the direct pointer
506 args[1] = obj2; // this is a reference, so it needs the direct pointer
507 507 w1->_obj->qt_metacall(QMetaObject::InvokeMetaMethod, info._slot->slotIndex(), args);
508 508 }
509 509 }
510 510 }
511 511 }
512 512 }
513 513 return -1;
514 514 }
515 515
516 516 static int PythonQtInstanceWrapper_nonzero(PyObject *obj)
517 517 {
518 518 PythonQtInstanceWrapper* wrapper = (PythonQtInstanceWrapper*)obj;
519 519 return (wrapper->_wrappedPtr == NULL && wrapper->_obj == NULL)?0:1;
520 520 }
521 521
522 522
523 523 static long PythonQtInstanceWrapper_hash(PythonQtInstanceWrapper *obj)
524 524 {
525 525 if (obj->_wrappedPtr != NULL) {
526 526 return reinterpret_cast<long>(obj->_wrappedPtr);
527 527 } else {
528 528 QObject* qobj = obj->_obj; // get pointer from QPointer wrapper
529 529 return reinterpret_cast<long>(qobj);
530 530 }
531 531 }
532 532
533 533
534 534
535 535 // we override nb_nonzero, so that one can do 'if' expressions to test for a NULL ptr
536 536 static PyNumberMethods PythonQtInstanceWrapper_as_number = {
537 537 0, /* nb_add */
538 538 0, /* nb_subtract */
539 539 0, /* nb_multiply */
540 540 0, /* nb_divide */
541 541 0, /* nb_remainder */
542 542 0, /* nb_divmod */
543 543 0, /* nb_power */
544 544 0, /* nb_negative */
545 545 0, /* nb_positive */
546 546 0, /* nb_absolute */
547 547 PythonQtInstanceWrapper_nonzero, /* nb_nonzero */
548 548 0, /* nb_invert */
549 549 0, /* nb_lshift */
550 550 0, /* nb_rshift */
551 551 0, /* nb_and */
552 552 0, /* nb_xor */
553 553 0, /* nb_or */
554 554 0, /* nb_coerce */
555 555 0, /* nb_int */
556 556 0, /* nb_long */
557 557 0, /* nb_float */
558 558 0, /* nb_oct */
559 559 0, /* nb_hex */
560 560 0, /* nb_inplace_add */
561 561 0, /* nb_inplace_subtract */
562 562 0, /* nb_inplace_multiply */
563 563 0, /* nb_inplace_divide */
564 564 0, /* nb_inplace_remainder */
565 565 0, /* nb_inplace_power */
566 566 0, /* nb_inplace_lshift */
567 567 0, /* nb_inplace_rshift */
568 568 0, /* nb_inplace_and */
569 569 0, /* nb_inplace_xor */
570 570 0, /* nb_inplace_or */
571 571 0, /* nb_floor_divide */
572 572 0, /* nb_true_divide */
573 573 0, /* nb_inplace_floor_divide */
574 574 0, /* nb_inplace_true_divide */
575 575 };
576 576
577 577 PyTypeObject PythonQtInstanceWrapper_Type = {
578 578 PyObject_HEAD_INIT(&PythonQtClassWrapper_Type)
579 579 0, /*ob_size*/
580 580 "PythonQt.PythonQtInstanceWrapper", /*tp_name*/
581 581 sizeof(PythonQtInstanceWrapper), /*tp_basicsize*/
582 582 0, /*tp_itemsize*/
583 583 (destructor)PythonQtInstanceWrapper_dealloc, /*tp_dealloc*/
584 584 0, /*tp_print*/
585 585 0, /*tp_getattr*/
586 586 0, /*tp_setattr*/
587 587 PythonQtInstanceWrapper_compare, /*tp_compare*/
588 588 PythonQtInstanceWrapper_repr, /*tp_repr*/
589 589 &PythonQtInstanceWrapper_as_number, /*tp_as_number*/
590 590 0, /*tp_as_sequence*/
591 591 0, /*tp_as_mapping*/
592 592 (hashfunc)PythonQtInstanceWrapper_hash, /*tp_hash */
593 593 0, /*tp_call*/
594 594 PythonQtInstanceWrapper_str, /*tp_str*/
595 595 PythonQtInstanceWrapper_getattro, /*tp_getattro*/
596 596 PythonQtInstanceWrapper_setattro, /*tp_setattro*/
597 597 0, /*tp_as_buffer*/
598 598 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
599 599 "PythonQtInstanceWrapper object", /* tp_doc */
600 600 0, /* tp_traverse */
601 601 0, /* tp_clear */
602 602 0, /* tp_richcompare */
603 603 0, /* tp_weaklistoffset */
604 604 0, /* tp_iter */
605 605 0, /* tp_iternext */
606 606 0, /* tp_methods */
607 607 0, /* tp_members */
608 608 0, /* tp_getset */
609 609 0, /* tp_base */
610 610 0, /* tp_dict */
611 611 0, /* tp_descr_get */
612 612 0, /* tp_descr_set */
613 613 0, /* tp_dictoffset */
614 614 (initproc)PythonQtInstanceWrapper_init, /* tp_init */
615 615 0, /* tp_alloc */
616 616 PythonQtInstanceWrapper_new, /* tp_new */
617 617 };
618 618
619 619 //-------------------------------------------------------
620 620
General Comments 0
You need to be logged in to leave comments. Login now