/
PropertyPythonObject.cpp
436 lines (400 loc) · 14.6 KB
/
PropertyPythonObject.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
/***************************************************************************
* Copyright (c) 2009 Werner Mayer <wmayer[at]users.sourceforge.net> *
* *
* 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_
#endif
#include "PropertyPythonObject.h"
#include "DocumentObjectPy.h"
#include "DocumentObject.h"
#include <Base/Base64.h>
#include <Base/Writer.h>
#include <Base/Reader.h>
#include <Base/Console.h>
#include <Base/Interpreter.h>
#include <iostream>
#include <boost/regex.hpp>
using namespace App;
TYPESYSTEM_SOURCE(App::PropertyPythonObject , App::Property)
PropertyPythonObject::PropertyPythonObject()
{
}
PropertyPythonObject::~PropertyPythonObject()
{
// this is needed because the release of the pickled object may need the
// GIL. Thus, we grab the GIL and replace the pickled with an empty object
Base::PyGILStateLocker lock;
this->object = Py::Object();
}
void PropertyPythonObject::setValue(Py::Object o)
{
Base::PyGILStateLocker lock;
aboutToSetValue();
this->object = o;
hasSetValue();
}
Py::Object PropertyPythonObject::getValue() const
{
return object;
}
PyObject *PropertyPythonObject::getPyObject(void)
{
return Py::new_reference_to(this->object);
}
void PropertyPythonObject::setPyObject(PyObject * obj)
{
Base::PyGILStateLocker lock;
aboutToSetValue();
this->object = obj;
hasSetValue();
}
std::string PropertyPythonObject::toString() const
{
std::string repr;
Base::PyGILStateLocker lock;
try {
Py::Module pickle(PyImport_ImportModule("json"),true);
if (pickle.isNull())
throw Py::Exception();
Py::Callable method(pickle.getAttr(std::string("dumps")));
Py::Object dump;
if (this->object.hasAttr("__getstate__")) {
Py::Tuple args;
Py::Callable state(this->object.getAttr("__getstate__"));
dump = state.apply(args);
}
else if (this->object.hasAttr("__dict__")) {
dump = this->object.getAttr("__dict__");
}
else {
dump = this->object;
}
Py::Tuple args(1);
args.setItem(0, dump);
Py::Object res = method.apply(args);
Py::String str(res);
repr = str.as_std_string("ascii");
}
catch (Py::Exception&) {
Py::String typestr(this->object.type().str());
Base::Console().Error("PropertyPythonObject::toString(): failed for %s\n", typestr.as_string().c_str());
Base::PyException e; // extract the Python error text
e.ReportException();
}
return repr;
}
void PropertyPythonObject::fromString(const std::string& repr)
{
Base::PyGILStateLocker lock;
try {
if (repr.empty())
return;
Py::Module pickle(PyImport_ImportModule("json"),true);
if (pickle.isNull())
throw Py::Exception();
Py::Callable method(pickle.getAttr(std::string("loads")));
Py::Tuple args(1);
args.setItem(0, Py::String(repr));
Py::Object res = method.apply(args);
if (this->object.hasAttr("__setstate__")) {
Py::Tuple args(1);
args.setItem(0, res);
Py::Callable state(this->object.getAttr("__setstate__"));
state.apply(args);
}
else if (this->object.hasAttr("__dict__")) {
this->object.setAttr("__dict__", res);
}
else {
this->object = res;
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
e.ReportException();
}
}
void PropertyPythonObject::loadPickle(const std::string& str)
{
// find the custom attributes and restore them
Base::PyGILStateLocker lock;
try {
std::string buffer = str;
boost::regex pickle("S'(\\w+)'.+S'(\\w+)'\\n");
boost::match_results<std::string::const_iterator> what;
std::string::const_iterator start, end;
start = buffer.begin();
end = buffer.end();
while (boost::regex_search(start, end, what, pickle)) {
std::string key = std::string(what[1].first, what[1].second);
std::string val = std::string(what[2].first, what[2].second);
this->object.setAttr(key, Py::String(val));
buffer = std::string(what[2].second, end);
start = buffer.begin();
end = buffer.end();
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
e.ReportException();
}
}
std::string PropertyPythonObject::encodeValue(const std::string& str) const
{
std::string tmp;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
if (*it == '<')
tmp += "<";
else if (*it == '"')
tmp += """;
else if (*it == '&')
tmp += "&";
else if (*it == '>')
tmp += ">";
else if (*it == '\n')
tmp += "\\n";
else
tmp += *it;
}
return tmp;
}
std::string PropertyPythonObject::decodeValue(const std::string& str) const
{
std::string tmp;
for (std::string::const_iterator it = str.begin(); it != str.end(); ++it) {
if (*it == '\\') {
++it;
if (it != str.end() && *it == 'n') {
tmp += '\n';
}
}
else
tmp += *it;
}
return tmp;
}
void PropertyPythonObject::saveObject(Base::Writer &writer) const
{
Base::PyGILStateLocker lock;
try {
PropertyContainer* parent = this->getContainer();
if (parent->isDerivedFrom(Base::Type::fromName("App::DocumentObject"))) {
if (this->object.hasAttr("__object__")) {
writer.Stream() << " object=\"yes\"";
}
}
if (parent->isDerivedFrom(Base::Type::fromName("Gui::ViewProvider"))) {
if (this->object.hasAttr("__vobject__")) {
writer.Stream() << " vobject=\"yes\"";
}
}
}
catch (Py::Exception& e) {
e.clear();
}
}
void PropertyPythonObject::restoreObject(Base::XMLReader &reader)
{
Base::PyGILStateLocker lock;
try {
PropertyContainer* parent = this->getContainer();
if (reader.hasAttribute("object")) {
if (strcmp(reader.getAttribute("object"),"yes") == 0) {
Py::Object obj = Py::asObject(parent->getPyObject());
this->object.setAttr("__object__", obj);
}
}
if (reader.hasAttribute("vobject")) {
if (strcmp(reader.getAttribute("vobject"),"yes") == 0) {
Py::Object obj = Py::asObject(parent->getPyObject());
this->object.setAttr("__vobject__", obj);
}
}
}
catch (Py::Exception& e) {
e.clear();
}
catch (const Base::Exception& e) {
Base::Console().Error("%s\n",e.what());
}
catch (...) {
Base::Console().Error("Critical error in PropertyPythonObject::restoreObject\n");
}
}
void PropertyPythonObject::Save (Base::Writer &writer) const
{
//if (writer.isForceXML()) {
std::string repr = this->toString();
repr = Base::base64_encode((const unsigned char*)repr.c_str(), repr.size());
std::string val = /*encodeValue*/(repr);
writer.Stream() << writer.ind() << "<Python value=\"" << val
<< "\" encoded=\"yes\"";
Base::PyGILStateLocker lock;
try {
if (this->object.hasAttr("__module__") && this->object.hasAttr("__class__")) {
Py::String mod(this->object.getAttr("__module__"));
Py::Object cls(this->object.getAttr("__class__"));
if (cls.hasAttr("__name__")) {
Py::String name(cls.getAttr("__name__"));
writer.Stream() << " module=\"" << (std::string)mod << "\""
<< " class=\"" << (std::string)name << "\"";
}
}
else {
writer.Stream() << " json=\"yes\"";
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
e.ReportException();
}
saveObject(writer);
writer.Stream() << "/>" << std::endl;
//}
//else {
// writer.Stream() << writer.ind() << "<Python file=\"" <<
// writer.addFile("pickle", this) << "\"/>" << std::endl;
//}
}
void PropertyPythonObject::Restore(Base::XMLReader &reader)
{
reader.readElement("Python");
if (reader.hasAttribute("file")) {
std::string file(reader.getAttribute("file"));
reader.addFile(file.c_str(),this);
}
else {
bool load_json=false;
bool load_pickle=false;
bool load_failed=false;
std::string buffer = reader.getAttribute("value");
if (reader.hasAttribute("encoded") &&
strcmp(reader.getAttribute("encoded"),"yes") == 0) {
buffer = Base::base64_decode(buffer);
}
else {
buffer = decodeValue(buffer);
}
Base::PyGILStateLocker lock;
try {
boost::regex pickle("^\\(i(\\w+)\\n(\\w+)\\n");
boost::match_results<std::string::const_iterator> what;
std::string::const_iterator start, end;
start = buffer.begin();
end = buffer.end();
if (reader.hasAttribute("module") && reader.hasAttribute("class")) {
Py::Module mod(PyImport_ImportModule(reader.getAttribute("module")),true);
if (mod.isNull())
throw Py::Exception();
PyObject* cls = mod.getAttr(reader.getAttribute("class")).ptr();
if (!cls) {
std::stringstream s;
s << "Module " << reader.getAttribute("module")
<< " has no class " << reader.getAttribute("class");
throw Py::AttributeError(s.str());
}
#if PY_MAJOR_VERSION >= 3
if (PyType_Check(cls)) {
#else
if (PyClass_Check(cls)) {
this->object = PyInstance_NewRaw(cls, 0);
}
else if (PyType_Check(cls)) {
#endif
this->object = PyType_GenericAlloc((PyTypeObject*)cls, 0);
}
else {
throw Py::TypeError("neither class nor type object");
}
load_json = true;
}
else if (boost::regex_search(start, end, what, pickle)) {
std::string nam = std::string(what[1].first, what[1].second);
std::string cls = std::string(what[2].first, what[2].second);
Py::Module mod(PyImport_ImportModule(nam.c_str()),true);
if (mod.isNull())
throw Py::Exception();
#if PY_MAJOR_VERSION >= 3
this->object = PyObject_CallObject(mod.getAttr(cls).ptr(), NULL);
#else
this->object = PyInstance_NewRaw(mod.getAttr(cls).ptr(), 0);
#endif
load_pickle = true;
buffer = std::string(what[2].second, end);
}
else if (reader.hasAttribute("json")) {
load_json = true;
}
}
catch (Py::Exception&) {
Base::PyException e; // extract the Python error text
e.ReportException();
this->object = Py::None();
load_failed = true;
}
aboutToSetValue();
if (load_json)
this->fromString(buffer);
else if (load_pickle)
this->loadPickle(buffer);
else if (!load_failed)
Base::Console().Warning("PropertyPythonObject::Restore: unsupported serialisation: %s\n", buffer.c_str());
restoreObject(reader);
hasSetValue();
}
}
void PropertyPythonObject::SaveDocFile (Base::Writer &writer) const
{
std::string buffer = this->toString();
for (std::string::iterator it = buffer.begin(); it != buffer.end(); ++it)
writer.Stream().put(*it);
}
void PropertyPythonObject::RestoreDocFile(Base::Reader &reader)
{
aboutToSetValue();
std::string buffer;
char c;
while (reader.get(c)) {
buffer.push_back(c);
}
this->fromString(buffer);
hasSetValue();
}
unsigned int PropertyPythonObject::getMemSize (void) const
{
return sizeof(Py::Object);
}
Property *PropertyPythonObject::Copy(void) const
{
PropertyPythonObject *p = new PropertyPythonObject();
Base::PyGILStateLocker lock;
p->object = this->object;
return p;
}
void PropertyPythonObject::Paste(const Property &from)
{
if (from.getTypeId() == PropertyPythonObject::getClassTypeId()) {
Base::PyGILStateLocker lock;
aboutToSetValue();
this->object = static_cast<const PropertyPythonObject&>(from).object;
hasSetValue();
}
}