/
PropertyContainerPyImp.cpp
567 lines (499 loc) · 20.1 KB
/
PropertyContainerPyImp.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/***************************************************************************
* Copyright (c) Jürgen Riegel (juergen.riegel@web.de) 2007 *
* *
* This file is part of the FreeCAD CAx development system. *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Library General Public *
* License as published by the Free Software Foundation; either *
* version 2 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 Library General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this library; see the file COPYING.LIB. If not, *
* write to the Free Software Foundation, Inc., 59 Temple Place, *
* Suite 330, Boston, MA 02111-1307, USA *
* *
***************************************************************************/
#include "PreCompiled.h"
#ifndef _PreComp_
# include <sstream>
#endif
#include "PropertyContainer.h"
#include "Property.h"
#include "PropertyLinks.h"
#include "Application.h"
#include "DocumentObject.h"
#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>
// inclution of the generated files (generated out of PropertyContainerPy.xml)
#include "PropertyContainerPy.h"
#include "PropertyContainerPy.cpp"
FC_LOG_LEVEL_INIT("Property", true, 2)
using namespace App;
// returns a string which represent the object e.g. when printed in python
std::string PropertyContainerPy::representation(void) const
{
return std::string("<property container>");
}
PyObject* PropertyContainerPy::getPropertyByName(PyObject *args)
{
char *pstr;
int checkOwner=0;
if (!PyArg_ParseTuple(args, "s|i", &pstr, &checkOwner)) // convert args: Python->C
return NULL; // NULL triggers exception
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(pstr);
if (prop) {
if(!checkOwner || (checkOwner==1 && prop->getContainer()==getPropertyContainerPtr()))
return prop->getPyObject();
Py::TupleN res(Py::asObject(prop->getContainer()->getPyObject()),
Py::asObject(prop->getPyObject()));
return Py::new_reference_to(res);
}
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", pstr);
return NULL;
}
PyObject* PropertyContainerPy::getPropertyTouchList(PyObject *args)
{
char *pstr;
if (!PyArg_ParseTuple(args, "s", &pstr)) // convert args: Python->C
return NULL; // NULL triggers exception
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(pstr);
if (prop && prop->isDerivedFrom(PropertyLists::getClassTypeId())) {
const auto &touched = static_cast<PropertyLists*>(prop)->getTouchList();
Py::Tuple ret(touched.size());
int i=0;
for(int idx : touched)
ret.setItem(i++,Py::Long(idx));
return Py::new_reference_to(ret);
}
else if(!prop)
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", pstr);
else
PyErr_Format(PyExc_AttributeError, "Property '%s' is not of list type", pstr);
return NULL;
}
PyObject* PropertyContainerPy::getTypeOfProperty(PyObject *args)
{
Py::List ret;
char *pstr;
if (!PyArg_ParseTuple(args, "s", &pstr)) // convert args: Python->C
return NULL; // NULL triggers exception
Property* prop = getPropertyContainerPtr()->getPropertyByName(pstr);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", pstr);
return 0;
}
short Type = prop->getType();
if (Type & Prop_Hidden)
ret.append(Py::String("Hidden"));
if (Type & Prop_ReadOnly)
ret.append(Py::String("ReadOnly"));
if (Type & Prop_Output)
ret.append(Py::String("Output"));
if (Type & Prop_NoRecompute)
ret.append(Py::String("NoRecompute"));
if (Type & Prop_Transient)
ret.append(Py::String("Transient"));
return Py::new_reference_to(ret);
}
PyObject* PropertyContainerPy::getTypeIdOfProperty(PyObject *args)
{
char *pstr;
if (!PyArg_ParseTuple(args, "s", &pstr)) // convert args: Python->C
return NULL; // NULL triggers exception
Property* prop = getPropertyContainerPtr()->getPropertyByName(pstr);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", pstr);
return 0;
}
Py::String str(prop->getTypeId().getName());
return Py::new_reference_to(str);
}
PyObject* PropertyContainerPy::setEditorMode(PyObject *args)
{
char* name;
short type;
if (PyArg_ParseTuple(args, "sh", &name, &type)) {
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(name);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", name);
return 0;
}
std::bitset<32> status(prop->getStatus());
status.set(Property::ReadOnly, (type & 1) > 0);
status.set(Property::Hidden, (type & 2) > 0);
prop->setStatusValue(status.to_ulong());
Py_Return;
}
PyErr_Clear();
PyObject *iter;
if (PyArg_ParseTuple(args, "sO", &name, &iter)) {
if (PyTuple_Check(iter) || PyList_Check(iter)) {
Py::Sequence seq(iter);
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(name);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", name);
return 0;
}
// reset all bits first
std::bitset<32> status(prop->getStatus());
status.reset(Property::ReadOnly);
status.reset(Property::Hidden);
for (Py::Sequence::iterator it = seq.begin();it!=seq.end();++it) {
std::string str = (std::string)Py::String(*it);
if (str == "ReadOnly")
status.set(Property::ReadOnly);
else if (str == "Hidden")
status.set(Property::Hidden);
}
prop->setStatusValue(status.to_ulong());
Py_Return;
}
}
PyErr_SetString(PyExc_TypeError, "First argument must be str, second can be int, list or tuple");
return 0;
}
static const std::map<std::string, int> &getStatusMap() {
static std::map<std::string,int> statusMap;
if(statusMap.empty()) {
statusMap["Immutable"] = Property::Immutable;
statusMap["ReadOnly"] = Property::ReadOnly;
statusMap["Hidden"] = Property::Hidden;
statusMap["Transient"] = Property::Transient;
statusMap["MaterialEdit"] = Property::MaterialEdit;
statusMap["NoMaterialListEdit"] = Property::NoMaterialListEdit;
statusMap["Output"] = Property::Output;
statusMap["LockDynamic"] = Property::LockDynamic;
statusMap["NoModify"] = Property::NoModify;
statusMap["PartialTrigger"] = Property::PartialTrigger;
}
return statusMap;
}
PyObject* PropertyContainerPy::setPropertyStatus(PyObject *args)
{
char* name;
PyObject *pyValue;
if (!PyArg_ParseTuple(args, "sO", &name, &pyValue))
return 0;
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(name);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", name);
return 0;
}
auto linkProp = Base::freecad_dynamic_cast<App::PropertyLinkBase>(prop);
std::bitset<32> status(prop->getStatus());
size_t count = 1;
bool isSeq = false;
if(PyList_Check(pyValue) || PyTuple_Check(pyValue)) {
isSeq = true;
count = PySequence_Size(pyValue);
}
for(size_t i=0;i<count;++i) {
Py::Object item;
if(isSeq)
item = Py::Object(PySequence_GetItem(pyValue,i));
else
item = Py::Object(pyValue);
bool value = true;
if(item.isString()) {
const auto &statusMap = getStatusMap();
auto v = (std::string)Py::String(item);
if(v.size()>1 && v[0] == '-') {
value = false;
v = v.substr(1);
}
auto it = statusMap.find(v);
if(it == statusMap.end()) {
if(linkProp && v == "AllowPartial") {
linkProp->setAllowPartial(value);
continue;
}
PyErr_Format(PyExc_ValueError, "Unknown property status '%s'", v.c_str());
return 0;
}
status.set(it->second,value);
}else if(item.isNumeric()) {
int v = Py::Int(item);
if(v<0) {
value = false;
v = -v;
}
if(v==0 || v>31)
PyErr_Format(PyExc_ValueError, "Status value out of range '%d'", v);
status.set(v,value);
} else {
PyErr_SetString(PyExc_TypeError, "Expects status type to be Int or String");
return 0;
}
}
prop->setStatusValue(status.to_ulong());
Py_Return;
}
PyObject* PropertyContainerPy::getPropertyStatus(PyObject *args)
{
char* name = "";
if (!PyArg_ParseTuple(args, "|s", &name)) // convert args: Python->C
return NULL; // NULL triggers exception
Py::List ret;
const auto &statusMap = getStatusMap();
if(!name[0]) {
for(auto &v : statusMap)
ret.append(Py::String(v.first.c_str()));
}else{
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(name);
if (prop) {
auto linkProp = Base::freecad_dynamic_cast<App::PropertyLinkBase>(prop);
if(linkProp && linkProp->testFlag(App::PropertyLinkBase::LinkAllowPartial))
ret.append(Py::String("AllowPartial"));
std::bitset<32> bits(prop->getStatus());
for(size_t i=1;i<bits.size();++i) {
if(!bits[i]) continue;
bool found = false;
for(auto &v : statusMap) {
if(v.second == (int)i) {
ret.append(Py::String(v.first.c_str()));
found = true;
break;
}
}
if(!found)
ret.append(Py::Int((long)i));
}
}
}
return Py::new_reference_to(ret);
}
PyObject* PropertyContainerPy::getEditorMode(PyObject *args)
{
char* name;
if (!PyArg_ParseTuple(args, "s", &name)) // convert args: Python->C
return NULL; // NULL triggers exception
App::Property* prop = getPropertyContainerPtr()->getPropertyByName(name);
Py::List ret;
if (prop) {
short Type = prop->getType();
if ((prop->testStatus(Property::ReadOnly)) || (Type & Prop_ReadOnly))
ret.append(Py::String("ReadOnly"));
if ((prop->testStatus(Property::Hidden)) || (Type & Prop_Hidden))
ret.append(Py::String("Hidden"));
}
return Py::new_reference_to(ret);
}
PyObject* PropertyContainerPy::getGroupOfProperty(PyObject *args)
{
char *pstr;
if (!PyArg_ParseTuple(args, "s", &pstr)) // convert args: Python->C
return NULL; // NULL triggers exception
Property* prop = getPropertyContainerPtr()->getPropertyByName(pstr);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", pstr);
return 0;
}
const char* Group = getPropertyContainerPtr()->getPropertyGroup(prop);
if (Group)
return Py::new_reference_to(Py::String(Group));
else
return Py::new_reference_to(Py::String(""));
}
PyObject* PropertyContainerPy::getDocumentationOfProperty(PyObject *args)
{
char *pstr;
if (!PyArg_ParseTuple(args, "s", &pstr)) // convert args: Python->C
return NULL; // NULL triggers exception
Property* prop = getPropertyContainerPtr()->getPropertyByName(pstr);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", pstr);
return 0;
}
const char* Group = getPropertyContainerPtr()->getPropertyDocumentation(prop);
if (Group)
return Py::new_reference_to(Py::String(Group));
else
return Py::new_reference_to(Py::String(""));
}
Py::List PropertyContainerPy::getPropertiesList(void) const
{
Py::List ret;
std::map<std::string,Property*> Map;
getPropertyContainerPtr()->getPropertyMap(Map);
for (std::map<std::string,Property*>::const_iterator It=Map.begin();It!=Map.end();++It)
ret.append(Py::String(It->first));
return ret;
}
PyObject* PropertyContainerPy::dumpPropertyContent(PyObject *args, PyObject *kwds)
{
int compression = 3;
char* property;
static char* kwds_def[] = {"Property", "Compression",NULL};
PyErr_Clear();
if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|i", kwds_def, &property, &compression)) {
return NULL;
}
Property* prop = getPropertyContainerPtr()->getPropertyByName(property);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", property);
return 0;
}
//setup the stream. the in flag is needed to make "read" work
std::stringstream stream(std::stringstream::out | std::stringstream::in | std::stringstream::binary);
try {
prop->dumpToStream(stream, compression);
}
catch (...) {
PyErr_SetString(PyExc_IOError, "Unable parse content into binary representation");
return NULL;
}
//build the byte array with correct size
if (!stream.seekp(0, stream.end)) {
PyErr_SetString(PyExc_IOError, "Unable to find end of stream");
return NULL;
}
std::stringstream::pos_type offset = stream.tellp();
if (!stream.seekg(0, stream.beg)) {
PyErr_SetString(PyExc_IOError, "Unable to find begin of stream");
return NULL;
}
PyObject* ba = PyByteArray_FromStringAndSize(NULL, offset);
//use the buffer protocol to access the underlying array and write into it
Py_buffer buf = Py_buffer();
PyObject_GetBuffer(ba, &buf, PyBUF_WRITABLE);
try {
if(!stream.read((char*)buf.buf, offset)) {
PyErr_SetString(PyExc_IOError, "Error copying data into byte array");
return NULL;
}
PyBuffer_Release(&buf);
}
catch (...) {
PyBuffer_Release(&buf);
PyErr_SetString(PyExc_IOError, "Error copying data into byte array");
return NULL;
}
return ba;
}
PyObject* PropertyContainerPy::restorePropertyContent(PyObject *args)
{
PyObject* buffer;
char* property;
if( !PyArg_ParseTuple(args, "sO", &property, &buffer) )
return NULL;
Property* prop = getPropertyContainerPtr()->getPropertyByName(property);
if (!prop) {
PyErr_Format(PyExc_AttributeError, "Property container has no property '%s'", property);
return 0;
}
//check if it really is a buffer
if( !PyObject_CheckBuffer(buffer) ) {
PyErr_SetString(PyExc_TypeError, "Must be a buffer object");
return NULL;
}
Py_buffer buf;
if(PyObject_GetBuffer(buffer, &buf, PyBUF_SIMPLE) < 0)
return NULL;
if(!PyBuffer_IsContiguous(&buf, 'C')) {
PyErr_SetString(PyExc_TypeError, "Buffer must be contiguous");
return NULL;
}
//check if it really is a buffer
try {
typedef boost::iostreams::basic_array_source<char> Device;
boost::iostreams::stream<Device> stream((char*)buf.buf, buf.len);
prop->restoreFromStream(stream);
}
catch(...) {
PyErr_SetString(PyExc_IOError, "Unable to restore content");
return NULL;
}
Py_Return;
}
PyObject *PropertyContainerPy::getCustomAttributes(const char* attr) const
{
// search in PropertyList
if(FC_LOG_INSTANCE.level()>FC_LOGLEVEL_TRACE) {
FC_TRACE("Get property " << attr);
}
Property *prop = getPropertyContainerPtr()->getPropertyByName(attr);
if (prop) {
PyObject* pyobj = prop->getPyObject();
if (!pyobj && PyErr_Occurred()) {
// the Python exception is already set
throw Py::Exception();
}
return pyobj;
}
else if (Base::streq(attr, "__dict__")) {
// get the properties to the C++ PropertyContainer class
std::map<std::string,App::Property*> Map;
getPropertyContainerPtr()->getPropertyMap(Map);
PyObject *dict = PyDict_New();
if (dict) {
for ( std::map<std::string,App::Property*>::iterator it = Map.begin(); it != Map.end(); ++it )
#if PY_MAJOR_VERSION >= 3
PyDict_SetItem(dict, PyUnicode_FromString(it->first.c_str()), PyUnicode_FromString(""));
#else
PyDict_SetItem(dict, PyString_FromString(it->first.c_str()), PyString_FromString(""));
#endif
if (PyErr_Occurred()) {
Py_DECREF(dict);
dict = NULL;
}
}
return dict;
} else if(Base::streq(attr,"Shape")
&& getPropertyContainerPtr()->isDerivedFrom(App::DocumentObject::getClassTypeId()))
{
// Special treatment of Shape property
static PyObject *_getShape = 0;
if(!_getShape) {
_getShape = Py_None;
PyObject *mod = PyImport_ImportModule("Part");
if(!mod) {
PyErr_Clear();
} else {
Py::Object pyMod = Py::asObject(mod);
if(pyMod.hasAttr("getShape"))
_getShape = Py::new_reference_to(pyMod.getAttr("getShape"));
}
}
if(_getShape != Py_None) {
Py::Tuple args(1);
args.setItem(0,Py::Object(const_cast<PropertyContainerPy*>(this)));
auto res = PyObject_CallObject(_getShape, args.ptr());
if(!res)
PyErr_Clear();
else {
Py::Object pyres(res,true);
if(pyres.hasAttr("isNull")) {
Py::Callable func(pyres.getAttr("isNull"));
if(!func.apply().isTrue())
return Py::new_reference_to(res);
}
}
}
}
return 0;
}
int PropertyContainerPy::setCustomAttributes(const char* attr, PyObject *obj)
{
// search in PropertyList
Property *prop = getPropertyContainerPtr()->getPropertyByName(attr);
if (prop) {
// Read-only attributes must not be set over its Python interface
if(prop->testStatus(Property::Immutable)) {
std::stringstream s;
s << "Object attribute '" << attr << "' is read-only";
throw Py::AttributeError(s.str());
}
PY_TRY {
FC_TRACE("Set property " << prop->getFullName());
prop->setPyObject(obj);
}_PY_CATCH(return(-1))
return 1;
}
return 0;
}